@lucern/mcp 0.3.0-alpha.4 → 0.3.0-alpha.5

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.
@@ -2,11 +2,28 @@ import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/
2
2
  import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
3
3
  import '@modelcontextprotocol/sdk/server/stdio.js';
4
4
  import { z } from 'zod';
5
+ import * as graphIntel_star from '@lucern/reasoning-kernel/graphIntel';
5
6
  import { v } from 'convex/values';
6
7
  import * as fs from 'fs';
7
8
  import * as path from 'path';
8
9
 
9
- // src/hosted-route.ts
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget);
10
27
 
11
28
  // src/credentials.ts
12
29
  var TENANT_API_KEY_PREFIXES = ["luc_", "stk_"];
@@ -152,6 +169,353 @@ function scoreObservation(record, terms) {
152
169
  return score;
153
170
  }
154
171
 
172
+ // ../sdk/src/index.ts
173
+ var src_exports = {};
174
+ __export(src_exports, {
175
+ ACTIVATE_WORKTREE: () => ACTIVATE_WORKTREE,
176
+ ADD_EVIDENCE: () => ADD_EVIDENCE,
177
+ ADD_WORKTREE: () => ADD_WORKTREE,
178
+ ANALYZE_TOPIC_DENSITY: () => ANALYZE_TOPIC_DENSITY,
179
+ ANSWER_QUESTION: () => ANSWER_QUESTION,
180
+ APPLY_AUTO_BRANCHING: () => APPLY_AUTO_BRANCHING,
181
+ APPLY_LENS_TO_TOPIC: () => APPLY_LENS_TO_TOPIC,
182
+ APPLY_ONTOLOGY: () => APPLY_ONTOLOGY,
183
+ ARCHIVE_BELIEF: () => ARCHIVE_BELIEF,
184
+ ARCHIVE_ONTOLOGY: () => ARCHIVE_ONTOLOGY,
185
+ ARCHIVE_QUESTION: () => ARCHIVE_QUESTION,
186
+ BEGIN_BUILD_SESSION: () => BEGIN_BUILD_SESSION,
187
+ BELIEF_STATUSES: () => BELIEF_STATUSES,
188
+ BISECT_CONFIDENCE: () => BISECT_CONFIDENCE,
189
+ BRANCH_DEPRECATION_MESSAGE: () => BRANCH_DEPRECATION_MESSAGE,
190
+ BROADCAST_MESSAGE: () => BROADCAST_MESSAGE,
191
+ CANONICAL_WORKFLOW_DEFINITIONS: () => CANONICAL_WORKFLOW_DEFINITIONS,
192
+ CHECK_PERMISSION: () => CHECK_PERMISSION,
193
+ CLAIM_FILES: () => CLAIM_FILES,
194
+ COMPILE_CONTEXT: () => COMPILE_CONTEXT,
195
+ COMPLETE_TASK: () => COMPLETE_TASK,
196
+ CONFIDENCE_TRIGGERS: () => CONFIDENCE_TRIGGERS,
197
+ CONTRADICTION_SEVERITIES: () => CONTRADICTION_SEVERITIES,
198
+ CONTRADICTION_STATUSES: () => CONTRADICTION_STATUSES,
199
+ CONTROL_OBJECT_BLAST_RADII: () => CONTROL_OBJECT_BLAST_RADII,
200
+ CONTROL_OBJECT_EDIT_SURFACES: () => CONTROL_OBJECT_EDIT_SURFACES,
201
+ CONTROL_OBJECT_INHERITANCE_RULES: () => CONTROL_OBJECT_INHERITANCE_RULES,
202
+ CONTROL_OBJECT_KINDS: () => CONTROL_OBJECT_KINDS,
203
+ CONTROL_OBJECT_OWNERSHIP_CONTRACT: () => CONTROL_OBJECT_OWNERSHIP_CONTRACT,
204
+ CONTROL_OBJECT_OWNERSHIP_MATRIX: () => CONTROL_OBJECT_OWNERSHIP_MATRIX,
205
+ CONTROL_OBJECT_OWNERSHIP_ROWS: () => CONTROL_OBJECT_OWNERSHIP_ROWS,
206
+ CONTROL_OBJECT_OWNER_SCOPES: () => CONTROL_OBJECT_OWNER_SCOPES,
207
+ CREATE_ANSWER: () => CREATE_ANSWER,
208
+ CREATE_BELIEF: () => CREATE_BELIEF,
209
+ CREATE_EDGE: () => CREATE_EDGE,
210
+ CREATE_EPISTEMIC_CONTRACT: () => CREATE_EPISTEMIC_CONTRACT,
211
+ CREATE_EVIDENCE: () => CREATE_EVIDENCE,
212
+ CREATE_LENS: () => CREATE_LENS,
213
+ CREATE_ONTOLOGY: () => CREATE_ONTOLOGY,
214
+ CREATE_ONTOLOGY_VERSION: () => CREATE_ONTOLOGY_VERSION,
215
+ CREATE_QUESTION: () => CREATE_QUESTION,
216
+ CREATE_TASK: () => CREATE_TASK,
217
+ CREATE_TOPIC: () => CREATE_TOPIC,
218
+ CustomToolRegistryError: () => CustomToolRegistryError,
219
+ DEFAULT_TIER_APPROVAL_MODE: () => DEFAULT_TIER_APPROVAL_MODE,
220
+ DEFAULT_WORKFLOW_AUTO_FIX_POLICY: () => DEFAULT_WORKFLOW_AUTO_FIX_POLICY,
221
+ DEFEAT_TYPES: () => DEFEAT_TYPES,
222
+ DEPRECATE_ONTOLOGY_VERSION: () => DEPRECATE_ONTOLOGY_VERSION,
223
+ DETECT_CONFIRMATION_BIAS: () => DETECT_CONFIRMATION_BIAS,
224
+ DISCOVER: () => DISCOVER,
225
+ DISCOVER_ENTITY_CONNECTIONS: () => DISCOVER_ENTITY_CONNECTIONS,
226
+ DOMAIN_EVENT_TYPES: () => DOMAIN_EVENT_TYPES,
227
+ DOMAIN_EVENT_VERSION: () => DOMAIN_EVENT_VERSION,
228
+ DeviceAuthorizationError: () => DeviceAuthorizationError,
229
+ EDGE_TYPES: () => EDGE_TYPES,
230
+ EMBEDDINGS_FIELDS: () => EMBEDDINGS_FIELDS,
231
+ END_SESSION: () => END_SESSION,
232
+ EPISTEMIC_EDGE_TYPES: () => EPISTEMIC_EDGE_TYPES,
233
+ EPISTEMIC_LAYERS: () => EPISTEMIC_LAYERS,
234
+ EVALUATE_CONTRACT: () => EVALUATE_CONTRACT,
235
+ EVENTING_FIELDS: () => EVENTING_FIELDS,
236
+ EVENT_RETENTION_DEFAULT_DAYS: () => EVENT_RETENTION_DEFAULT_DAYS,
237
+ FILTER_BY_PERMISSION: () => FILTER_BY_PERMISSION,
238
+ FIND_CONTRADICTIONS: () => FIND_CONTRADICTIONS,
239
+ FIND_MISSING_QUESTIONS: () => FIND_MISSING_QUESTIONS,
240
+ FLAG_CONTRADICTION: () => FLAG_CONTRADICTION,
241
+ FORK_BELIEF: () => FORK_BELIEF,
242
+ FORK_REASONS: () => FORK_REASONS,
243
+ FUNCTION_SURFACE_METHOD_PATHS: () => FUNCTION_SURFACE_METHOD_PATHS,
244
+ GENERATE_SESSION_HANDOFF: () => GENERATE_SESSION_HANDOFF,
245
+ GET_AGENT_INBOX: () => GET_AGENT_INBOX,
246
+ GET_ANSWER: () => GET_ANSWER,
247
+ GET_AUDIT_TRAIL: () => GET_AUDIT_TRAIL,
248
+ GET_BELIEF: () => GET_BELIEF,
249
+ GET_CHANGE_HISTORY: () => GET_CHANGE_HISTORY,
250
+ GET_CODE_CONTEXT: () => GET_CODE_CONTEXT,
251
+ GET_CONFIDENCE_HISTORY: () => GET_CONFIDENCE_HISTORY,
252
+ GET_CONTRACT_STATUS: () => GET_CONTRACT_STATUS,
253
+ GET_EVIDENCE: () => GET_EVIDENCE,
254
+ GET_FAILURE_LOG: () => GET_FAILURE_LOG,
255
+ GET_FALSIFICATION_QUESTIONS: () => GET_FALSIFICATION_QUESTIONS,
256
+ GET_GRAPH_GAPS: () => GET_GRAPH_GAPS,
257
+ GET_GRAPH_NEIGHBORHOOD: () => GET_GRAPH_NEIGHBORHOOD,
258
+ GET_GRAPH_STRUCTURE_ANALYSIS: () => GET_GRAPH_STRUCTURE_ANALYSIS,
259
+ GET_HIGH_PRIORITY_QUESTIONS: () => GET_HIGH_PRIORITY_QUESTIONS,
260
+ GET_LATTICE_COVERAGE: () => GET_LATTICE_COVERAGE,
261
+ GET_OBSERVATION_CONTEXT: () => GET_OBSERVATION_CONTEXT,
262
+ GET_ONTOLOGY: () => GET_ONTOLOGY,
263
+ GET_QUESTION: () => GET_QUESTION,
264
+ GET_TOPIC: () => GET_TOPIC,
265
+ GET_TOPIC_COVERAGE: () => GET_TOPIC_COVERAGE,
266
+ GET_TOPIC_TREE: () => GET_TOPIC_TREE,
267
+ GIT_SEMANTIC_REQUIRED_TOOLS: () => GIT_SEMANTIC_REQUIRED_TOOLS,
268
+ GRAPH_ANALYSIS_ANALYSIS_FIELDS: () => GRAPH_ANALYSIS_ANALYSIS_FIELDS,
269
+ GRAPH_ANALYSIS_COMPUTE_FIELDS: () => GRAPH_ANALYSIS_COMPUTE_FIELDS,
270
+ GRAPH_ANALYSIS_SUGGESTION_FIELDS: () => GRAPH_ANALYSIS_SUGGESTION_FIELDS,
271
+ GRAPH_INTELLIGENCE_MODE_TOOL_NAMES: () => GRAPH_INTELLIGENCE_MODE_TOOL_NAMES,
272
+ GRAPH_INTELLIGENCE_PUBLIC_TOOL_NAMES: () => GRAPH_INTELLIGENCE_PUBLIC_TOOL_NAMES,
273
+ GRAPH_INTELLIGENCE_QUERIES: () => GRAPH_INTELLIGENCE_QUERIES,
274
+ GRAPH_INTELLIGENCE_QUERIES_WITH_TOOLS: () => GRAPH_INTELLIGENCE_QUERIES_WITH_TOOLS,
275
+ GRAPH_INTELLIGENCE_QUERY_CATALOG_VERSION: () => GRAPH_INTELLIGENCE_QUERY_CATALOG_VERSION,
276
+ GRAPH_INTELLIGENCE_QUERY_CATEGORIES: () => GRAPH_INTELLIGENCE_QUERY_CATEGORIES,
277
+ GRAPH_INTELLIGENCE_QUERY_MODES: () => GRAPH_INTELLIGENCE_QUERY_MODES,
278
+ GRAPH_INTELLIGENCE_QUICK_QUERIES: () => GRAPH_INTELLIGENCE_QUICK_QUERIES,
279
+ GRAPH_RECOMMENDATION_FIELDS: () => GRAPH_RECOMMENDATION_FIELDS,
280
+ GRAPH_STATE_CLASSIFIER_FIELDS: () => GRAPH_STATE_CLASSIFIER_FIELDS,
281
+ HEARTBEAT_SESSION: () => HEARTBEAT_SESSION,
282
+ IDENTITY_WHOAMI: () => IDENTITY_WHOAMI,
283
+ INGEST_OBSERVATION: () => INGEST_OBSERVATION,
284
+ InfisicalRuntimeError: () => InfisicalRuntimeError,
285
+ JOBS_FIELDS: () => JOBS_FIELDS,
286
+ JUDGMENT_TYPES: () => JUDGMENT_TYPES,
287
+ LENS_PERSPECTIVE_TYPES: () => LENS_PERSPECTIVE_TYPES,
288
+ LENS_STATUSES: () => LENS_STATUSES,
289
+ LENS_TASK_TEMPLATE_PRIORITIES: () => LENS_TASK_TEMPLATE_PRIORITIES,
290
+ LINK_EVIDENCE: () => LINK_EVIDENCE,
291
+ LINK_EVIDENCE_TO_BELIEF: () => LINK_EVIDENCE_TO_BELIEF,
292
+ LINK_EVIDENCE_TO_QUESTION: () => LINK_EVIDENCE_TO_QUESTION,
293
+ LIST_ACTIVE_SESSIONS: () => LIST_ACTIVE_SESSIONS,
294
+ LIST_ALL_WORKTREES: () => LIST_ALL_WORKTREES,
295
+ LIST_BELIEFS: () => LIST_BELIEFS,
296
+ LIST_CAMPAIGNS: () => LIST_CAMPAIGNS,
297
+ LIST_EVIDENCE: () => LIST_EVIDENCE,
298
+ LIST_GRAPH_INTELLIGENCE_QUERIES: () => LIST_GRAPH_INTELLIGENCE_QUERIES,
299
+ LIST_LENSES: () => LIST_LENSES,
300
+ LIST_ONTOLOGIES: () => LIST_ONTOLOGIES,
301
+ LIST_QUESTIONS: () => LIST_QUESTIONS,
302
+ LIST_TASKS: () => LIST_TASKS,
303
+ LIST_TOPICS: () => LIST_TOPICS,
304
+ LIST_WORKTREES: () => LIST_WORKTREES,
305
+ LUCERN_SDK_VERSION: () => LUCERN_SDK_VERSION,
306
+ LucernApiError: () => LucernApiError,
307
+ LucernSdkAuthContextError: () => LucernSdkAuthContextError,
308
+ MANAGE_WRITE_POLICY: () => MANAGE_WRITE_POLICY,
309
+ MATCH_ENTITY_TYPE: () => MATCH_ENTITY_TYPE,
310
+ MAX_ENTITY_LIMIT: () => MAX_ENTITY_LIMIT,
311
+ MCP_ALWAYS_ALLOWED_TOOL_NAMES: () => MCP_ALWAYS_ALLOWED_TOOL_NAMES,
312
+ MCP_TOOL_CONTRACTS: () => MCP_TOOL_CONTRACTS,
313
+ MERGE: () => MERGE,
314
+ MERGE_OUTCOMES: () => MERGE_OUTCOMES,
315
+ MODEL_RUNTIME_FIELDS: () => MODEL_RUNTIME_FIELDS,
316
+ MODULATE_CONFIDENCE: () => MODULATE_CONFIDENCE,
317
+ MORNING_BRIEF_WORKFLOW_ID: () => MORNING_BRIEF_WORKFLOW_ID,
318
+ NIGHTLY_RECONCILIATION_WORKFLOW_ID: () => NIGHTLY_RECONCILIATION_WORKFLOW_ID,
319
+ ONTOLOGY_LINK_FIELDS: () => ONTOLOGY_LINK_FIELDS,
320
+ OPEN_PULL_REQUEST: () => OPEN_PULL_REQUEST,
321
+ ORG_GRAPH_SEARCH_FIELDS: () => ORG_GRAPH_SEARCH_FIELDS,
322
+ PIPELINE_SNAPSHOT: () => PIPELINE_SNAPSHOT,
323
+ PUBLISH_ONTOLOGY_VERSION: () => PUBLISH_ONTOLOGY_VERSION,
324
+ PUSH: () => PUSH,
325
+ QUERY_LINEAGE: () => QUERY_LINEAGE,
326
+ REASONING_METHODS: () => REASONING_METHODS,
327
+ RECORD_ATTEMPT: () => RECORD_ATTEMPT,
328
+ RECORD_JUDGMENT: () => RECORD_JUDGMENT,
329
+ RECORD_SCOPE_LEARNING: () => RECORD_SCOPE_LEARNING,
330
+ REFINE_BELIEF: () => REFINE_BELIEF,
331
+ REFINE_QUESTION: () => REFINE_QUESTION,
332
+ REGISTER_SESSION: () => REGISTER_SESSION,
333
+ REMOVE_LENS_FROM_TOPIC: () => REMOVE_LENS_FROM_TOPIC,
334
+ RESOLVE_EFFECTIVE_ONTOLOGY: () => RESOLVE_EFFECTIVE_ONTOLOGY,
335
+ RUN_GRAPH_INTELLIGENCE_QUERY: () => RUN_GRAPH_INTELLIGENCE_QUERY,
336
+ SEARCH_BELIEFS: () => SEARCH_BELIEFS,
337
+ SEARCH_EVIDENCE: () => SEARCH_EVIDENCE,
338
+ SEED_BELIEF_LATTICE: () => SEED_BELIEF_LATTICE,
339
+ SEND_AGENT_MESSAGE: () => SEND_AGENT_MESSAGE,
340
+ SESSION_AUTH_MODES: () => SESSION_AUTH_MODES,
341
+ SESSION_LIFECYCLE_STATUSES: () => SESSION_LIFECYCLE_STATUSES,
342
+ SESSION_PRINCIPAL_TYPES: () => SESSION_PRINCIPAL_TYPES,
343
+ STRUCTURAL_EDGE_TYPES: () => STRUCTURAL_EDGE_TYPES,
344
+ TELEMETRY_FIELDS: () => TELEMETRY_FIELDS,
345
+ TENANT_IDENTITY_FIELDS: () => TENANT_IDENTITY_FIELDS,
346
+ TOOL_REGISTRY_FIELDS: () => TOOL_REGISTRY_FIELDS,
347
+ TRACE_ENTITY_IMPACT: () => TRACE_ENTITY_IMPACT,
348
+ TRAVERSE_GRAPH: () => TRAVERSE_GRAPH,
349
+ TRIGGER_BELIEF_REVIEW: () => TRIGGER_BELIEF_REVIEW,
350
+ UPDATE_ONTOLOGY: () => UPDATE_ONTOLOGY,
351
+ UPDATE_QUESTION_STATUS: () => UPDATE_QUESTION_STATUS,
352
+ UPDATE_TASK: () => UPDATE_TASK,
353
+ UPDATE_TOPIC: () => UPDATE_TOPIC,
354
+ UPDATE_WORKTREE_METADATA: () => UPDATE_WORKTREE_METADATA,
355
+ UPDATE_WORKTREE_TARGETS: () => UPDATE_WORKTREE_TARGETS,
356
+ WEBHOOK_MAX_ATTEMPTS: () => WEBHOOK_MAX_ATTEMPTS,
357
+ WEBHOOK_RETRY_DELAYS_MS: () => WEBHOOK_RETRY_DELAYS_MS,
358
+ WORKFLOW_ACTION_KINDS: () => WORKFLOW_ACTION_KINDS,
359
+ WORKFLOW_APPROVAL_MODES: () => WORKFLOW_APPROVAL_MODES,
360
+ WORKFLOW_AUTO_FIX_MODES: () => WORKFLOW_AUTO_FIX_MODES,
361
+ WORKFLOW_HOOK_EVENTS: () => WORKFLOW_HOOK_EVENTS,
362
+ WORKFLOW_INTEGRITY_CHECKS: () => WORKFLOW_INTEGRITY_CHECKS,
363
+ WORKFLOW_MUTATION_TIERS: () => WORKFLOW_MUTATION_TIERS,
364
+ WORKFLOW_OUTPUT_KINDS: () => WORKFLOW_OUTPUT_KINDS,
365
+ WORKFLOW_PROOF_ARTIFACT_KINDS: () => WORKFLOW_PROOF_ARTIFACT_KINDS,
366
+ WORKFLOW_RUNTIME_SCHEMA_VERSION: () => WORKFLOW_RUNTIME_SCHEMA_VERSION,
367
+ WORKFLOW_RUN_STATUSES: () => WORKFLOW_RUN_STATUSES,
368
+ WORKFLOW_STAFFING_HINTS: () => WORKFLOW_STAFFING_HINTS,
369
+ WORKFLOW_TRIGGER_KINDS: () => WORKFLOW_TRIGGER_KINDS,
370
+ WORKTREE_PHASES: () => WORKTREE_PHASES,
371
+ applyInfisicalRuntimeEnv: () => applyInfisicalRuntimeEnv,
372
+ asListItems: () => asListItems,
373
+ assertValidWebhookSecret: () => assertValidWebhookSecret,
374
+ assertValidWebhookUrl: () => assertValidWebhookUrl,
375
+ buildDeprecatedBranchMetadata: () => buildDeprecatedBranchMetadata,
376
+ buildDomainEvent: () => buildDomainEvent,
377
+ buildMcpToolContracts: () => buildMcpToolContracts,
378
+ buildMcpToolManifest: () => buildMcpToolManifest,
379
+ clearRegisteredCustomTools: () => clearRegisteredCustomTools,
380
+ compareEventCursor: () => compareEventCursor,
381
+ compileContextPackFromSnapshot: () => compileContextPackFromSnapshot,
382
+ computeWebhookSignature: () => computeWebhookSignature,
383
+ createAdminClient: () => createAdminClient,
384
+ createAnswersClient: () => createAnswersClient,
385
+ createAudiencesClient: () => createAudiencesClient,
386
+ createAuditClient: () => createAuditClient,
387
+ createAuthDeviceClient: () => createAuthDeviceClient,
388
+ createBeliefsClient: () => createBeliefsClient,
389
+ createCanonicalAuthHeaders: () => createCanonicalAuthHeaders,
390
+ createContextClient: () => createContextClient,
391
+ createContextFacade: () => createContextFacade,
392
+ createDecisionsClient: () => createDecisionsClient,
393
+ createEmbeddingsClient: () => createEmbeddingsClient,
394
+ createEventId: () => createEventId,
395
+ createEventingClient: () => createEventingClient,
396
+ createEventsClientCore: () => createEventsClientCore,
397
+ createEvidenceClient: () => createEvidenceClient,
398
+ createFunctionSurfaceClient: () => createFunctionSurfaceClient,
399
+ createGatewayRequestClient: () => createGatewayRequestClient,
400
+ createGraphAnalysisClient: () => createGraphAnalysisClient,
401
+ createGraphClient: () => createGraphClient,
402
+ createGraphRecommendationsClient: () => createGraphRecommendationsClient,
403
+ createGraphStateClassifierClient: () => createGraphStateClassifierClient,
404
+ createHarnessClient: () => createHarnessClient,
405
+ createIdentityClient: () => createIdentityClient,
406
+ createJobsClient: () => createJobsClient,
407
+ createLearningClient: () => createLearningClient,
408
+ createListResult: () => createListResult,
409
+ createLucernClient: () => createLucernClient,
410
+ createModelRuntimeClient: () => createModelRuntimeClient,
411
+ createOntologyClient: () => createOntologyClient,
412
+ createOntologyLinksClient: () => createOntologyLinksClient,
413
+ createOrgGraphSearchClient: () => createOrgGraphSearchClient,
414
+ createPacksClient: () => createPacksClient,
415
+ createPolicyClient: () => createPolicyClient,
416
+ createReportsClient: () => createReportsClient,
417
+ createSchemaClient: () => createSchemaClient,
418
+ createSourcesClient: () => createSourcesClient,
419
+ createTelemetryClient: () => createTelemetryClient,
420
+ createToolRegistryClient: () => createToolRegistryClient,
421
+ createTopicsClient: () => createTopicsClient,
422
+ createWebhooksClientCore: () => createWebhooksClientCore,
423
+ createWorkflowClient: () => createWorkflowClient,
424
+ decodeEventCursor: () => decodeEventCursor,
425
+ emitDomainEvent: () => emitDomainEvent,
426
+ encodeEventCursor: () => encodeEventCursor,
427
+ eventPatternToRegExp: () => eventPatternToRegExp,
428
+ fillGraphIntelligencePromptTemplate: () => fillGraphIntelligencePromptTemplate,
429
+ getControlObjectOwnershipCase: () => getControlObjectOwnershipCase,
430
+ getGraphIntelligenceQuery: () => getGraphIntelligenceQuery,
431
+ getMcpToolExposure: () => getMcpToolExposure,
432
+ getRegisteredCustomTool: () => getRegisteredCustomTool,
433
+ hydrateInfisicalRuntimeEnv: () => hydrateInfisicalRuntimeEnv,
434
+ inferActorType: () => inferActorType,
435
+ inferLensPerspectiveTypeFromBranchSchema: () => inferLensPerspectiveTypeFromBranchSchema,
436
+ inferSessionPrincipalType: () => inferSessionPrincipalType,
437
+ invokeRegisteredCustomTool: () => invokeRegisteredCustomTool,
438
+ isAfterCursor: () => isAfterCursor,
439
+ isGraphIntelligenceQueryMode: () => isGraphIntelligenceQueryMode,
440
+ isInfisicalRuntimeDisabled: () => isInfisicalRuntimeDisabled,
441
+ isLensFilterCriteria: () => isLensFilterCriteria,
442
+ isLucernPrompt: () => isLucernPrompt,
443
+ isMcpToolAllowed: () => isMcpToolAllowed,
444
+ isTaxonomyFilterCriteriaV1: () => isTaxonomyFilterCriteriaV1,
445
+ lastDelegator: () => lastDelegator,
446
+ listControlObjectOwnershipCases: () => listControlObjectOwnershipCases,
447
+ listGraphIntelligenceQueries: () => listGraphIntelligenceQueries,
448
+ listRegisteredCustomTools: () => listRegisteredCustomTools,
449
+ mapAliasedList: () => mapAliasedList,
450
+ mapGatewayData: () => mapGatewayData,
451
+ mapOpinionHistoryEntriesFromGatewayData: () => mapOpinionHistoryEntriesFromGatewayData,
452
+ matchesAnyEventPattern: () => matchesAnyEventPattern,
453
+ matchesEventPattern: () => matchesEventPattern,
454
+ mcpContractToInputSchema: () => mcpContractToInputSchema,
455
+ mcpContractToManifestEntry: () => mcpContractToManifestEntry,
456
+ migrateBranchToLens: () => migrateBranchToLens,
457
+ nextDeliveryAttemptAt: () => nextDeliveryAttemptAt,
458
+ normalizeCanonicalLucernAuthContext: () => normalizeCanonicalLucernAuthContext,
459
+ normalizeDelegationChain: () => normalizeDelegationChain,
460
+ normalizeNodeVerificationStatus: () => normalizeNodeVerificationStatus,
461
+ normalizeNodeWriteInput: () => normalizeNodeWriteInput,
462
+ normalizeRetentionDays: () => normalizeRetentionDays,
463
+ normalizeTopicQuery: () => normalizeTopicQuery,
464
+ normalizeWebhookPatterns: () => normalizeWebhookPatterns,
465
+ opinionFromBaseRate: () => opinionFromBaseRate,
466
+ opinionFromDogmatic: () => opinionFromDogmatic,
467
+ opinionFromProjected: () => opinionFromProjected,
468
+ planContextPackCompilation: () => planContextPackCompilation,
469
+ randomIdempotencyKey: () => randomIdempotencyKey,
470
+ readInfisicalRuntimeBootstrap: () => readInfisicalRuntimeBootstrap,
471
+ registerCustomTool: () => registerCustomTool,
472
+ resolveDeliveryFailureStatus: () => resolveDeliveryFailureStatus,
473
+ resolveText: () => resolveText,
474
+ resolveTopicId: () => resolveTopicId,
475
+ sanitizeWebhookRecord: () => sanitizeWebhookRecord,
476
+ sortEventsByCursor: () => sortEventsByCursor,
477
+ toQueryString: () => toQueryString,
478
+ truncateWebhookResponseBody: () => truncateWebhookResponseBody,
479
+ unregisterCustomTool: () => unregisterCustomTool,
480
+ validateFilterCriteria: () => validateFilterCriteria,
481
+ validateGitSemantics: () => validateGitSemantics,
482
+ withSdkAliases: () => withSdkAliases,
483
+ withTextAlias: () => withTextAlias,
484
+ withTopicAlias: () => withTopicAlias
485
+ });
486
+
487
+ // ../sdk/src/opinion.ts
488
+ function clamp01(value) {
489
+ if (!Number.isFinite(value)) {
490
+ return 0;
491
+ }
492
+ return Math.max(0, Math.min(1, value));
493
+ }
494
+ function vacuous(baseRate) {
495
+ return { b: 0, d: 0, u: 1, a: clamp01(baseRate) };
496
+ }
497
+ function dogmatic(probability, baseRate) {
498
+ const p = clamp01(probability);
499
+ return { b: p, d: 1 - p, u: 0, a: clamp01(baseRate) };
500
+ }
501
+ function opinionFromBaseRate(probability) {
502
+ return vacuous(clamp01(probability));
503
+ }
504
+ function opinionFromDogmatic(probability, baseRate) {
505
+ return dogmatic(clamp01(probability), clamp01(baseRate));
506
+ }
507
+ function opinionFromProjected(probability, uncertainty, baseRate) {
508
+ const p = clamp01(probability);
509
+ const u = clamp01(uncertainty);
510
+ const remainingMass = 1 - u;
511
+ return {
512
+ b: p * remainingMass,
513
+ d: (1 - p) * remainingMass,
514
+ u,
515
+ a: clamp01(baseRate)
516
+ };
517
+ }
518
+
155
519
  // ../sdk/src/authContext.ts
156
520
  var LucernSdkAuthContextError = class extends Error {
157
521
  reason;
@@ -1460,7 +1824,7 @@ function readString2(value) {
1460
1824
  function readNumber(value) {
1461
1825
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
1462
1826
  }
1463
- function clamp01(value) {
1827
+ function clamp012(value) {
1464
1828
  return Math.max(0, Math.min(1, value));
1465
1829
  }
1466
1830
  function normalizeOpinionTuple(record) {
@@ -1475,10 +1839,10 @@ function normalizeOpinionTuple(record) {
1475
1839
  );
1476
1840
  }
1477
1841
  return {
1478
- b: clamp01(rawBelief),
1479
- d: clamp01(rawDisbelief),
1480
- u: clamp01(rawUncertainty),
1481
- a: clamp01(rawBaseRate)
1842
+ b: clamp012(rawBelief),
1843
+ d: clamp012(rawDisbelief),
1844
+ u: clamp012(rawUncertainty),
1845
+ a: clamp012(rawBaseRate)
1482
1846
  };
1483
1847
  }
1484
1848
  function mapOpinionHistoryEntriesFromGatewayData(payload) {
@@ -1486,7 +1850,7 @@ function mapOpinionHistoryEntriesFromGatewayData(payload) {
1486
1850
  return entries2.map((value) => {
1487
1851
  const record = asRecord2(value);
1488
1852
  const tuple = normalizeOpinionTuple(record);
1489
- const projected = readNumber(record.confidence) ?? clamp01(tuple.b + tuple.a * tuple.u);
1853
+ const projected = readNumber(record.confidence) ?? clamp012(tuple.b + tuple.a * tuple.u);
1490
1854
  const triggeringEvidenceId = readString2(record.triggeringEvidenceId);
1491
1855
  const triggeringQuestionId = readString2(record.triggeringQuestionId);
1492
1856
  const triggeringAnswerId = readString2(record.triggeringAnswerId);
@@ -1505,7 +1869,7 @@ function mapOpinionHistoryEntriesFromGatewayData(payload) {
1505
1869
  d: tuple.d,
1506
1870
  u: tuple.u,
1507
1871
  a: tuple.a,
1508
- P: clamp01(projected),
1872
+ P: clamp012(projected),
1509
1873
  trigger,
1510
1874
  ...triggeringRef ? { triggeringRef } : {},
1511
1875
  ...readString2(record.rationale) ? { rationale: readString2(record.rationale) } : {},
@@ -4267,9 +4631,33 @@ function graphAnalysisQuery(input) {
4267
4631
  cursor: input.cursor
4268
4632
  };
4269
4633
  }
4634
+ function normalizeRunQueryPayload(input) {
4635
+ return {
4636
+ ...input,
4637
+ topicId: requireTopicId2(input),
4638
+ projectId: void 0
4639
+ };
4640
+ }
4270
4641
  function createGraphAnalysisClient(config = {}) {
4271
4642
  const gateway = createGatewayRequestClient(config);
4272
4643
  return {
4644
+ listGraphIntelligenceQueries(input = {}) {
4645
+ return gateway.request({
4646
+ path: "/api/platform/v1/graph-intelligence/queries",
4647
+ method: "POST",
4648
+ body: {
4649
+ categoryId: input.categoryId,
4650
+ mode: input.mode
4651
+ }
4652
+ });
4653
+ },
4654
+ runGraphIntelligenceQuery(input) {
4655
+ return gateway.request({
4656
+ path: "/api/platform/v1/graph-intelligence/run",
4657
+ method: "POST",
4658
+ body: normalizeRunQueryPayload(input)
4659
+ });
4660
+ },
4273
4661
  saveAnalysis(input, idempotencyKey) {
4274
4662
  return gateway.request({
4275
4663
  path: "/api/platform/v1/graph-analysis/analyses",
@@ -5106,6 +5494,120 @@ function createMcpClient(config = {}) {
5106
5494
  }
5107
5495
 
5108
5496
  // ../sdk/src/generated/functionSurface.ts
5497
+ var FUNCTION_SURFACE_METHOD_PATHS = [
5498
+ "answers.answerQuestion",
5499
+ "answers.createAnswer",
5500
+ "answers.getAnswer",
5501
+ "beliefs.archiveBelief",
5502
+ "beliefs.bisectConfidence",
5503
+ "beliefs.createBelief",
5504
+ "beliefs.forkBelief",
5505
+ "beliefs.getBelief",
5506
+ "beliefs.getConfidenceHistory",
5507
+ "beliefs.listBeliefs",
5508
+ "beliefs.modulateConfidence",
5509
+ "beliefs.refineBelief",
5510
+ "beliefs.searchBeliefs",
5511
+ "bootstrap.generateSessionHandoff",
5512
+ "coding.getChangeHistory",
5513
+ "coding.getCodeContext",
5514
+ "coding.getFailureLog",
5515
+ "coding.recordAttempt",
5516
+ "context.analyzeTopicDensity",
5517
+ "context.applyAutoBranching",
5518
+ "context.compileContext",
5519
+ "context.discover",
5520
+ "context.discoverEntityConnections",
5521
+ "context.getLatticeCoverage",
5522
+ "context.recordScopeLearning",
5523
+ "context.seedBeliefLattice",
5524
+ "context.triggerBeliefReview",
5525
+ "contracts.createEpistemicContract",
5526
+ "contracts.evaluateContract",
5527
+ "contracts.getContractStatus",
5528
+ "contradictions.flagContradiction",
5529
+ "coordination.broadcastMessage",
5530
+ "coordination.claimFiles",
5531
+ "coordination.endSession",
5532
+ "coordination.getAgentInbox",
5533
+ "coordination.heartbeatSession",
5534
+ "coordination.listActiveSessions",
5535
+ "coordination.registerSession",
5536
+ "coordination.sendAgentMessage",
5537
+ "edges.createEdge",
5538
+ "edges.queryLineage",
5539
+ "evidence.addEvidence",
5540
+ "evidence.createEvidence",
5541
+ "evidence.getEvidence",
5542
+ "evidence.linkEvidence",
5543
+ "evidence.linkEvidenceToBelief",
5544
+ "evidence.linkEvidenceToQuestion",
5545
+ "evidence.listEvidence",
5546
+ "evidence.searchEvidence",
5547
+ "graph.detectConfirmationBias",
5548
+ "graph.findContradictions",
5549
+ "graph.getGraphGaps",
5550
+ "graph.getGraphNeighborhood",
5551
+ "graph.getGraphStructureAnalysis",
5552
+ "graph.getTopicCoverage",
5553
+ "graph.traceEntityImpact",
5554
+ "graph.traverseGraph",
5555
+ "graphAnalysis.listGraphIntelligenceQueries",
5556
+ "graphAnalysis.runGraphIntelligenceQuery",
5557
+ "identity.checkPermission",
5558
+ "identity.filterByPermission",
5559
+ "identity.whoami",
5560
+ "judgments.getAuditTrail",
5561
+ "judgments.recordJudgment",
5562
+ "lenses.applyLensToTopic",
5563
+ "lenses.createLens",
5564
+ "lenses.listLenses",
5565
+ "lenses.removeLensFromTopic",
5566
+ "observations.getObservationContext",
5567
+ "observations.ingestObservation",
5568
+ "ontologies.applyOntology",
5569
+ "ontologies.archiveOntology",
5570
+ "ontologies.createOntology",
5571
+ "ontologies.createOntologyVersion",
5572
+ "ontologies.deprecateOntologyVersion",
5573
+ "ontologies.getOntology",
5574
+ "ontologies.listOntologies",
5575
+ "ontologies.matchEntityType",
5576
+ "ontologies.publishOntologyVersion",
5577
+ "ontologies.resolveEffectiveOntology",
5578
+ "ontologies.updateOntology",
5579
+ "policy.manageWritePolicy",
5580
+ "questions.archiveQuestion",
5581
+ "questions.createQuestion",
5582
+ "questions.findMissingQuestions",
5583
+ "questions.getFalsificationQuestions",
5584
+ "questions.getHighPriorityQuestions",
5585
+ "questions.getQuestion",
5586
+ "questions.listQuestions",
5587
+ "questions.refineQuestion",
5588
+ "questions.updateQuestionStatus",
5589
+ "tasks.completeTask",
5590
+ "tasks.createTask",
5591
+ "tasks.listTasks",
5592
+ "tasks.updateTask",
5593
+ "topics.createTopic",
5594
+ "topics.getTopic",
5595
+ "topics.getTopicTree",
5596
+ "topics.listTopics",
5597
+ "topics.updateTopic",
5598
+ "worktrees.activateWorktree",
5599
+ "worktrees.addWorktree",
5600
+ "worktrees.beginBuildSession",
5601
+ "worktrees.listAllWorktrees",
5602
+ "worktrees.listCampaigns",
5603
+ "worktrees.listWorktrees",
5604
+ "worktrees.merge",
5605
+ "worktrees.openPullRequest",
5606
+ "worktrees.pipelineSnapshot",
5607
+ "worktrees.push",
5608
+ "worktrees.updateWorktreeMetadata",
5609
+ "worktrees.updateWorktreeTargets"
5610
+ ];
5109
5611
  var CONTRACTS = {
5110
5612
  "activate_worktree": { method: "POST", path: "/worktrees/activate", kind: "mutation", idempotent: true, surfaceIntent: "mcp_workflow" },
5111
5613
  "add_evidence": { method: "POST", path: "/evidence/add", kind: "mutation", idempotent: true, surfaceIntent: "compatibility" },
@@ -5181,6 +5683,7 @@ var CONTRACTS = {
5181
5683
  "list_beliefs": { method: "GET", path: "/beliefs", kind: "query", idempotent: false, surfaceIntent: "mcp_core" },
5182
5684
  "list_campaigns": { method: "GET", path: "/worktrees/campaigns", kind: "query", idempotent: false, surfaceIntent: "mcp_workflow" },
5183
5685
  "list_evidence": { method: "GET", path: "/evidence", kind: "query", idempotent: false, surfaceIntent: "mcp_core" },
5686
+ "list_graph_intelligence_queries": { method: "POST", path: "/graph-intelligence/queries", kind: "query", idempotent: false, surfaceIntent: "mcp_analysis" },
5184
5687
  "list_lenses": { method: "GET", path: "/lenses", kind: "query", idempotent: false, surfaceIntent: "mcp_workflow" },
5185
5688
  "list_ontologies": { method: "GET", path: "/ontologies", kind: "query", idempotent: false, surfaceIntent: "mcp_workflow" },
5186
5689
  "list_questions": { method: "GET", path: "/questions", kind: "query", idempotent: false, surfaceIntent: "mcp_core" },
@@ -5204,6 +5707,7 @@ var CONTRACTS = {
5204
5707
  "register_session": { method: "POST", path: "/coordination/register-session", kind: "mutation", idempotent: true, surfaceIntent: "system" },
5205
5708
  "remove_lens_from_topic": { method: "DELETE", path: "/lenses/apply", kind: "mutation", idempotent: true, surfaceIntent: "mcp_workflow" },
5206
5709
  "resolve_effective_ontology": { method: "POST", path: "/ontologies/effective", kind: "query", idempotent: false, surfaceIntent: "mcp_workflow" },
5710
+ "run_graph_intelligence_query": { method: "POST", path: "/graph-intelligence/run", kind: "query", idempotent: false, surfaceIntent: "mcp_analysis" },
5207
5711
  "search_beliefs": { method: "POST", path: "/beliefs/search", kind: "query", idempotent: false, surfaceIntent: "mcp_core" },
5208
5712
  "search_evidence": { method: "POST", path: "/evidence/search", kind: "query", idempotent: false, surfaceIntent: "mcp_core" },
5209
5713
  "seed_belief_lattice": { method: "POST", path: "/scope/belief-lattice/seed", kind: "mutation", idempotent: true, surfaceIntent: "system" },
@@ -5479,6 +5983,9 @@ function createFunctionSurfaceClient(config = {}) {
5479
5983
  listEvidence(input = {}, idempotencyKey) {
5480
5984
  return execute("list_evidence", input, idempotencyKey);
5481
5985
  },
5986
+ listGraphIntelligenceQueries(input = {}, idempotencyKey) {
5987
+ return execute("list_graph_intelligence_queries", input, idempotencyKey);
5988
+ },
5482
5989
  listLenses(input = {}, idempotencyKey) {
5483
5990
  return execute("list_lenses", input, idempotencyKey);
5484
5991
  },
@@ -5548,6 +6055,9 @@ function createFunctionSurfaceClient(config = {}) {
5548
6055
  resolveEffectiveOntology(input = {}, idempotencyKey) {
5549
6056
  return execute("resolve_effective_ontology", input, idempotencyKey);
5550
6057
  },
6058
+ runGraphIntelligenceQuery(input = {}, idempotencyKey) {
6059
+ return execute("run_graph_intelligence_query", input, idempotencyKey);
6060
+ },
5551
6061
  searchBeliefs(input = {}, idempotencyKey) {
5552
6062
  return execute("search_beliefs", input, idempotencyKey);
5553
6063
  },
@@ -9149,172 +9659,1585 @@ function createLucernClient(config = {}) {
9149
9659
  };
9150
9660
  }
9151
9661
 
9152
- // ../sdk/src/controlObjectOwnership.ts
9153
- var CONTROL_OBJECT_KINDS = [
9154
- "tenant",
9155
- "workspace",
9156
- "principal",
9157
- "tool",
9158
- "pack",
9159
- "ontology",
9160
- "belief",
9161
- "policy_rule"
9162
- ];
9163
- function defineCases(cases) {
9164
- return cases;
9662
+ // ../sdk/src/facade/context.ts
9663
+ function cleanString6(value) {
9664
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
9165
9665
  }
9166
- var CONTROL_OBJECT_OWNERSHIP_MATRIX = {
9167
- tenant: defineCases([
9168
- {
9169
- caseKey: "platform-record",
9170
- caseLabel: "Platform Record",
9171
- kind: "tenant",
9172
- canonicalOwnerScope: "platform",
9173
- editSurface: "platform_admin",
9174
- inheritanceRule: "none",
9175
- blastRadius: "tenant"
9666
+ function cleanNumber2(value) {
9667
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
9668
+ }
9669
+ function cleanBoolean2(value) {
9670
+ return typeof value === "boolean" ? value : void 0;
9671
+ }
9672
+ function buildCompileContextRequest2(topicId, input = {}) {
9673
+ const payload = { topicId };
9674
+ const query5 = cleanString6(input.query);
9675
+ if (query5) {
9676
+ payload.query = query5;
9677
+ }
9678
+ const budget = cleanNumber2(input.budget) ?? cleanNumber2(input.tokenBudget);
9679
+ if (budget !== void 0) {
9680
+ payload.budget = budget;
9681
+ }
9682
+ const ranking = cleanString6(input.ranking) ?? cleanString6(input.rankingProfile);
9683
+ if (ranking) {
9684
+ payload.ranking = ranking;
9685
+ }
9686
+ const limit = cleanNumber2(input.limit);
9687
+ if (limit !== void 0) {
9688
+ payload.limit = limit;
9689
+ }
9690
+ const maxDepth = cleanNumber2(input.maxDepth);
9691
+ if (maxDepth !== void 0) {
9692
+ payload.maxDepth = maxDepth;
9693
+ }
9694
+ const includeEntities = cleanBoolean2(input.includeEntities);
9695
+ if (includeEntities !== void 0) {
9696
+ payload.includeEntities = includeEntities;
9697
+ }
9698
+ const mode = cleanString6(input.mode);
9699
+ if (mode) {
9700
+ payload.mode = mode;
9701
+ }
9702
+ const includeFailures = cleanBoolean2(input.includeFailures);
9703
+ if (includeFailures !== void 0) {
9704
+ payload.includeFailures = includeFailures;
9705
+ }
9706
+ const worktreeId = cleanString6(input.worktreeId);
9707
+ if (worktreeId) {
9708
+ payload.worktreeId = worktreeId;
9709
+ }
9710
+ const sessionId = cleanString6(input.sessionId);
9711
+ if (sessionId) {
9712
+ payload.sessionId = sessionId;
9713
+ }
9714
+ if (Array.isArray(input.packWeightOverrides) && input.packWeightOverrides.length > 0) {
9715
+ payload.packWeightOverrides = input.packWeightOverrides;
9716
+ }
9717
+ return {
9718
+ path: "/api/platform/v1/context/compile",
9719
+ method: "POST",
9720
+ body: payload
9721
+ };
9722
+ }
9723
+ function createContextFacade(config) {
9724
+ return {
9725
+ compile(topicId, input = {}) {
9726
+ const request = buildCompileContextRequest2(topicId, input);
9727
+ return config.transport.request(request);
9176
9728
  }
9177
- ]),
9178
- workspace: defineCases([
9179
- {
9180
- caseKey: "tenant-workspace",
9181
- caseLabel: "Tenant Workspace",
9182
- kind: "workspace",
9183
- canonicalOwnerScope: "tenant",
9184
- editSurface: "tenant_admin",
9185
- inheritanceRule: "tenant_default_to_workspace",
9186
- blastRadius: "workspace"
9729
+ };
9730
+ }
9731
+
9732
+ // ../sdk/src/contracts/context-pack.contract.ts
9733
+ var CONTEXT_PACK_SCHEMA_VERSION = "1.0.0";
9734
+ var DEFAULT_COMPILATION_MODE = "standard";
9735
+ var SECTION_BUDGET_RATIOS = {
9736
+ invariants: 0.28,
9737
+ activeBeliefs: 0.3,
9738
+ openQuestions: 0.17,
9739
+ recentEvidence: 0.17,
9740
+ contradictions: 0.08
9741
+ };
9742
+ var MIN_TOKEN_BUDGET = 400;
9743
+ var MAX_TOKEN_BUDGET = 8e3;
9744
+ var DEFAULT_TOKEN_BUDGET = 1800;
9745
+ var MIN_CONTRADICTION_BUDGET = 40;
9746
+ var RANKING_WEIGHTS = {
9747
+ invariants: {
9748
+ query: 0.35,
9749
+ recency: 0.1,
9750
+ confidence: 0.4,
9751
+ beliefType: 0.15
9752
+ },
9753
+ activeBeliefs: {
9754
+ query: 0.5,
9755
+ recency: 0.2,
9756
+ confidence: 0.2,
9757
+ beliefType: 0.1
9758
+ },
9759
+ openQuestions: {
9760
+ query: 0.55,
9761
+ recency: 0.2,
9762
+ priority: 0.25
9763
+ },
9764
+ recentEvidence: {
9765
+ query: 0.6,
9766
+ recency: 0.4
9767
+ },
9768
+ contradictions: {
9769
+ query: 0.4,
9770
+ recency: 0.2,
9771
+ severity: 0.4
9772
+ }
9773
+ };
9774
+ var RECENCY_HALF_LIFE_DAYS = 30;
9775
+ var ENTITY_RANKING_WEIGHTS = {
9776
+ query: 0.4,
9777
+ connectivity: 0.6
9778
+ };
9779
+ var DEFAULT_ENTITY_LIMIT = 10;
9780
+ var MAX_ENTITY_LIMIT = 50;
9781
+ var BELIEF_TYPE_BONUS = {
9782
+ invariant: 1,
9783
+ tenet: 0.8,
9784
+ principle: 0.6
9785
+ };
9786
+ var DEFAULT_BELIEF_TYPE_BONUS = 0.4;
9787
+ var PRIORITY_SCORES = {
9788
+ critical: 1,
9789
+ high: 0.85,
9790
+ medium: 0.55,
9791
+ low: 0.35
9792
+ };
9793
+ var DEFAULT_PRIORITY_SCORE = 0.5;
9794
+ var SEVERITY_SCORES = {
9795
+ critical: 1,
9796
+ high: 0.85,
9797
+ medium: 0.6,
9798
+ low: 0.35
9799
+ };
9800
+ var DEFAULT_SEVERITY_SCORE = 0.5;
9801
+ var TOKENS_PER_WORD = 1.35;
9802
+ var MIN_TOKEN_ESTIMATE = 8;
9803
+
9804
+ // ../sdk/src/contextPackPolicy.ts
9805
+ function nowMs() {
9806
+ return Date.now();
9807
+ }
9808
+ function normalizeText(text) {
9809
+ return text.trim().toLowerCase();
9810
+ }
9811
+ function tokenHits(text, tokens) {
9812
+ if (tokens.length === 0) {
9813
+ return 1;
9814
+ }
9815
+ const haystack = normalizeText(text);
9816
+ let hits = 0;
9817
+ for (const token of tokens) {
9818
+ if (haystack.includes(token)) {
9819
+ hits += 1;
9187
9820
  }
9188
- ]),
9189
- principal: defineCases([
9190
- {
9191
- caseKey: "tenant-principal",
9192
- caseLabel: "Tenant Principal",
9193
- kind: "principal",
9194
- canonicalOwnerScope: "tenant",
9195
- editSurface: "tenant_admin",
9196
- inheritanceRule: "workspace_narrowing_only",
9197
- blastRadius: "resource"
9821
+ }
9822
+ return hits;
9823
+ }
9824
+ function clamp013(value) {
9825
+ if (!Number.isFinite(value)) {
9826
+ return 0;
9827
+ }
9828
+ return Math.max(0, Math.min(1, value));
9829
+ }
9830
+ function recencyScore(updatedAt, referenceTimeMs = nowMs()) {
9831
+ if (!updatedAt || !Number.isFinite(updatedAt)) {
9832
+ return 0.25;
9833
+ }
9834
+ const ageMs = Math.max(0, referenceTimeMs - updatedAt);
9835
+ const ageDays = ageMs / (1e3 * 60 * 60 * 24);
9836
+ const decay = 0.5 ** (ageDays / RECENCY_HALF_LIFE_DAYS);
9837
+ return clamp013(decay);
9838
+ }
9839
+ function confidenceScore(confidence) {
9840
+ if (typeof confidence !== "number" || !Number.isFinite(confidence)) {
9841
+ return 0.5;
9842
+ }
9843
+ return clamp013(confidence);
9844
+ }
9845
+ function priorityScore(priority) {
9846
+ const value = normalizeText(priority || "");
9847
+ return PRIORITY_SCORES[value] ?? DEFAULT_PRIORITY_SCORE;
9848
+ }
9849
+ function severityScore(severity) {
9850
+ const value = normalizeText(severity || "");
9851
+ return SEVERITY_SCORES[value] ?? DEFAULT_SEVERITY_SCORE;
9852
+ }
9853
+ function beliefTypeBonus(beliefType) {
9854
+ const value = normalizeText(beliefType || "");
9855
+ return BELIEF_TYPE_BONUS[value] ?? DEFAULT_BELIEF_TYPE_BONUS;
9856
+ }
9857
+ function resolveEffectiveWeights(overrides) {
9858
+ if (!overrides || overrides.length === 0) {
9859
+ return RANKING_WEIGHTS;
9860
+ }
9861
+ const result = { ...RANKING_WEIGHTS };
9862
+ for (const override of overrides) {
9863
+ const base = RANKING_WEIGHTS[override.section];
9864
+ if (base) {
9865
+ result[override.section] = { ...base, ...override.weights };
9198
9866
  }
9199
- ]),
9200
- tool: defineCases([
9201
- {
9202
- caseKey: "platform-core",
9203
- caseLabel: "Platform Core",
9204
- kind: "tool",
9205
- canonicalOwnerScope: "platform",
9206
- editSurface: "platform_admin",
9207
- inheritanceRule: "platform_seed_to_tenant",
9208
- blastRadius: "platform"
9209
- },
9210
- {
9211
- caseKey: "tenant-custom",
9212
- caseLabel: "Tenant Custom",
9213
- kind: "tool",
9214
- canonicalOwnerScope: "tenant",
9215
- editSurface: "tenant_admin",
9216
- inheritanceRule: "tenant_default_to_workspace",
9217
- blastRadius: "tenant"
9867
+ }
9868
+ return result;
9869
+ }
9870
+ function generateJustification(_section, candidate, queryTokens, weights) {
9871
+ const parts = [];
9872
+ const hits = tokenHits(candidate.text, queryTokens);
9873
+ if (queryTokens.length > 0 && hits > 0) {
9874
+ parts.push(`${hits}/${queryTokens.length} query terms matched`);
9875
+ } else if (queryTokens.length === 0) {
9876
+ parts.push("no query filter");
9877
+ }
9878
+ const ts = candidate.updatedAt || candidate.createdAt || null;
9879
+ if (ts && Number.isFinite(ts)) {
9880
+ const ageDays = Math.max(0, nowMs() - ts) / (1e3 * 60 * 60 * 24);
9881
+ if (ageDays < 1) {
9882
+ parts.push("updated today");
9883
+ } else if (ageDays < 7) {
9884
+ parts.push(`updated ${Math.floor(ageDays)}d ago`);
9885
+ } else if (ageDays < 30) {
9886
+ parts.push(`updated ${Math.floor(ageDays / 7)}w ago`);
9887
+ } else {
9888
+ parts.push(`updated ${Math.floor(ageDays)}d ago (decayed)`);
9889
+ }
9890
+ }
9891
+ if (weights.confidence !== void 0 && candidate.confidence !== null && candidate.confidence !== void 0) {
9892
+ parts.push(`confidence=${candidate.confidence.toFixed(2)}`);
9893
+ }
9894
+ if (weights.beliefType !== void 0 && candidate.beliefType) {
9895
+ parts.push(`type=${candidate.beliefType}`);
9896
+ }
9897
+ if (weights.priority !== void 0 && candidate.priority) {
9898
+ parts.push(`priority=${candidate.priority}`);
9899
+ }
9900
+ if (weights.severity !== void 0 && candidate.severity) {
9901
+ parts.push(`severity=${candidate.severity}`);
9902
+ }
9903
+ return parts.join(", ");
9904
+ }
9905
+ function computeBaselineScore(candidate, queryTokens) {
9906
+ const hits = tokenHits(candidate.text, queryTokens);
9907
+ return queryTokens.length === 0 ? 1 : hits;
9908
+ }
9909
+ function computeWeightedScore(section, candidate, queryTokens, effectiveWeights, referenceTimeMs) {
9910
+ const weights = (effectiveWeights ?? RANKING_WEIGHTS)[section];
9911
+ const queryComponent = queryTokens.length === 0 ? 0.4 : clamp013(tokenHits(candidate.text, queryTokens) / queryTokens.length);
9912
+ const recencyComponent = recencyScore(
9913
+ candidate.updatedAt || candidate.createdAt || null,
9914
+ referenceTimeMs
9915
+ );
9916
+ let score = queryComponent * weights.query + recencyComponent * weights.recency;
9917
+ if (weights.confidence !== void 0) {
9918
+ score += confidenceScore(candidate.confidence) * weights.confidence;
9919
+ }
9920
+ if (weights.beliefType !== void 0) {
9921
+ score += beliefTypeBonus(candidate.beliefType) * weights.beliefType;
9922
+ }
9923
+ if (weights.priority !== void 0) {
9924
+ score += priorityScore(candidate.priority) * weights.priority;
9925
+ }
9926
+ if (weights.severity !== void 0) {
9927
+ score += severityScore(candidate.severity) * weights.severity;
9928
+ }
9929
+ return score;
9930
+ }
9931
+ function rankContextSection(section, rows, queryTokens, limit, profile, options) {
9932
+ const effectiveWeights = options?.effectiveWeights;
9933
+ const includeJustifications = options?.includeJustifications ?? false;
9934
+ const referenceTimeMs = options?.referenceTimeMs;
9935
+ const scored = rows.map((row) => {
9936
+ const score = profile === "weighted_v1" ? computeWeightedScore(
9937
+ section,
9938
+ row,
9939
+ queryTokens,
9940
+ effectiveWeights,
9941
+ referenceTimeMs
9942
+ ) : computeBaselineScore(row, queryTokens);
9943
+ const result = { ...row, score };
9944
+ if (includeJustifications && profile === "weighted_v1") {
9945
+ const weights = (effectiveWeights ?? RANKING_WEIGHTS)[section];
9946
+ result.justification = generateJustification(section, row, queryTokens, weights);
9947
+ }
9948
+ return result;
9949
+ });
9950
+ const filtered = queryTokens.length === 0 ? scored : scored.filter((row) => row.score > 0);
9951
+ filtered.sort((left, right) => {
9952
+ if (right.score !== left.score) {
9953
+ return right.score - left.score;
9954
+ }
9955
+ const rightTs = right.updatedAt || right.createdAt || 0;
9956
+ const leftTs = left.updatedAt || left.createdAt || 0;
9957
+ return rightTs - leftTs;
9958
+ });
9959
+ return filtered.slice(0, limit);
9960
+ }
9961
+ function parseTokenBudget(value, fallback = DEFAULT_TOKEN_BUDGET) {
9962
+ const parsed = typeof value === "number" && Number.isFinite(value) ? Math.floor(value) : fallback;
9963
+ return Math.max(MIN_TOKEN_BUDGET, Math.min(MAX_TOKEN_BUDGET, parsed));
9964
+ }
9965
+ function estimateTokens(text) {
9966
+ const words = text.trim().split(/\s+/).filter(Boolean).length;
9967
+ return Math.max(MIN_TOKEN_ESTIMATE, Math.ceil(words * TOKENS_PER_WORD));
9968
+ }
9969
+ function buildInjectionPlan(args) {
9970
+ const tokenBudget = parseTokenBudget(args.tokenBudget);
9971
+ const trackExclusions = args.trackExclusions ?? false;
9972
+ const sectionBudgets = {
9973
+ invariants: Math.floor(tokenBudget * SECTION_BUDGET_RATIOS.invariants),
9974
+ activeBeliefs: Math.floor(
9975
+ tokenBudget * SECTION_BUDGET_RATIOS.activeBeliefs
9976
+ ),
9977
+ openQuestions: Math.floor(
9978
+ tokenBudget * SECTION_BUDGET_RATIOS.openQuestions
9979
+ ),
9980
+ recentEvidence: Math.floor(
9981
+ tokenBudget * SECTION_BUDGET_RATIOS.recentEvidence
9982
+ ),
9983
+ contradictions: Math.max(
9984
+ MIN_CONTRADICTION_BUDGET,
9985
+ Math.floor(tokenBudget * SECTION_BUDGET_RATIOS.contradictions)
9986
+ )
9987
+ };
9988
+ const selected = {
9989
+ invariants: [],
9990
+ activeBeliefs: [],
9991
+ openQuestions: [],
9992
+ recentEvidence: [],
9993
+ contradictions: []
9994
+ };
9995
+ const sectionUsage = {
9996
+ invariants: 0,
9997
+ activeBeliefs: 0,
9998
+ openQuestions: 0,
9999
+ recentEvidence: 0,
10000
+ contradictions: 0
10001
+ };
10002
+ const excludedItems = [];
10003
+ const pushItem = (section, id, text, score) => {
10004
+ const itemTokens = estimateTokens(text);
10005
+ const nextUsage = sectionUsage[section] + itemTokens;
10006
+ if (nextUsage > sectionBudgets[section]) {
10007
+ if (trackExclusions) {
10008
+ excludedItems.push({
10009
+ id,
10010
+ section,
10011
+ reason: "budget_exceeded",
10012
+ score: score ?? 0
10013
+ });
10014
+ }
10015
+ return;
9218
10016
  }
9219
- ]),
9220
- pack: defineCases([
9221
- {
9222
- caseKey: "platform-definition",
9223
- caseLabel: "Platform Definition",
9224
- kind: "pack",
9225
- canonicalOwnerScope: "platform",
9226
- editSurface: "platform_admin",
9227
- inheritanceRule: "platform_seed_to_tenant",
9228
- blastRadius: "platform"
9229
- },
9230
- {
9231
- caseKey: "tenant-installation",
9232
- caseLabel: "Tenant Installation",
9233
- kind: "pack",
9234
- canonicalOwnerScope: "tenant",
9235
- editSurface: "tenant_admin",
9236
- inheritanceRule: "platform_seed_to_tenant",
9237
- blastRadius: "tenant"
10017
+ selected[section].push(id);
10018
+ sectionUsage[section] = nextUsage;
10019
+ };
10020
+ for (const row of args.invariants) {
10021
+ pushItem("invariants", row.nodeId, row.canonicalText, row.score);
10022
+ }
10023
+ for (const row of args.activeBeliefs) {
10024
+ pushItem("activeBeliefs", row.nodeId, row.canonicalText, row.score);
10025
+ }
10026
+ for (const row of args.openQuestions) {
10027
+ pushItem("openQuestions", row.questionId, row.text, row.score);
10028
+ }
10029
+ for (const row of args.recentEvidence) {
10030
+ pushItem("recentEvidence", row.nodeId, row.canonicalText, row.score);
10031
+ }
10032
+ for (const row of args.contradictions) {
10033
+ pushItem("contradictions", row.contradictionId, row.description, row.score);
10034
+ }
10035
+ const estimatedTokens = sectionUsage.invariants + sectionUsage.activeBeliefs + sectionUsage.openQuestions + sectionUsage.recentEvidence + sectionUsage.contradictions;
10036
+ return {
10037
+ tokenBudget,
10038
+ estimatedTokens,
10039
+ sectionBudgets,
10040
+ sectionUsage,
10041
+ selected,
10042
+ ...trackExclusions ? { excludedItems } : {}
10043
+ };
10044
+ }
10045
+ function rankEntities(candidates, queryTokens, limit) {
10046
+ if (candidates.length === 0) {
10047
+ return [];
10048
+ }
10049
+ const effectiveLimit = Math.max(
10050
+ 1,
10051
+ Math.min(limit ?? DEFAULT_ENTITY_LIMIT, MAX_ENTITY_LIMIT)
10052
+ );
10053
+ const maxConnections = Math.max(
10054
+ 1,
10055
+ ...candidates.map(
10056
+ (candidate) => candidate.connectedBeliefCount + candidate.connectedEvidenceCount
10057
+ )
10058
+ );
10059
+ const scored = candidates.map((candidate) => {
10060
+ const searchText = `${candidate.title} ${candidate.entityType} ${candidate.canonicalText}`;
10061
+ const queryScore = queryTokens.length === 0 ? 0.4 : clamp013(tokenHits(searchText, queryTokens) / queryTokens.length);
10062
+ const totalConnections = candidate.connectedBeliefCount + candidate.connectedEvidenceCount;
10063
+ const connectivityScore = clamp013(totalConnections / maxConnections);
10064
+ const score = queryScore * ENTITY_RANKING_WEIGHTS.query + connectivityScore * ENTITY_RANKING_WEIGHTS.connectivity;
10065
+ return { ...candidate, score };
10066
+ });
10067
+ scored.sort((left, right) => {
10068
+ if (right.score !== left.score) {
10069
+ return right.score - left.score;
9238
10070
  }
9239
- ]),
9240
- ontology: defineCases([
9241
- {
9242
- caseKey: "platform-base",
9243
- caseLabel: "Platform Base",
9244
- kind: "ontology",
9245
- canonicalOwnerScope: "platform",
9246
- editSurface: "platform_admin",
9247
- inheritanceRule: "platform_seed_to_tenant",
9248
- blastRadius: "platform"
9249
- },
9250
- {
9251
- caseKey: "pack-overlay",
9252
- caseLabel: "Pack Overlay",
9253
- kind: "ontology",
9254
- canonicalOwnerScope: "platform",
9255
- editSurface: "platform_admin",
9256
- inheritanceRule: "pack_overlay_to_tenant",
9257
- blastRadius: "platform"
9258
- },
9259
- {
9260
- caseKey: "tenant-extension",
9261
- caseLabel: "Tenant Extension",
9262
- kind: "ontology",
9263
- canonicalOwnerScope: "tenant",
9264
- editSurface: "tenant_admin",
9265
- inheritanceRule: "topic_lineage_to_resource",
10071
+ const rightConn = right.connectedBeliefCount + right.connectedEvidenceCount;
10072
+ const leftConn = left.connectedBeliefCount + left.connectedEvidenceCount;
10073
+ return rightConn - leftConn;
10074
+ });
10075
+ return scored.slice(0, effectiveLimit);
10076
+ }
10077
+
10078
+ // ../sdk/src/contextPackSchema.ts
10079
+ var CONTEXT_PACK_SCHEMA_VERSION2 = "1.0.0";
10080
+ function isObject(value) {
10081
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10082
+ }
10083
+ function isString(value) {
10084
+ return typeof value === "string";
10085
+ }
10086
+ function isNumber(value) {
10087
+ return typeof value === "number" && Number.isFinite(value);
10088
+ }
10089
+ function isNullableNumber(value) {
10090
+ return value === null || isNumber(value);
10091
+ }
10092
+ function isStringArray(value) {
10093
+ return Array.isArray(value) && value.every((entry) => isString(entry));
10094
+ }
10095
+ function requireObject(parent, key, errors) {
10096
+ const value = parent[key];
10097
+ if (!isObject(value)) {
10098
+ errors.push(`Expected '${key}' to be an object`);
10099
+ return null;
10100
+ }
10101
+ return value;
10102
+ }
10103
+ function validateBeliefArray(key, value, errors) {
10104
+ if (!Array.isArray(value)) {
10105
+ errors.push(`Expected '${key}' to be an array`);
10106
+ return;
10107
+ }
10108
+ for (let index = 0; index < value.length; index += 1) {
10109
+ const row = value[index];
10110
+ if (!isObject(row)) {
10111
+ errors.push(`Expected '${key}[${index}]' to be an object`);
10112
+ continue;
10113
+ }
10114
+ if (!isString(row.nodeId)) {
10115
+ errors.push(`Expected '${key}[${index}].nodeId' to be a string`);
10116
+ }
10117
+ if (!isString(row.canonicalText)) {
10118
+ errors.push(`Expected '${key}[${index}].canonicalText' to be a string`);
10119
+ }
10120
+ if (!isNullableNumber(row.confidence)) {
10121
+ errors.push(`Expected '${key}[${index}].confidence' to be number|null`);
10122
+ }
10123
+ }
10124
+ }
10125
+ function validateQuestionArray(key, value, errors) {
10126
+ if (!Array.isArray(value)) {
10127
+ errors.push(`Expected '${key}' to be an array`);
10128
+ return;
10129
+ }
10130
+ for (let index = 0; index < value.length; index += 1) {
10131
+ const row = value[index];
10132
+ if (!isObject(row)) {
10133
+ errors.push(`Expected '${key}[${index}]' to be an object`);
10134
+ continue;
10135
+ }
10136
+ if (!isString(row.questionId)) {
10137
+ errors.push(`Expected '${key}[${index}].questionId' to be a string`);
10138
+ }
10139
+ if (!isString(row.text)) {
10140
+ errors.push(`Expected '${key}[${index}].text' to be a string`);
10141
+ }
10142
+ if (!isString(row.status)) {
10143
+ errors.push(`Expected '${key}[${index}].status' to be a string`);
10144
+ }
10145
+ }
10146
+ }
10147
+ function validateEvidenceArray(key, value, errors) {
10148
+ if (!Array.isArray(value)) {
10149
+ errors.push(`Expected '${key}' to be an array`);
10150
+ return;
10151
+ }
10152
+ for (let index = 0; index < value.length; index += 1) {
10153
+ const row = value[index];
10154
+ if (!isObject(row)) {
10155
+ errors.push(`Expected '${key}[${index}]' to be an object`);
10156
+ continue;
10157
+ }
10158
+ if (!isString(row.nodeId)) {
10159
+ errors.push(`Expected '${key}[${index}].nodeId' to be a string`);
10160
+ }
10161
+ if (!isString(row.canonicalText)) {
10162
+ errors.push(`Expected '${key}[${index}].canonicalText' to be a string`);
10163
+ }
10164
+ }
10165
+ }
10166
+ function validateEntityArray(key, value, errors) {
10167
+ if (!Array.isArray(value)) {
10168
+ errors.push(`Expected '${key}' to be an array`);
10169
+ return;
10170
+ }
10171
+ for (let index = 0; index < value.length; index += 1) {
10172
+ const row = value[index];
10173
+ if (!isObject(row)) {
10174
+ errors.push(`Expected '${key}[${index}]' to be an object`);
10175
+ continue;
10176
+ }
10177
+ if (!isString(row.nodeId)) {
10178
+ errors.push(`Expected '${key}[${index}].nodeId' to be a string`);
10179
+ }
10180
+ if (!isString(row.entityType)) {
10181
+ errors.push(`Expected '${key}[${index}].entityType' to be a string`);
10182
+ }
10183
+ if (!isString(row.title)) {
10184
+ errors.push(`Expected '${key}[${index}].title' to be a string`);
10185
+ }
10186
+ if (!isNumber(row.connectedBeliefCount)) {
10187
+ errors.push(`Expected '${key}[${index}].connectedBeliefCount' to be a number`);
10188
+ }
10189
+ if (!isNumber(row.connectedEvidenceCount)) {
10190
+ errors.push(`Expected '${key}[${index}].connectedEvidenceCount' to be a number`);
10191
+ }
10192
+ if (!isNumber(row.score)) {
10193
+ errors.push(`Expected '${key}[${index}].score' to be a number`);
10194
+ }
10195
+ }
10196
+ }
10197
+ function validateContradictionArray(key, value, errors) {
10198
+ if (!Array.isArray(value)) {
10199
+ errors.push(`Expected '${key}' to be an array`);
10200
+ return;
10201
+ }
10202
+ for (let index = 0; index < value.length; index += 1) {
10203
+ const row = value[index];
10204
+ if (!isObject(row)) {
10205
+ errors.push(`Expected '${key}[${index}]' to be an object`);
10206
+ continue;
10207
+ }
10208
+ if (!isString(row.contradictionId)) {
10209
+ errors.push(`Expected '${key}[${index}].contradictionId' to be a string`);
10210
+ }
10211
+ if (!isString(row.status)) {
10212
+ errors.push(`Expected '${key}[${index}].status' to be a string`);
10213
+ }
10214
+ }
10215
+ }
10216
+ function validateContextPackSchema(payload) {
10217
+ const errors = [];
10218
+ if (!isObject(payload)) {
10219
+ return {
10220
+ valid: false,
10221
+ errors: ["Expected context pack payload to be an object"]
10222
+ };
10223
+ }
10224
+ if (payload.schemaVersion !== CONTEXT_PACK_SCHEMA_VERSION2) {
10225
+ errors.push(
10226
+ `Expected schemaVersion='${CONTEXT_PACK_SCHEMA_VERSION2}', received '${String(
10227
+ payload.schemaVersion
10228
+ )}'`
10229
+ );
10230
+ }
10231
+ if (!isString(payload.topicId)) {
10232
+ errors.push("Expected 'topicId' to be a string");
10233
+ }
10234
+ if (!isString(payload.topicName)) {
10235
+ errors.push("Expected 'topicName' to be a string");
10236
+ }
10237
+ if (!isStringArray(payload.scopedTopicIds)) {
10238
+ errors.push("Expected 'scopedTopicIds' to be string[]");
10239
+ }
10240
+ if (!isNumber(payload.generatedAt)) {
10241
+ errors.push("Expected 'generatedAt' to be a number");
10242
+ }
10243
+ if (!isString(payload.ranking)) {
10244
+ errors.push("Expected 'ranking' to be a string");
10245
+ }
10246
+ validateBeliefArray("invariants", payload.invariants, errors);
10247
+ validateBeliefArray("activeBeliefs", payload.activeBeliefs, errors);
10248
+ validateQuestionArray("openQuestions", payload.openQuestions, errors);
10249
+ validateEvidenceArray("recentEvidence", payload.recentEvidence, errors);
10250
+ validateContradictionArray("contradictions", payload.contradictions, errors);
10251
+ if (payload.relatedEntities !== void 0 && payload.relatedEntities !== null) {
10252
+ validateEntityArray("relatedEntities", payload.relatedEntities, errors);
10253
+ }
10254
+ if (!Array.isArray(payload.contextNarrative)) {
10255
+ errors.push("Expected 'contextNarrative' to be an array");
10256
+ }
10257
+ const injectionPolicy = requireObject(payload, "injectionPolicy", errors);
10258
+ if (injectionPolicy) {
10259
+ if (!isNumber(injectionPolicy.tokenBudget)) {
10260
+ errors.push("Expected 'injectionPolicy.tokenBudget' to be a number");
10261
+ }
10262
+ if (!isNumber(injectionPolicy.estimatedTokens)) {
10263
+ errors.push("Expected 'injectionPolicy.estimatedTokens' to be a number");
10264
+ }
10265
+ }
10266
+ if (!isObject(payload.summary)) {
10267
+ errors.push("Expected 'summary' to be an object");
10268
+ }
10269
+ if (!isObject(payload.diagnostics)) {
10270
+ errors.push("Expected 'diagnostics' to be an object");
10271
+ }
10272
+ return {
10273
+ valid: errors.length === 0,
10274
+ errors
10275
+ };
10276
+ }
10277
+
10278
+ // ../sdk/src/contextPackCompiler.ts
10279
+ function assertContextPackSchema(payload) {
10280
+ const result = validateContextPackSchema(payload);
10281
+ if (!result.valid) {
10282
+ throw new Error(
10283
+ `Invalid context pack payload: ${result.errors.join("; ")}`
10284
+ );
10285
+ }
10286
+ }
10287
+ function asStringArray(value) {
10288
+ if (!Array.isArray(value)) {
10289
+ return [];
10290
+ }
10291
+ return value.map((entry) => typeof entry === "string" ? entry.trim() : "").filter((entry) => entry.length > 0);
10292
+ }
10293
+ function toPositiveInt(value, fallback, max) {
10294
+ if (typeof value !== "number" || !Number.isFinite(value)) {
10295
+ return fallback;
10296
+ }
10297
+ const floored = Math.floor(value);
10298
+ return Math.max(1, Math.min(floored, max));
10299
+ }
10300
+ function normalizeQueryTokens(query5) {
10301
+ if (!query5) {
10302
+ return [];
10303
+ }
10304
+ return query5.toLowerCase().split(/[^a-z0-9]+/).map((token) => token.trim()).filter((token) => token.length >= 2);
10305
+ }
10306
+ function parseRankingProfile(value) {
10307
+ return value === "baseline_v1" ? "baseline_v1" : "weighted_v1";
10308
+ }
10309
+ function beliefTypeOf(node) {
10310
+ if (typeof node.beliefType === "string") {
10311
+ return node.beliefType;
10312
+ }
10313
+ const metadata = node.metadata || {};
10314
+ if (typeof metadata.beliefType === "string") {
10315
+ return metadata.beliefType;
10316
+ }
10317
+ return "";
10318
+ }
10319
+ function questionStatusOf(node) {
10320
+ const metadata = node.metadata || {};
10321
+ const direct = typeof node.status === "string" ? node.status : "";
10322
+ const questionStatus = typeof metadata.questionStatus === "string" ? metadata.questionStatus : "";
10323
+ return (questionStatus || direct || "open").toLowerCase();
10324
+ }
10325
+ function isOpenQuestion(status) {
10326
+ return ![
10327
+ "answered",
10328
+ "archived",
10329
+ "closed",
10330
+ "resolved",
10331
+ "resolved_support",
10332
+ "resolved_contra",
10333
+ "belief_forked"
10334
+ ].includes(status);
10335
+ }
10336
+ function metadataText(payload) {
10337
+ return JSON.stringify(payload).toLowerCase();
10338
+ }
10339
+ function collectTopicNeighborhood(topics2, rootTopicId, maxDescendantDepth = 2) {
10340
+ const byId = /* @__PURE__ */ new Map();
10341
+ const children = /* @__PURE__ */ new Map();
10342
+ for (const topic of topics2) {
10343
+ const id = String(topic._id);
10344
+ byId.set(id, topic);
10345
+ if (!children.has(id)) {
10346
+ children.set(id, []);
10347
+ }
10348
+ }
10349
+ for (const topic of topics2) {
10350
+ if (!topic.parentTopicId) {
10351
+ continue;
10352
+ }
10353
+ const parent = String(topic.parentTopicId);
10354
+ const id = String(topic._id);
10355
+ const list = children.get(parent) || [];
10356
+ list.push(id);
10357
+ children.set(parent, list);
10358
+ }
10359
+ const selected = /* @__PURE__ */ new Set([rootTopicId]);
10360
+ let cursor = byId.get(rootTopicId);
10361
+ while (cursor?.parentTopicId) {
10362
+ const parentId = String(cursor.parentTopicId);
10363
+ if (selected.has(parentId)) {
10364
+ break;
10365
+ }
10366
+ selected.add(parentId);
10367
+ cursor = byId.get(parentId);
10368
+ }
10369
+ const queue = [
10370
+ { id: rootTopicId, depth: 0 }
10371
+ ];
10372
+ while (queue.length > 0) {
10373
+ const current = queue.shift();
10374
+ if (!current || current.depth >= maxDescendantDepth) {
10375
+ continue;
10376
+ }
10377
+ for (const childId of children.get(current.id) || []) {
10378
+ if (!selected.has(childId)) {
10379
+ selected.add(childId);
10380
+ }
10381
+ queue.push({ id: childId, depth: current.depth + 1 });
10382
+ }
10383
+ }
10384
+ return Array.from(selected);
10385
+ }
10386
+ function dedupeById(rows) {
10387
+ const seen = /* @__PURE__ */ new Set();
10388
+ const output = [];
10389
+ for (const row of rows) {
10390
+ const id = row?._id ? String(row._id) : "";
10391
+ if (!id || seen.has(id)) {
10392
+ continue;
10393
+ }
10394
+ seen.add(id);
10395
+ output.push(row);
10396
+ }
10397
+ return output;
10398
+ }
10399
+ function candidateTimestamp(candidate) {
10400
+ if (!candidate || typeof candidate !== "object") {
10401
+ return 0;
10402
+ }
10403
+ const record = candidate;
10404
+ const timestamps = [record.updatedAt, record.createdAt, record.generatedAt].filter(
10405
+ (value) => typeof value === "number" && Number.isFinite(value)
10406
+ );
10407
+ return timestamps.length > 0 ? Math.max(...timestamps) : 0;
10408
+ }
10409
+ function resolveReferenceTimeMs(...collections) {
10410
+ let maxTimestamp = 0;
10411
+ for (const collection of collections) {
10412
+ for (const item of collection) {
10413
+ const timestamp = candidateTimestamp(item);
10414
+ if (timestamp > maxTimestamp) {
10415
+ maxTimestamp = timestamp;
10416
+ }
10417
+ }
10418
+ }
10419
+ return maxTimestamp;
10420
+ }
10421
+ function planContextPackCompilation(input) {
10422
+ const args = input.args ?? {};
10423
+ const topicId = String(input.topic._id);
10424
+ const queryText = typeof args.query === "string" && args.query.trim().length > 0 ? args.query.trim() : void 0;
10425
+ const tokens = normalizeQueryTokens(queryText);
10426
+ const limit = toPositiveInt(args.limit, 8, 25);
10427
+ const rankingProfile = parseRankingProfile(
10428
+ typeof args.ranking === "string" ? args.ranking : args.rankingProfile
10429
+ );
10430
+ const tokenBudget = parseTokenBudget(
10431
+ typeof args.budget === "number" ? args.budget : args.tokenBudget,
10432
+ 1800
10433
+ );
10434
+ const topicDepth = typeof input.topic.depth === "number" && Number.isFinite(input.topic.depth) ? input.topic.depth : 0;
10435
+ const requestedMaxDepth = typeof args.maxDepth === "number" && Number.isFinite(args.maxDepth) ? Math.max(1, Math.min(Math.floor(args.maxDepth), 6)) : void 0;
10436
+ const descendantDepth = requestedMaxDepth ?? (topicDepth <= 1 ? 4 : 2);
10437
+ const includeEntities = args.includeEntities !== false;
10438
+ const compilationMode = args.mode === "delta" ? "delta" : DEFAULT_COMPILATION_MODE;
10439
+ const includeFailures = compilationMode === "delta" || args.includeFailures === true;
10440
+ const worktreeId = typeof args.worktreeId === "string" && args.worktreeId.trim().length > 0 ? args.worktreeId.trim() : void 0;
10441
+ const sessionId = typeof args.sessionId === "string" && args.sessionId.trim().length > 0 ? args.sessionId.trim() : void 0;
10442
+ const packWeightOverrides = Array.isArray(args.packWeightOverrides) ? args.packWeightOverrides : void 0;
10443
+ const effectiveWeights = resolveEffectiveWeights(packWeightOverrides);
10444
+ let scopedTopicIds = collectTopicNeighborhood(
10445
+ input.allTopics,
10446
+ topicId,
10447
+ descendantDepth
10448
+ );
10449
+ const allowedTopicIds = asStringArray(args.allowedTopicIds);
10450
+ if (allowedTopicIds.length > 0) {
10451
+ const allowedSet = new Set(allowedTopicIds);
10452
+ if (!allowedSet.has(topicId)) {
10453
+ throw new Error(`Access denied to compile context for topic ${topicId}.`);
10454
+ }
10455
+ scopedTopicIds = scopedTopicIds.filter((id) => allowedSet.has(id));
10456
+ }
10457
+ return {
10458
+ topicId,
10459
+ ...queryText ? { queryText } : {},
10460
+ tokens,
10461
+ limit,
10462
+ rankingProfile,
10463
+ tokenBudget,
10464
+ descendantDepth,
10465
+ includeEntities,
10466
+ compilationMode,
10467
+ includeFailures,
10468
+ ...worktreeId ? { worktreeId } : {},
10469
+ ...sessionId ? { sessionId } : {},
10470
+ ...packWeightOverrides ? { packWeightOverrides } : {},
10471
+ effectiveWeights,
10472
+ scopedTopicIds
10473
+ };
10474
+ }
10475
+ function compileContextPackFromSnapshot(snapshot) {
10476
+ const uniqueBeliefs = dedupeById(snapshot.beliefs);
10477
+ const uniqueQuestions = dedupeById(snapshot.questions);
10478
+ const uniqueEvidence = dedupeById(snapshot.evidence);
10479
+ const uniqueContradictions = dedupeById(snapshot.contradictions);
10480
+ const referenceTimeMs = resolveReferenceTimeMs(
10481
+ [snapshot.topic],
10482
+ uniqueBeliefs,
10483
+ uniqueQuestions,
10484
+ uniqueEvidence,
10485
+ uniqueContradictions,
10486
+ snapshot.entities
10487
+ ) || 0;
10488
+ const rankOptions = {
10489
+ effectiveWeights: snapshot.plan.effectiveWeights,
10490
+ includeJustifications: snapshot.plan.compilationMode === "delta",
10491
+ referenceTimeMs
10492
+ };
10493
+ const invariantCandidates = uniqueBeliefs.filter((belief) => beliefTypeOf(belief).toLowerCase() === "invariant").map((belief) => ({
10494
+ nodeId: String(belief._id),
10495
+ canonicalText: String(belief.canonicalText || ""),
10496
+ confidence: typeof belief.confidence === "number" ? belief.confidence : null,
10497
+ beliefType: beliefTypeOf(belief) || "invariant",
10498
+ updatedAt: belief.updatedAt || belief.createdAt || null
10499
+ }));
10500
+ const invariants = rankContextSection(
10501
+ "invariants",
10502
+ invariantCandidates.map((candidate) => ({
10503
+ ...candidate,
10504
+ id: candidate.nodeId,
10505
+ text: `${candidate.canonicalText} ${candidate.beliefType}`
10506
+ })),
10507
+ snapshot.plan.tokens,
10508
+ snapshot.plan.limit,
10509
+ snapshot.plan.rankingProfile,
10510
+ rankOptions
10511
+ ).map((row) => ({
10512
+ nodeId: row.nodeId,
10513
+ canonicalText: row.canonicalText,
10514
+ confidence: row.confidence,
10515
+ beliefType: row.beliefType,
10516
+ score: row.score,
10517
+ ...row.justification ? { justification: row.justification } : {}
10518
+ }));
10519
+ const activeBeliefCandidates = uniqueBeliefs.filter((belief) => (belief.status || "active") !== "archived").map((belief) => ({
10520
+ nodeId: String(belief._id),
10521
+ canonicalText: String(belief.canonicalText || ""),
10522
+ confidence: typeof belief.confidence === "number" ? belief.confidence : null,
10523
+ beliefType: beliefTypeOf(belief) || null,
10524
+ status: belief.status || "active",
10525
+ updatedAt: belief.updatedAt || belief.createdAt || null,
10526
+ metadataText: belief.metadata && typeof belief.metadata === "object" ? metadataText(belief.metadata) : ""
10527
+ }));
10528
+ const activeBeliefs = rankContextSection(
10529
+ "activeBeliefs",
10530
+ activeBeliefCandidates.map((candidate) => ({
10531
+ ...candidate,
10532
+ id: candidate.nodeId,
10533
+ text: `${candidate.canonicalText} ${candidate.metadataText}`
10534
+ })),
10535
+ snapshot.plan.tokens,
10536
+ snapshot.plan.limit,
10537
+ snapshot.plan.rankingProfile,
10538
+ rankOptions
10539
+ ).map((row) => ({
10540
+ nodeId: row.nodeId,
10541
+ canonicalText: row.canonicalText,
10542
+ confidence: row.confidence,
10543
+ beliefType: row.beliefType,
10544
+ status: row.status,
10545
+ updatedAt: row.updatedAt,
10546
+ score: row.score,
10547
+ ...row.justification ? { justification: row.justification } : {}
10548
+ }));
10549
+ const openQuestionCandidates = uniqueQuestions.map((question) => {
10550
+ const status = questionStatusOf(question);
10551
+ const metadata = question.metadata && typeof question.metadata === "object" ? question.metadata : {};
10552
+ return {
10553
+ questionId: String(question._id),
10554
+ text: String(question.canonicalText || ""),
10555
+ status,
10556
+ priority: typeof metadata.priority === "string" ? metadata.priority : "medium",
10557
+ updatedAt: question.updatedAt || question.createdAt || null,
10558
+ metadataText: metadataText(metadata)
10559
+ };
10560
+ }).filter((row) => isOpenQuestion(row.status));
10561
+ const openQuestions = rankContextSection(
10562
+ "openQuestions",
10563
+ openQuestionCandidates.map((candidate) => ({
10564
+ ...candidate,
10565
+ id: candidate.questionId,
10566
+ text: `${candidate.text} ${candidate.metadataText}`
10567
+ })),
10568
+ snapshot.plan.tokens,
10569
+ snapshot.plan.limit,
10570
+ snapshot.plan.rankingProfile,
10571
+ rankOptions
10572
+ ).map((row) => ({
10573
+ questionId: row.questionId,
10574
+ text: row.text,
10575
+ status: row.status,
10576
+ priority: row.priority,
10577
+ updatedAt: row.updatedAt,
10578
+ score: row.score,
10579
+ ...row.justification ? { justification: row.justification } : {}
10580
+ }));
10581
+ const evidenceCandidates = uniqueEvidence.map((item) => {
10582
+ const metadata = item.metadata && typeof item.metadata === "object" ? item.metadata : {};
10583
+ return {
10584
+ nodeId: String(item._id),
10585
+ canonicalText: String(item.canonicalText || ""),
10586
+ sourceUrl: typeof metadata.sourceUrl === "string" && metadata.sourceUrl || typeof item.sourceUrl === "string" && item.sourceUrl || null,
10587
+ kind: typeof metadata.kind === "string" && metadata.kind || "observation",
10588
+ createdAt: item.createdAt || null,
10589
+ updatedAt: item.updatedAt || item.createdAt || null,
10590
+ metadataText: metadataText(metadata)
10591
+ };
10592
+ });
10593
+ const recentEvidence = rankContextSection(
10594
+ "recentEvidence",
10595
+ evidenceCandidates.map((candidate) => ({
10596
+ ...candidate,
10597
+ id: candidate.nodeId,
10598
+ text: `${candidate.canonicalText} ${candidate.metadataText}`
10599
+ })),
10600
+ snapshot.plan.tokens,
10601
+ snapshot.plan.limit,
10602
+ snapshot.plan.rankingProfile,
10603
+ rankOptions
10604
+ ).map((row) => ({
10605
+ nodeId: row.nodeId,
10606
+ canonicalText: row.canonicalText,
10607
+ sourceUrl: row.sourceUrl,
10608
+ kind: row.kind,
10609
+ createdAt: row.createdAt,
10610
+ score: row.score,
10611
+ ...row.justification ? { justification: row.justification } : {}
10612
+ }));
10613
+ const contradictionCandidates = uniqueContradictions.map((row) => {
10614
+ const weight = typeof row.weight === "number" ? row.weight : 0;
10615
+ const severity = weight <= -0.9 ? "critical" : weight <= -0.7 ? "high" : weight <= -0.5 ? "medium" : "low";
10616
+ return {
10617
+ contradictionId: String(row._id || row.globalId || ""),
10618
+ severity,
10619
+ status: "active",
10620
+ description: row.context || row.description || row.summary || "",
10621
+ updatedAt: row.updatedAt || row.createdAt || null
10622
+ };
10623
+ });
10624
+ const contradictions2 = rankContextSection(
10625
+ "contradictions",
10626
+ contradictionCandidates.map((candidate) => ({
10627
+ ...candidate,
10628
+ id: candidate.contradictionId,
10629
+ text: `${candidate.description} ${candidate.severity}`
10630
+ })),
10631
+ snapshot.plan.tokens,
10632
+ snapshot.plan.limit,
10633
+ snapshot.plan.rankingProfile,
10634
+ rankOptions
10635
+ ).map((row) => ({
10636
+ contradictionId: row.contradictionId,
10637
+ severity: row.severity,
10638
+ status: row.status,
10639
+ description: row.description,
10640
+ score: row.score,
10641
+ ...row.justification ? { justification: row.justification } : {}
10642
+ }));
10643
+ const entityCandidates = snapshot.entities.map((row) => ({
10644
+ nodeId: String(row._id),
10645
+ entityType: String(row.nodeType || ""),
10646
+ title: String(row.title || ""),
10647
+ canonicalText: String(row.canonicalText || ""),
10648
+ connectedBeliefCount: typeof row.connectedBeliefCount === "number" ? row.connectedBeliefCount : 0,
10649
+ connectedEvidenceCount: typeof row.connectedEvidenceCount === "number" ? row.connectedEvidenceCount : 0,
10650
+ metadata: row.metadata && typeof row.metadata === "object" ? row.metadata : {},
10651
+ updatedAt: row.updatedAt || null
10652
+ }));
10653
+ const entityLimit = toPositiveInt(
10654
+ snapshot.plan.limit,
10655
+ DEFAULT_ENTITY_LIMIT,
10656
+ MAX_ENTITY_LIMIT
10657
+ );
10658
+ const rankedEntities = snapshot.plan.includeEntities ? rankEntities(entityCandidates, snapshot.plan.tokens, entityLimit).map(
10659
+ (row) => ({
10660
+ nodeId: row.nodeId,
10661
+ entityType: row.entityType,
10662
+ title: row.title,
10663
+ connectedBeliefCount: row.connectedBeliefCount,
10664
+ connectedEvidenceCount: row.connectedEvidenceCount,
10665
+ score: row.score,
10666
+ ...Object.keys(row.metadata).length > 0 ? { metadata: row.metadata } : {}
10667
+ })
10668
+ ) : void 0;
10669
+ let failureContext;
10670
+ if (snapshot.plan.includeFailures && snapshot.failures) {
10671
+ const allFailures = snapshot.failures.filter((node) => {
10672
+ const metadata = node.metadata || {};
10673
+ return metadata.failedApproach === true || metadata.isFailedAttempt === true;
10674
+ });
10675
+ const rankedFailures = rankContextSection(
10676
+ "recentEvidence",
10677
+ allFailures.map((node) => ({
10678
+ id: String(node._id),
10679
+ text: String(node.canonicalText || ""),
10680
+ createdAt: node.createdAt || null,
10681
+ updatedAt: node.updatedAt || node.createdAt || null
10682
+ })),
10683
+ snapshot.plan.tokens,
10684
+ 10,
10685
+ snapshot.plan.rankingProfile,
10686
+ rankOptions
10687
+ );
10688
+ const failures = rankedFailures.map((row) => {
10689
+ const original = allFailures.find((node) => String(node._id) === row.id);
10690
+ const metadata = original?.metadata || {};
10691
+ return {
10692
+ attemptId: row.id,
10693
+ approach: String(row.text || ""),
10694
+ outcome: String(metadata.errorMessage || "Failed"),
10695
+ recordedAt: row.createdAt || referenceTimeMs || 0,
10696
+ score: row.score
10697
+ };
10698
+ });
10699
+ const failureTexts = new Set(
10700
+ failures.map((failure) => failure.approach.toLowerCase().slice(0, 100))
10701
+ );
10702
+ const suppressionIds = /* @__PURE__ */ new Set();
10703
+ if (snapshot.plan.sessionId && failureTexts.size > 0) {
10704
+ for (const evidenceRow of recentEvidence) {
10705
+ const evidenceText = evidenceRow.canonicalText.toLowerCase().slice(0, 100);
10706
+ for (const failureText of failureTexts) {
10707
+ if (evidenceText.includes(failureText) || failureText.includes(evidenceText)) {
10708
+ suppressionIds.add(evidenceRow.nodeId);
10709
+ break;
10710
+ }
10711
+ }
10712
+ }
10713
+ }
10714
+ if (failures.length > 0) {
10715
+ failureContext = {
10716
+ failures,
10717
+ suppressedIds: Array.from(suppressionIds)
10718
+ };
10719
+ }
10720
+ }
10721
+ const suppressionSet = new Set(failureContext?.suppressedIds || []);
10722
+ const effectiveEvidence = suppressionSet.size > 0 ? recentEvidence.filter((row) => !suppressionSet.has(row.nodeId)) : recentEvidence;
10723
+ const suppressedEvidenceIds = suppressionSet.size > 0 ? recentEvidence.filter((row) => suppressionSet.has(row.nodeId)).map((row) => row.nodeId) : [];
10724
+ const summary = {
10725
+ totalBeliefs: uniqueBeliefs.length,
10726
+ invariants: invariants.length,
10727
+ openQuestions: openQuestions.length,
10728
+ evidenceItems: uniqueEvidence.length,
10729
+ contradictions: contradictions2.length,
10730
+ ...rankedEntities ? { relatedEntities: rankedEntities.length } : {},
10731
+ scopedTopics: snapshot.plan.scopedTopicIds.length,
10732
+ descendantDepth: snapshot.plan.descendantDepth,
10733
+ query: snapshot.plan.queryText || null
10734
+ };
10735
+ const injectionPolicy = buildInjectionPlan({
10736
+ tokenBudget: snapshot.plan.tokenBudget,
10737
+ invariants: invariants.map((row) => ({
10738
+ nodeId: row.nodeId,
10739
+ canonicalText: row.canonicalText,
10740
+ score: row.score
10741
+ })),
10742
+ activeBeliefs: activeBeliefs.map((row) => ({
10743
+ nodeId: row.nodeId,
10744
+ canonicalText: row.canonicalText,
10745
+ score: row.score
10746
+ })),
10747
+ openQuestions: openQuestions.map((row) => ({
10748
+ questionId: row.questionId,
10749
+ text: row.text,
10750
+ score: row.score
10751
+ })),
10752
+ recentEvidence: effectiveEvidence.map((row) => ({
10753
+ nodeId: row.nodeId,
10754
+ canonicalText: row.canonicalText,
10755
+ score: row.score
10756
+ })),
10757
+ contradictions: contradictions2.map((row) => ({
10758
+ contradictionId: row.contradictionId,
10759
+ description: row.description,
10760
+ score: row.score
10761
+ })),
10762
+ trackExclusions: snapshot.plan.compilationMode === "delta"
10763
+ });
10764
+ const contextNarrative = [
10765
+ "Prefer invariant beliefs as hard constraints while reasoning over this scope.",
10766
+ "Treat open questions as unresolved work items and avoid claiming closure without evidence.",
10767
+ "Use recent evidence for implementation context before creating new beliefs.",
10768
+ "When contradictions exist, resolve explicitly (fork, lower confidence, or gather counter-evidence).",
10769
+ `Apply injection token budget of ${injectionPolicy.tokenBudget} with section quotas before prompt assembly.`
10770
+ ];
10771
+ const deltaReport = snapshot.plan.compilationMode === "delta" && snapshot.plan.worktreeId ? {
10772
+ changedItems: [],
10773
+ verificationObligations: [],
10774
+ referencePoint: snapshot.plan.worktreeId
10775
+ } : void 0;
10776
+ const excludedItems = [
10777
+ ...injectionPolicy.excludedItems || [],
10778
+ ...suppressedEvidenceIds.map((id) => ({
10779
+ id,
10780
+ section: "recentEvidence",
10781
+ reason: "anti_repetition",
10782
+ score: recentEvidence.find((row) => row.nodeId === id)?.score ?? 0
10783
+ }))
10784
+ ];
10785
+ const result = {
10786
+ schemaVersion: CONTEXT_PACK_SCHEMA_VERSION,
10787
+ topicId: snapshot.plan.topicId,
10788
+ topicName: snapshot.topic.name || "Untitled Topic",
10789
+ scopedTopicIds: snapshot.plan.scopedTopicIds,
10790
+ generatedAt: referenceTimeMs,
10791
+ rankingProfile: snapshot.plan.rankingProfile,
10792
+ summary,
10793
+ invariants,
10794
+ activeBeliefs,
10795
+ openQuestions,
10796
+ recentEvidence: effectiveEvidence,
10797
+ contradictions: contradictions2,
10798
+ ...rankedEntities ? { relatedEntities: rankedEntities } : {},
10799
+ contextNarrative,
10800
+ injectionPolicy: {
10801
+ ...injectionPolicy,
10802
+ ...excludedItems.length > 0 ? { excludedItems } : {}
10803
+ },
10804
+ diagnostics: {
10805
+ itemsScored: invariantCandidates.length + activeBeliefCandidates.length + openQuestionCandidates.length + evidenceCandidates.length + contradictionCandidates.length + entityCandidates.length,
10806
+ tokenBudgetUtilization: injectionPolicy.tokenBudget === 0 ? 0 : Number(
10807
+ (injectionPolicy.estimatedTokens / injectionPolicy.tokenBudget).toFixed(4)
10808
+ ),
10809
+ referenceTimeMs
10810
+ },
10811
+ ...snapshot.plan.compilationMode !== "standard" ? { compilationMode: snapshot.plan.compilationMode } : {},
10812
+ ...failureContext ? { failureContext } : {},
10813
+ ...deltaReport ? { deltaReport } : {},
10814
+ ...snapshot.plan.packWeightOverrides && snapshot.plan.packWeightOverrides.length > 0 ? { appliedWeightOverrides: snapshot.plan.packWeightOverrides } : {}
10815
+ };
10816
+ assertContextPackSchema(result);
10817
+ return result;
10818
+ }
10819
+
10820
+ // ../sdk/src/controlObjectOwnership.ts
10821
+ var CONTROL_OBJECT_KINDS = [
10822
+ "tenant",
10823
+ "workspace",
10824
+ "principal",
10825
+ "tool",
10826
+ "pack",
10827
+ "ontology",
10828
+ "belief",
10829
+ "policy_rule"
10830
+ ];
10831
+ var CONTROL_OBJECT_OWNER_SCOPES = [
10832
+ "platform",
10833
+ "tenant",
10834
+ "workspace",
10835
+ "resource"
10836
+ ];
10837
+ var CONTROL_OBJECT_EDIT_SURFACES = [
10838
+ "platform_admin",
10839
+ "tenant_admin",
10840
+ "workspace_admin",
10841
+ "graph_worktree"
10842
+ ];
10843
+ var CONTROL_OBJECT_INHERITANCE_RULES = [
10844
+ "none",
10845
+ "platform_seed_to_tenant",
10846
+ "tenant_default_to_workspace",
10847
+ "workspace_narrowing_only",
10848
+ "pack_overlay_to_tenant",
10849
+ "topic_lineage_to_resource"
10850
+ ];
10851
+ var CONTROL_OBJECT_BLAST_RADII = [
10852
+ "platform",
10853
+ "tenant",
10854
+ "workspace",
10855
+ "resource"
10856
+ ];
10857
+ function defineCases(cases) {
10858
+ return cases;
10859
+ }
10860
+ var CONTROL_OBJECT_OWNERSHIP_MATRIX = {
10861
+ tenant: defineCases([
10862
+ {
10863
+ caseKey: "platform-record",
10864
+ caseLabel: "Platform Record",
10865
+ kind: "tenant",
10866
+ canonicalOwnerScope: "platform",
10867
+ editSurface: "platform_admin",
10868
+ inheritanceRule: "none",
9266
10869
  blastRadius: "tenant"
9267
10870
  }
9268
10871
  ]),
9269
- belief: defineCases([
10872
+ workspace: defineCases([
9270
10873
  {
9271
- caseKey: "topic-resource",
9272
- caseLabel: "Topic Resource",
9273
- kind: "belief",
9274
- canonicalOwnerScope: "resource",
9275
- editSurface: "graph_worktree",
9276
- inheritanceRule: "topic_lineage_to_resource",
10874
+ caseKey: "tenant-workspace",
10875
+ caseLabel: "Tenant Workspace",
10876
+ kind: "workspace",
10877
+ canonicalOwnerScope: "tenant",
10878
+ editSurface: "tenant_admin",
10879
+ inheritanceRule: "tenant_default_to_workspace",
10880
+ blastRadius: "workspace"
10881
+ }
10882
+ ]),
10883
+ principal: defineCases([
10884
+ {
10885
+ caseKey: "tenant-principal",
10886
+ caseLabel: "Tenant Principal",
10887
+ kind: "principal",
10888
+ canonicalOwnerScope: "tenant",
10889
+ editSurface: "tenant_admin",
10890
+ inheritanceRule: "workspace_narrowing_only",
9277
10891
  blastRadius: "resource"
9278
10892
  }
9279
10893
  ]),
9280
- policy_rule: defineCases([
10894
+ tool: defineCases([
9281
10895
  {
9282
- caseKey: "platform-baseline",
9283
- caseLabel: "Platform Baseline",
9284
- kind: "policy_rule",
10896
+ caseKey: "platform-core",
10897
+ caseLabel: "Platform Core",
10898
+ kind: "tool",
9285
10899
  canonicalOwnerScope: "platform",
9286
10900
  editSurface: "platform_admin",
9287
10901
  inheritanceRule: "platform_seed_to_tenant",
9288
10902
  blastRadius: "platform"
9289
10903
  },
9290
10904
  {
9291
- caseKey: "tenant-bundle",
9292
- caseLabel: "Tenant Bundle",
9293
- kind: "policy_rule",
10905
+ caseKey: "tenant-custom",
10906
+ caseLabel: "Tenant Custom",
10907
+ kind: "tool",
9294
10908
  canonicalOwnerScope: "tenant",
9295
10909
  editSurface: "tenant_admin",
9296
10910
  inheritanceRule: "tenant_default_to_workspace",
9297
10911
  blastRadius: "tenant"
9298
- },
9299
- {
9300
- caseKey: "workspace-override",
9301
- caseLabel: "Workspace Override",
9302
- kind: "policy_rule",
9303
- canonicalOwnerScope: "workspace",
9304
- editSurface: "workspace_admin",
9305
- inheritanceRule: "none",
9306
- blastRadius: "workspace"
10912
+ }
10913
+ ]),
10914
+ pack: defineCases([
10915
+ {
10916
+ caseKey: "platform-definition",
10917
+ caseLabel: "Platform Definition",
10918
+ kind: "pack",
10919
+ canonicalOwnerScope: "platform",
10920
+ editSurface: "platform_admin",
10921
+ inheritanceRule: "platform_seed_to_tenant",
10922
+ blastRadius: "platform"
10923
+ },
10924
+ {
10925
+ caseKey: "tenant-installation",
10926
+ caseLabel: "Tenant Installation",
10927
+ kind: "pack",
10928
+ canonicalOwnerScope: "tenant",
10929
+ editSurface: "tenant_admin",
10930
+ inheritanceRule: "platform_seed_to_tenant",
10931
+ blastRadius: "tenant"
10932
+ }
10933
+ ]),
10934
+ ontology: defineCases([
10935
+ {
10936
+ caseKey: "platform-base",
10937
+ caseLabel: "Platform Base",
10938
+ kind: "ontology",
10939
+ canonicalOwnerScope: "platform",
10940
+ editSurface: "platform_admin",
10941
+ inheritanceRule: "platform_seed_to_tenant",
10942
+ blastRadius: "platform"
10943
+ },
10944
+ {
10945
+ caseKey: "pack-overlay",
10946
+ caseLabel: "Pack Overlay",
10947
+ kind: "ontology",
10948
+ canonicalOwnerScope: "platform",
10949
+ editSurface: "platform_admin",
10950
+ inheritanceRule: "pack_overlay_to_tenant",
10951
+ blastRadius: "platform"
10952
+ },
10953
+ {
10954
+ caseKey: "tenant-extension",
10955
+ caseLabel: "Tenant Extension",
10956
+ kind: "ontology",
10957
+ canonicalOwnerScope: "tenant",
10958
+ editSurface: "tenant_admin",
10959
+ inheritanceRule: "topic_lineage_to_resource",
10960
+ blastRadius: "tenant"
10961
+ }
10962
+ ]),
10963
+ belief: defineCases([
10964
+ {
10965
+ caseKey: "topic-resource",
10966
+ caseLabel: "Topic Resource",
10967
+ kind: "belief",
10968
+ canonicalOwnerScope: "resource",
10969
+ editSurface: "graph_worktree",
10970
+ inheritanceRule: "topic_lineage_to_resource",
10971
+ blastRadius: "resource"
10972
+ }
10973
+ ]),
10974
+ policy_rule: defineCases([
10975
+ {
10976
+ caseKey: "platform-baseline",
10977
+ caseLabel: "Platform Baseline",
10978
+ kind: "policy_rule",
10979
+ canonicalOwnerScope: "platform",
10980
+ editSurface: "platform_admin",
10981
+ inheritanceRule: "platform_seed_to_tenant",
10982
+ blastRadius: "platform"
10983
+ },
10984
+ {
10985
+ caseKey: "tenant-bundle",
10986
+ caseLabel: "Tenant Bundle",
10987
+ kind: "policy_rule",
10988
+ canonicalOwnerScope: "tenant",
10989
+ editSurface: "tenant_admin",
10990
+ inheritanceRule: "tenant_default_to_workspace",
10991
+ blastRadius: "tenant"
10992
+ },
10993
+ {
10994
+ caseKey: "workspace-override",
10995
+ caseLabel: "Workspace Override",
10996
+ kind: "policy_rule",
10997
+ canonicalOwnerScope: "workspace",
10998
+ editSurface: "workspace_admin",
10999
+ inheritanceRule: "none",
11000
+ blastRadius: "workspace"
9307
11001
  }
9308
11002
  ])
9309
11003
  };
9310
11004
  function flattenOwnershipMatrix(matrix) {
9311
11005
  return CONTROL_OBJECT_KINDS.flatMap((kind) => [...matrix[kind]]);
9312
11006
  }
9313
- Object.freeze(
11007
+ var CONTROL_OBJECT_OWNERSHIP_ROWS = Object.freeze(
9314
11008
  flattenOwnershipMatrix(CONTROL_OBJECT_OWNERSHIP_MATRIX)
9315
11009
  );
11010
+ var CONTROL_OBJECT_OWNERSHIP_CONTRACT = {
11011
+ version: "1.0.0",
11012
+ kinds: CONTROL_OBJECT_KINDS,
11013
+ ownerScopes: CONTROL_OBJECT_OWNER_SCOPES,
11014
+ editSurfaces: CONTROL_OBJECT_EDIT_SURFACES,
11015
+ inheritanceRules: CONTROL_OBJECT_INHERITANCE_RULES,
11016
+ blastRadii: CONTROL_OBJECT_BLAST_RADII,
11017
+ matrix: CONTROL_OBJECT_OWNERSHIP_MATRIX,
11018
+ rows: CONTROL_OBJECT_OWNERSHIP_ROWS
11019
+ };
11020
+ function listControlObjectOwnershipCases(kind) {
11021
+ if (!kind) {
11022
+ return CONTROL_OBJECT_OWNERSHIP_ROWS;
11023
+ }
11024
+ return CONTROL_OBJECT_OWNERSHIP_MATRIX[kind];
11025
+ }
11026
+ function getControlObjectOwnershipCase(kind, caseKey) {
11027
+ return CONTROL_OBJECT_OWNERSHIP_MATRIX[kind].find(
11028
+ (ownershipCase) => ownershipCase.caseKey === caseKey
11029
+ );
11030
+ }
9316
11031
 
9317
- // ../contracts/src/lens-workflow.contract.ts
11032
+ // ../sdk/src/contracts/api-enums.contract.ts
11033
+ var BELIEF_STATUSES = [
11034
+ "assumption",
11035
+ "hypothesis",
11036
+ "belief",
11037
+ "fact"
11038
+ ];
11039
+ var FORK_REASONS = [
11040
+ "refinement",
11041
+ "contradiction_response",
11042
+ "scope_change",
11043
+ "confidence_collapse",
11044
+ "manual"
11045
+ ];
11046
+ var CONFIDENCE_TRIGGERS = [
11047
+ "evidence_added",
11048
+ "evidence_removed",
11049
+ "contradiction_detected",
11050
+ "contradiction_resolved",
11051
+ "agent_assessment",
11052
+ "worktree_outcome",
11053
+ "worktree_completed",
11054
+ "manual",
11055
+ "decay",
11056
+ "fusion",
11057
+ "discount",
11058
+ "deduction"
11059
+ ];
11060
+ var EPISTEMIC_EDGE_TYPES = [
11061
+ "supports",
11062
+ "informs",
11063
+ "depends_on",
11064
+ "derived_from",
11065
+ "contains",
11066
+ "tests"
11067
+ ];
11068
+ var STRUCTURAL_EDGE_TYPES = [
11069
+ "supersedes",
11070
+ "responds_to",
11071
+ "belongs_to",
11072
+ "relates_to_thesis"
11073
+ ];
11074
+ var EDGE_TYPES = [
11075
+ ...EPISTEMIC_EDGE_TYPES,
11076
+ ...STRUCTURAL_EDGE_TYPES
11077
+ ];
11078
+ var REASONING_METHODS = [
11079
+ "deductive",
11080
+ "inductive",
11081
+ "abductive",
11082
+ "analogical",
11083
+ "empirical"
11084
+ ];
11085
+ var DEFEAT_TYPES = [
11086
+ "rebuts",
11087
+ "undercuts",
11088
+ "undermines"
11089
+ ];
11090
+ var CONTRADICTION_SEVERITIES = [
11091
+ "low",
11092
+ "medium",
11093
+ "high",
11094
+ "critical"
11095
+ ];
11096
+ var CONTRADICTION_STATUSES = [
11097
+ "unresolved",
11098
+ "resolved",
11099
+ "accepted"
11100
+ ];
11101
+ var MERGE_OUTCOMES = [
11102
+ "validated",
11103
+ "invalidated",
11104
+ "forked",
11105
+ "inconclusive"
11106
+ ];
11107
+ var WORKTREE_PHASES = [
11108
+ "hypothesis",
11109
+ "investigation",
11110
+ "evaluation",
11111
+ "resolution"
11112
+ ];
11113
+ var EPISTEMIC_LAYERS = [
11114
+ "L1",
11115
+ "L2",
11116
+ "L3",
11117
+ "L4"
11118
+ ];
11119
+ var JUDGMENT_TYPES = [
11120
+ "thesis",
11121
+ "thesis_maturity",
11122
+ "contradiction_ruling",
11123
+ "scope_determination",
11124
+ "confidence_ruling"
11125
+ ];
11126
+
11127
+ // ../sdk/src/contracts/auth-session.contract.ts
11128
+ var SESSION_AUTH_MODES = [
11129
+ "interactive_user",
11130
+ "service_principal",
11131
+ "tenant_api_key",
11132
+ "session_token"
11133
+ ];
11134
+ var SESSION_PRINCIPAL_TYPES = ["human", "service", "agent"];
11135
+ var SESSION_LIFECYCLE_STATUSES = [
11136
+ "active",
11137
+ "expired",
11138
+ "revoked"
11139
+ ];
11140
+ function inferSessionPrincipalType(principalId) {
11141
+ if (principalId.startsWith("user:")) {
11142
+ return "human";
11143
+ }
11144
+ if (principalId.startsWith("agent:")) {
11145
+ return "agent";
11146
+ }
11147
+ return "service";
11148
+ }
11149
+ function normalizeDelegationChain(args) {
11150
+ if (args.delegationChain && args.delegationChain.length > 0) {
11151
+ return [...args.delegationChain];
11152
+ }
11153
+ if (!args.delegatedBy) {
11154
+ return;
11155
+ }
11156
+ return [
11157
+ {
11158
+ principalId: args.delegatedBy,
11159
+ principalType: args.delegatedByType ?? inferSessionPrincipalType(args.delegatedBy),
11160
+ delegatedAt: args.delegatedAt,
11161
+ reason: args.reason
11162
+ }
11163
+ ];
11164
+ }
11165
+ function lastDelegator(delegationChain) {
11166
+ if (!delegationChain || delegationChain.length === 0) {
11167
+ return;
11168
+ }
11169
+ return delegationChain[delegationChain.length - 1]?.principalId;
11170
+ }
11171
+
11172
+ // ../sdk/src/contracts/lens-filter.contract.ts
11173
+ function isLensFilterCriteria(value) {
11174
+ if (!value || typeof value !== "object") return false;
11175
+ const obj = value;
11176
+ return typeof obj.version === "number" && typeof obj.kind === "string";
11177
+ }
11178
+ function isTaxonomyFilterCriteriaV1(value) {
11179
+ if (!isLensFilterCriteria(value)) return false;
11180
+ return value.version === 1 && value.kind === "taxonomy";
11181
+ }
11182
+ function validateFilterCriteria(value) {
11183
+ if (value === void 0 || value === null) {
11184
+ return { valid: true };
11185
+ }
11186
+ if (!isLensFilterCriteria(value)) {
11187
+ return {
11188
+ valid: false,
11189
+ errors: [
11190
+ 'filterCriteria must have numeric "version" and string "kind" fields'
11191
+ ]
11192
+ };
11193
+ }
11194
+ if (isTaxonomyFilterCriteriaV1(value)) {
11195
+ return validateTaxonomyFilterV1(value);
11196
+ }
11197
+ const raw = value;
11198
+ return {
11199
+ valid: false,
11200
+ errors: [
11201
+ `Unsupported filter criteria: version=${raw.version}, kind=${raw.kind}`
11202
+ ]
11203
+ };
11204
+ }
11205
+ function validateTaxonomyFilterV1(criteria) {
11206
+ const errors = [];
11207
+ if (!Array.isArray(criteria.entityTypeFilters)) {
11208
+ errors.push("entityTypeFilters must be an array");
11209
+ return { valid: false, errors };
11210
+ }
11211
+ if (criteria.entityTypeFilters.length === 0) {
11212
+ errors.push("entityTypeFilters must contain at least one entry");
11213
+ return { valid: false, errors };
11214
+ }
11215
+ for (let i = 0; i < criteria.entityTypeFilters.length; i++) {
11216
+ const filter = criteria.entityTypeFilters[i];
11217
+ if (!filter || typeof filter.entityTypeValue !== "string") {
11218
+ errors.push(
11219
+ `entityTypeFilters[${i}].entityTypeValue must be a non-empty string`
11220
+ );
11221
+ continue;
11222
+ }
11223
+ if (filter.entityTypeValue.trim().length === 0) {
11224
+ errors.push(
11225
+ `entityTypeFilters[${i}].entityTypeValue must be a non-empty string`
11226
+ );
11227
+ }
11228
+ if (filter.subtypeValues !== void 0 && !Array.isArray(filter.subtypeValues)) {
11229
+ errors.push(`entityTypeFilters[${i}].subtypeValues must be an array`);
11230
+ }
11231
+ }
11232
+ if (criteria.ontologyScope !== void 0) {
11233
+ if (typeof criteria.ontologyScope !== "object" || criteria.ontologyScope === null) {
11234
+ errors.push("ontologyScope must be an object");
11235
+ }
11236
+ }
11237
+ return errors.length === 0 ? { valid: true } : { valid: false, errors };
11238
+ }
11239
+
11240
+ // ../sdk/src/contracts/lens-workflow.contract.ts
9318
11241
  var LENS_PERSPECTIVE_TYPES = [
9319
11242
  "investigation",
9320
11243
  "monitoring",
@@ -9322,6 +11245,58 @@ var LENS_PERSPECTIVE_TYPES = [
9322
11245
  "comparison",
9323
11246
  "taxonomy"
9324
11247
  ];
11248
+ var LENS_STATUSES = ["draft", "active", "archived"];
11249
+ var LENS_TASK_TEMPLATE_PRIORITIES = [
11250
+ "critical",
11251
+ "high",
11252
+ "medium",
11253
+ "low"
11254
+ ];
11255
+ var BRANCH_DEPRECATION_MESSAGE = "Branches are deprecated for operational framing. Create a workspace-scoped lens instead.";
11256
+ function inferLensPerspectiveTypeFromBranchSchema(schema) {
11257
+ const normalized = schema?.trim().toLowerCase();
11258
+ if (normalized === "phase") {
11259
+ return "monitoring";
11260
+ }
11261
+ if (normalized === "axis" || normalized === "dimension") {
11262
+ return "comparison";
11263
+ }
11264
+ if (normalized === "track") {
11265
+ return "investigation";
11266
+ }
11267
+ return "analysis";
11268
+ }
11269
+ function migrateBranchToLens(args) {
11270
+ const perspectiveType = inferLensPerspectiveTypeFromBranchSchema(args.schema);
11271
+ return {
11272
+ recommendedTool: "create_lens",
11273
+ perspectiveType,
11274
+ message: "Branches are deprecated for operational framing. Create a workspace-scoped lens with the suggested payload instead.",
11275
+ suggestedPayload: {
11276
+ name: args.name,
11277
+ description: args.description,
11278
+ topicId: args.topicId,
11279
+ workspaceId: args.workspaceId,
11280
+ perspectiveType
11281
+ }
11282
+ };
11283
+ }
11284
+ function buildDeprecatedBranchMetadata(args) {
11285
+ return {
11286
+ deprecated: true,
11287
+ deprecationMessage: BRANCH_DEPRECATION_MESSAGE,
11288
+ lensSuggestion: migrateBranchToLens(args)
11289
+ };
11290
+ }
11291
+
11292
+ // ../contracts/src/lens-workflow.contract.ts
11293
+ var LENS_PERSPECTIVE_TYPES2 = [
11294
+ "investigation",
11295
+ "monitoring",
11296
+ "analysis",
11297
+ "comparison",
11298
+ "taxonomy"
11299
+ ];
9325
11300
 
9326
11301
  // ../contracts/src/tool-contracts.ts
9327
11302
  var CREATE_BELIEF = {
@@ -10216,7 +12191,7 @@ var CREATE_LENS = {
10216
12191
  perspectiveType: {
10217
12192
  type: "string",
10218
12193
  description: "Perspective type for the lens. Validated against schemaEnumConfig category 'lens_perspective_type'.",
10219
- enum: [...LENS_PERSPECTIVE_TYPES]
12194
+ enum: [...LENS_PERSPECTIVE_TYPES2]
10220
12195
  },
10221
12196
  promptTemplates: {
10222
12197
  type: "array",
@@ -10269,7 +12244,7 @@ var LIST_LENSES = {
10269
12244
  perspectiveType: {
10270
12245
  type: "string",
10271
12246
  description: "Filter by perspective type",
10272
- enum: [...LENS_PERSPECTIVE_TYPES]
12247
+ enum: [...LENS_PERSPECTIVE_TYPES2]
10273
12248
  }
10274
12249
  },
10275
12250
  required: [],
@@ -10458,6 +12433,74 @@ var GET_GRAPH_STRUCTURE_ANALYSIS = {
10458
12433
  ontologyPrimitive: "graph",
10459
12434
  tier: "showcase"
10460
12435
  };
12436
+ var LIST_GRAPH_INTELLIGENCE_QUERIES = {
12437
+ name: "list_graph_intelligence_queries",
12438
+ description: "List the Graph Intelligence query catalog that powers structural graph analysis experiences. Returns categories, query IDs, prompt templates, modes, and the public tool plan each query can use.",
12439
+ parameters: {
12440
+ categoryId: {
12441
+ type: "string",
12442
+ description: "Optional category filter, such as problems or strategic"
12443
+ },
12444
+ mode: {
12445
+ type: "string",
12446
+ description: "Optional mode filter: core, bias, stress, operational, alpha, semantic, or evidence"
12447
+ }
12448
+ },
12449
+ required: [],
12450
+ response: {
12451
+ description: "Graph Intelligence query catalog and mode-to-tool mapping",
12452
+ fields: {
12453
+ categories: "array \u2014 query categories",
12454
+ queries: "array \u2014 query definitions with prompt templates and tools",
12455
+ quickQueries: "array \u2014 recommended one-click query presets",
12456
+ publicToolNamesByMode: "object \u2014 public tool names available to each Graph Intelligence mode"
12457
+ }
12458
+ },
12459
+ ownerModule: "graph-intelligence",
12460
+ ontologyPrimitive: "graph",
12461
+ tier: "showcase"
12462
+ };
12463
+ var RUN_GRAPH_INTELLIGENCE_QUERY = {
12464
+ name: "run_graph_intelligence_query",
12465
+ description: "Run a named Graph Intelligence query against a tenant topic graph. Returns the selected query, prompt, deterministic graph-analysis bundle, graph context, and public tool plan for model synthesis.",
12466
+ parameters: {
12467
+ topicId: { type: "string", description: "Topic to analyze" },
12468
+ queryId: {
12469
+ type: "string",
12470
+ description: "Graph Intelligence query ID, such as confirmation-bias, pre-mortem, or thesis-summary"
12471
+ },
12472
+ prompt: {
12473
+ type: "string",
12474
+ description: "Optional custom prompt for custom analysis runs"
12475
+ },
12476
+ input: {
12477
+ type: "string",
12478
+ description: "Optional entity, theme, belief, company, or search text for input-driven queries"
12479
+ },
12480
+ mode: {
12481
+ type: "string",
12482
+ description: "Optional mode override: core, bias, stress, operational, alpha, semantic, or evidence"
12483
+ },
12484
+ limit: {
12485
+ type: "number",
12486
+ description: "Maximum graph context rows to return"
12487
+ }
12488
+ },
12489
+ required: ["topicId"],
12490
+ response: {
12491
+ description: "Graph Intelligence query result bundle ready for model or prompt-library synthesis",
12492
+ fields: {
12493
+ query: "object \u2014 selected query definition",
12494
+ prompt: "string \u2014 resolved prompt template",
12495
+ toolPlan: "array \u2014 public tools and args the model can call next",
12496
+ analysis: "object \u2014 structure, coverage, gap, and confirmation-bias analysis",
12497
+ context: "object \u2014 sampled beliefs, questions, evidence, edges, and contradictions"
12498
+ }
12499
+ },
12500
+ ownerModule: "graph-intelligence",
12501
+ ontologyPrimitive: "graph",
12502
+ tier: "showcase"
12503
+ };
10461
12504
  var GET_FALSIFICATION_QUESTIONS = {
10462
12505
  name: "get_falsification_questions",
10463
12506
  description: "Generate Popperian falsification questions for beliefs. Like `git test` \u2014 identifies the questions most likely to disprove current beliefs. Karl Popper as a tool: surfaces what would need to be true to invalidate each belief.",
@@ -13033,6 +15076,8 @@ var MCP_TOOL_CONTRACTS = {
13033
15076
  // Graph intelligence (showcase)
13034
15077
  detect_confirmation_bias: DETECT_CONFIRMATION_BIAS,
13035
15078
  get_graph_structure_analysis: GET_GRAPH_STRUCTURE_ANALYSIS,
15079
+ list_graph_intelligence_queries: LIST_GRAPH_INTELLIGENCE_QUERIES,
15080
+ run_graph_intelligence_query: RUN_GRAPH_INTELLIGENCE_QUERY,
13036
15081
  get_falsification_questions: GET_FALSIFICATION_QUESTIONS,
13037
15082
  // Evidence operations (workhorse)
13038
15083
  search_evidence: SEARCH_EVIDENCE,
@@ -13120,6 +15165,18 @@ var MCP_TOOL_CONTRACTS = {
13120
15165
  deprecate_ontology_version: DEPRECATE_ONTOLOGY_VERSION,
13121
15166
  resolve_effective_ontology: RESOLVE_EFFECTIVE_ONTOLOGY
13122
15167
  };
15168
+ var GIT_SEMANTIC_REQUIRED_TOOLS = Object.keys(MCP_TOOL_CONTRACTS);
15169
+ function validateGitSemantics(tool) {
15170
+ const desc = tool.description;
15171
+ const hasGitReference = /Like (`git |a `git |a merge conflict|opening a `git)/.test(desc);
15172
+ if (!hasGitReference) {
15173
+ return {
15174
+ valid: false,
15175
+ reason: `Tool "${tool.name}" description missing git-semantic reference`
15176
+ };
15177
+ }
15178
+ return { valid: true };
15179
+ }
13123
15180
 
13124
15181
  // ../contracts/src/function-registry/manifest.ts
13125
15182
  var publicEverywhere = {
@@ -13215,6 +15272,8 @@ var MCP_ANALYSIS_PLATFORM_OPERATION_NAMES = [
13215
15272
  "traverse_graph",
13216
15273
  "get_graph_neighborhood",
13217
15274
  "get_graph_structure_analysis",
15275
+ "list_graph_intelligence_queries",
15276
+ "run_graph_intelligence_query",
13218
15277
  "find_contradictions",
13219
15278
  "flag_contradiction",
13220
15279
  "detect_confirmation_bias",
@@ -13444,7 +15503,1303 @@ var LUCERN_OPERATION_MANIFEST = {
13444
15503
  "Lucern MCP-only platform operation for local agent/bootstrap or verification workflows. Hidden from public discovery."
13445
15504
  )
13446
15505
  };
13447
- globalThis.process?.env;
15506
+
15507
+ // ../sdk/src/contracts/mcpTools.ts
15508
+ var OPERATION_MANIFEST = LUCERN_OPERATION_MANIFEST;
15509
+ var MCP_ALWAYS_ALLOWED_TOOL_NAMES = ["identity_whoami"];
15510
+ function getMcpToolExposure(toolName) {
15511
+ return OPERATION_MANIFEST[toolName]?.surfaces.mcp ?? "none";
15512
+ }
15513
+ function decorateMcpToolContract(toolName, contract) {
15514
+ const exposure = getMcpToolExposure(toolName);
15515
+ if (exposure === "none") {
15516
+ return null;
15517
+ }
15518
+ return exposure === "internal" || contract.internal ? { ...contract, internal: true } : contract;
15519
+ }
15520
+ function buildMcpToolContracts(options = {}) {
15521
+ const merged = {
15522
+ ...MCP_TOOL_CONTRACTS,
15523
+ ...options.extensions ?? {}
15524
+ };
15525
+ return Object.fromEntries(
15526
+ Object.entries(merged).flatMap(([toolName, contract]) => {
15527
+ const decorated = decorateMcpToolContract(toolName, contract);
15528
+ return decorated ? [[toolName, decorated]] : [];
15529
+ })
15530
+ );
15531
+ }
15532
+ function mcpContractToInputSchema(contract) {
15533
+ const properties = {};
15534
+ for (const [paramName, paramDef] of Object.entries(contract.parameters)) {
15535
+ const prop = {
15536
+ type: paramDef.type,
15537
+ description: paramDef.description
15538
+ };
15539
+ if (paramDef.enum) {
15540
+ prop.enum = paramDef.enum;
15541
+ }
15542
+ properties[paramName] = prop;
15543
+ }
15544
+ return {
15545
+ type: "object",
15546
+ properties,
15547
+ required: contract.required
15548
+ };
15549
+ }
15550
+ function mcpContractToManifestEntry(name, contract) {
15551
+ return {
15552
+ name,
15553
+ description: contract.description,
15554
+ inputSchema: mcpContractToInputSchema(contract),
15555
+ internal: Boolean(contract.internal),
15556
+ ownerModule: contract.ownerModule,
15557
+ ontologyPrimitive: contract.ontologyPrimitive,
15558
+ tier: contract.tier
15559
+ };
15560
+ }
15561
+ function isMcpToolAllowed(toolName, options = {}) {
15562
+ const contracts = options.contracts ?? buildMcpToolContracts();
15563
+ const contract = contracts[toolName];
15564
+ const alwaysAllowed = /* @__PURE__ */ new Set([
15565
+ ...MCP_ALWAYS_ALLOWED_TOOL_NAMES,
15566
+ ...options.alwaysAllowedTools ?? []
15567
+ ]);
15568
+ if (alwaysAllowed.has(toolName)) {
15569
+ return true;
15570
+ }
15571
+ if (options.sessionType === "user" && contract?.internal) {
15572
+ return false;
15573
+ }
15574
+ if (options.permittedTools !== void 0 && options.permittedTools !== null) {
15575
+ return options.permittedTools.some((tool) => tool.toolName === toolName);
15576
+ }
15577
+ if (options.allowedTools === null || options.allowedTools === void 0) {
15578
+ return true;
15579
+ }
15580
+ return options.allowedTools.includes(toolName);
15581
+ }
15582
+ function buildMcpToolManifest(args = {}) {
15583
+ const contracts = args.contracts ?? buildMcpToolContracts();
15584
+ return Object.entries(contracts).filter(([name, contract]) => {
15585
+ if (args.visibility?.sessionType === "user" && contract.internal) {
15586
+ return false;
15587
+ }
15588
+ return isMcpToolAllowed(name, {
15589
+ ...args.visibility,
15590
+ contracts
15591
+ });
15592
+ }).map(([name, contract]) => mcpContractToManifestEntry(name, contract));
15593
+ }
15594
+
15595
+ // ../sdk/src/contracts/prompt.contract.ts
15596
+ function isLucernPrompt(value) {
15597
+ if (!value || typeof value !== "object") {
15598
+ return false;
15599
+ }
15600
+ const prompt = value;
15601
+ return typeof prompt.slug === "string" && typeof prompt.version === "string" && typeof prompt.template === "string" && Array.isArray(prompt.variables) && prompt.variables.every((entry) => typeof entry === "string") && (prompt.modelHint === "fast" || prompt.modelHint === "balanced" || prompt.modelHint === "strong") && !!prompt.metadata && typeof prompt.metadata === "object" && typeof prompt.metadata.author === "string" && typeof prompt.metadata.createdAt === "string" && typeof prompt.metadata.description === "string" && Array.isArray(prompt.metadata.tags) && prompt.metadata.tags.every((entry) => typeof entry === "string");
15602
+ }
15603
+
15604
+ // ../sdk/src/contracts/workflow-runtime.contract.ts
15605
+ var WORKFLOW_RUNTIME_SCHEMA_VERSION = "1.0.0";
15606
+ var WORKFLOW_MUTATION_TIERS = [
15607
+ "read_only",
15608
+ "low_risk_write",
15609
+ "high_risk_write"
15610
+ ];
15611
+ var WORKFLOW_APPROVAL_MODES = [
15612
+ "none",
15613
+ "audit_only",
15614
+ "human_required",
15615
+ "auto_approve"
15616
+ ];
15617
+ var DEFAULT_TIER_APPROVAL_MODE = {
15618
+ read_only: "none",
15619
+ low_risk_write: "audit_only",
15620
+ high_risk_write: "human_required"
15621
+ };
15622
+ var WORKFLOW_ACTION_KINDS = [
15623
+ "context_pack",
15624
+ "integrity_check",
15625
+ "lucern_tool",
15626
+ "report_compile",
15627
+ "brief_publish",
15628
+ "notification",
15629
+ "custom"
15630
+ ];
15631
+ var WORKFLOW_HOOK_EVENTS = [
15632
+ "schedule.tick",
15633
+ "worktree.activated",
15634
+ "worktree.completed",
15635
+ "question.created",
15636
+ "question.answered",
15637
+ "evidence.appended",
15638
+ "inbox.item_created"
15639
+ ];
15640
+ var WORKFLOW_OUTPUT_KINDS = [
15641
+ "engineering_brief",
15642
+ "research_memo",
15643
+ "strategy_artifact",
15644
+ "inbox_summary",
15645
+ "pipeline_brief",
15646
+ "structured_payload"
15647
+ ];
15648
+ var WORKFLOW_RUN_STATUSES = [
15649
+ "queued",
15650
+ "running",
15651
+ "awaiting_approval",
15652
+ "completed",
15653
+ "failed",
15654
+ "cancelled"
15655
+ ];
15656
+ var WORKFLOW_TRIGGER_KINDS = [
15657
+ "manual",
15658
+ "schedule",
15659
+ "hook"
15660
+ ];
15661
+ var WORKFLOW_PROOF_ARTIFACT_KINDS = [
15662
+ "report",
15663
+ "brief",
15664
+ "artifact",
15665
+ "dashboard",
15666
+ "test_evidence"
15667
+ ];
15668
+ var WORKFLOW_STAFFING_HINTS = [
15669
+ "solo",
15670
+ "backend+tests",
15671
+ "fullstack",
15672
+ "mcp+tests"
15673
+ ];
15674
+ var WORKFLOW_AUTO_FIX_MODES = [
15675
+ "disabled",
15676
+ "dry_run",
15677
+ "safe",
15678
+ "aggressive"
15679
+ ];
15680
+ var WORKFLOW_INTEGRITY_CHECKS = [
15681
+ "null_dependency_refs",
15682
+ "superseded_blockers",
15683
+ "band_order_inconsistency",
15684
+ "sparse_shaping",
15685
+ "failed_completed_gate"
15686
+ ];
15687
+ var DEFAULT_WORKFLOW_AUTO_FIX_POLICY = {
15688
+ mode: "disabled",
15689
+ permittedMutationTiers: ["read_only"],
15690
+ requireAuditTrail: true
15691
+ };
15692
+ var NIGHTLY_RECONCILIATION_WORKFLOW_ID = "workflow.pipeline_reconciliation.v1";
15693
+ var MORNING_BRIEF_WORKFLOW_ID = "workflow.morning_brief.v1";
15694
+ var CANONICAL_WORKFLOW_DEFINITIONS = [
15695
+ {
15696
+ workflowId: NIGHTLY_RECONCILIATION_WORKFLOW_ID,
15697
+ version: WORKFLOW_RUNTIME_SCHEMA_VERSION,
15698
+ title: "Nightly Pipeline Reconciliation",
15699
+ description: "Runs deterministic integrity checks, compiles pipeline state, and emits an operator-facing reconciliation brief.",
15700
+ trigger: {
15701
+ kind: "schedule",
15702
+ cadence: "daily",
15703
+ timezone: "America/New_York"
15704
+ },
15705
+ staffingHint: "backend+tests",
15706
+ proofArtifacts: [
15707
+ {
15708
+ kind: "report",
15709
+ label: "Pipeline reconciliation report",
15710
+ required: true
15711
+ },
15712
+ {
15713
+ kind: "test_evidence",
15714
+ label: "Integrity check receipt",
15715
+ required: true
15716
+ }
15717
+ ],
15718
+ autoFixPolicy: {
15719
+ mode: "safe",
15720
+ maxActionsPerRun: 5,
15721
+ permittedMutationTiers: ["read_only", "low_risk_write"],
15722
+ requireAuditTrail: true,
15723
+ escalationGate: "gate:workflow-runtime-contract-live"
15724
+ },
15725
+ actions: [
15726
+ {
15727
+ actionId: "compile_context_pack",
15728
+ kind: "context_pack",
15729
+ title: "Compile pipeline context",
15730
+ description: "Build the ranked context needed for deterministic checks.",
15731
+ mutationTier: "read_only",
15732
+ produces: ["structured_payload"],
15733
+ idempotent: true,
15734
+ approval: { mode: "none" }
15735
+ },
15736
+ {
15737
+ actionId: "run_integrity_checks",
15738
+ kind: "integrity_check",
15739
+ title: "Run integrity checks",
15740
+ description: "Evaluate dependency references, blockers, campaign/lane placement, shaping coverage, and completed gates.",
15741
+ mutationTier: "read_only",
15742
+ produces: ["structured_payload"],
15743
+ idempotent: true,
15744
+ approval: { mode: "none" }
15745
+ },
15746
+ {
15747
+ actionId: "record_followup_questions",
15748
+ kind: "lucern_tool",
15749
+ title: "Record follow-up questions",
15750
+ description: "Create or reopen operator-facing questions for integrity failures that require human review.",
15751
+ mutationTier: "low_risk_write",
15752
+ toolName: "create_question",
15753
+ produces: ["pipeline_brief"],
15754
+ approval: { mode: "audit_only", rationaleRequired: true }
15755
+ },
15756
+ {
15757
+ actionId: "publish_reconciliation_brief",
15758
+ kind: "brief_publish",
15759
+ title: "Publish reconciliation brief",
15760
+ description: "Emit an inbox-routed brief summarizing the nightly pipeline state and grouped blockers.",
15761
+ mutationTier: "low_risk_write",
15762
+ produces: ["pipeline_brief", "inbox_summary"],
15763
+ approval: { mode: "audit_only" }
15764
+ }
15765
+ ],
15766
+ hooks: [
15767
+ {
15768
+ hookId: "nightly-schedule",
15769
+ event: "schedule.tick",
15770
+ description: "Run once per nightly cadence.",
15771
+ actionIds: [
15772
+ "compile_context_pack",
15773
+ "run_integrity_checks",
15774
+ "record_followup_questions",
15775
+ "publish_reconciliation_brief"
15776
+ ]
15777
+ }
15778
+ ],
15779
+ outputs: ["pipeline_brief", "inbox_summary", "structured_payload"],
15780
+ integrityChecks: WORKFLOW_INTEGRITY_CHECKS
15781
+ },
15782
+ {
15783
+ workflowId: MORNING_BRIEF_WORKFLOW_ID,
15784
+ version: WORKFLOW_RUNTIME_SCHEMA_VERSION,
15785
+ title: "Morning Brief",
15786
+ description: "Compiles a developer-facing morning brief from graph state, overnight workflow outputs, and inbox routing preferences.",
15787
+ trigger: {
15788
+ kind: "schedule",
15789
+ cadence: "daily",
15790
+ timezone: "America/New_York"
15791
+ },
15792
+ staffingHint: "solo",
15793
+ proofArtifacts: [
15794
+ {
15795
+ kind: "brief",
15796
+ label: "Morning brief",
15797
+ required: true
15798
+ }
15799
+ ],
15800
+ autoFixPolicy: {
15801
+ mode: "dry_run",
15802
+ maxActionsPerRun: 1,
15803
+ permittedMutationTiers: ["read_only", "low_risk_write"],
15804
+ requireAuditTrail: true
15805
+ },
15806
+ actions: [
15807
+ {
15808
+ actionId: "compile_brief_inputs",
15809
+ kind: "context_pack",
15810
+ title: "Compile brief inputs",
15811
+ description: "Read graph state, worktree state, and overnight workflow receipts.",
15812
+ mutationTier: "read_only",
15813
+ produces: ["structured_payload"],
15814
+ idempotent: true,
15815
+ approval: { mode: "none" }
15816
+ },
15817
+ {
15818
+ actionId: "publish_morning_brief",
15819
+ kind: "brief_publish",
15820
+ title: "Publish morning brief",
15821
+ description: "Publish a typed inbox summary with prioritized worktree and question context.",
15822
+ mutationTier: "low_risk_write",
15823
+ produces: ["engineering_brief", "inbox_summary"],
15824
+ approval: { mode: "audit_only" }
15825
+ }
15826
+ ],
15827
+ hooks: [
15828
+ {
15829
+ hookId: "morning-schedule",
15830
+ event: "schedule.tick",
15831
+ description: "Run once per morning cadence.",
15832
+ actionIds: ["compile_brief_inputs", "publish_morning_brief"]
15833
+ },
15834
+ {
15835
+ hookId: "worktree-complete-refresh",
15836
+ event: "worktree.completed",
15837
+ description: "Refresh the queued morning brief inputs when worktree outcomes land overnight.",
15838
+ actionIds: ["compile_brief_inputs"]
15839
+ }
15840
+ ],
15841
+ outputs: ["engineering_brief", "inbox_summary", "structured_payload"],
15842
+ integrityChecks: ["sparse_shaping"]
15843
+ }
15844
+ ];
15845
+
15846
+ // ../sdk/src/events.ts
15847
+ var DOMAIN_EVENT_VERSION = "1.0";
15848
+ var EVENT_RETENTION_DEFAULT_DAYS = 30;
15849
+ var WEBHOOK_MAX_ATTEMPTS = 5;
15850
+ var WEBHOOK_RETRY_DELAYS_MS = [1e3, 5e3, 3e4, 3e5];
15851
+ var DOMAIN_EVENT_TYPES = [
15852
+ "belief.created",
15853
+ "belief.forked",
15854
+ "belief.confidence_updated",
15855
+ "belief.archived",
15856
+ "belief.refined",
15857
+ "belief.contract_created",
15858
+ "belief.contract_evaluated",
15859
+ "belief.lineage_queried",
15860
+ "evidence.created",
15861
+ "evidence.linked",
15862
+ "evidence.search_executed",
15863
+ "question.created",
15864
+ "question.answered",
15865
+ "question.refined",
15866
+ "question.status_updated",
15867
+ "question.archived",
15868
+ "edge.created",
15869
+ "contradiction.flagged",
15870
+ "worktree.created",
15871
+ "worktree.activated",
15872
+ "worktree.merged",
15873
+ "worktree.targets_updated",
15874
+ "worktree.metadata_updated",
15875
+ "topic.created",
15876
+ "topic.updated",
15877
+ "topic.archived",
15878
+ "task.created",
15879
+ "task.completed",
15880
+ "task.updated",
15881
+ "ontology.bound",
15882
+ "context.compiled",
15883
+ "identity.key_created",
15884
+ "identity.key_rotated",
15885
+ "identity.key_revoked",
15886
+ "webhook.test"
15887
+ ];
15888
+ var RUNTIME_BUFFER = globalThis.Buffer;
15889
+ var RUNTIME_ENV = globalThis.process?.env;
15890
+ function escapeRegex(value) {
15891
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15892
+ }
15893
+ function eventPatternToRegExp(pattern) {
15894
+ const normalized = pattern.trim();
15895
+ if (!normalized) {
15896
+ return /^$/;
15897
+ }
15898
+ if (normalized === "*") {
15899
+ return /^.*$/;
15900
+ }
15901
+ const source = escapeRegex(normalized).replace(/\\\*/g, ".*");
15902
+ return new RegExp(`^${source}$`);
15903
+ }
15904
+ function matchesEventPattern(eventType, pattern) {
15905
+ return eventPatternToRegExp(pattern).test(eventType.trim());
15906
+ }
15907
+ function matchesAnyEventPattern(eventType, patterns) {
15908
+ if (patterns.length === 0) {
15909
+ return true;
15910
+ }
15911
+ return patterns.some((pattern) => matchesEventPattern(eventType, pattern));
15912
+ }
15913
+ function toBase64(value) {
15914
+ if (RUNTIME_BUFFER) {
15915
+ return RUNTIME_BUFFER.from(value, "utf8").toString("base64url");
15916
+ }
15917
+ return btoa(unescape(encodeURIComponent(value))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
15918
+ }
15919
+ function fromBase64(value) {
15920
+ if (RUNTIME_BUFFER) {
15921
+ return RUNTIME_BUFFER.from(value, "base64url").toString("utf8");
15922
+ }
15923
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
15924
+ return decodeURIComponent(escape(atob(normalized)));
15925
+ }
15926
+ function createEventId() {
15927
+ const random = typeof globalThis.crypto?.randomUUID === "function" ? globalThis.crypto.randomUUID().replace(/-/g, "") : Array.from(
15928
+ typeof globalThis.crypto?.getRandomValues === "function" ? globalThis.crypto.getRandomValues(new Uint8Array(16)) : Array.from({ length: 16 }, () => Math.floor(Math.random() * 256)),
15929
+ (value) => value.toString(16).padStart(2, "0")
15930
+ ).join("");
15931
+ return `evt_${random}`;
15932
+ }
15933
+ function normalizeRetentionDays(value) {
15934
+ if (!Number.isFinite(value) || typeof value !== "number" || value <= 0) {
15935
+ return EVENT_RETENTION_DEFAULT_DAYS;
15936
+ }
15937
+ return Math.max(1, Math.trunc(value));
15938
+ }
15939
+ function buildDomainEvent(input) {
15940
+ const timestamp = input.timestamp ?? Date.now();
15941
+ const retentionDays = normalizeRetentionDays(input.retentionDays);
15942
+ return {
15943
+ eventId: input.eventId?.trim() || createEventId(),
15944
+ type: input.type.trim(),
15945
+ version: DOMAIN_EVENT_VERSION,
15946
+ timestamp,
15947
+ tenantId: input.tenantId?.trim() || void 0,
15948
+ workspaceId: input.workspaceId?.trim() || void 0,
15949
+ topicId: input.topicId.trim(),
15950
+ resourceId: input.resourceId.trim(),
15951
+ resourceType: input.resourceType.trim(),
15952
+ actorId: input.actorId.trim(),
15953
+ actorType: input.actorType,
15954
+ data: input.data ?? {},
15955
+ correlationId: input.correlationId?.trim() || void 0,
15956
+ expiresAt: timestamp + retentionDays * 24 * 60 * 60 * 1e3
15957
+ };
15958
+ }
15959
+ function compareEventCursor(left, right) {
15960
+ if (left.timestamp !== right.timestamp) {
15961
+ return left.timestamp - right.timestamp;
15962
+ }
15963
+ return left.eventId.localeCompare(right.eventId);
15964
+ }
15965
+ function encodeEventCursor(cursor) {
15966
+ return toBase64(JSON.stringify(cursor));
15967
+ }
15968
+ function decodeEventCursor(cursor) {
15969
+ if (!cursor || cursor.trim().length === 0) {
15970
+ return null;
15971
+ }
15972
+ try {
15973
+ const parsed = JSON.parse(fromBase64(cursor.trim()));
15974
+ if (typeof parsed.timestamp !== "number" || !Number.isFinite(parsed.timestamp) || typeof parsed.eventId !== "string" || parsed.eventId.trim().length === 0) {
15975
+ return null;
15976
+ }
15977
+ return {
15978
+ timestamp: parsed.timestamp,
15979
+ eventId: parsed.eventId.trim()
15980
+ };
15981
+ } catch {
15982
+ return null;
15983
+ }
15984
+ }
15985
+ function isAfterCursor(event, cursor) {
15986
+ if (!cursor) {
15987
+ return true;
15988
+ }
15989
+ return compareEventCursor(event, cursor) > 0;
15990
+ }
15991
+ function sortEventsByCursor(events) {
15992
+ return [...events].sort((left, right) => compareEventCursor(left, right));
15993
+ }
15994
+ function inferActorType(args) {
15995
+ if (args.sessionType === "agent") {
15996
+ return "agent";
15997
+ }
15998
+ if (args.authMode === "service_principal" || args.authMode === "tenant_api_key" || args.principalType === "service") {
15999
+ return "service";
16000
+ }
16001
+ return "human";
16002
+ }
16003
+ async function emitDomainEvent(invokeMutation, input) {
16004
+ return await invokeMutation("events:recordEvent", input);
16005
+ }
16006
+ var LOCALHOST_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1"]);
16007
+ function normalizeUrl(url) {
16008
+ try {
16009
+ return new URL(url.trim());
16010
+ } catch {
16011
+ throw new Error("Webhook URL must be a valid absolute URL.");
16012
+ }
16013
+ }
16014
+ function assertValidWebhookUrl(url) {
16015
+ const parsed = normalizeUrl(url);
16016
+ const hostname = parsed.hostname.trim().toLowerCase();
16017
+ const nodeEnv = RUNTIME_ENV?.NODE_ENV;
16018
+ const allowLocalHttp = nodeEnv === "test" || LOCALHOST_HOSTS.has(hostname);
16019
+ if (parsed.protocol !== "https:" && !(allowLocalHttp && parsed.protocol === "http:")) {
16020
+ throw new Error("Webhook URL must use HTTPS.");
16021
+ }
16022
+ return parsed.toString();
16023
+ }
16024
+ function normalizeWebhookPatterns(patterns) {
16025
+ const normalized = Array.from(
16026
+ new Set(
16027
+ patterns.map((pattern) => pattern.trim()).filter((pattern) => pattern.length > 0)
16028
+ )
16029
+ );
16030
+ if (normalized.length === 0) {
16031
+ throw new Error("At least one webhook event pattern is required.");
16032
+ }
16033
+ return normalized;
16034
+ }
16035
+ function assertValidWebhookSecret(secret) {
16036
+ const normalized = secret.trim();
16037
+ if (normalized.length < 8) {
16038
+ throw new Error("Webhook secret must be at least 8 characters.");
16039
+ }
16040
+ return normalized;
16041
+ }
16042
+ async function computeWebhookSignature(payload, secret) {
16043
+ const encoder = new TextEncoder();
16044
+ const key = await crypto.subtle.importKey(
16045
+ "raw",
16046
+ encoder.encode(secret),
16047
+ { name: "HMAC", hash: "SHA-256" },
16048
+ false,
16049
+ ["sign"]
16050
+ );
16051
+ const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(payload));
16052
+ return Array.from(new Uint8Array(signature)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
16053
+ }
16054
+ function nextDeliveryAttemptAt(currentAttemptCount, now = Date.now()) {
16055
+ if (currentAttemptCount >= WEBHOOK_MAX_ATTEMPTS) {
16056
+ return void 0;
16057
+ }
16058
+ const retryIndex = currentAttemptCount - 1;
16059
+ const delay2 = WEBHOOK_RETRY_DELAYS_MS[retryIndex];
16060
+ return typeof delay2 === "number" ? now + delay2 : void 0;
16061
+ }
16062
+ function resolveDeliveryFailureStatus(attemptCount) {
16063
+ return attemptCount >= WEBHOOK_MAX_ATTEMPTS ? "dead_letter" : "failed";
16064
+ }
16065
+ function sanitizeWebhookRecord(value) {
16066
+ return {
16067
+ id: String(value.id ?? value.webhookId ?? value._id ?? ""),
16068
+ webhookId: String(value.webhookId ?? value.id ?? value._id ?? ""),
16069
+ tenantId: typeof value.tenantId === "string" && value.tenantId.trim().length > 0 ? value.tenantId : void 0,
16070
+ workspaceId: typeof value.workspaceId === "string" && value.workspaceId.trim().length > 0 ? value.workspaceId : void 0,
16071
+ topicId: typeof value.topicId === "string" && value.topicId.trim().length > 0 ? value.topicId : void 0,
16072
+ url: String(value.url ?? ""),
16073
+ events: Array.isArray(value.events) ? value.events.map((entry) => typeof entry === "string" ? entry.trim() : "").filter(Boolean) : [],
16074
+ active: value.active !== false,
16075
+ secretConfigured: true,
16076
+ createdAt: Number(value.createdAt ?? Date.now()),
16077
+ updatedAt: Number(value.updatedAt ?? value.createdAt ?? Date.now()),
16078
+ createdBy: String(value.createdBy ?? ""),
16079
+ updatedBy: String(value.updatedBy ?? value.createdBy ?? ""),
16080
+ lastDeliveryAt: typeof value.lastDeliveryAt === "number" ? value.lastDeliveryAt : void 0,
16081
+ lastSuccessfulDeliveryAt: typeof value.lastSuccessfulDeliveryAt === "number" ? value.lastSuccessfulDeliveryAt : void 0
16082
+ };
16083
+ }
16084
+ function truncateWebhookResponseBody(responseBody, maxLength = 2e3) {
16085
+ if (!responseBody) {
16086
+ return void 0;
16087
+ }
16088
+ if (responseBody.length <= maxLength) {
16089
+ return responseBody;
16090
+ }
16091
+ return `${responseBody.slice(0, maxLength - 3)}...`;
16092
+ }
16093
+
16094
+ // ../sdk/src/eventsCore.ts
16095
+ function serializeTypes2(types) {
16096
+ return Array.isArray(types) && types.length > 0 ? types.join(",") : void 0;
16097
+ }
16098
+ function createEventsClientCore(config = {}) {
16099
+ const gateway = createGatewayRequestClient(config);
16100
+ return {
16101
+ async list(query5 = {}) {
16102
+ return gateway.request({
16103
+ path: `/v1/events${toQueryString({
16104
+ topicId: query5.topicId,
16105
+ after: query5.after,
16106
+ types: serializeTypes2(query5.types),
16107
+ startTime: query5.startTime,
16108
+ endTime: query5.endTime,
16109
+ limit: query5.limit
16110
+ })}`
16111
+ });
16112
+ },
16113
+ async replay(input, idempotencyKey = randomIdempotencyKey()) {
16114
+ return gateway.request({
16115
+ path: "/v1/events/replay",
16116
+ method: "POST",
16117
+ body: input,
16118
+ idempotencyKey
16119
+ });
16120
+ }
16121
+ };
16122
+ }
16123
+ function createWebhooksClientCore(config = {}) {
16124
+ const gateway = createGatewayRequestClient(config);
16125
+ return {
16126
+ async create(input, idempotencyKey = randomIdempotencyKey()) {
16127
+ return gateway.request({
16128
+ path: "/v1/webhooks",
16129
+ method: "POST",
16130
+ body: input,
16131
+ idempotencyKey
16132
+ });
16133
+ },
16134
+ async list(query5 = {}) {
16135
+ return gateway.request({
16136
+ path: `/v1/webhooks${toQueryString({
16137
+ topicId: query5.topicId
16138
+ })}`
16139
+ });
16140
+ },
16141
+ async get(id) {
16142
+ return gateway.request({
16143
+ path: `/v1/webhooks/${encodeURIComponent(id)}`
16144
+ });
16145
+ },
16146
+ async update(id, input, idempotencyKey = randomIdempotencyKey()) {
16147
+ return gateway.request({
16148
+ path: `/v1/webhooks/${encodeURIComponent(id)}`,
16149
+ method: "PATCH",
16150
+ body: input,
16151
+ idempotencyKey
16152
+ });
16153
+ },
16154
+ async delete(id, idempotencyKey = randomIdempotencyKey()) {
16155
+ return gateway.request({
16156
+ path: `/v1/webhooks/${encodeURIComponent(id)}`,
16157
+ method: "DELETE",
16158
+ idempotencyKey
16159
+ });
16160
+ },
16161
+ async test(id, input = {}, idempotencyKey = randomIdempotencyKey()) {
16162
+ return gateway.request({
16163
+ path: `/v1/webhooks/${encodeURIComponent(id)}/test`,
16164
+ method: "POST",
16165
+ body: input,
16166
+ idempotencyKey
16167
+ });
16168
+ },
16169
+ async deliveries(id, query5 = {}) {
16170
+ return gateway.request({
16171
+ path: `/v1/webhooks/${encodeURIComponent(id)}/deliveries${toQueryString({
16172
+ limit: query5.limit
16173
+ })}`
16174
+ });
16175
+ },
16176
+ async health(id) {
16177
+ return gateway.request({
16178
+ path: `/v1/webhooks/${encodeURIComponent(id)}/health`
16179
+ });
16180
+ }
16181
+ };
16182
+ }
16183
+
16184
+ // ../sdk/src/graphIntel.ts
16185
+ var graphIntel_exports = {};
16186
+ __reExport(graphIntel_exports, graphIntel_star);
16187
+
16188
+ // ../sdk/src/index.ts
16189
+ __reExport(src_exports, graphIntel_exports);
16190
+
16191
+ // ../sdk/src/graphIntelligence.ts
16192
+ var graphIntelligence_exports = {};
16193
+ __export(graphIntelligence_exports, {
16194
+ GRAPH_INTELLIGENCE_MODE_TOOL_NAMES: () => GRAPH_INTELLIGENCE_MODE_TOOL_NAMES,
16195
+ GRAPH_INTELLIGENCE_PUBLIC_TOOL_NAMES: () => GRAPH_INTELLIGENCE_PUBLIC_TOOL_NAMES,
16196
+ GRAPH_INTELLIGENCE_QUERIES: () => GRAPH_INTELLIGENCE_QUERIES,
16197
+ GRAPH_INTELLIGENCE_QUERIES_WITH_TOOLS: () => GRAPH_INTELLIGENCE_QUERIES_WITH_TOOLS,
16198
+ GRAPH_INTELLIGENCE_QUERY_CATALOG_VERSION: () => GRAPH_INTELLIGENCE_QUERY_CATALOG_VERSION,
16199
+ GRAPH_INTELLIGENCE_QUERY_CATEGORIES: () => GRAPH_INTELLIGENCE_QUERY_CATEGORIES,
16200
+ GRAPH_INTELLIGENCE_QUERY_MODES: () => GRAPH_INTELLIGENCE_QUERY_MODES,
16201
+ GRAPH_INTELLIGENCE_QUICK_QUERIES: () => GRAPH_INTELLIGENCE_QUICK_QUERIES,
16202
+ fillGraphIntelligencePromptTemplate: () => fillGraphIntelligencePromptTemplate,
16203
+ getGraphIntelligenceQuery: () => getGraphIntelligenceQuery,
16204
+ isGraphIntelligenceQueryMode: () => isGraphIntelligenceQueryMode,
16205
+ listGraphIntelligenceQueries: () => listGraphIntelligenceQueries
16206
+ });
16207
+ __reExport(graphIntelligence_exports, graphIntel_exports);
16208
+
16209
+ // ../contracts/src/graph-intelligence.contract.ts
16210
+ var GRAPH_INTELLIGENCE_QUERY_CATALOG_VERSION = "graph_intelligence_query_catalog.v1";
16211
+ var GRAPH_INTELLIGENCE_QUERY_MODES = [
16212
+ "core",
16213
+ "bias",
16214
+ "stress",
16215
+ "operational",
16216
+ "alpha",
16217
+ "semantic",
16218
+ "evidence"
16219
+ ];
16220
+ var GRAPH_INTELLIGENCE_PUBLIC_TOOL_NAMES = [
16221
+ "get_graph_structure_analysis",
16222
+ "detect_confirmation_bias",
16223
+ "get_graph_gaps",
16224
+ "get_topic_coverage",
16225
+ "find_contradictions",
16226
+ "get_falsification_questions",
16227
+ "search_beliefs",
16228
+ "search_evidence",
16229
+ "list_beliefs",
16230
+ "list_questions",
16231
+ "traverse_graph",
16232
+ "query_lineage",
16233
+ "get_graph_neighborhood"
16234
+ ];
16235
+ var GRAPH_INTELLIGENCE_MODE_TOOL_NAMES = {
16236
+ core: [
16237
+ "get_graph_structure_analysis",
16238
+ "get_topic_coverage",
16239
+ "get_graph_gaps",
16240
+ "list_beliefs",
16241
+ "list_questions",
16242
+ "search_evidence"
16243
+ ],
16244
+ bias: [
16245
+ "get_graph_structure_analysis",
16246
+ "detect_confirmation_bias",
16247
+ "find_contradictions",
16248
+ "search_evidence",
16249
+ "list_beliefs"
16250
+ ],
16251
+ stress: [
16252
+ "get_graph_structure_analysis",
16253
+ "get_graph_gaps",
16254
+ "find_contradictions",
16255
+ "get_falsification_questions",
16256
+ "list_beliefs",
16257
+ "list_questions"
16258
+ ],
16259
+ operational: [
16260
+ "get_topic_coverage",
16261
+ "get_graph_gaps",
16262
+ "list_beliefs",
16263
+ "list_questions",
16264
+ "search_evidence"
16265
+ ],
16266
+ alpha: [
16267
+ "get_graph_structure_analysis",
16268
+ "detect_confirmation_bias",
16269
+ "find_contradictions",
16270
+ "search_beliefs",
16271
+ "search_evidence"
16272
+ ],
16273
+ semantic: [
16274
+ "get_graph_structure_analysis",
16275
+ "search_beliefs",
16276
+ "search_evidence",
16277
+ "traverse_graph",
16278
+ "query_lineage",
16279
+ "get_graph_neighborhood"
16280
+ ],
16281
+ evidence: [
16282
+ "get_graph_structure_analysis",
16283
+ "get_topic_coverage",
16284
+ "search_evidence",
16285
+ "get_falsification_questions",
16286
+ "find_contradictions"
16287
+ ]
16288
+ };
16289
+ var GRAPH_INTELLIGENCE_QUERY_CATEGORIES = [
16290
+ {
16291
+ id: "problems",
16292
+ name: "Find Problems",
16293
+ description: "Risk, contradiction, bias, and structural weakness queries."
16294
+ },
16295
+ {
16296
+ id: "gaps",
16297
+ name: "Find Gaps",
16298
+ description: "Missing evidence, unanswered questions, and sparse areas."
16299
+ },
16300
+ {
16301
+ id: "reasoning",
16302
+ name: "Reasoning Quality",
16303
+ description: "Assumption chains, evidence convergence, and weak links."
16304
+ },
16305
+ {
16306
+ id: "strategic",
16307
+ name: "Strategic Analysis",
16308
+ description: "Pre-mortems, falsification, contrarian signals, and bets."
16309
+ },
16310
+ {
16311
+ id: "deep",
16312
+ name: "Deep Graph Analysis",
16313
+ description: "Centrality, propagation, underdetermination, and topology."
16314
+ },
16315
+ {
16316
+ id: "browse",
16317
+ name: "Browse and Explore",
16318
+ description: "Narrative summaries, search, theme exploration, and bridges."
16319
+ },
16320
+ {
16321
+ id: "prep",
16322
+ name: "Meeting Prep",
16323
+ description: "Company, entity, and question prep from graph context."
16324
+ }
16325
+ ];
16326
+ var byMode = (mode) => GRAPH_INTELLIGENCE_MODE_TOOL_NAMES[mode];
16327
+ var GRAPH_INTELLIGENCE_QUERIES = [
16328
+ {
16329
+ id: "confirmation-bias",
16330
+ categoryId: "problems",
16331
+ mode: "bias",
16332
+ name: "Find Confirmation Bias",
16333
+ description: "Find beliefs supported mainly by confirming evidence.",
16334
+ prompt: "Find beliefs where supporting evidence overwhelms challenging evidence. Prioritize high-conviction beliefs with few defeaters.",
16335
+ highlightStrategy: "bias-risk",
16336
+ riskLevel: "high"
16337
+ },
16338
+ {
16339
+ id: "contradiction-map",
16340
+ categoryId: "problems",
16341
+ mode: "stress",
16342
+ name: "Map Contradictions",
16343
+ description: "Surface direct and indirect contradiction clusters.",
16344
+ prompt: "Map the graph's contradiction clusters and explain which tensions matter most.",
16345
+ highlightStrategy: "contradictions",
16346
+ riskLevel: "high"
16347
+ },
16348
+ {
16349
+ id: "weak-evidence",
16350
+ categoryId: "problems",
16351
+ mode: "stress",
16352
+ name: "Weak Evidence Chains",
16353
+ description: "Find important claims with thin or indirect evidence.",
16354
+ prompt: "Find high-importance beliefs whose evidence support is thin, indirect, stale, or low quality.",
16355
+ highlightStrategy: "weak-support",
16356
+ riskLevel: "medium"
16357
+ },
16358
+ {
16359
+ id: "single-source",
16360
+ categoryId: "problems",
16361
+ mode: "bias",
16362
+ name: "Single-Source Risk",
16363
+ description: "Find claims overly dependent on one source or source type.",
16364
+ prompt: "Identify beliefs that rely on a single source, one methodology, or one repeated perspective.",
16365
+ highlightStrategy: "source-concentration",
16366
+ riskLevel: "medium"
16367
+ },
16368
+ {
16369
+ id: "untested-assumptions",
16370
+ categoryId: "problems",
16371
+ mode: "stress",
16372
+ name: "Untested Assumptions",
16373
+ description: "Find load-bearing assumptions without falsification paths.",
16374
+ prompt: "Find assumptions that appear load-bearing but do not have direct testing questions or falsification evidence.",
16375
+ highlightStrategy: "untested",
16376
+ riskLevel: "high"
16377
+ },
16378
+ {
16379
+ id: "load-bearing-beliefs",
16380
+ categoryId: "problems",
16381
+ mode: "stress",
16382
+ name: "Load-Bearing Beliefs",
16383
+ description: "Find central beliefs whose failure would affect many claims.",
16384
+ prompt: "Find the beliefs with the largest downstream impact if they are wrong.",
16385
+ highlightStrategy: "load-bearing",
16386
+ riskLevel: "high"
16387
+ },
16388
+ {
16389
+ id: "cascade-analysis",
16390
+ categoryId: "problems",
16391
+ mode: "stress",
16392
+ name: "Cascade Analysis",
16393
+ description: "Trace what changes if a belief is weakened or invalidated.",
16394
+ prompt: "Analyze likely downstream cascades if the most central or uncertain beliefs are weakened.",
16395
+ highlightStrategy: "cascade",
16396
+ riskLevel: "high"
16397
+ },
16398
+ {
16399
+ id: "unanswered-questions",
16400
+ categoryId: "gaps",
16401
+ mode: "operational",
16402
+ name: "Unanswered Questions",
16403
+ description: "Find important open questions that block confidence.",
16404
+ prompt: "Identify the most important unanswered questions and explain which beliefs they block.",
16405
+ highlightStrategy: "open-questions"
16406
+ },
16407
+ {
16408
+ id: "thin-themes",
16409
+ categoryId: "gaps",
16410
+ mode: "operational",
16411
+ name: "Thin Themes",
16412
+ description: "Find topics with shallow belief or evidence coverage.",
16413
+ prompt: "Find themes that look underdeveloped relative to their role in the graph.",
16414
+ highlightStrategy: "thin-themes"
16415
+ },
16416
+ {
16417
+ id: "missing-evidence",
16418
+ categoryId: "gaps",
16419
+ mode: "stress",
16420
+ name: "Missing Evidence",
16421
+ description: "Find beliefs that need specific missing evidence.",
16422
+ prompt: "Find the most valuable missing evidence needed to strengthen or falsify the graph.",
16423
+ highlightStrategy: "missing-evidence"
16424
+ },
16425
+ {
16426
+ id: "isolated-clusters",
16427
+ categoryId: "gaps",
16428
+ mode: "operational",
16429
+ name: "Isolated Clusters",
16430
+ description: "Find clusters not connected to the broader graph.",
16431
+ prompt: "Find isolated graph clusters and recommend bridge questions or bridge evidence.",
16432
+ highlightStrategy: "isolated-clusters"
16433
+ },
16434
+ {
16435
+ id: "source-contribution",
16436
+ categoryId: "gaps",
16437
+ mode: "evidence",
16438
+ name: "Source Contribution",
16439
+ description: "Assess how source mix shapes the graph.",
16440
+ prompt: "Assess whether the source mix is balanced enough for the graph's strongest claims.",
16441
+ highlightStrategy: "source-mix"
16442
+ },
16443
+ {
16444
+ id: "stale-beliefs",
16445
+ categoryId: "gaps",
16446
+ mode: "operational",
16447
+ name: "Stale Beliefs",
16448
+ description: "Find beliefs that need review because they are old or stale.",
16449
+ prompt: "Find beliefs that should be revisited because they are stale, unsupported by recent evidence, or contradicted by newer context.",
16450
+ highlightStrategy: "staleness"
16451
+ },
16452
+ {
16453
+ id: "assumption-pyramid",
16454
+ categoryId: "reasoning",
16455
+ mode: "operational",
16456
+ name: "Assumption Pyramid",
16457
+ description: "Show which conclusions rest on which assumptions.",
16458
+ prompt: "Build an assumption pyramid from the graph: foundational assumptions, intermediate claims, and top-level conclusions.",
16459
+ highlightStrategy: "assumptions"
16460
+ },
16461
+ {
16462
+ id: "converging-evidence",
16463
+ categoryId: "reasoning",
16464
+ mode: "evidence",
16465
+ name: "Converging Evidence",
16466
+ description: "Find claims supported by independent evidence streams.",
16467
+ prompt: "Find beliefs with genuinely independent converging evidence and explain why they are robust.",
16468
+ highlightStrategy: "convergence"
16469
+ },
16470
+ {
16471
+ id: "weakest-links",
16472
+ categoryId: "reasoning",
16473
+ mode: "stress",
16474
+ name: "Weakest Links",
16475
+ description: "Find the weakest links in important reasoning chains.",
16476
+ prompt: "Find the weakest links in important reasoning chains and explain how to test them.",
16477
+ highlightStrategy: "weak-links",
16478
+ riskLevel: "medium"
16479
+ },
16480
+ {
16481
+ id: "challenged-beliefs",
16482
+ categoryId: "reasoning",
16483
+ mode: "stress",
16484
+ name: "Challenged Beliefs",
16485
+ description: "Find beliefs with active challenges or defeaters.",
16486
+ prompt: "Find beliefs with active challenges, contradiction edges, or unresolved defeaters.",
16487
+ highlightStrategy: "challenged"
16488
+ },
16489
+ {
16490
+ id: "contrarian-map",
16491
+ categoryId: "strategic",
16492
+ mode: "alpha",
16493
+ name: "Contrarian Map",
16494
+ description: "Find non-consensus beliefs and where they are grounded.",
16495
+ prompt: "Find the graph's strongest contrarian or non-consensus beliefs and explain their support.",
16496
+ highlightStrategy: "contrarian"
16497
+ },
16498
+ {
16499
+ id: "irreversibility-audit",
16500
+ categoryId: "strategic",
16501
+ mode: "stress",
16502
+ name: "Irreversibility Audit",
16503
+ description: "Find irreversible bets and assumptions behind them.",
16504
+ prompt: "Audit irreversible decisions or beliefs and identify what must be true before acting.",
16505
+ highlightStrategy: "irreversible",
16506
+ riskLevel: "high"
16507
+ },
16508
+ {
16509
+ id: "pre-mortem",
16510
+ categoryId: "strategic",
16511
+ mode: "stress",
16512
+ name: "Pre-Mortem",
16513
+ description: "Explain how the graph could be wrong.",
16514
+ prompt: "Run a pre-mortem: assume the current thesis fails and identify the most plausible failure paths.",
16515
+ highlightStrategy: "failure-paths",
16516
+ riskLevel: "high"
16517
+ },
16518
+ {
16519
+ id: "devils-advocate",
16520
+ categoryId: "strategic",
16521
+ mode: "stress",
16522
+ name: "Devil's Advocate",
16523
+ description: "Generate the strongest critique of the graph.",
16524
+ prompt: "Produce the strongest evidence-grounded critique of the current graph and its main thesis.",
16525
+ highlightStrategy: "critique"
16526
+ },
16527
+ {
16528
+ id: "falsification-map",
16529
+ categoryId: "strategic",
16530
+ mode: "stress",
16531
+ name: "Falsification Map",
16532
+ description: "Find the cheapest tests that would disprove key beliefs.",
16533
+ prompt: "Map the cheapest, clearest falsification tests for the graph's key claims.",
16534
+ highlightStrategy: "falsification",
16535
+ riskLevel: "high"
16536
+ },
16537
+ {
16538
+ id: "prediction-tracker",
16539
+ categoryId: "strategic",
16540
+ mode: "evidence",
16541
+ name: "Prediction Tracker",
16542
+ description: "Find beliefs that imply measurable predictions.",
16543
+ prompt: "Find beliefs that imply measurable predictions and suggest tracking signals.",
16544
+ highlightStrategy: "predictions"
16545
+ },
16546
+ {
16547
+ id: "belief-pagerank",
16548
+ categoryId: "deep",
16549
+ mode: "semantic",
16550
+ name: "Belief PageRank",
16551
+ description: "Identify structurally central beliefs.",
16552
+ prompt: "Use graph centrality to identify the most structurally important beliefs.",
16553
+ highlightStrategy: "centrality"
16554
+ },
16555
+ {
16556
+ id: "underdetermination",
16557
+ categoryId: "deep",
16558
+ mode: "semantic",
16559
+ name: "Underdetermination",
16560
+ description: "Find places where evidence supports multiple explanations.",
16561
+ prompt: "Find places where the same evidence could support multiple incompatible explanations.",
16562
+ highlightStrategy: "underdetermination"
16563
+ },
16564
+ {
16565
+ id: "confidence-propagation",
16566
+ categoryId: "deep",
16567
+ mode: "semantic",
16568
+ name: "Confidence Propagation",
16569
+ description: "Assess how uncertainty moves through the graph.",
16570
+ prompt: "Explain how uncertainty propagates from weak or contested beliefs through downstream conclusions.",
16571
+ highlightStrategy: "confidence-flow"
16572
+ },
16573
+ {
16574
+ id: "argument-depth",
16575
+ categoryId: "deep",
16576
+ mode: "evidence",
16577
+ name: "Argument Depth",
16578
+ description: "Assess reasoning depth and chain quality.",
16579
+ prompt: "Assess reasoning depth: where claims are shallow, deeply supported, or overextended.",
16580
+ highlightStrategy: "depth"
16581
+ },
16582
+ {
16583
+ id: "information-edge",
16584
+ categoryId: "deep",
16585
+ mode: "alpha",
16586
+ name: "Information Edge",
16587
+ description: "Find differentiated evidence or signals.",
16588
+ prompt: "Find evidence, sources, or beliefs that could represent differentiated information edge.",
16589
+ highlightStrategy: "information-edge"
16590
+ },
16591
+ {
16592
+ id: "thesis-summary",
16593
+ categoryId: "browse",
16594
+ mode: "semantic",
16595
+ name: "Thesis Summary",
16596
+ description: "Summarize the graph's core thesis and support.",
16597
+ prompt: "Summarize the graph's core thesis, strongest support, weakest support, and open questions.",
16598
+ highlightStrategy: "summary"
16599
+ },
16600
+ {
16601
+ id: "theme-deep-dive",
16602
+ categoryId: "browse",
16603
+ mode: "semantic",
16604
+ name: "Theme Deep Dive",
16605
+ description: "Deep dive into a named theme.",
16606
+ prompt: "Deep dive into {input}. Explain the key beliefs, evidence, contradictions, and open questions.",
16607
+ inputType: "theme",
16608
+ highlightStrategy: "theme"
16609
+ },
16610
+ {
16611
+ id: "belief-detail",
16612
+ categoryId: "browse",
16613
+ mode: "semantic",
16614
+ name: "Belief Detail",
16615
+ description: "Explain one belief and its graph neighborhood.",
16616
+ prompt: "Explain {input} and its support, challenges, related beliefs, and downstream implications.",
16617
+ inputType: "belief",
16618
+ highlightStrategy: "belief"
16619
+ },
16620
+ {
16621
+ id: "strongest-beliefs",
16622
+ categoryId: "browse",
16623
+ mode: "operational",
16624
+ name: "Strongest Beliefs",
16625
+ description: "Find the graph's strongest current beliefs.",
16626
+ prompt: "Find the strongest current beliefs and explain why each one deserves confidence.",
16627
+ highlightStrategy: "strongest"
16628
+ },
16629
+ {
16630
+ id: "cross-theme-connection",
16631
+ categoryId: "browse",
16632
+ mode: "semantic",
16633
+ name: "Cross-Theme Connections",
16634
+ description: "Find bridges between themes.",
16635
+ prompt: "Find meaningful connections across themes and explain which bridge beliefs matter.",
16636
+ highlightStrategy: "bridges"
16637
+ },
16638
+ {
16639
+ id: "research-velocity",
16640
+ categoryId: "browse",
16641
+ mode: "operational",
16642
+ name: "Research Velocity",
16643
+ description: "Summarize recent graph movement and momentum.",
16644
+ prompt: "Assess research velocity: what changed recently, where progress is fastest, and what is stuck.",
16645
+ highlightStrategy: "velocity"
16646
+ },
16647
+ {
16648
+ id: "search",
16649
+ categoryId: "browse",
16650
+ mode: "semantic",
16651
+ name: "Graph Search",
16652
+ description: "Search the graph with semantic context.",
16653
+ prompt: "Search the graph for {input}. Return the most relevant beliefs, evidence, and questions.",
16654
+ inputType: "search",
16655
+ highlightStrategy: "search"
16656
+ },
16657
+ {
16658
+ id: "expert-coverage",
16659
+ categoryId: "browse",
16660
+ mode: "semantic",
16661
+ name: "Expert Coverage",
16662
+ description: "Assess coverage from expert/source perspectives.",
16663
+ prompt: "Assess whether the graph has enough expert, primary, and dissenting coverage.",
16664
+ highlightStrategy: "expert-coverage"
16665
+ },
16666
+ {
16667
+ id: "value-chain-map",
16668
+ categoryId: "browse",
16669
+ mode: "semantic",
16670
+ name: "Value Chain Map",
16671
+ description: "Map entities, dependencies, and value-chain logic.",
16672
+ prompt: "Map the value chain implied by this graph: entities, dependencies, pressure points, and missing links.",
16673
+ highlightStrategy: "value-chain"
16674
+ },
16675
+ {
16676
+ id: "meeting-brief",
16677
+ categoryId: "prep",
16678
+ mode: "semantic",
16679
+ name: "Meeting Brief",
16680
+ description: "Prepare a meeting brief from graph context.",
16681
+ prompt: "Prepare a concise meeting brief using the graph: thesis, open questions, risks, and recommended asks.",
16682
+ highlightStrategy: "brief"
16683
+ },
16684
+ {
16685
+ id: "open-questions-entity",
16686
+ categoryId: "prep",
16687
+ mode: "semantic",
16688
+ name: "Entity Open Questions",
16689
+ description: "Find open questions about a specific entity.",
16690
+ prompt: "Find the most important open questions about {input} and the beliefs those questions would unlock.",
16691
+ inputType: "entity",
16692
+ highlightStrategy: "entity-questions"
16693
+ },
16694
+ {
16695
+ id: "company-context",
16696
+ categoryId: "prep",
16697
+ mode: "semantic",
16698
+ name: "Company Context",
16699
+ description: "Summarize graph context about a company.",
16700
+ prompt: "Summarize what the graph knows about {input}: thesis relevance, evidence, risks, and open questions.",
16701
+ inputType: "company",
16702
+ highlightStrategy: "company"
16703
+ },
16704
+ {
16705
+ id: "company-theme-fit",
16706
+ categoryId: "prep",
16707
+ mode: "semantic",
16708
+ name: "Company Theme Fit",
16709
+ description: "Assess how a company fits graph themes.",
16710
+ prompt: "Assess how {input} fits the graph's themes and where the fit is weak or uncertain.",
16711
+ inputType: "company",
16712
+ highlightStrategy: "fit"
16713
+ },
16714
+ {
16715
+ id: "company-comparison",
16716
+ categoryId: "prep",
16717
+ mode: "semantic",
16718
+ name: "Company Comparison",
16719
+ description: "Compare companies through graph context.",
16720
+ prompt: "Compare {input} using graph beliefs, evidence, risks, and open questions.",
16721
+ inputType: "company-list",
16722
+ highlightStrategy: "comparison"
16723
+ },
16724
+ {
16725
+ id: "questions-to-ask",
16726
+ categoryId: "prep",
16727
+ mode: "operational",
16728
+ name: "Questions to Ask",
16729
+ description: "Generate high-signal questions from graph gaps.",
16730
+ prompt: "Generate the highest-signal questions to ask next, grounded in current graph gaps.",
16731
+ highlightStrategy: "questions"
16732
+ },
16733
+ {
16734
+ id: "beliefs-to-test",
16735
+ categoryId: "prep",
16736
+ mode: "stress",
16737
+ name: "Beliefs to Test",
16738
+ description: "Prioritize beliefs that should be tested next.",
16739
+ prompt: "Prioritize the beliefs that should be tested next and explain the cheapest test for each.",
16740
+ highlightStrategy: "tests",
16741
+ riskLevel: "medium"
16742
+ }
16743
+ ];
16744
+ var GRAPH_INTELLIGENCE_QUERIES_WITH_TOOLS = GRAPH_INTELLIGENCE_QUERIES.map((query5) => {
16745
+ const definition = query5;
16746
+ return {
16747
+ ...definition,
16748
+ tools: definition.tools ?? byMode(definition.mode)
16749
+ };
16750
+ });
16751
+ var GRAPH_INTELLIGENCE_QUICK_QUERIES = [
16752
+ {
16753
+ id: "health-check",
16754
+ name: "Health Check",
16755
+ queryId: "thesis-summary",
16756
+ prompt: "Give me a fast graph health check: biggest strengths, biggest risks, and next best action."
16757
+ },
16758
+ {
16759
+ id: "find-risks",
16760
+ name: "Find Risks",
16761
+ queryId: "weakest-links",
16762
+ prompt: "Find the most important risks in this graph and the beliefs or evidence behind each one."
16763
+ },
16764
+ {
16765
+ id: "pre-mortem",
16766
+ name: "Pre-Mortem",
16767
+ queryId: "pre-mortem",
16768
+ prompt: "Assume this thesis fails. Explain the most plausible failure paths and what would reveal them early."
16769
+ },
16770
+ {
16771
+ id: "whats-next",
16772
+ name: "What's Next",
16773
+ queryId: "questions-to-ask",
16774
+ prompt: "What should I learn or test next to make this graph more useful?"
16775
+ }
16776
+ ];
16777
+ function isGraphIntelligenceQueryMode(value) {
16778
+ return typeof value === "string" && GRAPH_INTELLIGENCE_QUERY_MODES.includes(value);
16779
+ }
16780
+ function getGraphIntelligenceQuery(queryId) {
16781
+ return GRAPH_INTELLIGENCE_QUERIES_WITH_TOOLS.find(
16782
+ (query5) => query5.id === queryId
16783
+ );
16784
+ }
16785
+ function listGraphIntelligenceQueries(filter = {}) {
16786
+ return GRAPH_INTELLIGENCE_QUERIES_WITH_TOOLS.filter((query5) => {
16787
+ if (filter.categoryId && query5.categoryId !== filter.categoryId) {
16788
+ return false;
16789
+ }
16790
+ if (filter.mode && query5.mode !== filter.mode) {
16791
+ return false;
16792
+ }
16793
+ return true;
16794
+ });
16795
+ }
16796
+ function fillGraphIntelligencePromptTemplate(prompt, input) {
16797
+ const replacement = input?.trim() || "the current topic";
16798
+ return prompt.split("{input}").join(replacement);
16799
+ }
16800
+
16801
+ // ../sdk/src/index.ts
16802
+ __reExport(src_exports, graphIntelligence_exports);
13448
16803
 
13449
16804
  // ../contracts/src/dsl/defineTable.ts
13450
16805
  function defineTable(spec) {
@@ -13462,7 +16817,10 @@ function idOf(table) {
13462
16817
  return schema;
13463
16818
  }
13464
16819
  var NODE_TYPE = z.enum(["decision", "belief", "question", "theme", "deal", "topic", "claim", "evidence", "synthesis", "answer", "atomic_fact", "excerpt", "source", "company", "person", "investor", "function", "value_chain"]);
13465
- var EDGE_TYPE = z.enum(["supports", "informs", "depends_on", "extracted_from", "contains", "tests", "supersedes", "responds_to", "belongs_to", "relates_to_thesis", "works_at", "invested_in", "competes_with", "participates_in", "founded_by", "evaluates", "performs", "function_in", "impacts", "raised_from", "mentioned_in", "perspective_on", "plays_theme", "answers", "explores", "qualifies", "based_on", "based_on_belief", "based_on_question", "blocked_by_contradiction", "informed_by_theme", "same_as", "reinforces", "parent_of", "child_of", "falsified_by", "exclusive_with", "collapses_if", "cascade_from", "counterfactual_of", "cascade_to", "mutually_exclusive", "correlates_with", "amplifies", "precondition_for", "in_tension_with", "strengthened_by", "weakened_by", "alternative_to", "subsumes", "validated_by", "required_for", "blocks", "prerequisite_for", "parallel_to", "corroborates", "extends", "same_source_as", "same_theme_as", "assumes", "would_predict", "analogous_to", "independent_of", "implements", "violates", "co_changes_with", "migrating_from", "migrating_to", "scoped_by", "about_entity", "entity_referenced_in", "contradicts", "cites", "summarizes", "related_to", "partially_answers", "refines", "branches_from"]);
16820
+ var EDGE_TYPE_VALUES = ["supports", "informs", "depends_on", "derived_from", "contains", "tests", "supersedes", "responds_to", "belongs_to", "relates_to_thesis", "works_at", "invested_in", "competes_with", "participates_in", "founded_by", "evaluates", "performs", "function_in", "impacts", "raised_from", "mentioned_in", "perspective_on", "plays_theme", "answers", "explores", "qualifies", "based_on", "based_on_belief", "based_on_question", "blocked_by_contradiction", "informed_by_theme", "same_as", "reinforces", "parent_of", "child_of", "falsified_by", "exclusive_with", "collapses_if", "cascade_from", "counterfactual_of", "cascade_to", "mutually_exclusive", "correlates_with", "amplifies", "precondition_for", "in_tension_with", "strengthened_by", "weakened_by", "alternative_to", "subsumes", "validated_by", "required_for", "blocks", "prerequisite_for", "parallel_to", "corroborates", "extends", "same_source_as", "same_theme_as", "assumes", "would_predict", "analogous_to", "independent_of", "implements", "violates", "co_changes_with", "migrating_from", "migrating_to", "scoped_by", "about_entity", "entity_referenced_in", "contradicts", "cites", "summarizes", "related_to", "partially_answers", "refines", "branches_from"];
16821
+ var STORAGE_EDGE_TYPE_VALUES = [...EDGE_TYPE_VALUES, "extracted_from"];
16822
+ z.enum(EDGE_TYPE_VALUES);
16823
+ var STORAGE_EDGE_TYPE = z.enum(STORAGE_EDGE_TYPE_VALUES);
13466
16824
  var TOPIC_STATUS = z.enum(["active", "archived", "watching"]);
13467
16825
  var TOPIC_VISIBILITY = z.enum(["private", "team", "firm", "external", "public"]);
13468
16826
  defineTable({
@@ -14947,7 +18305,7 @@ defineTable({
14947
18305
  "toNodeId": z.string().optional(),
14948
18306
  "sourceGlobalId": z.string().optional(),
14949
18307
  "targetGlobalId": z.string().optional(),
14950
- "edgeType": EDGE_TYPE,
18308
+ "edgeType": STORAGE_EDGE_TYPE,
14951
18309
  "edgeTier": z.string().optional(),
14952
18310
  "domainNamespace": z.string().optional(),
14953
18311
  "constraint": z.string().optional(),
@@ -17718,6 +21076,298 @@ var edgePolicyManifest = {
17718
21076
  }
17719
21077
  ]
17720
21078
  };
21079
+
21080
+ // ../contracts/src/tenant-client.contract.ts
21081
+ var TENANT_CLIENT_INSTALL_TOKEN_INFISICAL_PATH = "tenants/shared";
21082
+ var TENANT_CLIENT_INSTALLABLE_PACKAGES = [
21083
+ {
21084
+ packageName: "@lucern/access-control",
21085
+ role: "runtime_entrypoint",
21086
+ directTenantImport: true
21087
+ },
21088
+ {
21089
+ packageName: "@lucern/agent",
21090
+ role: "platform_runtime",
21091
+ directTenantImport: false
21092
+ },
21093
+ {
21094
+ packageName: "@lucern/auth",
21095
+ role: "sdk_dependency",
21096
+ directTenantImport: false
21097
+ },
21098
+ {
21099
+ packageName: "@lucern/cli",
21100
+ role: "developer_tool",
21101
+ directTenantImport: false
21102
+ },
21103
+ {
21104
+ packageName: "@lucern/client-core",
21105
+ role: "sdk_dependency",
21106
+ directTenantImport: false
21107
+ },
21108
+ {
21109
+ packageName: "@lucern/confidence",
21110
+ role: "sdk_dependency",
21111
+ directTenantImport: false
21112
+ },
21113
+ {
21114
+ packageName: "@lucern/config",
21115
+ role: "configuration",
21116
+ directTenantImport: false
21117
+ },
21118
+ {
21119
+ packageName: "@lucern/contracts",
21120
+ role: "contract_entrypoint",
21121
+ directTenantImport: true
21122
+ },
21123
+ {
21124
+ packageName: "@lucern/control-plane",
21125
+ role: "platform_runtime",
21126
+ directTenantImport: false
21127
+ },
21128
+ {
21129
+ packageName: "@lucern/developer-kit",
21130
+ role: "developer_tool",
21131
+ directTenantImport: false
21132
+ },
21133
+ {
21134
+ packageName: "@lucern/events",
21135
+ role: "sdk_dependency",
21136
+ directTenantImport: false
21137
+ },
21138
+ {
21139
+ packageName: "@lucern/graph-primitives",
21140
+ role: "sdk_dependency",
21141
+ directTenantImport: false
21142
+ },
21143
+ {
21144
+ packageName: "@lucern/identity",
21145
+ role: "component_runtime",
21146
+ directTenantImport: false
21147
+ },
21148
+ {
21149
+ packageName: "@lucern/mcp",
21150
+ role: "runtime_entrypoint",
21151
+ directTenantImport: true
21152
+ },
21153
+ {
21154
+ packageName: "@lucern/pack-host",
21155
+ role: "platform_runtime",
21156
+ directTenantImport: false
21157
+ },
21158
+ {
21159
+ packageName: "@lucern/pack-installer",
21160
+ role: "developer_tool",
21161
+ directTenantImport: false
21162
+ },
21163
+ {
21164
+ packageName: "@lucern/proof-compiler",
21165
+ role: "developer_tool",
21166
+ directTenantImport: false
21167
+ },
21168
+ {
21169
+ packageName: "@lucern/react",
21170
+ role: "runtime_entrypoint",
21171
+ directTenantImport: true
21172
+ },
21173
+ {
21174
+ packageName: "@lucern/reasoning-kernel",
21175
+ role: "component_runtime",
21176
+ directTenantImport: false
21177
+ },
21178
+ {
21179
+ packageName: "@lucern/sdk",
21180
+ role: "runtime_entrypoint",
21181
+ directTenantImport: true
21182
+ },
21183
+ {
21184
+ packageName: "@lucern/server-core",
21185
+ role: "platform_runtime",
21186
+ directTenantImport: false
21187
+ },
21188
+ {
21189
+ packageName: "@lucern/testing",
21190
+ role: "test_support",
21191
+ directTenantImport: false
21192
+ },
21193
+ {
21194
+ packageName: "@lucern/types",
21195
+ role: "contract_entrypoint",
21196
+ directTenantImport: true
21197
+ }
21198
+ ];
21199
+ TENANT_CLIENT_INSTALLABLE_PACKAGES.map(
21200
+ (entry) => entry.packageName
21201
+ );
21202
+ var INFISICAL_RUNTIME_DEFAULT_API_URL = "https://app.infisical.com";
21203
+ var INFISICAL_RUNTIME_DEFAULT_PROJECT_ID = "344b0526-90df-4606-ba50-22c647a36c65";
21204
+ var INFISICAL_RUNTIME_BOOTSTRAP_ENV = {
21205
+ apiUrl: ["INFISICAL_API_URL", "INFISICAL_URL"],
21206
+ projectId: ["INFISICAL_PROJECT_ID", "INFISICAL_WORKSPACE_ID"],
21207
+ clientId: [
21208
+ "INFISICAL_CLIENT_ID",
21209
+ "INFISICAL_MACHINE_CLIENT_ID",
21210
+ "INFISICAL_UNIVERSAL_AUTH_CLIENT_ID"
21211
+ ],
21212
+ clientSecret: [
21213
+ "INFISICAL_CLIENT_SECRET",
21214
+ "INFISICAL_MACHINE_CLIENT_SECRET",
21215
+ "INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET"
21216
+ ],
21217
+ environment: ["INFISICAL_ENV", "LUCERN_INFISICAL_ENV"],
21218
+ organizationSlug: ["INFISICAL_ORG_SLUG", "INFISICAL_ORGANIZATION_SLUG"],
21219
+ disabled: ["LUCERN_INFISICAL_DISABLE", "INFISICAL_DISABLE"]
21220
+ };
21221
+ var INFISICAL_RUNTIME_PATHS = [
21222
+ {
21223
+ id: "platform-auth",
21224
+ secretPath: "/platform/auth",
21225
+ description: "Lucern platform authentication secrets. Synced into Vercel web/gateway projects; never distributed to tenant tools.",
21226
+ variables: [
21227
+ {
21228
+ name: "NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY",
21229
+ required: true,
21230
+ secret: false,
21231
+ public: true,
21232
+ description: "Clerk publishable key for the Lucern web origin."
21233
+ },
21234
+ {
21235
+ name: "CLERK_SECRET_KEY",
21236
+ required: true,
21237
+ secret: true,
21238
+ public: false,
21239
+ description: "Clerk backend secret key for Lucern server runtimes."
21240
+ },
21241
+ {
21242
+ name: "CLERK_JWT_ISSUER_DOMAIN",
21243
+ required: false,
21244
+ secret: false,
21245
+ public: false,
21246
+ description: "Expected Clerk issuer/JWKS domain for JWT verification."
21247
+ },
21248
+ {
21249
+ name: "NEXT_PUBLIC_CLERK_SIGN_IN_URL",
21250
+ required: false,
21251
+ secret: false,
21252
+ public: true,
21253
+ description: "Public sign-in URL for Lucern-owned web flows."
21254
+ },
21255
+ {
21256
+ name: "NEXT_PUBLIC_CLERK_SIGN_UP_URL",
21257
+ required: false,
21258
+ secret: false,
21259
+ public: true,
21260
+ description: "Public sign-up URL for Lucern-owned web flows."
21261
+ }
21262
+ ]
21263
+ },
21264
+ {
21265
+ id: "platform-runtime",
21266
+ secretPath: "/platform/runtime",
21267
+ description: "Runtime defaults shared by server-side Lucern clients and operator tooling.",
21268
+ variables: [
21269
+ {
21270
+ name: "LUCERN_API_URL",
21271
+ required: true,
21272
+ secret: false,
21273
+ public: false,
21274
+ aliases: ["LUCERN_API_BASE_URL", "LUCERN_BASE_URL"],
21275
+ description: "Canonical Lucern API gateway URL."
21276
+ },
21277
+ {
21278
+ name: "LUCERN_LOGIN_BASE_URL",
21279
+ required: false,
21280
+ secret: false,
21281
+ public: false,
21282
+ aliases: ["LUCERN_AUTH_BASE_URL"],
21283
+ description: "Browser login origin used when it differs from the API."
21284
+ },
21285
+ {
21286
+ name: "LUCERN_ENVIRONMENT",
21287
+ required: false,
21288
+ secret: false,
21289
+ public: false,
21290
+ aliases: ["LUCERN_ENV"],
21291
+ description: "Lucern environment label consumed by CLI profiles."
21292
+ }
21293
+ ]
21294
+ },
21295
+ {
21296
+ id: "tenant-shared-install",
21297
+ secretPath: TENANT_CLIENT_INSTALL_TOKEN_INFISICAL_PATH,
21298
+ description: "Tenant package-install secrets. This is install-only and distinct from platform publish credentials.",
21299
+ variables: [
21300
+ {
21301
+ name: "INSTALL_LUCERN_NPM",
21302
+ required: true,
21303
+ secret: true,
21304
+ public: false,
21305
+ description: "Read-only install token for the published @lucern/* suite."
21306
+ }
21307
+ ]
21308
+ }
21309
+ ];
21310
+ var INFISICAL_RUNTIME_SURFACES = [
21311
+ {
21312
+ id: "lucern-web",
21313
+ delivery: "vercel_sync",
21314
+ sourcePathIds: ["platform-auth", "platform-runtime"],
21315
+ consumer: "apps/web on Vercel project lucern",
21316
+ description: "Lucern web consumes Clerk and runtime config via Infisical-to-Vercel syncs."
21317
+ },
21318
+ {
21319
+ id: "lucern-gateway",
21320
+ delivery: "vercel_sync",
21321
+ sourcePathIds: ["platform-auth", "platform-runtime"],
21322
+ consumer: "apps/gateway on Vercel project lucern-gateway",
21323
+ description: "Lucern gateway consumes platform config via Infisical-to-Vercel syncs."
21324
+ },
21325
+ {
21326
+ id: "lucern-sdk",
21327
+ packageName: "@lucern/sdk",
21328
+ delivery: "runtime_fetch",
21329
+ sourcePathIds: ["platform-runtime"],
21330
+ consumer: "server-side SDK operator contexts with a scoped Infisical identity",
21331
+ description: "SDK exposes the runtime Infisical resolver used by clients that have machine identity credentials."
21332
+ },
21333
+ {
21334
+ id: "lucern-cli",
21335
+ packageName: "@lucern/cli",
21336
+ delivery: "runtime_fetch",
21337
+ fallback: "device_auth",
21338
+ sourcePathIds: ["platform-runtime"],
21339
+ consumer: "developer/operator CLI processes",
21340
+ description: "CLI hydrates runtime defaults from Infisical when configured, then authenticates users through Lucern device login."
21341
+ },
21342
+ {
21343
+ id: "lucern-mcp",
21344
+ packageName: "@lucern/mcp",
21345
+ delivery: "runtime_fetch",
21346
+ fallback: "device_auth",
21347
+ sourcePathIds: ["platform-runtime"],
21348
+ consumer: "MCP server/client processes",
21349
+ description: "MCP hydrates runtime defaults through the SDK resolver and remains a Lucern client, not a platform secret owner."
21350
+ },
21351
+ {
21352
+ id: "tenant-client",
21353
+ delivery: "device_auth",
21354
+ sourcePathIds: ["tenant-shared-install"],
21355
+ consumer: "tenant-owned apps and coding agents",
21356
+ description: "Tenant clients install the published packages and receive user/service credentials through Lucern auth surfaces."
21357
+ }
21358
+ ];
21359
+ function findInfisicalRuntimePath(pathId) {
21360
+ return INFISICAL_RUNTIME_PATHS.find((path2) => path2.id === pathId);
21361
+ }
21362
+ function findInfisicalRuntimeSurface(surfaceId) {
21363
+ return INFISICAL_RUNTIME_SURFACES.find(
21364
+ (surface) => surface.id === surfaceId
21365
+ );
21366
+ }
21367
+
21368
+ // ../contracts/src/manifests/infisical-runtime-manifest.ts
21369
+ var INFISICAL_RUNTIME_MANIFEST = {
21370
+ bootstrapEnv: INFISICAL_RUNTIME_BOOTSTRAP_ENV};
17721
21371
  z.object({
17722
21372
  manifestVersion: z.literal("1.0.0"),
17723
21373
  rules: z.array(
@@ -20447,6 +24097,15 @@ var edgesContracts = [
20447
24097
  args: queryLineageArgs
20448
24098
  })
20449
24099
  ];
24100
+ var graphIntelligenceQueryModes = [
24101
+ "core",
24102
+ "bias",
24103
+ "stress",
24104
+ "operational",
24105
+ "alpha",
24106
+ "semantic",
24107
+ "evidence"
24108
+ ];
20450
24109
  var traversalLayerSchema = z.enum([
20451
24110
  "L4",
20452
24111
  "L3",
@@ -20480,6 +24139,22 @@ var graphNeighborhoodArgs = z.object({
20480
24139
  topicId: z.string().optional().describe("Topic scope for edge lookup."),
20481
24140
  limit: z.number().optional().describe("Maximum edges to return.")
20482
24141
  });
24142
+ var graphIntelligenceModeSchema = z.enum([
24143
+ graphIntelligenceQueryModes[0],
24144
+ ...graphIntelligenceQueryModes.slice(1)
24145
+ ]);
24146
+ var graphIntelligenceCatalogArgs = z.object({
24147
+ categoryId: z.string().optional().describe("Optional query category filter."),
24148
+ mode: graphIntelligenceModeSchema.optional().describe("Optional Graph Intelligence query mode filter.")
24149
+ });
24150
+ var graphIntelligenceRunArgs = z.object({
24151
+ topicId: z.string().describe("Topic to analyze."),
24152
+ queryId: z.string().optional().describe("Catalog query ID to run, such as pre-mortem."),
24153
+ prompt: z.string().optional().describe("Custom prompt when queryId is omitted or overridden."),
24154
+ input: z.string().optional().describe("Optional entity, theme, belief, company, or search text."),
24155
+ mode: graphIntelligenceModeSchema.optional().describe("Optional query mode override for custom prompts."),
24156
+ limit: z.number().optional().describe("Maximum graph context rows to return.")
24157
+ });
20483
24158
  var flagContradictionArgs = z.object({
20484
24159
  beliefA: z.string().describe("First belief in tension."),
20485
24160
  beliefB: z.string().describe("Second belief in tension."),
@@ -20585,6 +24260,38 @@ var graphContracts = [
20585
24260
  kind: "query"
20586
24261
  }
20587
24262
  }),
24263
+ surfaceContract({
24264
+ name: "list_graph_intelligence_queries",
24265
+ kind: "query",
24266
+ domain: "graph",
24267
+ surfaceClass: "platform_public",
24268
+ path: "/graph-intelligence/queries",
24269
+ sdkNamespace: "graphAnalysis",
24270
+ sdkMethod: "listGraphIntelligenceQueries",
24271
+ summary: "List Graph Intelligence query catalog entries.",
24272
+ convex: {
24273
+ module: "contextCompiler",
24274
+ functionName: "listGraphIntelligenceQueries",
24275
+ kind: "query"
24276
+ },
24277
+ args: graphIntelligenceCatalogArgs
24278
+ }),
24279
+ surfaceContract({
24280
+ name: "run_graph_intelligence_query",
24281
+ kind: "query",
24282
+ domain: "graph",
24283
+ surfaceClass: "platform_public",
24284
+ path: "/graph-intelligence/run",
24285
+ sdkNamespace: "graphAnalysis",
24286
+ sdkMethod: "runGraphIntelligenceQuery",
24287
+ summary: "Run a Graph Intelligence query against a topic graph.",
24288
+ convex: {
24289
+ module: "contextCompiler",
24290
+ functionName: "runGraphIntelligenceQuery",
24291
+ kind: "query"
24292
+ },
24293
+ args: graphIntelligenceRunArgs
24294
+ }),
20588
24295
  surfaceContract({
20589
24296
  name: "find_contradictions",
20590
24297
  kind: "query",
@@ -21961,6 +25668,292 @@ TENANT_BOOTSTRAP_TABLE_REQUIREMENTS.filter(
21961
25668
  (entry) => !isCopyableSeedRequirement(entry)
21962
25669
  ).map((entry) => entry.table);
21963
25670
 
25671
+ // ../sdk/src/infisicalRuntime.ts
25672
+ var InfisicalRuntimeError = class extends Error {
25673
+ code;
25674
+ status;
25675
+ constructor(args) {
25676
+ super(args.message);
25677
+ this.name = "InfisicalRuntimeError";
25678
+ this.code = args.code;
25679
+ this.status = args.status;
25680
+ }
25681
+ };
25682
+ function readInfisicalRuntimeBootstrap(env = {}, overrides = {}) {
25683
+ if (isInfisicalRuntimeDisabled(env)) {
25684
+ return null;
25685
+ }
25686
+ const bootstrapEnv = INFISICAL_RUNTIME_MANIFEST.bootstrapEnv;
25687
+ const clientId = overrides.clientId ?? readFirst(env, bootstrapEnv.clientId);
25688
+ const clientSecret = overrides.clientSecret ?? readFirst(env, bootstrapEnv.clientSecret);
25689
+ const hasAuthSignal = Boolean(clientId || clientSecret);
25690
+ if (!hasAuthSignal) {
25691
+ return null;
25692
+ }
25693
+ if (!clientId || !clientSecret) {
25694
+ throw new InfisicalRuntimeError({
25695
+ code: "INFISICAL_BOOTSTRAP_INCOMPLETE",
25696
+ message: "Infisical runtime bootstrap requires both INFISICAL_CLIENT_ID and INFISICAL_CLIENT_SECRET."
25697
+ });
25698
+ }
25699
+ return {
25700
+ apiUrl: overrides.apiUrl ?? readFirst(env, bootstrapEnv.apiUrl) ?? INFISICAL_RUNTIME_DEFAULT_API_URL,
25701
+ projectId: overrides.projectId ?? readFirst(env, bootstrapEnv.projectId) ?? INFISICAL_RUNTIME_DEFAULT_PROJECT_ID,
25702
+ clientId,
25703
+ clientSecret,
25704
+ environment: normalizeInfisicalEnvironment(
25705
+ overrides.environment ?? readFirst(env, bootstrapEnv.environment)
25706
+ ),
25707
+ organizationSlug: overrides.organizationSlug ?? readFirst(env, bootstrapEnv.organizationSlug)
25708
+ };
25709
+ }
25710
+ function isInfisicalRuntimeDisabled(env = {}) {
25711
+ return INFISICAL_RUNTIME_MANIFEST.bootstrapEnv.disabled.some(
25712
+ (name) => isTruthyEnv(env[name])
25713
+ );
25714
+ }
25715
+ async function hydrateInfisicalRuntimeEnv(options) {
25716
+ const env = options.env ?? {};
25717
+ const bootstrap = mergeBootstrap(
25718
+ readInfisicalRuntimeBootstrap(env, options.bootstrap),
25719
+ options.bootstrap
25720
+ );
25721
+ if (!bootstrap) {
25722
+ return {
25723
+ status: "disabled",
25724
+ surfaceId: options.surfaceId,
25725
+ values: {},
25726
+ sourcePaths: []
25727
+ };
25728
+ }
25729
+ const surface = findInfisicalRuntimeSurface(options.surfaceId);
25730
+ if (!surface) {
25731
+ throw new InfisicalRuntimeError({
25732
+ code: "INFISICAL_UNKNOWN_SURFACE",
25733
+ message: `Unknown Lucern Infisical runtime surface: ${options.surfaceId}.`
25734
+ });
25735
+ }
25736
+ if (surface.delivery !== "runtime_fetch") {
25737
+ throw new InfisicalRuntimeError({
25738
+ code: "INFISICAL_UNSUPPORTED_SURFACE_DELIVERY",
25739
+ message: `${surface.id} uses ${surface.delivery}; runtime fetch is only valid for runtime_fetch surfaces.`
25740
+ });
25741
+ }
25742
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
25743
+ if (typeof fetchImpl !== "function") {
25744
+ throw new InfisicalRuntimeError({
25745
+ code: "INFISICAL_FETCH_UNAVAILABLE",
25746
+ message: "No fetch implementation is available for Infisical runtime hydration."
25747
+ });
25748
+ }
25749
+ const token = await loginWithUniversalAuth(bootstrap, fetchImpl);
25750
+ const values = {};
25751
+ const missingRequired = [];
25752
+ const sourcePaths = [];
25753
+ for (const pathId of surface.sourcePathIds) {
25754
+ const path2 = findInfisicalRuntimePath(pathId);
25755
+ if (!path2) {
25756
+ throw new InfisicalRuntimeError({
25757
+ code: "INFISICAL_UNKNOWN_PATH",
25758
+ message: `Unknown Lucern Infisical runtime path: ${pathId}.`
25759
+ });
25760
+ }
25761
+ sourcePaths.push(path2.secretPath);
25762
+ for (const variable of path2.variables) {
25763
+ const runtimeVariable = variable;
25764
+ const secretValue = await readVariableSecret({
25765
+ bootstrap,
25766
+ fetchImpl,
25767
+ token,
25768
+ secretPath: path2.secretPath,
25769
+ variable: runtimeVariable
25770
+ });
25771
+ if (!secretValue) {
25772
+ if (runtimeVariable.required) {
25773
+ missingRequired.push(runtimeVariable.name);
25774
+ }
25775
+ continue;
25776
+ }
25777
+ values[runtimeVariable.name] = secretValue.value;
25778
+ for (const alias of runtimeVariable.aliases ?? []) {
25779
+ values[alias] = secretValue.value;
25780
+ }
25781
+ }
25782
+ }
25783
+ if (missingRequired.length > 0) {
25784
+ throw new InfisicalRuntimeError({
25785
+ code: "INFISICAL_REQUIRED_SECRETS_MISSING",
25786
+ message: `Missing required Infisical runtime secrets: ${missingRequired.join(", ")}.`
25787
+ });
25788
+ }
25789
+ return {
25790
+ status: "hydrated",
25791
+ surfaceId: options.surfaceId,
25792
+ environment: bootstrap.environment,
25793
+ values,
25794
+ sourcePaths
25795
+ };
25796
+ }
25797
+ function applyInfisicalRuntimeEnv(result, targetEnv, options = {}) {
25798
+ for (const [key, value] of Object.entries(result.values)) {
25799
+ if (options.overrideExisting || !targetEnv[key]) {
25800
+ targetEnv[key] = value;
25801
+ }
25802
+ }
25803
+ }
25804
+ function normalizeInfisicalEnvironment(value) {
25805
+ if (value === "dev" || value === "staging" || value === "prod") {
25806
+ return value;
25807
+ }
25808
+ if (value === "development") {
25809
+ return "dev";
25810
+ }
25811
+ if (value === "production") {
25812
+ return "prod";
25813
+ }
25814
+ return "prod";
25815
+ }
25816
+ function mergeBootstrap(base, overrides) {
25817
+ if (!base) {
25818
+ return null;
25819
+ }
25820
+ return {
25821
+ ...base,
25822
+ ...compact(overrides ?? {}),
25823
+ apiUrl: trimTrailingSlash(overrides?.apiUrl ?? base.apiUrl)
25824
+ };
25825
+ }
25826
+ async function loginWithUniversalAuth(bootstrap, fetchImpl) {
25827
+ const response = await fetchImpl(
25828
+ `${trimTrailingSlash(bootstrap.apiUrl)}/api/v1/auth/universal-auth/login`,
25829
+ {
25830
+ method: "POST",
25831
+ headers: {
25832
+ "Content-Type": "application/json"
25833
+ },
25834
+ body: JSON.stringify({
25835
+ clientId: bootstrap.clientId,
25836
+ clientSecret: bootstrap.clientSecret,
25837
+ ...bootstrap.organizationSlug ? { organizationSlug: bootstrap.organizationSlug } : {}
25838
+ })
25839
+ }
25840
+ );
25841
+ const body4 = await readJson2(response);
25842
+ if (!response.ok) {
25843
+ throw new InfisicalRuntimeError({
25844
+ code: "INFISICAL_UNIVERSAL_AUTH_FAILED",
25845
+ status: response.status,
25846
+ message: `Infisical Universal Auth failed with HTTP ${response.status}: ${messageFromBody(body4)}`
25847
+ });
25848
+ }
25849
+ const accessToken = readNestedString(body4, ["accessToken"]);
25850
+ if (!accessToken) {
25851
+ throw new InfisicalRuntimeError({
25852
+ code: "INFISICAL_UNIVERSAL_AUTH_INVALID_RESPONSE",
25853
+ message: "Infisical Universal Auth response did not include accessToken."
25854
+ });
25855
+ }
25856
+ return accessToken;
25857
+ }
25858
+ async function readVariableSecret(args) {
25859
+ const names = [args.variable.name, ...args.variable.aliases ?? []];
25860
+ for (const name of names) {
25861
+ const value = await readSecretValue({
25862
+ bootstrap: args.bootstrap,
25863
+ fetchImpl: args.fetchImpl,
25864
+ token: args.token,
25865
+ secretPath: args.secretPath,
25866
+ name,
25867
+ optional: true
25868
+ });
25869
+ if (value) {
25870
+ return { name, value };
25871
+ }
25872
+ }
25873
+ return null;
25874
+ }
25875
+ async function readSecretValue(args) {
25876
+ const params = new URLSearchParams({
25877
+ projectId: args.bootstrap.projectId,
25878
+ environment: args.bootstrap.environment,
25879
+ secretPath: args.secretPath,
25880
+ type: "shared",
25881
+ viewSecretValue: "true",
25882
+ expandSecretReferences: "true",
25883
+ includeImports: "true"
25884
+ });
25885
+ const response = await args.fetchImpl(
25886
+ `${trimTrailingSlash(args.bootstrap.apiUrl)}/api/v4/secrets/${encodeURIComponent(args.name)}?${params.toString()}`,
25887
+ {
25888
+ method: "GET",
25889
+ headers: {
25890
+ Authorization: `Bearer ${args.token}`
25891
+ }
25892
+ }
25893
+ );
25894
+ const body4 = await readJson2(response);
25895
+ if (response.status === 404 && args.optional) {
25896
+ return null;
25897
+ }
25898
+ if (!response.ok) {
25899
+ throw new InfisicalRuntimeError({
25900
+ code: "INFISICAL_SECRET_READ_FAILED",
25901
+ status: response.status,
25902
+ message: `Infisical secret ${args.name} read failed with HTTP ${response.status}: ${messageFromBody(body4)}`
25903
+ });
25904
+ }
25905
+ return readNestedString(body4, ["secret", "secretValue"]);
25906
+ }
25907
+ async function readJson2(response) {
25908
+ try {
25909
+ return await response.json();
25910
+ } catch {
25911
+ return void 0;
25912
+ }
25913
+ }
25914
+ function readNestedString(value, path2) {
25915
+ let current = value;
25916
+ for (const key of path2) {
25917
+ if (!current || typeof current !== "object" || !(key in current)) {
25918
+ return null;
25919
+ }
25920
+ current = current[key];
25921
+ }
25922
+ return typeof current === "string" && current.length > 0 ? current : null;
25923
+ }
25924
+ function messageFromBody(body4) {
25925
+ if (!body4 || typeof body4 !== "object") {
25926
+ return "no response body";
25927
+ }
25928
+ const record = body4;
25929
+ for (const key of ["message", "error", "errorMessage"]) {
25930
+ if (typeof record[key] === "string") {
25931
+ return record[key];
25932
+ }
25933
+ }
25934
+ return JSON.stringify(body4);
25935
+ }
25936
+ function readFirst(env, names) {
25937
+ for (const name of names) {
25938
+ const value = env[name]?.trim();
25939
+ if (value) {
25940
+ return value;
25941
+ }
25942
+ }
25943
+ return void 0;
25944
+ }
25945
+ function isTruthyEnv(value) {
25946
+ return ["1", "true", "yes", "on"].includes(value?.toLowerCase() ?? "");
25947
+ }
25948
+ function trimTrailingSlash(value) {
25949
+ return value.replace(/\/+$/u, "");
25950
+ }
25951
+ function compact(value) {
25952
+ return Object.fromEntries(
25953
+ Object.entries(value).filter(([, entry]) => entry !== void 0)
25954
+ );
25955
+ }
25956
+
21964
25957
  // src/execution.ts
21965
25958
  var SCOPE_ALIAS_GROUPS = [];
21966
25959
  function createToolExecutionEnvelope(args) {
@@ -23707,9 +27700,9 @@ var MCP_RATE_LIMIT_SIGNALS = [
23707
27700
  "RATE_LIMIT_EXCEEDED",
23708
27701
  "Retry-After"
23709
27702
  ];
23710
- var OPERATION_MANIFEST = LUCERN_OPERATION_MANIFEST;
27703
+ var OPERATION_MANIFEST2 = LUCERN_OPERATION_MANIFEST;
23711
27704
  function mcpExposureFor(toolName) {
23712
- return OPERATION_MANIFEST[toolName]?.surfaces.mcp ?? "none";
27705
+ return OPERATION_MANIFEST2[toolName]?.surfaces.mcp ?? "none";
23713
27706
  }
23714
27707
  function withManifestVisibility(toolName, contract) {
23715
27708
  return mcpExposureFor(toolName) === "internal" || contract.internal ? { ...contract, internal: true } : contract;