@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.
- 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
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RFC-001 v2.0 PR-B: Lightweight 2-Layer Ephemeral Session Mini World Model v2.
|
|
3
|
+
*
|
|
4
|
+
* - Schema & rendering (`renderSessionMiniWorldModelPinV2`, <= 850 Unicode code points,
|
|
5
|
+
* `invariant_constraints` protected last, valid JSON arrays, intact footer,
|
|
6
|
+
* credential & audit-prefix filtering).
|
|
7
|
+
* - Atomic session-scoped journal persistence (`journalRoot/<sessionRef>/session-world-model.json`)
|
|
8
|
+
* protected by a dedicated lock (`journalRoot/<sessionRef>/.session-world-model.lock`),
|
|
9
|
+
* strict monotonic `turn_sequence` guard, `0o600` tmp + `fsyncSync` + `renameSync`,
|
|
10
|
+
* and fail-open reading.
|
|
11
|
+
* - PR #1044 upstream evidence draft adapter (`toLearningCandidateEvidenceDraftFromSessionWMV2`),
|
|
12
|
+
* producing a human-authorization-gated evidence draft only (never writes to Graph or auto-adopts).
|
|
13
|
+
*/
|
|
14
|
+
import { randomUUID } from 'node:crypto';
|
|
15
|
+
import { closeSync, constants as fsConstants, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
16
|
+
import { dirname, join } from 'node:path';
|
|
17
|
+
import { containsJudgmentFrameCredential } from './judgment-frame.js';
|
|
18
|
+
import { AUDIT_LINE_STRIP_PREFIX } from './judgment-reasoning-gate-prompt.js';
|
|
19
|
+
export const SESSION_MINI_WORLD_MODEL_SCHEMA_VERSION_V2 = 'brainbase-session-mini-world-model.v2';
|
|
20
|
+
export const SESSION_WORLD_MODEL_FILENAME = 'session-world-model.json';
|
|
21
|
+
export const SESSION_WORLD_MODEL_LOCK_FILENAME = '.session-world-model.lock';
|
|
22
|
+
export const DEFAULT_SESSION_WORLD_MODEL_UPDATE_TIMEOUT_MS = 1500;
|
|
23
|
+
export const WM_V2_LIMITS = {
|
|
24
|
+
MAX_INVARIANT_ITEMS: 3,
|
|
25
|
+
MAX_INVARIANT_CHARS: 50,
|
|
26
|
+
MAX_SUPERSEDED_ITEMS: 2,
|
|
27
|
+
MAX_SUPERSEDED_CHARS: 60,
|
|
28
|
+
MAX_PIN_ITEMS: 4,
|
|
29
|
+
MAX_ITEM_CHARS: 60,
|
|
30
|
+
MAX_THESIS_CHARS: 100,
|
|
31
|
+
MAX_PIN_TOTAL_CHARS: 850,
|
|
32
|
+
};
|
|
33
|
+
const SAFE_SESSION_REF = /^[^/\\\u0000-\u001f\u007f]+$/u;
|
|
34
|
+
const MAX_SESSION_WORLD_MODEL_FILE_BYTES = 256 * 1024;
|
|
35
|
+
const DEFAULT_LOCK_MAX_ATTEMPTS = 100;
|
|
36
|
+
const DEFAULT_LOCK_RETRY_DELAY_MS = 10;
|
|
37
|
+
function isPlainRecord(value) {
|
|
38
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
39
|
+
}
|
|
40
|
+
function isStringArray(value) {
|
|
41
|
+
return Array.isArray(value) && value.every((item) => typeof item === 'string');
|
|
42
|
+
}
|
|
43
|
+
function isSafeSessionRef(sessionRef) {
|
|
44
|
+
return (typeof sessionRef === 'string'
|
|
45
|
+
&& sessionRef.length > 0
|
|
46
|
+
&& sessionRef.length <= 512
|
|
47
|
+
&& sessionRef !== '.'
|
|
48
|
+
&& sessionRef !== '..'
|
|
49
|
+
&& SAFE_SESSION_REF.test(sessionRef));
|
|
50
|
+
}
|
|
51
|
+
export function sessionWorldModelPaths(journalRootDir, sessionRef) {
|
|
52
|
+
if (!isSafeSessionRef(sessionRef)) {
|
|
53
|
+
throw new Error('session_world_model_invalid_session_ref');
|
|
54
|
+
}
|
|
55
|
+
const directory = join(journalRootDir, sessionRef);
|
|
56
|
+
return {
|
|
57
|
+
directory,
|
|
58
|
+
filePath: join(directory, SESSION_WORLD_MODEL_FILENAME),
|
|
59
|
+
lockPath: join(directory, SESSION_WORLD_MODEL_LOCK_FILENAME),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Validates and normalizes an untrusted JSON payload into `SessionMiniWorldModelV2`.
|
|
64
|
+
* Returns `null` if the payload does not match the v2 schema.
|
|
65
|
+
*/
|
|
66
|
+
export function parseSessionMiniWorldModelV2(value) {
|
|
67
|
+
if (!isPlainRecord(value))
|
|
68
|
+
return null;
|
|
69
|
+
if (value.schema_version !== SESSION_MINI_WORLD_MODEL_SCHEMA_VERSION_V2)
|
|
70
|
+
return null;
|
|
71
|
+
if (typeof value.session_ref !== 'string' || !isSafeSessionRef(value.session_ref))
|
|
72
|
+
return null;
|
|
73
|
+
if (typeof value.turn_sequence !== 'number'
|
|
74
|
+
|| !Number.isSafeInteger(value.turn_sequence)
|
|
75
|
+
|| value.turn_sequence < 1) {
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
if (typeof value.updated_after_turn_id !== 'string' || value.updated_after_turn_id.trim().length === 0) {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
if (typeof value.updated_at !== 'string' || value.updated_at.trim().length === 0)
|
|
82
|
+
return null;
|
|
83
|
+
if (typeof value.steelman_thesis !== 'string')
|
|
84
|
+
return null;
|
|
85
|
+
if (!isStringArray(value.invariant_constraints)
|
|
86
|
+
|| !isStringArray(value.superseded_edges)
|
|
87
|
+
|| !isStringArray(value.confirmed_edges)
|
|
88
|
+
|| !isStringArray(value.open_edges)
|
|
89
|
+
|| !isStringArray(value.separated_normative_questions)
|
|
90
|
+
|| !isStringArray(value.rejected_false_premises)) {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
if (value.referenced_refutation_ids !== undefined && !isStringArray(value.referenced_refutation_ids)) {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
if (value.referenced_eval_ids !== undefined && !isStringArray(value.referenced_eval_ids)) {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
schema_version: SESSION_MINI_WORLD_MODEL_SCHEMA_VERSION_V2,
|
|
101
|
+
session_ref: value.session_ref,
|
|
102
|
+
turn_sequence: value.turn_sequence,
|
|
103
|
+
updated_after_turn_id: value.updated_after_turn_id,
|
|
104
|
+
updated_at: value.updated_at,
|
|
105
|
+
steelman_thesis: value.steelman_thesis,
|
|
106
|
+
invariant_constraints: [...value.invariant_constraints],
|
|
107
|
+
superseded_edges: [...value.superseded_edges],
|
|
108
|
+
confirmed_edges: [...value.confirmed_edges],
|
|
109
|
+
open_edges: [...value.open_edges],
|
|
110
|
+
separated_normative_questions: [...value.separated_normative_questions],
|
|
111
|
+
rejected_false_premises: [...value.rejected_false_premises],
|
|
112
|
+
...(value.referenced_refutation_ids !== undefined
|
|
113
|
+
? { referenced_refutation_ids: [...value.referenced_refutation_ids] }
|
|
114
|
+
: {}),
|
|
115
|
+
...(value.referenced_eval_ids !== undefined
|
|
116
|
+
? { referenced_eval_ids: [...value.referenced_eval_ids] }
|
|
117
|
+
: {}),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Fail-open reader for `journalRoot/<sessionRef>/session-world-model.json`.
|
|
122
|
+
* Never throws on ENOENT, corrupted JSON, schema mismatch, symlink, or IO error.
|
|
123
|
+
*/
|
|
124
|
+
export function readSessionMiniWorldModelV2(journalRootDir, sessionRef) {
|
|
125
|
+
try {
|
|
126
|
+
const { filePath } = sessionWorldModelPaths(journalRootDir, sessionRef);
|
|
127
|
+
const stats = lstatSync(filePath);
|
|
128
|
+
if (stats.isSymbolicLink() || !stats.isFile() || stats.size > MAX_SESSION_WORLD_MODEL_FILE_BYTES) {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
const parsed = JSON.parse(readFileSync(filePath, 'utf8'));
|
|
132
|
+
const state = parseSessionMiniWorldModelV2(parsed);
|
|
133
|
+
if (!state || state.session_ref !== sessionRef)
|
|
134
|
+
return null;
|
|
135
|
+
return state;
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Dedicated session-world-model file lock (independent of per-turn `.lock`).
|
|
143
|
+
*/
|
|
144
|
+
export async function withSessionWorldModelLock(lockPath, operation, options = {}) {
|
|
145
|
+
const maxAttempts = Math.max(1, options.maxAttempts ?? DEFAULT_LOCK_MAX_ATTEMPTS);
|
|
146
|
+
const retryDelayMs = Math.max(1, options.retryDelayMs ?? DEFAULT_LOCK_RETRY_DELAY_MS);
|
|
147
|
+
mkdirSync(dirname(lockPath), { recursive: true, mode: 0o700 });
|
|
148
|
+
let descriptor = null;
|
|
149
|
+
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
|
150
|
+
try {
|
|
151
|
+
descriptor = openSync(lockPath, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
|
|
152
|
+
writeFileSync(descriptor, `${process.pid}\n`);
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
if (!(error instanceof Error && 'code' in error && error.code === 'EEXIST'))
|
|
157
|
+
throw error;
|
|
158
|
+
if (attempt + 1 < maxAttempts) {
|
|
159
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, retryDelayMs));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (descriptor === null)
|
|
164
|
+
throw new Error('session_world_model_lock_timeout');
|
|
165
|
+
let operationError;
|
|
166
|
+
try {
|
|
167
|
+
return await operation();
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
operationError = error;
|
|
171
|
+
throw error;
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
let releaseError;
|
|
175
|
+
try {
|
|
176
|
+
closeSync(descriptor);
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
releaseError = error;
|
|
180
|
+
}
|
|
181
|
+
try {
|
|
182
|
+
unlinkSync(lockPath);
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
releaseError ??= error;
|
|
186
|
+
}
|
|
187
|
+
if (releaseError && operationError === undefined) {
|
|
188
|
+
throw new Error('session_world_model_lock_release_failed', { cause: releaseError });
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Atomically persists a v2 session mini world model under the dedicated lock
|
|
194
|
+
* `journalRoot/<sessionRef>/.session-world-model.lock`.
|
|
195
|
+
*
|
|
196
|
+
* Enforces strict monotonic `turn_sequence`: rejects/skips any write where
|
|
197
|
+
* `existing.turn_sequence >= incoming.turn_sequence` to prevent out-of-order
|
|
198
|
+
* async Stop overwrites. Writes via temp file (`0o600`) + `fsyncSync` + `renameSync`.
|
|
199
|
+
*/
|
|
200
|
+
export async function writeSessionMiniWorldModelV2(journalRootDir, sessionRef, incoming, options = {}) {
|
|
201
|
+
const validated = parseSessionMiniWorldModelV2(incoming);
|
|
202
|
+
if (!validated) {
|
|
203
|
+
return { written: false, reason: 'invalid_state' };
|
|
204
|
+
}
|
|
205
|
+
if (!isSafeSessionRef(sessionRef) || validated.session_ref !== sessionRef) {
|
|
206
|
+
return { written: false, reason: 'session_ref_mismatch' };
|
|
207
|
+
}
|
|
208
|
+
const { directory, filePath, lockPath } = sessionWorldModelPaths(journalRootDir, sessionRef);
|
|
209
|
+
return withSessionWorldModelLock(lockPath, () => {
|
|
210
|
+
const existing = readSessionMiniWorldModelV2(journalRootDir, sessionRef);
|
|
211
|
+
if (existing !== null && existing.turn_sequence >= validated.turn_sequence) {
|
|
212
|
+
return { written: false, reason: 'stale_turn_sequence' };
|
|
213
|
+
}
|
|
214
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
215
|
+
const tempPath = join(directory, `.${SESSION_WORLD_MODEL_FILENAME}.${process.pid}.${randomUUID()}.tmp`);
|
|
216
|
+
let descriptor = null;
|
|
217
|
+
let renamed = false;
|
|
218
|
+
try {
|
|
219
|
+
descriptor = openSync(tempPath, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
|
|
220
|
+
writeFileSync(descriptor, `${JSON.stringify(validated)}\n`);
|
|
221
|
+
fsyncSync(descriptor);
|
|
222
|
+
closeSync(descriptor);
|
|
223
|
+
descriptor = null;
|
|
224
|
+
renameSync(tempPath, filePath);
|
|
225
|
+
renamed = true;
|
|
226
|
+
}
|
|
227
|
+
finally {
|
|
228
|
+
if (descriptor !== null) {
|
|
229
|
+
try {
|
|
230
|
+
closeSync(descriptor);
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
// Preserve the primary write error.
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (!renamed) {
|
|
237
|
+
try {
|
|
238
|
+
unlinkSync(tempPath);
|
|
239
|
+
}
|
|
240
|
+
catch {
|
|
241
|
+
// Best-effort temp cleanup.
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return { written: true, state: validated };
|
|
246
|
+
}, {
|
|
247
|
+
maxAttempts: options.lockMaxAttempts,
|
|
248
|
+
retryDelayMs: options.lockRetryDelayMs,
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
function clipText(value, maxChars) {
|
|
252
|
+
const cleaned = value.replace(/[\u0000-\u001f\u007f-\u009f]/gu, ' ').trim();
|
|
253
|
+
const chars = [...cleaned];
|
|
254
|
+
return chars.length <= maxChars ? cleaned : `${chars.slice(0, Math.max(1, maxChars - 1)).join('')}…`;
|
|
255
|
+
}
|
|
256
|
+
function sanitizeSafeItems(items, containsCredential, maxItems, maxChars) {
|
|
257
|
+
if (!items)
|
|
258
|
+
return [];
|
|
259
|
+
const out = [];
|
|
260
|
+
const seen = new Set();
|
|
261
|
+
for (const raw of items) {
|
|
262
|
+
if (typeof raw !== 'string')
|
|
263
|
+
continue;
|
|
264
|
+
if (containsCredential(raw))
|
|
265
|
+
continue;
|
|
266
|
+
const clipped = clipText(raw, maxChars);
|
|
267
|
+
if (!clipped || containsCredential(clipped) || AUDIT_LINE_STRIP_PREFIX.test(clipped))
|
|
268
|
+
continue;
|
|
269
|
+
if (seen.has(clipped))
|
|
270
|
+
continue;
|
|
271
|
+
seen.add(clipped);
|
|
272
|
+
out.push(clipped);
|
|
273
|
+
if (out.length >= maxItems)
|
|
274
|
+
break;
|
|
275
|
+
}
|
|
276
|
+
return out;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Render an ephemeral 2-layer session mini world model for `UserPromptSubmit` `additionalContext`.
|
|
280
|
+
* Reserves header & footer budget first, then trims elements in reverse priority order:
|
|
281
|
+
* normative -> open -> rejected -> superseded -> confirmed -> thesis -> invariant (protected LAST).
|
|
282
|
+
* Guarantees valid JSON arrays, intact footer, credential filtering, and total length <= 850 code points.
|
|
283
|
+
* Returns `null` when all fields are empty after sanitization.
|
|
284
|
+
*/
|
|
285
|
+
export function renderSessionMiniWorldModelPinV2(state, containsCredential = containsJudgmentFrameCredential) {
|
|
286
|
+
const rawThesis = typeof state.steelman_thesis === 'string' ? state.steelman_thesis : '';
|
|
287
|
+
const thesisRaw = containsCredential(rawThesis)
|
|
288
|
+
? ''
|
|
289
|
+
: clipText(rawThesis, WM_V2_LIMITS.MAX_THESIS_CHARS);
|
|
290
|
+
const thesis = thesisRaw && !containsCredential(thesisRaw) && !AUDIT_LINE_STRIP_PREFIX.test(thesisRaw)
|
|
291
|
+
? thesisRaw
|
|
292
|
+
: '';
|
|
293
|
+
const invariant = sanitizeSafeItems(state.invariant_constraints, containsCredential, WM_V2_LIMITS.MAX_INVARIANT_ITEMS, WM_V2_LIMITS.MAX_INVARIANT_CHARS);
|
|
294
|
+
const superseded = sanitizeSafeItems(state.superseded_edges, containsCredential, WM_V2_LIMITS.MAX_SUPERSEDED_ITEMS, WM_V2_LIMITS.MAX_SUPERSEDED_CHARS);
|
|
295
|
+
const confirmed = sanitizeSafeItems(state.confirmed_edges, containsCredential, WM_V2_LIMITS.MAX_PIN_ITEMS, WM_V2_LIMITS.MAX_ITEM_CHARS);
|
|
296
|
+
const open = sanitizeSafeItems(state.open_edges, containsCredential, WM_V2_LIMITS.MAX_PIN_ITEMS, WM_V2_LIMITS.MAX_ITEM_CHARS);
|
|
297
|
+
const normative = sanitizeSafeItems(state.separated_normative_questions, containsCredential, WM_V2_LIMITS.MAX_PIN_ITEMS, WM_V2_LIMITS.MAX_ITEM_CHARS);
|
|
298
|
+
const rejected = sanitizeSafeItems(state.rejected_false_premises, containsCredential, WM_V2_LIMITS.MAX_PIN_ITEMS, WM_V2_LIMITS.MAX_ITEM_CHARS);
|
|
299
|
+
if (!thesis
|
|
300
|
+
&& invariant.length === 0
|
|
301
|
+
&& superseded.length === 0
|
|
302
|
+
&& confirmed.length === 0
|
|
303
|
+
&& open.length === 0
|
|
304
|
+
&& normative.length === 0
|
|
305
|
+
&& rejected.length === 0) {
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
const header = '[Session Mini World Model v2(不変制約保護・作業前提ピン留め・巻き戻し禁止)]';
|
|
309
|
+
const footer = '※ invariant_constraints は厳守し、confirmed_edges / superseded_edges / rejected_false_premises を巻き戻さず、反証ID(ref-等)・評価ID(eval-等)と具体数値を明示引用して open_edges との差分だけ前へ進めること。';
|
|
310
|
+
let t = thesis;
|
|
311
|
+
const buckets = {
|
|
312
|
+
invariant: [...invariant],
|
|
313
|
+
confirmed: [...confirmed],
|
|
314
|
+
superseded: [...superseded],
|
|
315
|
+
rejected: [...rejected],
|
|
316
|
+
open: [...open],
|
|
317
|
+
normative: [...normative],
|
|
318
|
+
};
|
|
319
|
+
const build = () => [
|
|
320
|
+
header,
|
|
321
|
+
...(t ? [`- Steelman 幹: ${t}`] : []),
|
|
322
|
+
`- invariant_constraints: ${JSON.stringify(buckets.invariant)}`,
|
|
323
|
+
`- confirmed_edges: ${JSON.stringify(buckets.confirmed)}`,
|
|
324
|
+
...(buckets.superseded.length > 0 ? [`- superseded_edges: ${JSON.stringify(buckets.superseded)}`] : []),
|
|
325
|
+
`- open_edges: ${JSON.stringify(buckets.open)}`,
|
|
326
|
+
...(buckets.normative.length > 0 ? [`- separated_normative: ${JSON.stringify(buckets.normative)}`] : []),
|
|
327
|
+
`- rejected_false_premises: ${JSON.stringify(buckets.rejected)}`,
|
|
328
|
+
footer,
|
|
329
|
+
].join('\n');
|
|
330
|
+
const preThesisTrimOrder = [
|
|
331
|
+
'normative',
|
|
332
|
+
'open',
|
|
333
|
+
'rejected',
|
|
334
|
+
'superseded',
|
|
335
|
+
'confirmed',
|
|
336
|
+
];
|
|
337
|
+
while ([...build()].length > WM_V2_LIMITS.MAX_PIN_TOTAL_CHARS) {
|
|
338
|
+
let trimmed = false;
|
|
339
|
+
for (const key of preThesisTrimOrder) {
|
|
340
|
+
if (buckets[key].length > 0) {
|
|
341
|
+
buckets[key].pop();
|
|
342
|
+
trimmed = true;
|
|
343
|
+
break;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if (!trimmed) {
|
|
347
|
+
const thesisCodePoints = [...t];
|
|
348
|
+
if (thesisCodePoints.length > 0) {
|
|
349
|
+
t = thesisCodePoints.length > 20 ? clipText(t, Math.floor(thesisCodePoints.length / 2)) : '';
|
|
350
|
+
}
|
|
351
|
+
else if (buckets.invariant.length > 0) {
|
|
352
|
+
// Last resort only if invariant items themselves exceed the entire 850-char budget.
|
|
353
|
+
buckets.invariant.pop();
|
|
354
|
+
}
|
|
355
|
+
else {
|
|
356
|
+
break;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return build();
|
|
361
|
+
}
|
|
362
|
+
function sanitizeIds(ids, containsCredential) {
|
|
363
|
+
if (!ids)
|
|
364
|
+
return [];
|
|
365
|
+
return [
|
|
366
|
+
...new Set(ids
|
|
367
|
+
.filter((id) => typeof id === 'string')
|
|
368
|
+
.map((id) => id.trim())
|
|
369
|
+
.filter((id) => id.length > 0 && !containsCredential(id))),
|
|
370
|
+
];
|
|
371
|
+
}
|
|
372
|
+
export function toLearningCandidateEvidenceDraftFromSessionWMV2(state, options) {
|
|
373
|
+
const containsCredential = options.containsCredential ?? containsJudgmentFrameCredential;
|
|
374
|
+
const grounds = sanitizeSafeItems([
|
|
375
|
+
...state.invariant_constraints,
|
|
376
|
+
...state.confirmed_edges,
|
|
377
|
+
...state.superseded_edges,
|
|
378
|
+
], containsCredential, 24, 400);
|
|
379
|
+
const uncertainty = sanitizeSafeItems(state.open_edges, containsCredential, 16, 400);
|
|
380
|
+
const missing = [];
|
|
381
|
+
if (grounds.length === 0)
|
|
382
|
+
missing.push('grounds');
|
|
383
|
+
if (uncertainty.length === 0)
|
|
384
|
+
missing.push('uncertainty');
|
|
385
|
+
if (missing.length > 0) {
|
|
386
|
+
return { ok: false, missing_required_fields: missing };
|
|
387
|
+
}
|
|
388
|
+
const counterexamples = sanitizeSafeItems([...(options.observedCounterexamples ?? []), ...state.rejected_false_premises], containsCredential, 16, 400);
|
|
389
|
+
const addressedRefutationIds = sanitizeIds(state.referenced_refutation_ids, containsCredential);
|
|
390
|
+
const addressedEvalIds = sanitizeIds(state.referenced_eval_ids, containsCredential);
|
|
391
|
+
const competingModels = (options.competingModels ?? []).filter((m) => !containsCredential(m.hypothesis)
|
|
392
|
+
&& !containsCredential(m.comparison)
|
|
393
|
+
&& (!m.ref || !containsCredential(m.ref)));
|
|
394
|
+
return {
|
|
395
|
+
ok: true,
|
|
396
|
+
draft: {
|
|
397
|
+
proposedChangeNote: containsCredential(options.proposedChangeNote)
|
|
398
|
+
? ''
|
|
399
|
+
: options.proposedChangeNote.trim(),
|
|
400
|
+
grounds,
|
|
401
|
+
counterexamples,
|
|
402
|
+
uncertainty,
|
|
403
|
+
...(addressedRefutationIds.length > 0 ? { addressedRefutationIds } : {}),
|
|
404
|
+
...(addressedEvalIds.length > 0 ? { addressedEvalIds } : {}),
|
|
405
|
+
...(competingModels.length > 0 ? { competingModels } : {}),
|
|
406
|
+
},
|
|
407
|
+
};
|
|
408
|
+
}
|
|
@@ -121,6 +121,7 @@ export function assertPortableGraphBundle(bundle) {
|
|
|
121
121
|
validatePortableGraph(bundle);
|
|
122
122
|
}
|
|
123
123
|
function parseGraphRetrievalResponse(value) {
|
|
124
|
+
const validOptionalCount = (candidate) => (candidate === undefined || (typeof candidate === 'number' && Number.isInteger(candidate) && candidate >= 0));
|
|
124
125
|
if (!isRecord(value)
|
|
125
126
|
|| (value.graphVersion !== 1 && value.graphVersion !== 2)
|
|
126
127
|
|| (value.schemaVersion !== 1 && value.schemaVersion !== 2)
|
|
@@ -135,6 +136,8 @@ function parseGraphRetrievalResponse(value) {
|
|
|
135
136
|
|| !['semantic', 'lexical', 'seed'].includes(String(value.semantic.method))
|
|
136
137
|
|| !Array.isArray(value.candidates)
|
|
137
138
|
|| !Array.isArray(value.results)
|
|
139
|
+
|| !validOptionalCount(value.totalScopedCount)
|
|
140
|
+
|| !validOptionalCount(value.returnedCount)
|
|
138
141
|
|| !Array.isArray(value.observedRelations)
|
|
139
142
|
|| !Array.isArray(value.observedRelationCatalog)
|
|
140
143
|
|| !isRecord(value.traversal)
|
|
@@ -154,7 +157,12 @@ function parseGraphRetrievalResponse(value) {
|
|
|
154
157
|
// This route searches only the token owner's own snapshot (the owner-private
|
|
155
158
|
// area), never the organization's shared Graph. A service from before the
|
|
156
159
|
// owner_private label answered organization_graph for the same area.
|
|
157
|
-
|
|
160
|
+
// Older services that omit totalScopedCount/returnedCount leave them
|
|
161
|
+
// undefined rather than fabricating a denominator from returned results.
|
|
162
|
+
return {
|
|
163
|
+
...value,
|
|
164
|
+
authority: 'owner_private',
|
|
165
|
+
};
|
|
158
166
|
}
|
|
159
167
|
function parseImportResult(value) {
|
|
160
168
|
if (!isRecord(value)
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { JudgmentJournalTurnInput } from './judgment-journal-turn-publisher.js';
|
|
2
|
+
import type { ReasoningGateMode } from './judgment-reasoning-gate-prompt.js';
|
|
3
|
+
import type { SessionWorldModelUpdaterV2 } from './judgment-session-world-model.js';
|
|
2
4
|
/** Minimal identity verified by the consuming host's authentication boundary. */
|
|
3
5
|
export interface RemoteJudgmentHookPrincipal {
|
|
4
6
|
personId: string;
|
|
@@ -12,12 +14,15 @@ export interface RemoteJudgmentHookDispatchResult {
|
|
|
12
14
|
output: Record<string, unknown>;
|
|
13
15
|
receiptId?: string;
|
|
14
16
|
routeResolutionSha256?: string;
|
|
17
|
+
/** Optional non-digest reasoning gate telemetry surfaced by the Host dispatcher. */
|
|
18
|
+
reasoningGateApplied?: boolean;
|
|
19
|
+
reasoningGateMode?: ReasoningGateMode;
|
|
15
20
|
}
|
|
16
21
|
/**
|
|
17
|
-
* `remote`: a remote runtime. `claude-code`:
|
|
18
|
-
* the owner's loopback bridge or authenticated with a person's hosted JWT.
|
|
22
|
+
* `remote`: a remote runtime. `claude-code` / `antigravity`: interactive CLI
|
|
23
|
+
* hosts on the owner's loopback bridge or authenticated with a person's hosted JWT.
|
|
19
24
|
*/
|
|
20
|
-
export type RemoteJudgmentHookHost = 'remote' | 'claude-code';
|
|
25
|
+
export type RemoteJudgmentHookHost = 'remote' | 'claude-code' | 'antigravity';
|
|
21
26
|
/**
|
|
22
27
|
* Authentication context verified by the Host before it reaches the hook
|
|
23
28
|
* dispatcher. A shared bearer intentionally has no trusted principal or
|
|
@@ -39,6 +44,8 @@ export interface RemoteJudgmentHookDispatchOptions {
|
|
|
39
44
|
trustedAuthKind?: RemoteJudgmentHookAuthKind;
|
|
40
45
|
/** Raw encoded Company Authority response verified by the canonical API. */
|
|
41
46
|
companyAuthorityResponse?: string;
|
|
47
|
+
/** Optional PR-B ephemeral session mini world model v2 updater forwarded to the Host. */
|
|
48
|
+
sessionWorldModelUpdater?: SessionWorldModelUpdaterV2;
|
|
42
49
|
}
|
|
43
50
|
export type RemoteJudgmentHookDispatch = (payload: Record<string, unknown>, projectCode: string | undefined, options: RemoteJudgmentHookDispatchOptions) => Promise<RemoteJudgmentHookDispatchResult>;
|
|
44
51
|
export interface RemoteJudgmentHookRequest {
|
|
@@ -62,10 +69,36 @@ export interface RemoteJudgmentHookRequest {
|
|
|
62
69
|
localClaudeCodeAllowed?: boolean;
|
|
63
70
|
/** True only for a person authenticated by the hosted MCP's JWT boundary. */
|
|
64
71
|
personHostedClaudeCodeAllowed?: boolean;
|
|
72
|
+
/**
|
|
73
|
+
* The x-brainbase-repository header of a person-hosted Claude Code turn.
|
|
74
|
+
* Caller-declared, so it is only a lookup key for `resolveProjectCode`;
|
|
75
|
+
* the resolved project must still be inside the verified principal scope.
|
|
76
|
+
*/
|
|
77
|
+
repository?: string;
|
|
78
|
+
/**
|
|
79
|
+
* Host-owned repository-to-project mapping, consulted only when a
|
|
80
|
+
* person-hosted Claude Code turn sent no project code. Return undefined
|
|
81
|
+
* when the host has no mapping for the repository.
|
|
82
|
+
*/
|
|
83
|
+
resolveProjectCode?: (input: {
|
|
84
|
+
repository: string;
|
|
85
|
+
principal: RemoteJudgmentHookPrincipal;
|
|
86
|
+
}) => Promise<string | undefined> | string | undefined;
|
|
65
87
|
isAuthorized: (authorization: string | undefined, expectedToken: string) => boolean;
|
|
66
88
|
dispatch: RemoteJudgmentHookDispatch;
|
|
67
89
|
/** Optional HTTP publisher for person-authenticated hosted Claude Code Stop events. */
|
|
68
90
|
journalTurnPublisher?: (input: JudgmentJournalTurnInput) => Promise<void>;
|
|
91
|
+
/** Optional PR-B ephemeral session mini world model v2 updater forwarded to dispatch. */
|
|
92
|
+
sessionWorldModelUpdater?: SessionWorldModelUpdaterV2;
|
|
93
|
+
/** Optional non-digest reasoning gate telemetry observer (fail-open). */
|
|
94
|
+
onReasoningGateTelemetry?: (details: {
|
|
95
|
+
eventName: string;
|
|
96
|
+
sessionId: string;
|
|
97
|
+
turnId: string;
|
|
98
|
+
projectCode?: string;
|
|
99
|
+
reasoning_gate_applied: boolean;
|
|
100
|
+
reasoning_gate_mode: ReasoningGateMode;
|
|
101
|
+
}) => void;
|
|
69
102
|
onDispatchError?: (details: {
|
|
70
103
|
eventName: string;
|
|
71
104
|
reason: string;
|