@subcortex-ai/sdk 0.3.7 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/http.ts","../src/types/schema.ts","../src/types/signals.ts","../src/signals.ts","../src/users.ts","../src/types/rules.ts","../src/rules.ts","../src/client.ts","../src/context.ts"],"sourcesContent":["/**\n * @subcortex-ai/sdk — TypeScript SDK for the SubCortex Cognitive Engine\n *\n * @example\n * ```typescript\n * import { SubCortexClient } from '@subcortex-ai/sdk'\n *\n * const subcortex = new SubCortexClient({\n * endpoint: 'https://api.subcortex.example.com',\n * tenantId: 'my-tenant',\n * apiKey: 'scx_live_...',\n * })\n *\n * // Assertions\n * await subcortex.assertions.create({ subject: 'user:alice', predicate: 'name', value: 'Alice' })\n * const facts = await subcortex.assertions.query('user:alice')\n *\n * // Relationships\n * await subcortex.relationships.create({ fromSubject: 'user:alice', toSubject: 'team:eng', relationshipType: 'member_of' })\n *\n * // Health\n * const health = await subcortex.health()\n * ```\n */\n\n// Client\nexport { SubCortexClient } from './client'\nexport type { SubCortexClientOptions } from './client'\n\n// Namespace classes (for type reference in docs)\nexport {\n AssertionsNamespace, RelationshipsNamespace, AgentsNamespace, MemoryNamespace,\n GraphNamespace, TemporalNamespace, SearchNamespace, RecallNamespace, ExperiencesNamespace,\n EntitiesNamespace,\n} from './client'\n\n// HTTP transport config\nexport type { RetryConfig } from './http'\n\n// Assertion types\nexport type {\n Assertion,\n CreateAssertionInput,\n SupersedeAssertionInput,\n} from './client'\n\n// Relationship types\nexport type {\n Relationship,\n CreateRelationshipInput,\n} from './client'\n\n// Agent types\nexport type {\n AgentConfig,\n AgentPersonality,\n AgentInstructions,\n AgentModelConfig,\n AgentCapability,\n AgentMemoryPolicy,\n CreateAgentInput,\n UpdateAgentInput,\n ComposedInstructions,\n} from './client'\n\n// Memory types\nexport type {\n StoreMemoryInput,\n} from './client'\n\n// Intake types (Thalamus)\nexport type {\n CandidateAssertion,\n IntakeSubmission,\n IntakeResult,\n IntakeResponseItem,\n IntakeStats,\n} from './client'\n\n// Intake namespace\nexport { IntakeNamespace } from './client'\n\n// Graph types\nexport type {\n GraphPath,\n FindPathsInput,\n TraversalNode,\n TraversalResult,\n TraverseInput,\n} from './client'\n\n// Temporal types\nexport type {\n TemporalSnapshot,\n TemporalRange,\n} from './client'\n\n// Search types\nexport type {\n SearchResult,\n SemanticSearchInput,\n} from './client'\n\n// Experience types\nexport type { Experience } from './client'\n\n// Entity types\nexport type {\n CreateEntityInput,\n AddPropertyInput,\n EntityDescription,\n} from './client'\n\n// Recall types\nexport type {\n RecallResult,\n RecallSearchInput,\n RecallSearchResponse,\n} from './client'\n\n// Users namespace\nexport { UsersNamespace } from './users'\nexport type {\n IdentifyUserInput,\n UserIdentification,\n UserMemory,\n ConnectedPerson,\n ConflictItem,\n RegisterPersonInput,\n RegisterPersonResult,\n RecordRapportInput,\n} from './types/users'\n\n// Context formatting (model injection)\nexport { formatContext, toContextXml, CONTEXT_SCHEMA_VERSION } from './context'\nexport type { ContextFormat, ContextFormatOptions } from './context'\n\n// Signals namespace\nexport { SignalsNamespace } from './signals'\nexport type {\n SignalType,\n SystemSignalType,\n SignalEntry,\n SignalSnapshot,\n RecordSignalInput,\n SignalQueryOptions,\n ResolveSignalInput,\n Trajectory,\n} from './types/signals'\nexport {\n SYSTEM_SIGNAL_TYPES,\n SIGNAL_DECAY_CONFIG,\n POSITIVE_SIGNALS,\n NEGATIVE_SIGNALS,\n isValidSignalType,\n getDecayHalfLife,\n} from './types/signals'\n\n// Rules namespace — typed code guardrails\nexport { RulesNamespace } from './rules'\nexport type {\n RuleType,\n RuleSeverity,\n RulePredicate,\n RuleValue,\n Rule,\n CreateRuleInput,\n UpdateRuleInput,\n RuleQueryOptions,\n} from './types/rules'\nexport { RulePredicates } from './types/rules'\n\n// Schema — built-in predicates, relationships, confidence\nexport {\n SubjectPrefix,\n subject,\n IdentityPredicate,\n WorkPredicate,\n EventPredicate,\n RapportPredicate,\n MemoryPredicate,\n EntityPredicate,\n Predicates,\n OrgRelationship,\n EntityRelationship,\n RelationshipTypes,\n ConfidenceLevel,\n ConfidenceScores,\n confidenceToScore,\n scoreToConfidence,\n MULTI_VALUE_PREDICATES,\n REVERSE_RELATIONSHIPS,\n RELATIONSHIP_LABELS,\n} from './types/schema'\n\n// Common types\nexport type {\n HealthResponse,\n ConfidenceScore,\n TemporalBounds,\n Provenance,\n PaginatedResponse,\n BatchResult,\n} from './types/common'\n\n// Errors\nexport {\n SubCortexError,\n SubCortexValidationError,\n SubCortexAuthenticationError,\n SubCortexAuthorizationError,\n SubCortexNotFoundError,\n SubCortexConflictError,\n SubCortexRateLimitError,\n SubCortexServerError,\n SubCortexNetworkError,\n SubCortexTimeoutError,\n} from './errors'\n","/**\n * SubCortex SDK Error Hierarchy\n *\n * Typed error classes for programmatic error handling.\n * Consumers can catch specific error types:\n *\n * ```typescript\n * try {\n * await subcortex.assertions.create(...)\n * } catch (e) {\n * if (e instanceof SubCortexNotFoundError) { ... }\n * if (e instanceof SubCortexRateLimitError) { await sleep(e.retryAfter) }\n * }\n * ```\n */\n\n/** Base error for all SubCortex SDK errors. */\nexport class SubCortexError extends Error {\n /** HTTP status code (0 for network errors) */\n readonly statusCode: number\n /** Server-assigned request ID for debugging */\n readonly requestId?: string\n /** Whether the request can be retried */\n readonly retryable: boolean\n /** Raw response body */\n readonly body?: string\n\n constructor(\n message: string,\n statusCode: number,\n options?: {\n requestId?: string\n retryable?: boolean\n body?: string\n }\n ) {\n super(message)\n this.name = 'SubCortexError'\n this.statusCode = statusCode\n this.requestId = options?.requestId\n this.retryable = options?.retryable ?? false\n this.body = options?.body\n }\n}\n\n/** 400 — Bad request, validation failure. */\nexport class SubCortexValidationError extends SubCortexError {\n /** Field-level validation errors if available */\n readonly details?: Record<string, string>\n\n constructor(\n message: string,\n options?: {\n requestId?: string\n body?: string\n details?: Record<string, string>\n }\n ) {\n super(message, 400, { ...options, retryable: false })\n this.name = 'SubCortexValidationError'\n this.details = options?.details\n }\n}\n\n/** 401 — Invalid or missing credentials. */\nexport class SubCortexAuthenticationError extends SubCortexError {\n constructor(message: string, options?: { requestId?: string; body?: string }) {\n super(message, 401, { ...options, retryable: false })\n this.name = 'SubCortexAuthenticationError'\n }\n}\n\n/** 403 — Valid credentials but insufficient permissions. */\nexport class SubCortexAuthorizationError extends SubCortexError {\n constructor(message: string, options?: { requestId?: string; body?: string }) {\n super(message, 403, { ...options, retryable: false })\n this.name = 'SubCortexAuthorizationError'\n }\n}\n\n/** 404 — Resource not found. */\nexport class SubCortexNotFoundError extends SubCortexError {\n constructor(message: string, options?: { requestId?: string; body?: string }) {\n super(message, 404, { ...options, retryable: false })\n this.name = 'SubCortexNotFoundError'\n }\n}\n\n/** 409 — Conflict (e.g., duplicate assertion). */\nexport class SubCortexConflictError extends SubCortexError {\n constructor(message: string, options?: { requestId?: string; body?: string }) {\n super(message, 409, { ...options, retryable: false })\n this.name = 'SubCortexConflictError'\n }\n}\n\n/** 429 — Rate limit exceeded. */\nexport class SubCortexRateLimitError extends SubCortexError {\n /** Seconds to wait before retrying */\n readonly retryAfter?: number\n\n constructor(\n message: string,\n options?: {\n requestId?: string\n body?: string\n retryAfter?: number\n }\n ) {\n super(message, 429, { ...options, retryable: true })\n this.name = 'SubCortexRateLimitError'\n this.retryAfter = options?.retryAfter\n }\n}\n\n/** 5xx — Server-side error. */\nexport class SubCortexServerError extends SubCortexError {\n constructor(\n message: string,\n statusCode: number,\n options?: { requestId?: string; body?: string }\n ) {\n super(message, statusCode, { ...options, retryable: true })\n this.name = 'SubCortexServerError'\n }\n}\n\n/** Network-level failure (DNS, timeout, connection refused). */\nexport class SubCortexNetworkError extends SubCortexError {\n readonly cause?: Error\n\n constructor(message: string, options?: { cause?: Error }) {\n super(message, 0, { retryable: true })\n this.name = 'SubCortexNetworkError'\n this.cause = options?.cause\n }\n}\n\n/** Timeout — request exceeded the configured timeout. */\nexport class SubCortexTimeoutError extends SubCortexNetworkError {\n constructor(timeoutMs: number) {\n super(`Request timed out after ${timeoutMs}ms`)\n this.name = 'SubCortexTimeoutError'\n }\n}\n\n\n/**\n * Structured error response from the SubCortex REST API.\n *\n * ```json\n * {\n * \"error\": {\n * \"code\": \"NOT_FOUND\",\n * \"message\": \"Assertion not found\",\n * \"details\": { ... }\n * }\n * }\n * ```\n */\ninterface SubCortexErrorResponse {\n error?: {\n code?: string\n message?: string\n details?: Record<string, unknown>\n }\n}\n\n/**\n * Classify an HTTP response into the appropriate error type.\n * Parses structured JSON error responses from the SubCortex API.\n * Falls back to raw body if not parseable.\n */\nexport function classifyError(\n statusCode: number,\n body: string,\n requestId?: string,\n retryAfterHint?: number\n): SubCortexError {\n // Try to parse structured error response\n let errorCode = ''\n let message = ''\n let details: Record<string, string> | undefined\n\n try {\n const parsed: SubCortexErrorResponse = JSON.parse(body)\n if (parsed.error) {\n errorCode = parsed.error.code || ''\n message = parsed.error.message || ''\n if (parsed.error.details) {\n details = parsed.error.details as Record<string, string>\n }\n }\n } catch {\n // Not JSON — use raw body as message\n }\n\n if (!message) {\n message = body || `HTTP ${statusCode}`\n }\n\n const opts = { requestId, body }\n\n switch (statusCode) {\n case 400:\n return new SubCortexValidationError(message, { ...opts, details })\n case 401:\n return new SubCortexAuthenticationError(message, opts)\n case 403:\n return new SubCortexAuthorizationError(message, opts)\n case 404:\n return new SubCortexNotFoundError(message, opts)\n case 409:\n return new SubCortexConflictError(message, opts)\n case 429: {\n let retryAfter: number | undefined = retryAfterHint\n if (retryAfter === undefined) {\n try {\n const parsed = JSON.parse(body)\n retryAfter = parsed.retryAfter ?? parsed.retry_after\n } catch {\n // ignore\n }\n }\n return new SubCortexRateLimitError(message, { ...opts, retryAfter })\n }\n default:\n if (statusCode >= 500) {\n return new SubCortexServerError(message, statusCode, opts)\n }\n return new SubCortexError(message, statusCode, opts)\n }\n}\n","/**\n * HTTP Transport Layer\n *\n * Handles fetch calls, auth headers, retry with backoff,\n * timeout, request IDs, and snake_case ↔ camelCase mapping.\n *\n * This module is internal — consumers use SubCortexClient, not HttpTransport.\n */\n\nimport {\n SubCortexNetworkError,\n SubCortexRateLimitError,\n SubCortexTimeoutError,\n classifyError,\n} from './errors'\n\n// ─── Configuration ──────────────────────────────────\n\nexport interface RetryConfig {\n maxRetries: number\n baseDelayMs: number\n maxDelayMs: number\n}\n\nexport interface HttpTransportOptions {\n baseUrl: string\n tenantId: string\n apiKey?: string\n token?: string\n retry: RetryConfig\n timeoutMs: number\n fetchImpl: typeof fetch\n headers: Record<string, string>\n signal?: AbortSignal\n}\n\n// ─── snake_case ↔ camelCase mapping ─────────────────\n\nfunction snakeToCamel(s: string): string {\n return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase())\n}\n\nfunction camelToSnake(s: string): string {\n return s.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)\n}\n\n/** Deep-map object keys from snake_case to camelCase */\nexport function mapKeys(obj: unknown, mapper: (s: string) => string): unknown {\n if (obj === null || obj === undefined) return obj\n if (Array.isArray(obj)) return obj.map((item) => mapKeys(item, mapper))\n if (typeof obj === 'object') {\n const mapped: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n mapped[mapper(key)] = mapKeys(value, mapper)\n }\n return mapped\n }\n return obj\n}\n\n/** Convert wire format (snake_case) to SDK format (camelCase) */\nexport function fromWire<T>(data: unknown): T {\n return mapKeys(data, snakeToCamel) as T\n}\n\n/** Convert SDK format (camelCase) to wire format (snake_case) */\nexport function toWire(data: unknown): unknown {\n return mapKeys(data, camelToSnake)\n}\n\n// ─── Request ID generation ──────────────────────────\n\nlet counter = 0\nfunction generateRequestId(): string {\n const ts = Date.now().toString(36)\n const seq = (counter++).toString(36)\n const rand = Math.random().toString(36).slice(2, 6)\n return `scx-${ts}-${seq}-${rand}`\n}\n\n// ─── Retry with exponential backoff + jitter ────────\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction computeDelay(attempt: number, config: RetryConfig): number {\n const exponential = config.baseDelayMs * Math.pow(2, attempt)\n const capped = Math.min(exponential, config.maxDelayMs)\n // Full jitter: random between 50% and 150% of computed delay\n const jitter = capped * (0.5 + Math.random())\n return Math.round(jitter)\n}\n\nfunction isRetryable(status: number): boolean {\n return status === 429 || status >= 500\n}\n\n// ─── Transport ──────────────────────────────────────\n\nexport class HttpTransport {\n private readonly opts: HttpTransportOptions\n\n constructor(options: HttpTransportOptions) {\n this.opts = {\n ...options,\n baseUrl: options.baseUrl.replace(/\\/$/, ''),\n }\n }\n\n /** GET request with retry and typed response. */\n async get<T>(path: string, tenantId?: string): Promise<T> {\n return this.request<T>('GET', path, undefined, tenantId)\n }\n\n /** POST request with retry and typed response. */\n async post<T>(path: string, body: unknown, tenantId?: string): Promise<T> {\n return this.request<T>('POST', path, body, tenantId)\n }\n\n /** PUT request with retry and typed response. */\n async put<T>(path: string, body: unknown, tenantId?: string): Promise<T> {\n return this.request<T>('PUT', path, body, tenantId)\n }\n\n /** DELETE request with retry and typed response. */\n async delete<T>(path: string, tenantId?: string): Promise<T> {\n return this.request<T>('DELETE', path, undefined, tenantId)\n }\n\n /** Core request method with retry loop. */\n private async request<T>(\n method: string,\n path: string,\n body: unknown,\n tenantIdOverride?: string\n ): Promise<T> {\n const url = `${this.opts.baseUrl}${path}`\n const requestId = generateRequestId()\n const tenantId = tenantIdOverride || this.opts.tenantId\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'X-Request-ID': requestId,\n 'X-Tenant-ID': tenantId,\n ...this.opts.headers,\n }\n\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json'\n }\n\n // Auth header\n if (this.opts.apiKey) {\n headers['Authorization'] = `Bearer ${this.opts.apiKey}`\n } else if (this.opts.token) {\n headers['Authorization'] = `Bearer ${this.opts.token}`\n }\n\n const fetchOpts: RequestInit = {\n method,\n headers,\n body: body !== undefined ? JSON.stringify(body) : undefined,\n }\n\n let lastError: Error | undefined\n\n for (let attempt = 0; attempt <= this.opts.retry.maxRetries; attempt++) {\n try {\n const response = await this.fetchWithTimeout(url, fetchOpts)\n\n if (response.ok) {\n const text = await response.text()\n if (!text) return undefined as T\n const parsed = JSON.parse(text)\n return fromWire<T>(parsed)\n }\n\n // Non-OK response\n const responseBody = await response.text()\n\n // Rate limit: respect Retry-After header\n if (response.status === 429) {\n const retryAfterRaw = response.headers.get('Retry-After')\n const retryAfterSecs = retryAfterRaw ? parseInt(retryAfterRaw, 10) : 0\n if (attempt < this.opts.retry.maxRetries) {\n const delay = retryAfterSecs > 0\n ? retryAfterSecs * 1000\n : computeDelay(attempt, this.opts.retry)\n await sleep(delay)\n lastError = classifyError(response.status, responseBody, requestId, retryAfterSecs || undefined)\n continue\n }\n // Exhausted retries on 429 — throw with retryAfter from header\n throw classifyError(response.status, responseBody, requestId, retryAfterSecs || undefined)\n }\n\n // Retryable server error\n if (isRetryable(response.status) && attempt < this.opts.retry.maxRetries) {\n lastError = classifyError(response.status, responseBody, requestId)\n await sleep(computeDelay(attempt, this.opts.retry))\n continue\n }\n\n // Non-retryable or exhausted retries — throw classified error\n throw classifyError(response.status, responseBody, requestId)\n } catch (error) {\n // Already a SubCortexError — rethrow if non-retryable or out of retries\n if (error instanceof Error && error.name.startsWith('SubCortex')) {\n if (\n !(error as { retryable?: boolean }).retryable ||\n attempt >= this.opts.retry.maxRetries\n ) {\n throw error\n }\n lastError = error\n await sleep(computeDelay(attempt, this.opts.retry))\n continue\n }\n\n // Network-level failure (DNS, connection refused, etc.)\n if (error instanceof TypeError || error instanceof DOMException) {\n lastError = new SubCortexNetworkError(\n `Network error: ${(error as Error).message}`,\n { cause: error as Error }\n )\n if (attempt < this.opts.retry.maxRetries) {\n await sleep(computeDelay(attempt, this.opts.retry))\n continue\n }\n throw lastError\n }\n\n // Unknown error\n throw error\n }\n }\n\n // Should not reach here, but safety net\n throw lastError || new SubCortexNetworkError('Request failed after all retries')\n }\n\n /** Fetch with AbortController timeout. */\n private async fetchWithTimeout(\n url: string,\n init: RequestInit\n ): Promise<Response> {\n const controller = new AbortController()\n const timeoutId = setTimeout(\n () => controller.abort(),\n this.opts.timeoutMs\n )\n\n // Compose with user-provided signal\n if (this.opts.signal) {\n this.opts.signal.addEventListener('abort', () => controller.abort())\n }\n\n try {\n return await this.opts.fetchImpl(url, {\n ...init,\n signal: controller.signal,\n })\n } catch (error) {\n if (\n error instanceof DOMException &&\n error.name === 'AbortError' &&\n !this.opts.signal?.aborted\n ) {\n throw new SubCortexTimeoutError(this.opts.timeoutMs)\n }\n throw error\n } finally {\n clearTimeout(timeoutId)\n }\n }\n}\n","/**\n * SubCortex Built-in Schema\n *\n * These are the foundational types, predicates, relationship types,\n * and confidence levels that SubCortex supports natively. They are\n * NOT exhaustive — tenants can extend them. But these cover the\n * universal patterns every agent-user interaction needs.\n *\n * Consumer systems import these instead of using raw strings.\n */\n\n// ─── Subject Prefixes ───────────────────────────────\n\n/**\n * Well-known subject prefixes. SubCortex recognizes these and\n * provides specialized behavior for each.\n */\nexport enum SubjectPrefix {\n /** The authenticated user interacting with the agent */\n USER = 'user',\n /** A person mentioned by the user (not the user themselves) */\n PERSON = 'person',\n /** A job role or position */\n ROLE = 'role',\n /** A business entity / data model (e.g., Project, Invoice) */\n ENTITY = 'entity',\n /** A property/field on an entity */\n PROPERTY = 'property',\n /** A project, initiative, or ongoing effort */\n PROJECT = 'project',\n /** An event, meeting, or milestone */\n EVENT = 'event',\n /** An agent using SubCortex */\n AGENT = 'agent',\n}\n\n/**\n * Build a subject string from a prefix and identifier.\n * Normalizes the identifier to lowercase with hyphens.\n */\n/**\n * Common abbreviation expansions for role/title normalization.\n * Ensures \"VP of Engineering\" and \"Vice President of Engineering\"\n * resolve to the same subject.\n */\nconst TITLE_NORMALIZATIONS: [RegExp, string][] = [\n [/\\bvp\\b/gi, 'Vice President'],\n [/\\bsvp\\b/gi, 'Senior Vice President'],\n [/\\bevp\\b/gi, 'Executive Vice President'],\n [/\\bcto\\b/gi, 'Chief Technology Officer'],\n [/\\bceo\\b/gi, 'Chief Executive Officer'],\n [/\\bcfo\\b/gi, 'Chief Financial Officer'],\n [/\\bcoo\\b/gi, 'Chief Operating Officer'],\n [/\\bcmo\\b/gi, 'Chief Marketing Officer'],\n [/\\bcpo\\b/gi, 'Chief Product Officer'],\n [/\\bcio\\b/gi, 'Chief Information Officer'],\n [/\\bea\\b/gi, 'Executive Assistant'],\n [/\\bpm\\b/gi, 'Project Manager'],\n [/\\bdir\\b/gi, 'Director'],\n [/\\bsr\\b/gi, 'Senior'],\n [/\\bjr\\b/gi, 'Junior'],\n]\n\nexport function subject(prefix: SubjectPrefix | string, identifier: string): string {\n let expanded = identifier\n // Normalize titles/roles to prevent duplicate subjects from abbreviations\n if (prefix === SubjectPrefix.ROLE || prefix === 'role') {\n for (const [pattern, replacement] of TITLE_NORMALIZATIONS) {\n expanded = expanded.replace(pattern, replacement)\n }\n }\n const normalized = expanded.toLowerCase().replace(/\\s+/g, '-')\n return `${prefix}:${normalized}`\n}\n\n// ─── Predicates ─────────────────────────────────────\n\n/**\n * Built-in predicates for user/person identity and profile.\n */\nexport enum IdentityPredicate {\n NAME = 'name',\n FULL_NAME = 'full_name',\n ROLE = 'role',\n TITLE = 'title',\n DEPARTMENT = 'department',\n TEAM = 'team',\n START_DATE = 'start_date',\n EMAIL = 'email',\n}\n\n/**\n * Built-in predicates for work context.\n * NOTE: Org relationships (reports_to, manages, etc.) are NOT predicates.\n * They are relationship types — connections between two subjects.\n * See OrgRelationship enum.\n */\nexport enum WorkPredicate {\n EXPERTISE = 'expertise',\n CURRENT_PROJECT = 'current_project',\n PAIN_POINT = 'pain_point',\n}\n\n/**\n * Built-in predicates for events and status tracking.\n */\nexport enum EventPredicate {\n STATUS = 'status',\n STATUS_CHANGE = 'status_change',\n EVENT = 'event',\n DECISION = 'decision',\n OUTCOME = 'outcome',\n}\n\n/**\n * Built-in predicates for emotional/rapport tracking.\n */\nexport enum RapportPredicate {\n SENTIMENT = 'sentiment',\n FRUSTRATION = 'frustration',\n EXCITEMENT = 'excitement',\n CONCERN = 'concern',\n GOAL = 'goal',\n ASPIRATION = 'aspiration',\n PREFERENCE = 'preference',\n PAIN_POINT = 'pain_point',\n INTEREST = 'interest',\n COMMUNICATION_STYLE = 'communication_style',\n}\n\n/**\n * Built-in predicates for agent memory management.\n */\nexport enum MemoryPredicate {\n REMINDER = 'reminder',\n CONTEXT = 'context',\n CONTEXT_TASK = 'context:task',\n CURRENT_PROJECT = 'current_project',\n}\n\n/**\n * Built-in predicates for entity/schema definition.\n */\nexport enum EntityPredicate {\n TYPE = 'type',\n DESCRIPTION = 'description',\n FIELD_TYPE = 'field_type',\n REQUIRED = 'required',\n WORKFLOW = 'workflow',\n}\n\n/**\n * All built-in predicates combined.\n * Consumer systems should use these instead of raw strings.\n */\nexport const Predicates = {\n ...IdentityPredicate,\n ...WorkPredicate,\n ...EventPredicate,\n ...RapportPredicate,\n ...MemoryPredicate,\n ...EntityPredicate,\n} as const\n\n// ─── Relationship Types ─────────────────────────────\n\n/**\n * Built-in relationship types for organizational structure.\n *\n * Each relationship is directional. Many have a natural reverse:\n * reports_to ↔ manages\n * mentored_by ↔ mentors\n * member_of ↔ has_member\n */\nexport enum OrgRelationship {\n /** Person reports to user/manager */\n REPORTS_TO = 'reports_to',\n /** User/manager manages person */\n MANAGES = 'manages',\n /** Person is member of team/project */\n MEMBER_OF = 'member_of',\n /** Team/project has this person as member */\n HAS_MEMBER = 'has_member',\n /** Person holds a specific role */\n HOLDS_ROLE = 'holds_role',\n /** Person is a candidate for a role */\n CANDIDATE_FOR = 'candidate_for',\n /** Person collaborates with another person */\n COLLABORATES_WITH = 'collaborates_with',\n /** Person mentors another person */\n MENTORS = 'mentors',\n /** Person is mentored by another person */\n MENTORED_BY = 'mentored_by',\n /** Person is a stakeholder in something */\n STAKEHOLDER_IN = 'stakeholder_in',\n}\n\n/**\n * Built-in relationship types for entity/schema structure.\n */\nexport enum EntityRelationship {\n HAS_PROPERTY = 'has_property',\n BELONGS_TO = 'belongs_to',\n HAS_MANY = 'has_many',\n MANY_TO_MANY = 'many_to_many',\n DEPENDS_ON = 'depends_on',\n}\n\n/**\n * All built-in relationship types combined.\n */\nexport const RelationshipTypes = {\n ...OrgRelationship,\n ...EntityRelationship,\n} as const\n\n// ─── Confidence ─────────────────────────────────────\n\n/**\n * Standard confidence levels with numeric values.\n * The agent chooses the level; SubCortex maps to the score.\n */\nexport enum ConfidenceLevel {\n /** User stated it directly: \"My name is Alice\" */\n CONFIRMED = 'confirmed',\n /** Strongly implied: \"I've been managing the team\" → manager */\n HIGH = 'high',\n /** Reasonable inference from context */\n MODERATE = 'moderate',\n /** Speculative — worth checking later */\n LOW = 'low',\n}\n\n/** Map confidence levels to numeric scores */\nexport const ConfidenceScores: Record<ConfidenceLevel, number> = {\n [ConfidenceLevel.CONFIRMED]: 0.99,\n [ConfidenceLevel.HIGH]: 0.85,\n [ConfidenceLevel.MODERATE]: 0.65,\n [ConfidenceLevel.LOW]: 0.40,\n}\n\n/** Convert a confidence level label to a numeric score */\nexport function confidenceToScore(level: ConfidenceLevel | string): number {\n return ConfidenceScores[level as ConfidenceLevel] ?? 0.70\n}\n\n/** Convert a numeric score to the closest confidence level */\nexport function scoreToConfidence(score: number): ConfidenceLevel {\n if (score >= 0.95) return ConfidenceLevel.CONFIRMED\n if (score >= 0.80) return ConfidenceLevel.HIGH\n if (score >= 0.60) return ConfidenceLevel.MODERATE\n return ConfidenceLevel.LOW\n}\n\n// ─── Predicate Metadata ─────────────────────────────\n\n/**\n * Whether a predicate supports multiple values on the same subject.\n * Multi-value predicates don't trigger conflict detection in the Thalamus.\n */\n/**\n * Predicates that can have multiple values on the same subject.\n * These don't trigger conflict detection in the Thalamus.\n */\nexport const MULTI_VALUE_PREDICATES = new Set<string>([\n // Events — multiple things happen over time\n EventPredicate.STATUS_CHANGE,\n EventPredicate.EVENT,\n EventPredicate.DECISION,\n EventPredicate.OUTCOME,\n // Emotional — multiple sentiments about different things\n RapportPredicate.SENTIMENT,\n RapportPredicate.FRUSTRATION,\n RapportPredicate.EXCITEMENT,\n RapportPredicate.CONCERN,\n RapportPredicate.GOAL,\n RapportPredicate.INTEREST,\n // Memory — multiple reminders, contexts, projects\n MemoryPredicate.REMINDER,\n MemoryPredicate.CONTEXT_TASK,\n WorkPredicate.CURRENT_PROJECT,\n // Timeline\n 'timeline',\n])\n\n/**\n * Map from relationship type to its reverse.\n * Used by brain.users.registerPerson() to create bidirectional edges.\n */\nexport const REVERSE_RELATIONSHIPS: Record<string, string> = {\n // Proper OrgRelationship values\n [OrgRelationship.REPORTS_TO]: OrgRelationship.MANAGES,\n [OrgRelationship.MANAGES]: OrgRelationship.REPORTS_TO,\n [OrgRelationship.MEMBER_OF]: OrgRelationship.HAS_MEMBER,\n [OrgRelationship.HAS_MEMBER]: OrgRelationship.MEMBER_OF,\n [OrgRelationship.MENTORS]: OrgRelationship.MENTORED_BY,\n [OrgRelationship.MENTORED_BY]: OrgRelationship.MENTORS,\n [OrgRelationship.COLLABORATES_WITH]: OrgRelationship.COLLABORATES_WITH,\n [OrgRelationship.CANDIDATE_FOR]: OrgRelationship.CANDIDATE_FOR,\n [OrgRelationship.STAKEHOLDER_IN]: OrgRelationship.STAKEHOLDER_IN,\n // Agent-facing predicate names → proper relationship types\n // The model sends 'direct_report' as predicate, SDK maps to proper relationships\n 'direct_report': OrgRelationship.REPORTS_TO,\n 'team_member': OrgRelationship.MEMBER_OF,\n 'candidate': OrgRelationship.CANDIDATE_FOR,\n 'manager': OrgRelationship.MANAGES,\n 'stakeholder': OrgRelationship.STAKEHOLDER_IN,\n 'collaborator': OrgRelationship.COLLABORATES_WITH,\n 'mentor': OrgRelationship.MENTORED_BY,\n}\n\n/**\n * Agent-facing labels for relationship types.\n * Used in tool descriptions so the model knows what's available.\n */\nexport const RELATIONSHIP_LABELS: Record<string, string> = {\n [OrgRelationship.REPORTS_TO]: 'reports to (person is a direct report)',\n [OrgRelationship.MANAGES]: 'manages (user is the manager)',\n [OrgRelationship.MEMBER_OF]: 'is a member of (team, project)',\n [OrgRelationship.HOLDS_ROLE]: 'holds a role/position',\n [OrgRelationship.CANDIDATE_FOR]: 'is a candidate for a role',\n [OrgRelationship.COLLABORATES_WITH]: 'collaborates with',\n [OrgRelationship.MENTORS]: 'mentors',\n [OrgRelationship.STAKEHOLDER_IN]: 'is a stakeholder in',\n}\n","/**\n * SubCortex Signal Types\n *\n * Signals represent emotional and rapport-related data that attach to\n * the knowledge they relate to. Unlike assertions, signals:\n * - Compound (never conflict)\n * - Decay over time (exponential, configurable half-life)\n * - Have trajectory (warming/cooling/stable/neutral)\n * - Can be resolved by interaction (not just time)\n *\n * Storage: Signals are assertions with `signal:{type}` predicates.\n * The consumer-facing API treats them as a separate entity.\n */\n\n// ─── Signal Types (Gated + Custom) ────────────────────\n\n/**\n * SYSTEM signal types — available for all tenants.\n * Tenant-specific types use `custom:{tenant}:{type}` convention.\n */\nexport const SYSTEM_SIGNAL_TYPES = [\n 'frustration',\n 'excitement',\n 'concern',\n 'satisfaction',\n 'confusion',\n 'gratitude',\n 'tension',\n 'sentiment',\n] as const\n\nexport type SystemSignalType = typeof SYSTEM_SIGNAL_TYPES[number]\n\n/** Any valid signal type — system or custom */\nexport type SignalType = SystemSignalType | `custom:${string}`\n\nexport function isValidSignalType(type: string): type is SignalType {\n if (SYSTEM_SIGNAL_TYPES.includes(type as SystemSignalType)) return true\n if (type.startsWith('custom:')) return true\n return false\n}\n\n// ─── Decay Configuration ──────────────────────────────\n\n/**\n * Per-type decay half-life in hours.\n * Tuned to match emotional persistence patterns:\n * - Fast decay: confusion (resolves or escalates quickly)\n * - Medium decay: excitement, frustration, tension\n * - Slow decay: concern (persists until addressed), satisfaction/gratitude (positive baseline)\n */\nexport const SIGNAL_DECAY_CONFIG: Record<string, number> = {\n confusion: 8,\n excitement: 16,\n frustration: 18,\n tension: 18,\n sentiment: 24,\n concern: 36,\n satisfaction: 48,\n gratitude: 48,\n _default: 24,\n}\n\nexport function getDecayHalfLife(signalType: string): number {\n return SIGNAL_DECAY_CONFIG[signalType] ?? SIGNAL_DECAY_CONFIG._default\n}\n\n// ─── Trajectory ───────────────────────────────────────\n\nexport type Trajectory = 'warming' | 'cooling' | 'stable' | 'neutral'\n\n// ─── Signal Entry ─────────────────────────────────────\n\n/** A single recorded signal */\nexport interface SignalEntry {\n /** Assertion ID backing this signal */\n id: string\n /** Signal type (e.g., 'frustration', 'excitement') */\n type: string\n /** Human-readable content */\n content: string\n /** Raw recorded intensity (0-1) */\n intensity: number\n /** Time-decayed intensity */\n decayedIntensity: number\n /** Age in hours since recorded */\n ageHours: number\n /** Subject this signal is about (e.g., 'context:hiring', 'person:sarah') */\n aboutSubject?: string\n /** If this signal was resolved by another signal */\n resolvedBy?: string\n /** ISO timestamp when recorded */\n timestamp: string\n}\n\n/** Aggregated snapshot of all signals for a subject */\nexport interface SignalSnapshot {\n /** All signal entries within the query window */\n signals: SignalEntry[]\n /** Overall rapport trajectory */\n trajectory: Trajectory\n /** Aggregate intensity across all active signals */\n aggregateIntensity: number\n}\n\n// ─── Signal Resolution Sets ──────────────────────────\n\n/**\n * Signal types that indicate a positive emotional shift.\n * When recorded with `resolveConflicting: true`, these automatically\n * resolve recent negative signals on the same subject.\n */\nexport const POSITIVE_SIGNALS = new Set<string>([\n 'satisfaction',\n 'excitement',\n 'gratitude',\n])\n\n/**\n * Signal types that indicate a negative emotional state.\n * These are candidates for resolution by a subsequent positive signal.\n */\nexport const NEGATIVE_SIGNALS = new Set<string>([\n 'frustration',\n 'concern',\n 'tension',\n 'confusion',\n])\n\n// ─── Input/Output Types ───────────────────────────────\n\nexport interface RecordSignalInput {\n /** User ID the signal is about */\n userId: string\n /** Signal type */\n type: SignalType\n /** Human-readable description */\n content: string\n /** Intensity 0-1 (default: 0.7) */\n intensity?: number\n /** Subject this signal relates to (e.g., a project, person, topic) */\n aboutSubject?: string\n /** Session ID for contextual binding */\n sessionId?: string\n /**\n * When true and the signal type is a positive signal (satisfaction, excitement, gratitude),\n * automatically resolves recent negative signals on the same subject within the last 72 hours.\n * Resolved signals decay 4x faster. Default: false.\n */\n resolveConflicting?: boolean\n}\n\nexport interface SignalQueryOptions {\n /** Window in hours to look back (default: 72) */\n windowHours?: number\n /** Filter to specific signal type */\n type?: string\n}\n\nexport interface ResolveSignalInput {\n /** ID of the signal being resolved */\n signalId: string\n /** ID of the signal that resolves it */\n resolvedBySignalId: string\n}\n","/**\n * SubCortex Signals Namespace\n *\n * Records and queries emotional/rapport signals. Signals attach to\n * the knowledge they relate to and provide temporal decay + trajectory.\n *\n * Signals are stored as assertions with `signal:{type}` predicates.\n * The consumer sees them as a separate entity via this namespace.\n */\n\nimport type { HttpTransport } from './http'\nimport type { Assertion } from './client'\nimport type {\n SignalEntry,\n SignalSnapshot,\n RecordSignalInput,\n SignalQueryOptions,\n ResolveSignalInput,\n Trajectory,\n} from './types/signals'\nimport {\n isValidSignalType,\n getDecayHalfLife,\n SYSTEM_SIGNAL_TYPES,\n POSITIVE_SIGNALS,\n NEGATIVE_SIGNALS,\n} from './types/signals'\nimport { SubjectPrefix, subject } from './types/schema'\n\n/** Shape returned by the engine's GET /api/v1/signals/:tenant/:subject */\ninterface EngineSignalQueryResponse {\n signals: Array<{\n assertion_id: string\n signal_type: string\n content: string\n intensity: number\n decayed_intensity: number\n age_hours: number\n about_subject: string | null\n resolved_by: string | null\n timestamp: string\n }>\n trajectory: string\n aggregate_intensity: number\n}\n\n/** Predicates from legacy rapport recording (pre-signal: namespace) */\nconst LEGACY_SIGNAL_PREDICATES = new Set([\n 'sentiment', 'frustration', 'excitement', 'concern',\n 'goal', 'aspiration', 'preference', 'interest',\n])\n\nexport class SignalsNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /**\n * Record an emotional signal about a user.\n *\n * @example\n * ```typescript\n * await brain.signals.record({\n * userId: 'cmk123',\n * type: 'frustration',\n * content: 'Frustrated about the hiring timeline',\n * intensity: 0.85,\n * aboutSubject: 'context:hiring-ea',\n * })\n * ```\n */\n async record(input: RecordSignalInput): Promise<{ id: string; resolved?: number }> {\n if (!isValidSignalType(input.type)) {\n throw new Error(`Invalid signal type: ${input.type}. Use one of: ${SYSTEM_SIGNAL_TYPES.join(', ')} or custom:{tenant}:{type}`)\n }\n\n const userSubject = subject(SubjectPrefix.USER, input.userId)\n const predicate = `signal:${input.type}`\n const value = {\n content: input.content,\n intensity: input.intensity ?? 0.7,\n about_subject: input.aboutSubject || null,\n }\n\n const result = await this.http.post<Assertion>('/api/v1/assertions', {\n tenant_id: this.tenantId,\n subject: userSubject,\n predicate,\n value,\n confidence: input.intensity ?? 0.7,\n ...(input.sessionId ? { session_id: input.sessionId } : {}),\n })\n\n // Auto-resolve negative signals when a positive signal is recorded\n let resolved = 0\n if (input.resolveConflicting && POSITIVE_SIGNALS.has(input.type)) {\n try {\n const snapshot = await this.query(userSubject, { windowHours: 72 })\n for (const sig of snapshot.signals) {\n if (!NEGATIVE_SIGNALS.has(sig.type)) continue\n if (sig.resolvedBy) continue\n const sameContext = input.aboutSubject\n ? sig.aboutSubject === input.aboutSubject\n : !sig.aboutSubject\n if (sameContext) {\n await this.resolve({ signalId: sig.id, resolvedBySignalId: result.id })\n resolved++\n }\n }\n } catch {\n // Non-critical — signal was recorded successfully\n }\n }\n\n return { id: result.id, ...(resolved > 0 && { resolved }) }\n }\n\n /**\n * Query signals for a user with computed decay and trajectory.\n * Delegates to the engine's signal query endpoint for server-side computation.\n *\n * @example\n * ```typescript\n * const snapshot = await brain.signals.query('user:cmk123', {\n * windowHours: 72,\n * type: 'frustration',\n * })\n * ```\n */\n async query(userSubject: string, options: SignalQueryOptions = {}): Promise<SignalSnapshot> {\n const windowHours = options.windowHours ?? 72\n\n const query: Record<string, string> = { window: String(windowHours) }\n if (options.type) query.type = options.type\n\n const qs = new URLSearchParams(query).toString()\n const response = await this.http.get<EngineSignalQueryResponse>(\n `/api/v1/signals/${enc(this.tenantId)}/${enc(userSubject)}?${qs}`\n )\n\n const signals: SignalEntry[] = response.signals.map(s => ({\n id: s.assertion_id,\n type: s.signal_type,\n content: s.content,\n intensity: s.intensity,\n decayedIntensity: s.decayed_intensity,\n ageHours: Math.round(s.age_hours * 10) / 10,\n aboutSubject: s.about_subject || undefined,\n resolvedBy: s.resolved_by || undefined,\n timestamp: s.timestamp,\n }))\n\n return {\n signals,\n trajectory: response.trajectory as Trajectory,\n aggregateIntensity: response.aggregate_intensity,\n }\n }\n\n /**\n * Resolve a signal — mark it as resolved by a subsequent positive interaction.\n * The resolved signal's effective intensity drops faster.\n *\n * @example\n * ```typescript\n * await brain.signals.resolve({\n * signalId: 'abc123',\n * resolvedBySignalId: 'def456',\n * })\n * ```\n */\n async resolve(input: ResolveSignalInput): Promise<{ success: boolean }> {\n // Supersede the original assertion with an updated value that includes resolved_by\n const original = await this.http.get<Assertion>(\n `/api/v1/assertions/${enc(this.tenantId)}/${enc(input.signalId)}`\n ).catch(() => null)\n\n if (!original) return { success: false }\n\n const value = typeof original.value === 'object' && original.value !== null\n ? { ...(original.value as Record<string, unknown>), resolved_by: input.resolvedBySignalId }\n : { content: String(original.value), resolved_by: input.resolvedBySignalId }\n\n await this.http.post('/api/v1/assertions/supersede', {\n tenant_id: this.tenantId,\n original_assertion_id: input.signalId,\n subject: original.subject,\n predicate: original.predicate,\n value,\n confidence: original.confidence,\n })\n\n return { success: true }\n }\n}\n\n// ─── Pure Computation Functions ───────────────────────\n// @internal — computeDecay is still needed by extractSignals() for users.identify(),\n// which builds signal entries from raw assertions. Trajectory computation has been\n// moved to the engine (SignalIndex::compute_trajectory in cortex-storage).\n\n/**\n * Exponential decay: intensity × 2^(-age / halfLife)\n * Resolved signals decay 4x faster.\n */\nexport function computeDecay(\n intensity: number,\n ageHours: number,\n halfLifeHours: number,\n isResolved: boolean = false\n): number {\n const effectiveHalfLife = isResolved ? halfLifeHours / 4 : halfLifeHours\n const decayed = intensity * Math.pow(2, -ageHours / effectiveHalfLife)\n return Math.round(decayed * 100) / 100\n}\n\n// ─── Helpers ──────────────────────────────────────────\n\n/**\n * Extract signal entries from a list of assertions.\n * Used by users.identify() to populate the signals field.\n */\nexport function extractSignals(\n assertions: Assertion[],\n windowHours: number = 72\n): SignalEntry[] {\n const now = Date.now()\n const windowMs = windowHours * 60 * 60 * 1000\n const entries: SignalEntry[] = []\n\n for (const a of assertions) {\n if (a.isSuperseded) continue\n const isSignal = a.predicate.startsWith('signal:')\n const isLegacy = LEGACY_SIGNAL_PREDICATES.has(a.predicate)\n if (!isSignal && !isLegacy) continue\n\n const timestamp = a.validFrom\n const ageMs = now - new Date(timestamp).getTime()\n if (ageMs > windowMs) continue\n\n const ageHours = ageMs / (60 * 60 * 1000)\n const type = isSignal ? a.predicate.slice(7) : a.predicate\n const halfLife = getDecayHalfLife(type)\n\n let content = ''\n let intensity = a.confidence ?? 0.7\n let aboutSubject: string | undefined\n let resolvedBy: string | undefined\n\n if (typeof a.value === 'object' && a.value !== null) {\n const v = a.value as Record<string, unknown>\n content = (v.content as string) || ''\n intensity = (v.intensity as number) ?? intensity\n aboutSubject = (v.about_subject as string) || undefined\n resolvedBy = (v.resolved_by as string) || undefined\n } else {\n content = String(a.value)\n }\n\n entries.push({\n id: a.id,\n type,\n content,\n intensity,\n decayedIntensity: computeDecay(intensity, ageHours, halfLife, !!resolvedBy),\n ageHours: Math.round(ageHours * 10) / 10,\n aboutSubject,\n resolvedBy,\n timestamp,\n })\n }\n\n entries.sort((a, b) => a.ageHours - b.ageHours)\n return entries\n}\n\nfunction enc(s: string): string {\n return encodeURIComponent(s)\n}\n","/**\n * SubCortex Users Namespace\n *\n * High-level operations for user rapport building.\n * This is where orchestration logic lives — NOT in the consumer's proxy.\n *\n * The consumer agent calls brain.users.identify() and gets back\n * a complete picture. One call, one round-trip, full context.\n */\n\nimport type { HttpTransport } from './http'\nimport type { Assertion, IntakeResult } from './client'\nimport type {\n IdentifyUserInput,\n UserIdentification,\n UserMemory,\n ConnectedPerson,\n ConflictItem,\n RegisterPersonInput,\n RegisterPersonResult,\n RecordRapportInput,\n} from './types/users'\nimport {\n SubjectPrefix,\n subject,\n confidenceToScore,\n ConfidenceLevel,\n REVERSE_RELATIONSHIPS,\n OrgRelationship,\n} from './types/schema'\nimport type { Trajectory } from './types/signals'\nimport { extractSignals } from './signals'\n\nexport class UsersNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /**\n * Identify a user and retrieve their full context.\n *\n * This is the FIRST thing an agent should call at session start.\n * Returns whether the user is known, their memories, connected\n * people, reminders, conflicts, and a summary.\n *\n * @example\n * ```typescript\n * const user = await brain.users.identify({\n * userId: 'cmk123...',\n * displayName: 'Tom Santos',\n * })\n *\n * if (!user.isKnown) {\n * // First encounter — get to know them\n * } else {\n * // Returning user — reference what you know\n * // user.reminders — bring these up\n * // user.conflicts — address these\n * // user.connectedPeople — context about their org\n * }\n * ```\n */\n async identify(input: IdentifyUserInput): Promise<UserIdentification> {\n const userSubject = subject(SubjectPrefix.USER, input.userId)\n\n // 1. Get all assertions about this user\n const assertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(this.tenantId)}/${enc(userSubject)}`\n )\n\n const active = assertions.filter(a => !a.isSuperseded)\n const isKnown = active.length > 0\n\n // 2. Seed display name if first encounter\n if (input.displayName && !active.some(a => a.predicate === 'name' || a.predicate === 'full_name')) {\n try {\n await this.http.post('/api/v1/assertions', {\n tenant_id: this.tenantId,\n subject: userSubject,\n predicate: 'name',\n value: input.displayName,\n confidence: 1.0,\n })\n } catch { /* best-effort */ }\n }\n\n // 3. Get user's name\n const nameAssertion = active.find(a => a.predicate === 'name' || a.predicate === 'full_name')\n const name = (nameAssertion?.value as string) || input.displayName || null\n\n // 4. Categorize assertions\n const reminders: UserMemory[] = active\n .filter(a => a.predicate === 'reminder')\n .map(a => ({ id: a.id, predicate: a.predicate, value: a.value, confidence: a.confidence, createdAt: a.validFrom }))\n\n // Auto-dismiss reminders after returning them.\n // Once surfaced, they shouldn't repeat. If the user wants to\n // keep a reminder alive, they'll say so and the agent will recreate it.\n for (const reminder of reminders) {\n try {\n await this.http.post(\n `/api/v1/assertions/retract/${enc(this.tenantId)}/${enc(reminder.id)}`,\n {}\n )\n } catch { /* best-effort — don't block recall if retract fails */ }\n }\n\n const contexts: UserMemory[] = active\n .filter(a => a.predicate === 'context' || a.predicate === 'context:task')\n .map(a => ({ id: a.id, predicate: a.predicate, value: a.value, confidence: a.confidence, createdAt: a.validFrom }))\n\n // 5a. Extract signals (signal:* predicates + legacy rapport predicates)\n const signals = extractSignals(assertions)\n const signalIds = new Set(signals.map(s => s.id))\n\n // Get trajectory from the engine (server-side computation)\n let rapportTrajectory: Trajectory = 'neutral'\n try {\n const qs = new URLSearchParams({ window: '72' }).toString()\n const snapshot = await this.http.get<{ trajectory: Trajectory }>(\n `/api/v1/signals/${enc(this.tenantId)}/${enc(userSubject)}?${qs}`\n )\n rapportTrajectory = snapshot.trajectory\n } catch { /* Non-critical — default to neutral */ }\n\n const memories: UserMemory[] = active\n .filter(a =>\n a.predicate !== 'reminder' &&\n a.predicate !== 'context' &&\n a.predicate !== 'context:task' &&\n !signalIds.has(a.id) // exclude signals from memories\n )\n .map(a => ({ id: a.id, predicate: a.predicate, value: a.value, confidence: a.confidence, createdAt: a.validFrom }))\n\n // 5. Traverse relationships to find connected people\n const connectedPeople: ConnectedPerson[] = []\n try {\n const relationships = await this.http.get<Array<{\n fromSubject: string; toSubject: string; relationshipType: string\n }>>(`/api/v1/relationships/${enc(this.tenantId)}/${enc(userSubject)}`)\n\n const visited = new Set<string>()\n for (const rel of relationships) {\n const other = rel.fromSubject === userSubject ? rel.toSubject : rel.fromSubject\n if (!other || other === userSubject || visited.has(other)) continue\n visited.add(other)\n\n const personAssertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(this.tenantId)}/${enc(other)}`\n )\n const personActive = personAssertions.filter(a => !a.isSuperseded)\n const personName = personActive.find(a => a.predicate === 'name')\n const facts = personActive\n .filter(a => a.predicate !== 'name')\n .map(a => ({ predicate: a.predicate, value: a.value }))\n\n connectedPeople.push({\n subject: other,\n name: (personName?.value as string) || other,\n relationship: rel.relationshipType,\n facts,\n })\n }\n } catch { /* non-critical */ }\n\n // 6. Check Thalamus queue for conflicts relevant to THIS user\n const conflicts: ConflictItem[] = []\n try {\n if (!input.agentId) throw new Error('agentId is required on IdentifyUserInput to fetch conflicts')\n const pending = await this.http.get<Array<{\n id: string; surfacingHint: string; acknowledged: boolean; status: string;\n persistedAssertionIds?: string[]; conflictingAssertionId?: string\n }>>(`/api/v1/intake/pending/${enc(input.agentId)}?status=conflict_detected`)\n\n for (const item of pending) {\n if (item.acknowledged) continue\n\n // Only surface conflicts that mention this user's subject\n const hint = item.surfacingHint || ''\n const involvesUser = hint.includes(userSubject)\n || (item.persistedAssertionIds || []).some(id => {\n // Check if any persisted assertion is about this user\n const a = assertions.find(a2 => a2.id === id)\n return a?.subject === userSubject\n })\n\n if (!involvesUser) continue\n\n let resolvedHint = hint || 'A conflict was detected.'\n if (name) {\n resolvedHint = resolvedHint.replace(\n new RegExp(userSubject.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'g'),\n name\n )\n }\n conflicts.push({ id: item.id, hint: resolvedHint })\n }\n } catch { /* non-critical */ }\n\n // 7. Build summary\n const parts: string[] = []\n if (conflicts.length > 0) {\n parts.push(`ATTENTION: ${conflicts.length} knowledge conflict(s) — MUST address: ${conflicts.map(c => c.hint).join(' | ')}`)\n }\n if (reminders.length > 0) {\n parts.push(`REMINDERS (${reminders.length}): ${reminders.map(r => `\"${r.value}\"`).join(', ')}. Dismiss each after surfacing.`)\n }\n if (connectedPeople.length > 0) {\n parts.push(`Connected people:\\n${connectedPeople.map(p => {\n const factsStr = p.facts.map(f => `${f.predicate}: ${f.value}`).join(', ')\n return `- ${p.name} (${p.relationship})${factsStr ? ': ' + factsStr : ''}`\n }).join('\\n')}`)\n }\n if (memories.length > 0 && parts.length === 0) {\n parts.push(`You know ${memories.length} things about this user.`)\n }\n if (parts.length === 0) {\n parts.push('This is a new user — no memories yet. Get to know them.')\n }\n\n return {\n subject: userSubject,\n isKnown,\n name,\n memories,\n connectedPeople,\n reminders,\n contexts,\n conflicts,\n signals,\n rapportTrajectory,\n summary: parts.join('\\n'),\n }\n }\n\n /**\n * Register a person that the user mentioned.\n *\n * Creates the person node, their role, and bidirectional\n * relationships to the user. One call does everything.\n *\n * @example\n * ```typescript\n * const result = await brain.users.registerPerson({\n * name: 'John Smith',\n * userId: 'cmk123...',\n * relationship: 'direct_report',\n * role: 'VP of Engineering',\n * })\n * ```\n */\n async registerPerson(input: RegisterPersonInput): Promise<RegisterPersonResult> {\n const userSubject = subject(SubjectPrefix.USER, input.userId)\n const personSubject = subject(SubjectPrefix.PERSON, input.name)\n const conf = typeof input.confidence === 'number'\n ? input.confidence\n : confidenceToScore(input.confidence || ConfidenceLevel.CONFIRMED)\n\n let assertionsCreated = 0\n let relationshipsCreated = 0\n const warnings: string[] = []\n\n // Route ALL assertions through Thalamus for conflict detection, dedup, and signal classification\n const candidates: Array<{\n subject: string; predicate: string; value: unknown;\n source_confidence: number; provenance: string\n }> = []\n\n // Person identity\n candidates.push({ subject: personSubject, predicate: 'name', value: input.name, source_confidence: conf, provenance: 'agent' })\n\n // Role\n if (input.role) {\n candidates.push({ subject: personSubject, predicate: 'role', value: input.role, source_confidence: conf, provenance: 'agent' })\n\n // Check if someone else holds this role (warning only, Thalamus handles conflicts)\n try {\n const allAssertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/list/${enc(this.tenantId)}`\n )\n const sameRole = allAssertions.filter(a =>\n a.subject.startsWith('person:') &&\n a.subject !== personSubject &&\n a.predicate === 'role' &&\n a.value === input.role &&\n !a.isSuperseded\n )\n if (sameRole.length > 0) {\n const otherAssertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(this.tenantId)}/${enc(sameRole[0].subject)}`\n )\n const otherName = otherAssertions.find(a => a.predicate === 'name')?.value || sameRole[0].subject\n warnings.push(`\"${input.role}\" is already held by ${otherName}. Is ${otherName} no longer in this role?`)\n }\n } catch { /* non-critical */ }\n }\n\n // Details\n if (input.details) {\n candidates.push({ subject: personSubject, predicate: 'details', value: input.details, source_confidence: conf, provenance: 'agent' })\n }\n\n // Status\n candidates.push({\n subject: personSubject, predicate: 'status',\n value: input.relationship === 'candidate' ? 'candidate' : 'active',\n source_confidence: conf, provenance: 'agent',\n })\n\n // Submit through Thalamus\n const correlationId = `register_person_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`\n const intakeResult = await this.http.post<IntakeResult>('/api/v1/intake/submit', {\n correlation_id: correlationId,\n agent_id: 'sdk',\n tenant_id: this.tenantId,\n candidates,\n context: input.sessionId ? { sessionId: input.sessionId } : undefined,\n })\n\n assertionsCreated = intakeResult.accepted + intakeResult.reinforced\n if (intakeResult.conflicts > 0) {\n const conflictItems = (intakeResult.items || []).filter(\n (i: { status: string }) => i.status === 'conflict_detected'\n )\n for (const item of conflictItems) {\n warnings.push(item.surfacingHint || 'A conflict was detected with existing data.')\n }\n }\n\n // Relationships still go direct (they don't have conflict semantics)\n if (input.role) {\n const roleSubject = subject(SubjectPrefix.ROLE, input.role)\n // Role node + holds_role relationship\n await this.http.post('/api/v1/assertions', {\n tenant_id: this.tenantId, subject: roleSubject, predicate: 'name', value: input.role, confidence: conf,\n })\n await this.http.post('/api/v1/relationships', {\n tenant_id: this.tenantId, from_subject: personSubject, to_subject: roleSubject,\n relationship_type: OrgRelationship.HOLDS_ROLE, confidence: conf,\n })\n relationshipsCreated++\n }\n\n // Normalize relationship types\n const FORWARD_MAP: Record<string, string> = {\n 'direct_report': OrgRelationship.MANAGES,\n 'team_member': OrgRelationship.HAS_MEMBER,\n 'candidate': OrgRelationship.MANAGES,\n 'manager': OrgRelationship.REPORTS_TO,\n 'stakeholder': OrgRelationship.STAKEHOLDER_IN,\n 'collaborator': OrgRelationship.COLLABORATES_WITH,\n 'mentor': OrgRelationship.MENTORS,\n }\n\n const forwardType = FORWARD_MAP[input.relationship] || input.relationship\n const reverseType = REVERSE_RELATIONSHIPS[input.relationship] || REVERSE_RELATIONSHIPS[forwardType] || input.relationship\n\n // User → Person\n await this.http.post('/api/v1/relationships', {\n tenant_id: this.tenantId, from_subject: userSubject, to_subject: personSubject,\n relationship_type: forwardType, confidence: conf,\n })\n relationshipsCreated++\n\n // Person → User (reverse)\n await this.http.post('/api/v1/relationships', {\n tenant_id: this.tenantId, from_subject: personSubject, to_subject: userSubject,\n relationship_type: reverseType, confidence: conf,\n })\n relationshipsCreated++\n\n return { personSubject, assertionsCreated, relationshipsCreated, warnings }\n }\n\n /**\n * Record an emotional state or rapport signal about the user.\n *\n * @example\n * ```typescript\n * await brain.users.recordRapport({\n * userId: 'cmk123...',\n * type: 'frustration',\n * value: 'Frustrated about losing the EA candidate',\n * aboutPerson: 'Sarah Johnson',\n * })\n * ```\n */\n async recordRapport(input: RecordRapportInput): Promise<{ success: boolean }> {\n const userSubject = subject(SubjectPrefix.USER, input.userId)\n const conf = typeof input.confidence === 'number'\n ? input.confidence\n : confidenceToScore(input.confidence || ConfidenceLevel.HIGH)\n\n // Route through Thalamus for conflict detection and signal classification\n const candidates: Array<{\n subject: string; predicate: string; value: unknown;\n source_confidence: number; provenance: string\n }> = [\n { subject: userSubject, predicate: input.type, value: input.value, source_confidence: conf, provenance: 'agent' },\n ]\n\n // If about a specific person, add a timeline entry candidate\n if (input.aboutPerson) {\n const personSubject = subject(SubjectPrefix.PERSON, input.aboutPerson)\n candidates.push({\n subject: personSubject, predicate: 'timeline', value: input.value,\n source_confidence: conf, provenance: 'agent',\n })\n }\n\n const correlationId = `rapport_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`\n await this.http.post<IntakeResult>('/api/v1/intake/submit', {\n correlation_id: correlationId,\n agent_id: 'sdk',\n tenant_id: this.tenantId,\n candidates,\n ...(input.sessionId ? { context: { sessionId: input.sessionId } } : {}),\n })\n\n return { success: true }\n }\n\n /**\n * Dismiss a reminder after the agent has surfaced it.\n */\n async dismissReminder(userId: string, reminderContent: string): Promise<{ success: boolean }> {\n const userSubject = subject(SubjectPrefix.USER, userId)\n const assertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(this.tenantId)}/${enc(userSubject)}`\n )\n\n const reminder = assertions.find(\n a => a.predicate === 'reminder' && !a.isSuperseded &&\n (a.value as string).toLowerCase().includes(reminderContent.toLowerCase())\n )\n\n if (reminder) {\n await this.http.post(`/api/v1/assertions/retract/${enc(this.tenantId)}/${enc(reminder.id)}`, {})\n return { success: true }\n }\n return { success: false }\n }\n}\n\nfunction enc(s: string): string {\n return encodeURIComponent(s)\n}\n","/**\n * Rule types — typed code guardrails stored as assertions.\n *\n * Rules are assertions with structured predicates (`rule:banned_pattern`,\n * `rule:required_pattern`, etc.) and typed values. The engine stores them\n * identically to any other assertion — same WAL, same content-addressable IDs,\n * same temporal model, same supersession chain.\n *\n * The RulesNamespace provides typed CRUD and file-scope matching on top of\n * the raw assertion layer, so consumers don't parse JSON blobs in hooks.\n */\n\n// ─── Rule Types ─────────────────────────────────────\n\n/** The kind of enforcement a rule performs. */\nexport type RuleType =\n | 'banned_pattern' // Regex that must NOT appear in matching files\n | 'required_pattern' // Regex that MUST appear in matching files\n | 'file_constraint' // Constraint on a specific file or path\n | 'requires_propagation' // A change in scope X must propagate to Y\n\n/** How the system responds to a violation. */\nexport type RuleSeverity =\n | 'block' // Exit code 2 — tool call blocked, Claude retries\n | 'warn' // Injected as strong guidance, not enforced\n | 'info' // Contextual — available for recall, not proactively injected\n\n/** Well-known rule predicates. Scoped under `rule:` to avoid collision with general assertions. */\nexport const RulePredicates = {\n BANNED_PATTERN: 'rule:banned_pattern',\n REQUIRED_PATTERN: 'rule:required_pattern',\n FILE_CONSTRAINT: 'rule:file_constraint',\n REQUIRES_PROPAGATION: 'rule:requires_propagation',\n} as const\n\nexport type RulePredicate = typeof RulePredicates[keyof typeof RulePredicates]\n\n// ─── Rule Value (structured, not a JSON blob) ──────\n\n/** The typed structure stored in the assertion value field. */\nexport interface RuleValue {\n /** Regex pattern to match against file content (banned/required pattern rules). */\n pattern?: string\n /** Glob or regex for which files this rule applies to. If omitted, applies to all files. */\n fileScope?: string\n /** Human-readable description of what this rule enforces and why. */\n description: string\n /** What surfaces must be updated when this rule's scope is changed (propagation rules). */\n propagatesTo?: string[]\n}\n\n// ─── Rule (parsed assertion) ────────────────────────\n\n/** A rule — a typed, parsed view of an enforcement assertion. */\nexport interface Rule {\n /** Assertion ID (content-addressable BLAKE3 hash) */\n id: string\n /** Tenant this rule belongs to */\n tenantId: string\n /** Subject scope — e.g. `project:{id}`, `intent:api`, `file:prisma/schema.prisma` */\n subject: string\n /** Rule type — which enforcement behavior this rule triggers */\n type: RuleType\n /** The full typed predicate, e.g. `rule:banned_pattern` */\n predicate: RulePredicate\n /** Structured rule configuration */\n value: RuleValue\n /** Severity — block (enforcement), warn (guidance), info (context) */\n severity: RuleSeverity\n /** Confidence score from the underlying assertion */\n confidence: number\n /** When this rule became active */\n validFrom: string\n /** Whether this rule has been superseded by a newer version */\n isSuperseded: boolean\n}\n\n// ─── Input Types ────────────────────────────────────\n\n/** Input for creating a rule. */\nexport interface CreateRuleInput {\n /** Subject scope — e.g. `project:{id}`, `intent:api`, `file:src/db/schema.ts` */\n subject: string\n /** Rule type */\n type: RuleType\n /** Regex pattern (for banned_pattern and required_pattern) */\n pattern?: string\n /** File scope glob/regex — which files this rule applies to */\n fileScope?: string\n /** Human-readable description of the rule and its rationale */\n description: string\n /** Surfaces that must be updated (for requires_propagation rules) */\n propagatesTo?: string[]\n /** Severity — defaults to 'block' for confidence 1.0, 'warn' for >= 0.7, 'info' otherwise */\n severity?: RuleSeverity\n /** Confidence — defaults to 1.0 (enforcement). Set lower for guidance/context. */\n confidence?: number\n /** Override tenant ID */\n tenantId?: string\n}\n\n/** Input for updating (superseding) a rule. */\nexport interface UpdateRuleInput {\n /** ID of the rule to supersede */\n ruleId: string\n /** Updated fields (only provided fields change; others carry forward) */\n pattern?: string\n fileScope?: string\n description?: string\n propagatesTo?: string[]\n severity?: RuleSeverity\n confidence?: number\n /** Override tenant ID */\n tenantId?: string\n}\n\n/** Options for querying rules. */\nexport interface RuleQueryOptions {\n /** Filter by rule type */\n type?: RuleType\n /** Filter by severity */\n severity?: RuleSeverity\n /** Include superseded rules in results (default: false) */\n includeSuperseded?: boolean\n /** Override tenant ID */\n tenantId?: string\n}\n","/**\n * RulesNamespace — typed code guardrails stored as assertions.\n *\n * Rules are assertions with `rule:*` predicates and structured values.\n * This namespace provides typed CRUD, file-scope matching, and intent-based\n * queries so consumers work with `Rule` objects instead of raw assertions\n * with JSON blobs stuffed into the value field.\n *\n * @example\n * ```typescript\n * // Create a rule\n * const rule = await subcortex.rules.create({\n * subject: 'intent:api',\n * type: 'banned_pattern',\n * pattern: 'NextResponse\\\\.json\\\\(',\n * fileScope: 'app/api/.*\\\\.ts$',\n * description: 'Use apiSuccess() instead of NextResponse.json()',\n * })\n *\n * // Get all rules that apply to a file\n * const rules = await subcortex.rules.forFile('app/api/users/route.ts')\n *\n * // Get enforcement rules only\n * const enforcement = await subcortex.rules.list({ severity: 'block' })\n * ```\n */\n\nimport type { HttpTransport } from './http'\nimport type { Assertion } from './client'\nimport {\n RulePredicates,\n type Rule,\n type RuleType,\n type RuleValue,\n type RuleSeverity,\n type RulePredicate,\n type CreateRuleInput,\n type UpdateRuleInput,\n type RuleQueryOptions,\n} from './types/rules'\n\nconst RULE_PREDICATE_PREFIX = 'rule:'\n\n/** Maps RuleType → full predicate string */\nconst TYPE_TO_PREDICATE: Record<RuleType, RulePredicate> = {\n banned_pattern: RulePredicates.BANNED_PATTERN,\n required_pattern: RulePredicates.REQUIRED_PATTERN,\n file_constraint: RulePredicates.FILE_CONSTRAINT,\n requires_propagation: RulePredicates.REQUIRES_PROPAGATION,\n}\n\n/** Maps confidence → default severity */\nfunction defaultSeverity(confidence: number): RuleSeverity {\n if (confidence >= 1.0) return 'block'\n if (confidence >= 0.7) return 'warn'\n return 'info'\n}\n\nexport class RulesNamespace {\n private http: HttpTransport\n private tenantId: string\n\n constructor(http: HttpTransport, tenantId: string) {\n this.http = http\n this.tenantId = tenantId\n }\n\n /**\n * Create a new rule.\n *\n * Stores an assertion with a `rule:*` predicate and a typed value.\n * Defaults to confidence 1.0 (enforcement) if not specified.\n *\n * @example\n * ```typescript\n * await subcortex.rules.create({\n * subject: 'project:my-project',\n * type: 'banned_pattern',\n * pattern: 'as any',\n * description: 'No any casts — use proper types',\n * })\n * ```\n */\n async create(input: CreateRuleInput): Promise<Rule> {\n const confidence = input.confidence ?? 1.0\n const severity = input.severity ?? defaultSeverity(confidence)\n\n const ruleValue: RuleValue = {\n description: input.description,\n pattern: input.pattern,\n fileScope: input.fileScope,\n propagatesTo: input.propagatesTo,\n }\n\n const assertion = await this.http.post<Assertion>(\n `/api/v1/assertions`,\n {\n subject: input.subject,\n predicate: TYPE_TO_PREDICATE[input.type],\n value: { ...ruleValue, severity },\n confidence,\n tenant_id: input.tenantId ?? this.tenantId,\n },\n input.tenantId ?? this.tenantId,\n )\n\n return parseRule(assertion)\n }\n\n /**\n * Get a rule by its assertion ID.\n */\n async get(ruleId: string, options?: { tenantId?: string }): Promise<Rule> {\n const tenant = options?.tenantId ?? this.tenantId\n const assertion = await this.http.get<Assertion>(\n `/api/v1/assertions/${enc(tenant)}/${enc(ruleId)}`,\n )\n return parseRule(assertion)\n }\n\n /**\n * List all rules for this project, optionally filtered by type or severity.\n */\n async list(options?: RuleQueryOptions): Promise<Rule[]> {\n const tenant = options?.tenantId ?? this.tenantId\n const assertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/list/${enc(tenant)}`,\n )\n\n return assertions\n .filter((a) => isRuleAssertion(a))\n .filter((a) => options?.includeSuperseded || !a.isSuperseded)\n .map(parseRule)\n .filter((r) => !options?.type || r.type === options.type)\n .filter((r) => !options?.severity || r.severity === options.severity)\n }\n\n /**\n * Get all rules whose fileScope matches the given file path.\n *\n * This is the primary query for the PreToolUse hook — \"what rules apply\n * to the file I'm about to modify?\"\n *\n * @example\n * ```typescript\n * const rules = await subcortex.rules.forFile('app/api/users/route.ts')\n * // Returns banned_pattern and required_pattern rules whose fileScope\n * // matches the path, plus any project-wide rules without a fileScope.\n * ```\n */\n async forFile(filePath: string, options?: RuleQueryOptions): Promise<Rule[]> {\n const allRules = await this.list(options)\n\n return allRules.filter((rule) => {\n // Rules with no fileScope apply to all files\n if (!rule.value.fileScope) return true\n\n // Match fileScope as regex against the file path\n try {\n const regex = new RegExp(rule.value.fileScope)\n return regex.test(filePath)\n } catch {\n // Invalid regex — skip this rule\n return false\n }\n })\n }\n\n /**\n * Get all rules scoped to a specific intent subject.\n *\n * @example\n * ```typescript\n * const apiRules = await subcortex.rules.forIntent('api')\n * // Queries subject \"intent:api\" for all rule assertions\n * ```\n */\n async forIntent(intent: string, options?: RuleQueryOptions): Promise<Rule[]> {\n const tenant = options?.tenantId ?? this.tenantId\n const subject = intent.startsWith('intent:') ? intent : `intent:${intent}`\n\n const assertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(tenant)}/${enc(subject)}`,\n )\n\n return assertions\n .filter((a) => isRuleAssertion(a))\n .filter((a) => options?.includeSuperseded || !a.isSuperseded)\n .map(parseRule)\n .filter((r) => !options?.type || r.type === options.type)\n .filter((r) => !options?.severity || r.severity === options.severity)\n }\n\n /**\n * Get all rules scoped to a specific subject (project, file, intent, etc.).\n */\n async forSubject(subject: string, options?: RuleQueryOptions): Promise<Rule[]> {\n const tenant = options?.tenantId ?? this.tenantId\n\n const assertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(tenant)}/${enc(subject)}`,\n )\n\n return assertions\n .filter((a) => isRuleAssertion(a))\n .filter((a) => options?.includeSuperseded || !a.isSuperseded)\n .map(parseRule)\n .filter((r) => !options?.type || r.type === options.type)\n .filter((r) => !options?.severity || r.severity === options.severity)\n }\n\n /**\n * Update a rule by superseding it.\n *\n * The old rule is marked as superseded, a new one is created.\n * Full assertion history is preserved.\n */\n async update(input: UpdateRuleInput): Promise<Rule> {\n const tenant = input.tenantId ?? this.tenantId\n\n // Fetch the existing rule to carry forward unchanged fields\n const existing = await this.get(input.ruleId, { tenantId: tenant })\n\n const confidence = input.confidence ?? existing.confidence\n const severity = input.severity ?? existing.severity\n\n const ruleValue: RuleValue = {\n description: input.description ?? existing.value.description,\n pattern: input.pattern ?? existing.value.pattern,\n fileScope: input.fileScope ?? existing.value.fileScope,\n propagatesTo: input.propagatesTo ?? existing.value.propagatesTo,\n }\n\n const assertion = await this.http.post<Assertion>(\n `/api/v1/assertions/supersede`,\n {\n original_assertion_id: input.ruleId,\n subject: existing.subject,\n predicate: existing.predicate,\n value: { ...ruleValue, severity },\n confidence,\n tenant_id: tenant,\n },\n tenant,\n )\n\n return parseRule(assertion)\n }\n\n /**\n * Retract (deactivate) a rule.\n *\n * The assertion's temporal bounds are closed. The rule stops matching\n * in future queries but its history is preserved.\n */\n async retract(ruleId: string, options?: { tenantId?: string }): Promise<void> {\n const tenant = options?.tenantId ?? this.tenantId\n await this.http.post(\n `/api/v1/assertions/retract/${enc(tenant)}/${enc(ruleId)}`,\n {},\n tenant,\n )\n }\n}\n\n// ─── Helpers ────────────────────────────────────────\n\n/** Check if an assertion is a rule (has a `rule:*` predicate). */\nfunction isRuleAssertion(assertion: Assertion): boolean {\n return assertion.predicate?.startsWith(RULE_PREDICATE_PREFIX) ?? false\n}\n\n/** Parse an Assertion into a typed Rule. */\nfunction parseRule(assertion: Assertion): Rule {\n const predicate = assertion.predicate as RulePredicate\n const type = predicate.replace(RULE_PREDICATE_PREFIX, '') as RuleType\n\n // Parse the value — could be a structured object or a legacy JSON string\n let ruleValue: RuleValue\n let severity: RuleSeverity\n\n if (typeof assertion.value === 'object' && assertion.value !== null) {\n const val = assertion.value as Record<string, unknown>\n ruleValue = {\n description: String(val.description ?? ''),\n pattern: val.pattern != null ? String(val.pattern) : undefined,\n fileScope: val.fileScope != null ? String(val.fileScope) : undefined,\n propagatesTo: Array.isArray(val.propagatesTo) ? val.propagatesTo.map(String) : undefined,\n }\n severity = (val.severity as RuleSeverity) ?? defaultSeverity(assertion.confidence)\n } else if (typeof assertion.value === 'string') {\n // Legacy: value is a JSON string (old format) or plain text\n try {\n const parsed = JSON.parse(assertion.value) as Record<string, unknown>\n ruleValue = {\n description: String(parsed.description ?? ''),\n pattern: parsed.pattern != null ? String(parsed.pattern) : undefined,\n fileScope: parsed.filePattern != null ? String(parsed.filePattern) : undefined,\n propagatesTo: Array.isArray(parsed.propagatesTo) ? parsed.propagatesTo.map(String) : undefined,\n }\n severity = (parsed.severity as RuleSeverity) ?? defaultSeverity(assertion.confidence)\n } catch {\n // Plain text value\n ruleValue = { description: String(assertion.value) }\n severity = defaultSeverity(assertion.confidence)\n }\n } else {\n ruleValue = { description: '' }\n severity = defaultSeverity(assertion.confidence)\n }\n\n return {\n id: assertion.id,\n tenantId: assertion.tenantId,\n subject: assertion.subject,\n type,\n predicate,\n value: ruleValue,\n severity,\n confidence: assertion.confidence,\n validFrom: assertion.validFrom,\n isSuperseded: assertion.isSuperseded,\n }\n}\n\nfunction enc(s: string): string {\n return encodeURIComponent(s)\n}\n\nfunction toWire(input: Record<string, unknown>): Record<string, unknown> {\n // Re-use the SDK's toWire for camelCase → snake_case mapping\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(input)) {\n if (value === undefined) continue\n const snakeKey = key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)\n result[snakeKey] = value\n }\n return result\n}\n","/**\n * SubCortexClient — the main entry point for the SubCortex SDK.\n *\n * @example\n * ```typescript\n * import { SubCortexClient } from '@subcortex-ai/sdk'\n *\n * const subcortex = new SubCortexClient({\n * endpoint: 'https://api.subcortex.example.com',\n * tenantId: 'my-tenant',\n * apiKey: 'scx_live_...',\n * })\n *\n * // Create an assertion\n * const assertion = await subcortex.assertions.create({\n * subject: 'user:alice',\n * predicate: 'name',\n * value: 'Alice Smith',\n * })\n *\n * // Query by subject\n * const facts = await subcortex.assertions.query('user:alice')\n *\n * // Create a relationship\n * const rel = await subcortex.relationships.create({\n * fromSubject: 'user:alice',\n * toSubject: 'team:engineering',\n * relationshipType: 'belongs_to',\n * })\n * ```\n */\n\nimport { HttpTransport, toWire, type RetryConfig } from './http'\nimport type { HealthResponse } from './types/common'\nimport { UsersNamespace } from './users'\nimport { SignalsNamespace } from './signals'\nimport { RulesNamespace } from './rules'\n\n// ─── Client Options ─────────────────────────────────\n\nexport interface SubCortexClientOptions {\n /** Base URL of the SubCortex REST API */\n endpoint: string\n /** Tenant ID — required, used as default for all operations */\n tenantId: string\n /** API key for authentication */\n apiKey?: string\n /** JWT token for authentication (alternative to apiKey) */\n token?: string\n /** Retry configuration */\n retry?: Partial<RetryConfig>\n /** Request timeout in milliseconds (default: 30000) */\n timeoutMs?: number\n /** Custom fetch implementation (for testing or Cloudflare Workers) */\n fetch?: typeof fetch\n /** Custom headers added to every request */\n headers?: Record<string, string>\n /** AbortSignal for cancelling all pending requests */\n signal?: AbortSignal\n}\n\n// ─── Assertion Types ────────────────────────────────\n\n/**\n * An assertion — the atomic unit of knowledge in SubCortex.\n *\n * An assertion represents a single claim: \"subject S has property P with value V.\"\n * Assertions are content-addressable (same content = same ID), carry confidence\n * scores, and have temporal bounds.\n *\n * @example\n * ```typescript\n * const fact = await subcortex.assertions.create({\n * subject: 'user:alice',\n * predicate: 'role',\n * value: 'Engineering Manager',\n * confidence: 0.99,\n * })\n * console.log(fact.id) // content-addressable BLAKE3 hash\n * ```\n */\nexport interface Assertion {\n /** Content-addressable ID (BLAKE3 hash of subject + predicate + value + temporal bounds) */\n id: string\n /** Tenant this assertion belongs to */\n tenantId: string\n /** The subject this assertion is about (e.g., `\"user:alice\"`, `\"entity:Project\"`) */\n subject: string\n /** The property being asserted (e.g., `\"name\"`, `\"role\"`, `\"status\"`) */\n predicate: string\n /** The asserted value — can be a string, number, boolean, or object */\n value: unknown\n /** Confidence score (0.0–1.0). Higher = more certain. */\n confidence: number\n /** When this assertion became valid (ISO 8601) */\n validFrom: string\n /** Whether this assertion has been superseded by a newer version */\n isSuperseded: boolean\n}\n\n/**\n * Input for creating an assertion.\n *\n * @example\n * ```typescript\n * await subcortex.assertions.create({\n * subject: 'user:alice',\n * predicate: 'department',\n * value: 'Engineering',\n * confidence: 0.95,\n * })\n * ```\n */\nexport interface CreateAssertionInput {\n /** Subject of the assertion (e.g., `\"user:alice\"`, `\"entity:Project\"`) */\n subject: string\n /** Predicate — what property is being asserted */\n predicate: string\n /** The value being asserted */\n value: unknown\n /** Confidence score 0.0–1.0 (default: server-side default, typically 0.95) */\n confidence?: number\n /** Override the default tenant ID for this operation */\n tenantId?: string\n /** Session ID — binds this assertion to an Experience for session grouping */\n sessionId?: string\n}\n\n/**\n * Input for superseding (updating) an existing assertion.\n *\n * SubCortex assertions are immutable. To \"update\" a fact, you supersede it:\n * the old assertion is marked as superseded and a new one is created.\n *\n * @example\n * ```typescript\n * await subcortex.assertions.supersede({\n * originalAssertionId: 'abc123...',\n * subject: 'user:alice',\n * predicate: 'role',\n * value: 'VP Engineering', // was \"Engineering Manager\"\n * })\n * ```\n */\nexport interface SupersedeAssertionInput {\n /** ID of the assertion being superseded */\n originalAssertionId: string\n /** Subject of the new assertion */\n subject: string\n /** Predicate of the new assertion */\n predicate: string\n /** Updated value */\n value: unknown\n /** Confidence for the new assertion */\n confidence?: number\n /** Override the default tenant ID */\n tenantId?: string\n /** Session ID — binds this assertion to an Experience for session grouping */\n sessionId?: string\n}\n\n// ─── Relationship Types ─────────────────────────────\n\n/** What the SDK returns for a relationship. */\nexport interface Relationship {\n id: string\n tenantId: string\n fromSubject: string\n toSubject: string\n relationshipType: string\n confidence: number\n validFrom: string\n weight: number | null\n properties: Record<string, string>\n}\n\n/** Input for creating a relationship. */\nexport interface CreateRelationshipInput {\n fromSubject: string\n toSubject: string\n relationshipType: string\n confidence?: number\n weight?: number\n properties?: Record<string, string>\n tenantId?: string\n}\n\n// ─── Namespace Classes ──────────────────────────────\n\n/** Operations on assertions — the atomic units of knowledge in SubCortex. */\nexport class AssertionsNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** Create an assertion in the knowledge graph. */\n async create(input: CreateAssertionInput): Promise<Assertion> {\n const tenantId = input.tenantId || this.tenantId\n return this.http.post<Assertion>('/api/v1/assertions', {\n tenant_id: tenantId,\n subject: input.subject,\n predicate: input.predicate,\n value: input.value,\n confidence: input.confidence,\n ...(input.sessionId ? { session_id: input.sessionId } : {}),\n })\n }\n\n /** Get an assertion by its content-addressable ID. */\n async get(assertionId: string, options?: { tenantId?: string }): Promise<Assertion> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<Assertion>(\n `/api/v1/assertions/${enc(tenantId)}/${enc(assertionId)}`\n )\n }\n\n /** Query assertions by subject. */\n async query(subject: string, options?: { tenantId?: string }): Promise<Assertion[]> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(tenantId)}/${enc(subject)}`\n )\n }\n\n /** List all active assertions for the tenant. */\n async list(options?: { tenantId?: string }): Promise<Assertion[]> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<Assertion[]>(\n `/api/v1/assertions/list/${enc(tenantId)}`\n )\n }\n\n /** Supersede an existing assertion with updated values. */\n async supersede(input: SupersedeAssertionInput): Promise<Assertion> {\n const tenantId = input.tenantId || this.tenantId\n return this.http.post<Assertion>('/api/v1/assertions/supersede', {\n tenant_id: tenantId,\n original_assertion_id: input.originalAssertionId,\n subject: input.subject,\n predicate: input.predicate,\n value: input.value,\n confidence: input.confidence,\n ...(input.sessionId ? { session_id: input.sessionId } : {}),\n })\n }\n\n /** Retract an assertion by closing its temporal bounds. */\n async retract(assertionId: string, options?: { tenantId?: string }): Promise<Assertion> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.post<Assertion>(\n `/api/v1/assertions/retract/${enc(tenantId)}/${enc(assertionId)}`,\n {}\n )\n }\n}\n\n/** Operations on relationships — directional edges between subjects. */\nexport class RelationshipsNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** Create a relationship between two subjects. */\n async create(input: CreateRelationshipInput): Promise<Relationship> {\n const tenantId = input.tenantId || this.tenantId\n return this.http.post<Relationship>('/api/v1/relationships', {\n tenant_id: tenantId,\n from_subject: input.fromSubject,\n to_subject: input.toSubject,\n relationship_type: input.relationshipType,\n confidence: input.confidence,\n weight: input.weight,\n properties: input.properties,\n })\n }\n\n /** Get relationships for a subject. */\n async query(subject: string, options?: { tenantId?: string }): Promise<Relationship[]> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<Relationship[]>(\n `/api/v1/relationships/${enc(tenantId)}/${enc(subject)}`\n )\n }\n\n /** List all relationships for the tenant. */\n async list(options?: { tenantId?: string }): Promise<Relationship[]> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<Relationship[]>(\n `/api/v1/relationships/list/${enc(tenantId)}`\n )\n }\n}\n\n// ─── Agent Types ────────────────────────────────────\n\n/**\n * Agent personality — defines how the agent communicates.\n *\n * @example\n * ```typescript\n * const personality: AgentPersonality = {\n * voice: \"Friendly cubicle neighbor who knows the business inside out\",\n * tone: \"casual\",\n * traits: [\"curious\", \"witty\", \"empathetic\"],\n * avoid: [\"corporate speak\", \"jargon\", \"being verbose\"],\n * }\n * ```\n */\nexport interface AgentPersonality {\n /** Overall personality description */\n voice?: string\n /** Communication tone: `\"casual\"`, `\"professional\"`, `\"playful\"` */\n tone?: string\n /** Personality traits */\n traits?: string[]\n /** Things the agent should avoid saying/doing */\n avoid?: string[]\n}\n\n/**\n * Composable instruction sections for an agent.\n *\n * Instructions are broken into sections so they can be independently\n * configured. SubCortex assembles them into a single system prompt\n * via {@link SubCortexClient.agents.getInstructions}.\n */\nexport interface AgentInstructions {\n /** How the agent speaks and presents itself */\n personality?: string\n /** What to remember about users, how to categorize facts */\n memoryGuidance?: string\n /** Domain-specific behavior rules (e.g., schema emergence) */\n domainRules?: string\n /** Organization-specific additions */\n custom?: string\n /** How to greet new vs returning users */\n greetingRules?: string\n /** The agent's purpose, responsibilities, and proactive behaviors */\n goals?: string\n /** How to read and respond to emotional signals and rapport shifts */\n emotionalIntelligence?: string\n /** Guardrails, compliance rules, escalation triggers */\n safety?: string\n}\n\n/**\n * LLM model configuration for the agent.\n */\nexport interface AgentModelConfig {\n /** Provider: `\"anthropic\"`, `\"openai\"`, `\"azure-openai\"` */\n provider?: string\n /** Model identifier (e.g., `\"claude-opus-4-6\"`, `\"gpt-4-turbo\"`) */\n modelId?: string\n /** Inference temperature (0.0–2.0) */\n temperature?: number\n /** Maximum response tokens */\n maxTokens?: number\n /** Voice ID for voice agents (e.g., `\"marin\"`, `\"echo\"`) */\n voiceId?: string\n}\n\n/**\n * A capability (tool/function) the agent can use.\n *\n * @example\n * ```typescript\n * const cap: AgentCapability = {\n * name: \"registerUserFact\",\n * description: \"Store a learned fact about the user\",\n * enabled: true,\n * }\n * ```\n */\nexport interface AgentCapability {\n /** Tool/function name */\n name: string\n /** What this capability does */\n description?: string\n /** Whether this capability is active */\n enabled?: boolean\n /** Tool parameter schema (JSON Schema) */\n parameters?: unknown\n}\n\n/**\n * Memory retention policy — controls how the agent manages its memories.\n */\nexport interface AgentMemoryPolicy {\n /** Max assertions per user subject (0 = unlimited) */\n maxMemoriesPerUser?: number\n /** Auto-forget memories below this confidence (0.0 = keep everything) */\n forgetConfidenceBelow?: number\n /** Days to retain memories (0 = forever) */\n retainDays?: number\n /** Compress old memories into higher-level summaries */\n autoSummarize?: boolean\n}\n\n/**\n * Full agent configuration — the agent's identity in SubCortex.\n *\n * This is what an agent retrieves at session start to know who it is,\n * how to behave, what tools it has, and how to manage its memory.\n *\n * @example\n * ```typescript\n * const agent = await cortex.agents.create({\n * name: 'Aria',\n * description: 'AI assistant for customer support',\n * personality: { tone: 'casual', traits: ['curious', 'empathetic'] },\n * instructions: {\n * personality: 'You are the user\\'s best friend at work...',\n * memoryGuidance: 'Remember names, roles, and org structure...',\n * },\n * model: { provider: 'openai', modelId: 'gpt-realtime-1.5', voiceId: 'marin' },\n * })\n * ```\n */\nexport interface AgentConfig {\n agentId: string\n tenantId: string\n name: string\n description: string\n personality: AgentPersonality\n instructions: AgentInstructions\n model: AgentModelConfig\n capabilities: AgentCapability[]\n memoryPolicy: AgentMemoryPolicy\n isActive: boolean\n createdAt: string\n updatedAt: string\n}\n\n/** Input for creating an agent. */\nexport interface CreateAgentInput {\n name: string\n description?: string\n personality?: AgentPersonality\n instructions?: AgentInstructions\n model?: AgentModelConfig\n capabilities?: AgentCapability[]\n memoryPolicy?: AgentMemoryPolicy\n tenantId?: string\n}\n\n/** Input for updating an agent. */\nexport interface UpdateAgentInput {\n name?: string\n description?: string\n personality?: AgentPersonality\n instructions?: AgentInstructions\n model?: AgentModelConfig\n capabilities?: AgentCapability[]\n memoryPolicy?: AgentMemoryPolicy\n isActive?: boolean\n}\n\n/** Composed instructions response. */\nexport interface ComposedInstructions {\n composedInstructions: string\n agentName: string\n modelProvider: string\n modelId: string\n temperature: number\n maxTokens: number\n voiceId: string\n}\n\n/**\n * Operations on agent configurations — the identity layer.\n *\n * Create, update, and retrieve agent profiles that define who an agent is,\n * how it behaves, what tools it can use, and how it manages memory.\n *\n * @example\n * ```typescript\n * // Create an agent\n * const agent = await subcortex.agents.create({\n * name: 'Aria',\n * description: 'AI assistant for customer support',\n * personality: { tone: 'casual', traits: ['curious', 'witty'] },\n * })\n *\n * // Get composed system prompt at session start\n * const { composedInstructions } = await subcortex.agents.getInstructions(agent.agentId)\n * ```\n */\nexport class AgentsNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** Create a new agent. */\n async create(input: CreateAgentInput): Promise<AgentConfig> {\n const tenantId = input.tenantId || this.tenantId\n return this.http.post<AgentConfig>('/api/v1/agents', {\n tenant_id: tenantId,\n name: input.name,\n description: input.description,\n personality: input.personality,\n instructions: input.instructions ? toWire(input.instructions) : undefined,\n model: input.model ? toWire(input.model) : undefined,\n capabilities: input.capabilities,\n memory_policy: input.memoryPolicy ? toWire(input.memoryPolicy) : undefined,\n })\n }\n\n /** Get an agent by ID. */\n async get(agentId: string, options?: { tenantId?: string }): Promise<AgentConfig> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<AgentConfig>(\n `/api/v1/agents/${enc(tenantId)}/${enc(agentId)}`\n )\n }\n\n /** Update an agent. */\n async update(agentId: string, input: UpdateAgentInput, options?: { tenantId?: string }): Promise<AgentConfig> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.put<AgentConfig>(\n `/api/v1/agents/${enc(tenantId)}/${enc(agentId)}`,\n {\n tenant_id: tenantId,\n name: input.name,\n description: input.description,\n personality: input.personality,\n instructions: input.instructions ? toWire(input.instructions) : undefined,\n model: input.model ? toWire(input.model) : undefined,\n capabilities: input.capabilities,\n memory_policy: input.memoryPolicy ? toWire(input.memoryPolicy) : undefined,\n is_active: input.isActive,\n }\n )\n }\n\n /** Delete an agent. */\n async delete(agentId: string, options?: { tenantId?: string }): Promise<void> {\n const tenantId = options?.tenantId || this.tenantId\n await this.http.delete<unknown>(`/api/v1/agents/${enc(tenantId)}/${enc(agentId)}`)\n }\n\n /** List all agents for the tenant. */\n async list(options?: { tenantId?: string }): Promise<AgentConfig[]> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<AgentConfig[]>(\n `/api/v1/agents/list/${enc(tenantId)}`\n )\n }\n\n /** Get composed system instructions for an agent. */\n async getInstructions(agentId: string, options?: { tenantId?: string }): Promise<ComposedInstructions> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<ComposedInstructions>(\n `/api/v1/agents/${enc(tenantId)}/${enc(agentId)}/instructions`\n )\n }\n}\n\n// ─── Memory Namespace ───────────────────────────────\n\n/** Input for storing a memory. */\nexport interface StoreMemoryInput {\n subject: string\n predicate: string\n value: unknown\n confidence?: number\n tenantId?: string\n /** Agent ID — required for Thalamus routing (used as agentId in intake submission) */\n agentId?: string\n /** Person this fact relates to */\n personName?: string\n /** Skip Thalamus processing — write directly to assertion store. For bulk imports, migrations. */\n raw?: boolean\n /** Conversational context for deep encoding */\n context?: {\n topic?: string\n emotionalState?: string\n sessionId?: string\n excerpt?: string\n }\n}\n\n/**\n * Agent memory operations.\n *\n * By default, `store()` routes through the Thalamus cognitive intake\n * pipeline for signal classification, contradiction detection, and\n * deduplication. Use `raw: true` to bypass for bulk imports.\n *\n * @example\n * ```typescript\n * // Store via Thalamus (default — validated, deduped, conflict-checked)\n * await subcortex.memory.store({\n * subject: 'user:alice',\n * predicate: 'role',\n * value: 'Engineering Manager',\n * confidence: 0.99,\n * agentId: 'agent_abc',\n * })\n *\n * // Store raw (bypass Thalamus — for imports/migrations)\n * await subcortex.memory.store({\n * subject: 'user:alice',\n * predicate: 'role',\n * value: 'Engineering Manager',\n * raw: true,\n * })\n *\n * // Recall everything about a user\n * const memories = await subcortex.memory.recall('user:alice')\n * ```\n */\nexport class MemoryNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /**\n * Store a fact in the agent's memory.\n *\n * Routes through the Thalamus by default. The Thalamus will:\n * - Classify the signal (reject noise)\n * - Check for contradictions with existing assertions\n * - Detect duplicates and reinforce instead of creating new\n *\n * Pass `raw: true` to bypass Thalamus for system operations.\n */\n async store(input: StoreMemoryInput): Promise<Assertion | IntakeResult> {\n const tenantId = input.tenantId || this.tenantId\n\n if (input.raw) {\n // Direct write — bypass Thalamus\n return this.http.post<Assertion>('/api/v1/assertions', {\n tenant_id: tenantId,\n subject: input.subject,\n predicate: input.predicate,\n value: input.value,\n confidence: input.confidence,\n })\n }\n\n // Route through Thalamus\n const correlationId = `mem_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`\n return this.http.post<IntakeResult>('/api/v1/intake/submit', {\n correlation_id: correlationId,\n agent_id: input.agentId,\n tenant_id: tenantId,\n candidates: [{\n subject: input.subject,\n predicate: input.predicate,\n value: input.value,\n source_confidence: input.confidence ?? 0.95,\n provenance: 'agent',\n person_name: input.personName,\n }],\n context: input.context,\n })\n }\n\n /** Recall all memories for a subject. */\n async recall(subject: string, options?: { tenantId?: string }): Promise<Assertion[]> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(tenantId)}/${enc(subject)}`\n )\n }\n\n /** Forget a specific memory (retract the assertion). */\n async forget(assertionId: string, options?: { tenantId?: string }): Promise<Assertion> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.post<Assertion>(\n `/api/v1/assertions/retract/${enc(tenantId)}/${enc(assertionId)}`,\n {}\n )\n }\n}\n\n// ─── Intake Types ───────────────────────────────────\n\n/** A candidate assertion submitted for Thalamus processing. */\nexport interface CandidateAssertion {\n subject: string\n predicate: string\n value: unknown\n sourceConfidence: number\n validFrom?: string\n validUntil?: string | null\n provenance: 'human' | 'agent' | 'import' | 'derived'\n personName?: string\n}\n\n/** Full intake submission. */\nexport interface IntakeSubmission {\n correlationId: string\n agentId: string\n candidates: CandidateAssertion[]\n context?: {\n topic?: string\n emotionalState?: string\n sessionId?: string\n excerpt?: string\n }\n tenantId?: string\n}\n\n/** Result of Thalamus processing. */\nexport interface IntakeResult {\n correlationId: string\n processed: number\n accepted: number\n reinforced: number\n conflicts: number\n rejected: number\n items: IntakeResponseItem[]\n}\n\n/** A single intake response queue item. */\nexport interface IntakeResponseItem {\n id: string\n correlationId: string\n agentId: string\n tenantId: string\n status: 'accepted' | 'reinforced' | 'conflict_detected' | 'needs_clarification' | 'rejected'\n priority: number\n surfacingHint?: string\n expiresAt: string\n persistedAssertionIds: string[]\n inferredBondIds: string[]\n conflictingAssertionId?: string\n clarificationQuestions: string[]\n rejectionReason?: string\n signalCategory?: string\n acknowledged: boolean\n createdAt: string\n}\n\n/** Intake processing stats. */\nexport interface IntakeStats {\n total: number\n accepted: number\n reinforced: number\n conflicts: number\n clarifications: number\n rejected: number\n}\n\n/**\n * Thalamus cognitive intake operations.\n *\n * Submit candidate assertions for processing through the Thalamus\n * pipeline. The pipeline validates, deduplicates, detects contradictions,\n * and enriches assertions before persisting them.\n *\n * @example\n * ```typescript\n * // Submit a fact for processing\n * const result = await subcortex.intake.submit({\n * correlationId: 'corr-123',\n * agentId: 'agent_abc',\n * candidates: [{\n * subject: 'user:tommy',\n * predicate: 'role',\n * value: 'CTO',\n * sourceConfidence: 0.99,\n * provenance: 'human',\n * }],\n * })\n *\n * // Check for conflicts or clarification requests\n * const pending = await subcortex.intake.pending('agent_abc')\n *\n * // Acknowledge after handling\n * await subcortex.intake.acknowledge(pending[0].id)\n * ```\n */\nexport class IntakeNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** Submit candidate assertions for Thalamus processing. */\n async submit(input: IntakeSubmission): Promise<IntakeResult> {\n const tenantId = input.tenantId || this.tenantId\n return this.http.post<IntakeResult>('/api/v1/intake/submit', {\n correlation_id: input.correlationId,\n agent_id: input.agentId,\n tenant_id: tenantId,\n candidates: input.candidates.map(c => ({\n subject: c.subject,\n predicate: c.predicate,\n value: c.value,\n source_confidence: c.sourceConfidence,\n valid_from: c.validFrom,\n valid_until: c.validUntil,\n provenance: c.provenance,\n person_name: c.personName,\n })),\n context: input.context,\n })\n }\n\n /** Get pending intake results for an agent. */\n async pending(agentId: string, options?: {\n status?: string[]\n limit?: number\n }): Promise<IntakeResponseItem[]> {\n let path = `/api/v1/intake/pending/${enc(agentId)}`\n const params: string[] = []\n if (options?.status) params.push(`status=${options.status.join(',')}`)\n if (options?.limit) params.push(`limit=${options.limit}`)\n if (params.length) path += `?${params.join('&')}`\n\n return this.http.get<IntakeResponseItem[]>(path)\n }\n\n /** Acknowledge an intake result (mark as consumed). */\n async acknowledge(itemId: string): Promise<void> {\n await this.http.post<unknown>(`/api/v1/intake/acknowledge/${enc(itemId)}`, {})\n }\n\n /** Acknowledge all pending items for an agent. */\n async acknowledgeAll(agentId: string): Promise<{ acknowledged: number }> {\n return this.http.post<{ acknowledged: number }>(\n `/api/v1/intake/acknowledge-all/${enc(agentId)}`,\n {}\n )\n }\n\n /** Get intake processing stats for an agent. */\n async stats(agentId: string): Promise<IntakeStats> {\n return this.http.get<IntakeStats>(`/api/v1/intake/stats/${enc(agentId)}`)\n }\n}\n\n// ─── Experience Types ─────────────────────────────\n\nexport interface Experience {\n id: string\n tenant_id: string\n agent_id: string | null\n session_id: string\n start_time: string\n end_time: string | null\n assertion_ids: string[]\n relationship_ids: string[]\n summary: string | null\n topic: string | null\n emotional_arc: string | null\n}\n\nexport class ExperiencesNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** List experiences, optionally filtered by subject. */\n async list(input?: { subject?: string; limit?: number; tenantId?: string }): Promise<Experience[]> {\n const tenantId = input?.tenantId || this.tenantId\n const params = new URLSearchParams()\n if (input?.subject) params.set('subject', input.subject)\n if (input?.limit) params.set('limit', String(input.limit))\n const qs = params.toString()\n return this.http.get<Experience[]>(\n `/api/v1/experiences/${enc(tenantId)}${qs ? `?${qs}` : ''}`\n )\n }\n\n /** Get a single experience by ID. */\n async get(experienceId: string, options?: { tenantId?: string }): Promise<Experience> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<Experience>(\n `/api/v1/experiences/${enc(tenantId)}/${enc(experienceId)}`\n )\n }\n}\n\n// ─── Recall Types ─────────────────────────────────\n\nexport interface RecallResult {\n assertion_id: string\n score: number\n subject: string\n predicate: string\n snippet: string\n}\n\nexport interface RecallSearchInput {\n query: string\n limit?: number\n tenantId?: string\n}\n\nexport interface RecallSearchResponse {\n results: RecallResult[]\n total_hits: number\n}\n\nexport class RecallNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** BM25 full-text search across assertions. */\n async search(input: RecallSearchInput): Promise<RecallSearchResponse> {\n const tenantId = input.tenantId || this.tenantId\n const params = new URLSearchParams({ q: input.query })\n if (input.limit) params.set('limit', String(input.limit))\n return this.http.get<RecallSearchResponse>(\n `/api/v1/recall/${enc(tenantId)}?${params.toString()}`\n )\n }\n}\n\n// ─── Graph Types ──────────────────────────────────\n\nexport interface GraphPath {\n subjects: string[]\n total_confidence: number\n length: number\n}\n\nexport interface FindPathsInput {\n from: string\n to: string\n maxDepth?: number\n minConfidence?: number\n /** \"shortest\" | \"highest_confidence\" | \"all\" */\n strategy?: string\n tenantId?: string\n}\n\nexport interface TraversalNode {\n subject: string\n depth: number\n path_confidence: number\n}\n\nexport interface TraversalResult {\n nodes: TraversalNode[]\n edge_count: number\n depth_reached: number\n truncated: boolean\n}\n\nexport interface TraverseInput {\n startSubject: string\n maxDepth?: number\n relationshipTypes?: string[]\n minConfidence?: number\n maxNodes?: number\n tenantId?: string\n}\n\nexport class GraphNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** Find paths between two subjects. */\n async findPaths(input: FindPathsInput): Promise<GraphPath[]> {\n const tenantId = input.tenantId || this.tenantId\n return this.http.post<GraphPath[]>(\n `/api/v1/graph/${enc(tenantId)}/paths`,\n {\n from: input.from,\n to: input.to,\n max_depth: input.maxDepth,\n min_confidence: input.minConfidence,\n strategy: input.strategy,\n }\n )\n }\n\n /** BFS traversal from a starting subject. */\n async traverse(input: TraverseInput): Promise<TraversalResult> {\n const tenantId = input.tenantId || this.tenantId\n return this.http.post<TraversalResult>(\n `/api/v1/graph/${enc(tenantId)}/traverse`,\n {\n start_subject: input.startSubject,\n max_depth: input.maxDepth,\n relationship_types: input.relationshipTypes,\n min_confidence: input.minConfidence,\n max_nodes: input.maxNodes,\n }\n )\n }\n}\n\n// ─── Temporal Types ───────────────────────────────\n\nexport interface TemporalSnapshot {\n subject: string\n point: string\n assertions: Assertion[]\n}\n\nexport interface TemporalRange {\n subject: string\n start: string\n end: string\n assertions: Assertion[]\n}\n\nexport class TemporalNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** Get assertions valid at a specific point in time. */\n async at(subject: string, point: Date | string, options?: { tenantId?: string }): Promise<TemporalSnapshot> {\n const tenantId = options?.tenantId || this.tenantId\n const pointStr = point instanceof Date ? point.toISOString() : point\n return this.http.get<TemporalSnapshot>(\n `/api/v1/temporal/${enc(tenantId)}/${enc(subject)}/at?point=${enc(pointStr)}`\n )\n }\n\n /** Get assertions within a date range. */\n async range(subject: string, start: Date | string, end: Date | string, options?: { tenantId?: string }): Promise<TemporalRange> {\n const tenantId = options?.tenantId || this.tenantId\n const startStr = start instanceof Date ? start.toISOString() : start\n const endStr = end instanceof Date ? end.toISOString() : end\n return this.http.get<TemporalRange>(\n `/api/v1/temporal/${enc(tenantId)}/${enc(subject)}/range?start=${enc(startStr)}&end=${enc(endStr)}`\n )\n }\n}\n\n// ─── Search Types ─────────────────────────────────\n\nexport interface SearchResult {\n assertion_id: string\n similarity: number\n}\n\nexport interface SemanticSearchInput {\n embedding: number[]\n topK?: number\n tenantId?: string\n}\n\nexport class SearchNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** Semantic nearest-neighbor search over assertion embeddings. */\n async semantic(input: SemanticSearchInput): Promise<SearchResult[]> {\n const tenantId = input.tenantId || this.tenantId\n return this.http.post<SearchResult[]>(\n `/api/v1/search/${enc(tenantId)}/semantic`,\n {\n embedding: input.embedding,\n top_k: input.topK,\n }\n )\n }\n}\n\n// ─── Client ─────────────────────────────────────────\n\nconst DEFAULT_RETRY: RetryConfig = {\n maxRetries: 3,\n baseDelayMs: 500,\n maxDelayMs: 10_000,\n}\n\n// ─── Entity Types ──────────────────────────────────\n\nexport interface CreateEntityInput {\n /** Entity name (used as the subject identifier, e.g. \"Project\") */\n name: string\n /** Human-readable description */\n description?: string\n /** Entity type classification (e.g. \"model\", \"workflow\", \"reference\") */\n type?: string\n /** Override default tenant */\n tenantId?: string\n}\n\nexport interface AddPropertyInput {\n /** Entity name this property belongs to */\n entityName: string\n /** Property name */\n name: string\n /** Property field type (e.g. \"string\", \"number\", \"date\", \"boolean\", \"reference\") */\n fieldType: string\n /** Whether this property is required */\n required?: boolean\n /** Override default tenant */\n tenantId?: string\n}\n\nexport interface EntityDescription {\n subject: string\n name: string\n type: string | null\n description: string | null\n properties: Array<{\n name: string\n fieldType: string | null\n required: boolean\n }>\n relationships: Array<{\n type: string\n target: string\n confidence: number\n }>\n}\n\nexport class EntitiesNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** Create an entity with optional description and type. */\n async create(input: CreateEntityInput): Promise<Assertion> {\n const tenantId = input.tenantId || this.tenantId\n const subject = `entity:${input.name.toLowerCase().replace(/\\s+/g, '-')}`\n\n // Create the type assertion (defines this as an entity)\n const typeAssertion = await this.http.post<Assertion>(\n `/api/v1/assertions`,\n {\n tenant_id: tenantId,\n subject,\n predicate: 'type',\n value: input.type || 'model',\n confidence: 1.0,\n }\n )\n\n // Add description if provided\n if (input.description) {\n await this.http.post<Assertion>(\n `/api/v1/assertions`,\n {\n tenant_id: tenantId,\n subject,\n predicate: 'description',\n value: input.description,\n confidence: 1.0,\n }\n )\n }\n\n return typeAssertion\n }\n\n /** Add a property to an entity. */\n async addProperty(input: AddPropertyInput): Promise<{ assertion: Assertion; relationship: Relationship }> {\n const tenantId = input.tenantId || this.tenantId\n const entitySubject = `entity:${input.entityName.toLowerCase().replace(/\\s+/g, '-')}`\n const propertySubject = `property:${input.entityName.toLowerCase().replace(/\\s+/g, '-')}.${input.name.toLowerCase().replace(/\\s+/g, '-')}`\n\n // Create property field_type assertion\n const assertion = await this.http.post<Assertion>(\n `/api/v1/assertions`,\n {\n tenant_id: tenantId,\n subject: propertySubject,\n predicate: 'field_type',\n value: input.fieldType,\n confidence: 1.0,\n }\n )\n\n // Create has_property relationship\n const relationship = await this.http.post<Relationship>(\n `/api/v1/relationships`,\n {\n tenant_id: tenantId,\n from_subject: entitySubject,\n to_subject: propertySubject,\n relationship_type: 'has_property',\n confidence: 1.0,\n }\n )\n\n // Mark required if specified\n if (input.required) {\n await this.http.post<Assertion>(\n `/api/v1/assertions`,\n {\n tenant_id: tenantId,\n subject: propertySubject,\n predicate: 'required',\n value: true,\n confidence: 1.0,\n }\n )\n }\n\n return { assertion, relationship }\n }\n\n /** Describe an entity by reconstructing its properties and relationships from assertions. */\n async describe(entityName: string, options?: { tenantId?: string }): Promise<EntityDescription> {\n const tenantId = options?.tenantId || this.tenantId\n const subject = `entity:${entityName.toLowerCase().replace(/\\s+/g, '-')}`\n\n // Fetch entity assertions\n const assertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(tenantId)}/${enc(subject)}`\n )\n\n // Fetch outgoing relationships (has_property, belongs_to, etc.)\n const relationships = await this.http.get<Relationship[]>(\n `/api/v1/relationships/query/${enc(tenantId)}/${enc(subject)}`\n )\n\n // Extract known predicates\n const typeAssertion = assertions.find(a => a.predicate === 'type' && !a.isSuperseded)\n const descAssertion = assertions.find(a => a.predicate === 'description' && !a.isSuperseded)\n\n // Fetch property details for each has_property relationship\n const propertyRels = relationships.filter(r => r.relationshipType === 'has_property')\n const properties = await Promise.all(\n propertyRels.map(async (rel) => {\n const propAssertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(tenantId)}/${enc(rel.toSubject)}`\n )\n const fieldType = propAssertions.find(a => a.predicate === 'field_type' && !a.isSuperseded)\n const required = propAssertions.find(a => a.predicate === 'required' && !a.isSuperseded)\n const name = rel.toSubject.replace(/^property:[^.]+\\./, '')\n return {\n name,\n fieldType: fieldType ? String(fieldType.value) : null,\n required: required ? Boolean(required.value) : false,\n }\n })\n )\n\n // Non-property relationships\n const otherRels = relationships\n .filter(r => r.relationshipType !== 'has_property')\n .map(r => ({\n type: r.relationshipType,\n target: r.toSubject,\n confidence: r.confidence,\n }))\n\n return {\n subject,\n name: entityName,\n type: typeAssertion ? String(typeAssertion.value) : null,\n description: descAssertion ? String(descAssertion.value) : null,\n properties,\n relationships: otherRels,\n }\n }\n\n /** List all entities for a tenant (subjects with entity: prefix that have a type predicate). */\n async list(options?: { tenantId?: string }): Promise<Assertion[]> {\n const tenantId = options?.tenantId || this.tenantId\n const all = await this.http.get<Assertion[]>(\n `/api/v1/assertions/list/${enc(tenantId)}`\n )\n return all.filter(a => a.subject.startsWith('entity:') && a.predicate === 'type' && !a.isSuperseded)\n }\n}\n\nexport class SubCortexClient {\n /** Assertion operations (low-level knowledge primitives) */\n readonly assertions: AssertionsNamespace\n /** Relationship operations */\n readonly relationships: RelationshipsNamespace\n /** Agent identity & configuration */\n readonly agents: AgentsNamespace\n /** Agent memory (semantic wrapper over assertions) */\n readonly memory: MemoryNamespace\n /** Thalamus cognitive intake pipeline */\n readonly intake: IntakeNamespace\n /** User rapport building operations */\n readonly users: UsersNamespace\n /** Emotional signals — record, query, and resolve */\n readonly signals: SignalsNamespace\n /** Graph queries — pathfinding and traversal */\n readonly graph: GraphNamespace\n /** Temporal queries — point-in-time snapshots and range queries */\n readonly temporal: TemporalNamespace\n /** Semantic search over assertion embeddings */\n readonly search: SearchNamespace\n /** BM25 full-text recall search */\n readonly recall: RecallNamespace\n /** Episodic memory — experiences grouped by session */\n readonly experiences: ExperiencesNamespace\n /** Entity schema management — create, describe, and manage data models */\n readonly entities: EntitiesNamespace\n /** Code guardrails — typed rules stored as assertions with file-scope matching */\n readonly rules: RulesNamespace\n\n private readonly http: HttpTransport\n\n constructor(options: SubCortexClientOptions) {\n if (!options.apiKey && !options.token) {\n console.warn('[SubCortex] No apiKey or token provided — requests will be unauthenticated.')\n }\n\n this.http = new HttpTransport({\n baseUrl: options.endpoint,\n tenantId: options.tenantId,\n apiKey: options.apiKey,\n token: options.token,\n retry: { ...DEFAULT_RETRY, ...options.retry },\n timeoutMs: options.timeoutMs ?? 30_000,\n fetchImpl: options.fetch ?? globalThis.fetch,\n headers: options.headers ?? {},\n signal: options.signal,\n })\n\n this.assertions = new AssertionsNamespace(this.http, options.tenantId)\n this.relationships = new RelationshipsNamespace(this.http, options.tenantId)\n this.agents = new AgentsNamespace(this.http, options.tenantId)\n this.memory = new MemoryNamespace(this.http, options.tenantId)\n this.intake = new IntakeNamespace(this.http, options.tenantId)\n this.users = new UsersNamespace(this.http, options.tenantId)\n this.signals = new SignalsNamespace(this.http, options.tenantId)\n this.graph = new GraphNamespace(this.http, options.tenantId)\n this.temporal = new TemporalNamespace(this.http, options.tenantId)\n this.search = new SearchNamespace(this.http, options.tenantId)\n this.recall = new RecallNamespace(this.http, options.tenantId)\n this.experiences = new ExperiencesNamespace(this.http, options.tenantId)\n this.entities = new EntitiesNamespace(this.http, options.tenantId)\n this.rules = new RulesNamespace(this.http, options.tenantId)\n }\n\n /** Check SubCortex server health. */\n async health(): Promise<HealthResponse> {\n return this.http.get<HealthResponse>('/health')\n }\n}\n\n\n// ─── Helpers ────────────────────────────────────────\n\nfunction enc(s: string): string {\n return encodeURIComponent(s)\n}\n","/**\n * SubCortex Context Formatting — v1.0 Schema\n *\n * Transforms structured UserIdentification data into XML optimized\n * for model injection. Signals nest as children of the knowledge\n * they relate to, not as a separate section.\n *\n * Section order = priority order (transformer attention bias):\n * conflicts → reminders → contexts → identity → knowledge → relationships\n *\n * Why XML: Tag boundaries create hard attention delimiters for transformers.\n * See docs/context-format-rationale.md for full analysis.\n */\n\nimport type { UserIdentification, UserMemory, ConnectedPerson } from './types/users'\nimport type { SignalEntry } from './types/signals'\n\nexport const CONTEXT_SCHEMA_VERSION = '1.0'\n\nexport type ContextFormat = 'xml' | 'json' | 'summary'\n\nexport interface ContextFormatOptions {\n /** Output format. Default: 'xml' */\n format?: ContextFormat\n /** Include memories section. Default: true */\n includeMemories?: boolean\n /** Include connected people. Default: true */\n includeRelationships?: boolean\n /** Include reminders. Default: true */\n includeReminders?: boolean\n /** Include conflicts. Default: true */\n includeConflicts?: boolean\n /** Include active contexts. Default: true */\n includeContexts?: boolean\n /** Include emotional signals. Default: true */\n includeSignals?: boolean\n /** Minimum confidence threshold to include (0-1). Default: 0 */\n minConfidence?: number\n}\n\n/**\n * Format a UserIdentification result for model injection.\n */\nexport function formatContext(user: UserIdentification, options: ContextFormatOptions = {}): string {\n const format = options.format ?? 'xml'\n switch (format) {\n case 'xml': return toContextXml(user, options)\n case 'json': return JSON.stringify(user, null, 2)\n case 'summary': return user.summary\n }\n}\n\n/**\n * Transform UserIdentification into versioned XML optimized for model attention.\n * Signals nest as children of the facts/contexts/people they relate to.\n */\nexport function toContextXml(user: UserIdentification, options: ContextFormatOptions = {}): string {\n const {\n includeMemories = true,\n includeRelationships = true,\n includeReminders = true,\n includeConflicts = true,\n includeContexts = true,\n includeSignals = true,\n minConfidence = 0,\n } = options\n\n const ts = new Date().toISOString()\n const lines: string[] = []\n\n // Build signal lookup: aboutSubject → signals\n const signalsByAbout = new Map<string, SignalEntry[]>()\n const unattachedSignals: SignalEntry[] = []\n if (includeSignals && user.signals) {\n for (const sig of user.signals) {\n if (sig.aboutSubject) {\n const existing = signalsByAbout.get(sig.aboutSubject) || []\n existing.push(sig)\n signalsByAbout.set(sig.aboutSubject, existing)\n } else {\n unattachedSignals.push(sig)\n }\n }\n }\n\n lines.push(`<subcortex_context version=\"${CONTEXT_SCHEMA_VERSION}\" subject=\"${esc(user.subject)}\" known=\"${user.isKnown}\" ts=\"${ts}\">`)\n\n // ── Priority 1: Conflicts ──\n if (includeConflicts && user.conflicts.length > 0) {\n lines.push(` <conflicts count=\"${user.conflicts.length}\" priority=\"critical\">`)\n for (const conflict of user.conflicts) {\n lines.push(` <conflict id=\"${esc(conflict.id)}\">${esc(conflict.hint)}</conflict>`)\n }\n lines.push(` </conflicts>`)\n }\n\n // ── Priority 2: Reminders ──\n if (includeReminders && user.reminders.length > 0) {\n lines.push(` <reminders count=\"${user.reminders.length}\" priority=\"high\">`)\n for (const reminder of user.reminders) {\n lines.push(` <reminder id=\"${esc(reminder.id)}\" confidence=\"${fmtConf(reminder.confidence)}\">${esc(String(reminder.value))}</reminder>`)\n }\n lines.push(` </reminders>`)\n }\n\n // ── Priority 3: Active Contexts (with attached signals) ──\n if (includeContexts && user.contexts.length > 0) {\n lines.push(` <active_contexts count=\"${user.contexts.length}\">`)\n for (const ctx of user.contexts) {\n const ctxSignals = findSignalsForFact(ctx, signalsByAbout)\n if (ctxSignals.length > 0) {\n lines.push(` <context predicate=\"${esc(ctx.predicate)}\" confidence=\"${fmtConf(ctx.confidence)}\">`)\n lines.push(` ${esc(String(ctx.value))}`)\n for (const sig of ctxSignals) {\n lines.push(` ${renderSignal(sig)}`)\n }\n lines.push(` </context>`)\n } else {\n lines.push(` <context predicate=\"${esc(ctx.predicate)}\" confidence=\"${fmtConf(ctx.confidence)}\">${esc(String(ctx.value))}</context>`)\n }\n }\n lines.push(` </active_contexts>`)\n }\n\n // ── Priority 4: Identity (with unattached signals + rapport trajectory) ──\n if (user.name) {\n const trajectoryAttr = user.rapportTrajectory ? ` rapport_trajectory=\"${user.rapportTrajectory}\"` : ''\n lines.push(` <identity name=\"${esc(String(user.name))}\" subject=\"${esc(user.subject)}\"${trajectoryAttr}>`)\n const identityPredicates = new Set(['name', 'full_name', 'role', 'title', 'department', 'team', 'email', 'start_date', 'communication_style'])\n const identityFacts = user.memories.filter(m => identityPredicates.has(m.predicate) && m.confidence >= minConfidence)\n for (const fact of identityFacts) {\n const factSignals = findSignalsForFact(fact, signalsByAbout)\n if (factSignals.length > 0) {\n lines.push(` <fact predicate=\"${esc(fact.predicate)}\" confidence=\"${fmtConf(fact.confidence)}\">`)\n lines.push(` ${esc(String(fact.value))}`)\n for (const sig of factSignals) {\n lines.push(` ${renderSignal(sig)}`)\n }\n lines.push(` </fact>`)\n } else {\n lines.push(` <fact predicate=\"${esc(fact.predicate)}\" confidence=\"${fmtConf(fact.confidence)}\">${esc(String(fact.value))}</fact>`)\n }\n }\n // Unattached signals go under identity (general mood)\n for (const sig of unattachedSignals) {\n lines.push(` ${renderSignal(sig)}`)\n }\n lines.push(` </identity>`)\n }\n\n // ── Priority 5: Knowledge (with attached signals) ──\n if (includeMemories) {\n const identityPredicates = new Set(['name', 'full_name', 'role', 'title', 'department', 'team', 'email', 'start_date', 'communication_style'])\n const knowledge = user.memories.filter(m =>\n !identityPredicates.has(m.predicate) && m.confidence >= minConfidence\n )\n if (knowledge.length > 0) {\n lines.push(` <knowledge count=\"${knowledge.length}\">`)\n for (const mem of knowledge) {\n const memSignals = findSignalsForFact(mem, signalsByAbout)\n if (memSignals.length > 0) {\n lines.push(` <fact predicate=\"${esc(mem.predicate)}\" confidence=\"${fmtConf(mem.confidence)}\">`)\n lines.push(` ${esc(String(mem.value))}`)\n for (const sig of memSignals) {\n lines.push(` ${renderSignal(sig)}`)\n }\n lines.push(` </fact>`)\n } else {\n lines.push(` <fact predicate=\"${esc(mem.predicate)}\" confidence=\"${fmtConf(mem.confidence)}\">${esc(String(mem.value))}</fact>`)\n }\n }\n lines.push(` </knowledge>`)\n }\n }\n\n // ── Priority 6: Relationships (with attached signals) ──\n if (includeRelationships && user.connectedPeople.length > 0) {\n lines.push(` <relationships count=\"${user.connectedPeople.length}\">`)\n for (const person of user.connectedPeople) {\n const personSignals = signalsByAbout.get(person.subject) || []\n const hasContent = person.facts.length > 0 || personSignals.length > 0\n if (!hasContent) {\n lines.push(` <person name=\"${esc(person.name)}\" relationship=\"${esc(person.relationship)}\" />`)\n } else {\n lines.push(` <person name=\"${esc(person.name)}\" relationship=\"${esc(person.relationship)}\">`)\n for (const fact of person.facts) {\n lines.push(` <fact predicate=\"${esc(fact.predicate)}\">${esc(String(fact.value))}</fact>`)\n }\n for (const sig of personSignals) {\n lines.push(` ${renderSignal(sig)}`)\n }\n lines.push(` </person>`)\n }\n }\n lines.push(` </relationships>`)\n }\n\n lines.push(`</subcortex_context>`)\n return lines.join('\\n')\n}\n\n// ─── Helpers ──────────────────────────────────────────\n\nfunction renderSignal(sig: SignalEntry): string {\n const aboutAttr = sig.aboutSubject ? ` about=\"${esc(sig.aboutSubject)}\"` : ''\n return `<signal type=\"${esc(sig.type)}\" intensity=\"${fmtConf(sig.intensity)}\" decayed=\"${fmtConf(sig.decayedIntensity)}\" age_hours=\"${sig.ageHours}\"${aboutAttr}>${esc(sig.content)}</signal>`\n}\n\n/**\n * Find signals that relate to a specific fact/memory.\n * Matches on predicate name or value content as subject references.\n */\nfunction findSignalsForFact(fact: UserMemory, signalsByAbout: Map<string, SignalEntry[]>): SignalEntry[] {\n const results: SignalEntry[] = []\n // Match by predicate (e.g., about_subject = \"context:current_project\" matches predicate \"current_project\")\n for (const [aboutSubject, signals] of signalsByAbout) {\n if (aboutSubject.includes(fact.predicate) || aboutSubject.includes(String(fact.value).toLowerCase().replace(/\\s+/g, '-').slice(0, 30))) {\n results.push(...signals)\n }\n }\n return results\n}\n\nfunction fmtConf(n: number): string {\n return n.toFixed(2)\n}\n\nfunction esc(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiBO,IAAM,iBAAN,cAA6B,MAAM;AAAA;AAAA,EAE/B;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAET,YACE,SACA,YACA,SAKA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,YAAY,SAAS;AAC1B,SAAK,YAAY,SAAS,aAAa;AACvC,SAAK,OAAO,SAAS;AAA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AQ,MAAM,MAAM,EACpB,QAAQ,MAAM,QAAQ;AAC3B;","names":["SubjectPrefix","IdentityPredicate","WorkPredicate","EventPredicate","RapportPredicate","MemoryPredicate","EntityPredicate","OrgRelationship","EntityRelationship","ConfidenceLevel","enc","enc","subject","enc","subject"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/http.ts","../src/types/schema.ts","../src/types/signals.ts","../src/signals.ts","../src/users.ts","../src/types/rules.ts","../src/rules.ts","../src/client.ts","../src/context.ts"],"sourcesContent":["/**\n * @subcortex-ai/sdk — TypeScript SDK for the SubCortex Cognitive Engine\n *\n * @example\n * ```typescript\n * import { SubCortexClient } from '@subcortex-ai/sdk'\n *\n * const subcortex = new SubCortexClient({\n * endpoint: 'https://api.subcortex.example.com',\n * tenantId: 'my-tenant',\n * apiKey: 'scx_live_...',\n * })\n *\n * // Assertions\n * await subcortex.assertions.create({ subject: 'user:alice', predicate: 'name', value: 'Alice' })\n * const facts = await subcortex.assertions.query('user:alice')\n *\n * // Relationships\n * await subcortex.relationships.create({ fromSubject: 'user:alice', toSubject: 'team:eng', relationshipType: 'member_of' })\n *\n * // Health\n * const health = await subcortex.health()\n * ```\n */\n\n// Client\nexport { SubCortexClient } from './client'\nexport type { SubCortexClientOptions } from './client'\n\n// Namespace classes (for type reference in docs)\nexport {\n AssertionsNamespace, RelationshipsNamespace, AgentsNamespace, MemoryNamespace,\n GraphNamespace, TemporalNamespace, SearchNamespace, RecallNamespace, ExperiencesNamespace,\n EntitiesNamespace,\n} from './client'\n\n// HTTP transport config\nexport type { RetryConfig } from './http'\n\n// Assertion types\nexport type {\n Assertion,\n CreateAssertionInput,\n SupersedeAssertionInput,\n} from './client'\n\n// Relationship types\nexport type {\n Relationship,\n CreateRelationshipInput,\n} from './client'\n\n// Agent types\nexport type {\n AgentConfig,\n AgentPersonality,\n AgentInstructions,\n AgentModelConfig,\n AgentCapability,\n AgentMemoryPolicy,\n CreateAgentInput,\n UpdateAgentInput,\n ComposedInstructions,\n} from './client'\n\n// Memory types\nexport type {\n StoreMemoryInput,\n} from './client'\n\n// Intake types (Thalamus)\nexport type {\n CandidateAssertion,\n IntakeSubmission,\n IntakeResult,\n IntakeResponseItem,\n IntakeStats,\n} from './client'\n\n// Intake namespace\nexport { IntakeNamespace } from './client'\n\n// Graph types\nexport type {\n GraphPath,\n FindPathsInput,\n TraversalNode,\n TraversalResult,\n TraverseInput,\n} from './client'\n\n// Temporal types\nexport type {\n TemporalSnapshot,\n TemporalRange,\n} from './client'\n\n// Search types\nexport type {\n SearchResult,\n SemanticSearchInput,\n} from './client'\n\n// Experience types\nexport type { Experience } from './client'\n\n// Entity types\nexport type {\n CreateEntityInput,\n AddPropertyInput,\n EntityDescription,\n} from './client'\n\n// Recall types\nexport type {\n RecallResult,\n RecallSearchInput,\n RecallSearchResponse,\n} from './client'\n\n// Users namespace\nexport { UsersNamespace } from './users'\nexport type {\n IdentifyUserInput,\n UserIdentification,\n UserMemory,\n ConnectedPerson,\n ConflictItem,\n RegisterPersonInput,\n RegisterPersonResult,\n RecordRapportInput,\n} from './types/users'\n\n// Context formatting (model injection)\nexport { formatContext, toContextXml, CONTEXT_SCHEMA_VERSION } from './context'\nexport type { ContextFormat, ContextFormatOptions } from './context'\n\n// Signals namespace\nexport { SignalsNamespace } from './signals'\nexport type {\n SignalType,\n SystemSignalType,\n SignalEntry,\n SignalSnapshot,\n RecordSignalInput,\n SignalQueryOptions,\n ResolveSignalInput,\n Trajectory,\n} from './types/signals'\nexport {\n SYSTEM_SIGNAL_TYPES,\n SIGNAL_DECAY_CONFIG,\n POSITIVE_SIGNALS,\n NEGATIVE_SIGNALS,\n isValidSignalType,\n getDecayHalfLife,\n} from './types/signals'\n\n// Rules namespace — typed code guardrails\nexport { RulesNamespace } from './rules'\nexport type {\n RuleType,\n RuleSeverity,\n RulePredicate,\n RuleValue,\n Rule,\n CreateRuleInput,\n UpdateRuleInput,\n RuleQueryOptions,\n} from './types/rules'\nexport { RulePredicates } from './types/rules'\n\n// Schema — built-in predicates, relationships, confidence\nexport {\n SubjectPrefix,\n subject,\n IdentityPredicate,\n WorkPredicate,\n EventPredicate,\n RapportPredicate,\n MemoryPredicate,\n EntityPredicate,\n Predicates,\n OrgRelationship,\n EntityRelationship,\n RelationshipTypes,\n ConfidenceLevel,\n ConfidenceScores,\n confidenceToScore,\n scoreToConfidence,\n MULTI_VALUE_PREDICATES,\n REVERSE_RELATIONSHIPS,\n RELATIONSHIP_LABELS,\n} from './types/schema'\n\n// Common types\nexport type {\n HealthResponse,\n ConfidenceScore,\n TemporalBounds,\n Provenance,\n PaginatedResponse,\n BatchResult,\n} from './types/common'\n\n// Errors\nexport {\n SubCortexError,\n SubCortexValidationError,\n SubCortexAuthenticationError,\n SubCortexAuthorizationError,\n SubCortexNotFoundError,\n SubCortexConflictError,\n SubCortexRateLimitError,\n SubCortexServerError,\n SubCortexNetworkError,\n SubCortexTimeoutError,\n} from './errors'\n","/**\n * SubCortex SDK Error Hierarchy\n *\n * Typed error classes for programmatic error handling.\n * Consumers can catch specific error types:\n *\n * ```typescript\n * try {\n * await subcortex.assertions.create(...)\n * } catch (e) {\n * if (e instanceof SubCortexNotFoundError) { ... }\n * if (e instanceof SubCortexRateLimitError) { await sleep(e.retryAfter) }\n * }\n * ```\n */\n\n/** Base error for all SubCortex SDK errors. */\nexport class SubCortexError extends Error {\n /** HTTP status code (0 for network errors) */\n readonly statusCode: number\n /** Server-assigned request ID for debugging */\n readonly requestId?: string\n /** Whether the request can be retried */\n readonly retryable: boolean\n /** Raw response body */\n readonly body?: string\n\n constructor(\n message: string,\n statusCode: number,\n options?: {\n requestId?: string\n retryable?: boolean\n body?: string\n }\n ) {\n super(message)\n this.name = 'SubCortexError'\n this.statusCode = statusCode\n this.requestId = options?.requestId\n this.retryable = options?.retryable ?? false\n this.body = options?.body\n }\n}\n\n/** 400 — Bad request, validation failure. */\nexport class SubCortexValidationError extends SubCortexError {\n /** Field-level validation errors if available */\n readonly details?: Record<string, string>\n\n constructor(\n message: string,\n options?: {\n requestId?: string\n body?: string\n details?: Record<string, string>\n }\n ) {\n super(message, 400, { ...options, retryable: false })\n this.name = 'SubCortexValidationError'\n this.details = options?.details\n }\n}\n\n/** 401 — Invalid or missing credentials. */\nexport class SubCortexAuthenticationError extends SubCortexError {\n constructor(message: string, options?: { requestId?: string; body?: string }) {\n super(message, 401, { ...options, retryable: false })\n this.name = 'SubCortexAuthenticationError'\n }\n}\n\n/** 403 — Valid credentials but insufficient permissions. */\nexport class SubCortexAuthorizationError extends SubCortexError {\n constructor(message: string, options?: { requestId?: string; body?: string }) {\n super(message, 403, { ...options, retryable: false })\n this.name = 'SubCortexAuthorizationError'\n }\n}\n\n/** 404 — Resource not found. */\nexport class SubCortexNotFoundError extends SubCortexError {\n constructor(message: string, options?: { requestId?: string; body?: string }) {\n super(message, 404, { ...options, retryable: false })\n this.name = 'SubCortexNotFoundError'\n }\n}\n\n/** 409 — Conflict (e.g., duplicate assertion). */\nexport class SubCortexConflictError extends SubCortexError {\n constructor(message: string, options?: { requestId?: string; body?: string }) {\n super(message, 409, { ...options, retryable: false })\n this.name = 'SubCortexConflictError'\n }\n}\n\n/** 429 — Rate limit exceeded. */\nexport class SubCortexRateLimitError extends SubCortexError {\n /** Seconds to wait before retrying */\n readonly retryAfter?: number\n\n constructor(\n message: string,\n options?: {\n requestId?: string\n body?: string\n retryAfter?: number\n }\n ) {\n super(message, 429, { ...options, retryable: true })\n this.name = 'SubCortexRateLimitError'\n this.retryAfter = options?.retryAfter\n }\n}\n\n/** 5xx — Server-side error. */\nexport class SubCortexServerError extends SubCortexError {\n constructor(\n message: string,\n statusCode: number,\n options?: { requestId?: string; body?: string }\n ) {\n super(message, statusCode, { ...options, retryable: true })\n this.name = 'SubCortexServerError'\n }\n}\n\n/** Network-level failure (DNS, timeout, connection refused). */\nexport class SubCortexNetworkError extends SubCortexError {\n readonly cause?: Error\n\n constructor(message: string, options?: { cause?: Error }) {\n super(message, 0, { retryable: true })\n this.name = 'SubCortexNetworkError'\n this.cause = options?.cause\n }\n}\n\n/** Timeout — request exceeded the configured timeout. */\nexport class SubCortexTimeoutError extends SubCortexNetworkError {\n constructor(timeoutMs: number) {\n super(`Request timed out after ${timeoutMs}ms`)\n this.name = 'SubCortexTimeoutError'\n }\n}\n\n\n/**\n * Structured error response from the SubCortex REST API.\n *\n * ```json\n * {\n * \"error\": {\n * \"code\": \"NOT_FOUND\",\n * \"message\": \"Assertion not found\",\n * \"details\": { ... }\n * }\n * }\n * ```\n */\ninterface SubCortexErrorResponse {\n error?: {\n code?: string\n message?: string\n details?: Record<string, unknown>\n }\n}\n\n/**\n * Classify an HTTP response into the appropriate error type.\n * Parses structured JSON error responses from the SubCortex API.\n * Falls back to raw body if not parseable.\n */\nexport function classifyError(\n statusCode: number,\n body: string,\n requestId?: string,\n retryAfterHint?: number\n): SubCortexError {\n // Try to parse structured error response\n let errorCode = ''\n let message = ''\n let details: Record<string, string> | undefined\n\n try {\n const parsed: SubCortexErrorResponse = JSON.parse(body)\n if (parsed.error) {\n errorCode = parsed.error.code || ''\n message = parsed.error.message || ''\n if (parsed.error.details) {\n details = parsed.error.details as Record<string, string>\n }\n }\n } catch {\n // Not JSON — use raw body as message\n }\n\n if (!message) {\n message = body || `HTTP ${statusCode}`\n }\n\n const opts = { requestId, body }\n\n switch (statusCode) {\n case 400:\n return new SubCortexValidationError(message, { ...opts, details })\n case 401:\n return new SubCortexAuthenticationError(message, opts)\n case 403:\n return new SubCortexAuthorizationError(message, opts)\n case 404:\n return new SubCortexNotFoundError(message, opts)\n case 409:\n return new SubCortexConflictError(message, opts)\n case 429: {\n let retryAfter: number | undefined = retryAfterHint\n if (retryAfter === undefined) {\n try {\n const parsed = JSON.parse(body)\n retryAfter = parsed.retryAfter ?? parsed.retry_after\n } catch {\n // ignore\n }\n }\n return new SubCortexRateLimitError(message, { ...opts, retryAfter })\n }\n default:\n if (statusCode >= 500) {\n return new SubCortexServerError(message, statusCode, opts)\n }\n return new SubCortexError(message, statusCode, opts)\n }\n}\n","/**\n * HTTP Transport Layer\n *\n * Handles fetch calls, auth headers, retry with backoff,\n * timeout, request IDs, and snake_case ↔ camelCase mapping.\n *\n * This module is internal — consumers use SubCortexClient, not HttpTransport.\n */\n\nimport {\n SubCortexNetworkError,\n SubCortexRateLimitError,\n SubCortexTimeoutError,\n classifyError,\n} from './errors'\n\n// ─── Configuration ──────────────────────────────────\n\nexport interface RetryConfig {\n maxRetries: number\n baseDelayMs: number\n maxDelayMs: number\n}\n\nexport interface HttpTransportOptions {\n baseUrl: string\n tenantId: string\n apiKey?: string\n token?: string\n retry: RetryConfig\n timeoutMs: number\n fetchImpl: typeof fetch\n headers: Record<string, string>\n signal?: AbortSignal\n}\n\n// ─── snake_case ↔ camelCase mapping ─────────────────\n\nfunction snakeToCamel(s: string): string {\n return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase())\n}\n\nfunction camelToSnake(s: string): string {\n return s.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)\n}\n\n/** Deep-map object keys from snake_case to camelCase */\nexport function mapKeys(obj: unknown, mapper: (s: string) => string): unknown {\n if (obj === null || obj === undefined) return obj\n if (Array.isArray(obj)) return obj.map((item) => mapKeys(item, mapper))\n if (typeof obj === 'object') {\n const mapped: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n mapped[mapper(key)] = mapKeys(value, mapper)\n }\n return mapped\n }\n return obj\n}\n\n/** Convert wire format (snake_case) to SDK format (camelCase) */\nexport function fromWire<T>(data: unknown): T {\n return mapKeys(data, snakeToCamel) as T\n}\n\n/** Convert SDK format (camelCase) to wire format (snake_case) */\nexport function toWire(data: unknown): unknown {\n return mapKeys(data, camelToSnake)\n}\n\n// ─── Request ID generation ──────────────────────────\n\nlet counter = 0\nfunction generateRequestId(): string {\n const ts = Date.now().toString(36)\n const seq = (counter++).toString(36)\n const rand = Math.random().toString(36).slice(2, 6)\n return `scx-${ts}-${seq}-${rand}`\n}\n\n// ─── Retry with exponential backoff + jitter ────────\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction computeDelay(attempt: number, config: RetryConfig): number {\n const exponential = config.baseDelayMs * Math.pow(2, attempt)\n const capped = Math.min(exponential, config.maxDelayMs)\n // Full jitter: random between 50% and 150% of computed delay\n const jitter = capped * (0.5 + Math.random())\n return Math.round(jitter)\n}\n\nfunction isRetryable(status: number): boolean {\n return status === 429 || status >= 500\n}\n\n// ─── Transport ──────────────────────────────────────\n\nexport class HttpTransport {\n private readonly opts: HttpTransportOptions\n\n constructor(options: HttpTransportOptions) {\n this.opts = {\n ...options,\n baseUrl: options.baseUrl.replace(/\\/$/, ''),\n }\n }\n\n /** GET request with retry and typed response. */\n async get<T>(path: string, tenantId?: string): Promise<T> {\n return this.request<T>('GET', path, undefined, tenantId)\n }\n\n /** POST request with retry and typed response. */\n async post<T>(path: string, body: unknown, tenantId?: string): Promise<T> {\n return this.request<T>('POST', path, body, tenantId)\n }\n\n /** PUT request with retry and typed response. */\n async put<T>(path: string, body: unknown, tenantId?: string): Promise<T> {\n return this.request<T>('PUT', path, body, tenantId)\n }\n\n /** DELETE request with retry and typed response. */\n async delete<T>(path: string, tenantId?: string): Promise<T> {\n return this.request<T>('DELETE', path, undefined, tenantId)\n }\n\n /** Core request method with retry loop. */\n private async request<T>(\n method: string,\n path: string,\n body: unknown,\n tenantIdOverride?: string\n ): Promise<T> {\n const url = `${this.opts.baseUrl}${path}`\n const requestId = generateRequestId()\n const tenantId = tenantIdOverride || this.opts.tenantId\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'X-Request-ID': requestId,\n 'X-Tenant-ID': tenantId,\n ...this.opts.headers,\n }\n\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json'\n }\n\n // Auth header\n if (this.opts.apiKey) {\n headers['Authorization'] = `Bearer ${this.opts.apiKey}`\n } else if (this.opts.token) {\n headers['Authorization'] = `Bearer ${this.opts.token}`\n }\n\n const fetchOpts: RequestInit = {\n method,\n headers,\n body: body !== undefined ? JSON.stringify(body) : undefined,\n }\n\n let lastError: Error | undefined\n\n for (let attempt = 0; attempt <= this.opts.retry.maxRetries; attempt++) {\n try {\n const response = await this.fetchWithTimeout(url, fetchOpts)\n\n if (response.ok) {\n const text = await response.text()\n if (!text) return undefined as T\n const parsed = JSON.parse(text)\n return fromWire<T>(parsed)\n }\n\n // Non-OK response\n const responseBody = await response.text()\n\n // Rate limit: respect Retry-After header\n if (response.status === 429) {\n const retryAfterRaw = response.headers.get('Retry-After')\n const retryAfterSecs = retryAfterRaw ? parseInt(retryAfterRaw, 10) : 0\n if (attempt < this.opts.retry.maxRetries) {\n const delay = retryAfterSecs > 0\n ? retryAfterSecs * 1000\n : computeDelay(attempt, this.opts.retry)\n await sleep(delay)\n lastError = classifyError(response.status, responseBody, requestId, retryAfterSecs || undefined)\n continue\n }\n // Exhausted retries on 429 — throw with retryAfter from header\n throw classifyError(response.status, responseBody, requestId, retryAfterSecs || undefined)\n }\n\n // Retryable server error\n if (isRetryable(response.status) && attempt < this.opts.retry.maxRetries) {\n lastError = classifyError(response.status, responseBody, requestId)\n await sleep(computeDelay(attempt, this.opts.retry))\n continue\n }\n\n // Non-retryable or exhausted retries — throw classified error\n throw classifyError(response.status, responseBody, requestId)\n } catch (error) {\n // Already a SubCortexError — rethrow if non-retryable or out of retries\n if (error instanceof Error && error.name.startsWith('SubCortex')) {\n if (\n !(error as { retryable?: boolean }).retryable ||\n attempt >= this.opts.retry.maxRetries\n ) {\n throw error\n }\n lastError = error\n await sleep(computeDelay(attempt, this.opts.retry))\n continue\n }\n\n // Network-level failure (DNS, connection refused, etc.)\n if (error instanceof TypeError || error instanceof DOMException) {\n lastError = new SubCortexNetworkError(\n `Network error: ${(error as Error).message}`,\n { cause: error as Error }\n )\n if (attempt < this.opts.retry.maxRetries) {\n await sleep(computeDelay(attempt, this.opts.retry))\n continue\n }\n throw lastError\n }\n\n // Unknown error\n throw error\n }\n }\n\n // Should not reach here, but safety net\n throw lastError || new SubCortexNetworkError('Request failed after all retries')\n }\n\n /** Fetch with AbortController timeout. */\n private async fetchWithTimeout(\n url: string,\n init: RequestInit\n ): Promise<Response> {\n const controller = new AbortController()\n const timeoutId = setTimeout(\n () => controller.abort(),\n this.opts.timeoutMs\n )\n\n // Compose with user-provided signal\n if (this.opts.signal) {\n this.opts.signal.addEventListener('abort', () => controller.abort())\n }\n\n try {\n return await this.opts.fetchImpl(url, {\n ...init,\n signal: controller.signal,\n })\n } catch (error) {\n if (\n error instanceof DOMException &&\n error.name === 'AbortError' &&\n !this.opts.signal?.aborted\n ) {\n throw new SubCortexTimeoutError(this.opts.timeoutMs)\n }\n throw error\n } finally {\n clearTimeout(timeoutId)\n }\n }\n}\n","/**\n * SubCortex Built-in Schema\n *\n * These are the foundational types, predicates, relationship types,\n * and confidence levels that SubCortex supports natively. They are\n * NOT exhaustive — tenants can extend them. But these cover the\n * universal patterns every agent-user interaction needs.\n *\n * Consumer systems import these instead of using raw strings.\n */\n\n// ─── Subject Prefixes ───────────────────────────────\n\n/**\n * Well-known subject prefixes. SubCortex recognizes these and\n * provides specialized behavior for each.\n */\nexport enum SubjectPrefix {\n /** The authenticated user interacting with the agent */\n USER = 'user',\n /** A person mentioned by the user (not the user themselves) */\n PERSON = 'person',\n /** A job role or position */\n ROLE = 'role',\n /** A business entity / data model (e.g., Project, Invoice) */\n ENTITY = 'entity',\n /** A property/field on an entity */\n PROPERTY = 'property',\n /** A project, initiative, or ongoing effort */\n PROJECT = 'project',\n /** An event, meeting, or milestone */\n EVENT = 'event',\n /** An agent using SubCortex */\n AGENT = 'agent',\n}\n\n/**\n * Build a subject string from a prefix and identifier.\n * Normalizes the identifier to lowercase with hyphens.\n */\n/**\n * Common abbreviation expansions for role/title normalization.\n * Ensures \"VP of Engineering\" and \"Vice President of Engineering\"\n * resolve to the same subject.\n */\nconst TITLE_NORMALIZATIONS: [RegExp, string][] = [\n [/\\bvp\\b/gi, 'Vice President'],\n [/\\bsvp\\b/gi, 'Senior Vice President'],\n [/\\bevp\\b/gi, 'Executive Vice President'],\n [/\\bcto\\b/gi, 'Chief Technology Officer'],\n [/\\bceo\\b/gi, 'Chief Executive Officer'],\n [/\\bcfo\\b/gi, 'Chief Financial Officer'],\n [/\\bcoo\\b/gi, 'Chief Operating Officer'],\n [/\\bcmo\\b/gi, 'Chief Marketing Officer'],\n [/\\bcpo\\b/gi, 'Chief Product Officer'],\n [/\\bcio\\b/gi, 'Chief Information Officer'],\n [/\\bea\\b/gi, 'Executive Assistant'],\n [/\\bpm\\b/gi, 'Project Manager'],\n [/\\bdir\\b/gi, 'Director'],\n [/\\bsr\\b/gi, 'Senior'],\n [/\\bjr\\b/gi, 'Junior'],\n]\n\nexport function subject(prefix: SubjectPrefix | string, identifier: string): string {\n let expanded = identifier\n // Normalize titles/roles to prevent duplicate subjects from abbreviations\n if (prefix === SubjectPrefix.ROLE || prefix === 'role') {\n for (const [pattern, replacement] of TITLE_NORMALIZATIONS) {\n expanded = expanded.replace(pattern, replacement)\n }\n }\n const normalized = expanded.toLowerCase().replace(/\\s+/g, '-')\n return `${prefix}:${normalized}`\n}\n\n// ─── Predicates ─────────────────────────────────────\n\n/**\n * Built-in predicates for user/person identity and profile.\n */\nexport enum IdentityPredicate {\n NAME = 'name',\n FULL_NAME = 'full_name',\n ROLE = 'role',\n TITLE = 'title',\n DEPARTMENT = 'department',\n TEAM = 'team',\n START_DATE = 'start_date',\n EMAIL = 'email',\n}\n\n/**\n * Built-in predicates for work context.\n * NOTE: Org relationships (reports_to, manages, etc.) are NOT predicates.\n * They are relationship types — connections between two subjects.\n * See OrgRelationship enum.\n */\nexport enum WorkPredicate {\n EXPERTISE = 'expertise',\n CURRENT_PROJECT = 'current_project',\n PAIN_POINT = 'pain_point',\n}\n\n/**\n * Built-in predicates for events and status tracking.\n */\nexport enum EventPredicate {\n STATUS = 'status',\n STATUS_CHANGE = 'status_change',\n EVENT = 'event',\n DECISION = 'decision',\n OUTCOME = 'outcome',\n}\n\n/**\n * Built-in predicates for emotional/rapport tracking.\n */\nexport enum RapportPredicate {\n SENTIMENT = 'sentiment',\n FRUSTRATION = 'frustration',\n EXCITEMENT = 'excitement',\n CONCERN = 'concern',\n GOAL = 'goal',\n ASPIRATION = 'aspiration',\n PREFERENCE = 'preference',\n PAIN_POINT = 'pain_point',\n INTEREST = 'interest',\n COMMUNICATION_STYLE = 'communication_style',\n}\n\n/**\n * Built-in predicates for agent memory management.\n */\nexport enum MemoryPredicate {\n REMINDER = 'reminder',\n CONTEXT = 'context',\n CONTEXT_TASK = 'context:task',\n CURRENT_PROJECT = 'current_project',\n}\n\n/**\n * Built-in predicates for entity/schema definition.\n */\nexport enum EntityPredicate {\n TYPE = 'type',\n DESCRIPTION = 'description',\n FIELD_TYPE = 'field_type',\n REQUIRED = 'required',\n WORKFLOW = 'workflow',\n}\n\n/**\n * All built-in predicates combined.\n * Consumer systems should use these instead of raw strings.\n */\nexport const Predicates = {\n ...IdentityPredicate,\n ...WorkPredicate,\n ...EventPredicate,\n ...RapportPredicate,\n ...MemoryPredicate,\n ...EntityPredicate,\n} as const\n\n// ─── Relationship Types ─────────────────────────────\n\n/**\n * Built-in relationship types for organizational structure.\n *\n * Each relationship is directional. Many have a natural reverse:\n * reports_to ↔ manages\n * mentored_by ↔ mentors\n * member_of ↔ has_member\n */\nexport enum OrgRelationship {\n /** Person reports to user/manager */\n REPORTS_TO = 'reports_to',\n /** User/manager manages person */\n MANAGES = 'manages',\n /** Person is member of team/project */\n MEMBER_OF = 'member_of',\n /** Team/project has this person as member */\n HAS_MEMBER = 'has_member',\n /** Person holds a specific role */\n HOLDS_ROLE = 'holds_role',\n /** Person is a candidate for a role */\n CANDIDATE_FOR = 'candidate_for',\n /** Person collaborates with another person */\n COLLABORATES_WITH = 'collaborates_with',\n /** Person mentors another person */\n MENTORS = 'mentors',\n /** Person is mentored by another person */\n MENTORED_BY = 'mentored_by',\n /** Person is a stakeholder in something */\n STAKEHOLDER_IN = 'stakeholder_in',\n}\n\n/**\n * Built-in relationship types for entity/schema structure.\n */\nexport enum EntityRelationship {\n HAS_PROPERTY = 'has_property',\n BELONGS_TO = 'belongs_to',\n HAS_MANY = 'has_many',\n MANY_TO_MANY = 'many_to_many',\n DEPENDS_ON = 'depends_on',\n}\n\n/**\n * All built-in relationship types combined.\n */\nexport const RelationshipTypes = {\n ...OrgRelationship,\n ...EntityRelationship,\n} as const\n\n// ─── Confidence ─────────────────────────────────────\n\n/**\n * Standard confidence levels with numeric values.\n * The agent chooses the level; SubCortex maps to the score.\n */\nexport enum ConfidenceLevel {\n /** User stated it directly: \"My name is Alice\" */\n CONFIRMED = 'confirmed',\n /** Strongly implied: \"I've been managing the team\" → manager */\n HIGH = 'high',\n /** Reasonable inference from context */\n MODERATE = 'moderate',\n /** Speculative — worth checking later */\n LOW = 'low',\n}\n\n/** Map confidence levels to numeric scores */\nexport const ConfidenceScores: Record<ConfidenceLevel, number> = {\n [ConfidenceLevel.CONFIRMED]: 0.99,\n [ConfidenceLevel.HIGH]: 0.85,\n [ConfidenceLevel.MODERATE]: 0.65,\n [ConfidenceLevel.LOW]: 0.40,\n}\n\n/** Convert a confidence level label to a numeric score */\nexport function confidenceToScore(level: ConfidenceLevel | string): number {\n return ConfidenceScores[level as ConfidenceLevel] ?? 0.70\n}\n\n/** Convert a numeric score to the closest confidence level */\nexport function scoreToConfidence(score: number): ConfidenceLevel {\n if (score >= 0.95) return ConfidenceLevel.CONFIRMED\n if (score >= 0.80) return ConfidenceLevel.HIGH\n if (score >= 0.60) return ConfidenceLevel.MODERATE\n return ConfidenceLevel.LOW\n}\n\n// ─── Predicate Metadata ─────────────────────────────\n\n/**\n * Whether a predicate supports multiple values on the same subject.\n * Multi-value predicates don't trigger conflict detection in the Thalamus.\n */\n/**\n * Predicates that can have multiple values on the same subject.\n * These don't trigger conflict detection in the Thalamus.\n */\nexport const MULTI_VALUE_PREDICATES = new Set<string>([\n // Events — multiple things happen over time\n EventPredicate.STATUS_CHANGE,\n EventPredicate.EVENT,\n EventPredicate.DECISION,\n EventPredicate.OUTCOME,\n // Emotional — multiple sentiments about different things\n RapportPredicate.SENTIMENT,\n RapportPredicate.FRUSTRATION,\n RapportPredicate.EXCITEMENT,\n RapportPredicate.CONCERN,\n RapportPredicate.GOAL,\n RapportPredicate.INTEREST,\n // Memory — multiple reminders, contexts, projects\n MemoryPredicate.REMINDER,\n MemoryPredicate.CONTEXT_TASK,\n WorkPredicate.CURRENT_PROJECT,\n // Timeline\n 'timeline',\n])\n\n/**\n * Map from relationship type to its reverse.\n * Used by brain.users.registerPerson() to create bidirectional edges.\n */\nexport const REVERSE_RELATIONSHIPS: Record<string, string> = {\n // Proper OrgRelationship values\n [OrgRelationship.REPORTS_TO]: OrgRelationship.MANAGES,\n [OrgRelationship.MANAGES]: OrgRelationship.REPORTS_TO,\n [OrgRelationship.MEMBER_OF]: OrgRelationship.HAS_MEMBER,\n [OrgRelationship.HAS_MEMBER]: OrgRelationship.MEMBER_OF,\n [OrgRelationship.MENTORS]: OrgRelationship.MENTORED_BY,\n [OrgRelationship.MENTORED_BY]: OrgRelationship.MENTORS,\n [OrgRelationship.COLLABORATES_WITH]: OrgRelationship.COLLABORATES_WITH,\n [OrgRelationship.CANDIDATE_FOR]: OrgRelationship.CANDIDATE_FOR,\n [OrgRelationship.STAKEHOLDER_IN]: OrgRelationship.STAKEHOLDER_IN,\n // Agent-facing predicate names → proper relationship types\n // The model sends 'direct_report' as predicate, SDK maps to proper relationships\n 'direct_report': OrgRelationship.REPORTS_TO,\n 'team_member': OrgRelationship.MEMBER_OF,\n 'candidate': OrgRelationship.CANDIDATE_FOR,\n 'manager': OrgRelationship.MANAGES,\n 'stakeholder': OrgRelationship.STAKEHOLDER_IN,\n 'collaborator': OrgRelationship.COLLABORATES_WITH,\n 'mentor': OrgRelationship.MENTORED_BY,\n}\n\n/**\n * Agent-facing labels for relationship types.\n * Used in tool descriptions so the model knows what's available.\n */\nexport const RELATIONSHIP_LABELS: Record<string, string> = {\n [OrgRelationship.REPORTS_TO]: 'reports to (person is a direct report)',\n [OrgRelationship.MANAGES]: 'manages (user is the manager)',\n [OrgRelationship.MEMBER_OF]: 'is a member of (team, project)',\n [OrgRelationship.HOLDS_ROLE]: 'holds a role/position',\n [OrgRelationship.CANDIDATE_FOR]: 'is a candidate for a role',\n [OrgRelationship.COLLABORATES_WITH]: 'collaborates with',\n [OrgRelationship.MENTORS]: 'mentors',\n [OrgRelationship.STAKEHOLDER_IN]: 'is a stakeholder in',\n}\n","/**\n * SubCortex Signal Types\n *\n * Signals represent emotional and rapport-related data that attach to\n * the knowledge they relate to. Unlike assertions, signals:\n * - Compound (never conflict)\n * - Decay over time (exponential, configurable half-life)\n * - Have trajectory (warming/cooling/stable/neutral)\n * - Can be resolved by interaction (not just time)\n *\n * Storage: Signals are assertions with `signal:{type}` predicates.\n * The consumer-facing API treats them as a separate entity.\n */\n\n// ─── Signal Types (Gated + Custom) ────────────────────\n\n/**\n * SYSTEM signal types — available for all tenants.\n * Tenant-specific types use `custom:{tenant}:{type}` convention.\n */\nexport const SYSTEM_SIGNAL_TYPES = [\n 'frustration',\n 'excitement',\n 'concern',\n 'satisfaction',\n 'confusion',\n 'gratitude',\n 'tension',\n 'sentiment',\n] as const\n\nexport type SystemSignalType = typeof SYSTEM_SIGNAL_TYPES[number]\n\n/** Any valid signal type — system or custom */\nexport type SignalType = SystemSignalType | `custom:${string}`\n\nexport function isValidSignalType(type: string): type is SignalType {\n if (SYSTEM_SIGNAL_TYPES.includes(type as SystemSignalType)) return true\n if (type.startsWith('custom:')) return true\n return false\n}\n\n// ─── Decay Configuration ──────────────────────────────\n\n/**\n * Per-type decay half-life in hours.\n * Tuned to match emotional persistence patterns:\n * - Fast decay: confusion (resolves or escalates quickly)\n * - Medium decay: excitement, frustration, tension\n * - Slow decay: concern (persists until addressed), satisfaction/gratitude (positive baseline)\n */\nexport const SIGNAL_DECAY_CONFIG: Record<string, number> = {\n confusion: 8,\n excitement: 16,\n frustration: 18,\n tension: 18,\n sentiment: 24,\n concern: 36,\n satisfaction: 48,\n gratitude: 48,\n _default: 24,\n}\n\nexport function getDecayHalfLife(signalType: string): number {\n return SIGNAL_DECAY_CONFIG[signalType] ?? SIGNAL_DECAY_CONFIG._default\n}\n\n// ─── Trajectory ───────────────────────────────────────\n\nexport type Trajectory = 'warming' | 'cooling' | 'stable' | 'neutral'\n\n// ─── Signal Entry ─────────────────────────────────────\n\n/** A single recorded signal */\nexport interface SignalEntry {\n /** Assertion ID backing this signal */\n id: string\n /** Signal type (e.g., 'frustration', 'excitement') */\n type: string\n /** Human-readable content */\n content: string\n /** Raw recorded intensity (0-1) */\n intensity: number\n /** Time-decayed intensity */\n decayedIntensity: number\n /** Age in hours since recorded */\n ageHours: number\n /** Subject this signal is about (e.g., 'context:hiring', 'person:sarah') */\n aboutSubject?: string\n /** If this signal was resolved by another signal */\n resolvedBy?: string\n /** ISO timestamp when recorded */\n timestamp: string\n}\n\n/** Aggregated snapshot of all signals for a subject */\nexport interface SignalSnapshot {\n /** All signal entries within the query window */\n signals: SignalEntry[]\n /** Overall rapport trajectory */\n trajectory: Trajectory\n /** Aggregate intensity across all active signals */\n aggregateIntensity: number\n}\n\n// ─── Signal Resolution Sets ──────────────────────────\n\n/**\n * Signal types that indicate a positive emotional shift.\n * When recorded with `resolveConflicting: true`, these automatically\n * resolve recent negative signals on the same subject.\n */\nexport const POSITIVE_SIGNALS = new Set<string>([\n 'satisfaction',\n 'excitement',\n 'gratitude',\n])\n\n/**\n * Signal types that indicate a negative emotional state.\n * These are candidates for resolution by a subsequent positive signal.\n */\nexport const NEGATIVE_SIGNALS = new Set<string>([\n 'frustration',\n 'concern',\n 'tension',\n 'confusion',\n])\n\n// ─── Input/Output Types ───────────────────────────────\n\nexport interface RecordSignalInput {\n /** User ID the signal is about */\n userId: string\n /** Signal type */\n type: SignalType\n /** Human-readable description */\n content: string\n /** Intensity 0-1 (default: 0.7) */\n intensity?: number\n /** Subject this signal relates to (e.g., a project, person, topic) */\n aboutSubject?: string\n /** Session ID for contextual binding */\n sessionId?: string\n /**\n * When true and the signal type is a positive signal (satisfaction, excitement, gratitude),\n * automatically resolves recent negative signals on the same subject within the last 72 hours.\n * Resolved signals decay 4x faster. Default: false.\n */\n resolveConflicting?: boolean\n}\n\nexport interface SignalQueryOptions {\n /** Window in hours to look back (default: 72) */\n windowHours?: number\n /** Filter to specific signal type */\n type?: string\n}\n\nexport interface ResolveSignalInput {\n /** ID of the signal being resolved */\n signalId: string\n /** ID of the signal that resolves it */\n resolvedBySignalId: string\n}\n","/**\n * SubCortex Signals Namespace\n *\n * Records and queries emotional/rapport signals. Signals attach to\n * the knowledge they relate to and provide temporal decay + trajectory.\n *\n * Signals are stored as assertions with `signal:{type}` predicates.\n * The consumer sees them as a separate entity via this namespace.\n */\n\nimport type { HttpTransport } from './http'\nimport type { Assertion } from './client'\nimport type {\n SignalEntry,\n SignalSnapshot,\n RecordSignalInput,\n SignalQueryOptions,\n ResolveSignalInput,\n Trajectory,\n} from './types/signals'\nimport {\n isValidSignalType,\n getDecayHalfLife,\n SYSTEM_SIGNAL_TYPES,\n POSITIVE_SIGNALS,\n NEGATIVE_SIGNALS,\n} from './types/signals'\nimport { SubjectPrefix, subject } from './types/schema'\n\n/** Shape returned by the engine's GET /api/v1/signals/:tenant/:subject */\ninterface EngineSignalQueryResponse {\n signals: Array<{\n assertion_id: string\n signal_type: string\n content: string\n intensity: number\n decayed_intensity: number\n age_hours: number\n about_subject: string | null\n resolved_by: string | null\n timestamp: string\n }>\n trajectory: string\n aggregate_intensity: number\n}\n\n/** Predicates from legacy rapport recording (pre-signal: namespace) */\nconst LEGACY_SIGNAL_PREDICATES = new Set([\n 'sentiment', 'frustration', 'excitement', 'concern',\n 'goal', 'aspiration', 'preference', 'interest',\n])\n\nexport class SignalsNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /**\n * Record an emotional signal about a user.\n *\n * @example\n * ```typescript\n * await brain.signals.record({\n * userId: 'cmk123',\n * type: 'frustration',\n * content: 'Frustrated about the hiring timeline',\n * intensity: 0.85,\n * aboutSubject: 'context:hiring-ea',\n * })\n * ```\n */\n async record(input: RecordSignalInput): Promise<{ id: string; resolved?: number }> {\n if (!isValidSignalType(input.type)) {\n throw new Error(`Invalid signal type: ${input.type}. Use one of: ${SYSTEM_SIGNAL_TYPES.join(', ')} or custom:{tenant}:{type}`)\n }\n\n const userSubject = subject(SubjectPrefix.USER, input.userId)\n const predicate = `signal:${input.type}`\n const value = {\n content: input.content,\n intensity: input.intensity ?? 0.7,\n about_subject: input.aboutSubject || null,\n }\n\n const result = await this.http.post<Assertion>('/api/v1/assertions', {\n tenant_id: this.tenantId,\n subject: userSubject,\n predicate,\n value,\n confidence: input.intensity ?? 0.7,\n ...(input.sessionId ? { session_id: input.sessionId } : {}),\n })\n\n // Auto-resolve negative signals when a positive signal is recorded\n let resolved = 0\n if (input.resolveConflicting && POSITIVE_SIGNALS.has(input.type)) {\n try {\n const snapshot = await this.query(userSubject, { windowHours: 72 })\n for (const sig of snapshot.signals) {\n if (!NEGATIVE_SIGNALS.has(sig.type)) continue\n if (sig.resolvedBy) continue\n const sameContext = input.aboutSubject\n ? sig.aboutSubject === input.aboutSubject\n : !sig.aboutSubject\n if (sameContext) {\n await this.resolve({ signalId: sig.id, resolvedBySignalId: result.id })\n resolved++\n }\n }\n } catch {\n // Non-critical — signal was recorded successfully\n }\n }\n\n return { id: result.id, ...(resolved > 0 && { resolved }) }\n }\n\n /**\n * Query signals for a user with computed decay and trajectory.\n * Delegates to the engine's signal query endpoint for server-side computation.\n *\n * @example\n * ```typescript\n * const snapshot = await brain.signals.query('user:cmk123', {\n * windowHours: 72,\n * type: 'frustration',\n * })\n * ```\n */\n async query(userSubject: string, options: SignalQueryOptions = {}): Promise<SignalSnapshot> {\n const windowHours = options.windowHours ?? 72\n\n const query: Record<string, string> = { window: String(windowHours) }\n if (options.type) query.type = options.type\n\n const qs = new URLSearchParams(query).toString()\n const response = await this.http.get<EngineSignalQueryResponse>(\n `/api/v1/signals/${enc(this.tenantId)}/${enc(userSubject)}?${qs}`\n )\n\n const signals: SignalEntry[] = response.signals.map(s => ({\n id: s.assertion_id,\n type: s.signal_type,\n content: s.content,\n intensity: s.intensity,\n decayedIntensity: s.decayed_intensity,\n ageHours: Math.round(s.age_hours * 10) / 10,\n aboutSubject: s.about_subject || undefined,\n resolvedBy: s.resolved_by || undefined,\n timestamp: s.timestamp,\n }))\n\n return {\n signals,\n trajectory: response.trajectory as Trajectory,\n aggregateIntensity: response.aggregate_intensity,\n }\n }\n\n /**\n * Resolve a signal — mark it as resolved by a subsequent positive interaction.\n * The resolved signal's effective intensity drops faster.\n *\n * @example\n * ```typescript\n * await brain.signals.resolve({\n * signalId: 'abc123',\n * resolvedBySignalId: 'def456',\n * })\n * ```\n */\n async resolve(input: ResolveSignalInput): Promise<{ success: boolean }> {\n // Supersede the original assertion with an updated value that includes resolved_by\n const original = await this.http.get<Assertion>(\n `/api/v1/assertions/${enc(this.tenantId)}/${enc(input.signalId)}`\n ).catch(() => null)\n\n if (!original) return { success: false }\n\n const value = typeof original.value === 'object' && original.value !== null\n ? { ...(original.value as Record<string, unknown>), resolved_by: input.resolvedBySignalId }\n : { content: String(original.value), resolved_by: input.resolvedBySignalId }\n\n await this.http.post('/api/v1/assertions/supersede', {\n tenant_id: this.tenantId,\n original_assertion_id: input.signalId,\n subject: original.subject,\n predicate: original.predicate,\n value,\n confidence: original.confidence,\n })\n\n return { success: true }\n }\n}\n\n// ─── Pure Computation Functions ───────────────────────\n// @internal — computeDecay is still needed by extractSignals() for users.identify(),\n// which builds signal entries from raw assertions. Trajectory computation has been\n// moved to the engine (SignalIndex::compute_trajectory in cortex-storage).\n\n/**\n * Exponential decay: intensity × 2^(-age / halfLife)\n * Resolved signals decay 4x faster.\n */\nexport function computeDecay(\n intensity: number,\n ageHours: number,\n halfLifeHours: number,\n isResolved: boolean = false\n): number {\n const effectiveHalfLife = isResolved ? halfLifeHours / 4 : halfLifeHours\n const decayed = intensity * Math.pow(2, -ageHours / effectiveHalfLife)\n return Math.round(decayed * 100) / 100\n}\n\n// ─── Helpers ──────────────────────────────────────────\n\n/**\n * Extract signal entries from a list of assertions.\n * Used by users.identify() to populate the signals field.\n */\nexport function extractSignals(\n assertions: Assertion[],\n windowHours: number = 72\n): SignalEntry[] {\n const now = Date.now()\n const windowMs = windowHours * 60 * 60 * 1000\n const entries: SignalEntry[] = []\n\n for (const a of assertions) {\n if (a.isSuperseded) continue\n const isSignal = a.predicate.startsWith('signal:')\n const isLegacy = LEGACY_SIGNAL_PREDICATES.has(a.predicate)\n if (!isSignal && !isLegacy) continue\n\n const timestamp = a.validFrom\n const ageMs = now - new Date(timestamp).getTime()\n if (ageMs > windowMs) continue\n\n const ageHours = ageMs / (60 * 60 * 1000)\n const type = isSignal ? a.predicate.slice(7) : a.predicate\n const halfLife = getDecayHalfLife(type)\n\n let content = ''\n let intensity = a.confidence ?? 0.7\n let aboutSubject: string | undefined\n let resolvedBy: string | undefined\n\n if (typeof a.value === 'object' && a.value !== null) {\n const v = a.value as Record<string, unknown>\n content = (v.content as string) || ''\n intensity = (v.intensity as number) ?? intensity\n aboutSubject = (v.about_subject as string) || undefined\n resolvedBy = (v.resolved_by as string) || undefined\n } else {\n content = String(a.value)\n }\n\n entries.push({\n id: a.id,\n type,\n content,\n intensity,\n decayedIntensity: computeDecay(intensity, ageHours, halfLife, !!resolvedBy),\n ageHours: Math.round(ageHours * 10) / 10,\n aboutSubject,\n resolvedBy,\n timestamp,\n })\n }\n\n entries.sort((a, b) => a.ageHours - b.ageHours)\n return entries\n}\n\nfunction enc(s: string): string {\n return encodeURIComponent(s)\n}\n","/**\n * SubCortex Users Namespace\n *\n * High-level operations for user rapport building.\n * This is where orchestration logic lives — NOT in the consumer's proxy.\n *\n * The consumer agent calls brain.users.identify() and gets back\n * a complete picture. One call, one round-trip, full context.\n */\n\nimport type { HttpTransport } from './http'\nimport type { Assertion, IntakeResult } from './client'\nimport type {\n IdentifyUserInput,\n UserIdentification,\n UserMemory,\n ConnectedPerson,\n ConflictItem,\n RegisterPersonInput,\n RegisterPersonResult,\n RecordRapportInput,\n} from './types/users'\nimport {\n SubjectPrefix,\n subject,\n confidenceToScore,\n ConfidenceLevel,\n REVERSE_RELATIONSHIPS,\n OrgRelationship,\n} from './types/schema'\nimport type { Trajectory } from './types/signals'\nimport { extractSignals } from './signals'\n\nexport class UsersNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /**\n * Identify a user and retrieve their full context.\n *\n * This is the FIRST thing an agent should call at session start.\n * Returns whether the user is known, their memories, connected\n * people, reminders, conflicts, and a summary.\n *\n * @example\n * ```typescript\n * const user = await brain.users.identify({\n * userId: 'cmk123...',\n * displayName: 'Tom Santos',\n * })\n *\n * if (!user.isKnown) {\n * // First encounter — get to know them\n * } else {\n * // Returning user — reference what you know\n * // user.reminders — bring these up\n * // user.conflicts — address these\n * // user.connectedPeople — context about their org\n * }\n * ```\n */\n async identify(input: IdentifyUserInput): Promise<UserIdentification> {\n const userSubject = subject(SubjectPrefix.USER, input.userId)\n\n // 1. Get all assertions about this user\n const assertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(this.tenantId)}/${enc(userSubject)}`\n )\n\n const active = assertions.filter(a => !a.isSuperseded)\n const isKnown = active.length > 0\n\n // 2. Seed display name if first encounter\n if (input.displayName && !active.some(a => a.predicate === 'name' || a.predicate === 'full_name')) {\n try {\n await this.http.post('/api/v1/assertions', {\n tenant_id: this.tenantId,\n subject: userSubject,\n predicate: 'name',\n value: input.displayName,\n confidence: 1.0,\n })\n } catch { /* best-effort */ }\n }\n\n // 3. Get user's name\n const nameAssertion = active.find(a => a.predicate === 'name' || a.predicate === 'full_name')\n const name = (nameAssertion?.value as string) || input.displayName || null\n\n // 4. Categorize assertions\n const reminders: UserMemory[] = active\n .filter(a => a.predicate === 'reminder')\n .map(a => ({ id: a.id, predicate: a.predicate, value: a.value, confidence: a.confidence, createdAt: a.validFrom }))\n\n // Auto-dismiss reminders after returning them.\n // Once surfaced, they shouldn't repeat. If the user wants to\n // keep a reminder alive, they'll say so and the agent will recreate it.\n for (const reminder of reminders) {\n try {\n await this.http.post(\n `/api/v1/assertions/retract/${enc(this.tenantId)}/${enc(reminder.id)}`,\n {}\n )\n } catch { /* best-effort — don't block recall if retract fails */ }\n }\n\n const contexts: UserMemory[] = active\n .filter(a => a.predicate === 'context' || a.predicate === 'context:task')\n .map(a => ({ id: a.id, predicate: a.predicate, value: a.value, confidence: a.confidence, createdAt: a.validFrom }))\n\n // 5a. Extract signals (signal:* predicates + legacy rapport predicates)\n const signals = extractSignals(assertions)\n const signalIds = new Set(signals.map(s => s.id))\n\n // Get trajectory from the engine (server-side computation)\n let rapportTrajectory: Trajectory = 'neutral'\n try {\n const qs = new URLSearchParams({ window: '72' }).toString()\n const snapshot = await this.http.get<{ trajectory: Trajectory }>(\n `/api/v1/signals/${enc(this.tenantId)}/${enc(userSubject)}?${qs}`\n )\n rapportTrajectory = snapshot.trajectory\n } catch { /* Non-critical — default to neutral */ }\n\n const memories: UserMemory[] = active\n .filter(a =>\n a.predicate !== 'reminder' &&\n a.predicate !== 'context' &&\n a.predicate !== 'context:task' &&\n !signalIds.has(a.id) // exclude signals from memories\n )\n .map(a => ({ id: a.id, predicate: a.predicate, value: a.value, confidence: a.confidence, createdAt: a.validFrom }))\n\n // 5. Traverse relationships to find connected people\n const connectedPeople: ConnectedPerson[] = []\n try {\n const relationships = await this.http.get<Array<{\n fromSubject: string; toSubject: string; relationshipType: string\n }>>(`/api/v1/relationships/${enc(this.tenantId)}/${enc(userSubject)}`)\n\n const visited = new Set<string>()\n for (const rel of relationships) {\n const other = rel.fromSubject === userSubject ? rel.toSubject : rel.fromSubject\n if (!other || other === userSubject || visited.has(other)) continue\n visited.add(other)\n\n const personAssertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(this.tenantId)}/${enc(other)}`\n )\n const personActive = personAssertions.filter(a => !a.isSuperseded)\n const personName = personActive.find(a => a.predicate === 'name')\n const facts = personActive\n .filter(a => a.predicate !== 'name')\n .map(a => ({ predicate: a.predicate, value: a.value }))\n\n connectedPeople.push({\n subject: other,\n name: (personName?.value as string) || other,\n relationship: rel.relationshipType,\n facts,\n })\n }\n } catch { /* non-critical */ }\n\n // 6. Check Thalamus queue for conflicts relevant to THIS user\n const conflicts: ConflictItem[] = []\n try {\n if (!input.agentId) throw new Error('agentId is required on IdentifyUserInput to fetch conflicts')\n const pending = await this.http.get<Array<{\n id: string; surfacingHint: string; acknowledged: boolean; status: string;\n persistedAssertionIds?: string[]; conflictingAssertionId?: string\n }>>(`/api/v1/intake/pending/${enc(input.agentId)}?status=conflict_detected`)\n\n for (const item of pending) {\n if (item.acknowledged) continue\n\n // Only surface conflicts that mention this user's subject\n const hint = item.surfacingHint || ''\n const involvesUser = hint.includes(userSubject)\n || (item.persistedAssertionIds || []).some(id => {\n // Check if any persisted assertion is about this user\n const a = assertions.find(a2 => a2.id === id)\n return a?.subject === userSubject\n })\n\n if (!involvesUser) continue\n\n let resolvedHint = hint || 'A conflict was detected.'\n if (name) {\n resolvedHint = resolvedHint.replace(\n new RegExp(userSubject.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'g'),\n name\n )\n }\n conflicts.push({ id: item.id, hint: resolvedHint })\n }\n } catch { /* non-critical */ }\n\n // 7. Build summary\n const parts: string[] = []\n if (conflicts.length > 0) {\n parts.push(`ATTENTION: ${conflicts.length} knowledge conflict(s) — MUST address: ${conflicts.map(c => c.hint).join(' | ')}`)\n }\n if (reminders.length > 0) {\n parts.push(`REMINDERS (${reminders.length}): ${reminders.map(r => `\"${r.value}\"`).join(', ')}. Dismiss each after surfacing.`)\n }\n if (connectedPeople.length > 0) {\n parts.push(`Connected people:\\n${connectedPeople.map(p => {\n const factsStr = p.facts.map(f => `${f.predicate}: ${f.value}`).join(', ')\n return `- ${p.name} (${p.relationship})${factsStr ? ': ' + factsStr : ''}`\n }).join('\\n')}`)\n }\n if (memories.length > 0 && parts.length === 0) {\n parts.push(`You know ${memories.length} things about this user.`)\n }\n if (parts.length === 0) {\n parts.push('This is a new user — no memories yet. Get to know them.')\n }\n\n return {\n subject: userSubject,\n isKnown,\n name,\n memories,\n connectedPeople,\n reminders,\n contexts,\n conflicts,\n signals,\n rapportTrajectory,\n summary: parts.join('\\n'),\n }\n }\n\n /**\n * Register a person that the user mentioned.\n *\n * Creates the person node, their role, and bidirectional\n * relationships to the user. One call does everything.\n *\n * @example\n * ```typescript\n * const result = await brain.users.registerPerson({\n * name: 'John Smith',\n * userId: 'cmk123...',\n * relationship: 'direct_report',\n * role: 'VP of Engineering',\n * })\n * ```\n */\n async registerPerson(input: RegisterPersonInput): Promise<RegisterPersonResult> {\n const userSubject = subject(SubjectPrefix.USER, input.userId)\n const personSubject = subject(SubjectPrefix.PERSON, input.name)\n const conf = typeof input.confidence === 'number'\n ? input.confidence\n : confidenceToScore(input.confidence || ConfidenceLevel.CONFIRMED)\n\n let assertionsCreated = 0\n let relationshipsCreated = 0\n const warnings: string[] = []\n\n // Route ALL assertions through Thalamus for conflict detection, dedup, and signal classification\n const candidates: Array<{\n subject: string; predicate: string; value: unknown;\n source_confidence: number; provenance: string\n }> = []\n\n // Person identity\n candidates.push({ subject: personSubject, predicate: 'name', value: input.name, source_confidence: conf, provenance: 'agent' })\n\n // Role\n if (input.role) {\n candidates.push({ subject: personSubject, predicate: 'role', value: input.role, source_confidence: conf, provenance: 'agent' })\n\n // Check if someone else holds this role (warning only, Thalamus handles conflicts)\n try {\n const allAssertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/list/${enc(this.tenantId)}`\n )\n const sameRole = allAssertions.filter(a =>\n a.subject.startsWith('person:') &&\n a.subject !== personSubject &&\n a.predicate === 'role' &&\n a.value === input.role &&\n !a.isSuperseded\n )\n if (sameRole.length > 0) {\n const otherAssertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(this.tenantId)}/${enc(sameRole[0].subject)}`\n )\n const otherName = otherAssertions.find(a => a.predicate === 'name')?.value || sameRole[0].subject\n warnings.push(`\"${input.role}\" is already held by ${otherName}. Is ${otherName} no longer in this role?`)\n }\n } catch { /* non-critical */ }\n }\n\n // Details\n if (input.details) {\n candidates.push({ subject: personSubject, predicate: 'details', value: input.details, source_confidence: conf, provenance: 'agent' })\n }\n\n // Status\n candidates.push({\n subject: personSubject, predicate: 'status',\n value: input.relationship === 'candidate' ? 'candidate' : 'active',\n source_confidence: conf, provenance: 'agent',\n })\n\n // Submit through Thalamus\n const correlationId = `register_person_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`\n const intakeResult = await this.http.post<IntakeResult>('/api/v1/intake/submit', {\n correlation_id: correlationId,\n agent_id: 'sdk',\n tenant_id: this.tenantId,\n candidates,\n context: input.sessionId ? { sessionId: input.sessionId } : undefined,\n })\n\n assertionsCreated = intakeResult.accepted + intakeResult.reinforced\n if (intakeResult.conflicts > 0) {\n const conflictItems = (intakeResult.items || []).filter(\n (i: { status: string }) => i.status === 'conflict_detected'\n )\n for (const item of conflictItems) {\n warnings.push(item.surfacingHint || 'A conflict was detected with existing data.')\n }\n }\n\n // Relationships still go direct (they don't have conflict semantics)\n if (input.role) {\n const roleSubject = subject(SubjectPrefix.ROLE, input.role)\n // Role node + holds_role relationship\n await this.http.post('/api/v1/assertions', {\n tenant_id: this.tenantId, subject: roleSubject, predicate: 'name', value: input.role, confidence: conf,\n })\n await this.http.post('/api/v1/relationships', {\n tenant_id: this.tenantId, from_subject: personSubject, to_subject: roleSubject,\n relationship_type: OrgRelationship.HOLDS_ROLE, confidence: conf,\n })\n relationshipsCreated++\n }\n\n // Normalize relationship types\n const FORWARD_MAP: Record<string, string> = {\n 'direct_report': OrgRelationship.MANAGES,\n 'team_member': OrgRelationship.HAS_MEMBER,\n 'candidate': OrgRelationship.MANAGES,\n 'manager': OrgRelationship.REPORTS_TO,\n 'stakeholder': OrgRelationship.STAKEHOLDER_IN,\n 'collaborator': OrgRelationship.COLLABORATES_WITH,\n 'mentor': OrgRelationship.MENTORS,\n }\n\n const forwardType = FORWARD_MAP[input.relationship] || input.relationship\n const reverseType = REVERSE_RELATIONSHIPS[input.relationship] || REVERSE_RELATIONSHIPS[forwardType] || input.relationship\n\n // User → Person\n await this.http.post('/api/v1/relationships', {\n tenant_id: this.tenantId, from_subject: userSubject, to_subject: personSubject,\n relationship_type: forwardType, confidence: conf,\n })\n relationshipsCreated++\n\n // Person → User (reverse)\n await this.http.post('/api/v1/relationships', {\n tenant_id: this.tenantId, from_subject: personSubject, to_subject: userSubject,\n relationship_type: reverseType, confidence: conf,\n })\n relationshipsCreated++\n\n return { personSubject, assertionsCreated, relationshipsCreated, warnings }\n }\n\n /**\n * Record an emotional state or rapport signal about the user.\n *\n * @example\n * ```typescript\n * await brain.users.recordRapport({\n * userId: 'cmk123...',\n * type: 'frustration',\n * value: 'Frustrated about losing the EA candidate',\n * aboutPerson: 'Sarah Johnson',\n * })\n * ```\n */\n async recordRapport(input: RecordRapportInput): Promise<{ success: boolean }> {\n const userSubject = subject(SubjectPrefix.USER, input.userId)\n const conf = typeof input.confidence === 'number'\n ? input.confidence\n : confidenceToScore(input.confidence || ConfidenceLevel.HIGH)\n\n // Route through Thalamus for conflict detection and signal classification\n const candidates: Array<{\n subject: string; predicate: string; value: unknown;\n source_confidence: number; provenance: string\n }> = [\n { subject: userSubject, predicate: input.type, value: input.value, source_confidence: conf, provenance: 'agent' },\n ]\n\n // If about a specific person, add a timeline entry candidate\n if (input.aboutPerson) {\n const personSubject = subject(SubjectPrefix.PERSON, input.aboutPerson)\n candidates.push({\n subject: personSubject, predicate: 'timeline', value: input.value,\n source_confidence: conf, provenance: 'agent',\n })\n }\n\n const correlationId = `rapport_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`\n await this.http.post<IntakeResult>('/api/v1/intake/submit', {\n correlation_id: correlationId,\n agent_id: 'sdk',\n tenant_id: this.tenantId,\n candidates,\n ...(input.sessionId ? { context: { session_id: input.sessionId } } : {}),\n })\n\n return { success: true }\n }\n\n /**\n * Dismiss a reminder after the agent has surfaced it.\n */\n async dismissReminder(userId: string, reminderContent: string): Promise<{ success: boolean }> {\n const userSubject = subject(SubjectPrefix.USER, userId)\n const assertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(this.tenantId)}/${enc(userSubject)}`\n )\n\n const reminder = assertions.find(\n a => a.predicate === 'reminder' && !a.isSuperseded &&\n (a.value as string).toLowerCase().includes(reminderContent.toLowerCase())\n )\n\n if (reminder) {\n await this.http.post(`/api/v1/assertions/retract/${enc(this.tenantId)}/${enc(reminder.id)}`, {})\n return { success: true }\n }\n return { success: false }\n }\n}\n\nfunction enc(s: string): string {\n return encodeURIComponent(s)\n}\n","/**\n * Rule types — typed code guardrails stored as assertions.\n *\n * Rules are assertions with structured predicates (`rule:banned_pattern`,\n * `rule:required_pattern`, etc.) and typed values. The engine stores them\n * identically to any other assertion — same WAL, same content-addressable IDs,\n * same temporal model, same supersession chain.\n *\n * The RulesNamespace provides typed CRUD and file-scope matching on top of\n * the raw assertion layer, so consumers don't parse JSON blobs in hooks.\n */\n\n// ─── Rule Types ─────────────────────────────────────\n\n/** The kind of enforcement a rule performs. */\nexport type RuleType =\n | 'banned_pattern' // Regex that must NOT appear in matching files\n | 'required_pattern' // Regex that MUST appear in matching files\n | 'file_constraint' // Constraint on a specific file or path\n | 'requires_propagation' // A change in scope X must propagate to Y\n\n/** How the system responds to a violation. */\nexport type RuleSeverity =\n | 'block' // Exit code 2 — tool call blocked, Claude retries\n | 'warn' // Injected as strong guidance, not enforced\n | 'info' // Contextual — available for recall, not proactively injected\n\n/** Well-known rule predicates. Scoped under `rule:` to avoid collision with general assertions. */\nexport const RulePredicates = {\n BANNED_PATTERN: 'rule:banned_pattern',\n REQUIRED_PATTERN: 'rule:required_pattern',\n FILE_CONSTRAINT: 'rule:file_constraint',\n REQUIRES_PROPAGATION: 'rule:requires_propagation',\n} as const\n\nexport type RulePredicate = typeof RulePredicates[keyof typeof RulePredicates]\n\n// ─── Rule Value (structured, not a JSON blob) ──────\n\n/** The typed structure stored in the assertion value field. */\nexport interface RuleValue {\n /** Regex pattern to match against file content (banned/required pattern rules). */\n pattern?: string\n /** Glob or regex for which files this rule applies to. If omitted, applies to all files. */\n fileScope?: string\n /** Human-readable description of what this rule enforces and why. */\n description: string\n /** What surfaces must be updated when this rule's scope is changed (propagation rules). */\n propagatesTo?: string[]\n}\n\n// ─── Rule (parsed assertion) ────────────────────────\n\n/** A rule — a typed, parsed view of an enforcement assertion. */\nexport interface Rule {\n /** Assertion ID (content-addressable BLAKE3 hash) */\n id: string\n /** Tenant this rule belongs to */\n tenantId: string\n /** Subject scope — e.g. `project:{id}`, `intent:api`, `file:prisma/schema.prisma` */\n subject: string\n /** Rule type — which enforcement behavior this rule triggers */\n type: RuleType\n /** The full typed predicate, e.g. `rule:banned_pattern` */\n predicate: RulePredicate\n /** Structured rule configuration */\n value: RuleValue\n /** Severity — block (enforcement), warn (guidance), info (context) */\n severity: RuleSeverity\n /** Confidence score from the underlying assertion */\n confidence: number\n /** When this rule became active */\n validFrom: string\n /** Whether this rule has been superseded by a newer version */\n isSuperseded: boolean\n}\n\n// ─── Input Types ────────────────────────────────────\n\n/** Input for creating a rule. */\nexport interface CreateRuleInput {\n /** Subject scope — e.g. `project:{id}`, `intent:api`, `file:src/db/schema.ts` */\n subject: string\n /** Rule type */\n type: RuleType\n /** Regex pattern (for banned_pattern and required_pattern) */\n pattern?: string\n /** File scope glob/regex — which files this rule applies to */\n fileScope?: string\n /** Human-readable description of the rule and its rationale */\n description: string\n /** Surfaces that must be updated (for requires_propagation rules) */\n propagatesTo?: string[]\n /** Severity — defaults to 'block' for confidence 1.0, 'warn' for >= 0.7, 'info' otherwise */\n severity?: RuleSeverity\n /** Confidence — defaults to 1.0 (enforcement). Set lower for guidance/context. */\n confidence?: number\n /** Override tenant ID */\n tenantId?: string\n}\n\n/** Input for updating (superseding) a rule. */\nexport interface UpdateRuleInput {\n /** ID of the rule to supersede */\n ruleId: string\n /** Updated fields (only provided fields change; others carry forward) */\n pattern?: string\n fileScope?: string\n description?: string\n propagatesTo?: string[]\n severity?: RuleSeverity\n confidence?: number\n /** Override tenant ID */\n tenantId?: string\n}\n\n/** Options for querying rules. */\nexport interface RuleQueryOptions {\n /** Filter by rule type */\n type?: RuleType\n /** Filter by severity */\n severity?: RuleSeverity\n /** Include superseded rules in results (default: false) */\n includeSuperseded?: boolean\n /** Override tenant ID */\n tenantId?: string\n}\n","/**\n * RulesNamespace — typed code guardrails stored as assertions.\n *\n * Rules are assertions with `rule:*` predicates and structured values.\n * This namespace provides typed CRUD, file-scope matching, and intent-based\n * queries so consumers work with `Rule` objects instead of raw assertions\n * with JSON blobs stuffed into the value field.\n *\n * @example\n * ```typescript\n * // Create a rule\n * const rule = await subcortex.rules.create({\n * subject: 'intent:api',\n * type: 'banned_pattern',\n * pattern: 'NextResponse\\\\.json\\\\(',\n * fileScope: 'app/api/.*\\\\.ts$',\n * description: 'Use apiSuccess() instead of NextResponse.json()',\n * })\n *\n * // Get all rules that apply to a file\n * const rules = await subcortex.rules.forFile('app/api/users/route.ts')\n *\n * // Get enforcement rules only\n * const enforcement = await subcortex.rules.list({ severity: 'block' })\n * ```\n */\n\nimport type { HttpTransport } from './http'\nimport type { Assertion } from './client'\nimport {\n RulePredicates,\n type Rule,\n type RuleType,\n type RuleValue,\n type RuleSeverity,\n type RulePredicate,\n type CreateRuleInput,\n type UpdateRuleInput,\n type RuleQueryOptions,\n} from './types/rules'\n\nconst RULE_PREDICATE_PREFIX = 'rule:'\n\n/** Maps RuleType → full predicate string */\nconst TYPE_TO_PREDICATE: Record<RuleType, RulePredicate> = {\n banned_pattern: RulePredicates.BANNED_PATTERN,\n required_pattern: RulePredicates.REQUIRED_PATTERN,\n file_constraint: RulePredicates.FILE_CONSTRAINT,\n requires_propagation: RulePredicates.REQUIRES_PROPAGATION,\n}\n\n/** Maps confidence → default severity */\nfunction defaultSeverity(confidence: number): RuleSeverity {\n if (confidence >= 1.0) return 'block'\n if (confidence >= 0.7) return 'warn'\n return 'info'\n}\n\nexport class RulesNamespace {\n private http: HttpTransport\n private tenantId: string\n\n constructor(http: HttpTransport, tenantId: string) {\n this.http = http\n this.tenantId = tenantId\n }\n\n /**\n * Create a new rule.\n *\n * Stores an assertion with a `rule:*` predicate and a typed value.\n * Defaults to confidence 1.0 (enforcement) if not specified.\n *\n * @example\n * ```typescript\n * await subcortex.rules.create({\n * subject: 'project:my-project',\n * type: 'banned_pattern',\n * pattern: 'as any',\n * description: 'No any casts — use proper types',\n * })\n * ```\n */\n async create(input: CreateRuleInput): Promise<Rule> {\n const confidence = input.confidence ?? 1.0\n const severity = input.severity ?? defaultSeverity(confidence)\n\n const ruleValue: RuleValue = {\n description: input.description,\n pattern: input.pattern,\n fileScope: input.fileScope,\n propagatesTo: input.propagatesTo,\n }\n\n const assertion = await this.http.post<Assertion>(\n `/api/v1/assertions`,\n {\n subject: input.subject,\n predicate: TYPE_TO_PREDICATE[input.type],\n value: { ...ruleValue, severity },\n confidence,\n tenant_id: input.tenantId ?? this.tenantId,\n },\n input.tenantId ?? this.tenantId,\n )\n\n return parseRule(assertion)\n }\n\n /**\n * Get a rule by its assertion ID.\n */\n async get(ruleId: string, options?: { tenantId?: string }): Promise<Rule> {\n const tenant = options?.tenantId ?? this.tenantId\n const assertion = await this.http.get<Assertion>(\n `/api/v1/assertions/${enc(tenant)}/${enc(ruleId)}`,\n )\n return parseRule(assertion)\n }\n\n /**\n * List all rules for this project, optionally filtered by type or severity.\n */\n async list(options?: RuleQueryOptions): Promise<Rule[]> {\n const tenant = options?.tenantId ?? this.tenantId\n const assertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/list/${enc(tenant)}`,\n )\n\n return assertions\n .filter((a) => isRuleAssertion(a))\n .filter((a) => options?.includeSuperseded || !a.isSuperseded)\n .map(parseRule)\n .filter((r) => !options?.type || r.type === options.type)\n .filter((r) => !options?.severity || r.severity === options.severity)\n }\n\n /**\n * Get all rules whose fileScope matches the given file path.\n *\n * This is the primary query for the PreToolUse hook — \"what rules apply\n * to the file I'm about to modify?\"\n *\n * @example\n * ```typescript\n * const rules = await subcortex.rules.forFile('app/api/users/route.ts')\n * // Returns banned_pattern and required_pattern rules whose fileScope\n * // matches the path, plus any project-wide rules without a fileScope.\n * ```\n */\n async forFile(filePath: string, options?: RuleQueryOptions): Promise<Rule[]> {\n const allRules = await this.list(options)\n\n return allRules.filter((rule) => {\n // Rules with no fileScope apply to all files\n if (!rule.value.fileScope) return true\n\n // Match fileScope as regex against the file path\n try {\n const regex = new RegExp(rule.value.fileScope)\n return regex.test(filePath)\n } catch {\n // Invalid regex — skip this rule\n return false\n }\n })\n }\n\n /**\n * Get all rules scoped to a specific intent subject.\n *\n * @example\n * ```typescript\n * const apiRules = await subcortex.rules.forIntent('api')\n * // Queries subject \"intent:api\" for all rule assertions\n * ```\n */\n async forIntent(intent: string, options?: RuleQueryOptions): Promise<Rule[]> {\n const tenant = options?.tenantId ?? this.tenantId\n const subject = intent.startsWith('intent:') ? intent : `intent:${intent}`\n\n const assertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(tenant)}/${enc(subject)}`,\n )\n\n return assertions\n .filter((a) => isRuleAssertion(a))\n .filter((a) => options?.includeSuperseded || !a.isSuperseded)\n .map(parseRule)\n .filter((r) => !options?.type || r.type === options.type)\n .filter((r) => !options?.severity || r.severity === options.severity)\n }\n\n /**\n * Get all rules scoped to a specific subject (project, file, intent, etc.).\n */\n async forSubject(subject: string, options?: RuleQueryOptions): Promise<Rule[]> {\n const tenant = options?.tenantId ?? this.tenantId\n\n const assertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(tenant)}/${enc(subject)}`,\n )\n\n return assertions\n .filter((a) => isRuleAssertion(a))\n .filter((a) => options?.includeSuperseded || !a.isSuperseded)\n .map(parseRule)\n .filter((r) => !options?.type || r.type === options.type)\n .filter((r) => !options?.severity || r.severity === options.severity)\n }\n\n /**\n * Update a rule by superseding it.\n *\n * The old rule is marked as superseded, a new one is created.\n * Full assertion history is preserved.\n */\n async update(input: UpdateRuleInput): Promise<Rule> {\n const tenant = input.tenantId ?? this.tenantId\n\n // Fetch the existing rule to carry forward unchanged fields\n const existing = await this.get(input.ruleId, { tenantId: tenant })\n\n const confidence = input.confidence ?? existing.confidence\n const severity = input.severity ?? existing.severity\n\n const ruleValue: RuleValue = {\n description: input.description ?? existing.value.description,\n pattern: input.pattern ?? existing.value.pattern,\n fileScope: input.fileScope ?? existing.value.fileScope,\n propagatesTo: input.propagatesTo ?? existing.value.propagatesTo,\n }\n\n const assertion = await this.http.post<Assertion>(\n `/api/v1/assertions/supersede`,\n {\n original_assertion_id: input.ruleId,\n subject: existing.subject,\n predicate: existing.predicate,\n value: { ...ruleValue, severity },\n confidence,\n tenant_id: tenant,\n },\n tenant,\n )\n\n return parseRule(assertion)\n }\n\n /**\n * Retract (deactivate) a rule.\n *\n * The assertion's temporal bounds are closed. The rule stops matching\n * in future queries but its history is preserved.\n */\n async retract(ruleId: string, options?: { tenantId?: string }): Promise<void> {\n const tenant = options?.tenantId ?? this.tenantId\n await this.http.post(\n `/api/v1/assertions/retract/${enc(tenant)}/${enc(ruleId)}`,\n {},\n tenant,\n )\n }\n}\n\n// ─── Helpers ────────────────────────────────────────\n\n/** Check if an assertion is a rule (has a `rule:*` predicate). */\nfunction isRuleAssertion(assertion: Assertion): boolean {\n return assertion.predicate?.startsWith(RULE_PREDICATE_PREFIX) ?? false\n}\n\n/** Parse an Assertion into a typed Rule. */\nfunction parseRule(assertion: Assertion): Rule {\n const predicate = assertion.predicate as RulePredicate\n const type = predicate.replace(RULE_PREDICATE_PREFIX, '') as RuleType\n\n // Parse the value — could be a structured object or a legacy JSON string\n let ruleValue: RuleValue\n let severity: RuleSeverity\n\n if (typeof assertion.value === 'object' && assertion.value !== null) {\n const val = assertion.value as Record<string, unknown>\n ruleValue = {\n description: String(val.description ?? ''),\n pattern: val.pattern != null ? String(val.pattern) : undefined,\n fileScope: val.fileScope != null ? String(val.fileScope) : undefined,\n propagatesTo: Array.isArray(val.propagatesTo) ? val.propagatesTo.map(String) : undefined,\n }\n severity = (val.severity as RuleSeverity) ?? defaultSeverity(assertion.confidence)\n } else if (typeof assertion.value === 'string') {\n // Legacy: value is a JSON string (old format) or plain text\n try {\n const parsed = JSON.parse(assertion.value) as Record<string, unknown>\n ruleValue = {\n description: String(parsed.description ?? ''),\n pattern: parsed.pattern != null ? String(parsed.pattern) : undefined,\n fileScope: parsed.filePattern != null ? String(parsed.filePattern) : undefined,\n propagatesTo: Array.isArray(parsed.propagatesTo) ? parsed.propagatesTo.map(String) : undefined,\n }\n severity = (parsed.severity as RuleSeverity) ?? defaultSeverity(assertion.confidence)\n } catch {\n // Plain text value\n ruleValue = { description: String(assertion.value) }\n severity = defaultSeverity(assertion.confidence)\n }\n } else {\n ruleValue = { description: '' }\n severity = defaultSeverity(assertion.confidence)\n }\n\n return {\n id: assertion.id,\n tenantId: assertion.tenantId,\n subject: assertion.subject,\n type,\n predicate,\n value: ruleValue,\n severity,\n confidence: assertion.confidence,\n validFrom: assertion.validFrom,\n isSuperseded: assertion.isSuperseded,\n }\n}\n\nfunction enc(s: string): string {\n return encodeURIComponent(s)\n}\n\nfunction toWire(input: Record<string, unknown>): Record<string, unknown> {\n // Re-use the SDK's toWire for camelCase → snake_case mapping\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(input)) {\n if (value === undefined) continue\n const snakeKey = key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)\n result[snakeKey] = value\n }\n return result\n}\n","/**\n * SubCortexClient — the main entry point for the SubCortex SDK.\n *\n * @example\n * ```typescript\n * import { SubCortexClient } from '@subcortex-ai/sdk'\n *\n * const subcortex = new SubCortexClient({\n * endpoint: 'https://api.subcortex.example.com',\n * tenantId: 'my-tenant',\n * apiKey: 'scx_live_...',\n * })\n *\n * // Create an assertion\n * const assertion = await subcortex.assertions.create({\n * subject: 'user:alice',\n * predicate: 'name',\n * value: 'Alice Smith',\n * })\n *\n * // Query by subject\n * const facts = await subcortex.assertions.query('user:alice')\n *\n * // Create a relationship\n * const rel = await subcortex.relationships.create({\n * fromSubject: 'user:alice',\n * toSubject: 'team:engineering',\n * relationshipType: 'belongs_to',\n * })\n * ```\n */\n\nimport { HttpTransport, toWire, type RetryConfig } from './http'\nimport type { HealthResponse } from './types/common'\nimport { UsersNamespace } from './users'\nimport { SignalsNamespace } from './signals'\nimport { RulesNamespace } from './rules'\n\n// ─── Client Options ─────────────────────────────────\n\nexport interface SubCortexClientOptions {\n /** Base URL of the SubCortex REST API */\n endpoint: string\n /** Tenant ID — required, used as default for all operations */\n tenantId: string\n /** API key for authentication */\n apiKey?: string\n /** JWT token for authentication (alternative to apiKey) */\n token?: string\n /** Retry configuration */\n retry?: Partial<RetryConfig>\n /** Request timeout in milliseconds (default: 30000) */\n timeoutMs?: number\n /** Custom fetch implementation (for testing or Cloudflare Workers) */\n fetch?: typeof fetch\n /** Custom headers added to every request */\n headers?: Record<string, string>\n /** AbortSignal for cancelling all pending requests */\n signal?: AbortSignal\n}\n\n// ─── Assertion Types ────────────────────────────────\n\n/**\n * An assertion — the atomic unit of knowledge in SubCortex.\n *\n * An assertion represents a single claim: \"subject S has property P with value V.\"\n * Assertions are content-addressable (same content = same ID), carry confidence\n * scores, and have temporal bounds.\n *\n * @example\n * ```typescript\n * const fact = await subcortex.assertions.create({\n * subject: 'user:alice',\n * predicate: 'role',\n * value: 'Engineering Manager',\n * confidence: 0.99,\n * })\n * console.log(fact.id) // content-addressable BLAKE3 hash\n * ```\n */\nexport interface Assertion {\n /** Content-addressable ID (BLAKE3 hash of subject + predicate + value + temporal bounds) */\n id: string\n /** Tenant this assertion belongs to */\n tenantId: string\n /** The subject this assertion is about (e.g., `\"user:alice\"`, `\"entity:Project\"`) */\n subject: string\n /** The property being asserted (e.g., `\"name\"`, `\"role\"`, `\"status\"`) */\n predicate: string\n /** The asserted value — can be a string, number, boolean, or object */\n value: unknown\n /** Confidence score (0.0–1.0). Higher = more certain. */\n confidence: number\n /** When this assertion became valid (ISO 8601) */\n validFrom: string\n /** Whether this assertion has been superseded by a newer version */\n isSuperseded: boolean\n}\n\n/**\n * Input for creating an assertion.\n *\n * @example\n * ```typescript\n * await subcortex.assertions.create({\n * subject: 'user:alice',\n * predicate: 'department',\n * value: 'Engineering',\n * confidence: 0.95,\n * })\n * ```\n */\nexport interface CreateAssertionInput {\n /** Subject of the assertion (e.g., `\"user:alice\"`, `\"entity:Project\"`) */\n subject: string\n /** Predicate — what property is being asserted */\n predicate: string\n /** The value being asserted */\n value: unknown\n /** Confidence score 0.0–1.0 (default: server-side default, typically 0.95) */\n confidence?: number\n /** Override the default tenant ID for this operation */\n tenantId?: string\n /** Session ID — binds this assertion to an Experience for session grouping */\n sessionId?: string\n}\n\n/**\n * Input for superseding (updating) an existing assertion.\n *\n * SubCortex assertions are immutable. To \"update\" a fact, you supersede it:\n * the old assertion is marked as superseded and a new one is created.\n *\n * @example\n * ```typescript\n * await subcortex.assertions.supersede({\n * originalAssertionId: 'abc123...',\n * subject: 'user:alice',\n * predicate: 'role',\n * value: 'VP Engineering', // was \"Engineering Manager\"\n * })\n * ```\n */\nexport interface SupersedeAssertionInput {\n /** ID of the assertion being superseded */\n originalAssertionId: string\n /** Subject of the new assertion */\n subject: string\n /** Predicate of the new assertion */\n predicate: string\n /** Updated value */\n value: unknown\n /** Confidence for the new assertion */\n confidence?: number\n /** Override the default tenant ID */\n tenantId?: string\n /** Session ID — binds this assertion to an Experience for session grouping */\n sessionId?: string\n}\n\n// ─── Relationship Types ─────────────────────────────\n\n/** What the SDK returns for a relationship. */\nexport interface Relationship {\n id: string\n tenantId: string\n fromSubject: string\n toSubject: string\n relationshipType: string\n confidence: number\n validFrom: string\n weight: number | null\n properties: Record<string, string>\n}\n\n/** Input for creating a relationship. */\nexport interface CreateRelationshipInput {\n fromSubject: string\n toSubject: string\n relationshipType: string\n confidence?: number\n weight?: number\n properties?: Record<string, string>\n tenantId?: string\n}\n\n// ─── Namespace Classes ──────────────────────────────\n\n/** Operations on assertions — the atomic units of knowledge in SubCortex. */\nexport class AssertionsNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** Create an assertion in the knowledge graph. */\n async create(input: CreateAssertionInput): Promise<Assertion> {\n const tenantId = input.tenantId || this.tenantId\n return this.http.post<Assertion>('/api/v1/assertions', {\n tenant_id: tenantId,\n subject: input.subject,\n predicate: input.predicate,\n value: input.value,\n confidence: input.confidence,\n ...(input.sessionId ? { session_id: input.sessionId } : {}),\n })\n }\n\n /** Get an assertion by its content-addressable ID. */\n async get(assertionId: string, options?: { tenantId?: string }): Promise<Assertion> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<Assertion>(\n `/api/v1/assertions/${enc(tenantId)}/${enc(assertionId)}`\n )\n }\n\n /** Query assertions by subject. */\n async query(subject: string, options?: { tenantId?: string }): Promise<Assertion[]> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(tenantId)}/${enc(subject)}`\n )\n }\n\n /** List all active assertions for the tenant. */\n async list(options?: { tenantId?: string }): Promise<Assertion[]> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<Assertion[]>(\n `/api/v1/assertions/list/${enc(tenantId)}`\n )\n }\n\n /** Supersede an existing assertion with updated values. */\n async supersede(input: SupersedeAssertionInput): Promise<Assertion> {\n const tenantId = input.tenantId || this.tenantId\n return this.http.post<Assertion>('/api/v1/assertions/supersede', {\n tenant_id: tenantId,\n original_assertion_id: input.originalAssertionId,\n subject: input.subject,\n predicate: input.predicate,\n value: input.value,\n confidence: input.confidence,\n ...(input.sessionId ? { session_id: input.sessionId } : {}),\n })\n }\n\n /** Retract an assertion by closing its temporal bounds. */\n async retract(assertionId: string, options?: { tenantId?: string }): Promise<Assertion> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.post<Assertion>(\n `/api/v1/assertions/retract/${enc(tenantId)}/${enc(assertionId)}`,\n {}\n )\n }\n}\n\n/** Operations on relationships — directional edges between subjects. */\nexport class RelationshipsNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** Create a relationship between two subjects. */\n async create(input: CreateRelationshipInput): Promise<Relationship> {\n const tenantId = input.tenantId || this.tenantId\n return this.http.post<Relationship>('/api/v1/relationships', {\n tenant_id: tenantId,\n from_subject: input.fromSubject,\n to_subject: input.toSubject,\n relationship_type: input.relationshipType,\n confidence: input.confidence,\n weight: input.weight,\n properties: input.properties,\n })\n }\n\n /** Get relationships for a subject. */\n async query(subject: string, options?: { tenantId?: string }): Promise<Relationship[]> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<Relationship[]>(\n `/api/v1/relationships/${enc(tenantId)}/${enc(subject)}`\n )\n }\n\n /** List all relationships for the tenant. */\n async list(options?: { tenantId?: string }): Promise<Relationship[]> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<Relationship[]>(\n `/api/v1/relationships/list/${enc(tenantId)}`\n )\n }\n}\n\n// ─── Agent Types ────────────────────────────────────\n\n/**\n * Agent personality — defines how the agent communicates.\n *\n * @example\n * ```typescript\n * const personality: AgentPersonality = {\n * voice: \"Friendly cubicle neighbor who knows the business inside out\",\n * tone: \"casual\",\n * traits: [\"curious\", \"witty\", \"empathetic\"],\n * avoid: [\"corporate speak\", \"jargon\", \"being verbose\"],\n * }\n * ```\n */\nexport interface AgentPersonality {\n /** Overall personality description */\n voice?: string\n /** Communication tone: `\"casual\"`, `\"professional\"`, `\"playful\"` */\n tone?: string\n /** Personality traits */\n traits?: string[]\n /** Things the agent should avoid saying/doing */\n avoid?: string[]\n}\n\n/**\n * Composable instruction sections for an agent.\n *\n * Instructions are broken into sections so they can be independently\n * configured. SubCortex assembles them into a single system prompt\n * via {@link SubCortexClient.agents.getInstructions}.\n */\nexport interface AgentInstructions {\n /** How the agent speaks and presents itself */\n personality?: string\n /** What to remember about users, how to categorize facts */\n memoryGuidance?: string\n /** Domain-specific behavior rules (e.g., schema emergence) */\n domainRules?: string\n /** Organization-specific additions */\n custom?: string\n /** How to greet new vs returning users */\n greetingRules?: string\n /** The agent's purpose, responsibilities, and proactive behaviors */\n goals?: string\n /** How to read and respond to emotional signals and rapport shifts */\n emotionalIntelligence?: string\n /** Guardrails, compliance rules, escalation triggers */\n safety?: string\n}\n\n/**\n * LLM model configuration for the agent.\n */\nexport interface AgentModelConfig {\n /** Provider: `\"anthropic\"`, `\"openai\"`, `\"azure-openai\"` */\n provider?: string\n /** Model identifier (e.g., `\"claude-opus-4-6\"`, `\"gpt-4-turbo\"`) */\n modelId?: string\n /** Inference temperature (0.0–2.0) */\n temperature?: number\n /** Maximum response tokens */\n maxTokens?: number\n /** Voice ID for voice agents (e.g., `\"marin\"`, `\"echo\"`) */\n voiceId?: string\n}\n\n/**\n * A capability (tool/function) the agent can use.\n *\n * @example\n * ```typescript\n * const cap: AgentCapability = {\n * name: \"registerUserFact\",\n * description: \"Store a learned fact about the user\",\n * enabled: true,\n * }\n * ```\n */\nexport interface AgentCapability {\n /** Tool/function name */\n name: string\n /** What this capability does */\n description?: string\n /** Whether this capability is active */\n enabled?: boolean\n /** Tool parameter schema (JSON Schema) */\n parameters?: unknown\n}\n\n/**\n * Memory retention policy — controls how the agent manages its memories.\n */\nexport interface AgentMemoryPolicy {\n /** Max assertions per user subject (0 = unlimited) */\n maxMemoriesPerUser?: number\n /** Auto-forget memories below this confidence (0.0 = keep everything) */\n forgetConfidenceBelow?: number\n /** Days to retain memories (0 = forever) */\n retainDays?: number\n /** Compress old memories into higher-level summaries */\n autoSummarize?: boolean\n}\n\n/**\n * Full agent configuration — the agent's identity in SubCortex.\n *\n * This is what an agent retrieves at session start to know who it is,\n * how to behave, what tools it has, and how to manage its memory.\n *\n * @example\n * ```typescript\n * const agent = await cortex.agents.create({\n * name: 'Aria',\n * description: 'AI assistant for customer support',\n * personality: { tone: 'casual', traits: ['curious', 'empathetic'] },\n * instructions: {\n * personality: 'You are the user\\'s best friend at work...',\n * memoryGuidance: 'Remember names, roles, and org structure...',\n * },\n * model: { provider: 'openai', modelId: 'gpt-realtime-1.5', voiceId: 'marin' },\n * })\n * ```\n */\nexport interface AgentConfig {\n agentId: string\n tenantId: string\n name: string\n description: string\n personality: AgentPersonality\n instructions: AgentInstructions\n model: AgentModelConfig\n capabilities: AgentCapability[]\n memoryPolicy: AgentMemoryPolicy\n isActive: boolean\n createdAt: string\n updatedAt: string\n}\n\n/** Input for creating an agent. */\nexport interface CreateAgentInput {\n name: string\n description?: string\n personality?: AgentPersonality\n instructions?: AgentInstructions\n model?: AgentModelConfig\n capabilities?: AgentCapability[]\n memoryPolicy?: AgentMemoryPolicy\n tenantId?: string\n}\n\n/** Input for updating an agent. */\nexport interface UpdateAgentInput {\n name?: string\n description?: string\n personality?: AgentPersonality\n instructions?: AgentInstructions\n model?: AgentModelConfig\n capabilities?: AgentCapability[]\n memoryPolicy?: AgentMemoryPolicy\n isActive?: boolean\n}\n\n/** Composed instructions response. */\nexport interface ComposedInstructions {\n composedInstructions: string\n agentName: string\n modelProvider: string\n modelId: string\n temperature: number\n maxTokens: number\n voiceId: string\n}\n\n/**\n * Operations on agent configurations — the identity layer.\n *\n * Create, update, and retrieve agent profiles that define who an agent is,\n * how it behaves, what tools it can use, and how it manages memory.\n *\n * @example\n * ```typescript\n * // Create an agent\n * const agent = await subcortex.agents.create({\n * name: 'Aria',\n * description: 'AI assistant for customer support',\n * personality: { tone: 'casual', traits: ['curious', 'witty'] },\n * })\n *\n * // Get composed system prompt at session start\n * const { composedInstructions } = await subcortex.agents.getInstructions(agent.agentId)\n * ```\n */\nexport class AgentsNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** Create a new agent. */\n async create(input: CreateAgentInput): Promise<AgentConfig> {\n const tenantId = input.tenantId || this.tenantId\n return this.http.post<AgentConfig>('/api/v1/agents', {\n tenant_id: tenantId,\n name: input.name,\n description: input.description,\n personality: input.personality,\n instructions: input.instructions ? toWire(input.instructions) : undefined,\n model: input.model ? toWire(input.model) : undefined,\n capabilities: input.capabilities,\n memory_policy: input.memoryPolicy ? toWire(input.memoryPolicy) : undefined,\n })\n }\n\n /** Get an agent by ID. */\n async get(agentId: string, options?: { tenantId?: string }): Promise<AgentConfig> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<AgentConfig>(\n `/api/v1/agents/${enc(tenantId)}/${enc(agentId)}`\n )\n }\n\n /** Update an agent. */\n async update(agentId: string, input: UpdateAgentInput, options?: { tenantId?: string }): Promise<AgentConfig> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.put<AgentConfig>(\n `/api/v1/agents/${enc(tenantId)}/${enc(agentId)}`,\n {\n tenant_id: tenantId,\n name: input.name,\n description: input.description,\n personality: input.personality,\n instructions: input.instructions ? toWire(input.instructions) : undefined,\n model: input.model ? toWire(input.model) : undefined,\n capabilities: input.capabilities,\n memory_policy: input.memoryPolicy ? toWire(input.memoryPolicy) : undefined,\n is_active: input.isActive,\n }\n )\n }\n\n /** Delete an agent. */\n async delete(agentId: string, options?: { tenantId?: string }): Promise<void> {\n const tenantId = options?.tenantId || this.tenantId\n await this.http.delete<unknown>(`/api/v1/agents/${enc(tenantId)}/${enc(agentId)}`)\n }\n\n /** List all agents for the tenant. */\n async list(options?: { tenantId?: string }): Promise<AgentConfig[]> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<AgentConfig[]>(\n `/api/v1/agents/list/${enc(tenantId)}`\n )\n }\n\n /** Get composed system instructions for an agent. */\n async getInstructions(agentId: string, options?: { tenantId?: string }): Promise<ComposedInstructions> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<ComposedInstructions>(\n `/api/v1/agents/${enc(tenantId)}/${enc(agentId)}/instructions`\n )\n }\n}\n\n// ─── Memory Namespace ───────────────────────────────\n\n/** Input for storing a memory. */\nexport interface StoreMemoryInput {\n subject: string\n predicate: string\n value: unknown\n confidence?: number\n tenantId?: string\n /** Agent ID — required for Thalamus routing (used as agentId in intake submission) */\n agentId?: string\n /** Person this fact relates to */\n personName?: string\n /** Skip Thalamus processing — write directly to assertion store. For bulk imports, migrations. */\n raw?: boolean\n /** Conversational context for deep encoding */\n context?: {\n topic?: string\n emotionalState?: string\n sessionId?: string\n excerpt?: string\n }\n}\n\n/**\n * Agent memory operations.\n *\n * By default, `store()` routes through the Thalamus cognitive intake\n * pipeline for signal classification, contradiction detection, and\n * deduplication. Use `raw: true` to bypass for bulk imports.\n *\n * @example\n * ```typescript\n * // Store via Thalamus (default — validated, deduped, conflict-checked)\n * await subcortex.memory.store({\n * subject: 'user:alice',\n * predicate: 'role',\n * value: 'Engineering Manager',\n * confidence: 0.99,\n * agentId: 'agent_abc',\n * })\n *\n * // Store raw (bypass Thalamus — for imports/migrations)\n * await subcortex.memory.store({\n * subject: 'user:alice',\n * predicate: 'role',\n * value: 'Engineering Manager',\n * raw: true,\n * })\n *\n * // Recall everything about a user\n * const memories = await subcortex.memory.recall('user:alice')\n * ```\n */\nexport class MemoryNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /**\n * Store a fact in the agent's memory.\n *\n * Routes through the Thalamus by default. The Thalamus will:\n * - Classify the signal (reject noise)\n * - Check for contradictions with existing assertions\n * - Detect duplicates and reinforce instead of creating new\n *\n * Pass `raw: true` to bypass Thalamus for system operations.\n */\n async store(input: StoreMemoryInput): Promise<Assertion | IntakeResult> {\n const tenantId = input.tenantId || this.tenantId\n\n if (input.raw) {\n // Direct write — bypass Thalamus\n return this.http.post<Assertion>('/api/v1/assertions', {\n tenant_id: tenantId,\n subject: input.subject,\n predicate: input.predicate,\n value: input.value,\n confidence: input.confidence,\n })\n }\n\n // Route through Thalamus\n const correlationId = `mem_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`\n return this.http.post<IntakeResult>('/api/v1/intake/submit', {\n correlation_id: correlationId,\n agent_id: input.agentId,\n tenant_id: tenantId,\n candidates: [{\n subject: input.subject,\n predicate: input.predicate,\n value: input.value,\n source_confidence: input.confidence ?? 0.95,\n provenance: 'agent',\n person_name: input.personName,\n }],\n context: input.context,\n })\n }\n\n /** Recall all memories for a subject. */\n async recall(subject: string, options?: { tenantId?: string }): Promise<Assertion[]> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(tenantId)}/${enc(subject)}`\n )\n }\n\n /** Forget a specific memory (retract the assertion). */\n async forget(assertionId: string, options?: { tenantId?: string }): Promise<Assertion> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.post<Assertion>(\n `/api/v1/assertions/retract/${enc(tenantId)}/${enc(assertionId)}`,\n {}\n )\n }\n}\n\n// ─── Intake Types ───────────────────────────────────\n\n/** A candidate assertion submitted for Thalamus processing. */\nexport interface CandidateAssertion {\n subject: string\n predicate: string\n value: unknown\n sourceConfidence: number\n validFrom?: string\n validUntil?: string | null\n provenance: 'human' | 'agent' | 'import' | 'derived'\n personName?: string\n}\n\n/** Full intake submission. */\nexport interface IntakeSubmission {\n correlationId: string\n agentId: string\n candidates: CandidateAssertion[]\n context?: {\n topic?: string\n emotionalState?: string\n sessionId?: string\n excerpt?: string\n }\n tenantId?: string\n}\n\n/** Result of Thalamus processing. */\nexport interface IntakeResult {\n correlationId: string\n processed: number\n accepted: number\n reinforced: number\n conflicts: number\n rejected: number\n items: IntakeResponseItem[]\n}\n\n/** A single intake response queue item. */\nexport interface IntakeResponseItem {\n id: string\n correlationId: string\n agentId: string\n tenantId: string\n status: 'accepted' | 'reinforced' | 'conflict_detected' | 'needs_clarification' | 'rejected'\n priority: number\n surfacingHint?: string\n expiresAt: string\n persistedAssertionIds: string[]\n inferredBondIds: string[]\n conflictingAssertionId?: string\n clarificationQuestions: string[]\n rejectionReason?: string\n signalCategory?: string\n acknowledged: boolean\n createdAt: string\n}\n\n/** Intake processing stats. */\nexport interface IntakeStats {\n total: number\n accepted: number\n reinforced: number\n conflicts: number\n clarifications: number\n rejected: number\n}\n\n/**\n * Thalamus cognitive intake operations.\n *\n * Submit candidate assertions for processing through the Thalamus\n * pipeline. The pipeline validates, deduplicates, detects contradictions,\n * and enriches assertions before persisting them.\n *\n * @example\n * ```typescript\n * // Submit a fact for processing\n * const result = await subcortex.intake.submit({\n * correlationId: 'corr-123',\n * agentId: 'agent_abc',\n * candidates: [{\n * subject: 'user:tommy',\n * predicate: 'role',\n * value: 'CTO',\n * sourceConfidence: 0.99,\n * provenance: 'human',\n * }],\n * })\n *\n * // Check for conflicts or clarification requests\n * const pending = await subcortex.intake.pending('agent_abc')\n *\n * // Acknowledge after handling\n * await subcortex.intake.acknowledge(pending[0].id)\n * ```\n */\nexport class IntakeNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** Submit candidate assertions for Thalamus processing. */\n async submit(input: IntakeSubmission): Promise<IntakeResult> {\n const tenantId = input.tenantId || this.tenantId\n return this.http.post<IntakeResult>('/api/v1/intake/submit', {\n correlation_id: input.correlationId,\n agent_id: input.agentId,\n tenant_id: tenantId,\n candidates: input.candidates.map(c => ({\n subject: c.subject,\n predicate: c.predicate,\n value: c.value,\n source_confidence: c.sourceConfidence,\n valid_from: c.validFrom,\n valid_until: c.validUntil,\n provenance: c.provenance,\n person_name: c.personName,\n })),\n context: input.context ? {\n topic: input.context.topic,\n emotional_state: input.context.emotionalState,\n session_id: input.context.sessionId,\n excerpt: input.context.excerpt,\n } : undefined,\n })\n }\n\n /** Get pending intake results for an agent. */\n async pending(agentId: string, options?: {\n status?: string[]\n limit?: number\n }): Promise<IntakeResponseItem[]> {\n let path = `/api/v1/intake/pending/${enc(agentId)}`\n const params: string[] = []\n if (options?.status) params.push(`status=${options.status.join(',')}`)\n if (options?.limit) params.push(`limit=${options.limit}`)\n if (params.length) path += `?${params.join('&')}`\n\n return this.http.get<IntakeResponseItem[]>(path)\n }\n\n /** Acknowledge an intake result (mark as consumed). */\n async acknowledge(itemId: string): Promise<void> {\n await this.http.post<unknown>(`/api/v1/intake/acknowledge/${enc(itemId)}`, {})\n }\n\n /** Acknowledge all pending items for an agent. */\n async acknowledgeAll(agentId: string): Promise<{ acknowledged: number }> {\n return this.http.post<{ acknowledged: number }>(\n `/api/v1/intake/acknowledge-all/${enc(agentId)}`,\n {}\n )\n }\n\n /** Get intake processing stats for an agent. */\n async stats(agentId: string): Promise<IntakeStats> {\n return this.http.get<IntakeStats>(`/api/v1/intake/stats/${enc(agentId)}`)\n }\n}\n\n// ─── Experience Types ─────────────────────────────\n\nexport interface Experience {\n id: string\n tenant_id: string\n agent_id: string | null\n session_id: string\n start_time: string\n end_time: string | null\n assertion_ids: string[]\n relationship_ids: string[]\n summary: string | null\n topic: string | null\n emotional_arc: string | null\n}\n\nexport class ExperiencesNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** List experiences, optionally filtered by subject. */\n async list(input?: { subject?: string; limit?: number; tenantId?: string }): Promise<Experience[]> {\n const tenantId = input?.tenantId || this.tenantId\n const params = new URLSearchParams()\n if (input?.subject) params.set('subject', input.subject)\n if (input?.limit) params.set('limit', String(input.limit))\n const qs = params.toString()\n return this.http.get<Experience[]>(\n `/api/v1/experiences/${enc(tenantId)}${qs ? `?${qs}` : ''}`\n )\n }\n\n /** Get a single experience by ID. */\n async get(experienceId: string, options?: { tenantId?: string }): Promise<Experience> {\n const tenantId = options?.tenantId || this.tenantId\n return this.http.get<Experience>(\n `/api/v1/experiences/${enc(tenantId)}/${enc(experienceId)}`\n )\n }\n}\n\n// ─── Recall Types ─────────────────────────────────\n\nexport interface RecallResult {\n assertion_id: string\n score: number\n subject: string\n predicate: string\n snippet: string\n}\n\nexport interface RecallSearchInput {\n query: string\n limit?: number\n tenantId?: string\n}\n\nexport interface RecallSearchResponse {\n results: RecallResult[]\n total_hits: number\n}\n\nexport class RecallNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** BM25 full-text search across assertions. */\n async search(input: RecallSearchInput): Promise<RecallSearchResponse> {\n const tenantId = input.tenantId || this.tenantId\n const params = new URLSearchParams({ q: input.query })\n if (input.limit) params.set('limit', String(input.limit))\n return this.http.get<RecallSearchResponse>(\n `/api/v1/recall/${enc(tenantId)}?${params.toString()}`\n )\n }\n}\n\n// ─── Graph Types ──────────────────────────────────\n\nexport interface GraphPath {\n subjects: string[]\n total_confidence: number\n length: number\n}\n\nexport interface FindPathsInput {\n from: string\n to: string\n maxDepth?: number\n minConfidence?: number\n /** \"shortest\" | \"highest_confidence\" | \"all\" */\n strategy?: string\n tenantId?: string\n}\n\nexport interface TraversalNode {\n subject: string\n depth: number\n path_confidence: number\n}\n\nexport interface TraversalResult {\n nodes: TraversalNode[]\n edge_count: number\n depth_reached: number\n truncated: boolean\n}\n\nexport interface TraverseInput {\n startSubject: string\n maxDepth?: number\n relationshipTypes?: string[]\n minConfidence?: number\n maxNodes?: number\n tenantId?: string\n}\n\nexport class GraphNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** Find paths between two subjects. */\n async findPaths(input: FindPathsInput): Promise<GraphPath[]> {\n const tenantId = input.tenantId || this.tenantId\n return this.http.post<GraphPath[]>(\n `/api/v1/graph/${enc(tenantId)}/paths`,\n {\n from: input.from,\n to: input.to,\n max_depth: input.maxDepth,\n min_confidence: input.minConfidence,\n strategy: input.strategy,\n }\n )\n }\n\n /** BFS traversal from a starting subject. */\n async traverse(input: TraverseInput): Promise<TraversalResult> {\n const tenantId = input.tenantId || this.tenantId\n return this.http.post<TraversalResult>(\n `/api/v1/graph/${enc(tenantId)}/traverse`,\n {\n start_subject: input.startSubject,\n max_depth: input.maxDepth,\n relationship_types: input.relationshipTypes,\n min_confidence: input.minConfidence,\n max_nodes: input.maxNodes,\n }\n )\n }\n}\n\n// ─── Temporal Types ───────────────────────────────\n\nexport interface TemporalSnapshot {\n subject: string\n point: string\n assertions: Assertion[]\n}\n\nexport interface TemporalRange {\n subject: string\n start: string\n end: string\n assertions: Assertion[]\n}\n\nexport class TemporalNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** Get assertions valid at a specific point in time. */\n async at(subject: string, point: Date | string, options?: { tenantId?: string }): Promise<TemporalSnapshot> {\n const tenantId = options?.tenantId || this.tenantId\n const pointStr = point instanceof Date ? point.toISOString() : point\n return this.http.get<TemporalSnapshot>(\n `/api/v1/temporal/${enc(tenantId)}/${enc(subject)}/at?point=${enc(pointStr)}`\n )\n }\n\n /** Get assertions within a date range. */\n async range(subject: string, start: Date | string, end: Date | string, options?: { tenantId?: string }): Promise<TemporalRange> {\n const tenantId = options?.tenantId || this.tenantId\n const startStr = start instanceof Date ? start.toISOString() : start\n const endStr = end instanceof Date ? end.toISOString() : end\n return this.http.get<TemporalRange>(\n `/api/v1/temporal/${enc(tenantId)}/${enc(subject)}/range?start=${enc(startStr)}&end=${enc(endStr)}`\n )\n }\n}\n\n// ─── Search Types ─────────────────────────────────\n\nexport interface SearchResult {\n assertion_id: string\n similarity: number\n}\n\nexport interface SemanticSearchInput {\n embedding: number[]\n topK?: number\n tenantId?: string\n}\n\nexport class SearchNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** Semantic nearest-neighbor search over assertion embeddings. */\n async semantic(input: SemanticSearchInput): Promise<SearchResult[]> {\n const tenantId = input.tenantId || this.tenantId\n return this.http.post<SearchResult[]>(\n `/api/v1/search/${enc(tenantId)}/semantic`,\n {\n embedding: input.embedding,\n top_k: input.topK,\n }\n )\n }\n}\n\n// ─── Client ─────────────────────────────────────────\n\nconst DEFAULT_RETRY: RetryConfig = {\n maxRetries: 3,\n baseDelayMs: 500,\n maxDelayMs: 10_000,\n}\n\n// ─── Entity Types ──────────────────────────────────\n\nexport interface CreateEntityInput {\n /** Entity name (used as the subject identifier, e.g. \"Project\") */\n name: string\n /** Human-readable description */\n description?: string\n /** Entity type classification (e.g. \"model\", \"workflow\", \"reference\") */\n type?: string\n /** Override default tenant */\n tenantId?: string\n}\n\nexport interface AddPropertyInput {\n /** Entity name this property belongs to */\n entityName: string\n /** Property name */\n name: string\n /** Property field type (e.g. \"string\", \"number\", \"date\", \"boolean\", \"reference\") */\n fieldType: string\n /** Whether this property is required */\n required?: boolean\n /** Override default tenant */\n tenantId?: string\n}\n\nexport interface EntityDescription {\n subject: string\n name: string\n type: string | null\n description: string | null\n properties: Array<{\n name: string\n fieldType: string | null\n required: boolean\n }>\n relationships: Array<{\n type: string\n target: string\n confidence: number\n }>\n}\n\nexport class EntitiesNamespace {\n constructor(\n private http: HttpTransport,\n private tenantId: string\n ) {}\n\n /** Create an entity with optional description and type. */\n async create(input: CreateEntityInput): Promise<Assertion> {\n const tenantId = input.tenantId || this.tenantId\n const subject = `entity:${input.name.toLowerCase().replace(/\\s+/g, '-')}`\n\n // Create the type assertion (defines this as an entity)\n const typeAssertion = await this.http.post<Assertion>(\n `/api/v1/assertions`,\n {\n tenant_id: tenantId,\n subject,\n predicate: 'type',\n value: input.type || 'model',\n confidence: 1.0,\n }\n )\n\n // Add description if provided\n if (input.description) {\n await this.http.post<Assertion>(\n `/api/v1/assertions`,\n {\n tenant_id: tenantId,\n subject,\n predicate: 'description',\n value: input.description,\n confidence: 1.0,\n }\n )\n }\n\n return typeAssertion\n }\n\n /** Add a property to an entity. */\n async addProperty(input: AddPropertyInput): Promise<{ assertion: Assertion; relationship: Relationship }> {\n const tenantId = input.tenantId || this.tenantId\n const entitySubject = `entity:${input.entityName.toLowerCase().replace(/\\s+/g, '-')}`\n const propertySubject = `property:${input.entityName.toLowerCase().replace(/\\s+/g, '-')}.${input.name.toLowerCase().replace(/\\s+/g, '-')}`\n\n // Create property field_type assertion\n const assertion = await this.http.post<Assertion>(\n `/api/v1/assertions`,\n {\n tenant_id: tenantId,\n subject: propertySubject,\n predicate: 'field_type',\n value: input.fieldType,\n confidence: 1.0,\n }\n )\n\n // Create has_property relationship\n const relationship = await this.http.post<Relationship>(\n `/api/v1/relationships`,\n {\n tenant_id: tenantId,\n from_subject: entitySubject,\n to_subject: propertySubject,\n relationship_type: 'has_property',\n confidence: 1.0,\n }\n )\n\n // Mark required if specified\n if (input.required) {\n await this.http.post<Assertion>(\n `/api/v1/assertions`,\n {\n tenant_id: tenantId,\n subject: propertySubject,\n predicate: 'required',\n value: true,\n confidence: 1.0,\n }\n )\n }\n\n return { assertion, relationship }\n }\n\n /** Describe an entity by reconstructing its properties and relationships from assertions. */\n async describe(entityName: string, options?: { tenantId?: string }): Promise<EntityDescription> {\n const tenantId = options?.tenantId || this.tenantId\n const subject = `entity:${entityName.toLowerCase().replace(/\\s+/g, '-')}`\n\n // Fetch entity assertions\n const assertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(tenantId)}/${enc(subject)}`\n )\n\n // Fetch outgoing relationships (has_property, belongs_to, etc.)\n const relationships = await this.http.get<Relationship[]>(\n `/api/v1/relationships/query/${enc(tenantId)}/${enc(subject)}`\n )\n\n // Extract known predicates\n const typeAssertion = assertions.find(a => a.predicate === 'type' && !a.isSuperseded)\n const descAssertion = assertions.find(a => a.predicate === 'description' && !a.isSuperseded)\n\n // Fetch property details for each has_property relationship\n const propertyRels = relationships.filter(r => r.relationshipType === 'has_property')\n const properties = await Promise.all(\n propertyRels.map(async (rel) => {\n const propAssertions = await this.http.get<Assertion[]>(\n `/api/v1/assertions/query/${enc(tenantId)}/${enc(rel.toSubject)}`\n )\n const fieldType = propAssertions.find(a => a.predicate === 'field_type' && !a.isSuperseded)\n const required = propAssertions.find(a => a.predicate === 'required' && !a.isSuperseded)\n const name = rel.toSubject.replace(/^property:[^.]+\\./, '')\n return {\n name,\n fieldType: fieldType ? String(fieldType.value) : null,\n required: required ? Boolean(required.value) : false,\n }\n })\n )\n\n // Non-property relationships\n const otherRels = relationships\n .filter(r => r.relationshipType !== 'has_property')\n .map(r => ({\n type: r.relationshipType,\n target: r.toSubject,\n confidence: r.confidence,\n }))\n\n return {\n subject,\n name: entityName,\n type: typeAssertion ? String(typeAssertion.value) : null,\n description: descAssertion ? String(descAssertion.value) : null,\n properties,\n relationships: otherRels,\n }\n }\n\n /** List all entities for a tenant (subjects with entity: prefix that have a type predicate). */\n async list(options?: { tenantId?: string }): Promise<Assertion[]> {\n const tenantId = options?.tenantId || this.tenantId\n const all = await this.http.get<Assertion[]>(\n `/api/v1/assertions/list/${enc(tenantId)}`\n )\n return all.filter(a => a.subject.startsWith('entity:') && a.predicate === 'type' && !a.isSuperseded)\n }\n}\n\nexport class SubCortexClient {\n /** Assertion operations (low-level knowledge primitives) */\n readonly assertions: AssertionsNamespace\n /** Relationship operations */\n readonly relationships: RelationshipsNamespace\n /** Agent identity & configuration */\n readonly agents: AgentsNamespace\n /** Agent memory (semantic wrapper over assertions) */\n readonly memory: MemoryNamespace\n /** Thalamus cognitive intake pipeline */\n readonly intake: IntakeNamespace\n /** User rapport building operations */\n readonly users: UsersNamespace\n /** Emotional signals — record, query, and resolve */\n readonly signals: SignalsNamespace\n /** Graph queries — pathfinding and traversal */\n readonly graph: GraphNamespace\n /** Temporal queries — point-in-time snapshots and range queries */\n readonly temporal: TemporalNamespace\n /** Semantic search over assertion embeddings */\n readonly search: SearchNamespace\n /** BM25 full-text recall search */\n readonly recall: RecallNamespace\n /** Episodic memory — experiences grouped by session */\n readonly experiences: ExperiencesNamespace\n /** Entity schema management — create, describe, and manage data models */\n readonly entities: EntitiesNamespace\n /** Code guardrails — typed rules stored as assertions with file-scope matching */\n readonly rules: RulesNamespace\n\n private readonly http: HttpTransport\n\n constructor(options: SubCortexClientOptions) {\n if (!options.apiKey && !options.token) {\n console.warn('[SubCortex] No apiKey or token provided — requests will be unauthenticated.')\n }\n\n this.http = new HttpTransport({\n baseUrl: options.endpoint,\n tenantId: options.tenantId,\n apiKey: options.apiKey,\n token: options.token,\n retry: { ...DEFAULT_RETRY, ...options.retry },\n timeoutMs: options.timeoutMs ?? 30_000,\n fetchImpl: options.fetch ?? globalThis.fetch,\n headers: options.headers ?? {},\n signal: options.signal,\n })\n\n this.assertions = new AssertionsNamespace(this.http, options.tenantId)\n this.relationships = new RelationshipsNamespace(this.http, options.tenantId)\n this.agents = new AgentsNamespace(this.http, options.tenantId)\n this.memory = new MemoryNamespace(this.http, options.tenantId)\n this.intake = new IntakeNamespace(this.http, options.tenantId)\n this.users = new UsersNamespace(this.http, options.tenantId)\n this.signals = new SignalsNamespace(this.http, options.tenantId)\n this.graph = new GraphNamespace(this.http, options.tenantId)\n this.temporal = new TemporalNamespace(this.http, options.tenantId)\n this.search = new SearchNamespace(this.http, options.tenantId)\n this.recall = new RecallNamespace(this.http, options.tenantId)\n this.experiences = new ExperiencesNamespace(this.http, options.tenantId)\n this.entities = new EntitiesNamespace(this.http, options.tenantId)\n this.rules = new RulesNamespace(this.http, options.tenantId)\n }\n\n /** Check SubCortex server health. */\n async health(): Promise<HealthResponse> {\n return this.http.get<HealthResponse>('/health')\n }\n}\n\n\n// ─── Helpers ────────────────────────────────────────\n\nfunction enc(s: string): string {\n return encodeURIComponent(s)\n}\n","/**\n * SubCortex Context Formatting — v1.0 Schema\n *\n * Transforms structured UserIdentification data into XML optimized\n * for model injection. Signals nest as children of the knowledge\n * they relate to, not as a separate section.\n *\n * Section order = priority order (transformer attention bias):\n * conflicts → reminders → contexts → identity → knowledge → relationships\n *\n * Why XML: Tag boundaries create hard attention delimiters for transformers.\n * See docs/context-format-rationale.md for full analysis.\n */\n\nimport type { UserIdentification, UserMemory, ConnectedPerson } from './types/users'\nimport type { SignalEntry } from './types/signals'\n\nexport const CONTEXT_SCHEMA_VERSION = '1.0'\n\nexport type ContextFormat = 'xml' | 'json' | 'summary'\n\nexport interface ContextFormatOptions {\n /** Output format. Default: 'xml' */\n format?: ContextFormat\n /** Include memories section. Default: true */\n includeMemories?: boolean\n /** Include connected people. Default: true */\n includeRelationships?: boolean\n /** Include reminders. Default: true */\n includeReminders?: boolean\n /** Include conflicts. Default: true */\n includeConflicts?: boolean\n /** Include active contexts. Default: true */\n includeContexts?: boolean\n /** Include emotional signals. Default: true */\n includeSignals?: boolean\n /** Minimum confidence threshold to include (0-1). Default: 0 */\n minConfidence?: number\n}\n\n/**\n * Format a UserIdentification result for model injection.\n */\nexport function formatContext(user: UserIdentification, options: ContextFormatOptions = {}): string {\n const format = options.format ?? 'xml'\n switch (format) {\n case 'xml': return toContextXml(user, options)\n case 'json': return JSON.stringify(user, null, 2)\n case 'summary': return user.summary\n }\n}\n\n/**\n * Transform UserIdentification into versioned XML optimized for model attention.\n * Signals nest as children of the facts/contexts/people they relate to.\n */\nexport function toContextXml(user: UserIdentification, options: ContextFormatOptions = {}): string {\n const {\n includeMemories = true,\n includeRelationships = true,\n includeReminders = true,\n includeConflicts = true,\n includeContexts = true,\n includeSignals = true,\n minConfidence = 0,\n } = options\n\n const ts = new Date().toISOString()\n const lines: string[] = []\n\n // Build signal lookup: aboutSubject → signals\n const signalsByAbout = new Map<string, SignalEntry[]>()\n const unattachedSignals: SignalEntry[] = []\n if (includeSignals && user.signals) {\n for (const sig of user.signals) {\n if (sig.aboutSubject) {\n const existing = signalsByAbout.get(sig.aboutSubject) || []\n existing.push(sig)\n signalsByAbout.set(sig.aboutSubject, existing)\n } else {\n unattachedSignals.push(sig)\n }\n }\n }\n\n lines.push(`<subcortex_context version=\"${CONTEXT_SCHEMA_VERSION}\" subject=\"${esc(user.subject)}\" known=\"${user.isKnown}\" ts=\"${ts}\">`)\n\n // ── Priority 1: Conflicts ──\n if (includeConflicts && user.conflicts.length > 0) {\n lines.push(` <conflicts count=\"${user.conflicts.length}\" priority=\"critical\">`)\n for (const conflict of user.conflicts) {\n lines.push(` <conflict id=\"${esc(conflict.id)}\">${esc(conflict.hint)}</conflict>`)\n }\n lines.push(` </conflicts>`)\n }\n\n // ── Priority 2: Reminders ──\n if (includeReminders && user.reminders.length > 0) {\n lines.push(` <reminders count=\"${user.reminders.length}\" priority=\"high\">`)\n for (const reminder of user.reminders) {\n lines.push(` <reminder id=\"${esc(reminder.id)}\" confidence=\"${fmtConf(reminder.confidence)}\">${esc(String(reminder.value))}</reminder>`)\n }\n lines.push(` </reminders>`)\n }\n\n // ── Priority 3: Active Contexts (with attached signals) ──\n if (includeContexts && user.contexts.length > 0) {\n lines.push(` <active_contexts count=\"${user.contexts.length}\">`)\n for (const ctx of user.contexts) {\n const ctxSignals = findSignalsForFact(ctx, signalsByAbout)\n if (ctxSignals.length > 0) {\n lines.push(` <context predicate=\"${esc(ctx.predicate)}\" confidence=\"${fmtConf(ctx.confidence)}\">`)\n lines.push(` ${esc(String(ctx.value))}`)\n for (const sig of ctxSignals) {\n lines.push(` ${renderSignal(sig)}`)\n }\n lines.push(` </context>`)\n } else {\n lines.push(` <context predicate=\"${esc(ctx.predicate)}\" confidence=\"${fmtConf(ctx.confidence)}\">${esc(String(ctx.value))}</context>`)\n }\n }\n lines.push(` </active_contexts>`)\n }\n\n // ── Priority 4: Identity (with unattached signals + rapport trajectory) ──\n if (user.name) {\n const trajectoryAttr = user.rapportTrajectory ? ` rapport_trajectory=\"${user.rapportTrajectory}\"` : ''\n lines.push(` <identity name=\"${esc(String(user.name))}\" subject=\"${esc(user.subject)}\"${trajectoryAttr}>`)\n const identityPredicates = new Set(['name', 'full_name', 'role', 'title', 'department', 'team', 'email', 'start_date', 'communication_style'])\n const identityFacts = user.memories.filter(m => identityPredicates.has(m.predicate) && m.confidence >= minConfidence)\n for (const fact of identityFacts) {\n const factSignals = findSignalsForFact(fact, signalsByAbout)\n if (factSignals.length > 0) {\n lines.push(` <fact predicate=\"${esc(fact.predicate)}\" confidence=\"${fmtConf(fact.confidence)}\">`)\n lines.push(` ${esc(String(fact.value))}`)\n for (const sig of factSignals) {\n lines.push(` ${renderSignal(sig)}`)\n }\n lines.push(` </fact>`)\n } else {\n lines.push(` <fact predicate=\"${esc(fact.predicate)}\" confidence=\"${fmtConf(fact.confidence)}\">${esc(String(fact.value))}</fact>`)\n }\n }\n // Unattached signals go under identity (general mood)\n for (const sig of unattachedSignals) {\n lines.push(` ${renderSignal(sig)}`)\n }\n lines.push(` </identity>`)\n }\n\n // ── Priority 5: Knowledge (with attached signals) ──\n if (includeMemories) {\n const identityPredicates = new Set(['name', 'full_name', 'role', 'title', 'department', 'team', 'email', 'start_date', 'communication_style'])\n const knowledge = user.memories.filter(m =>\n !identityPredicates.has(m.predicate) && m.confidence >= minConfidence\n )\n if (knowledge.length > 0) {\n lines.push(` <knowledge count=\"${knowledge.length}\">`)\n for (const mem of knowledge) {\n // Signal assertions stored as memories — render as signal tags, not facts\n if (mem.predicate.startsWith('signal:')) {\n const sigType = mem.predicate.slice(7)\n const val = mem.value as Record<string, unknown> | null\n const content = (typeof val === 'object' && val?.content) ? String(val.content) : formatValue(mem.value)\n const intensity = (typeof val === 'object' && val?.intensity) ? Number(val.intensity) : mem.confidence\n const about = (typeof val === 'object' && val?.aboutSubject) ? ` about=\"${esc(String(val.aboutSubject))}\"` : ''\n lines.push(` <signal type=\"${esc(sigType)}\" intensity=\"${fmtConf(intensity)}\"${about}>${esc(content)}</signal>`)\n continue\n }\n\n const memSignals = findSignalsForFact(mem, signalsByAbout)\n if (memSignals.length > 0) {\n lines.push(` <fact predicate=\"${esc(mem.predicate)}\" confidence=\"${fmtConf(mem.confidence)}\">`)\n lines.push(` ${esc(formatValue(mem.value))}`)\n for (const sig of memSignals) {\n lines.push(` ${renderSignal(sig)}`)\n }\n lines.push(` </fact>`)\n } else {\n lines.push(` <fact predicate=\"${esc(mem.predicate)}\" confidence=\"${fmtConf(mem.confidence)}\">${esc(formatValue(mem.value))}</fact>`)\n }\n }\n lines.push(` </knowledge>`)\n }\n }\n\n // ── Priority 6: Relationships (with attached signals) ──\n if (includeRelationships && user.connectedPeople.length > 0) {\n lines.push(` <relationships count=\"${user.connectedPeople.length}\">`)\n for (const person of user.connectedPeople) {\n const personSignals = signalsByAbout.get(person.subject) || []\n const hasContent = person.facts.length > 0 || personSignals.length > 0\n if (!hasContent) {\n lines.push(` <person name=\"${esc(person.name)}\" relationship=\"${esc(person.relationship)}\" />`)\n } else {\n lines.push(` <person name=\"${esc(person.name)}\" relationship=\"${esc(person.relationship)}\">`)\n for (const fact of person.facts) {\n lines.push(` <fact predicate=\"${esc(fact.predicate)}\">${esc(String(fact.value))}</fact>`)\n }\n for (const sig of personSignals) {\n lines.push(` ${renderSignal(sig)}`)\n }\n lines.push(` </person>`)\n }\n }\n lines.push(` </relationships>`)\n }\n\n lines.push(`</subcortex_context>`)\n return lines.join('\\n')\n}\n\n// ─── Helpers ──────────────────────────────────────────\n\nfunction renderSignal(sig: SignalEntry): string {\n const aboutAttr = sig.aboutSubject ? ` about=\"${esc(sig.aboutSubject)}\"` : ''\n return `<signal type=\"${esc(sig.type)}\" intensity=\"${fmtConf(sig.intensity)}\" decayed=\"${fmtConf(sig.decayedIntensity)}\" age_hours=\"${sig.ageHours}\"${aboutAttr}>${esc(sig.content)}</signal>`\n}\n\n/**\n * Find signals that relate to a specific fact/memory.\n * Matches on predicate name or value content as subject references.\n */\nfunction findSignalsForFact(fact: UserMemory, signalsByAbout: Map<string, SignalEntry[]>): SignalEntry[] {\n const results: SignalEntry[] = []\n // Match by predicate (e.g., about_subject = \"context:current_project\" matches predicate \"current_project\")\n for (const [aboutSubject, signals] of signalsByAbout) {\n if (aboutSubject.includes(fact.predicate) || aboutSubject.includes(String(fact.value).toLowerCase().replace(/\\s+/g, '-').slice(0, 30))) {\n results.push(...signals)\n }\n }\n return results\n}\n\n/** Safely stringify a value — handles objects, strings, and nulls */\nfunction formatValue(v: unknown): string {\n if (v === null || v === undefined) return ''\n if (typeof v === 'string') return v\n if (typeof v === 'object' && 'content' in (v as Record<string, unknown>)) return String((v as Record<string, unknown>).content)\n return JSON.stringify(v)\n}\n\nfunction fmtConf(n: number): string {\n return n.toFixed(2)\n}\n\nfunction esc(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/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MAAM,OAAW,QAAO;AAC1C,MAAI,OAAO,MAAM,SAAU,QAAO;AAClC,MAAI,OAAO,MAAM,YAAY,aAAc,EAA+B,QAAO,OAAQ,EAA8B,OAAO;AAC9H,SAAO,KAAK,UAAU,CAAC;AACzB;AAEA,SAAS,QAAQ,GAAmB;AAClC,SAAO,EAAE,QAAQ,CAAC;AACpB;AAEA,SAAS,IAAI,GAAmB;AAC9B,SAAO,EACJ,QAAQ,MAAM,OAAO,EACrB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,QAAQ;AAC3B;","names":["SubjectPrefix","IdentityPredicate","WorkPredicate","EventPredicate","RapportPredicate","MemoryPredicate","EntityPredicate","OrgRelationship","EntityRelationship","ConfidenceLevel","enc","enc","subject","enc","subject"]}