@unson/brainbase-mcp 0.47.5 → 0.48.0

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.
@@ -27,6 +27,37 @@ CREATE TABLE IF NOT EXISTS canonical_tasks (
27
27
  ALTER TABLE canonical_tasks
28
28
  ADD COLUMN IF NOT EXISTS project_codes TEXT[] NOT NULL DEFAULT '{}'::text[];
29
29
 
30
+ -- Shared record kind; existing rows and callers that omit it remain work.
31
+ ALTER TABLE canonical_tasks
32
+ ADD COLUMN IF NOT EXISTS record_kind TEXT NOT NULL DEFAULT 'work';
33
+
34
+ DO $$
35
+ BEGIN
36
+ IF NOT EXISTS (
37
+ SELECT 1 FROM pg_constraint
38
+ WHERE conrelid = 'canonical_tasks'::regclass
39
+ AND conname = 'canonical_tasks_record_kind_check'
40
+ ) THEN
41
+ ALTER TABLE canonical_tasks
42
+ ADD CONSTRAINT canonical_tasks_record_kind_check
43
+ CHECK (record_kind IN ('work', 'request', 'requirement'));
44
+ END IF;
45
+ END $$;
46
+
47
+ ALTER TABLE canonical_tasks ADD COLUMN IF NOT EXISTS ledger_attributes JSONB;
48
+ ALTER TABLE canonical_tasks ADD COLUMN IF NOT EXISTS ledger_agreed BOOLEAN;
49
+ DO $$
50
+ BEGIN
51
+ IF NOT EXISTS (
52
+ SELECT 1 FROM pg_constraint
53
+ WHERE conrelid = 'canonical_tasks'::regclass
54
+ AND conname = 'canonical_tasks_ledger_agreed_check'
55
+ ) THEN
56
+ ALTER TABLE canonical_tasks ADD CONSTRAINT canonical_tasks_ledger_agreed_check
57
+ CHECK (record_kind = 'requirement' OR ledger_agreed IS NULL) NOT VALID;
58
+ END IF;
59
+ END $$;
60
+
30
61
  -- 何のための仕事か(例: 口コミ)。1 Taskに1つ、未分類はNULL。
31
62
  ALTER TABLE canonical_tasks
32
63
  ADD COLUMN IF NOT EXISTS purpose_label TEXT;
@@ -98,6 +129,8 @@ ALTER TABLE canonical_tasks
98
129
 
99
130
  CREATE INDEX IF NOT EXISTS canonical_tasks_status_priority_idx
100
131
  ON canonical_tasks (status, priority);
132
+ CREATE INDEX IF NOT EXISTS canonical_tasks_ledger_record_kind_idx
133
+ ON canonical_tasks (record_kind, created_at, id) WHERE record_kind <> 'work';
101
134
  CREATE INDEX IF NOT EXISTS canonical_tasks_assignee_due_idx
102
135
  ON canonical_tasks (assignee_person_id, due_at);
103
136
  CREATE INDEX IF NOT EXISTS canonical_tasks_project_codes_idx
@@ -1,4 +1,5 @@
1
1
  import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
2
+ import { isCanonicalTaskRecordKind } from './canonical-task-service.js';
2
3
  const STATUSES = new Set(['pending', 'in_progress', 'waiting', 'completed', 'cancelled']);
3
4
  const PRIORITIES = new Set(['low', 'medium', 'high', 'urgent']);
4
5
  const SEARCH_CURSOR_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
@@ -26,6 +27,7 @@ const MUTABLE_COLUMNS = Object.freeze({
26
27
  });
27
28
  /** Errors that keep their meaning across the store boundary. */
28
29
  const PASSTHROUGH_ERROR_CODES = new Set([
30
+ 'ledger_record_use_ledger_api',
29
31
  'task_not_found',
30
32
  'validation_failed',
31
33
  'version_conflict',
@@ -210,6 +212,10 @@ export class CanonicalTaskPostgresRepository {
210
212
  if (!row)
211
213
  return null;
212
214
  const warnings = [];
215
+ const recordKind = isCanonicalTaskRecordKind(row.record_kind) ? row.record_kind : 'unknown';
216
+ if (recordKind === 'unknown') {
217
+ warnings.push({ code: 'unknown_record_kind', message: 'Unknown Task record kind' });
218
+ }
213
219
  let status = row.status;
214
220
  let priority = row.priority;
215
221
  if (!STATUSES.has(status)) {
@@ -228,6 +234,9 @@ export class CanonicalTaskPostgresRepository {
228
234
  const id = this.encodeTaskId(row);
229
235
  const task = {
230
236
  id,
237
+ record_kind: recordKind,
238
+ ledger_attributes: row.ledger_attributes ?? null,
239
+ ledger_agreed: row.ledger_agreed ?? null,
231
240
  version: Number(row.version ?? 1),
232
241
  title: String(row.title ?? ''),
233
242
  description: row.description ?? null,
@@ -422,6 +431,12 @@ export class CanonicalTaskPostgresRepository {
422
431
  const columns = [
423
432
  ['id', randomUUID()],
424
433
  ['title', input.title],
434
+ ...(input.record_kind !== undefined && input.record_kind !== 'work'
435
+ ? [['record_kind', input.record_kind]] : []),
436
+ ...(input.ledger_attributes != null
437
+ ? [['ledger_attributes', JSON.stringify(input.ledger_attributes), '::jsonb']]
438
+ : []),
439
+ ...(input.ledger_agreed != null ? [['ledger_agreed', input.ledger_agreed]] : []),
425
440
  ['description', input.description ?? null],
426
441
  ['status', input.status],
427
442
  ['priority', input.priority],
@@ -531,13 +546,17 @@ export class CanonicalTaskPostgresRepository {
531
546
  const result = await client.query(`UPDATE canonical_tasks
532
547
  SET ${assignments.join(', ')}, updated_at = NOW()
533
548
  WHERE ${locator.column} = $${locatorParameter}
549
+ AND record_kind = 'work'
534
550
  ${expectedVersion === null ? '' : `AND version = $${versionParameter}`}
535
551
  RETURNING *`, values);
536
552
  if (result.rows[0])
537
553
  return this.normalize(result.rows[0]);
538
- if (expectedVersion !== null) {
539
- const current = await client.query(`SELECT * FROM canonical_tasks WHERE ${locator.column} = $1 LIMIT 1`, [locator.value]);
540
- if (current.rows[0])
554
+ const current = await client.query(`SELECT * FROM canonical_tasks WHERE ${locator.column} = $1 LIMIT 1`, [locator.value]);
555
+ if (current.rows[0]) {
556
+ if (current.rows[0].record_kind !== 'work') {
557
+ throw storeError('ledger_record_use_ledger_api', 'Use the ledger API to mutate this record', 409);
558
+ }
559
+ if (expectedVersion !== null)
541
560
  throw versionConflict(this.normalize(current.rows[0]));
542
561
  }
543
562
  throw notFound();
@@ -583,12 +602,15 @@ export class CanonicalTaskPostgresRepository {
583
602
  if (!Number.isSafeInteger(expectedVersion) || expectedVersion < 1) {
584
603
  throw storeError('validation_failed', 'Expected Task version is required', 422);
585
604
  }
586
- const result = await this.query(`DELETE FROM canonical_tasks WHERE ${locator.column} = $1 AND version = $2 RETURNING id`, [locator.value, expectedVersion]);
605
+ const result = await this.query(`DELETE FROM canonical_tasks WHERE ${locator.column} = $1 AND version = $2 AND record_kind = 'work' RETURNING id`, [locator.value, expectedVersion]);
587
606
  if (result.rows[0])
588
607
  return;
589
608
  const currentTask = await this.get(taskId);
590
609
  if (!currentTask)
591
610
  throw notFound();
611
+ if (currentTask.record_kind !== 'work') {
612
+ throw storeError('ledger_record_use_ledger_api', 'Use the ledger API to mutate this record', 409);
613
+ }
592
614
  throw versionConflict(currentTask);
593
615
  }
594
616
  }
@@ -20,8 +20,15 @@ export interface CanonicalTaskCompletionContract {
20
20
  condition: string;
21
21
  }>;
22
22
  }
23
+ export type CanonicalTaskRecordKind = 'work' | 'request' | 'requirement';
24
+ export declare function isCanonicalTaskRecordKind(value: unknown): value is CanonicalTaskRecordKind;
23
25
  export interface CanonicalTaskRecord extends JsonRecord {
24
26
  id: string;
27
+ /** Optional for older repository implementations; public responses always include it. */
28
+ record_kind?: CanonicalTaskRecordKind | 'unknown';
29
+ ledger_attributes?: JsonRecord | null;
30
+ /** NULL is unrecorded and must not be interpreted as false. */
31
+ ledger_agreed?: boolean | null;
25
32
  version: number;
26
33
  title: string;
27
34
  description?: string | null;
@@ -45,6 +52,10 @@ export interface CanonicalTaskRecord extends JsonRecord {
45
52
  web_url?: string | null;
46
53
  }
47
54
  export interface CanonicalTaskCreateInput extends JsonRecord {
55
+ record_kind?: CanonicalTaskRecordKind;
56
+ /** Host policy validates kind-specific keys and authority to set agreement. */
57
+ ledger_attributes?: JsonRecord | null;
58
+ ledger_agreed?: boolean | null;
48
59
  completion_contract?: unknown;
49
60
  title: string;
50
61
  description?: string | null;
@@ -285,6 +296,7 @@ export declare class CanonicalTaskService {
285
296
  }>;
286
297
  private versionedMutation;
287
298
  private normalizeCreateInput;
299
+ private assertGeneralMutationAllowed;
288
300
  private normalizeUpdateInput;
289
301
  private normalizeListFilters;
290
302
  private normalizeSearchFilters;
@@ -1,6 +1,9 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { canTransitionCanonicalTaskStatus, hasInvalidCanonicalTaskProjectCode, isCanonicalTaskPriority, isCanonicalTaskStatus, normalizeCanonicalTaskProjectCodes, } from './canonical-task-contract.js';
3
3
  import { normalizeCanonicalTaskPrincipal, principalNamespace, } from './canonical-task-principal.js';
4
+ export function isCanonicalTaskRecordKind(value) {
5
+ return value === 'work' || value === 'request' || value === 'requirement';
6
+ }
4
7
  export class CanonicalTaskError extends Error {
5
8
  code;
6
9
  status;
@@ -24,9 +27,13 @@ const MAX_TITLE_LENGTH = 200;
24
27
  const MAX_SEARCH_LENGTH = 200;
25
28
  const DEFAULT_LIMIT = 20;
26
29
  const MAX_LIMIT = 100;
27
- const MAX_SOURCE_REFS_APPEND_JSON_DEPTH = 128;
30
+ const MAX_JSON_DEPTH = 128;
31
+ const MAX_LEDGER_ATTRIBUTES_JSON_BYTES = 64 * 1024;
28
32
  const RESERVED_IDEMPOTENCY_PREFIXES = ['api:', 'workflow:'];
29
33
  const CREATE_FIELDS = new Set([
34
+ 'record_kind',
35
+ 'ledger_attributes',
36
+ 'ledger_agreed',
30
37
  'completion_contract',
31
38
  'title',
32
39
  'description',
@@ -194,7 +201,7 @@ function assertJsonValue(value, field, ancestors = new Set(), depth = 0) {
194
201
  if (typeof value !== 'object') {
195
202
  fail('validation_error', `${field} must contain JSON-serializable values`, 400, { field });
196
203
  }
197
- if (depth >= MAX_SOURCE_REFS_APPEND_JSON_DEPTH) {
204
+ if (depth >= MAX_JSON_DEPTH) {
198
205
  fail('validation_error', `${field} exceeds the maximum JSON nesting depth`, 400, { field });
199
206
  }
200
207
  if (ancestors.has(value)) {
@@ -459,7 +466,12 @@ export class CanonicalTaskService {
459
466
  await this.assertMutationReady();
460
467
  await this.authorize('create', normalizedContext, undefined, payload);
461
468
  const operation = operationKey(normalizedContext, clientKey, 'api:');
462
- const inputFingerprint = fingerprint(payload);
469
+ // Preserve pre-record-kind create fingerprints, including persisted replays.
470
+ // Explicit work and omitted work describe the same command.
471
+ const fingerprintPayload = { ...payload };
472
+ if (fingerprintPayload.record_kind === 'work')
473
+ delete fingerprintPayload.record_kind;
474
+ const inputFingerprint = fingerprint(fingerprintPayload);
463
475
  const recover = async () => {
464
476
  await this.assertMutationReady();
465
477
  const existing = await this.read(() => this.repository.findByIdempotencyKey(operation, ...this.scopeArgs(normalizedContext)));
@@ -593,6 +605,7 @@ export class CanonicalTaskService {
593
605
  task = await this.read(() => this.repository.get(normalizedId, ...this.scopeArgs(normalizedContext)));
594
606
  if (task) {
595
607
  await this.authorize('delete', normalizedContext, task);
608
+ this.assertGeneralMutationAllowed(task);
596
609
  this.assertVersion(task, version);
597
610
  }
598
611
  }
@@ -601,6 +614,7 @@ export class CanonicalTaskService {
601
614
  if (!task)
602
615
  throw new CanonicalTaskError('task_not_found', 'Task was not found', 404, { task_id: normalizedId });
603
616
  await this.authorize('delete', normalizedContext, task);
617
+ this.assertGeneralMutationAllowed(task);
604
618
  this.assertVersion(task, version);
605
619
  }
606
620
  // The client key identifies the delete command. The task/version claim is
@@ -634,6 +648,7 @@ export class CanonicalTaskService {
634
648
  if (!current)
635
649
  throw new CanonicalTaskError('task_not_found', 'Task was not found', 404, { task_id: normalizedId });
636
650
  await this.authorize('delete', normalizedContext, current);
651
+ this.assertGeneralMutationAllowed(current);
637
652
  this.assertVersion(current, version);
638
653
  task = current;
639
654
  return {
@@ -668,6 +683,7 @@ export class CanonicalTaskService {
668
683
  // Recheck the current policy at the destructive boundary so a revoked
669
684
  // actor cannot delete a task using a previously prepared authorization.
670
685
  await this.authorize('delete', normalizedContext, taskToRemove);
686
+ this.assertGeneralMutationAllowed(taskToRemove);
671
687
  this.assertVersion(taskToRemove, version);
672
688
  await this.read(() => this.repository.delete(normalizedId, version, ...this.scopeArgs(normalizedContext)));
673
689
  };
@@ -690,6 +706,7 @@ export class CanonicalTaskService {
690
706
  throw new CanonicalTaskError('task_not_found', 'Task was not found', 404);
691
707
  }
692
708
  await this.authorize('delete', normalizedContext, taskSnapshot);
709
+ this.assertGeneralMutationAllowed(taskSnapshot);
693
710
  };
694
711
  let deleted;
695
712
  if (this.operationRepository?.executePreparedDelete) {
@@ -760,6 +777,9 @@ export class CanonicalTaskService {
760
777
  if (!current)
761
778
  throw new CanonicalTaskError('task_not_found', 'Task was not found', 404, { task_id: taskId });
762
779
  await this.authorize(input.action, input.context, current, input.patch);
780
+ // Reject known ledger records before claiming a coordinated operation.
781
+ // PostgreSQL also checks the kind in the UPDATE to close concurrent changes.
782
+ this.assertGeneralMutationAllowed(current);
763
783
  const operation = operationKey(input.context, `${taskId}:${expectedVersion}`, `${input.action}:`);
764
784
  const mutationTimestamp = this.clock().toISOString();
765
785
  const patch = {
@@ -804,6 +824,7 @@ export class CanonicalTaskService {
804
824
  if (!latest)
805
825
  throw new CanonicalTaskError('task_not_found', 'Task was not found', 404, { task_id: taskId });
806
826
  await this.authorize(input.action, input.context, latest, input.patch);
827
+ this.assertGeneralMutationAllowed(latest);
807
828
  if (wasApplied(latest))
808
829
  return { recovered: true, result: this.normalizeResponse(latest) };
809
830
  this.assertVersion(latest, expectedVersion);
@@ -820,6 +841,7 @@ export class CanonicalTaskService {
820
841
  const latest = await this.read(() => this.repository.get(taskId, ...this.scopeArgs(input.context)));
821
842
  if (!latest)
822
843
  throw new CanonicalTaskError('task_not_found', 'Task was not found', 404, { task_id: taskId });
844
+ this.assertGeneralMutationAllowed(latest);
823
845
  if (wasApplied(latest))
824
846
  return this.normalizeResponse(latest);
825
847
  this.assertVersion(latest, expectedVersion);
@@ -884,6 +906,26 @@ export class CanonicalTaskService {
884
906
  const unknownFields = Object.keys(input).filter((field) => !CREATE_FIELDS.has(field));
885
907
  if (unknownFields.length > 0)
886
908
  fail('validation_error', 'Task input contains unsupported fields', 400, { fields: unknownFields });
909
+ const recordKind = input.record_kind === undefined ? 'work' : input.record_kind;
910
+ if (!isCanonicalTaskRecordKind(recordKind))
911
+ fail('validation_error', 'record_kind is invalid', 400, { field: 'record_kind' });
912
+ for (const field of ['ledger_attributes', 'ledger_agreed']) {
913
+ if (recordKind === 'work' && Object.prototype.hasOwnProperty.call(input, field)) {
914
+ fail('validation_error', `${field} requires a ledger record`, 400, { field });
915
+ }
916
+ }
917
+ if (input.ledger_attributes != null && !isPlainJsonObject(input.ledger_attributes)) {
918
+ fail('validation_error', 'ledger_attributes must be an object', 400, { field: 'ledger_attributes' });
919
+ }
920
+ if (input.ledger_attributes != null) {
921
+ assertJsonValue(input.ledger_attributes, 'ledger_attributes');
922
+ if (Buffer.byteLength(JSON.stringify(input.ledger_attributes), 'utf8') > MAX_LEDGER_ATTRIBUTES_JSON_BYTES) {
923
+ fail('validation_error', 'ledger_attributes exceeds the maximum JSON size', 400, { field: 'ledger_attributes' });
924
+ }
925
+ }
926
+ if (input.ledger_agreed != null && (typeof input.ledger_agreed !== 'boolean' || recordKind !== 'requirement')) {
927
+ fail('validation_error', 'ledger_agreed requires a requirement and a boolean or null', 400, { field: 'ledger_agreed' });
928
+ }
887
929
  const title = normalizeString(input.title, 'title', { required: true, max: MAX_TITLE_LENGTH });
888
930
  const priority = input.priority == null || input.priority === '' ? 'medium' : String(input.priority);
889
931
  if (!isCanonicalTaskPriority(priority))
@@ -892,6 +934,9 @@ export class CanonicalTaskService {
892
934
  const waitingOnPersonId = normalizeWaitingOnPersonId(input.waiting_on_person_id);
893
935
  const completionContract = normalizeCompletionContract(input.completion_contract);
894
936
  return {
937
+ record_kind: recordKind,
938
+ ...(input.ledger_attributes != null ? { ledger_attributes: input.ledger_attributes } : {}),
939
+ ...(input.ledger_agreed != null ? { ledger_agreed: input.ledger_agreed } : {}),
895
940
  ...(completionContract ? { completion_contract: completionContract } : {}),
896
941
  title,
897
942
  description: normalizeString(input.description, 'description', { max: 10000, multiline: true }),
@@ -908,6 +953,13 @@ export class CanonicalTaskService {
908
953
  ...(waitingOnPersonId ? { waiting_on_person_id: waitingOnPersonId } : {}),
909
954
  };
910
955
  }
956
+ assertGeneralMutationAllowed(task) {
957
+ // Older host repositories may omit the field. They keep their historical
958
+ // mutation behavior; the PostgreSQL adapter rejects every persisted non-work value.
959
+ if (task.record_kind !== undefined && task.record_kind !== 'work') {
960
+ fail('ledger_record_use_ledger_api', 'Use the ledger API to mutate this record', 409);
961
+ }
962
+ }
911
963
  normalizeUpdateInput(input) {
912
964
  if (!input || typeof input !== 'object')
913
965
  fail('validation_error', 'Task update is required');
@@ -1111,6 +1163,10 @@ export class CanonicalTaskService {
1111
1163
  catch (error) {
1112
1164
  if (error instanceof CanonicalTaskError)
1113
1165
  throw error;
1166
+ if (error && typeof error === 'object'
1167
+ && error.code === 'ledger_record_use_ledger_api') {
1168
+ throw new CanonicalTaskError('ledger_record_use_ledger_api', 'Use the ledger API to mutate this record', 409);
1169
+ }
1114
1170
  // Keep the fail-closed backend selection contract observable to the
1115
1171
  // host boundary while still hiding arbitrary storage details.
1116
1172
  if (error && typeof error === 'object'
@@ -1122,6 +1178,14 @@ export class CanonicalTaskService {
1122
1178
  }
1123
1179
  normalizeResponse(task) {
1124
1180
  const response = { ...task };
1181
+ if (!isCanonicalTaskRecordKind(response.record_kind)) {
1182
+ response.record_kind = 'unknown';
1183
+ const warnings = Array.isArray(response.normalization_warnings) ? [...response.normalization_warnings] : [];
1184
+ if (!warnings.some((warning) => warningCode(warning) === 'unknown_record_kind')) {
1185
+ warnings.push({ code: 'unknown_record_kind', message: 'Unknown Task record kind' });
1186
+ }
1187
+ response.normalization_warnings = warnings;
1188
+ }
1125
1189
  delete response._payload_fingerprint;
1126
1190
  delete response._last_operation_key;
1127
1191
  delete response._last_operation_fingerprint;
@@ -193,6 +193,13 @@ async function requestEmbeddings(config, texts, deadline) {
193
193
  throw new EmbeddingProviderError('embedding_request_failed', 'embedding service request failed');
194
194
  }
195
195
  if (!Number.isInteger(response.status) || response.status < 200 || response.status >= 300) {
196
+ // Surface an exhausted embedding balance distinctly so Graph search can tell
197
+ // the owner that semantic retrieval is temporarily down for a billing reason,
198
+ // not a malformed request. The quota signal is either HTTP 402 or an explicit
199
+ // `embedding_provider_quota_exhausted` body code. Never echo the body itself.
200
+ if (response.status === 402 || await errorBodyCode(response, deadline) === 'embedding_provider_quota_exhausted') {
201
+ throw new EmbeddingProviderError('embedding_provider_quota_exhausted', 'the embedding provider prepaid balance is exhausted; semantic Graph search will work again once the balance is restored. Use resolve_entity or get_entity for known identifiers meanwhile');
202
+ }
196
203
  throw new EmbeddingProviderError('embedding_request_failed', `embedding service returned HTTP ${Number.isInteger(response.status) ? response.status : 'an invalid status'}`);
197
204
  }
198
205
  let raw;
@@ -213,6 +220,27 @@ async function requestEmbeddings(config, texts, deadline) {
213
220
  }
214
221
  return validateEmbeddingResponse(parsed, texts.length);
215
222
  }
223
+ /**
224
+ * Best-effort read of a failed response's `code` field. The error body may be
225
+ * absent, oversized, or non-JSON; any failure is swallowed because the HTTP
226
+ * status is still actionable on its own. The body text is never surfaced.
227
+ */
228
+ async function errorBodyCode(response, deadline) {
229
+ let raw;
230
+ try {
231
+ raw = await withDeadline(readResponseText(response), deadline);
232
+ }
233
+ catch {
234
+ return undefined;
235
+ }
236
+ try {
237
+ const parsed = JSON.parse(raw);
238
+ return isRecord(parsed) && typeof parsed.code === 'string' ? parsed.code : undefined;
239
+ }
240
+ catch {
241
+ return undefined;
242
+ }
243
+ }
216
244
  function createDeadline(timeoutMs) {
217
245
  return { controller: new AbortController(), expiresAt: Date.now() + timeoutMs, timeoutMs };
218
246
  }
@@ -5,6 +5,7 @@ export type GraphEmbeddingFetchResponse = {
5
5
  readonly ok?: boolean;
6
6
  readonly status?: number;
7
7
  json(): Promise<unknown>;
8
+ text?(): Promise<string>;
8
9
  };
9
10
  export type GraphEmbeddingFetch = (input: string, init: {
10
11
  method: 'POST';
@@ -25,14 +26,30 @@ export interface GraphEmbeddingProvider {
25
26
  readonly dimensions: number;
26
27
  embed(texts: string[], kind: GraphEmbeddingKind): Promise<number[][]>;
27
28
  }
29
+ export type GraphEmbeddingProviderErrorSummary = {
30
+ readonly upstreamStatus?: string;
31
+ readonly upstreamMessage?: string;
32
+ readonly detail?: string;
33
+ };
34
+ type GraphEmbeddingProviderErrorDetails = {
35
+ readonly upstreamStatus?: string;
36
+ readonly upstreamMessage?: string;
37
+ readonly detail?: string;
38
+ };
28
39
  export declare class GraphEmbeddingProviderError extends Error {
29
40
  readonly code: string;
30
41
  status?: number;
31
- constructor(code: string, message: string, status?: number);
42
+ readonly upstreamStatus?: string;
43
+ readonly upstreamMessage?: string;
44
+ readonly detail?: string;
45
+ constructor(code: string, message: string, status?: number, details?: GraphEmbeddingProviderErrorDetails);
32
46
  }
47
+ export declare function sanitizeEmbeddingProviderErrorText(text: string, secrets?: string[]): string;
48
+ export declare function summarizeEmbeddingProviderErrorBody(httpStatus: number | undefined, body: string | unknown, secrets?: string[]): GraphEmbeddingProviderErrorSummary;
33
49
  /**
34
50
  * Create the server-side Gemini embedding boundary used by Graph vector
35
51
  * indexing and query retrieval. The queue and cache belong to this provider
36
52
  * instance, which should be shared by the server process.
37
53
  */
38
54
  export declare function createGraphEmbeddingProvider({ apiKey, fetchImpl, timeoutMs, queueTimeoutMs, queryCacheTtlMs, queryCacheMaxEntries, }?: GraphEmbeddingProviderOptions): GraphEmbeddingProvider;
55
+ export {};
@@ -22,19 +22,128 @@ const MAX_REQUEST_TIMEOUT_MS = 15_000;
22
22
  const MAX_QUEUE_SIZE = 16;
23
23
  const MAX_CACHE_ENTRIES = 256;
24
24
  const DEFAULT_CACHE_TTL_MS = 60_000;
25
+ const MAX_ERROR_BODY_READ_MS = 2_000;
26
+ const MAX_ERROR_DETAIL_LENGTH = 500;
27
+ const REDACTED = '[REDACTED]';
25
28
  export class GraphEmbeddingProviderError extends Error {
26
29
  code;
27
30
  status;
28
- constructor(code, message, status) {
31
+ upstreamStatus;
32
+ upstreamMessage;
33
+ detail;
34
+ constructor(code, message, status, details = {}) {
29
35
  super(message);
30
36
  this.name = 'GraphEmbeddingProviderError';
31
37
  this.code = code;
32
38
  if (Number.isInteger(status))
33
39
  this.status = status;
40
+ if (details.upstreamStatus)
41
+ this.upstreamStatus = details.upstreamStatus;
42
+ if (details.upstreamMessage)
43
+ this.upstreamMessage = details.upstreamMessage;
44
+ if (details.detail)
45
+ this.detail = details.detail;
34
46
  }
35
47
  }
36
- function providerError(code, message, status) {
37
- return new GraphEmbeddingProviderError(code, message, status);
48
+ function providerError(code, message, status, details) {
49
+ return new GraphEmbeddingProviderError(code, message, status, details);
50
+ }
51
+ function collapseErrorWhitespace(text) {
52
+ return text.replace(/\s+/g, ' ').trim();
53
+ }
54
+ function truncateErrorText(text) {
55
+ return text.length > MAX_ERROR_DETAIL_LENGTH
56
+ ? `${text.slice(0, MAX_ERROR_DETAIL_LENGTH)}…`
57
+ : text;
58
+ }
59
+ function redactErrorText(text, secrets) {
60
+ let result = text.replace(/AIza[0-9A-Za-z_-]{30,}/g, REDACTED);
61
+ result = result.replace(/(x-goog-api-key)(\s*["']?\s*[:=]?\s*["']?)([^\s"',;]+)/gi, (_match, name) => `${name}: ${REDACTED}`);
62
+ result = result.replace(/(authorization)(\s*["']?\s*[:=]?\s*["']?\s*)((?:bearer|basic)\s+)?[^\s"',;]+/gi, (_match, name) => `${name}: ${REDACTED}`);
63
+ result = result.replace(/([?&]key=)[^&\s"'#]+/gi, (_match, prefix) => `${prefix}${REDACTED}`);
64
+ for (const secret of secrets) {
65
+ if (secret)
66
+ result = result.split(secret).join(REDACTED);
67
+ }
68
+ return result;
69
+ }
70
+ export function sanitizeEmbeddingProviderErrorText(text, secrets = []) {
71
+ const normalizedSecrets = secrets.filter(secret => secret.length > 0);
72
+ const redacted = redactErrorText(text, normalizedSecrets);
73
+ const truncated = truncateErrorText(redacted);
74
+ const boundarySafe = redactErrorText(truncated, normalizedSecrets)
75
+ .replace(/AIza[0-9A-Za-z_-]+/g, fragment => fragment.length >= 8 ? REDACTED : fragment);
76
+ return truncateErrorText(boundarySafe);
77
+ }
78
+ function extractUpstreamError(body) {
79
+ if (typeof body === 'string') {
80
+ const trimmed = body.trim();
81
+ if (trimmed) {
82
+ try {
83
+ const parsed = JSON.parse(trimmed);
84
+ const extracted = extractUpstreamError(parsed);
85
+ if (extracted.status || extracted.message)
86
+ return extracted;
87
+ }
88
+ catch {
89
+ // Not JSON; use the raw text below.
90
+ }
91
+ }
92
+ return { message: collapseErrorWhitespace(body) };
93
+ }
94
+ if (body && typeof body === 'object') {
95
+ const error = body.error;
96
+ if (error && typeof error === 'object') {
97
+ const { status, message } = error;
98
+ return {
99
+ status: typeof status === 'string' && status.trim() ? status : undefined,
100
+ message: typeof message === 'string' && message.trim() ? message : undefined,
101
+ };
102
+ }
103
+ if (typeof error === 'string' && error.trim())
104
+ return { message: error };
105
+ }
106
+ return {};
107
+ }
108
+ export function summarizeEmbeddingProviderErrorBody(httpStatus, body, secrets = []) {
109
+ const extracted = extractUpstreamError(body);
110
+ const upstreamStatus = extracted.status
111
+ ? sanitizeEmbeddingProviderErrorText(collapseErrorWhitespace(extracted.status), secrets)
112
+ : undefined;
113
+ const upstreamMessage = extracted.message
114
+ ? sanitizeEmbeddingProviderErrorText(collapseErrorWhitespace(extracted.message), secrets)
115
+ : undefined;
116
+ const httpPart = Number.isInteger(httpStatus) ? `HTTP ${httpStatus}` : '';
117
+ const prefix = [httpPart, upstreamStatus].filter((part) => Boolean(part)).join(' ');
118
+ const summary = [prefix, upstreamMessage].filter((part) => Boolean(part)).join(': ');
119
+ return {
120
+ upstreamStatus,
121
+ upstreamMessage,
122
+ detail: summary ? sanitizeEmbeddingProviderErrorText(summary, secrets) : undefined,
123
+ };
124
+ }
125
+ const UNREAD_ERROR_BODY = Symbol('unread-error-body');
126
+ async function readEmbeddingProviderErrorBody(response) {
127
+ let timer;
128
+ const readText = response.text;
129
+ const bodyPromise = typeof readText === 'function'
130
+ ? Promise.resolve().then(() => readText.call(response))
131
+ : Promise.resolve().then(() => response.json());
132
+ const timeoutPromise = new Promise(resolve => {
133
+ timer = setTimeout(() => resolve(UNREAD_ERROR_BODY), MAX_ERROR_BODY_READ_MS);
134
+ timer.unref?.();
135
+ });
136
+ try {
137
+ const value = await Promise.race([bodyPromise, timeoutPromise]);
138
+ return value === UNREAD_ERROR_BODY ? undefined : { value };
139
+ }
140
+ catch {
141
+ return undefined;
142
+ }
143
+ finally {
144
+ if (timer !== undefined)
145
+ clearTimeout(timer);
146
+ }
38
147
  }
39
148
  function boundedInteger(value, fallback, minimum, maximum, code) {
40
149
  if (value === undefined)
@@ -266,7 +375,16 @@ export function createGraphEmbeddingProvider({ apiKey = process.env.BRAINBASE_EM
266
375
  signalState.cleanup();
267
376
  }
268
377
  if (!response || response.ok !== true) {
269
- throw providerError('embedding_provider_http_error', `Embedding provider request failed (HTTP ${Number.isInteger(response?.status) ? response?.status : 0})`, Number.isInteger(response?.status) ? response?.status : undefined);
378
+ const httpStatus = Number.isInteger(response?.status) ? response?.status : undefined;
379
+ const message = `Embedding provider request failed (HTTP ${httpStatus ?? 0})`;
380
+ const body = response ? await readEmbeddingProviderErrorBody(response) : undefined;
381
+ // Hide identifiable echoed caller text and the configured key without
382
+ // over-redacting short common words in the upstream message.
383
+ const secrets = [normalizedApiKey, ...texts.filter(text => text.length >= 20)];
384
+ const summary = body
385
+ ? summarizeEmbeddingProviderErrorBody(httpStatus, body.value, secrets)
386
+ : undefined;
387
+ throw providerError('embedding_provider_http_error', summary?.detail ? `${message}: ${summary.detail}` : message, httpStatus, summary);
270
388
  }
271
389
  let result;
272
390
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unson/brainbase-mcp",
3
- "version": "0.47.5",
3
+ "version": "0.48.0",
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",
@@ -624,5 +624,5 @@
624
624
  "url": "https://github.com/Unson-LLC/brainbase/issues"
625
625
  },
626
626
  "homepage": "https://github.com/Unson-LLC/brainbase#readme",
627
- "gitHead": "58653c598fd801e609c9e9627fbfaf8715081ad5"
627
+ "gitHead": "3f6256529785b9638eeaa75d2810a1d26e75782a"
628
628
  }
@@ -14,7 +14,7 @@ import {
14
14
  workspaceNotice,
15
15
  workspacePageHeader,
16
16
  workspaceSectionTitle,
17
- workspaceHelp, workspaceDialog, workspaceDisclosure, workspaceErrorCard, workspaceLoadingCard, workspaceDismissNotification,
17
+ workspaceHelp, workspaceDialog, workspaceDisclosure, workspaceErrorCard, workspaceLoadingCard, workspaceLoadingStage, workspaceDismissNotification,
18
18
  } from './workspace-kit.js';
19
19
 
20
20
  export const FOUNDATION_OVERVIEW_CONTRACT_VERSION = 'foundation-overview.v1';
@@ -920,7 +920,11 @@ export function renderFoundationOverview(root, state, {
920
920
  else surface.append(workspaceErrorCard(doc, notice));
921
921
  };
922
922
  if (state.status === 'loading') {
923
- root.append(surface); renderLoadingState(doc, root, viewState, true, onLoading); return surface;
923
+ surface.append(workspaceLoadingStage(doc, { title: '目的と現状を準備しています' }));
924
+ root.append(surface);
925
+ // The stage says it in the page; close any old floating loading card.
926
+ renderLoadingState(doc, root, viewState, false, onLoading);
927
+ return surface;
924
928
  }
925
929
  if (state.status !== 'ready') {
926
930
  notify({ title: '取得失敗', message: `${state.error?.message ?? '目的・哲学・世界モデルを確認できません。'} 登録なし・0件として表示していません。`, onRetry: callbacks.load });
@@ -1002,7 +1006,14 @@ export function renderFoundationCollectionOverview(root, sources, {
1002
1006
  });
1003
1007
  root.append(mount);
1004
1008
  }
1005
- renderLoadingState(doc, root, viewState, sources.some(source => source.state.status === 'loading'), onLoading);
1009
+ const loading = sources.some(source => source.state.status === 'loading');
1010
+ if (loading && ready === 0) {
1011
+ // The stage says it in the page; close any old floating loading card.
1012
+ renderLoadingState(doc, root, viewState, false, onLoading);
1013
+ root.append(workspaceLoadingStage(doc, { title: '目的と現状を準備しています' }));
1014
+ } else {
1015
+ renderLoadingState(doc, root, viewState, loading, onLoading);
1016
+ }
1006
1017
  return root;
1007
1018
  }
1008
1019