@unson/brainbase-mcp 0.50.30 → 0.51.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.
Files changed (56) hide show
  1. package/contracts/canonical-task/store-schema.sql +3 -0
  2. package/dist/automation-run.js +3 -2
  3. package/dist/canonical-task-postgres.js +3 -0
  4. package/dist/canonical-task-service.d.ts +6 -0
  5. package/dist/canonical-task-service.js +40 -1
  6. package/dist/company-os-learning-adoption.d.ts +9 -0
  7. package/dist/company-os-learning-adoption.js +50 -1
  8. package/dist/durable-waits.d.ts +30 -0
  9. package/dist/durable-waits.js +100 -94
  10. package/dist/foundation-public-provider.d.ts +3 -1
  11. package/dist/foundation-public-provider.js +2 -2
  12. package/dist/graph-corrections.d.ts +46 -1
  13. package/dist/graph-corrections.js +172 -1
  14. package/dist/judgment-event-outbox.d.ts +24 -2
  15. package/dist/judgment-event-outbox.js +92 -10
  16. package/dist/judgment-frame.js +2 -2
  17. package/dist/judgment-host.d.ts +4 -1
  18. package/dist/judgment-host.js +126 -14
  19. package/dist/judgment-task-progress.d.ts +41 -0
  20. package/dist/judgment-task-progress.js +18 -0
  21. package/dist/knowledge-continuation.js +7 -1
  22. package/dist/knowledge-lookup.js +43 -58
  23. package/dist/mcp-runtime.d.ts +9 -0
  24. package/dist/mcp-runtime.js +12 -4
  25. package/dist/meeting-automation-runtime.d.ts +52 -0
  26. package/dist/meeting-automation-runtime.js +46 -0
  27. package/dist/queue-task-tools.js +2 -2
  28. package/dist/routine-liveness.js +0 -1
  29. package/dist/routine-runtime.js +1 -1
  30. package/dist/server.d.ts +59 -85
  31. package/dist/server.js +44 -36
  32. package/dist/ssot.js +1 -1
  33. package/dist/testing/queue-task-tools-contract.js +1 -1
  34. package/dist/world-model-impact-index.d.ts +132 -0
  35. package/dist/world-model-impact-index.js +901 -0
  36. package/package.json +6 -18
  37. package/ui/README.md +31 -0
  38. package/ui/graph-own-share.js +106 -50
  39. package/ui/graph-projects-view.js +4 -4
  40. package/ui/graph-view-shared.css +3 -0
  41. package/ui/judgment-history.css +13 -0
  42. package/ui/objective-editor.css +19 -2
  43. package/ui/objective-editor.js +6 -3
  44. package/ui/project-workspace.css +33 -26
  45. package/ui/workspace-kit.css +141 -0
  46. package/ui/workspace-kit.js +59 -8
  47. package/ui/world/world-view.css +65 -46
  48. package/ui/world/world-view.js +28 -19
  49. package/dist/execution-authority-http.d.ts +0 -30
  50. package/dist/execution-authority-http.js +0 -454
  51. package/dist/execution-authority.d.ts +0 -282
  52. package/dist/execution-authority.js +0 -867
  53. package/dist/resource-reservation-http.d.ts +0 -31
  54. package/dist/resource-reservation-http.js +0 -371
  55. package/dist/resource-reservations.d.ts +0 -221
  56. package/dist/resource-reservations.js +0 -577
@@ -1,4 +1,5 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
+ import { execFileSync } from 'node:child_process';
2
3
  import { closeSync, constants as fsConstants, fsyncSync, linkSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
3
4
  import { homedir } from 'node:os';
4
5
  import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
@@ -8,6 +9,7 @@ import { containsJudgmentFrameCredential } from './judgment-frame.js';
8
9
  import { canonicalJson } from './judgment-resolution-contract.js';
9
10
  import { AUDIT_LINE_STRIP_PREFIX, COMPACT_FOUR_BLOCK_GATE_PROMPT_V2, COMPACT_FOUR_BLOCK_GATE_PROMPT_V3, REASONING_GATE_MODES, resolveReasoningGateMode, shouldApplyReasoningGate } from './judgment-reasoning-gate-prompt.js';
10
11
  import { DEFAULT_SESSION_WORLD_MODEL_UPDATE_TIMEOUT_MS, SESSION_MINI_WORLD_MODEL_SCHEMA_VERSION_V2, SESSION_WORLD_MODEL_FILENAME, SESSION_WORLD_MODEL_LOCK_FILENAME, WM_V2_LIMITS, parseSessionMiniWorldModelV2, readSessionMiniWorldModelV2, renderSessionMiniWorldModelPinV2, sessionWorldModelPaths, toLearningCandidateEvidenceDraftFromSessionWMV2, withSessionWorldModelLock, writeSessionMiniWorldModelV2 } from './judgment-session-world-model.js';
12
+ import { taskProgressScopeSchema, taskProgressObservationSchema } from './judgment-task-progress.js';
11
13
  export { AUDIT_LINE_STRIP_PREFIX, COMPACT_FOUR_BLOCK_GATE_PROMPT_V2, COMPACT_FOUR_BLOCK_GATE_PROMPT_V3, DEFAULT_SESSION_WORLD_MODEL_UPDATE_TIMEOUT_MS, REASONING_GATE_MODES, SESSION_MINI_WORLD_MODEL_SCHEMA_VERSION_V2, SESSION_WORLD_MODEL_FILENAME, SESSION_WORLD_MODEL_LOCK_FILENAME, WM_V2_LIMITS, parseSessionMiniWorldModelV2, readSessionMiniWorldModelV2, renderSessionMiniWorldModelPinV2, resolveReasoningGateMode, sessionWorldModelPaths, shouldApplyReasoningGate, toLearningCandidateEvidenceDraftFromSessionWMV2, withSessionWorldModelLock, writeSessionMiniWorldModelV2 };
12
14
  const DEFAULT_HOST_BINDING = Object.freeze({
13
15
  adapter_id: 'brainbase-local',
@@ -247,22 +249,26 @@ function readCanonicalTranscript(payload, env, trustedConversationMessages) {
247
249
  };
248
250
  }
249
251
  function findRepoRoot(start) {
250
- let current = resolve(start);
251
- for (;;) {
252
- try {
253
- statSync(join(current, '.git'));
254
- return current;
255
- }
256
- catch {
257
- const parent = dirname(current);
258
- if (parent === current)
259
- return null;
260
- current = parent;
252
+ try {
253
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')));
254
+ return execFileSync('git', ['-C', resolve(start), 'rev-parse', '--show-toplevel'], {
255
+ encoding: 'utf8',
256
+ env: { ...env, LC_ALL: 'C' },
257
+ timeout: 2000,
258
+ stdio: ['ignore', 'pipe', 'pipe']
259
+ }).replace(/\r?\n$/u, '') || null;
260
+ }
261
+ catch (error) {
262
+ const stderr = error instanceof Error && 'stderr' in error ? String(error.stderr) : '';
263
+ const reason = stderr.includes('dubious ownership') ? 'unsafe_repository'
264
+ : error instanceof Error && 'code' in error && error.code === 'ETIMEDOUT' ? 'timeout' : null;
265
+ if (reason) {
266
+ process.stderr.write(`${JSON.stringify({ event: 'judgment_repository_discovery_failed', reason })}\n`);
261
267
  }
268
+ return null;
262
269
  }
263
270
  }
264
- function instructionBindings(cwd) {
265
- const discoveredRoot = findRepoRoot(cwd);
271
+ function instructionBindings(cwd, discoveredRoot) {
266
272
  if (!discoveredRoot)
267
273
  return [];
268
274
  const root = realpathSync(discoveredRoot);
@@ -432,7 +438,7 @@ export function buildJudgmentRequest(payload, { env = process.env, trustedConver
432
438
  permission_mode: typeof payload.permission_mode === 'string' && payload.permission_mode ? payload.permission_mode : null,
433
439
  project_binding: projectBinding
434
440
  },
435
- instruction_bindings: instructionBindings(cwd),
441
+ instruction_bindings: instructionBindings(cwd, repoRoot),
436
442
  completeness: transcript.complete ? 'complete' : 'partial'
437
443
  };
438
444
  return {
@@ -1216,6 +1222,7 @@ export async function runJudgmentHost(payload, options = {}) {
1216
1222
  request_text_digest: sha256(request.request),
1217
1223
  initial_receipt_digest: sha256(canonicalJson(adoption.receipt)),
1218
1224
  adoption,
1225
+ ...(options.taskProgress ? { task_progress_scope: taskProgressScopeSchema.parse(options.taskProgress.scope) } : {}),
1219
1226
  audit_contract: {
1220
1227
  schema_version: 'brainbase-owner-audit-contract-v1',
1221
1228
  repair_body_policy: 'preserve',
@@ -1519,6 +1526,108 @@ async function autonomyStopSnapshot(payload, env, expectedHostBinding = DEFAULT_
1519
1526
  };
1520
1527
  });
1521
1528
  }
1529
+ async function evaluateTaskProgressStop(payload, env, options) {
1530
+ const { sessionRef, turnId } = hookIdentity(payload);
1531
+ const paths = journalPaths(sessionRef, turnId, env);
1532
+ return withTurnLock(paths.lock, async () => {
1533
+ let episode;
1534
+ try {
1535
+ episode = readEpisode(paths.episode);
1536
+ }
1537
+ catch (error) {
1538
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
1539
+ throw new Error('judgment_orphan_stop');
1540
+ }
1541
+ throw error;
1542
+ }
1543
+ verifyEpisodeAdoption(episode, paths.target, options.expectedHostBinding);
1544
+ if (!episode.task_progress_scope)
1545
+ return null;
1546
+ const scope = taskProgressScopeSchema.parse(episode.task_progress_scope);
1547
+ const adapter = options.taskProgress;
1548
+ if (!adapter || canonicalJson(taskProgressScopeSchema.parse(adapter.scope)) !== canonicalJson(scope)) {
1549
+ throw new Error('judgment_task_progress_binding_changed');
1550
+ }
1551
+ try {
1552
+ readFinal(paths.final);
1553
+ return null;
1554
+ }
1555
+ catch (error) {
1556
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
1557
+ throw error;
1558
+ }
1559
+ const events = readEvents(paths.events);
1560
+ const snapshot = {
1561
+ episode_digest: episode.episode_digest,
1562
+ event_set_digest: sha256(canonicalJson(events)),
1563
+ request: episode.adoption.request.request,
1564
+ events
1565
+ };
1566
+ const scopeRef = sha256(canonicalJson(scope));
1567
+ const directory = join(journalRoot(env), 'task-progress', scopeRef);
1568
+ return withTurnLock(`${directory}.lock`, async () => {
1569
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
1570
+ const entries = readdirSync(directory).sort().map((name) => {
1571
+ const entry = readJsonArtifact(join(directory, name));
1572
+ if (entry.entry_digest !== artifactDigest(entry, 'entry_digest')) {
1573
+ throw new Error('judgment_task_progress_journal_corrupt');
1574
+ }
1575
+ return entry;
1576
+ });
1577
+ let preparationCount = 0;
1578
+ let previousDigest = null;
1579
+ for (const entry of entries) {
1580
+ if (entry.scope_ref !== scopeRef || entry.previous_digest !== previousDigest) {
1581
+ throw new Error('judgment_task_progress_chain_corrupt');
1582
+ }
1583
+ const observation = taskProgressObservationSchema.parse(entry.observation);
1584
+ if (observation.kind === 'preparation_only')
1585
+ preparationCount += 1;
1586
+ if (observation.kind === 'verified_outcome')
1587
+ preparationCount = 0;
1588
+ previousDigest = entry.entry_digest;
1589
+ }
1590
+ const snapshotRef = sha256(canonicalJson({ episode: snapshot.episode_digest, events: snapshot.event_set_digest }));
1591
+ const replay = entries.find((entry) => entry.snapshot_ref === snapshotRef);
1592
+ if (replay) {
1593
+ if (replay.replan_required !== true)
1594
+ return null;
1595
+ throw new Error('judgment_task_progress_replan_requires_new_evidence');
1596
+ }
1597
+ const successfulIds = new Set(events.filter((event) => event.success).map((event) => event.tool_use_id));
1598
+ const observation = taskProgressObservationSchema.parse(await adapter.assess(snapshot));
1599
+ if (observation.kind !== 'waiting'
1600
+ && !observation.evidence_tool_use_ids.every((id) => successfulIds.has(id))) {
1601
+ throw new Error('judgment_task_progress_evidence_not_in_episode');
1602
+ }
1603
+ if (observation.kind === 'verified_outcome') {
1604
+ if (entries.some((entry) => {
1605
+ const prior = taskProgressObservationSchema.parse(entry.observation);
1606
+ return prior.kind === 'verified_outcome' && prior.verification_ref === observation.verification_ref;
1607
+ }))
1608
+ throw new Error('judgment_task_progress_outcome_repeated');
1609
+ if (!await adapter.verifyOutcome({ ...snapshot, observation })) {
1610
+ throw new Error('judgment_task_progress_outcome_unverified');
1611
+ }
1612
+ preparationCount = 0;
1613
+ }
1614
+ if (observation.kind === 'preparation_only')
1615
+ preparationCount += 1;
1616
+ const replanRequired = observation.kind === 'preparation_only' && preparationCount >= 2;
1617
+ const entry = {
1618
+ scope_ref: scopeRef, snapshot_ref: snapshotRef, previous_digest: previousDigest,
1619
+ observation, replan_required: replanRequired
1620
+ };
1621
+ writeImmutableJson(join(directory, `${String(entries.length + 1).padStart(8, '0')}.json`), {
1622
+ ...entry, entry_digest: sha256(canonicalJson(entry))
1623
+ });
1624
+ return replanRequired ? {
1625
+ decision: 'block', block_kind: 'semantic_replan',
1626
+ reason: '同じ完了条件について準備だけの反復を検出しました。資料を増やす継続を止め、業務成果または新しい否定結果を検証できる方針へ切り替えてください。完了・本人受入とは扱いません。'
1627
+ } : null;
1628
+ });
1629
+ });
1630
+ }
1522
1631
  async function evaluateAutonomyStop(payload, env, options) {
1523
1632
  const config = resolveAutonomyMode(options, env);
1524
1633
  if (config.mode === 'off')
@@ -1804,6 +1913,9 @@ export async function processJudgmentHook(payload, options = {}) {
1804
1913
  return event ? { systemMessage: event.display_line } : {};
1805
1914
  }
1806
1915
  if (eventName === 'Stop') {
1916
+ const progressBlock = await evaluateTaskProgressStop(payload, env, options);
1917
+ if (progressBlock)
1918
+ return progressBlock;
1807
1919
  const autonomyBlock = await evaluateAutonomyStop(payload, env, options);
1808
1920
  if (autonomyBlock)
1809
1921
  return autonomyBlock;
@@ -0,0 +1,41 @@
1
+ import { z } from 'zod';
2
+ import type { JudgmentToolEvent } from './judgment-host.js';
3
+ export declare const taskProgressScopeSchema: z.ZodObject<{
4
+ task_ref: z.ZodString;
5
+ criterion_ref: z.ZodString;
6
+ contract_revision: z.ZodString;
7
+ }, z.core.$strict>;
8
+ export declare const taskProgressObservationSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
9
+ kind: z.ZodLiteral<"preparation_only">;
10
+ evidence_tool_use_ids: z.ZodArray<z.ZodString>;
11
+ }, z.core.$strict>, z.ZodObject<{
12
+ kind: z.ZodLiteral<"waiting">;
13
+ }, z.core.$strict>, z.ZodObject<{
14
+ kind: z.ZodLiteral<"verified_outcome">;
15
+ outcome: z.ZodEnum<{
16
+ criterion_advanced: "criterion_advanced";
17
+ new_negative_result: "new_negative_result";
18
+ }>;
19
+ evidence_tool_use_ids: z.ZodArray<z.ZodString>;
20
+ verification_ref: z.ZodString;
21
+ }, z.core.$strict>], "kind">;
22
+ export interface JudgmentTaskProgressSnapshot {
23
+ episode_digest: string;
24
+ event_set_digest: string;
25
+ request: string;
26
+ events: readonly JudgmentToolEvent[];
27
+ }
28
+ /** Host configuration, never fields copied from a model's Stop payload.
29
+ * assess owns semantic classification; verifyOutcome must independently check
30
+ * the actual result against this task/criterion, not accept a declaration.
31
+ * Neither callback is provided by default or invokes a paid model internally.
32
+ */
33
+ export interface JudgmentTaskProgressAdapter {
34
+ scope: z.infer<typeof taskProgressScopeSchema>;
35
+ assess(snapshot: JudgmentTaskProgressSnapshot): Promise<z.infer<typeof taskProgressObservationSchema>>;
36
+ verifyOutcome(snapshot: JudgmentTaskProgressSnapshot & {
37
+ observation: Extract<z.infer<typeof taskProgressObservationSchema>, {
38
+ kind: 'verified_outcome';
39
+ }>;
40
+ }): Promise<boolean>;
41
+ }
@@ -0,0 +1,18 @@
1
+ import { z } from 'zod';
2
+ const reference = z.string().trim().min(1).max(512);
3
+ export const taskProgressScopeSchema = z.object({
4
+ task_ref: reference,
5
+ criterion_ref: reference,
6
+ contract_revision: reference
7
+ }).strict();
8
+ const evidenceIds = z.array(reference).min(1).refine((ids) => new Set(ids).size === ids.length);
9
+ export const taskProgressObservationSchema = z.discriminatedUnion('kind', [
10
+ z.object({ kind: z.literal('preparation_only'), evidence_tool_use_ids: evidenceIds }).strict(),
11
+ z.object({ kind: z.literal('waiting') }).strict(),
12
+ z.object({
13
+ kind: z.literal('verified_outcome'),
14
+ outcome: z.enum(['criterion_advanced', 'new_negative_result']),
15
+ evidence_tool_use_ids: evidenceIds,
16
+ verification_ref: reference
17
+ }).strict()
18
+ ]);
@@ -495,7 +495,13 @@ export function stopKnowledgeLookup(previous, now = Date.now()) {
495
495
  return { state, block: true, reason: knowledgeLookupContext(state) };
496
496
  }
497
497
  export function cancelKnowledgeLookup(previous) {
498
- return terminate(structuredClone(previous), 'user_cancelled', 'cancelled');
498
+ const state = structuredClone(previous);
499
+ // Like a late result or Stop, a cancel never rewrites a finished lookup:
500
+ // its status and termination_reason stay as they were, and cancelling a
501
+ // cancelled lookup again returns it unchanged.
502
+ if (isKnowledgeLookupTerminal(state))
503
+ return state;
504
+ return terminate(state, 'user_cancelled', 'cancelled');
499
505
  }
500
506
  export function knowledgeLookupContext(state) {
501
507
  return `知識取得のHost状態: ${JSON.stringify({
@@ -647,25 +647,6 @@ function unsupported(input, action, error) {
647
647
  error: { code: error.code, message: error.message },
648
648
  };
649
649
  }
650
- function lookupActionVariant(kind, properties, required) {
651
- return {
652
- type: 'object',
653
- properties: {
654
- kind: { const: kind },
655
- ...properties,
656
- required_fields: {
657
- type: 'array',
658
- minItems: 1,
659
- maxItems: MAX_FIELDS,
660
- description: 'Must contain the same public field paths as the top-level required_fields.',
661
- items: { type: 'string', minLength: 1, maxLength: MAX_FIELD_LENGTH },
662
- },
663
- why_different: { type: 'string', minLength: 1, maxLength: MAX_HINT_LENGTH },
664
- },
665
- required: ['kind', ...required],
666
- additionalProperties: false,
667
- };
668
- }
669
650
  export const knowledgeLookupTools = [{
670
651
  name: 'brainbase_knowledge_lookup',
671
652
  description: 'Find and read authorized Graph knowledge by purpose. Each call performs one bounded search, read, relation follow, or finish proposal; project hints never change authorization scope.',
@@ -690,49 +671,53 @@ export const knowledgeLookupTools = [{
690
671
  missing_information: { type: 'array', maxItems: MAX_FIELDS, items: { type: 'string', minLength: 1, maxLength: MAX_HINT_LENGTH } },
691
672
  based_on_attempt_ids: { type: 'array', maxItems: MAX_IDS, items: { type: 'string', minLength: 1, maxLength: 300 } },
692
673
  why_different: { type: 'string', minLength: 1, maxLength: MAX_HINT_LENGTH },
693
- // Each variant lists its own properties. Codex renders only the oneOf
694
- // variants into the model-facing declaration, so properties declared
695
- // beside oneOf are invisible and read/finish calls cannot be written.
674
+ // Keep next_action as a flat portable object schema (no oneOf / const)
675
+ // so Gemini, OpenAI, Claude, and Codex all render every action property.
676
+ // Per-kind required/forbidden fields are enforced at runtime in normalizeAction.
696
677
  next_action: {
697
678
  type: 'object',
698
- oneOf: [
699
- lookupActionVariant('search', {
700
- query: { type: 'string', minLength: 1, maxLength: MAX_TEXT_LENGTH },
701
- entity_types: { type: 'array', maxItems: 10, items: { type: 'string', minLength: 1, maxLength: 100 } },
702
- seed_ids: { type: 'array', minItems: 1, maxItems: MAX_IDS, items: { type: 'string', minLength: 1, maxLength: 1_000 } },
703
- }, []),
704
- lookupActionVariant('read', {
705
- entity_id: { type: 'string', minLength: 1, maxLength: 1_000 },
706
- entity_type: { type: 'string', minLength: 1, maxLength: 100 },
707
- }, ['entity_id', 'entity_type']),
708
- lookupActionVariant('follow_relation', {
709
- seed_ids: { type: 'array', minItems: 1, maxItems: MAX_IDS, items: { type: 'string', minLength: 1, maxLength: 1_000 } },
710
- relation: { type: 'string', minLength: 1, maxLength: MAX_RELATION_LENGTH },
711
- direction: { type: 'string', enum: ['incoming', 'outgoing'] },
712
- target_types: { type: 'array', maxItems: 10, items: { type: 'string', minLength: 1, maxLength: 100 } },
713
- }, ['seed_ids', 'relation', 'direction']),
714
- lookupActionVariant('finish', {
715
- assessment: { type: 'string', enum: ['sufficient', 'insufficient'] },
716
- status: { type: 'string', enum: ['satisfied', 'unresolved', 'needs_user_input'] },
717
- reference_ids: { type: 'array', maxItems: MAX_IDS, items: { type: 'string', minLength: 1, maxLength: 1_000 } },
718
- field_evidence: {
719
- type: 'array',
720
- maxItems: MAX_FIELDS,
721
- items: {
722
- type: 'object',
723
- properties: {
724
- field: { type: 'string', minLength: 1, maxLength: MAX_FIELD_LENGTH },
725
- reference_id: { type: 'string', minLength: 1, maxLength: 1_000 },
726
- attempt_id: { type: 'string', minLength: 1, maxLength: 300 },
727
- },
728
- required: ['field', 'reference_id', 'attempt_id'],
729
- additionalProperties: false,
679
+ description: 'Next bounded action. Supply only fields for the chosen kind: search (query, entity_types, seed_ids), read (required: entity_id, entity_type), follow_relation (required: seed_ids, relation, direction; optional: target_types), or finish (required: assessment, status, reference_ids, field_evidence, unresolved_items, termination_reason).',
680
+ properties: {
681
+ kind: { type: 'string', enum: ['search', 'read', 'follow_relation', 'finish'] },
682
+ query: { type: 'string', minLength: 1, maxLength: MAX_TEXT_LENGTH, description: 'Used when kind is search.' },
683
+ entity_types: { type: 'array', maxItems: 10, items: { type: 'string', minLength: 1, maxLength: 100 }, description: 'Used when kind is search.' },
684
+ seed_ids: { type: 'array', minItems: 1, maxItems: MAX_IDS, items: { type: 'string', minLength: 1, maxLength: 1_000 }, description: 'Optional for search; required when kind is follow_relation.' },
685
+ entity_id: { type: 'string', minLength: 1, maxLength: 1_000, description: 'Required when kind is read.' },
686
+ entity_type: { type: 'string', minLength: 1, maxLength: 100, description: 'Required when kind is read.' },
687
+ relation: { type: 'string', minLength: 1, maxLength: MAX_RELATION_LENGTH, description: 'Required when kind is follow_relation.' },
688
+ direction: { type: 'string', enum: ['incoming', 'outgoing'], description: 'Required when kind is follow_relation.' },
689
+ target_types: { type: 'array', maxItems: 10, items: { type: 'string', minLength: 1, maxLength: 100 }, description: 'Optional when kind is follow_relation.' },
690
+ assessment: { type: 'string', enum: ['sufficient', 'insufficient'], description: 'Required when kind is finish.' },
691
+ status: { type: 'string', enum: ['satisfied', 'unresolved', 'needs_user_input'], description: 'Required when kind is finish.' },
692
+ reference_ids: { type: 'array', maxItems: MAX_IDS, items: { type: 'string', minLength: 1, maxLength: 1_000 }, description: 'Required when kind is finish.' },
693
+ field_evidence: {
694
+ type: 'array',
695
+ maxItems: MAX_FIELDS,
696
+ description: 'Required when kind is finish.',
697
+ items: {
698
+ type: 'object',
699
+ properties: {
700
+ field: { type: 'string', minLength: 1, maxLength: MAX_FIELD_LENGTH },
701
+ reference_id: { type: 'string', minLength: 1, maxLength: 1_000 },
702
+ attempt_id: { type: 'string', minLength: 1, maxLength: 300 },
730
703
  },
704
+ required: ['field', 'reference_id', 'attempt_id'],
705
+ additionalProperties: false,
731
706
  },
732
- unresolved_items: { type: 'array', maxItems: MAX_FIELDS, items: { type: 'string', minLength: 1, maxLength: MAX_HINT_LENGTH } },
733
- termination_reason: { type: 'string', minLength: 1, maxLength: MAX_HINT_LENGTH },
734
- }, ['assessment', 'status', 'reference_ids', 'field_evidence', 'unresolved_items', 'termination_reason']),
735
- ],
707
+ },
708
+ unresolved_items: { type: 'array', maxItems: MAX_FIELDS, items: { type: 'string', minLength: 1, maxLength: MAX_HINT_LENGTH }, description: 'Required when kind is finish.' },
709
+ termination_reason: { type: 'string', minLength: 1, maxLength: MAX_HINT_LENGTH, description: 'Required when kind is finish.' },
710
+ required_fields: {
711
+ type: 'array',
712
+ minItems: 1,
713
+ maxItems: MAX_FIELDS,
714
+ description: 'Must contain the same public field paths as the top-level required_fields.',
715
+ items: { type: 'string', minLength: 1, maxLength: MAX_FIELD_LENGTH },
716
+ },
717
+ why_different: { type: 'string', minLength: 1, maxLength: MAX_HINT_LENGTH },
718
+ },
719
+ required: ['kind'],
720
+ additionalProperties: false,
736
721
  },
737
722
  },
738
723
  required: ['question', 'target_hint', 'required_fields'],
@@ -2,6 +2,8 @@ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
2
  import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
3
3
  import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
4
4
  import { type CallToolResult, type ServerNotification, type ServerRequest, type Tool } from '@modelcontextprotocol/sdk/types.js';
5
+ import { applyMcpToolSchemaProfile, assertMcpToolSchemasPortable, normalizeMcpToolForPortability, normalizeMcpToolInputSchemaForPortability, normalizeMcpToolInputSchemaForProfile, resolveMcpToolSchemaProfile, validateMcpToolInputSchemaPortability, validateMcpToolSchemaPortability, type McpToolSchemaPortabilityIssue, type McpToolSchemaPortabilityIssueCode, type McpToolSchemaProfile } from './mcp-tool-schema-portability.js';
6
+ export { applyMcpToolSchemaProfile, assertMcpToolSchemasPortable, normalizeMcpToolForPortability, normalizeMcpToolInputSchemaForPortability, normalizeMcpToolInputSchemaForProfile, resolveMcpToolSchemaProfile, validateMcpToolInputSchemaPortability, validateMcpToolSchemaPortability, type McpToolSchemaPortabilityIssue, type McpToolSchemaPortabilityIssueCode, type McpToolSchemaProfile };
5
7
  export declare const MCP_RUNTIME_CONTRACT_VERSION: "mcp_runtime.v1";
6
8
  export interface LocalMcpRuntimeDescriptor {
7
9
  packageName: string;
@@ -43,6 +45,13 @@ export interface LocalMcpRuntimeOptions {
43
45
  onUnknownTool?: LocalMcpUnknownToolHandler;
44
46
  /** The host may inject HTTP, stdio, or an in-memory SDK transport. */
45
47
  transport?: Transport;
48
+ /**
49
+ * Schema serialization profile applied to advertised tool definitions.
50
+ * Defaults to `'gemini'` for backwards compatibility; pass `'standard'` to
51
+ * preserve lossless JSON Schema (e.g. type unions with null, anyOf/oneOf)
52
+ * for Claude / OpenAI / Codex hosts.
53
+ */
54
+ schemaProfile?: McpToolSchemaProfile;
46
55
  }
47
56
  export interface LocalMcpRuntimeHandle {
48
57
  readonly server: Server;
@@ -9,6 +9,8 @@
9
9
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
10
10
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
11
11
  import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
12
+ import { applyMcpToolSchemaProfile, assertMcpToolSchemasPortable, normalizeMcpToolForPortability, normalizeMcpToolInputSchemaForPortability, normalizeMcpToolInputSchemaForProfile, resolveMcpToolSchemaProfile, validateMcpToolInputSchemaPortability, validateMcpToolSchemaPortability } from './mcp-tool-schema-portability.js';
13
+ export { applyMcpToolSchemaProfile, assertMcpToolSchemasPortable, normalizeMcpToolForPortability, normalizeMcpToolInputSchemaForPortability, normalizeMcpToolInputSchemaForProfile, resolveMcpToolSchemaProfile, validateMcpToolInputSchemaPortability, validateMcpToolSchemaPortability };
12
14
  export const MCP_RUNTIME_CONTRACT_VERSION = 'mcp_runtime.v1';
13
15
  export class McpRuntimeContractError extends Error {
14
16
  code = 'mcp_runtime_contract_invalid';
@@ -17,7 +19,7 @@ export class McpRuntimeContractError extends Error {
17
19
  this.name = 'McpRuntimeContractError';
18
20
  }
19
21
  }
20
- function cloneToolDefinition(definition) {
22
+ function cloneToolDefinition(definition, schemaProfile) {
21
23
  if (!definition || typeof definition !== 'object' || Array.isArray(definition)) {
22
24
  throw new McpRuntimeContractError('tool.definition');
23
25
  }
@@ -28,7 +30,8 @@ function cloneToolDefinition(definition) {
28
30
  throw new McpRuntimeContractError('tool.definition.inputSchema');
29
31
  }
30
32
  try {
31
- return structuredClone(definition);
33
+ const cloned = structuredClone(definition);
34
+ return schemaProfile === 'gemini' ? normalizeMcpToolForPortability(cloned) : cloned;
32
35
  }
33
36
  catch {
34
37
  throw new McpRuntimeContractError('tool.definition', 'tool definition must be structured-cloneable');
@@ -45,13 +48,17 @@ function normalizeRuntimeOptions(options) {
45
48
  const version = text(options.version, 'version');
46
49
  if (!Array.isArray(options.tools))
47
50
  throw new McpRuntimeContractError('tools');
51
+ const schemaProfile = options.schemaProfile ?? 'gemini';
52
+ if (schemaProfile !== 'standard' && schemaProfile !== 'gemini') {
53
+ throw new McpRuntimeContractError('schemaProfile');
54
+ }
48
55
  const tools = [];
49
56
  const names = new Set();
50
57
  for (const tool of options.tools) {
51
58
  if (!tool || typeof tool !== 'object' || typeof tool.handler !== 'function') {
52
59
  throw new McpRuntimeContractError('tool.handler');
53
60
  }
54
- const definition = cloneToolDefinition(tool.definition);
61
+ const definition = cloneToolDefinition(tool.definition, schemaProfile);
55
62
  if (names.has(definition.name)) {
56
63
  throw new McpRuntimeContractError('tools', `duplicate MCP tool name: ${definition.name}`);
57
64
  }
@@ -65,7 +72,8 @@ function normalizeRuntimeOptions(options) {
65
72
  tools,
66
73
  ...(options.onListTools === undefined ? {} : { onListTools: options.onListTools }),
67
74
  ...(options.onUnknownTool === undefined ? {} : { onUnknownTool: options.onUnknownTool }),
68
- transport: options.transport
75
+ transport: options.transport,
76
+ schemaProfile
69
77
  };
70
78
  }
71
79
  /**
@@ -1,5 +1,57 @@
1
1
  import { verifyMeetingReviewPackage, type MeetingReviewPackage, type VerifiedMeetingReviewPackage } from './meeting-automation.js';
2
2
  export declare const MEETING_AUTOMATION_RUNTIME_VERSION: "brainbase.meeting-automation-runtime.v1";
3
+ /**
4
+ * Pre-generation seam. The personal host owns claiming, quotas and retries.
5
+ * This does not ingest a review package or publish/create tasks: those require
6
+ * a separately confirmed, published version and their existing human gates.
7
+ */
8
+ export interface MeetingDraftGenerationInput {
9
+ readonly owner_id: string;
10
+ readonly source_id: string;
11
+ readonly draft_id: string;
12
+ readonly transcript_digest: string;
13
+ readonly transcript: string;
14
+ readonly claim_token: string;
15
+ readonly tenant_id: string;
16
+ readonly org_id: string;
17
+ readonly project_id: string;
18
+ readonly project_code: string;
19
+ readonly channel_id: string | null;
20
+ }
21
+ export interface MeetingDraftGenerationContext {
22
+ readonly tenant_id: string;
23
+ readonly org_id: string;
24
+ readonly project_id: string;
25
+ readonly digest: string;
26
+ readonly records: readonly unknown[];
27
+ }
28
+ export interface MeetingDraftGenerationReceipt {
29
+ readonly input_fingerprint: string;
30
+ readonly draft_fingerprint: string;
31
+ }
32
+ export interface MeetingDraftGenerationPorts<Draft> {
33
+ /** Recheck publish selection, canonical project mapping and current access. */
34
+ readonly authorize: (input: MeetingDraftGenerationInput) => MaybePromise<boolean>;
35
+ readonly resolveContext: (input: MeetingDraftGenerationInput) => MaybePromise<MeetingDraftGenerationContext>;
36
+ /** Includes candidate-name extraction and mention/glossary resolution. */
37
+ readonly generate: (input: MeetingDraftGenerationInput, context: MeetingDraftGenerationContext) => MaybePromise<unknown>;
38
+ /** Check shape, transcript quotations and names against the supplied context. */
39
+ readonly validate: (output: unknown, input: MeetingDraftGenerationInput, context: MeetingDraftGenerationContext) => MaybePromise<{
40
+ valid: true;
41
+ draft: Draft;
42
+ } | {
43
+ valid: false;
44
+ }>;
45
+ /**
46
+ * Atomically compare current publish selection, source digest, access and
47
+ * claim ownership before saving. Return null on any stale/unauthorized write.
48
+ * Receipts and readback live in the person's storage, not an organization ledger.
49
+ */
50
+ readonly saveIfCurrent: (input: MeetingDraftGenerationInput, draft: Draft, receipt: MeetingDraftGenerationReceipt) => MaybePromise<MeetingDraftGenerationReceipt | null>;
51
+ readonly readback: (input: MeetingDraftGenerationInput) => MaybePromise<MeetingDraftGenerationReceipt | null>;
52
+ }
53
+ /** Opt-in contract only; no host switches to this path implicitly or on failure. */
54
+ export declare function runMeetingDraftGeneration<Draft>(input: MeetingDraftGenerationInput, ports: MeetingDraftGenerationPorts<Draft>): Promise<MeetingDraftGenerationReceipt>;
3
55
  type UnknownRecord = Record<string, unknown>;
4
56
  type MaybePromise<T> = T | Promise<T>;
5
57
  export interface MeetingAutomationRuntimeInput {
@@ -1,6 +1,52 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { assertMeetingCandidatesInput, normalizeDecisionCandidates, normalizeFollowUpDraft, normalizeTaskCandidates, verifyMeetingReviewPackage, } from './meeting-automation.js';
3
3
  export const MEETING_AUTOMATION_RUNTIME_VERSION = 'brainbase.meeting-automation-runtime.v1';
4
+ /** Opt-in contract only; no host switches to this path implicitly or on failure. */
5
+ export async function runMeetingDraftGeneration(input, ports) {
6
+ for (const field of ['owner_id', 'source_id', 'draft_id', 'transcript_digest', 'transcript', 'claim_token',
7
+ 'tenant_id', 'org_id', 'project_id', 'project_code']) {
8
+ if (typeof input?.[field] !== 'string' || !input[field].trim()) {
9
+ throw new MeetingAutomationRuntimeError('invalid_generation_input', `${field} is required`);
10
+ }
11
+ }
12
+ if (input.channel_id !== null && (typeof input.channel_id !== 'string' || !input.channel_id.trim())) {
13
+ throw new MeetingAutomationRuntimeError('invalid_generation_input', 'channel_id must be a channel or null');
14
+ }
15
+ for (const name of ['authorize', 'resolveContext', 'generate', 'validate', 'saveIfCurrent', 'readback']) {
16
+ if (typeof ports?.[name] !== 'function') {
17
+ throw new MeetingAutomationRuntimeError('invalid_ports', `${name} is required`);
18
+ }
19
+ }
20
+ // Pin scalar identity fields before crossing asynchronous host boundaries.
21
+ const pinned = Object.freeze({ ...input });
22
+ if (await ports.authorize(pinned) !== true) {
23
+ throw new MeetingAutomationRuntimeError('generation_not_authorized', 'publish selection and access must be current');
24
+ }
25
+ const context = await ports.resolveContext(pinned);
26
+ if (!context || !['tenant_id', 'org_id', 'project_id'].every((field) => context[field] === pinned[field]) ||
27
+ typeof context.digest !== 'string' || !context.digest.trim() || !Array.isArray(context.records)) {
28
+ throw new MeetingAutomationRuntimeError('context_unavailable', 'verified context for the selected project is required');
29
+ }
30
+ const output = await ports.generate(pinned, context);
31
+ const verified = await ports.validate(output, pinned, context);
32
+ if (verified?.valid !== true || verified.draft == null) {
33
+ throw new MeetingAutomationRuntimeError('output_invalid', 'meeting draft verification failed');
34
+ }
35
+ const receipt = Object.freeze({
36
+ input_fingerprint: digest({ ...pinned, context_digest: context.digest }),
37
+ draft_fingerprint: digest(verified.draft),
38
+ });
39
+ const saved = await ports.saveIfCurrent(pinned, verified.draft, receipt);
40
+ if (!saved) {
41
+ throw new MeetingAutomationRuntimeError('generation_stale', 'draft selection, source or claim changed before save');
42
+ }
43
+ const readback = await ports.readback(pinned);
44
+ if (saved.input_fingerprint !== receipt.input_fingerprint || saved.draft_fingerprint !== receipt.draft_fingerprint ||
45
+ readback?.input_fingerprint !== receipt.input_fingerprint || readback.draft_fingerprint !== receipt.draft_fingerprint) {
46
+ throw new MeetingAutomationRuntimeError('readback_mismatch', 'generated draft was not durably saved');
47
+ }
48
+ return receipt;
49
+ }
4
50
  export class MeetingAutomationRuntimeError extends Error {
5
51
  code;
6
52
  details;
@@ -87,7 +87,7 @@ const toolConfigs = {
87
87
  task_id: id,
88
88
  expected_version: version,
89
89
  kind: { type: 'string', enum: kinds },
90
- ref: { type: 'object' },
90
+ ref: { type: 'object', additionalProperties: true },
91
91
  idempotency_key: str,
92
92
  },
93
93
  required: ['task_id', 'expected_version', 'kind', 'ref'],
@@ -126,7 +126,7 @@ export const queueTaskToolDefinitions = QUEUE_TASK_TOOL_NAMES.map((name) => {
126
126
  inputSchema: {
127
127
  type: 'object',
128
128
  properties: config.properties,
129
- required: config.required,
129
+ ...(config.required.length > 0 ? { required: config.required } : {}),
130
130
  additionalProperties: false,
131
131
  },
132
132
  annotations: {
@@ -13,7 +13,6 @@ function asDate(value, fieldName) {
13
13
  function zonedParts(date, timezone) {
14
14
  const parts = new Intl.DateTimeFormat('en-US', {
15
15
  timeZone: timezone,
16
- hour12: false,
17
16
  hourCycle: 'h23',
18
17
  year: 'numeric',
19
18
  month: '2-digit',
@@ -218,7 +218,7 @@ export function routineScheduleMatches(expectation, instant) {
218
218
  }
219
219
  const parts = new Intl.DateTimeFormat('en-US', {
220
220
  timeZone: expectation.timezone,
221
- hour12: false,
221
+ hourCycle: 'h23',
222
222
  weekday: 'long',
223
223
  hour: '2-digit',
224
224
  minute: '2-digit'