@unson/brainbase-mcp 0.50.29 → 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 (37) 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
@@ -1,5 +1,9 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { normalizeJudgmentExecutionOutcome } from './judgment-execution-outcome.js';
3
+ /** Default fallback project_code when an episode omits project binding. */
4
+ export const DEFAULT_JUDGMENT_EVENT_PROJECT_CODE = 'brainbase';
5
+ /** Canonical project_code syntax shared with hook/relay/downstream API contracts. */
6
+ export const JUDGMENT_EVENT_PROJECT_CODE_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/u;
3
7
  const MAX_SUMMARY_LENGTH = 2000;
4
8
  const AUDIT_LINE = /^(?:🧠 |📚 |⚠️ |🔁 |🛠️ )/u;
5
9
  const SENSITIVE_CONTENT = [
@@ -43,13 +47,90 @@ export function sanitizeJudgmentAnswer(value) {
43
47
  function isRecord(value) {
44
48
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
45
49
  }
50
+ /** Validate and trim a portable knowledge event project_code. */
51
+ export function normalizeJudgmentEventProjectCode(value) {
52
+ if (typeof value !== 'string')
53
+ return null;
54
+ const trimmed = value.trim();
55
+ if (!trimmed)
56
+ return null;
57
+ return JUDGMENT_EVENT_PROJECT_CODE_PATTERN.test(trimmed) ? trimmed : null;
58
+ }
59
+ /**
60
+ * Exact-match check aligned with downstream `requireProjectAccess`
61
+ * (`allowed.includes(projectCode)`). Neither `projectCode` nor entries in
62
+ * `allowedProjectCodes` are implicitly trimmed; wildcards and invalid codes
63
+ * fail closed.
64
+ */
65
+ export function isProjectCodeAllowed(projectCode, allowedProjectCodes) {
66
+ if (typeof projectCode !== 'string'
67
+ || !JUDGMENT_EVENT_PROJECT_CODE_PATTERN.test(projectCode)
68
+ || !Array.isArray(allowedProjectCodes)
69
+ || allowedProjectCodes.length === 0) {
70
+ return false;
71
+ }
72
+ return allowedProjectCodes.some((entry) => typeof entry === 'string'
73
+ && JUDGMENT_EVENT_PROJECT_CODE_PATTERN.test(entry)
74
+ && entry === projectCode);
75
+ }
76
+ function isMissingProjectCode(value) {
77
+ return value === undefined || value === null || (typeof value === 'string' && value.trim().length === 0);
78
+ }
79
+ function rawEpisodeProjectCode(episode) {
80
+ if (!isMissingProjectCode(episode.project_code))
81
+ return episode.project_code;
82
+ if (isRecord(episode.applicability_scope) && !isMissingProjectCode(episode.applicability_scope.project_code)) {
83
+ return episode.applicability_scope.project_code;
84
+ }
85
+ if (isRecord(episode.payload) && !isMissingProjectCode(episode.payload.project_code)) {
86
+ return episode.payload.project_code;
87
+ }
88
+ if (isRecord(episode.adoption)) {
89
+ const requestCode = isRecord(episode.adoption.request) ? episode.adoption.request.project_code : undefined;
90
+ if (!isMissingProjectCode(requestCode))
91
+ return requestCode;
92
+ const receiptCode = isRecord(episode.adoption.receipt) ? episode.adoption.receipt.project_code : undefined;
93
+ if (!isMissingProjectCode(receiptCode))
94
+ return receiptCode;
95
+ }
96
+ return undefined;
97
+ }
98
+ function resolveEpisodeProjectCode(episode, options = {}) {
99
+ const fallback = options.fallbackProjectCode === undefined
100
+ ? DEFAULT_JUDGMENT_EVENT_PROJECT_CODE
101
+ : normalizeJudgmentEventProjectCode(options.fallbackProjectCode);
102
+ if (!fallback) {
103
+ throw new Error('fallbackProjectCode is invalid');
104
+ }
105
+ const raw = rawEpisodeProjectCode(episode);
106
+ let resolved;
107
+ if (isMissingProjectCode(raw)) {
108
+ resolved = fallback;
109
+ }
110
+ else {
111
+ const normalized = normalizeJudgmentEventProjectCode(raw);
112
+ if (!normalized) {
113
+ throw new Error('project_code is invalid');
114
+ }
115
+ resolved = normalized;
116
+ }
117
+ if (options.allowedProjectCodes !== undefined && !isProjectCodeAllowed(resolved, options.allowedProjectCodes)) {
118
+ if (options.onProjectOutOfScope === 'reject') {
119
+ const error = new Error(`knowledge_project_access_denied:${resolved}`);
120
+ error.code = 'knowledge_project_access_denied';
121
+ throw error;
122
+ }
123
+ return null;
124
+ }
125
+ return resolved;
126
+ }
46
127
  /**
47
128
  * Project a completed Host episode into a non-authoritative knowledge event.
48
129
  *
49
130
  * This is a portable projection only. Organization identity, Task binding,
50
131
  * transcript storage, and delivery/outbox behavior remain adapter concerns.
51
132
  */
52
- export function toKnowledgeEventFromJudgmentEpisode(episode) {
133
+ export function toKnowledgeEventFromJudgmentEpisode(episode, options = {}) {
53
134
  if (!episode || episode.completion_status !== 'complete')
54
135
  return null;
55
136
  const payload = isRecord(episode.payload) ? episode.payload : undefined;
@@ -70,7 +151,11 @@ export function toKnowledgeEventFromJudgmentEpisode(episode) {
70
151
  : null;
71
152
  if (outcome && outcome.status !== 'completed')
72
153
  return null;
73
- const sourceType = outcome?.host.type === 'claude-code' ? 'agent_judgment' : 'codex_judgment';
154
+ const projectCode = resolveEpisodeProjectCode(episode, options);
155
+ if (!projectCode)
156
+ return null;
157
+ const sourceType = outcome?.host.type === 'claude-code' || outcome?.host.type === 'antigravity'
158
+ ? 'agent_judgment' : 'codex_judgment';
74
159
  return {
75
160
  schema_version: 'knowledge_event.v1',
76
161
  contract_version: 'knowledge_event.v1',
@@ -87,7 +172,7 @@ export function toKnowledgeEventFromJudgmentEpisode(episode) {
87
172
  authorized: false,
88
173
  graph_promotion_allowed: false
89
174
  },
90
- applicability_scope: { scope: 'judgment_episode', project_code: 'brainbase' },
175
+ applicability_scope: { scope: 'judgment_episode', project_code: projectCode },
91
176
  permission_snapshot: { knowledge_registration: true, external_action: false },
92
177
  source_pointer: {
93
178
  uri: outcome
@@ -1,4 +1,4 @@
1
- import type { JudgmentKnowledgeEvent } from './judgment-event-adapter.js';
1
+ import { type JudgmentKnowledgeEvent } from './judgment-event-adapter.js';
2
2
  /** The queue format is intentionally independent of a Host, Task, or tenant. */
3
3
  export declare const JUDGMENT_EVENT_OUTBOX_SCHEMA_VERSION: "judgment_event_outbox.v1";
4
4
  export declare const JUDGMENT_EVENT_DELIVERY_RECEIPT_SCHEMA_VERSION: "knowledge_event_delivery_receipt.v1";
@@ -101,6 +101,7 @@ export interface JudgmentOutboxDeliveryResult {
101
101
  dead_lettered: number;
102
102
  pending: number;
103
103
  deferred?: number;
104
+ out_of_scope?: number;
104
105
  last_error_code?: string;
105
106
  }
106
107
  export interface JudgmentOutboxDeliveryOptions {
@@ -117,6 +118,13 @@ export interface JudgmentOutboxDeliveryOptions {
117
118
  staleLockAfterMs?: number;
118
119
  /** Set false only for an adapter that already owns a surrounding lock. */
119
120
  acquireLock?: boolean;
121
+ /**
122
+ * Optional allowlist matching the delivery token's `projectCodes` claim
123
+ * (downstream `requireProjectAccess`). When provided, queued events with a
124
+ * missing, conflicting, invalid, or out-of-scope `project_code` are deferred
125
+ * without posting, consuming a retry attempt, or dead-lettering.
126
+ */
127
+ allowedProjectCodes?: readonly string[];
120
128
  }
121
129
  /** Queue one event. Repeating the same event is idempotent; changing its body is a conflict. */
122
130
  export declare function enqueueJudgmentKnowledgeEvent(event: JudgmentKnowledgeEvent, options: {
@@ -1,5 +1,6 @@
1
1
  import { closeSync, linkSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
2
2
  import { basename, dirname, join } from 'node:path';
3
+ import { JUDGMENT_EVENT_PROJECT_CODE_PATTERN, isProjectCodeAllowed } from './judgment-event-adapter.js';
3
4
  /** The queue format is intentionally independent of a Host, Task, or tenant. */
4
5
  export const JUDGMENT_EVENT_OUTBOX_SCHEMA_VERSION = 'judgment_event_outbox.v1';
5
6
  export const JUDGMENT_EVENT_DELIVERY_RECEIPT_SCHEMA_VERSION = 'knowledge_event_delivery_receipt.v1';
@@ -194,16 +195,40 @@ function confirmedReceipt(value, eventId, candidateId, projectCode) {
194
195
  && readback.processing_stage === 'retrievable'
195
196
  && readback.semantic_state === 'active';
196
197
  }
197
- function projectCode(event) {
198
+ function parseEventProjectCodeField(value) {
199
+ if (value === undefined)
200
+ return { kind: 'missing' };
201
+ if (typeof value !== 'string')
202
+ return { kind: 'invalid' };
203
+ if (!JUDGMENT_EVENT_PROJECT_CODE_PATTERN.test(value))
204
+ return { kind: 'invalid' };
205
+ return { kind: 'valid', value };
206
+ }
207
+ /**
208
+ * Extract the effective project_code using the same precedence and strict
209
+ * validation as downstream `requireProjectAccess`
210
+ * (`applicability_scope.project_code` before top-level `project_code`).
211
+ * Explicitly present non-strings, untrimmed/malformed strings, or non-object
212
+ * `applicability_scope` values are flagged as `invalid` instead of missing.
213
+ */
214
+ function eventProjectCodes(event) {
198
215
  const candidate = event;
199
- if (typeof candidate.project_code === 'string' && candidate.project_code)
200
- return candidate.project_code;
201
216
  const scope = candidate.applicability_scope;
202
- if (scope && typeof scope === 'object' && !Array.isArray(scope)) {
203
- const value = scope.project_code;
204
- return typeof value === 'string' && value ? value : null;
217
+ if (scope !== undefined && (!scope || typeof scope !== 'object' || Array.isArray(scope))) {
218
+ return { effective: null, conflict: false, invalid: true };
205
219
  }
206
- return null;
220
+ const scopeField = parseEventProjectCodeField(scope ? scope.project_code : undefined);
221
+ const topField = parseEventProjectCodeField(candidate.project_code);
222
+ if (scopeField.kind === 'invalid' || topField.kind === 'invalid') {
223
+ return { effective: null, conflict: false, invalid: true };
224
+ }
225
+ const scopeCode = scopeField.kind === 'valid' ? scopeField.value : null;
226
+ const topCode = topField.kind === 'valid' ? topField.value : null;
227
+ return {
228
+ effective: scopeCode ?? topCode,
229
+ conflict: Boolean(scopeCode && topCode && scopeCode !== topCode),
230
+ invalid: false
231
+ };
207
232
  }
208
233
  function readConfirmedReceipt(path, eventId, candidateId, code, storage) {
209
234
  try {
@@ -260,6 +285,7 @@ function deliverCore(options) {
260
285
  let retryable = 0;
261
286
  let deadLettered = 0;
262
287
  let deferred = 0;
288
+ let outOfScope = 0;
263
289
  let processed = 0;
264
290
  let lastErrorCode;
265
291
  const process = async () => {
@@ -283,9 +309,19 @@ function deliverCore(options) {
283
309
  deferred += 1;
284
310
  continue;
285
311
  }
312
+ const { effective: code, conflict: projectCodeConflict, invalid: projectCodeInvalid } = eventProjectCodes(queued.event);
313
+ if (projectCodeInvalid || projectCodeConflict) {
314
+ deferred += 1;
315
+ outOfScope += 1;
316
+ continue;
317
+ }
318
+ if (options.allowedProjectCodes !== undefined && !isProjectCodeAllowed(code, options.allowedProjectCodes)) {
319
+ deferred += 1;
320
+ outOfScope += 1;
321
+ continue;
322
+ }
286
323
  processed += 1;
287
324
  const eventId = queued.event.event_id;
288
- const code = projectCode(queued.event);
289
325
  const postAck = queued.delivery.post_ack;
290
326
  const attempt = queued.delivery.attempt || 1;
291
327
  const readbackAttempt = queued.delivery.readback_attempt || 1;
@@ -410,6 +446,7 @@ function deliverCore(options) {
410
446
  retryable,
411
447
  dead_lettered: deadLettered,
412
448
  deferred,
449
+ ...(outOfScope > 0 ? { out_of_scope: outOfScope } : {}),
413
450
  pending: jsonFiles(options.paths.outboxDir, storage).length,
414
451
  ...(lastErrorCode ? { last_error_code: lastErrorCode } : {})
415
452
  };
@@ -4,7 +4,7 @@
4
4
  * process, Task, and delivery details stay at the Host boundary.
5
5
  */
6
6
  export declare const JUDGMENT_EXECUTION_OUTCOME_SCHEMA_VERSION: "judgment_execution_outcome.v1";
7
- export type JudgmentExecutionHostType = 'codex' | 'claude-code';
7
+ export type JudgmentExecutionHostType = 'codex' | 'claude-code' | 'antigravity';
8
8
  export type JudgmentExecutionScope = 'host_turn' | 'external_effect';
9
9
  export type JudgmentExecutionStatus = 'completed' | 'partial' | 'failed' | 'blocked' | 'unknown';
10
10
  export type JudgmentExecutionStage = 'open' | 'resolve' | 'execute' | 'finalize' | 'deliver' | 'readback';
@@ -36,6 +36,7 @@ export interface JudgmentExecutionOutcome {
36
36
  resume_from: string | null;
37
37
  evidence: JudgmentExecutionEvidence;
38
38
  }
39
+ export declare const EXECUTION_OUTCOME_HOSTS: Set<JudgmentExecutionHostType>;
39
40
  /**
40
41
  * Validate and normalize a host execution outcome.
41
42
  *
@@ -14,7 +14,8 @@ const EVIDENCE_FIELDS = new Set(['state', 'refs']);
14
14
  const STATUSES = new Set(['completed', 'partial', 'failed', 'blocked', 'unknown']);
15
15
  const STAGES = new Set(['open', 'resolve', 'execute', 'finalize', 'deliver', 'readback']);
16
16
  const EVIDENCE_STATES = new Set(['confirmed', 'unconfirmed', 'no_data']);
17
- const HOST_TYPES = new Set(['codex', 'claude-code']);
17
+ export const EXECUTION_OUTCOME_HOSTS = new Set(['codex', 'claude-code', 'antigravity']);
18
+ const HOST_TYPES = EXECUTION_OUTCOME_HOSTS;
18
19
  const SCOPES = new Set(['host_turn', 'external_effect']);
19
20
  const ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
20
21
  function object(value, field) {
@@ -1,5 +1,5 @@
1
1
  import type { Tool } from '@modelcontextprotocol/sdk/types.js';
2
- import { type JudgmentModelOutcome, type JudgmentModelOutcomeSummary } from './judgment-model-outcome.js';
2
+ import { type JudgmentModelOutcome, type JudgmentModelOutcomeRepresentativeness, type JudgmentModelOutcomeSummary } from './judgment-model-outcome.js';
3
3
  /**
4
4
  * Judgment frame (brainbase-project ADR-014).
5
5
  *
@@ -65,6 +65,22 @@ export interface JudgmentFrameSelection {
65
65
  readonly why: string;
66
66
  }
67
67
  export type JudgmentFramePredictionCheckStatus = 'held' | 'failed' | 'unchecked';
68
+ export declare const JUDGMENT_FRAME_CLAIM_SCOPES: readonly ["universal", "probabilistic", "bounded_case"];
69
+ export type JudgmentFrameClaimScope = typeof JUDGMENT_FRAME_CLAIM_SCOPES[number];
70
+ export interface JudgmentFrameCompetingHypothesis {
71
+ readonly hypothesis: string;
72
+ readonly ref?: string;
73
+ readonly comparison: string;
74
+ }
75
+ export interface JudgmentFramePredictionBalance {
76
+ readonly claim_scope: JudgmentFrameClaimScope;
77
+ readonly population: string;
78
+ readonly supporting_summary: string;
79
+ readonly counter_summary: string;
80
+ /** Optional explicit representativeness of counter-evidence; takes precedence over text heuristics. */
81
+ readonly counter_representativeness?: JudgmentModelOutcomeRepresentativeness;
82
+ readonly competing_hypotheses?: readonly JudgmentFrameCompetingHypothesis[];
83
+ }
68
84
  /**
69
85
  * How a world-model prediction was checked against data (ADR-014). The check is
70
86
  * structural: whether the evidence really shows the result is not judged.
@@ -75,6 +91,8 @@ export interface JudgmentFramePredictionCheck {
75
91
  readonly status: JudgmentFramePredictionCheckStatus;
76
92
  /** Where the check was done. Required for held and failed. */
77
93
  readonly evidence?: string;
94
+ /** Optional scope and support/counter balance to guard against cherry-picking and scope mismatch. */
95
+ readonly balance?: JudgmentFramePredictionBalance;
78
96
  }
79
97
  export interface JudgmentFrameUse {
80
98
  readonly ref: string;
@@ -111,7 +129,11 @@ export type JudgmentFrameEscalationCode = 'objective_unanchored' | 'chosen_viola
111
129
  /** The chosen option predicts with a world model refuted at its current revision (F5, F6). */
112
130
  | 'chosen_uses_refuted_model'
113
131
  /** The chosen option relies on a prediction that was checked against data and failed. */
114
- | 'chosen_relies_on_failed_prediction';
132
+ | 'chosen_relies_on_failed_prediction'
133
+ /** A prediction check with balance is missing population or counter/supporting balance needed for its status. */
134
+ | 'prediction_unbalanced_evidence'
135
+ /** A probabilistic prediction is marked failed with explicit counter_representativeness: 'anecdotal'. */
136
+ | 'prediction_scope_mismatch';
115
137
  export interface JudgmentFrameEscalation {
116
138
  readonly code: JudgmentFrameEscalationCode;
117
139
  readonly refs: readonly string[];
@@ -239,7 +261,7 @@ export declare function handleJudgmentFrameToolCall(name: string, args: Record<s
239
261
  */
240
262
  export declare const judgmentModelOutcomeTools: Tool[];
241
263
  export declare function handleJudgmentModelOutcomeToolCall(name: string, args: Record<string, unknown>, dependencies: JudgmentModelOutcomeToolDependencies): Promise<JudgmentFrameToolResult | null>;
242
- export { JUDGMENT_MODEL_OUTCOME_ALTERNATIVES, JUDGMENT_MODEL_OUTCOME_RECORD_VERSION, judgmentModelOutcomeDigest, parseJudgmentModelOutcomeRecords, summarizeJudgmentModelOutcomes, validateJudgmentModelOutcome, } from './judgment-model-outcome.js';
243
- export type { JudgmentModelOutcome, JudgmentModelOutcomeAlternative, JudgmentModelOutcomeEvidenceKind, JudgmentModelOutcomeEvidenceRef, JudgmentModelOutcomeIssue, JudgmentModelOutcomeIssueCode, JudgmentModelOutcomeStoredRecord, JudgmentModelOutcomeSummary, JudgmentModelOutcomeValidation, JudgmentModelOutcomeVerdict, } from './judgment-model-outcome.js';
264
+ export { JUDGMENT_MODEL_OUTCOME_ALTERNATIVES, JUDGMENT_MODEL_OUTCOME_CLAIM_TYPES, JUDGMENT_MODEL_OUTCOME_RECORD_VERSION, JUDGMENT_MODEL_OUTCOME_REPRESENTATIVENESS, isAnecdotalRefutation, judgmentModelOutcomeDigest, parseJudgmentModelOutcomeRecords, summarizeJudgmentModelOutcomes, validateJudgmentModelOutcome, } from './judgment-model-outcome.js';
265
+ export type { JudgmentModelOutcome, JudgmentModelOutcomeAlternative, JudgmentModelOutcomeClaimType, JudgmentModelOutcomeEvidenceKind, JudgmentModelOutcomeEvidenceRef, JudgmentModelOutcomeIssue, JudgmentModelOutcomeIssueCode, JudgmentModelOutcomeRepresentativeness, JudgmentModelOutcomeScopeMetrics, JudgmentModelOutcomeStoredRecord, JudgmentModelOutcomeSummary, JudgmentModelOutcomeValidation, JudgmentModelOutcomeVerdict, } from './judgment-model-outcome.js';
244
266
  export { judgmentFrameReadTools, handleJudgmentFrameReadToolCall, } from './judgment-frame-read.js';
245
267
  export type { JudgmentFrameReadDependencies, JudgmentFrameReadRecord, } from './judgment-frame-read.js';
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { JUDGMENT_MODEL_OUTCOME_ALTERNATIVES, JUDGMENT_MODEL_OUTCOME_RECORD_VERSION, judgmentModelOutcomeDigest, parseJudgmentModelOutcomeRecords, summarizeJudgmentModelOutcomes, validateJudgmentModelOutcome, } from './judgment-model-outcome.js';
2
+ import { JUDGMENT_MODEL_OUTCOME_ALTERNATIVES, JUDGMENT_MODEL_OUTCOME_CLAIM_TYPES, JUDGMENT_MODEL_OUTCOME_RECORD_VERSION, JUDGMENT_MODEL_OUTCOME_REPRESENTATIVENESS, judgmentModelOutcomeDigest, parseJudgmentModelOutcomeRecords, summarizeJudgmentModelOutcomes, validateJudgmentModelOutcome, } from './judgment-model-outcome.js';
3
3
  /**
4
4
  * Judgment frame (brainbase-project ADR-014).
5
5
  *
@@ -27,6 +27,7 @@ const MAX_SELECTIONS = 24;
27
27
  const MAX_OPTIONS = 8;
28
28
  const MAX_USES = 32;
29
29
  export const MAX_PUBLIC_FRAME_TEXT = 2_000;
30
+ export const JUDGMENT_FRAME_CLAIM_SCOPES = ['universal', 'probabilistic', 'bounded_case'];
30
31
  const isRecord = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
31
32
  const text = (value) => typeof value === 'string' && value.trim() ? value.trim() : undefined;
32
33
  const nonEmpty = (value, max) => typeof value === 'string' && value.trim().length > 0 && value.length <= max;
@@ -211,7 +212,20 @@ const KIND_HEADINGS = {
211
212
  function renderOutcomeSummary(summary) {
212
213
  if (!summary)
213
214
  return '';
214
- const counts = `支持${summary.supports}・反証${summary.refutes}・判定不能${summary.inconclusive}`;
215
+ const structural = summary.structural_refutes ?? summary.refutes;
216
+ const anecdotal = summary.anecdotal_refutes ?? 0;
217
+ if (anecdotal > 0) {
218
+ const counts = `支持${summary.supports}・構造反証${structural}・逸話反証${anecdotal}・判定不能${summary.inconclusive}`;
219
+ const parts = [];
220
+ if (summary.refuted_when.length > 0)
221
+ parts.push(`構造反証の条件:${summary.refuted_when.join('/')}`);
222
+ const anecdotalWhen = summary.anecdotal_refuted_when ?? [];
223
+ if (anecdotalWhen.length > 0)
224
+ parts.push(`逸話反証の条件:${anecdotalWhen.join('/')}`);
225
+ const details = parts.length > 0 ? `。${parts.join('。')}` : '';
226
+ return `(この版の結果:${counts}${details})`;
227
+ }
228
+ const counts = `支持${summary.supports}・反証${structural}・判定不能${summary.inconclusive}`;
215
229
  const refuted = summary.refuted_when.length > 0 ? `。反証の条件:${summary.refuted_when.join('/')}` : '';
216
230
  return `(この版の結果:${counts}${refuted})`;
217
231
  }
@@ -231,30 +245,123 @@ export function renderJudgmentFrameCatalog(catalog, outcomes = new Map()) {
231
245
  return lines.join('\n');
232
246
  }
233
247
  const PREDICTION_CHECK_STATUSES = ['held', 'failed', 'unchecked'];
248
+ const PREDICTION_CHECK_KEYS = ['falsified_if', 'status', 'evidence', 'balance'];
249
+ const PREDICTION_BALANCE_KEYS = [
250
+ 'claim_scope',
251
+ 'population',
252
+ 'supporting_summary',
253
+ 'counter_summary',
254
+ 'counter_representativeness',
255
+ 'competing_hypotheses',
256
+ ];
257
+ const COMPETING_HYPOTHESIS_KEYS = ['hypothesis', 'ref', 'comparison'];
234
258
  const MAX_CHECK_EVIDENCE = 800;
259
+ const MAX_COMPETING_HYPOTHESES = 8;
260
+ function isUnsafeCheckText(value) {
261
+ return PUBLIC_FRAME_CONTROL_CHARACTERS.test(value) || containsJudgmentFrameCredential(value);
262
+ }
263
+ function predictionBalanceProblem(value) {
264
+ if (!isRecord(value) || Object.keys(value).some((key) => !PREDICTION_BALANCE_KEYS.includes(key))) {
265
+ return 'check.balance takes claim_scope, population, supporting_summary, counter_summary, and optional counter_representativeness and competing_hypotheses';
266
+ }
267
+ if (!JUDGMENT_FRAME_CLAIM_SCOPES.includes(value.claim_scope)) {
268
+ return 'check.balance.claim_scope must be universal, probabilistic, or bounded_case';
269
+ }
270
+ if (value.counter_representativeness !== undefined
271
+ && !JUDGMENT_MODEL_OUTCOME_REPRESENTATIVENESS.includes(value.counter_representativeness)) {
272
+ return 'check.balance.counter_representativeness must be census, representative, anecdotal, or unknown';
273
+ }
274
+ for (const field of ['population', 'supporting_summary', 'counter_summary']) {
275
+ const candidate = value[field];
276
+ if (typeof candidate !== 'string' || candidate.length > MAX_NOTE) {
277
+ return `check.balance.${field} must be a string of at most ${MAX_NOTE} characters`;
278
+ }
279
+ if (isUnsafeCheckText(candidate)) {
280
+ return `check.balance.${field} contains control characters or a credential-like value`;
281
+ }
282
+ }
283
+ if (value.competing_hypotheses !== undefined) {
284
+ if (!Array.isArray(value.competing_hypotheses) || value.competing_hypotheses.length > MAX_COMPETING_HYPOTHESES) {
285
+ return `check.balance.competing_hypotheses must be a list of at most ${MAX_COMPETING_HYPOTHESES}`;
286
+ }
287
+ for (const entry of value.competing_hypotheses) {
288
+ if (!isRecord(entry) || Object.keys(entry).some((key) => !COMPETING_HYPOTHESIS_KEYS.includes(key))) {
289
+ return 'check.balance.competing_hypotheses entries take hypothesis, comparison, and optional ref';
290
+ }
291
+ if (!nonEmpty(entry.hypothesis, MAX_NOTE) || !nonEmpty(entry.comparison, MAX_NOTE)) {
292
+ return 'check.balance.competing_hypotheses entries need non-empty hypothesis and comparison';
293
+ }
294
+ if (entry.ref !== undefined && !nonEmpty(entry.ref, 1_000)) {
295
+ return 'check.balance.competing_hypotheses.ref must be a non-empty string of at most 1000 characters';
296
+ }
297
+ for (const fieldValue of [entry.hypothesis, entry.comparison, entry.ref]) {
298
+ if (typeof fieldValue === 'string' && isUnsafeCheckText(fieldValue)) {
299
+ return 'check.balance.competing_hypotheses contains control characters or a credential-like value';
300
+ }
301
+ }
302
+ }
303
+ }
304
+ return null;
305
+ }
235
306
  function predictionCheckProblem(value, role) {
236
307
  if (role !== 'prediction')
237
308
  return 'check is only for prediction uses';
238
- if (!isRecord(value) || Object.keys(value).some((key) => !['falsified_if', 'status', 'evidence'].includes(key))) {
239
- return 'check takes falsified_if, status, and evidence';
309
+ if (!isRecord(value) || Object.keys(value).some((key) => !PREDICTION_CHECK_KEYS.includes(key))) {
310
+ return 'check takes falsified_if, status, evidence, and optional balance';
240
311
  }
241
312
  if (!nonEmpty(value.falsified_if, MAX_NOTE))
242
313
  return 'check.falsified_if must say what observation would show the prediction wrong';
314
+ if (isUnsafeCheckText(value.falsified_if)) {
315
+ return 'check contains control characters or a credential-like value';
316
+ }
243
317
  if (!PREDICTION_CHECK_STATUSES.includes(value.status)) {
244
318
  return 'check.status must be held, failed, or unchecked';
245
319
  }
246
320
  if (value.evidence === undefined) {
247
- return value.status === 'unchecked' ? null : 'a held or failed check needs evidence of where it was checked';
321
+ if (value.status !== 'unchecked')
322
+ return 'a held or failed check needs evidence of where it was checked';
248
323
  }
249
- if (!nonEmpty(value.evidence, MAX_CHECK_EVIDENCE))
250
- return `check.evidence must be at most ${MAX_CHECK_EVIDENCE} characters`;
251
- for (const text of [value.falsified_if, value.evidence]) {
252
- if (typeof text === 'string' && (PUBLIC_FRAME_CONTROL_CHARACTERS.test(text) || containsJudgmentFrameCredential(text))) {
324
+ else {
325
+ if (!nonEmpty(value.evidence, MAX_CHECK_EVIDENCE))
326
+ return `check.evidence must be at most ${MAX_CHECK_EVIDENCE} characters`;
327
+ if (isUnsafeCheckText(value.evidence)) {
253
328
  return 'check contains control characters or a credential-like value';
254
329
  }
255
330
  }
331
+ if (value.balance !== undefined) {
332
+ const balanceProblem = predictionBalanceProblem(value.balance);
333
+ if (balanceProblem)
334
+ return balanceProblem;
335
+ }
256
336
  return null;
257
337
  }
338
+ function isUnbalancedPredictionCheck(check) {
339
+ if (!isRecord(check.balance))
340
+ return false;
341
+ const status = check.status;
342
+ if (status !== 'held' && status !== 'failed')
343
+ return false;
344
+ const population = typeof check.balance.population === 'string' ? check.balance.population.trim() : '';
345
+ const supporting = typeof check.balance.supporting_summary === 'string' ? check.balance.supporting_summary.trim() : '';
346
+ const counter = typeof check.balance.counter_summary === 'string' ? check.balance.counter_summary.trim() : '';
347
+ if (status === 'held') {
348
+ return population.length === 0 || counter.length === 0 || supporting.length === 0;
349
+ }
350
+ return population.length === 0
351
+ || counter.length === 0
352
+ || (check.balance.claim_scope === 'probabilistic' && supporting.length === 0);
353
+ }
354
+ /**
355
+ * Pure structural scope-mismatch check: fires only when a probabilistic
356
+ * prediction is marked failed with explicit `counter_representativeness: 'anecdotal'`.
357
+ * Free-text semantic interpretation is intentionally left to offline audit / Eval layers.
358
+ */
359
+ function isScopeMismatchedPredictionCheck(check) {
360
+ return check.status === 'failed'
361
+ && isRecord(check.balance)
362
+ && check.balance.claim_scope === 'probabilistic'
363
+ && check.balance.counter_representativeness === 'anecdotal';
364
+ }
258
365
  /** Counts of the chosen option's predictions by check status. A prediction without a check is unchecked. */
259
366
  export function judgmentFramePredictionCheckCounts(record) {
260
367
  const chosen = record.options.find((option) => option.label === record.chosen_option);
@@ -410,8 +517,14 @@ export function validateJudgmentFrameRecord(value, catalog, outcomes = new Map()
410
517
  if (tension.length > 0)
411
518
  escalations.push({ code: 'chosen_philosophy_tension', refs: tension });
412
519
  const refuted = [...new Set(chosenUses
413
- .filter((use) => isRecord(use) && use.role === 'prediction'
414
- && selected.get(String(use.ref)) === 'model' && (outcomes.get(String(use.ref))?.refutes ?? 0) > 0)
520
+ .filter((use) => {
521
+ if (!isRecord(use) || use.role !== 'prediction' || selected.get(String(use.ref)) !== 'model')
522
+ return false;
523
+ const summary = outcomes.get(String(use.ref));
524
+ if (!summary)
525
+ return false;
526
+ return (summary.structural_refutes ?? summary.refutes) > 0;
527
+ })
415
528
  .map((use) => String(use.ref)))];
416
529
  if (refuted.length > 0)
417
530
  escalations.push({ code: 'chosen_uses_refuted_model', refs: refuted });
@@ -422,12 +535,60 @@ export function validateJudgmentFrameRecord(value, catalog, outcomes = new Map()
422
535
  if (failed.length > 0)
423
536
  escalations.push({ code: 'chosen_relies_on_failed_prediction', refs: failed });
424
537
  }
538
+ const allPredictionUsesWithBalance = (options ?? []).flatMap((option) => (isRecord(option) && Array.isArray(option.uses) ? option.uses : [])).filter((use) => (isRecord(use)
539
+ && use.role === 'prediction'
540
+ && selected.has(String(use.ref))
541
+ && isRecord(use.check)
542
+ && isRecord(use.check.balance)));
543
+ if (allPredictionUsesWithBalance.length > 0) {
544
+ const unbalanced = [...new Set(allPredictionUsesWithBalance
545
+ .filter((use) => isUnbalancedPredictionCheck(use.check))
546
+ .map((use) => String(use.ref)))];
547
+ if (unbalanced.length > 0)
548
+ escalations.push({ code: 'prediction_unbalanced_evidence', refs: unbalanced });
549
+ const scopeMismatched = [...new Set(allPredictionUsesWithBalance
550
+ .filter((use) => isScopeMismatchedPredictionCheck(use.check))
551
+ .map((use) => String(use.ref)))];
552
+ if (scopeMismatched.length > 0)
553
+ escalations.push({ code: 'prediction_scope_mismatch', refs: scopeMismatched });
554
+ }
425
555
  return { valid: issues.length === 0, issues, escalations };
426
556
  }
427
557
  // ---------------------------------------------------------------------------
428
558
  // MCP tools. The host injects how Graph records are read; these definitions
429
559
  // and the validation stay shared so every host enforces the same contract.
430
560
  const FRAME_PAGE_LIMIT = 500;
561
+ const predictionBalanceSchema = {
562
+ type: 'object',
563
+ additionalProperties: false,
564
+ description: 'Optional scope, population, supporting/counter balance, counter_representativeness, and competing hypotheses to guard against cherry-picking and scope mismatch. Missing population/balance escalates prediction_unbalanced_evidence; marking a probabilistic prediction failed with counter_representativeness: "anecdotal" escalates prediction_scope_mismatch.',
565
+ properties: {
566
+ claim_scope: { type: 'string', enum: [...JUDGMENT_FRAME_CLAIM_SCOPES] },
567
+ population: { type: 'string', maxLength: MAX_NOTE },
568
+ supporting_summary: { type: 'string', maxLength: MAX_NOTE },
569
+ counter_summary: { type: 'string', maxLength: MAX_NOTE },
570
+ counter_representativeness: {
571
+ type: 'string',
572
+ enum: [...JUDGMENT_MODEL_OUTCOME_REPRESENTATIVENESS],
573
+ description: 'Optional representativeness of the counter-evidence. When failing a probabilistic prediction (claim_scope: "probabilistic") on an anecdotal/single-case exception only, set counter_representativeness: "anecdotal" to trigger prediction_scope_mismatch.',
574
+ },
575
+ competing_hypotheses: {
576
+ type: 'array',
577
+ maxItems: MAX_COMPETING_HYPOTHESES,
578
+ items: {
579
+ type: 'object',
580
+ additionalProperties: false,
581
+ properties: {
582
+ hypothesis: { type: 'string', minLength: 1, maxLength: MAX_NOTE },
583
+ ref: { type: 'string', minLength: 1, maxLength: 1_000 },
584
+ comparison: { type: 'string', minLength: 1, maxLength: MAX_NOTE },
585
+ },
586
+ required: ['hypothesis', 'comparison'],
587
+ },
588
+ },
589
+ },
590
+ required: ['claim_scope', 'population', 'supporting_summary', 'counter_summary'],
591
+ };
431
592
  const frameUseSchema = {
432
593
  type: 'object',
433
594
  additionalProperties: false,
@@ -439,11 +600,12 @@ const frameUseSchema = {
439
600
  check: {
440
601
  type: 'object',
441
602
  additionalProperties: false,
442
- description: 'Only for prediction uses: what observation would show the prediction wrong, and whether it was checked against data. held and failed need evidence. A chosen option that relies on a failed prediction returns the choice to the human.',
603
+ description: 'Only for prediction uses: what observation would show the prediction wrong, and whether it was checked against data. held and failed need evidence. Optional balance records claim_scope, population, supporting_summary, counter_summary, and competing_hypotheses to prevent cherry-picking and scope mismatch. A chosen option that relies on a failed prediction returns the choice to the human.',
443
604
  properties: {
444
605
  falsified_if: { type: 'string', minLength: 1, maxLength: MAX_NOTE },
445
606
  status: { type: 'string', enum: ['held', 'failed', 'unchecked'] },
446
607
  evidence: { type: 'string', minLength: 1, maxLength: 800 },
608
+ balance: predictionBalanceSchema,
447
609
  },
448
610
  required: ['falsified_if', 'status'],
449
611
  },
@@ -466,7 +628,7 @@ export const judgmentFrameTools = [{
466
628
  annotations: { readOnlyHint: true, destructiveHint: false },
467
629
  }, {
468
630
  name: 'brainbase_judgment_frame_record',
469
- description: 'Record the judgment frame: which catalog references you selected and why, and for each evaluated option how each selected reference was used. Philosophy is a constraint (give verdict satisfied, violated, or tension), an objective is a criterion, a world model is a prediction. Every selection must be used by at least one option. For a kind with no applicable reference, give the reason in none instead of selecting. Name the option you chose. The tool rejects references outside the catalog; it does not judge semantic quality. If escalations are returned, ask the human before acting on the chosen option. Include public_frame only when the caller explicitly intends this exact summary and reason for the future owner-only projection; Core never derives it from an answer, tool response, or internal reasoning. public_frame accepts only non-empty safe summary and reason strings up to 2000 characters.',
631
+ description: 'Record the judgment frame: which catalog references you selected and why, and for each evaluated option how each selected reference was used. Philosophy is a constraint (give verdict satisfied, violated, or tension), an objective is a criterion, a world model is a prediction. Every selection must be used by at least one option. For a kind with no applicable reference, give the reason in none instead of selecting. Name the option you chose. For prediction checks, you may optionally include check.balance (claim_scope, population, supporting_summary, counter_summary, optional counter_representativeness, and competing_hypotheses) to record scope and counter-evidence balance; missing population/balance returns prediction_unbalanced_evidence, and failing a probabilistic claim with counter_representativeness: "anecdotal" returns prediction_scope_mismatch. The tool rejects references outside the catalog; it does not judge semantic quality. If escalations are returned, ask the human before acting on the chosen option. Include public_frame only when the caller explicitly intends this exact summary and reason for the future owner-only projection; Core never derives it from an answer, tool response, or internal reasoning. public_frame accepts only non-empty safe summary and reason strings up to 2000 characters.',
470
632
  inputSchema: {
471
633
  type: 'object',
472
634
  additionalProperties: false,
@@ -614,7 +776,7 @@ const outcomeTextSchema = { type: 'string', minLength: 1, maxLength: 2_000 };
614
776
  */
615
777
  export const judgmentModelOutcomeTools = [{
616
778
  name: 'brainbase_judgment_model_outcome_record',
617
- description: 'After the result of a judgment is observed, record whether it supports or refutes a world model that the judgment used as a prediction. Read brainbase_judgment_frame_catalog first and pass its catalog_digest and the model id at its current revision. State the prediction made from the model, what was observed, the conditions (facility, period, state) under which the result holds, and at least one evidence reference. A refutation must say, for each of measurement_error, execution_difference, and external_change, why it does not explain the gap; a prediction gap alone is not a refutation. This does not change the model, its revision, or its adoption; adoption and verification stay human decisions. The tool does not judge whether the verdict is semantically right.',
779
+ description: 'After the result of a judgment is observed, record whether it supports or refutes a world model that the judgment used as a prediction. Read brainbase_judgment_frame_catalog first and pass its catalog_digest and the model id at its current revision. State the prediction made from the model, what was observed, the conditions (facility, period, state) under which the result holds, and at least one evidence reference. A refutation must say, for each of measurement_error, execution_difference, and external_change, why it does not explain the gap; a prediction gap alone is not a refutation. Optionally include scope_metrics (claim_type, representativeness, and optional sample_size, population_size, effect_magnitude) so explicitly anecdotal refutations against tendency claims are tracked separately from structural refutations (unknown representativeness stays conservatively structural). This does not change the model, its revision, or its adoption; adoption and verification stay human decisions. The tool does not judge whether the verdict is semantically right.',
618
780
  inputSchema: {
619
781
  type: 'object',
620
782
  additionalProperties: false,
@@ -662,6 +824,19 @@ export const judgmentModelOutcomeTools = [{
662
824
  properties: { frame_digest: { type: 'string', pattern: '^sha256:[a-f0-9]{64}$' } },
663
825
  required: ['frame_digest'],
664
826
  },
827
+ scope_metrics: {
828
+ type: 'object',
829
+ additionalProperties: false,
830
+ description: 'Optional claim scope and representativeness metrics. Explicitly anecdotal refutations on tendency claims are summarized separately from structural refutations; unknown representativeness stays conservatively structural.',
831
+ properties: {
832
+ claim_type: { type: 'string', enum: [...JUDGMENT_MODEL_OUTCOME_CLAIM_TYPES] },
833
+ sample_size: { type: 'integer', minimum: 1 },
834
+ population_size: { type: 'integer', minimum: 1 },
835
+ effect_magnitude: { type: 'string', minLength: 1, maxLength: 200 },
836
+ representativeness: { type: 'string', enum: [...JUDGMENT_MODEL_OUTCOME_REPRESENTATIVENESS] },
837
+ },
838
+ required: ['claim_type', 'representativeness'],
839
+ },
665
840
  },
666
841
  required: ['record_version', 'catalog_digest', 'model', 'verdict', 'prediction', 'observed', 'conditions', 'evidence_refs'],
667
842
  },
@@ -702,5 +877,5 @@ export async function handleJudgmentModelOutcomeToolCall(name, args, dependencie
702
877
  },
703
878
  };
704
879
  }
705
- export { JUDGMENT_MODEL_OUTCOME_ALTERNATIVES, JUDGMENT_MODEL_OUTCOME_RECORD_VERSION, judgmentModelOutcomeDigest, parseJudgmentModelOutcomeRecords, summarizeJudgmentModelOutcomes, validateJudgmentModelOutcome, } from './judgment-model-outcome.js';
880
+ export { JUDGMENT_MODEL_OUTCOME_ALTERNATIVES, JUDGMENT_MODEL_OUTCOME_CLAIM_TYPES, JUDGMENT_MODEL_OUTCOME_RECORD_VERSION, JUDGMENT_MODEL_OUTCOME_REPRESENTATIVENESS, isAnecdotalRefutation, judgmentModelOutcomeDigest, parseJudgmentModelOutcomeRecords, summarizeJudgmentModelOutcomes, validateJudgmentModelOutcome, } from './judgment-model-outcome.js';
706
881
  export { judgmentFrameReadTools, handleJudgmentFrameReadToolCall, } from './judgment-frame-read.js';