@unson/brainbase-mcp 0.50.18 → 0.50.20

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.
@@ -1,4 +1,4 @@
1
- import { assertFoundationCatalog, cloneFoundationCatalog, cloneFoundationDefinition, digestFoundationDefinition, findFoundationRecord, findLatestFoundationRecord, foundationCatalogOrEmpty, foundationKey, foundationRef, nextFoundationRevision } from './foundation-catalog.js';
1
+ import { cloneFoundationCatalog, cloneFoundationDefinition, digestFoundationDefinition, findFoundationRecord, findLatestFoundationRecord, foundationCatalogOrEmpty, foundationKey, foundationRef, nextFoundationRevision } from './foundation-catalog.js';
2
2
  import { validateFoundationDefinition, validateFoundationRelation } from './ontology-foundation.js';
3
3
  import { loadPersonalOs, mutatePersonalOs } from './ssot.js';
4
4
  export class FoundationStoreError extends Error {
@@ -342,7 +342,8 @@ function readCatalog(os) {
342
342
  throw new FoundationStoreError('unsupported_graph', 'Foundation catalog writes require canonical Graph v2');
343
343
  }
344
344
  try {
345
- assertFoundationCatalog(os.graph.foundation);
345
+ // foundationCatalogOrEmpty validates the whole catalog (shape and every digest)
346
+ // before it clones it. A second assertFoundationCatalog here repeated that work.
346
347
  return foundationCatalogOrEmpty(os.graph.foundation);
347
348
  }
348
349
  catch (error) {
@@ -0,0 +1,20 @@
1
+ export interface JudgmentJournalTurnInput {
2
+ sessionId: string;
3
+ turnId: string;
4
+ projectCode: string;
5
+ trustedToken: string;
6
+ /** Identity verified by the Host JWT boundary, never client body fields. */
7
+ trustedPrincipal: {
8
+ personId: string;
9
+ tenantId: string;
10
+ };
11
+ }
12
+ export interface JudgmentJournalTurnPublisherOptions {
13
+ apiBaseUrl?: string;
14
+ journalRoot: string;
15
+ fetch?: typeof globalThis.fetch;
16
+ /** Receives only a fixed reason code, never exception details or journal data. */
17
+ onError?: (reason: string) => void;
18
+ }
19
+ /** HTTP-only, best-effort publication of the host's finished canonical journal. */
20
+ export declare function createJudgmentJournalTurnPublisher(options: JudgmentJournalTurnPublisherOptions): (input: JudgmentJournalTurnInput) => Promise<void>;
@@ -0,0 +1,112 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile, readdir } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ const hash = (value) => createHash('sha256').update(value).digest('hex');
5
+ const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
6
+ /** HTTP-only, best-effort publication of the host's finished canonical journal. */
7
+ export function createJudgmentJournalTurnPublisher(options) {
8
+ const report = (reason) => {
9
+ try {
10
+ (options.onError ?? console.warn)(reason);
11
+ }
12
+ catch { /* Diagnostics must fail open too. */ }
13
+ };
14
+ return async (input) => {
15
+ if (!options.apiBaseUrl || !options.journalRoot) {
16
+ report('judgment_journal_not_configured');
17
+ return;
18
+ }
19
+ if (!input.trustedToken) {
20
+ report('judgment_journal_token_missing');
21
+ return;
22
+ }
23
+ let body;
24
+ try {
25
+ const sessionRef = hash(input.sessionId);
26
+ const prefix = join(options.journalRoot, sessionRef, hash(input.turnId));
27
+ const read = async (path, optional = false) => {
28
+ let text;
29
+ try {
30
+ text = await readFile(path, 'utf8');
31
+ }
32
+ catch (error) {
33
+ if (optional && error.code === 'ENOENT')
34
+ return undefined;
35
+ throw error;
36
+ }
37
+ const value = JSON.parse(text);
38
+ if (!object(value))
39
+ throw new Error('invalid');
40
+ return value;
41
+ };
42
+ const episode = (await read(`${prefix}.episode.json`));
43
+ // Check ownership when supplied; current hosts rely on the receiving API receipt-owner binding.
44
+ if (!input.trustedPrincipal?.personId?.trim() || !input.trustedPrincipal.tenantId?.trim()
45
+ || ('owner_person_id' in episode && episode.owner_person_id !== input.trustedPrincipal.personId)
46
+ || ('tenant_id' in episode && episode.tenant_id !== input.trustedPrincipal.tenantId))
47
+ throw new Error('invalid');
48
+ const final = (await read(`${prefix}.final.json`));
49
+ const receipt = episode.initial_route_receipt;
50
+ if (!object(receipt) || typeof receipt.resolution_id !== 'string' || !receipt.resolution_id
51
+ || receipt.project_code !== input.projectCode
52
+ || (receipt.turn_id !== undefined && receipt.turn_id !== input.turnId)
53
+ || (episode.turn_id !== undefined && episode.turn_id !== input.turnId)
54
+ || (episode.session_ref !== undefined && episode.session_ref !== sessionRef)
55
+ || (final.turn_id !== undefined && final.turn_id !== input.turnId)
56
+ || (final.session_ref !== undefined && final.session_ref !== sessionRef)
57
+ || typeof final.finalized_at !== 'string'
58
+ || !Number.isFinite(Date.parse(final.finalized_at)))
59
+ throw new Error('invalid');
60
+ let names;
61
+ try {
62
+ names = await readdir(`${prefix}.events`);
63
+ }
64
+ catch (error) {
65
+ if (error.code !== 'ENOENT')
66
+ throw error;
67
+ names = []; // Hosts need not create a directory for a zero-tool turn.
68
+ }
69
+ const rawEvents = await Promise.all(names.filter(name => name.endsWith('.json'))
70
+ .map(async (name) => (await read(join(`${prefix}.events`, name)))));
71
+ const sequence = (event) => typeof event.event_sequence === 'number' ? event.event_sequence : Number(event.sequence) - 1;
72
+ rawEvents.sort((a, b) => sequence(a) - sequence(b));
73
+ const events = rawEvents.map((event, index) => {
74
+ if (sequence(event) !== index || index >= 4096
75
+ || typeof event.event_fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(event.event_fingerprint)
76
+ || typeof event.tool_use_id !== 'string' || !event.tool_use_id.trim())
77
+ throw new Error('invalid');
78
+ return { event_sequence: index, event_fingerprint: event.event_fingerprint,
79
+ tool_use_id: event.tool_use_id, event };
80
+ });
81
+ if (final.event_count !== events.length)
82
+ throw new Error('invalid');
83
+ const turnInput = await read(`${prefix}.turn-input.json`, true);
84
+ const valueProof = await read(`${prefix}.value-proof.json`, true);
85
+ body = {
86
+ resolution_id: receipt.resolution_id, turn_id: input.turnId, project_code: input.projectCode,
87
+ turn_ref: `${sessionRef}/${hash(input.turnId)}`, entrypoint: 'claude_code',
88
+ receipt, episode, final, events,
89
+ ...(turnInput ? { turn_input: turnInput } : {}),
90
+ ...(valueProof ? { value_proof: valueProof } : {}), recorded_at: final.finalized_at,
91
+ };
92
+ }
93
+ catch (error) {
94
+ report(error.code === 'ENOENT'
95
+ ? 'judgment_journal_files_missing' : 'judgment_journal_files_invalid');
96
+ return;
97
+ }
98
+ try {
99
+ const response = await (options.fetch ?? globalThis.fetch)(`${options.apiBaseUrl.replace(/\/$/, '')}/api/organization/judgment-journal/turns`, {
100
+ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(1000),
101
+ headers: { Authorization: `Bearer ${input.trustedToken}`, 'Content-Type': 'application/json' },
102
+ body: JSON.stringify(body),
103
+ });
104
+ if (response.status !== 200 && response.status !== 201) {
105
+ report(response.status === 409 ? 'judgment_journal_conflict' : 'judgment_journal_http_failed');
106
+ }
107
+ }
108
+ catch {
109
+ report('judgment_journal_network_failed');
110
+ }
111
+ };
112
+ }
@@ -34,13 +34,32 @@ export class PersonalMemoryRegistrationError extends Error {
34
34
  /** Read both local memory stores and each memory's registration state. Never uses the network. */
35
35
  export async function listLocalMemories(dataDirInput) {
36
36
  const dataDir = resolveDataDir(dataDirInput);
37
- const [current, legacy, receipts] = await Promise.all([
37
+ // A malformed receipt rejects while the legacy read is still inside the
38
+ // canonical SSOT lock. Promise.all would return that rejection immediately
39
+ // and leave the lock to be created and removed afterwards. Wait for every
40
+ // read, then throw the rejection that happened first: the same one Promise.all
41
+ // would have thrown, once the other reads have released what they held.
42
+ const [current, legacy, receipts] = await awaitFirstRejection([
38
43
  readCurrentStore(dataDir),
39
44
  readLegacyStore(dataDir),
40
45
  readMemoryRegistrationReceipts(dataDir)
41
46
  ]);
42
47
  return [...current, ...legacy].map((memory) => withStatus(memory, receipts));
43
48
  }
49
+ /** The fulfilled values, or the earliest rejection, after every promise has settled. */
50
+ async function awaitFirstRejection(promises) {
51
+ let rejected = false;
52
+ let firstReason;
53
+ const values = await Promise.all(promises.map((promise) => promise.then((value) => value, (reason) => {
54
+ if (!rejected) {
55
+ rejected = true;
56
+ firstReason = reason;
57
+ }
58
+ })));
59
+ if (rejected)
60
+ throw firstReason;
61
+ return values;
62
+ }
44
63
  /** Pick exactly the requested memories, in request order, or fail before anything is sent. */
45
64
  export function selectLocalMemories(memories, ids) {
46
65
  const requested = [...new Set(ids.map((id) => id.trim()).filter(Boolean))];
@@ -0,0 +1,82 @@
1
+ import type { JudgmentJournalTurnInput } from './judgment-journal-turn-publisher.js';
2
+ /** Minimal identity verified by the consuming host's authentication boundary. */
3
+ export interface RemoteJudgmentHookPrincipal {
4
+ personId: string;
5
+ organizationId: string;
6
+ tenantId?: string;
7
+ projectCodes: string[];
8
+ }
9
+ export declare const REMOTE_JUDGMENT_HOOK_PATH = "/host/judgment/hook";
10
+ export declare const REMOTE_JUDGMENT_HOOK_MAX_BODY_BYTES: number;
11
+ export interface RemoteJudgmentHookDispatchResult {
12
+ output: Record<string, unknown>;
13
+ receiptId?: string;
14
+ routeResolutionSha256?: string;
15
+ }
16
+ /**
17
+ * `remote`: a remote runtime. `claude-code`: Claude Code on
18
+ * the owner's loopback bridge or authenticated with a person's hosted JWT.
19
+ */
20
+ export type RemoteJudgmentHookHost = 'remote' | 'claude-code';
21
+ /**
22
+ * Authentication context verified by the Host before it reaches the hook
23
+ * dispatcher. A shared bearer intentionally has no trusted principal or
24
+ * auth kind and therefore is not represented here.
25
+ */
26
+ export type RemoteJudgmentHookAuthKind = 'brainbase-jwt' | 'company-authority';
27
+ /** Derive flags from verified authentication and the host's owner-loopback check. */
28
+ export declare function remoteJudgmentHookHostFlags(authKind: RemoteJudgmentHookAuthKind | 'shared-bearer', isOwnerLocalBridge: boolean): {
29
+ personHostedClaudeCodeAllowed: boolean;
30
+ localClaudeCodeAllowed: boolean;
31
+ };
32
+ export interface RemoteJudgmentHookDispatchOptions {
33
+ host: RemoteJudgmentHookHost;
34
+ /** Principal verified by the Host authentication boundary, when available. */
35
+ trustedPrincipal?: RemoteJudgmentHookPrincipal;
36
+ /** The verified caller token, kept inside the dispatch boundary for canonical readback. */
37
+ trustedToken?: string;
38
+ /** Authentication kind verified by the Host authentication boundary. */
39
+ trustedAuthKind?: RemoteJudgmentHookAuthKind;
40
+ /** Raw encoded Company Authority response verified by the canonical API. */
41
+ companyAuthorityResponse?: string;
42
+ }
43
+ export type RemoteJudgmentHookDispatch = (payload: Record<string, unknown>, projectCode: string | undefined, options: RemoteJudgmentHookDispatchOptions) => Promise<RemoteJudgmentHookDispatchResult>;
44
+ export interface RemoteJudgmentHookRequest {
45
+ method?: string;
46
+ url?: string;
47
+ authorization?: string;
48
+ body: Buffer;
49
+ bearerToken: string;
50
+ projectCode?: string;
51
+ /** Principal verified by the Host authentication boundary, never by request body fields. */
52
+ trustedPrincipal?: RemoteJudgmentHookPrincipal;
53
+ /** Verified caller token; never included in the response or diagnostic payload. */
54
+ trustedToken?: string;
55
+ /** Authentication kind verified by the Host authentication boundary. */
56
+ trustedAuthKind?: RemoteJudgmentHookAuthKind;
57
+ /** Raw encoded Company Authority response verified by the canonical API. */
58
+ companyAuthorityResponse?: string;
59
+ /** The x-brainbase-judgment-host header, when the caller declared one. */
60
+ declaredHost?: string;
61
+ /** True only on the owner's loopback bridge for a shared-bearer request. */
62
+ localClaudeCodeAllowed?: boolean;
63
+ /** True only for a person authenticated by the hosted MCP's JWT boundary. */
64
+ personHostedClaudeCodeAllowed?: boolean;
65
+ isAuthorized: (authorization: string | undefined, expectedToken: string) => boolean;
66
+ dispatch: RemoteJudgmentHookDispatch;
67
+ /** Optional HTTP publisher for person-authenticated hosted Claude Code Stop events. */
68
+ journalTurnPublisher?: (input: JudgmentJournalTurnInput) => Promise<void>;
69
+ onDispatchError?: (details: {
70
+ eventName: string;
71
+ reason: string;
72
+ errorName: string;
73
+ errorCode?: string;
74
+ causeReasonCode?: string;
75
+ }) => void;
76
+ }
77
+ export interface RemoteJudgmentHookResponse {
78
+ status: number;
79
+ headers?: Record<string, string>;
80
+ body: Record<string, unknown>;
81
+ }
82
+ export declare function handleRemoteJudgmentHookRequest(request: RemoteJudgmentHookRequest): Promise<RemoteJudgmentHookResponse | null>;
@@ -0,0 +1,207 @@
1
+ export const REMOTE_JUDGMENT_HOOK_PATH = '/host/judgment/hook';
2
+ export const REMOTE_JUDGMENT_HOOK_MAX_BODY_BYTES = 1024 * 1024;
3
+ /** Derive flags from verified authentication and the host's owner-loopback check. */
4
+ export function remoteJudgmentHookHostFlags(authKind, isOwnerLocalBridge) {
5
+ return {
6
+ personHostedClaudeCodeAllowed: authKind === 'brainbase-jwt',
7
+ localClaudeCodeAllowed: authKind === 'shared-bearer' && isOwnerLocalBridge === true,
8
+ };
9
+ }
10
+ const PROJECT_CODE_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
11
+ const SUPPORTED_HOOK_EVENTS = new Set(['UserPromptSubmit', 'PostToolUse', 'PostToolUseFailure', 'Stop']);
12
+ // The owner's Claude Code also sends a knowledge lookup's PreToolUse, so the
13
+ // Host can reserve the attempt it later records. A remote runtime keeps the
14
+ // events above.
15
+ const CLAUDE_CODE_HOOK_EVENTS = new Set([...SUPPORTED_HOOK_EVENTS, 'PreToolUse']);
16
+ const SAFE_REASON_CODE = /^[a-z][a-z0-9_]{1,80}$/;
17
+ const FORBIDDEN_SCOPE_REASON_CODES = new Set([
18
+ 'judgment_history_scope_mismatch',
19
+ 'judgment_history_project_denied',
20
+ 'judgment_history_shared_bearer_denied',
21
+ // Current scope binder wording; retain the explicit deny classification if
22
+ // the binder has not yet adopted the shorter reason code above.
23
+ 'judgment_history_scope_shared_bearer_rejected',
24
+ ]);
25
+ function isInternalJudgmentControlTool(payload) {
26
+ const toolName = payload.tool_name ?? payload.toolName;
27
+ return typeof toolName === 'string'
28
+ && ['mcp__brainbase__brainbase_judgment_state_record',
29
+ 'mcp__brainbase__brainbase_judgment_audit_read',
30
+ 'mcp__brainbase__brainbase_judgment_repair_read'].includes(toolName);
31
+ }
32
+ function safeCauseReasonCode(error) {
33
+ let current = typeof error === 'object' && error && 'cause' in error ? error.cause : undefined;
34
+ const visited = new Set();
35
+ for (let depth = 0; depth < 6 && current && !visited.has(current); depth += 1) {
36
+ visited.add(current);
37
+ if (current instanceof Error && SAFE_REASON_CODE.test(current.message))
38
+ return current.message;
39
+ current = typeof current === 'object' && 'cause' in current ? current.cause : undefined;
40
+ }
41
+ return undefined;
42
+ }
43
+ export async function handleRemoteJudgmentHookRequest(request) {
44
+ if (request.method !== 'POST' || request.url !== REMOTE_JUDGMENT_HOOK_PATH)
45
+ return null;
46
+ if (!request.isAuthorized(request.authorization, request.bearerToken)) {
47
+ return {
48
+ status: 401,
49
+ headers: { 'WWW-Authenticate': 'Bearer' },
50
+ body: { error: 'unauthorized' },
51
+ };
52
+ }
53
+ if (request.body.length > REMOTE_JUDGMENT_HOOK_MAX_BODY_BYTES) {
54
+ return { status: 413, body: { error: 'judgment_hook_payload_too_large' } };
55
+ }
56
+ let payload;
57
+ try {
58
+ payload = JSON.parse(request.body.toString('utf8'));
59
+ }
60
+ catch {
61
+ return { status: 400, body: { error: 'invalid_json' } };
62
+ }
63
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
64
+ return { status: 400, body: { error: 'invalid_hook_payload' } };
65
+ }
66
+ const hookPayload = payload;
67
+ const eventName = hookPayload.hook_event_name ?? hookPayload.hookEventName;
68
+ if (typeof eventName !== 'string' || !CLAUDE_CODE_HOOK_EVENTS.has(eventName)) {
69
+ return { status: 400, body: { error: 'unsupported_hook_event' } };
70
+ }
71
+ const personHostedClaudeCode = request.personHostedClaudeCodeAllowed === true
72
+ && request.trustedAuthKind === 'brainbase-jwt';
73
+ const host = request.declaredHost === undefined || request.declaredHost === ''
74
+ ? 'remote' : 'claude-code';
75
+ if (host === 'claude-code'
76
+ && (request.declaredHost !== 'claude-code' || (request.localClaudeCodeAllowed !== true && !personHostedClaudeCode))) {
77
+ return { status: 400, body: { error: 'judgment_hook_host_unsupported' } };
78
+ }
79
+ if (host === 'remote' && !SUPPORTED_HOOK_EVENTS.has(eventName)) {
80
+ return { status: 400, body: { error: 'unsupported_hook_event' } };
81
+ }
82
+ // A local Claude Code turn may leave the project to the Host, which derives
83
+ // it from the turn's cwd exactly as for Codex.
84
+ const requiresProjectScope = host === 'remote' || (host === 'claude-code' && personHostedClaudeCode);
85
+ if (host === 'claude-code' && personHostedClaudeCode
86
+ && !request.trustedPrincipal?.tenantId?.trim()) {
87
+ return { status: 403, body: { error: 'authenticated_history_principal_unavailable' } };
88
+ }
89
+ if ((requiresProjectScope || request.projectCode !== undefined)
90
+ && (!request.projectCode || !PROJECT_CODE_PATTERN.test(request.projectCode))) {
91
+ return { status: 400, body: { error: 'invalid_project_code' } };
92
+ }
93
+ if (requiresProjectScope && request.trustedPrincipal
94
+ && (!request.projectCode || !request.trustedPrincipal.projectCodes.includes(request.projectCode))) {
95
+ return { status: 403, body: { error: 'project_not_authorized' } };
96
+ }
97
+ if (request.trustedPrincipal && !request.trustedPrincipal.tenantId?.trim()) {
98
+ return { status: 403, body: { error: 'authenticated_history_principal_unavailable' } };
99
+ }
100
+ const sessionId = hookPayload.session_id;
101
+ const turnId = hookPayload.turn_id;
102
+ if (typeof sessionId !== 'string' || !sessionId || typeof turnId !== 'string' || !turnId) {
103
+ return { status: 400, body: { error: 'invalid_hook_identity' } };
104
+ }
105
+ try {
106
+ const dispatchOptions = request.trustedPrincipal
107
+ ? {
108
+ host,
109
+ trustedPrincipal: request.trustedPrincipal,
110
+ ...(request.trustedToken ? { trustedToken: request.trustedToken } : {}),
111
+ ...(request.trustedAuthKind ? { trustedAuthKind: request.trustedAuthKind } : {}),
112
+ ...(request.companyAuthorityResponse
113
+ ? { companyAuthorityResponse: request.companyAuthorityResponse }
114
+ : {}),
115
+ }
116
+ : { host };
117
+ const dispatchResult = await request.dispatch(hookPayload, request.projectCode, dispatchOptions);
118
+ const { output } = dispatchResult;
119
+ if (!output || typeof output !== 'object' || Array.isArray(output)) {
120
+ return { status: 503, body: { error: 'judgment_hook_output_invalid' } };
121
+ }
122
+ // The remote runtime's stream validator needs an audit line per tool. A
123
+ // local Claude Code turn has no such validator; the Host decides alone.
124
+ if (host === 'remote' && (eventName === 'PostToolUse' || eventName === 'PostToolUseFailure')
125
+ && !isInternalJudgmentControlTool(hookPayload)
126
+ && (typeof output.systemMessage !== 'string' || !output.systemMessage.trim())) {
127
+ return { status: 503, body: { error: 'judgment_hook_audit_not_recorded' } };
128
+ }
129
+ if (eventName === 'UserPromptSubmit'
130
+ && (typeof dispatchResult.receiptId !== 'string' || !dispatchResult.receiptId.trim()
131
+ || typeof dispatchResult.routeResolutionSha256 !== 'string'
132
+ || !/^[a-f0-9]{64}$/.test(dispatchResult.routeResolutionSha256))) {
133
+ return { status: 503, body: { error: 'judgment_hook_route_receipt_missing' } };
134
+ }
135
+ if (eventName === 'Stop' && host === 'claude-code' && personHostedClaudeCode
136
+ && request.localClaudeCodeAllowed !== true) {
137
+ const report = (reason) => {
138
+ try {
139
+ console.warn(reason);
140
+ }
141
+ catch { /* Logging cannot affect the hook response. */ }
142
+ };
143
+ if (!request.journalTurnPublisher)
144
+ report('judgment_journal_not_configured');
145
+ else if (!request.trustedToken)
146
+ report('judgment_journal_token_missing');
147
+ else {
148
+ let timer;
149
+ try {
150
+ await Promise.race([
151
+ Promise.resolve().then(() => request.journalTurnPublisher({
152
+ sessionId, turnId, projectCode: request.projectCode, trustedToken: request.trustedToken,
153
+ trustedPrincipal: { personId: request.trustedPrincipal.personId, tenantId: request.trustedPrincipal.tenantId },
154
+ })),
155
+ new Promise((_resolve, reject) => {
156
+ timer = setTimeout(() => reject(new Error()), 1500);
157
+ }),
158
+ ]);
159
+ }
160
+ catch {
161
+ report('judgment_journal_publish_failed');
162
+ }
163
+ finally {
164
+ if (timer)
165
+ clearTimeout(timer);
166
+ }
167
+ }
168
+ }
169
+ const hasRouteReceipt = typeof dispatchResult.receiptId === 'string'
170
+ && dispatchResult.receiptId.trim().length > 0
171
+ && typeof dispatchResult.routeResolutionSha256 === 'string'
172
+ && /^[a-f0-9]{64}$/.test(dispatchResult.routeResolutionSha256);
173
+ return {
174
+ status: 200,
175
+ body: {
176
+ schema_version: '1', accepted: true,
177
+ hook_event_name: eventName, session_id: sessionId, turn_id: turnId,
178
+ ...((eventName === 'UserPromptSubmit' || eventName === 'Stop') && hasRouteReceipt ? {
179
+ receipt_id: dispatchResult.receiptId,
180
+ route_resolution_sha256: dispatchResult.routeResolutionSha256,
181
+ } : {}),
182
+ output,
183
+ },
184
+ };
185
+ }
186
+ catch (error) {
187
+ const reason = error instanceof Error
188
+ && /^judgment_[a-z0-9_]{1,80}$/.test(error.message)
189
+ ? error.message
190
+ : 'judgment_hook_unavailable';
191
+ const errorCode = error && typeof error === 'object'
192
+ && 'code' in error && typeof error.code === 'string'
193
+ && /^[A-Z0-9_]{1,80}$/.test(error.code)
194
+ ? error.code
195
+ : undefined;
196
+ const causeReasonCode = safeCauseReasonCode(error);
197
+ request.onDispatchError?.({
198
+ eventName,
199
+ reason,
200
+ errorName: error instanceof Error ? error.name : 'UnknownError',
201
+ ...(errorCode ? { errorCode } : {}),
202
+ ...(causeReasonCode && causeReasonCode !== reason ? { causeReasonCode } : {}),
203
+ });
204
+ const status = FORBIDDEN_SCOPE_REASON_CODES.has(reason) ? 403 : 503;
205
+ return { status, body: { error: reason } };
206
+ }
207
+ }
package/dist/ssot.js CHANGED
@@ -164,13 +164,25 @@ function blockMigrationWrite(plan, issue) {
164
164
  };
165
165
  }
166
166
  async function loadPersonalOsUnlocked(dataDir) {
167
- const graph = parseGraph(await readJson(join(dataDir, 'graph.json')));
168
- const relationships = relationshipsSchema.parse(await readJson(join(dataDir, 'relationships.json')));
169
- const personalKg = await readJsonl(join(dataDir, 'personal-kg.jsonl'), personalKgSchema, 'personal-kg.jsonl');
170
- const decisions = await readJsonl(join(dataDir, 'decisions.jsonl'), decisionSchema, 'decisions.jsonl');
171
- const sourceCount = await countSources(dataDir);
167
+ // Read and validate the files at the same time, but report a failure in the same
168
+ // file order as before so the first broken canonical file is the one named.
169
+ const [graph, relationships, personalKg, decisions, sourceCount] = await settleInOrder([
170
+ readJson(join(dataDir, 'graph.json')).then(parseGraph),
171
+ readJson(join(dataDir, 'relationships.json')).then((value) => relationshipsSchema.parse(value)),
172
+ readJsonl(join(dataDir, 'personal-kg.jsonl'), personalKgSchema, 'personal-kg.jsonl'),
173
+ readJsonl(join(dataDir, 'decisions.jsonl'), decisionSchema, 'decisions.jsonl'),
174
+ countSources(dataDir)
175
+ ]);
172
176
  return { dataDir, graph, personalKg, relationships, decisions, sourceCount };
173
177
  }
178
+ async function settleInOrder(promises) {
179
+ const results = await Promise.allSettled(promises);
180
+ for (const result of results) {
181
+ if (result.status === 'rejected')
182
+ throw result.reason;
183
+ }
184
+ return results.map((result) => result.value);
185
+ }
174
186
  async function commitAggregate(dataDir, next, mode, sidecars = []) {
175
187
  validateAggregate(next);
176
188
  const id = randomUUID();
@@ -341,33 +353,69 @@ async function copyCanonicalSet(sourceDir, targetDir) {
341
353
  }
342
354
  }
343
355
  async function ensureAncillaryDirectories(dataDir) {
344
- for (const relative of ['sources', 'sources/gmail', 'sources/calendar', 'sources/drive', 'sources/tasks', 'candidates', 'schemas']) {
345
- await mkdir(join(dataDir, relative), { recursive: true });
356
+ // This runs on every initialization, including for an existing directory, so the
357
+ // independent directories and schema files are created at the same time.
358
+ await Promise.all(['sources/gmail', 'sources/calendar', 'sources/drive', 'sources/tasks', 'candidates', 'schemas']
359
+ .map((relative) => mkdir(join(dataDir, relative), { recursive: true })));
360
+ await Promise.all(Object.entries(schemaTemplates).map(([fileName, schema]) => (writeFile(join(dataDir, 'schemas', fileName), `${JSON.stringify(schema, null, 2)}\n`, { flag: 'wx' }).catch((error) => {
361
+ if (error.code !== 'EEXIST')
362
+ throw error;
363
+ }))));
364
+ }
365
+ /**
366
+ * Callers in this process that wait for the same lock directory, in arrival order.
367
+ * The directory lock still guards other processes. Without this queue, callers in
368
+ * one process (for example the parallel checks in execution-authority) polled the
369
+ * directory lock every retry interval, so each one waited longer than the holder
370
+ * worked, and the polling added file operations while the holder was still writing.
371
+ */
372
+ const inProcessLockQueues = new Map();
373
+ async function withSsotLock(dataDir, operation) {
374
+ const deadline = Date.now() + parsePositiveInteger(process.env.BRAINBASE_SSOT_LOCK_TIMEOUT_MS, 5_000);
375
+ const lockDir = join(dataDir, lockName);
376
+ const queueKey = resolve(lockDir);
377
+ const previous = inProcessLockQueues.get(queueKey);
378
+ let finishTurn;
379
+ const turn = new Promise((resolveTurn) => { finishTurn = resolveTurn; });
380
+ // A caller that gives up still keeps its place until the callers before it finish,
381
+ // so the next caller never starts while an earlier holder is working.
382
+ const queueTail = previous ? previous.then(() => turn) : turn;
383
+ inProcessLockQueues.set(queueKey, queueTail);
384
+ try {
385
+ await mkdir(dataDir, { recursive: true });
386
+ if (previous)
387
+ await waitForInProcessTurn(previous, deadline, lockDir);
388
+ const owner = await acquireLock(dataDir, deadline);
389
+ try {
390
+ return await operation();
391
+ }
392
+ finally {
393
+ await releaseLock(dataDir, owner).catch((error) => {
394
+ warnCleanupFailure(`canonical SSOT lock ${lockDir}`, error);
395
+ });
396
+ }
346
397
  }
347
- for (const [fileName, schema] of Object.entries(schemaTemplates)) {
348
- await writeFile(join(dataDir, 'schemas', fileName), `${JSON.stringify(schema, null, 2)}\n`, { flag: 'wx' }).catch((error) => {
349
- if (error.code !== 'EEXIST')
350
- throw error;
351
- });
398
+ finally {
399
+ finishTurn();
400
+ if (inProcessLockQueues.get(queueKey) === queueTail)
401
+ inProcessLockQueues.delete(queueKey);
352
402
  }
353
403
  }
354
- async function withSsotLock(dataDir, operation) {
355
- await mkdir(dataDir, { recursive: true });
356
- const owner = await acquireLock(dataDir);
404
+ async function waitForInProcessTurn(previous, deadline, lockDir) {
405
+ let timer;
406
+ const timedOut = new Promise((_resolve, reject) => {
407
+ timer = setTimeout(() => reject(new Error(`Timed out waiting for canonical SSOT lock ${lockDir}`)), Math.max(0, deadline - Date.now()));
408
+ });
357
409
  try {
358
- return await operation();
410
+ await Promise.race([previous, timedOut]);
359
411
  }
360
412
  finally {
361
- await releaseLock(dataDir, owner).catch((error) => {
362
- warnCleanupFailure(`canonical SSOT lock ${join(dataDir, lockName)}`, error);
363
- });
413
+ clearTimeout(timer);
364
414
  }
365
415
  }
366
- async function acquireLock(dataDir) {
416
+ async function acquireLock(dataDir, deadline) {
367
417
  const lockDir = join(dataDir, lockName);
368
- const timeoutMs = parsePositiveInteger(process.env.BRAINBASE_SSOT_LOCK_TIMEOUT_MS, 5_000);
369
418
  const retryMs = parsePositiveInteger(process.env.BRAINBASE_SSOT_LOCK_RETRY_MS, 20);
370
- const deadline = Date.now() + timeoutMs;
371
419
  const owner = { token: randomUUID(), pid: process.pid, hostname: hostname() };
372
420
  while (true) {
373
421
  try {
@@ -432,12 +480,8 @@ function isProcessAlive(pid) {
432
480
  }
433
481
  }
434
482
  async function canonicalPresence(dataDir) {
435
- const result = [];
436
- for (const fileName of canonicalFiles) {
437
- if (await exists(join(dataDir, fileName)))
438
- result.push(fileName);
439
- }
440
- return result;
483
+ const present = await Promise.all(canonicalFiles.map((fileName) => exists(join(dataDir, fileName))));
484
+ return canonicalFiles.filter((_fileName, index) => present[index]);
441
485
  }
442
486
  function assertCompleteCanonicalSet(dataDir, present) {
443
487
  if (present.length !== canonicalFiles.length) {
@@ -532,11 +576,13 @@ async function countSources(dataDir) {
532
576
  }
533
577
  async function countSourceFiles(sourceDir) {
534
578
  try {
535
- const entries = await readdir(sourceDir);
536
- const counts = await Promise.all(entries.filter((entry) => !entry.startsWith('.')).map(async (entry) => {
537
- const entryPath = join(sourceDir, entry);
538
- const entryStat = await stat(entryPath);
539
- return entryStat.isDirectory() ? countSourceFiles(entryPath) : entryStat.isFile() ? 1 : 0;
579
+ const entries = await readdir(sourceDir, { withFileTypes: true });
580
+ const counts = await Promise.all(entries.filter((entry) => !entry.name.startsWith('.')).map(async (entry) => {
581
+ const entryPath = join(sourceDir, entry.name);
582
+ // The directory listing already says what most entries are. Only links and
583
+ // unknown types need stat, which follows the link as before.
584
+ const kind = entry.isDirectory() || entry.isFile() ? entry : await stat(entryPath);
585
+ return kind.isDirectory() ? countSourceFiles(entryPath) : kind.isFile() ? 1 : 0;
540
586
  }));
541
587
  return counts.reduce((sum, count) => sum + count, 0);
542
588
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unson/brainbase-mcp",
3
- "version": "0.50.18",
3
+ "version": "0.50.20",
4
4
  "description": "Local-first Brainbase judgment OS that lets supported AI agents reuse a user's approved goals, priorities, decisions, and judgment criteria.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -43,6 +43,14 @@
43
43
  "types": "./dist/judgment-history.d.ts",
44
44
  "import": "./dist/judgment-history.js"
45
45
  },
46
+ "./judgment-journal-turn-publisher": {
47
+ "types": "./dist/judgment-journal-turn-publisher.d.ts",
48
+ "import": "./dist/judgment-journal-turn-publisher.js"
49
+ },
50
+ "./remote-judgment-hook-http": {
51
+ "types": "./dist/remote-judgment-hook-http.d.ts",
52
+ "import": "./dist/remote-judgment-hook-http.js"
53
+ },
46
54
  "./judgment-history-http": {
47
55
  "types": "./dist/judgment-history-http.d.ts",
48
56
  "import": "./dist/judgment-history-http.js"
@@ -649,5 +657,5 @@
649
657
  "url": "https://github.com/Unson-LLC/brainbase/issues"
650
658
  },
651
659
  "homepage": "https://github.com/Unson-LLC/brainbase#readme",
652
- "gitHead": "c7217bea64aaf3562280a8ec55ce6e6ca590b4a9"
660
+ "gitHead": "e143043ecb89b03cf1e6b9c928a37c19e045c957"
653
661
  }
@@ -109,10 +109,10 @@
109
109
 
110
110
  .bb-jh-controls {
111
111
  display: flex;
112
- flex-wrap: nowrap;
112
+ flex-wrap: wrap;
113
113
  align-items: center;
114
- gap: 8px;
115
- margin: 0 0 6px;
114
+ gap: var(--bb-space-2);
115
+ margin: 0 0 var(--bb-space-2);
116
116
  }
117
117
 
118
118
  .bb-jh-toolbar-status {
@@ -135,9 +135,9 @@
135
135
  }
136
136
 
137
137
  .bb-jh-summary {
138
- margin: 4px 0 6px;
139
- color: #3b4148;
140
- font-size: 12.5px;
138
+ margin: var(--bb-space-1) 0 var(--bb-space-2);
139
+ color: var(--bb-color-muted);
140
+ font-size: var(--bb-font-size-xs, 12px);
141
141
  }
142
142
 
143
143
  .bb-jh-summary strong {
@@ -589,11 +589,16 @@
589
589
  .bb-jh > .bb-ws-page { margin-bottom: var(--bb-space-6, 32px); }
590
590
  .bb-jh-controls { margin-bottom: var(--bb-space-4, 16px); }
591
591
  .bb-jh-checked { font-size: 11px; font-variant-numeric: tabular-nums; }
592
- .bb-jh-filter-fields { display: grid; gap: 16px; }
593
- .bb-jh-filter-fields .bb-jh-periods { flex-wrap: wrap; gap: 6px; }
594
- .bb-jh-filter-fields .bb-jh-normal-filters { display: grid; flex: none; gap: 16px; }
595
- .bb-jh-filter-fields .bb-jh-filter { display: grid; gap: 6px; }
596
- .bb-jh-filter-fields select { width: 100%; }
592
+ .bb-jh-filter-fields { display: flex; flex-wrap: wrap; align-items: center; gap: var(--bb-space-2); min-width: 0; }
593
+ .bb-jh-filter-fields .bb-jh-periods { flex-wrap: wrap; gap: var(--bb-space-1); }
594
+ .bb-jh-filter-fields .bb-jh-normal-filters { flex: none; flex-direction: row; min-width: 0; }
595
+ .bb-jh-filter-fields .bb-jh-filter { display: grid; gap: var(--bb-space-1); max-width: 100%; white-space: normal; }
596
+ .bb-jh-filter-fields .bb-ws-combobox-trigger { max-width: 100%; }
597
+ @media (max-width: 760px) {
598
+ .bb-jh-filter-fields { flex: 1 1 100%; }
599
+ .bb-jh-filter-fields .bb-jh-normal-filters { flex: 1 1 100%; }
600
+ .bb-jh-filter-fields .bb-jh-filter { flex: 1 1 0; }
601
+ }
597
602
  .bb-jh-refresh { display: grid; place-items: center; flex: none; width: 32px; height: 32px; padding: 6px; }
598
603
  .bb-jh-refresh-mark { display: block; width: 16px; height: 16px; }
599
604
  .bb-jh-notifications { display: grid; gap: 8px; }
@@ -15,7 +15,6 @@ const {
15
15
  makeWorkspaceElement,
16
16
  workspaceButton,
17
17
  workspaceDialog,
18
- workspaceFilterPopover,
19
18
  workspaceErrorCard,
20
19
  workspaceCombobox,
21
20
  workspaceDefinition,
@@ -1872,15 +1871,23 @@ function loadingLine(doc) {
1872
1871
  });
1873
1872
  }
1874
1873
 
1875
- function summaryLine(doc, aggregate, { loading = false } = {}) {
1876
- const retrieved = Number.isInteger(aggregate?.retrievedCount) ? aggregate.retrievedCount : (aggregate?.rows?.length ?? 0);
1877
- const complete = aggregate?.countComplete === true && Number.isInteger(aggregate?.totalCount);
1878
- const showCount = complete || retrieved > 0;
1879
- if (loading && !showCount) return loadingLine(doc);
1880
- const line = makeWorkspaceElement(doc, 'p', { className: 'bb-jh-summary' });
1881
- line.append(makeWorkspaceElement(doc, 'strong', { text: `${complete ? aggregate.totalCount : retrieved}件` }));
1882
- line.append(makeWorkspaceElement(doc, 'span', { text: loading ? ' 届きました(続きを読み込んでいます…)' : ' 取得済み' }));
1883
- if (loading) return line;
1874
+ function summaryLine(doc, aggregate, { loading = false, retrievedCount } = {}) {
1875
+ const retrieved = retrievedCount ?? aggregate?.retrievedCount ?? aggregate?.rows?.length ?? 0;
1876
+ const normal = aggregate?.mode === 'normal';
1877
+ const complete = normal
1878
+ ? aggregate?.totalCount !== null && Number.isInteger(aggregate?.totalCount)
1879
+ : aggregate?.status === 'available';
1880
+ if (loading && retrieved === 0) return loadingLine(doc);
1881
+ const visible = aggregate?.rows?.length ?? 0;
1882
+ const line = makeWorkspaceElement(doc, 'p', { className: 'bb-jh-summary', attrs: { 'aria-live': 'polite' } });
1883
+ const total = complete ? `${aggregate.totalCount}件${aggregate.query ? '(検索前)' : ''}` : '未確認';
1884
+ line.append(makeWorkspaceElement(doc, 'span', {
1885
+ text: `取得済み ${retrieved}件 · 条件一致 ${visible}件${aggregate.query && normal ? '(取得済みの範囲)' : ''} · 表示 ${visible ? `1–${visible}` : '0'}件 · 総数 ${total}`,
1886
+ }));
1887
+ if (loading) {
1888
+ line.append(makeWorkspaceElement(doc, 'span', { text: ' 届きました(続きを読み込んでいます…)' }));
1889
+ return line;
1890
+ }
1884
1891
  const references = aggregate?.stats?.referenceCount ?? aggregate?.stats?.references;
1885
1892
  const confirmed = aggregate?.stats?.confirmedOutcomes ?? aggregate?.stats?.outcomes;
1886
1893
  line.append(makeWorkspaceElement(doc, 'span', { text: ' ・ 使った参照 ' }));
@@ -1983,11 +1990,9 @@ export function createJudgmentHistoryUI({
1983
1990
  personalMemories: new Map(),
1984
1991
  };
1985
1992
 
1986
- let filterPopover = null;
1987
1993
  let filterComboboxes = [];
1988
1994
  // The record details stay open across redraws of the same screen.
1989
1995
  let recordDetailsOpen = false;
1990
- let filterExpanded = false;
1991
1996
  let drawer = null;
1992
1997
  let drawerContent = null;
1993
1998
  let drawerKey = null;
@@ -2399,14 +2404,11 @@ export function createJudgmentHistoryUI({
2399
2404
  root.replaceChildren(pending);
2400
2405
  return;
2401
2406
  }
2402
- const focusedFilter = filterExpanded && filterPopover
2403
- ? findFirst(filterPopover.panel, node => node === doc.activeElement) : null;
2407
+ const focusedFilter = findFirst(root, node => node === doc.activeElement && (attributeValue(node, 'data-filter') || attributeValue(node, 'data-period')));
2404
2408
  const filterFocus = focusedFilter && {
2405
2409
  filter: attributeValue(focusedFilter, 'data-filter'),
2406
2410
  label: attributeValue(focusedFilter, 'aria-label'), period: attributeValue(focusedFilter, 'data-period'),
2407
2411
  };
2408
- filterPopover?.destroy();
2409
- filterPopover = null;
2410
2412
  for (const combobox of filterComboboxes) combobox.destroy();
2411
2413
  filterComboboxes = [];
2412
2414
  const previousSearchInput = findFirst(root, isSearchInput);
@@ -2445,7 +2447,7 @@ export function createJudgmentHistoryUI({
2445
2447
  if (!nativeDrawer) renderRail(doc, rail, null, null);
2446
2448
  return;
2447
2449
  }
2448
- const controls = makeWorkspaceElement(doc, 'div', { className: 'bb-jh-controls' });
2450
+ const controls = makeWorkspaceElement(doc, 'div', { className: 'bb-jh-controls', attrs: { role: 'group', 'aria-label': '判断の履歴の絞り込み' } });
2449
2451
  const filterFields = makeWorkspaceElement(doc, 'div', { className: 'bb-jh-filter-fields' });
2450
2452
  filterFields.append(periodButtons(doc, state.period, (period) => {
2451
2453
  state.period = period;
@@ -2471,11 +2473,7 @@ export function createJudgmentHistoryUI({
2471
2473
  if (searchable) state.aggregate = aggregateJudgmentHistory(searchable, { now: readNow(), period: state.period, query: state.query });
2472
2474
  render();
2473
2475
  }));
2474
- filterPopover = workspaceFilterPopover(doc, {
2475
- content: filterFields, open: filterExpanded,
2476
- onToggle: value => { filterExpanded = value; },
2477
- });
2478
- controls.append(filterPopover.root);
2476
+ controls.append(filterFields);
2479
2477
  const toolbarStatus = makeWorkspaceElement(doc, 'div', { className: 'bb-jh-toolbar-status' });
2480
2478
  if (state.checkedAt) {
2481
2479
  const stamp = formatCheckedAt(state.checkedAt);
@@ -2504,7 +2502,9 @@ export function createJudgmentHistoryUI({
2504
2502
  toolbarStatus.append(reloadButton);
2505
2503
  controls.append(toolbarStatus);
2506
2504
  wrapper.append(controls);
2507
- wrapper.append(summaryLine(doc, aggregate, { loading }));
2505
+ wrapper.append(summaryLine(doc, aggregate, {
2506
+ loading, retrievedCount: (sourceHome?.mode === 'normal' ? sourceHome.records : sourceHome?.items)?.length ?? 0,
2507
+ }));
2508
2508
  const emptyText = loading ? '' : state.home?.status === 'partial' || (normalMode() && !aggregate.countComplete)
2509
2509
  ? 'この期間に取得できた判断履歴はありません。全件数が未確認のため0件とは確認できません。'
2510
2510
  : 'この期間の判断履歴はありません。';
@@ -2539,8 +2539,8 @@ export function createJudgmentHistoryUI({
2539
2539
  replaceNode(nextSearchInput, previousSearchInput);
2540
2540
  }
2541
2541
  root.replaceChildren(wrapper);
2542
- if (filterExpanded && filterFocus) {
2543
- const field = findFirst(filterPopover.panel, node => (filterFocus.filter
2542
+ if (filterFocus) {
2543
+ const field = findFirst(controls, node => (filterFocus.filter
2544
2544
  ? attributeValue(node, 'data-filter') === filterFocus.filter
2545
2545
  : filterFocus.label
2546
2546
  ? attributeValue(node, 'aria-label') === filterFocus.label
@@ -2731,7 +2731,6 @@ export function createJudgmentHistoryUI({
2731
2731
  state.disposed = true;
2732
2732
  state.generation += 1;
2733
2733
  clearLoadTimers();
2734
- filterPopover?.destroy();
2735
2734
  for (const combobox of filterComboboxes) combobox.destroy();
2736
2735
  notifications.remove?.();
2737
2736
  disposeDrawer();