@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.
- package/contracts/brainbase-public-contract.v1.json +1 -0
- package/dist/antigravity-judgment-hook.d.ts +191 -0
- package/dist/antigravity-judgment-hook.js +2042 -0
- package/dist/claude-code-judgment-hook.d.ts +23 -0
- package/dist/claude-code-judgment-hook.js +8 -5
- package/dist/cli.js +273 -6
- package/dist/graph-retrieval.d.ts +4 -0
- package/dist/graph-retrieval.js +4 -0
- package/dist/judgment-event-adapter.d.ts +37 -2
- package/dist/judgment-event-adapter.js +88 -3
- package/dist/judgment-event-outbox.d.ts +9 -1
- package/dist/judgment-event-outbox.js +45 -8
- package/dist/judgment-execution-outcome.d.ts +2 -1
- package/dist/judgment-execution-outcome.js +2 -1
- package/dist/judgment-frame.d.ts +26 -4
- package/dist/judgment-frame.js +190 -15
- package/dist/judgment-host.d.ts +30 -0
- package/dist/judgment-host.js +170 -22
- package/dist/judgment-model-outcome.d.ts +29 -1
- package/dist/judgment-model-outcome.js +69 -1
- package/dist/judgment-offline-binary-audit.d.ts +360 -0
- package/dist/judgment-offline-binary-audit.js +555 -0
- package/dist/judgment-project-binding.d.ts +1 -1
- package/dist/judgment-project-binding.js +2 -1
- package/dist/judgment-reasoning-audit.d.ts +115 -0
- package/dist/judgment-reasoning-audit.js +623 -0
- package/dist/judgment-reasoning-gate-prompt.d.ts +42 -0
- package/dist/judgment-reasoning-gate-prompt.js +83 -0
- package/dist/judgment-runtime-resolution.d.ts +2 -2
- package/dist/judgment-runtime-resolution.js +2 -2
- package/dist/judgment-runtime-resolution.public.d.ts +2 -2
- package/dist/judgment-session-world-model.d.ts +163 -0
- package/dist/judgment-session-world-model.js +408 -0
- package/dist/organization-graph.js +9 -1
- package/dist/remote-judgment-hook-http.d.ts +36 -3
- package/dist/remote-judgment-hook-http.js +94 -15
- package/package.json +10 -2
- package/ui/README.md +31 -0
- package/ui/graph-own-share.js +106 -50
- package/ui/graph-projects-view.js +4 -4
- package/ui/graph-view-shared.css +3 -0
- package/ui/workspace-kit.css +141 -0
- package/ui/workspace-kit.js +50 -1
- package/ui/world/world-view.js +1 -1
package/dist/judgment-host.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { type JudgmentAutonomyEvaluation, type JudgmentAutonomyResolver } from './judgment-autonomy.js';
|
|
2
2
|
import type { JudgmentKnowledgeEventSink } from './judgment-event-outbox.js';
|
|
3
3
|
import { canonicalJson } from './judgment-resolution-contract.js';
|
|
4
|
+
import { AUDIT_LINE_STRIP_PREFIX, COMPACT_FOUR_BLOCK_GATE_PROMPT_V2, COMPACT_FOUR_BLOCK_GATE_PROMPT_V3, REASONING_GATE_MODES, resolveReasoningGateMode, shouldApplyReasoningGate, type ReasoningGateHostConfig, type ReasoningGateMode } from './judgment-reasoning-gate-prompt.js';
|
|
5
|
+
import { DEFAULT_SESSION_WORLD_MODEL_UPDATE_TIMEOUT_MS, SESSION_MINI_WORLD_MODEL_SCHEMA_VERSION_V2, SESSION_WORLD_MODEL_FILENAME, SESSION_WORLD_MODEL_LOCK_FILENAME, WM_V2_LIMITS, parseSessionMiniWorldModelV2, readSessionMiniWorldModelV2, renderSessionMiniWorldModelPinV2, sessionWorldModelPaths, toLearningCandidateEvidenceDraftFromSessionWMV2, withSessionWorldModelLock, writeSessionMiniWorldModelV2, type SessionMiniWorldModelV2, type SessionWMLearningEvidenceDraftResultV2, type SessionWMLearningEvidenceDraftV2, type SessionWorldModelPaths, type SessionWorldModelUpdateEventV2, type SessionWorldModelUpdaterV2, type SessionWorldModelWriteResult } from './judgment-session-world-model.js';
|
|
6
|
+
export { AUDIT_LINE_STRIP_PREFIX, COMPACT_FOUR_BLOCK_GATE_PROMPT_V2, COMPACT_FOUR_BLOCK_GATE_PROMPT_V3, DEFAULT_SESSION_WORLD_MODEL_UPDATE_TIMEOUT_MS, REASONING_GATE_MODES, SESSION_MINI_WORLD_MODEL_SCHEMA_VERSION_V2, SESSION_WORLD_MODEL_FILENAME, SESSION_WORLD_MODEL_LOCK_FILENAME, WM_V2_LIMITS, parseSessionMiniWorldModelV2, readSessionMiniWorldModelV2, renderSessionMiniWorldModelPinV2, resolveReasoningGateMode, sessionWorldModelPaths, shouldApplyReasoningGate, toLearningCandidateEvidenceDraftFromSessionWMV2, withSessionWorldModelLock, writeSessionMiniWorldModelV2, type ReasoningGateHostConfig, type ReasoningGateMode, type SessionMiniWorldModelV2, type SessionWMLearningEvidenceDraftResultV2, type SessionWMLearningEvidenceDraftV2, type SessionWorldModelPaths, type SessionWorldModelUpdateEventV2, type SessionWorldModelUpdaterV2, type SessionWorldModelWriteResult };
|
|
4
7
|
type Environment = Record<string, string | undefined>;
|
|
5
8
|
export interface ConversationMessage {
|
|
6
9
|
sequence?: number;
|
|
@@ -109,6 +112,22 @@ export interface JudgmentHookOutput {
|
|
|
109
112
|
additionalContext: string;
|
|
110
113
|
};
|
|
111
114
|
}
|
|
115
|
+
/**
|
|
116
|
+
* Non-digest runtime telemetry emitted on `UserPromptSubmit` for Dogfooding Layer 1
|
|
117
|
+
* observability (`reasoningGateApplied / eligibleTurns`). Never included in
|
|
118
|
+
* `episode_digest`, `receipt_digest`, or hook stdout contracts.
|
|
119
|
+
*/
|
|
120
|
+
export interface ReasoningGateTelemetryEvent {
|
|
121
|
+
readonly event: 'judgment_reasoning_gate_evaluated';
|
|
122
|
+
readonly session_ref: string;
|
|
123
|
+
readonly turn_id: string;
|
|
124
|
+
readonly project_code: string | null;
|
|
125
|
+
readonly replay: boolean;
|
|
126
|
+
readonly reasoning_gate_mode: ReasoningGateMode;
|
|
127
|
+
readonly reasoning_gate_applied: boolean;
|
|
128
|
+
readonly reasoning_gate_eligible: boolean;
|
|
129
|
+
readonly session_wm_injected: boolean;
|
|
130
|
+
}
|
|
112
131
|
export interface JudgmentHostOptions {
|
|
113
132
|
env?: Environment;
|
|
114
133
|
resolver?: (request: JudgmentRequest) => Promise<JudgmentReceipt>;
|
|
@@ -117,6 +136,17 @@ export interface JudgmentHostOptions {
|
|
|
117
136
|
autonomyResolver?: JudgmentAutonomyResolver;
|
|
118
137
|
autonomyMode?: JudgmentAutonomyMode;
|
|
119
138
|
autonomyCanaryProjects?: readonly string[];
|
|
139
|
+
reasoningGateMode?: ReasoningGateMode | 'compact_4block_v2';
|
|
140
|
+
reasoningGateCanaryProjects?: readonly string[];
|
|
141
|
+
/** Optional non-digest reasoning gate telemetry callback (fail-open). */
|
|
142
|
+
onReasoningGateTelemetry?: (event: ReasoningGateTelemetryEvent) => void;
|
|
143
|
+
/**
|
|
144
|
+
* Optional PR-B ephemeral session mini world model v2 updater.
|
|
145
|
+
* Invoked strictly AFTER `withTurnLock` releases on audited `Stop` completions.
|
|
146
|
+
*/
|
|
147
|
+
sessionWorldModelUpdater?: SessionWorldModelUpdaterV2;
|
|
148
|
+
/** Fail-open timeout in ms for `sessionWorldModelUpdater.enqueue()`. Defaults to 1500 ms. */
|
|
149
|
+
sessionWorldModelUpdateTimeoutMs?: number;
|
|
120
150
|
trustedConversationMessages?: ConversationMessage[];
|
|
121
151
|
/** Optional adapter-owned queue. The default Host lifecycle remains unchanged. */
|
|
122
152
|
knowledgeEventSink?: JudgmentKnowledgeEventSink;
|
package/dist/judgment-host.js
CHANGED
|
@@ -3,8 +3,12 @@ import { closeSync, constants as fsConstants, fsyncSync, linkSync, mkdirSync, op
|
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
5
5
|
import { evaluateJudgmentAutonomy, renderJudgmentAutonomyContinuation } from './judgment-autonomy.js';
|
|
6
|
-
import { toKnowledgeEventFromJudgmentEpisode } from './judgment-event-adapter.js';
|
|
6
|
+
import { normalizeJudgmentEventProjectCode, toKnowledgeEventFromJudgmentEpisode } from './judgment-event-adapter.js';
|
|
7
|
+
import { containsJudgmentFrameCredential } from './judgment-frame.js';
|
|
7
8
|
import { canonicalJson } from './judgment-resolution-contract.js';
|
|
9
|
+
import { AUDIT_LINE_STRIP_PREFIX, COMPACT_FOUR_BLOCK_GATE_PROMPT_V2, COMPACT_FOUR_BLOCK_GATE_PROMPT_V3, REASONING_GATE_MODES, resolveReasoningGateMode, shouldApplyReasoningGate } from './judgment-reasoning-gate-prompt.js';
|
|
10
|
+
import { DEFAULT_SESSION_WORLD_MODEL_UPDATE_TIMEOUT_MS, SESSION_MINI_WORLD_MODEL_SCHEMA_VERSION_V2, SESSION_WORLD_MODEL_FILENAME, SESSION_WORLD_MODEL_LOCK_FILENAME, WM_V2_LIMITS, parseSessionMiniWorldModelV2, readSessionMiniWorldModelV2, renderSessionMiniWorldModelPinV2, sessionWorldModelPaths, toLearningCandidateEvidenceDraftFromSessionWMV2, withSessionWorldModelLock, writeSessionMiniWorldModelV2 } from './judgment-session-world-model.js';
|
|
11
|
+
export { AUDIT_LINE_STRIP_PREFIX, COMPACT_FOUR_BLOCK_GATE_PROMPT_V2, COMPACT_FOUR_BLOCK_GATE_PROMPT_V3, DEFAULT_SESSION_WORLD_MODEL_UPDATE_TIMEOUT_MS, REASONING_GATE_MODES, SESSION_MINI_WORLD_MODEL_SCHEMA_VERSION_V2, SESSION_WORLD_MODEL_FILENAME, SESSION_WORLD_MODEL_LOCK_FILENAME, WM_V2_LIMITS, parseSessionMiniWorldModelV2, readSessionMiniWorldModelV2, renderSessionMiniWorldModelPinV2, resolveReasoningGateMode, sessionWorldModelPaths, shouldApplyReasoningGate, toLearningCandidateEvidenceDraftFromSessionWMV2, withSessionWorldModelLock, writeSessionMiniWorldModelV2 };
|
|
8
12
|
const DEFAULT_HOST_BINDING = Object.freeze({
|
|
9
13
|
adapter_id: 'brainbase-local',
|
|
10
14
|
adapter_version: '1',
|
|
@@ -968,7 +972,7 @@ function normalizedAnswerBody(answer, expectedLines) {
|
|
|
968
972
|
const bodyLines = answer.replaceAll('\r\n', '\n').split('\n')
|
|
969
973
|
.map((line) => line.replace(/[ \t]+$/u, ''))
|
|
970
974
|
.filter((line) => !auditLines.has(line));
|
|
971
|
-
while (bodyLines.length > 0 && (bodyLines[0] === '' ||
|
|
975
|
+
while (bodyLines.length > 0 && (bodyLines[0] === '' || AUDIT_LINE_STRIP_PREFIX.test(bodyLines[0])))
|
|
972
976
|
bodyLines.shift();
|
|
973
977
|
while (bodyLines.at(-1) === '')
|
|
974
978
|
bodyLines.pop();
|
|
@@ -1081,8 +1085,60 @@ export function buildOwnerAudit(request, receipt, { historicalExact = true } = {
|
|
|
1081
1085
|
export function buildOwnerReferenceLine(request, receipt) {
|
|
1082
1086
|
return buildOwnerAudit(request, receipt).display_line;
|
|
1083
1087
|
}
|
|
1084
|
-
function
|
|
1088
|
+
function invokeFailOpenObserver(observer, event) {
|
|
1089
|
+
if (!observer)
|
|
1090
|
+
return;
|
|
1091
|
+
try {
|
|
1092
|
+
const result = observer(event);
|
|
1093
|
+
if (result !== null && (typeof result === 'object' || typeof result === 'function')
|
|
1094
|
+
&& typeof result.then === 'function') {
|
|
1095
|
+
Promise.resolve(result).catch(() => {
|
|
1096
|
+
// Non-digest telemetry must never affect hook output or emit unhandled rejections.
|
|
1097
|
+
});
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
catch {
|
|
1101
|
+
// Non-digest telemetry must never affect hook output.
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
function emitReasoningGateTelemetry(options, env, telemetry) {
|
|
1105
|
+
invokeFailOpenObserver(options.onReasoningGateTelemetry, telemetry);
|
|
1106
|
+
const stderrMode = env.BRAINBASE_JUDGMENT_REASONING_GATE_TELEMETRY?.trim().toLowerCase();
|
|
1107
|
+
const shouldWriteStderr = stderrMode === 'stderr'
|
|
1108
|
+
|| (telemetry.reasoning_gate_mode !== 'off' && stderrMode !== 'off');
|
|
1109
|
+
if (shouldWriteStderr) {
|
|
1110
|
+
try {
|
|
1111
|
+
process.stderr.write(`${JSON.stringify(telemetry)}\n`);
|
|
1112
|
+
}
|
|
1113
|
+
catch {
|
|
1114
|
+
// Non-digest telemetry must never affect hook output.
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
function successOutput(request, receipt, ownerAudit = buildOwnerAudit(request, receipt), options = {}, env = {}, { replay = false } = {}) {
|
|
1085
1119
|
const ownerReferenceLine = ownerAudit.display_line;
|
|
1120
|
+
const projectCode = request.project_code ?? receipt.project_code;
|
|
1121
|
+
const reasoningGateMode = resolveReasoningGateMode(options, env, projectCode);
|
|
1122
|
+
const reasoningGateEligible = shouldApplyReasoningGate(receipt);
|
|
1123
|
+
const applyReasoningGate = reasoningGateMode !== 'off' && reasoningGateEligible;
|
|
1124
|
+
let sessionWmPin = null;
|
|
1125
|
+
if (applyReasoningGate && reasoningGateMode === 'compact_4block_with_wm') {
|
|
1126
|
+
const wmState = readSessionMiniWorldModelV2(journalRoot(env), request.conversation_context.session_ref);
|
|
1127
|
+
if (wmState) {
|
|
1128
|
+
sessionWmPin = renderSessionMiniWorldModelPinV2(wmState, containsJudgmentFrameCredential);
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
emitReasoningGateTelemetry(options, env, {
|
|
1132
|
+
event: 'judgment_reasoning_gate_evaluated',
|
|
1133
|
+
session_ref: request.conversation_context.session_ref,
|
|
1134
|
+
turn_id: request.turn_id,
|
|
1135
|
+
project_code: projectCode ?? null,
|
|
1136
|
+
replay,
|
|
1137
|
+
reasoning_gate_mode: reasoningGateMode,
|
|
1138
|
+
reasoning_gate_applied: applyReasoningGate,
|
|
1139
|
+
reasoning_gate_eligible: reasoningGateEligible,
|
|
1140
|
+
session_wm_injected: sessionWmPin !== null
|
|
1141
|
+
});
|
|
1086
1142
|
const executionPlan = {
|
|
1087
1143
|
status: receipt.status,
|
|
1088
1144
|
active_edges: receipt.active_edges,
|
|
@@ -1109,7 +1165,9 @@ function successOutput(request, receipt, ownerAudit = buildOwnerAudit(request, r
|
|
|
1109
1165
|
? 'This route requires a successful portable knowledge call; do not claim a zero-call completion.'
|
|
1110
1166
|
: `If no portable Brainbase MCP call occurs, put this exact line immediately after the judgment line:\n${ZERO_CALL_DISPLAY_LINE}`,
|
|
1111
1167
|
`Execution plan: ${JSON.stringify(executionPlan)}`,
|
|
1112
|
-
`audit_contract: ${JSON.stringify(auditContract)}
|
|
1168
|
+
`audit_contract: ${JSON.stringify(auditContract)}`,
|
|
1169
|
+
...(applyReasoningGate ? ['', COMPACT_FOUR_BLOCK_GATE_PROMPT_V3] : []),
|
|
1170
|
+
...(sessionWmPin ? ['', sessionWmPin] : [])
|
|
1113
1171
|
].join('\n');
|
|
1114
1172
|
return {
|
|
1115
1173
|
continue: true,
|
|
@@ -1121,6 +1179,8 @@ function successOutput(request, receipt, ownerAudit = buildOwnerAudit(request, r
|
|
|
1121
1179
|
export async function runJudgmentHost(payload, options = {}) {
|
|
1122
1180
|
const env = options.env ?? process.env;
|
|
1123
1181
|
const expectedHostBinding = normalizeExpectedHostBinding(options.expectedHostBinding);
|
|
1182
|
+
// Fail fast on invalid reasoning gate configuration before acquiring locks or invoking a resolver.
|
|
1183
|
+
resolveReasoningGateMode(options, env);
|
|
1124
1184
|
const sessionId = typeof payload.session_id === 'string' ? payload.session_id : '';
|
|
1125
1185
|
const turnId = typeof payload.turn_id === 'string' ? payload.turn_id.trim() : '';
|
|
1126
1186
|
if (!sessionId || !turnId)
|
|
@@ -1134,7 +1194,7 @@ export async function runJudgmentHost(payload, options = {}) {
|
|
|
1134
1194
|
if (!requestText || episode.request_text_digest !== sha256(requestText)) {
|
|
1135
1195
|
throw new Error('judgment_episode_binding_mismatch');
|
|
1136
1196
|
}
|
|
1137
|
-
return successOutput(episode.adoption.request, episode.adoption.receipt, episode.adoption.owner_audit);
|
|
1197
|
+
return successOutput(episode.adoption.request, episode.adoption.receipt, episode.adoption.owner_audit, options, env, { replay: true });
|
|
1138
1198
|
}
|
|
1139
1199
|
catch (error) {
|
|
1140
1200
|
if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
|
|
@@ -1172,7 +1232,7 @@ export async function runJudgmentHost(payload, options = {}) {
|
|
|
1172
1232
|
episode_digest: sha256(canonicalJson(episodeWithoutDigest))
|
|
1173
1233
|
};
|
|
1174
1234
|
writeImmutableJson(paths.episode, episode);
|
|
1175
|
-
return successOutput(adoption.request, adoption.receipt, adoption.owner_audit);
|
|
1235
|
+
return successOutput(adoption.request, adoption.receipt, adoption.owner_audit, options, env, { replay: false });
|
|
1176
1236
|
});
|
|
1177
1237
|
}
|
|
1178
1238
|
function hookIdentity(payload) {
|
|
@@ -1513,11 +1573,59 @@ async function evaluateAutonomyStop(payload, env, options) {
|
|
|
1513
1573
|
reason: renderJudgmentAutonomyContinuation(evaluation)
|
|
1514
1574
|
};
|
|
1515
1575
|
}
|
|
1516
|
-
async function
|
|
1576
|
+
async function enqueueSessionWorldModelUpdateFailOpen(input) {
|
|
1577
|
+
const updater = input.options.sessionWorldModelUpdater;
|
|
1578
|
+
if (!updater || !input.candidate.ownerAuditComplete)
|
|
1579
|
+
return;
|
|
1580
|
+
let mode;
|
|
1581
|
+
try {
|
|
1582
|
+
mode = resolveReasoningGateMode(input.options, input.env, input.candidate.projectCode);
|
|
1583
|
+
}
|
|
1584
|
+
catch {
|
|
1585
|
+
return;
|
|
1586
|
+
}
|
|
1587
|
+
if (mode !== 'compact_4block_with_wm')
|
|
1588
|
+
return;
|
|
1589
|
+
const previousState = readSessionMiniWorldModelV2(journalRoot(input.env), input.sessionRef);
|
|
1590
|
+
if (previousState?.updated_after_turn_id === input.turnId)
|
|
1591
|
+
return;
|
|
1592
|
+
const turnSequence = Math.max(input.candidate.priorReceiptsCount + 1, (previousState?.turn_sequence ?? 0) + 1);
|
|
1593
|
+
const event = {
|
|
1594
|
+
session_ref: input.sessionRef,
|
|
1595
|
+
turn_id: input.turnId,
|
|
1596
|
+
turn_sequence: turnSequence,
|
|
1597
|
+
user_prompt: input.candidate.userPrompt,
|
|
1598
|
+
final_answer: input.candidate.finalAnswer,
|
|
1599
|
+
previous_state: previousState
|
|
1600
|
+
};
|
|
1601
|
+
const configuredTimeout = input.options.sessionWorldModelUpdateTimeoutMs;
|
|
1602
|
+
const timeoutMs = typeof configuredTimeout === 'number' && Number.isFinite(configuredTimeout) && configuredTimeout > 0
|
|
1603
|
+
? configuredTimeout
|
|
1604
|
+
: DEFAULT_SESSION_WORLD_MODEL_UPDATE_TIMEOUT_MS;
|
|
1605
|
+
let timer;
|
|
1606
|
+
try {
|
|
1607
|
+
await Promise.race([
|
|
1608
|
+
Promise.resolve().then(() => updater.enqueue(event)),
|
|
1609
|
+
new Promise((_resolve, reject) => {
|
|
1610
|
+
timer = setTimeout(() => reject(new Error('session_world_model_update_timeout')), timeoutMs);
|
|
1611
|
+
})
|
|
1612
|
+
]);
|
|
1613
|
+
}
|
|
1614
|
+
catch {
|
|
1615
|
+
// Complete fail-open: exceptions or timeouts must never fail finalizeEpisode().
|
|
1616
|
+
}
|
|
1617
|
+
finally {
|
|
1618
|
+
if (timer !== undefined)
|
|
1619
|
+
clearTimeout(timer);
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
async function finalizeEpisode(payload, env, options = {}, expectedHostBinding = DEFAULT_HOST_BINDING) {
|
|
1623
|
+
const knowledgeEventSink = options.knowledgeEventSink;
|
|
1517
1624
|
const { sessionRef, turnId } = hookIdentity(payload);
|
|
1518
1625
|
const paths = journalPaths(sessionRef, turnId, env);
|
|
1519
|
-
const
|
|
1520
|
-
|
|
1626
|
+
const answer = typeof payload.last_assistant_message === 'string' ? payload.last_assistant_message : '';
|
|
1627
|
+
const answerDigest = sha256(answer);
|
|
1628
|
+
const lockedResult = await withTurnLock(paths.lock, async () => {
|
|
1521
1629
|
let episode;
|
|
1522
1630
|
try {
|
|
1523
1631
|
episode = readEpisode(paths.episode);
|
|
@@ -1533,6 +1641,10 @@ async function finalizeEpisode(payload, env, knowledgeEventSink, expectedHostBin
|
|
|
1533
1641
|
}
|
|
1534
1642
|
const events = readEvents(paths.events);
|
|
1535
1643
|
const eventSetDigest = sha256(canonicalJson(events));
|
|
1644
|
+
const expectedAuditLines = requiredAuditLines(episode, events);
|
|
1645
|
+
const body = normalizedAnswerBody(answer, expectedAuditLines);
|
|
1646
|
+
const projectCode = episode.adoption.request.project_code ?? episode.adoption.receipt.project_code;
|
|
1647
|
+
const priorReceiptsCount = episode.adoption.request.conversation_context.prior_receipts.length;
|
|
1536
1648
|
try {
|
|
1537
1649
|
const existing = readFinal(paths.final);
|
|
1538
1650
|
if (existing.initial_receipt_digest !== episode.initial_receipt_digest
|
|
@@ -1541,16 +1653,23 @@ async function finalizeEpisode(payload, env, knowledgeEventSink, expectedHostBin
|
|
|
1541
1653
|
|| existing.answer_digest !== answerDigest) {
|
|
1542
1654
|
throw new Error('judgment_final_conflict');
|
|
1543
1655
|
}
|
|
1544
|
-
await enqueueFinalizedKnowledgeEvent(knowledgeEventSink, sessionRef, turnId, existing,
|
|
1545
|
-
return
|
|
1656
|
+
await enqueueFinalizedKnowledgeEvent(knowledgeEventSink, sessionRef, turnId, existing, answer, projectCode);
|
|
1657
|
+
return {
|
|
1658
|
+
output: existing,
|
|
1659
|
+
wmCandidate: {
|
|
1660
|
+
projectCode,
|
|
1661
|
+
userPrompt: episode.adoption.request.request,
|
|
1662
|
+
finalAnswer: body,
|
|
1663
|
+
priorReceiptsCount,
|
|
1664
|
+
ownerAuditComplete: existing.owner_audit_complete === true
|
|
1665
|
+
}
|
|
1666
|
+
};
|
|
1546
1667
|
}
|
|
1547
1668
|
catch (error) {
|
|
1548
1669
|
if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
|
|
1549
1670
|
throw error;
|
|
1550
1671
|
}
|
|
1551
|
-
const expectedAuditLines = requiredAuditLines(episode, events);
|
|
1552
1672
|
const expectedAuditLinesDigest = sha256(canonicalJson(expectedAuditLines));
|
|
1553
|
-
const answer = typeof payload.last_assistant_message === 'string' ? payload.last_assistant_message : '';
|
|
1554
1673
|
const missingKnowledge = episode.adoption.receipt.selected_dag_ids.includes('knowledge.v1')
|
|
1555
1674
|
&& !events.some((event) => event.success && event.satisfies.includes('knowledge.resolve'));
|
|
1556
1675
|
const missingOwnerAudit = !answerContainsExactAuditPrefix(answer, expectedAuditLines);
|
|
@@ -1565,7 +1684,6 @@ async function finalizeEpisode(payload, env, knowledgeEventSink, expectedHostBin
|
|
|
1565
1684
|
if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
|
|
1566
1685
|
throw error;
|
|
1567
1686
|
}
|
|
1568
|
-
const body = normalizedAnswerBody(answer, expectedAuditLines);
|
|
1569
1687
|
const binding = continuation?.answer_body_binding;
|
|
1570
1688
|
const missingAnswerBody = Boolean(binding) && (binding?.character_count !== body.length || binding.body_digest !== sha256(body));
|
|
1571
1689
|
if (missingKnowledge || missingOwnerAudit || missingAnswerBody) {
|
|
@@ -1602,9 +1720,12 @@ async function finalizeEpisode(payload, env, knowledgeEventSink, expectedHostBin
|
|
|
1602
1720
|
] : [])
|
|
1603
1721
|
];
|
|
1604
1722
|
return {
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1723
|
+
output: {
|
|
1724
|
+
decision: 'block',
|
|
1725
|
+
block_kind: 'audit_repair',
|
|
1726
|
+
reason: `Brainbase judgment episodeを完了する前に${reasons.join('。その後')}。監査行の後に、元の回答本文をそのまま続けてください。`
|
|
1727
|
+
},
|
|
1728
|
+
wmCandidate: null
|
|
1608
1729
|
};
|
|
1609
1730
|
}
|
|
1610
1731
|
const finalWithoutDigest = {
|
|
@@ -1625,13 +1746,39 @@ async function finalizeEpisode(payload, env, knowledgeEventSink, expectedHostBin
|
|
|
1625
1746
|
final_digest: sha256(canonicalJson(finalWithoutDigest))
|
|
1626
1747
|
};
|
|
1627
1748
|
writeImmutableJson(paths.final, final);
|
|
1628
|
-
await enqueueFinalizedKnowledgeEvent(knowledgeEventSink, sessionRef, turnId, final, answer);
|
|
1629
|
-
return
|
|
1749
|
+
await enqueueFinalizedKnowledgeEvent(knowledgeEventSink, sessionRef, turnId, final, answer, projectCode);
|
|
1750
|
+
return {
|
|
1751
|
+
output: final,
|
|
1752
|
+
wmCandidate: {
|
|
1753
|
+
projectCode,
|
|
1754
|
+
userPrompt: episode.adoption.request.request,
|
|
1755
|
+
finalAnswer: body,
|
|
1756
|
+
priorReceiptsCount,
|
|
1757
|
+
ownerAuditComplete: final.owner_audit_complete === true
|
|
1758
|
+
}
|
|
1759
|
+
};
|
|
1630
1760
|
});
|
|
1761
|
+
// Strictly AFTER withTurnLock has released: fail-open PR-B session mini WM v2 enqueue.
|
|
1762
|
+
if (lockedResult.wmCandidate) {
|
|
1763
|
+
await enqueueSessionWorldModelUpdateFailOpen({
|
|
1764
|
+
env,
|
|
1765
|
+
options,
|
|
1766
|
+
sessionRef,
|
|
1767
|
+
turnId,
|
|
1768
|
+
candidate: lockedResult.wmCandidate
|
|
1769
|
+
});
|
|
1770
|
+
}
|
|
1771
|
+
return lockedResult.output;
|
|
1631
1772
|
}
|
|
1632
|
-
async function enqueueFinalizedKnowledgeEvent(sink, sessionRef, turnId, final, answer) {
|
|
1773
|
+
async function enqueueFinalizedKnowledgeEvent(sink, sessionRef, turnId, final, answer, projectCode) {
|
|
1633
1774
|
if (!sink)
|
|
1634
1775
|
return null;
|
|
1776
|
+
const hasExplicitProjectCode = typeof projectCode === 'string' && projectCode.trim().length > 0;
|
|
1777
|
+
const normalizedProjectCode = hasExplicitProjectCode
|
|
1778
|
+
? normalizeJudgmentEventProjectCode(projectCode)
|
|
1779
|
+
: undefined;
|
|
1780
|
+
if (hasExplicitProjectCode && !normalizedProjectCode)
|
|
1781
|
+
return null;
|
|
1635
1782
|
const event = toKnowledgeEventFromJudgmentEpisode({
|
|
1636
1783
|
episode_id: `${sessionRef}:${turnId}`,
|
|
1637
1784
|
session_id: sessionRef,
|
|
@@ -1639,7 +1786,8 @@ async function enqueueFinalizedKnowledgeEvent(sink, sessionRef, turnId, final, a
|
|
|
1639
1786
|
finalized_at: final.finalized_at,
|
|
1640
1787
|
answer_digest: final.answer_digest,
|
|
1641
1788
|
completion_status: 'complete',
|
|
1642
|
-
final_answer: answer
|
|
1789
|
+
final_answer: answer,
|
|
1790
|
+
...(normalizedProjectCode ? { project_code: normalizedProjectCode } : {})
|
|
1643
1791
|
});
|
|
1644
1792
|
if (event)
|
|
1645
1793
|
await sink.enqueue(event);
|
|
@@ -1659,7 +1807,7 @@ export async function processJudgmentHook(payload, options = {}) {
|
|
|
1659
1807
|
const autonomyBlock = await evaluateAutonomyStop(payload, env, options);
|
|
1660
1808
|
if (autonomyBlock)
|
|
1661
1809
|
return autonomyBlock;
|
|
1662
|
-
const output = await finalizeEpisode(payload, env, options
|
|
1810
|
+
const output = await finalizeEpisode(payload, env, options, expectedHostBinding);
|
|
1663
1811
|
if ('decision' in output && output.decision === 'block' && payload.stop_hook_active === true) {
|
|
1664
1812
|
throw new Error('judgment_stop_repair_exhausted');
|
|
1665
1813
|
}
|
|
@@ -17,11 +17,22 @@ export type JudgmentModelOutcomeVerdict = 'supports' | 'refutes' | 'inconclusive
|
|
|
17
17
|
export type JudgmentModelOutcomeEvidenceKind = 'artifact' | 'query' | 'document' | 'judgment';
|
|
18
18
|
export declare const JUDGMENT_MODEL_OUTCOME_ALTERNATIVES: readonly ["measurement_error", "execution_difference", "external_change"];
|
|
19
19
|
export type JudgmentModelOutcomeAlternative = typeof JUDGMENT_MODEL_OUTCOME_ALTERNATIVES[number];
|
|
20
|
+
export declare const JUDGMENT_MODEL_OUTCOME_CLAIM_TYPES: readonly ["universal", "tendency"];
|
|
21
|
+
export type JudgmentModelOutcomeClaimType = typeof JUDGMENT_MODEL_OUTCOME_CLAIM_TYPES[number];
|
|
22
|
+
export declare const JUDGMENT_MODEL_OUTCOME_REPRESENTATIVENESS: readonly ["census", "representative", "anecdotal", "unknown"];
|
|
23
|
+
export type JudgmentModelOutcomeRepresentativeness = typeof JUDGMENT_MODEL_OUTCOME_REPRESENTATIVENESS[number];
|
|
20
24
|
export interface JudgmentModelOutcomeEvidenceRef {
|
|
21
25
|
readonly kind: JudgmentModelOutcomeEvidenceKind;
|
|
22
26
|
readonly ref: string;
|
|
23
27
|
readonly label: string;
|
|
24
28
|
}
|
|
29
|
+
export interface JudgmentModelOutcomeScopeMetrics {
|
|
30
|
+
readonly claim_type: JudgmentModelOutcomeClaimType;
|
|
31
|
+
readonly sample_size?: number;
|
|
32
|
+
readonly population_size?: number;
|
|
33
|
+
readonly effect_magnitude?: string;
|
|
34
|
+
readonly representativeness: JudgmentModelOutcomeRepresentativeness;
|
|
35
|
+
}
|
|
25
36
|
export interface JudgmentModelOutcome {
|
|
26
37
|
readonly record_version: typeof JUDGMENT_MODEL_OUTCOME_RECORD_VERSION;
|
|
27
38
|
readonly model: {
|
|
@@ -41,6 +52,8 @@ export interface JudgmentModelOutcome {
|
|
|
41
52
|
readonly judgment_ref?: {
|
|
42
53
|
readonly frame_digest: `sha256:${string}`;
|
|
43
54
|
};
|
|
55
|
+
/** Optional scope and representativeness metrics to separate structural vs anecdotal refutations. */
|
|
56
|
+
readonly scope_metrics?: JudgmentModelOutcomeScopeMetrics;
|
|
44
57
|
}
|
|
45
58
|
/** A record as the host stored it: the outcome plus host-owned id, time, and content digest. */
|
|
46
59
|
export interface JudgmentModelOutcomeStoredRecord extends JudgmentModelOutcome {
|
|
@@ -50,10 +63,17 @@ export interface JudgmentModelOutcomeStoredRecord extends JudgmentModelOutcome {
|
|
|
50
63
|
}
|
|
51
64
|
export interface JudgmentModelOutcomeSummary {
|
|
52
65
|
readonly supports: number;
|
|
66
|
+
/** Total refutations (structural_refutes + anecdotal_refutes). */
|
|
53
67
|
readonly refutes: number;
|
|
68
|
+
/** Structural refutations (census/representative, universal claims, unknown representativeness, or legacy records without scope_metrics). */
|
|
69
|
+
readonly structural_refutes?: number;
|
|
70
|
+
/** Explicitly anecdotal refutations against a tendency claim (claim_type === 'tendency' and representativeness === 'anecdotal'). */
|
|
71
|
+
readonly anecdotal_refutes?: number;
|
|
54
72
|
readonly inconclusive: number;
|
|
55
|
-
/** Conditions of the most recent refutations, newest first. */
|
|
73
|
+
/** Conditions of the most recent structural refutations, newest first. */
|
|
56
74
|
readonly refuted_when: readonly string[];
|
|
75
|
+
/** Conditions of the most recent anecdotal refutations, newest first. */
|
|
76
|
+
readonly anecdotal_refuted_when?: readonly string[];
|
|
57
77
|
}
|
|
58
78
|
export type JudgmentModelOutcomeIssueCode = 'outcome_record_invalid' | 'outcome_catalog_mismatch' | 'outcome_model_unknown' | 'outcome_not_model' | 'outcome_revision_mismatch' | 'outcome_ruled_out_missing' | 'outcome_ruled_out_unexpected' | 'outcome_evidence_missing' | 'outcome_text_unsafe';
|
|
59
79
|
export interface JudgmentModelOutcomeIssue {
|
|
@@ -71,6 +91,14 @@ export type JudgmentModelOutcomeValidation = {
|
|
|
71
91
|
};
|
|
72
92
|
/** Digest of the outcome content. Host-owned id and time are not part of it. */
|
|
73
93
|
export declare function judgmentModelOutcomeDigest(outcome: JudgmentModelOutcome): `sha256:${string}`;
|
|
94
|
+
/**
|
|
95
|
+
* True only when a refutation explicitly declares `claim_type: 'tendency'` and
|
|
96
|
+
* `representativeness: 'anecdotal'`. Legacy records without `scope_metrics`,
|
|
97
|
+
* universal claims, census/representative refutations, and `unknown`
|
|
98
|
+
* representativeness stay on the conservative structural side so an unverified
|
|
99
|
+
* refutation cannot silently bypass `chosen_uses_refuted_model`.
|
|
100
|
+
*/
|
|
101
|
+
export declare function isAnecdotalRefutation(record: Pick<JudgmentModelOutcome, 'verdict' | 'scope_metrics'>): boolean;
|
|
74
102
|
/**
|
|
75
103
|
* Validate a new outcome against the catalog shown on this turn. The model
|
|
76
104
|
* must be a world model in the catalog, at its current revision.
|
|
@@ -14,13 +14,17 @@ import { createHash } from 'node:crypto';
|
|
|
14
14
|
*/
|
|
15
15
|
export const JUDGMENT_MODEL_OUTCOME_RECORD_VERSION = 'judgment-model-outcome.v1';
|
|
16
16
|
export const JUDGMENT_MODEL_OUTCOME_ALTERNATIVES = ['measurement_error', 'execution_difference', 'external_change'];
|
|
17
|
+
export const JUDGMENT_MODEL_OUTCOME_CLAIM_TYPES = ['universal', 'tendency'];
|
|
18
|
+
export const JUDGMENT_MODEL_OUTCOME_REPRESENTATIVENESS = ['census', 'representative', 'anecdotal', 'unknown'];
|
|
17
19
|
const VERDICTS = ['supports', 'refutes', 'inconclusive'];
|
|
18
20
|
const EVIDENCE_KINDS = ['artifact', 'query', 'document', 'judgment'];
|
|
21
|
+
const SCOPE_METRICS_KEYS = ['claim_type', 'sample_size', 'population_size', 'effect_magnitude', 'representativeness'];
|
|
19
22
|
const MAX_STATEMENT = 2_000;
|
|
20
23
|
const MAX_RULED_OUT = 1_000;
|
|
21
24
|
const MAX_EVIDENCE = 12;
|
|
22
25
|
const MAX_EVIDENCE_REF = 800;
|
|
23
26
|
const MAX_EVIDENCE_LABEL = 200;
|
|
27
|
+
const MAX_EFFECT_MAGNITUDE = 200;
|
|
24
28
|
const MAX_REFUTED_WHEN = 3;
|
|
25
29
|
const MAX_REFUTED_WHEN_TEXT = 120;
|
|
26
30
|
const DIGEST_PATTERN = /^sha256:[a-f0-9]{64}$/;
|
|
@@ -43,6 +47,15 @@ function clip(value, max) {
|
|
|
43
47
|
export function judgmentModelOutcomeDigest(outcome) {
|
|
44
48
|
return `sha256:${createHash('sha256').update(canonicalJson(outcomeContent(outcome)), 'utf8').digest('hex')}`;
|
|
45
49
|
}
|
|
50
|
+
function normalizeScopeMetrics(value) {
|
|
51
|
+
return {
|
|
52
|
+
claim_type: value.claim_type,
|
|
53
|
+
...(value.sample_size === undefined ? {} : { sample_size: value.sample_size }),
|
|
54
|
+
...(value.population_size === undefined ? {} : { population_size: value.population_size }),
|
|
55
|
+
...(value.effect_magnitude === undefined ? {} : { effect_magnitude: value.effect_magnitude }),
|
|
56
|
+
representativeness: value.representativeness,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
46
59
|
function outcomeContent(value) {
|
|
47
60
|
return {
|
|
48
61
|
record_version: value.record_version,
|
|
@@ -56,8 +69,21 @@ function outcomeContent(value) {
|
|
|
56
69
|
ruled_out: Object.fromEntries(JUDGMENT_MODEL_OUTCOME_ALTERNATIVES.map((key) => [key, value.ruled_out[key]])),
|
|
57
70
|
}),
|
|
58
71
|
...(value.judgment_ref === undefined ? {} : { judgment_ref: { frame_digest: value.judgment_ref.frame_digest } }),
|
|
72
|
+
...(value.scope_metrics === undefined ? {} : { scope_metrics: normalizeScopeMetrics(value.scope_metrics) }),
|
|
59
73
|
};
|
|
60
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* True only when a refutation explicitly declares `claim_type: 'tendency'` and
|
|
77
|
+
* `representativeness: 'anecdotal'`. Legacy records without `scope_metrics`,
|
|
78
|
+
* universal claims, census/representative refutations, and `unknown`
|
|
79
|
+
* representativeness stay on the conservative structural side so an unverified
|
|
80
|
+
* refutation cannot silently bypass `chosen_uses_refuted_model`.
|
|
81
|
+
*/
|
|
82
|
+
export function isAnecdotalRefutation(record) {
|
|
83
|
+
return record.verdict === 'refutes'
|
|
84
|
+
&& record.scope_metrics?.claim_type === 'tendency'
|
|
85
|
+
&& record.scope_metrics.representativeness === 'anecdotal';
|
|
86
|
+
}
|
|
61
87
|
function checkText(value, path, max, issue, unsafe) {
|
|
62
88
|
if (!nonEmpty(value, max)) {
|
|
63
89
|
issue('outcome_record_invalid', path, `${path} must be a non-empty string of at most ${max} characters`);
|
|
@@ -131,6 +157,43 @@ function checkOutcomeShape(value, issue, unsafe) {
|
|
|
131
157
|
issue('outcome_record_invalid', 'judgment_ref', 'judgment_ref needs only frame_digest as sha256');
|
|
132
158
|
}
|
|
133
159
|
}
|
|
160
|
+
if (value.scope_metrics !== undefined) {
|
|
161
|
+
const metrics = isRecord(value.scope_metrics) ? value.scope_metrics : null;
|
|
162
|
+
if (!metrics) {
|
|
163
|
+
issue('outcome_record_invalid', 'scope_metrics', 'scope_metrics must be an object');
|
|
164
|
+
}
|
|
165
|
+
else {
|
|
166
|
+
for (const key of Object.keys(metrics)) {
|
|
167
|
+
if (!SCOPE_METRICS_KEYS.includes(key)) {
|
|
168
|
+
issue('outcome_record_invalid', `scope_metrics.${key}`, 'scope_metrics contains an unknown field');
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (!JUDGMENT_MODEL_OUTCOME_CLAIM_TYPES.includes(metrics.claim_type)) {
|
|
172
|
+
issue('outcome_record_invalid', 'scope_metrics.claim_type', 'scope_metrics.claim_type must be universal or tendency');
|
|
173
|
+
}
|
|
174
|
+
if (!JUDGMENT_MODEL_OUTCOME_REPRESENTATIVENESS.includes(metrics.representativeness)) {
|
|
175
|
+
issue('outcome_record_invalid', 'scope_metrics.representativeness', 'scope_metrics.representativeness must be census, representative, anecdotal, or unknown');
|
|
176
|
+
}
|
|
177
|
+
const validSampleSize = metrics.sample_size === undefined
|
|
178
|
+
|| (typeof metrics.sample_size === 'number' && Number.isInteger(metrics.sample_size) && metrics.sample_size >= 1);
|
|
179
|
+
if (!validSampleSize) {
|
|
180
|
+
issue('outcome_record_invalid', 'scope_metrics.sample_size', 'scope_metrics.sample_size must be a positive integer');
|
|
181
|
+
}
|
|
182
|
+
const validPopulationSize = metrics.population_size === undefined
|
|
183
|
+
|| (typeof metrics.population_size === 'number' && Number.isInteger(metrics.population_size) && metrics.population_size >= 1);
|
|
184
|
+
if (!validPopulationSize) {
|
|
185
|
+
issue('outcome_record_invalid', 'scope_metrics.population_size', 'scope_metrics.population_size must be a positive integer');
|
|
186
|
+
}
|
|
187
|
+
if (validSampleSize && validPopulationSize
|
|
188
|
+
&& typeof metrics.sample_size === 'number' && typeof metrics.population_size === 'number'
|
|
189
|
+
&& metrics.sample_size > metrics.population_size) {
|
|
190
|
+
issue('outcome_record_invalid', 'scope_metrics.sample_size', 'scope_metrics.sample_size cannot exceed scope_metrics.population_size');
|
|
191
|
+
}
|
|
192
|
+
if (metrics.effect_magnitude !== undefined) {
|
|
193
|
+
checkText(metrics.effect_magnitude, 'scope_metrics.effect_magnitude', MAX_EFFECT_MAGNITUDE, issue, unsafe);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
134
197
|
}
|
|
135
198
|
/**
|
|
136
199
|
* Validate a new outcome against the catalog shown on this turn. The model
|
|
@@ -205,11 +268,16 @@ export function summarizeJudgmentModelOutcomes(records, catalog) {
|
|
|
205
268
|
const refutations = group
|
|
206
269
|
.filter((record) => record.verdict === 'refutes')
|
|
207
270
|
.sort((left, right) => Date.parse(right.recorded_at) - Date.parse(left.recorded_at) || right.id.localeCompare(left.id));
|
|
271
|
+
const structuralRefutations = refutations.filter((record) => !isAnecdotalRefutation(record));
|
|
272
|
+
const anecdotalRefutations = refutations.filter((record) => isAnecdotalRefutation(record));
|
|
208
273
|
summaries.set(id, {
|
|
209
274
|
supports: group.filter((record) => record.verdict === 'supports').length,
|
|
210
275
|
refutes: refutations.length,
|
|
276
|
+
structural_refutes: structuralRefutations.length,
|
|
277
|
+
anecdotal_refutes: anecdotalRefutations.length,
|
|
211
278
|
inconclusive: group.filter((record) => record.verdict === 'inconclusive').length,
|
|
212
|
-
refuted_when:
|
|
279
|
+
refuted_when: structuralRefutations.slice(0, MAX_REFUTED_WHEN).map((record) => clip(record.conditions, MAX_REFUTED_WHEN_TEXT)),
|
|
280
|
+
anecdotal_refuted_when: anecdotalRefutations.slice(0, MAX_REFUTED_WHEN).map((record) => clip(record.conditions, MAX_REFUTED_WHEN_TEXT)),
|
|
213
281
|
});
|
|
214
282
|
}
|
|
215
283
|
return summaries;
|