@open-mercato/shared 0.10.1-develop.8279.1.7d4003fb64 → 0.10.1-develop.8287.1.7313a0fe67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/lib/ai/referenceResolver.js +9 -0
  3. package/dist/lib/ai/referenceResolver.js.map +7 -0
  4. package/dist/lib/ai/run-observation.js +78 -0
  5. package/dist/lib/ai/run-observation.js.map +7 -0
  6. package/dist/lib/commands/auditCorrelationScope.js +32 -0
  7. package/dist/lib/commands/auditCorrelationScope.js.map +7 -0
  8. package/dist/lib/commands/command-bus.js +23 -0
  9. package/dist/lib/commands/command-bus.js.map +2 -2
  10. package/dist/lib/commands/index.js +4 -1
  11. package/dist/lib/commands/index.js.map +2 -2
  12. package/dist/lib/commands/types.js.map +2 -2
  13. package/dist/lib/version.js +1 -1
  14. package/dist/lib/version.js.map +1 -1
  15. package/dist/modules/search.js.map +2 -2
  16. package/dist/security/features.js +23 -0
  17. package/dist/security/features.js.map +2 -2
  18. package/package.json +2 -2
  19. package/src/lib/ai/__tests__/referenceResolver.test.ts +12 -0
  20. package/src/lib/ai/__tests__/run-observation.test.ts +124 -0
  21. package/src/lib/ai/referenceResolver.ts +34 -0
  22. package/src/lib/ai/run-observation.ts +110 -0
  23. package/src/lib/commands/__tests__/auditCorrelationScope.test.ts +48 -0
  24. package/src/lib/commands/__tests__/command-bus.test.ts +104 -0
  25. package/src/lib/commands/auditCorrelationScope.ts +53 -0
  26. package/src/lib/commands/command-bus.ts +28 -0
  27. package/src/lib/commands/index.ts +1 -0
  28. package/src/lib/commands/types.ts +6 -0
  29. package/src/modules/search.ts +61 -0
  30. package/src/modules/widgets/injection.ts +2 -0
  31. package/src/security/__tests__/features.test.ts +58 -0
  32. package/src/security/features.ts +32 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/commands/index.ts"],
4
- "sourcesContent": ["export * from './types'\nexport * from './registry'\nexport { CommandBus } from './command-bus'\nexport * from './customFieldSnapshots'\nexport * from './undo'\nexport * from './redo'\nexport {\n getTransactionLifetime,\n onTransactionLifetimeComplete,\n ownsTransactionLifetime,\n type TransactionLifetime,\n type TransactionOutcome,\n} from './transaction-lifetime'\nexport {\n CommandInterceptorError,\n isCommandInterceptorError,\n getCommandInterceptorHttpRejection,\n type CommandInterceptorErrorOptions,\n type CommandInterceptorHttpRejection,\n} from './errors'\nexport {\n runCrudCommandWrite,\n type RunCrudCommandWriteOptions,\n type RunCrudCommandWriteResult,\n type CrudCommandWritePhase,\n type CrudCommandWriteScope,\n type CrudCommandWriteSideEffectTarget,\n} from './runCrudCommandWrite'\n"],
5
- "mappings": "AAAA,cAAc;AACd,cAAc;AACd,SAAS,kBAAkB;AAC3B,cAAc;AACd,cAAc;AACd,cAAc;AACd;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,OAMK;",
4
+ "sourcesContent": ["export * from './types'\nexport * from './registry'\nexport { CommandBus } from './command-bus'\nexport * from './customFieldSnapshots'\nexport * from './undo'\nexport * from './redo'\nexport {\n getTransactionLifetime,\n onTransactionLifetimeComplete,\n ownsTransactionLifetime,\n type TransactionLifetime,\n type TransactionOutcome,\n} from './transaction-lifetime'\nexport {\n CommandInterceptorError,\n isCommandInterceptorError,\n getCommandInterceptorHttpRejection,\n type CommandInterceptorErrorOptions,\n type CommandInterceptorHttpRejection,\n} from './errors'\nexport {\n runCrudCommandWrite,\n type RunCrudCommandWriteOptions,\n type RunCrudCommandWriteResult,\n type CrudCommandWritePhase,\n type CrudCommandWriteScope,\n type CrudCommandWriteSideEffectTarget,\n} from './runCrudCommandWrite'\nexport { withAuditCorrelation, getAmbientAuditCorrelation } from './auditCorrelationScope'\n"],
5
+ "mappings": "AAAA,cAAc;AACd,cAAc;AACd,SAAS,kBAAkB;AAC3B,cAAc;AACd,cAAc;AACd,cAAc;AACd;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,OAMK;AACP,SAAS,sBAAsB,kCAAkC;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/commands/types.ts"],
4
- "sourcesContent": ["import type { AwilixContainer } from 'awilix'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { ZodTypeAny } from 'zod'\nimport { randomUUID } from 'crypto'\nimport type { AuthContext } from '../auth/server'\nimport type { OrganizationScope } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { TransactionLifetime } from './transaction-lifetime'\n\n/**\n * Bulk-import / backfill deferral flags. When a command runs under a context that\n * carries this, the command bus and data engine suppress the heavy per-record side\n * effects flagged below so a large backfill can defer them to a single batched pass.\n *\n * IMPORTANT \u2014 the caller owns restoring whatever it suppresses. With `skipReindex`\n * the `query_index` projection (and its search tokens) is stale for every record\n * written under this context until the caller runs a batched `query_index rebuild`\n * for the affected entity types at end-of-run.\n *\n * Concurrency: these flags are read from the context and threaded as a local\n * parameter through the side-effect flush \u2014 no shared engine state is mutated \u2014 so\n * two commands running concurrently with different flags never clobber each other.\n */\nexport type BulkImportSuppression = {\n /** Skip the inline `query_index.upsert_one` / `delete_one` reindex (rebuild after the run). */\n skipReindex?: boolean\n /** Skip the per-record `<module>.<entity>.<action>` domain event emission. */\n skipEvents?: boolean\n /** Advisory: handlers that fan out per-record notifications SHOULD honor this and skip them. */\n skipNotifications?: boolean\n /**\n * Skip a command's own full-collection derived-data rebuild (e.g. category tree\n * `parentId`/`treePath`/`depth`/ancestor-descendant rewrite). The caller MUST run that rebuild\n * itself exactly once after the batch, in a `finally` that covers the completed, cancelled and\n * failed paths \u2014 otherwise every record written under this context is left with a stale\n * derived shape.\n */\n skipDerivedRebuild?: boolean\n}\n\nexport type CommandRuntimeContext = {\n container: AwilixContainer\n auth: AuthContext | null\n organizationScope: OrganizationScope | null\n selectedOrganizationId: string | null\n organizationIds: string[] | null\n request?: Request\n syncOrigin?: string | null\n /**\n * See {@link BulkImportSuppression}. Set by bulk backfill callers to defer heavy\n * per-record side effects (reindex, events, notifications). The caller MUST rebuild\n * the `query_index` for the affected entity types after the run when `skipReindex`\n * is set. Unset for normal (interactive) writes \u2014 they get all side effects.\n */\n bulkImport?: BulkImportSuppression\n /**\n * Marks a trusted server-side invocation (CLI seeding, tenant setup) that runs\n * without an authenticated end-user actor. Commands that gate writes behind a\n * privileged actor (e.g. super-admin-only platform tables) may treat this as\n * an explicit system grant. HTTP request paths MUST NOT set this \u2014 they always\n * carry a real `auth` actor, so a present-but-unprivileged actor stays denied.\n */\n systemActor?: boolean\n /**\n * When set, command handlers that support it MUST run their writes within this\n * existing transactional EntityManager (reusing its row locks) instead of\n * opening their own transaction. Lets a caller compose a command with its own\n * surrounding work as a single atomic, single-locked operation.\n */\n transactionalEm?: EntityManager\n /**\n * Optional server-side guard that supported command handlers invoke after\n * opening their write transaction and before reading or mutating records.\n * The guard receives that same transaction-bound EntityManager and, when the\n * handler provides it, the final input after command interceptors. The input\n * stays optional so existing handlers and callers remain source-compatible.\n */\n beforeTransactionalWrite?: (em: EntityManager, input?: unknown) => Promise<void>\n /**\n * Identifies the owner of an already-active {@link transactionalEm} lifetime.\n * Atomic replay accepts an ambient EntityManager only when this is the exact\n * token returned by `getTransactionLifetime(transactionalEm)` from the outer\n * `withAtomicFlush` phase. The owner completes the token after its real commit\n * or rollback, allowing replay leases and post-commit work to follow that\n * boundary. Omit when the command bus opens and owns the transaction itself.\n */\n transactionLifetime?: TransactionLifetime\n /**\n * Optional request-level replay authorization that the command bus binds to\n * its replay EntityManager. Atomic handlers run this guard in the same\n * transaction as the source-log transition and domain mutation; legacy\n * handlers run it in a dedicated read transaction before preserving their\n * existing replay lifecycle.\n */\n replayTransactionGuard?: (args: {\n operation: CommandReplayOperation\n logEntry: CommandUndoLogEntry\n transactionalEm: EntityManager\n }) => Promise<void> | void\n /**\n * On-behalf-of attribution for non-human principals (Agent Identity &\n * On-Behalf-Of, Wave 4 P2). When an agent runs on behalf of a human, the\n * orchestrator's `runAs` wrapper sets this so every `ActionLog` the command\n * path writes records `actorUserId = runAs.actorUserId` (the agent principal's\n * `auth.User` id), `onBehalfOfUserId = runAs.onBehalfOfUserId` (the invoking\n * human, or null for system-invoked agents), and `sourceKey = runAs.source`\n * (`'agent'`). Additive + optional: callers that omit it keep the existing\n * `ctx.auth.sub`-derived attribution unchanged. This threads agent attribution\n * through the SAME audited Command/CRUD path as a human action \u2014 not a parallel\n * audit path.\n */\n runAs?: CommandRunAsContext\n}\n\nexport type CommandRunAsContext = {\n /** The actor stamped on every ActionLog this context produces (agent `auth.User` id). */\n actorUserId: string\n /** The human (or system) principal the actor acts on behalf of; null when system-invoked. */\n onBehalfOfUserId?: string | null\n /** The audit source key for the attributed writes; `'agent'` for agent runs. */\n source: 'agent'\n}\n\nexport type CommandLogMetadata = {\n skipLog?: boolean\n /**\n * Per-execution replay policy. `false` records the audit entry without an undo\n * token or command payload, so neither undo nor redo can replay sensitive input.\n * Omitted preserves the command handler's existing replay behavior.\n */\n replayable?: boolean\n /**\n * Overrides the command input persisted in the audit entry's redo envelope.\n * The default is the raw input, which for credential-bearing commands would put\n * a plaintext secret at rest in `action_logs`. A handler that still wants its\n * operation to be undoable supplies a redacted projection here instead of\n * switching the whole entry to `replayable: false` \u2014 suppressing the undo token\n * removes the operator's ability to revert a write that carries no secret of its\n * own (undoing a user create only deletes a row).\n */\n redoInput?: unknown\n tenantId?: string | null\n organizationId?: string | null\n actorUserId?: string | null\n onBehalfOfUserId?: string | null\n actionLabel?: string | null\n resourceKind?: string | null\n resourceId?: string | null\n parentResourceKind?: string | null\n parentResourceId?: string | null\n undoToken?: string | null\n payload?: unknown\n snapshotBefore?: unknown\n snapshotAfter?: unknown\n relatedResourceKind?: string | null\n relatedResourceId?: string | null\n changes?: Record<string, unknown> | null\n context?: Record<string, unknown> | null\n}\n\nexport type CommandExecuteResult<TResult> = {\n result: TResult\n logEntry: any | null\n /**\n * True when an atomic redo finalized its source action log in the same\n * transaction as the domain mutation and the newly persisted log entry, and\n * that transaction has committed. An ambient replay returns this as false\n * while its caller-owned transaction is still active; the returned result\n * object is updated to true by the owner's commit callback. It remains false\n * on rollback. A non-atomic redo returns true once its compare-and-set claim\n * moved the source log to redone before the command ran; with\n * `ctx.transactionalEm` that claim is part of the caller's transaction, whose\n * rollback reverts it. Callers that historically finalized redo themselves\n * can use this additive signal to avoid a redundant post-commit write.\n */\n replaySourceFinalized?: boolean\n}\n\n/**\n * Shape of the persisted action log handed to a command's `undo()` handler.\n *\n * IMPORTANT: there is intentionally **no `payload` field**. `buildLog()` returns\n * a `payload` in its metadata, but the command bus persists that under\n * `commandPayload` (column `command_payload`, wrapped in a redo envelope) \u2014 the\n * stored row never has a top-level `payload`. Reading `logEntry.payload` in an\n * undo handler is therefore always `undefined` and silently no-ops the undo\n * (issue #2504). Always read the undo snapshot through\n * `extractUndoPayload(logEntry)` from `@open-mercato/shared/lib/commands/undo`,\n * which unwraps `commandPayload`/snapshots correctly. Omitting `payload` here\n * makes the footgun a compile-time error instead of a runtime silent failure.\n */\nexport type CommandUndoLogEntry = {\n id?: string\n commandId?: string\n commandPayload?: unknown | null\n snapshotBefore?: unknown | null\n snapshotAfter?: unknown | null\n resourceKind?: string | null\n resourceId?: string | null\n undoToken?: string | null\n actionLabel?: string | null\n tenantId?: string | null\n organizationId?: string | null\n actorUserId?: string | null\n changesJson?: Record<string, unknown> | null\n contextJson?: Record<string, unknown> | null\n createdAt?: Date | string\n updatedAt?: Date | string\n}\n\nexport type CommandLogBuilderArgs<TInput, TResult> = {\n input: TInput\n result: TResult\n ctx: CommandRuntimeContext\n snapshots: {\n before?: unknown\n after?: unknown\n }\n}\n\nexport type CommandReplayOperation = 'undo' | 'redo'\n\nexport type CommandReplayAuthorizationArgs<TInput> = {\n operation: CommandReplayOperation\n input: TInput\n ctx: CommandRuntimeContext\n logEntry: CommandUndoLogEntry\n}\n\nexport interface CommandHandler<TInput = unknown, TResult = unknown> {\n readonly id: string\n readonly isUndoable?: boolean\n /**\n * Opts replay into the command bus's transaction-bound lifecycle. The source\n * action-log transition, handler mutation, and any new replay log share one\n * EntityManager and commit or roll back together. Handlers that enable this\n * MUST reuse `ctx.transactionalEm` for every replay-time database operation.\n * Omitted preserves the legacy non-atomic replay path.\n */\n readonly atomicReplay?: boolean\n /**\n * Acquires every authorization-state lock needed by an atomic replay before\n * request-level replay authorization and feature-gated interceptors run.\n * Implementations MUST discover their complete actor/target/destination set\n * before taking the first lock and MUST reuse `ctx.transactionalEm`.\n * Omitted preserves the existing lifecycle for handlers that do not need\n * domain-specific authorization stabilization.\n */\n stabilizeReplay?(params: CommandReplayAuthorizationArgs<TInput>): Promise<void> | void\n /**\n * Optional Zod schema describing the command's return value. Feeds the\n * workflows context ledger so downstream activities can reason about the\n * shape a command produces; when absent the ledger renders the output as\n * unknown.\n */\n readonly outputSchema?: ZodTypeAny\n prepare?(input: TInput, ctx: CommandRuntimeContext): Promise<{ before?: unknown } | null> | { before?: unknown } | null\n /**\n * Opt in to taking the undo snapshot inside the write transaction. The bus\n * defers `prepare()` into `ctx.beforeTransactionalWrite`, after the handler's\n * transaction guard and before its first read or mutation.\n */\n readonly prepareSnapshotInsideTransaction?: boolean\n execute(input: TInput, ctx: CommandRuntimeContext): Promise<TResult> | TResult\n buildLog?(args: CommandLogBuilderArgs<TInput, TResult>): Promise<CommandLogMetadata | null | undefined> | CommandLogMetadata | null | undefined\n captureAfter?(input: TInput, result: TResult, ctx: CommandRuntimeContext): Promise<unknown> | unknown\n /**\n * Re-authorizes a stored command against the actor and resource state that\n * exist at replay time. Legacy handlers are checked before claiming an undo\n * log or beginning redo processing. Atomic handlers are checked inside their\n * replay transaction before the guarded source transition; their mutation\n * path can repeat the check after taking domain locks. Throwing aborts replay\n * without committed domain side effects.\n */\n authorizeReplay?(params: CommandReplayAuthorizationArgs<TInput>): Promise<void> | void\n undo?(params: { input: TInput; ctx: CommandRuntimeContext; logEntry: CommandUndoLogEntry }): Promise<void> | void\n /**\n * Optional redo handler. When defined, the command bus calls this instead of\n * `execute()` while replaying a previously undone action (the redo route passes\n * `redoLogEntry` in the execution options). It receives the source action log so\n * it can re-materialize the original record **reusing its id** \u2014 for a create\n * command this restores the soft-deleted row (or re-creates it from the\n * `snapshotAfter`) instead of minting a new id, keeping undo/redo snapshots and\n * references stable (issue #2506, invariant I6). Handlers without `redo` keep the\n * legacy behavior of replaying `execute(__redoInput)`.\n */\n redo?(params: { input: TInput; ctx: CommandRuntimeContext; logEntry: CommandUndoLogEntry }): Promise<TResult> | TResult\n}\n\nexport type CommandExecutionOptions<TInput> = {\n input: TInput\n ctx: CommandRuntimeContext\n metadata?: CommandLogMetadata | null\n skipCacheInvalidation?: boolean\n /**\n * When set, marks this execution as a redo of a previously undone action. If the\n * resolved handler defines a `redo` method, the command bus calls\n * `handler.redo({ input, ctx, logEntry })` instead of `handler.execute(...)`. The\n * rest of the pipeline (snapshots, buildLog, undo-token minting, persistence,\n * cache invalidation, side effects) is identical, so the fresh log entry \u2014 and\n * the `x-om-operation` header derived from it \u2014 automatically carry the restored\n * resourceId. Ignored when the handler has no `redo` method (legacy replay path).\n */\n redoLogEntry?: CommandUndoLogEntry | null\n}\n\nexport function defaultUndoToken(): string {\n return randomUUID()\n}\n"],
5
- "mappings": "AAGA,SAAS,kBAAkB;AA8SpB,SAAS,mBAA2B;AACzC,SAAO,WAAW;AACpB;",
4
+ "sourcesContent": ["import type { AwilixContainer } from 'awilix'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { ZodTypeAny } from 'zod'\nimport { randomUUID } from 'crypto'\nimport type { AuthContext } from '../auth/server'\nimport type { OrganizationScope } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { TransactionLifetime } from './transaction-lifetime'\n\n/**\n * Bulk-import / backfill deferral flags. When a command runs under a context that\n * carries this, the command bus and data engine suppress the heavy per-record side\n * effects flagged below so a large backfill can defer them to a single batched pass.\n *\n * IMPORTANT \u2014 the caller owns restoring whatever it suppresses. With `skipReindex`\n * the `query_index` projection (and its search tokens) is stale for every record\n * written under this context until the caller runs a batched `query_index rebuild`\n * for the affected entity types at end-of-run.\n *\n * Concurrency: these flags are read from the context and threaded as a local\n * parameter through the side-effect flush \u2014 no shared engine state is mutated \u2014 so\n * two commands running concurrently with different flags never clobber each other.\n */\nexport type BulkImportSuppression = {\n /** Skip the inline `query_index.upsert_one` / `delete_one` reindex (rebuild after the run). */\n skipReindex?: boolean\n /** Skip the per-record `<module>.<entity>.<action>` domain event emission. */\n skipEvents?: boolean\n /** Advisory: handlers that fan out per-record notifications SHOULD honor this and skip them. */\n skipNotifications?: boolean\n /**\n * Skip a command's own full-collection derived-data rebuild (e.g. category tree\n * `parentId`/`treePath`/`depth`/ancestor-descendant rewrite). The caller MUST run that rebuild\n * itself exactly once after the batch, in a `finally` that covers the completed, cancelled and\n * failed paths \u2014 otherwise every record written under this context is left with a stale\n * derived shape.\n */\n skipDerivedRebuild?: boolean\n}\n\nexport type CommandRuntimeContext = {\n container: AwilixContainer\n auth: AuthContext | null\n organizationScope: OrganizationScope | null\n selectedOrganizationId: string | null\n organizationIds: string[] | null\n request?: Request\n syncOrigin?: string | null\n /**\n * See {@link BulkImportSuppression}. Set by bulk backfill callers to defer heavy\n * per-record side effects (reindex, events, notifications). The caller MUST rebuild\n * the `query_index` for the affected entity types after the run when `skipReindex`\n * is set. Unset for normal (interactive) writes \u2014 they get all side effects.\n */\n bulkImport?: BulkImportSuppression\n /**\n * Marks a trusted server-side invocation (CLI seeding, tenant setup) that runs\n * without an authenticated end-user actor. Commands that gate writes behind a\n * privileged actor (e.g. super-admin-only platform tables) may treat this as\n * an explicit system grant. HTTP request paths MUST NOT set this \u2014 they always\n * carry a real `auth` actor, so a present-but-unprivileged actor stays denied.\n */\n systemActor?: boolean\n /**\n * When set, command handlers that support it MUST run their writes within this\n * existing transactional EntityManager (reusing its row locks) instead of\n * opening their own transaction. Lets a caller compose a command with its own\n * surrounding work as a single atomic, single-locked operation.\n */\n transactionalEm?: EntityManager\n /**\n * Optional server-side guard that supported command handlers invoke after\n * opening their write transaction and before reading or mutating records.\n * The guard receives that same transaction-bound EntityManager and, when the\n * handler provides it, the final input after command interceptors. The input\n * stays optional so existing handlers and callers remain source-compatible.\n */\n beforeTransactionalWrite?: (em: EntityManager, input?: unknown) => Promise<void>\n /**\n * Identifies the owner of an already-active {@link transactionalEm} lifetime.\n * Atomic replay accepts an ambient EntityManager only when this is the exact\n * token returned by `getTransactionLifetime(transactionalEm)` from the outer\n * `withAtomicFlush` phase. The owner completes the token after its real commit\n * or rollback, allowing replay leases and post-commit work to follow that\n * boundary. Omit when the command bus opens and owns the transaction itself.\n */\n transactionLifetime?: TransactionLifetime\n /**\n * Optional request-level replay authorization that the command bus binds to\n * its replay EntityManager. Atomic handlers run this guard in the same\n * transaction as the source-log transition and domain mutation; legacy\n * handlers run it in a dedicated read transaction before preserving their\n * existing replay lifecycle.\n */\n replayTransactionGuard?: (args: {\n operation: CommandReplayOperation\n logEntry: CommandUndoLogEntry\n transactionalEm: EntityManager\n }) => Promise<void> | void\n /**\n * On-behalf-of attribution for non-human principals (Agent Identity &\n * On-Behalf-Of, Wave 4 P2). When an agent runs on behalf of a human, the\n * orchestrator's `runAs` wrapper sets this so every `ActionLog` the command\n * path writes records `actorUserId = runAs.actorUserId` (the agent principal's\n * `auth.User` id), `onBehalfOfUserId = runAs.onBehalfOfUserId` (the invoking\n * human, or null for system-invoked agents), and `sourceKey = runAs.source`\n * (`'agent'`). Additive + optional: callers that omit it keep the existing\n * `ctx.auth.sub`-derived attribution unchanged. This threads agent attribution\n * through the SAME audited Command/CRUD path as a human action \u2014 not a parallel\n * audit path.\n */\n runAs?: CommandRunAsContext\n /**\n * Correlation ids (e.g. `agentRunId`, `proposalId`) merged into the action log\n * `context.correlation` of every write this context produces. Additive: keys\n * already present in the logged context win, and non-string values are dropped.\n */\n auditCorrelation?: Record<string, string>\n}\n\nexport type CommandRunAsContext = {\n /** The actor stamped on every ActionLog this context produces (agent `auth.User` id). */\n actorUserId: string\n /** The human (or system) principal the actor acts on behalf of; null when system-invoked. */\n onBehalfOfUserId?: string | null\n /** The audit source key for the attributed writes; `'agent'` for agent runs. */\n source: 'agent'\n}\n\nexport type CommandLogMetadata = {\n skipLog?: boolean\n /**\n * Per-execution replay policy. `false` records the audit entry without an undo\n * token or command payload, so neither undo nor redo can replay sensitive input.\n * Omitted preserves the command handler's existing replay behavior.\n */\n replayable?: boolean\n /**\n * Overrides the command input persisted in the audit entry's redo envelope.\n * The default is the raw input, which for credential-bearing commands would put\n * a plaintext secret at rest in `action_logs`. A handler that still wants its\n * operation to be undoable supplies a redacted projection here instead of\n * switching the whole entry to `replayable: false` \u2014 suppressing the undo token\n * removes the operator's ability to revert a write that carries no secret of its\n * own (undoing a user create only deletes a row).\n */\n redoInput?: unknown\n tenantId?: string | null\n organizationId?: string | null\n actorUserId?: string | null\n onBehalfOfUserId?: string | null\n actionLabel?: string | null\n resourceKind?: string | null\n resourceId?: string | null\n parentResourceKind?: string | null\n parentResourceId?: string | null\n undoToken?: string | null\n payload?: unknown\n snapshotBefore?: unknown\n snapshotAfter?: unknown\n relatedResourceKind?: string | null\n relatedResourceId?: string | null\n changes?: Record<string, unknown> | null\n context?: Record<string, unknown> | null\n}\n\nexport type CommandExecuteResult<TResult> = {\n result: TResult\n logEntry: any | null\n /**\n * True when an atomic redo finalized its source action log in the same\n * transaction as the domain mutation and the newly persisted log entry, and\n * that transaction has committed. An ambient replay returns this as false\n * while its caller-owned transaction is still active; the returned result\n * object is updated to true by the owner's commit callback. It remains false\n * on rollback. A non-atomic redo returns true once its compare-and-set claim\n * moved the source log to redone before the command ran; with\n * `ctx.transactionalEm` that claim is part of the caller's transaction, whose\n * rollback reverts it. Callers that historically finalized redo themselves\n * can use this additive signal to avoid a redundant post-commit write.\n */\n replaySourceFinalized?: boolean\n}\n\n/**\n * Shape of the persisted action log handed to a command's `undo()` handler.\n *\n * IMPORTANT: there is intentionally **no `payload` field**. `buildLog()` returns\n * a `payload` in its metadata, but the command bus persists that under\n * `commandPayload` (column `command_payload`, wrapped in a redo envelope) \u2014 the\n * stored row never has a top-level `payload`. Reading `logEntry.payload` in an\n * undo handler is therefore always `undefined` and silently no-ops the undo\n * (issue #2504). Always read the undo snapshot through\n * `extractUndoPayload(logEntry)` from `@open-mercato/shared/lib/commands/undo`,\n * which unwraps `commandPayload`/snapshots correctly. Omitting `payload` here\n * makes the footgun a compile-time error instead of a runtime silent failure.\n */\nexport type CommandUndoLogEntry = {\n id?: string\n commandId?: string\n commandPayload?: unknown | null\n snapshotBefore?: unknown | null\n snapshotAfter?: unknown | null\n resourceKind?: string | null\n resourceId?: string | null\n undoToken?: string | null\n actionLabel?: string | null\n tenantId?: string | null\n organizationId?: string | null\n actorUserId?: string | null\n changesJson?: Record<string, unknown> | null\n contextJson?: Record<string, unknown> | null\n createdAt?: Date | string\n updatedAt?: Date | string\n}\n\nexport type CommandLogBuilderArgs<TInput, TResult> = {\n input: TInput\n result: TResult\n ctx: CommandRuntimeContext\n snapshots: {\n before?: unknown\n after?: unknown\n }\n}\n\nexport type CommandReplayOperation = 'undo' | 'redo'\n\nexport type CommandReplayAuthorizationArgs<TInput> = {\n operation: CommandReplayOperation\n input: TInput\n ctx: CommandRuntimeContext\n logEntry: CommandUndoLogEntry\n}\n\nexport interface CommandHandler<TInput = unknown, TResult = unknown> {\n readonly id: string\n readonly isUndoable?: boolean\n /**\n * Opts replay into the command bus's transaction-bound lifecycle. The source\n * action-log transition, handler mutation, and any new replay log share one\n * EntityManager and commit or roll back together. Handlers that enable this\n * MUST reuse `ctx.transactionalEm` for every replay-time database operation.\n * Omitted preserves the legacy non-atomic replay path.\n */\n readonly atomicReplay?: boolean\n /**\n * Acquires every authorization-state lock needed by an atomic replay before\n * request-level replay authorization and feature-gated interceptors run.\n * Implementations MUST discover their complete actor/target/destination set\n * before taking the first lock and MUST reuse `ctx.transactionalEm`.\n * Omitted preserves the existing lifecycle for handlers that do not need\n * domain-specific authorization stabilization.\n */\n stabilizeReplay?(params: CommandReplayAuthorizationArgs<TInput>): Promise<void> | void\n /**\n * Optional Zod schema describing the command's return value. Feeds the\n * workflows context ledger so downstream activities can reason about the\n * shape a command produces; when absent the ledger renders the output as\n * unknown.\n */\n readonly outputSchema?: ZodTypeAny\n prepare?(input: TInput, ctx: CommandRuntimeContext): Promise<{ before?: unknown } | null> | { before?: unknown } | null\n /**\n * Opt in to taking the undo snapshot inside the write transaction. The bus\n * defers `prepare()` into `ctx.beforeTransactionalWrite`, after the handler's\n * transaction guard and before its first read or mutation.\n */\n readonly prepareSnapshotInsideTransaction?: boolean\n execute(input: TInput, ctx: CommandRuntimeContext): Promise<TResult> | TResult\n buildLog?(args: CommandLogBuilderArgs<TInput, TResult>): Promise<CommandLogMetadata | null | undefined> | CommandLogMetadata | null | undefined\n captureAfter?(input: TInput, result: TResult, ctx: CommandRuntimeContext): Promise<unknown> | unknown\n /**\n * Re-authorizes a stored command against the actor and resource state that\n * exist at replay time. Legacy handlers are checked before claiming an undo\n * log or beginning redo processing. Atomic handlers are checked inside their\n * replay transaction before the guarded source transition; their mutation\n * path can repeat the check after taking domain locks. Throwing aborts replay\n * without committed domain side effects.\n */\n authorizeReplay?(params: CommandReplayAuthorizationArgs<TInput>): Promise<void> | void\n undo?(params: { input: TInput; ctx: CommandRuntimeContext; logEntry: CommandUndoLogEntry }): Promise<void> | void\n /**\n * Optional redo handler. When defined, the command bus calls this instead of\n * `execute()` while replaying a previously undone action (the redo route passes\n * `redoLogEntry` in the execution options). It receives the source action log so\n * it can re-materialize the original record **reusing its id** \u2014 for a create\n * command this restores the soft-deleted row (or re-creates it from the\n * `snapshotAfter`) instead of minting a new id, keeping undo/redo snapshots and\n * references stable (issue #2506, invariant I6). Handlers without `redo` keep the\n * legacy behavior of replaying `execute(__redoInput)`.\n */\n redo?(params: { input: TInput; ctx: CommandRuntimeContext; logEntry: CommandUndoLogEntry }): Promise<TResult> | TResult\n}\n\nexport type CommandExecutionOptions<TInput> = {\n input: TInput\n ctx: CommandRuntimeContext\n metadata?: CommandLogMetadata | null\n skipCacheInvalidation?: boolean\n /**\n * When set, marks this execution as a redo of a previously undone action. If the\n * resolved handler defines a `redo` method, the command bus calls\n * `handler.redo({ input, ctx, logEntry })` instead of `handler.execute(...)`. The\n * rest of the pipeline (snapshots, buildLog, undo-token minting, persistence,\n * cache invalidation, side effects) is identical, so the fresh log entry \u2014 and\n * the `x-om-operation` header derived from it \u2014 automatically carry the restored\n * resourceId. Ignored when the handler has no `redo` method (legacy replay path).\n */\n redoLogEntry?: CommandUndoLogEntry | null\n}\n\nexport function defaultUndoToken(): string {\n return randomUUID()\n}\n"],
5
+ "mappings": "AAGA,SAAS,kBAAkB;AAoTpB,SAAS,mBAA2B;AACzC,SAAO,WAAW;AACpB;",
6
6
  "names": []
7
7
  }
@@ -1,4 +1,4 @@
1
- const APP_VERSION = "0.10.1-develop.8279.1.7d4003fb64";
1
+ const APP_VERSION = "0.10.1-develop.8287.1.7313a0fe67";
2
2
  const appVersion = APP_VERSION;
3
3
  export {
4
4
  APP_VERSION,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/version.ts"],
4
- "sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.10.1-develop.8279.1.7d4003fb64';\nexport const appVersion = APP_VERSION;\n"],
4
+ "sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.10.1-develop.8287.1.7313a0fe67';\nexport const appVersion = APP_VERSION;\n"],
5
5
  "mappings": "AACO,MAAM,cAAc;AACpB,MAAM,aAAa;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/modules/search.ts"],
4
- "sourcesContent": ["import type { EntityId } from './entities'\nimport { createLogger } from '../lib/logger'\n\nconst logger = createLogger('shared').child({ component: 'search-registry' })\n\n// =============================================================================\n// Strategy Identifiers\n// =============================================================================\n\n/**\n * Built-in strategy identifiers plus extensible string for third-party strategies.\n */\nexport type SearchStrategyId = 'tokens' | 'vector' | 'fulltext' | (string & Record<string, never>)\n\n// =============================================================================\n// Result Types\n// =============================================================================\n\n/**\n * Presenter metadata for displaying search results in UI (Cmd+K, global search).\n */\nexport type SearchResultPresenter = {\n title: string\n subtitle?: string\n icon?: string\n /**\n * @deprecated No search UI renders this field, and none is planned \u2014 the Cmd+K dialog,\n * the topbar inline results and `/backend/search` render only `title`, `subtitle` and `icon`.\n * Slated for removal in 0.11.0.\n *\n * For an entity-type label, add a `search.entityType.<module>.<entity>` translation key\n * instead: every search surface already renders one next to the result title, so a badge\n * carrying the same word would render it twice. Declare that key in your own module's\n * `i18n/*.json` \u2014 dictionaries are merged flat across modules, so a `search.*` key\n * contributed by any module resolves normally. For per-record detail (a status, a\n * counterparty, a date), put the value in `subtitle`, which is rendered.\n */\n badge?: string\n}\n\n/**\n * Deep link rendered next to a search result.\n */\nexport type SearchResultLink = {\n href: string\n label: string\n kind?: 'primary' | 'secondary'\n}\n\n/**\n * A single search result returned by a strategy.\n */\nexport type SearchResult = {\n /** Entity type identifier, e.g., 'customers:customer_person_profile' */\n entityId: EntityId\n /** Record primary key */\n recordId: string\n /** Relevance score (normalized 0-1 range preferred, but RRF scores may exceed 1) */\n score: number\n /** Which strategy produced this result */\n source: SearchStrategyId\n /** Optional presenter for quick display */\n presenter?: SearchResultPresenter\n /** Primary URL when result is clicked */\n url?: string\n /** Additional action links */\n links?: SearchResultLink[]\n /** Extra metadata from the strategy */\n metadata?: Record<string, unknown>\n /** Organization scope of the result, when known by the strategy. */\n organizationId?: string | null\n}\n\n// =============================================================================\n// Search Options\n// =============================================================================\n\n/**\n * Options passed to SearchService.search()\n */\nexport type SearchOptions = {\n /** Tenant isolation - required */\n tenantId: string\n /**\n * Optional organization filter.\n * - `string` restricts results to that organization only.\n * - `undefined` or `null` means no organization filter (tenant-wide).\n */\n organizationId?: string | null\n /**\n * Optional organization allowlist.\n * - Non-empty array restricts results to one of those organizations.\n * - Empty array means no organizations are visible and should return no results.\n * - `undefined` or `null` means no organization filter (tenant-wide).\n *\n * `organizationId` takes precedence when both are provided.\n */\n organizationIds?: string[] | null\n /** Filter to specific entity types */\n entityTypes?: EntityId[]\n /** Use only specific strategies (defaults to all available) */\n strategies?: SearchStrategyId[]\n /** Maximum results per strategy before merging */\n limit?: number\n /** Offset for pagination */\n offset?: number\n /** How to combine results: 'or' merges all, 'and' requires match in all strategies */\n combineMode?: 'or' | 'and'\n /**\n * Restricts results to records whose query-index row (`entity_indexes`) matches this predicate,\n * evaluated inside the strategy's ranking query so a restrictive filter never starves the result\n * set (additive, 2026-10-06). Only strategies with `supportsIndexDocFilter: true` receive a\n * filtered search; any other strategy returns no results for it rather than unfiltered ones.\n */\n indexDocFilter?: SearchIndexDocFilter\n}\n\n/**\n * One condition over a record's query-index document (`entity_indexes.doc`), with the query\n * engine's index-document semantics:\n * - `exists`: the key is present and not JSON `null`;\n * - `eq`: the key's text value equals `value` (booleans and numbers compare by their JSON text);\n * - `overlap`: the key holds an array sharing at least one entry with `values`; empty `values`\n * matches nothing;\n * - `noverlap`: the key holds an array sharing no entry with `values`; a missing key never matches;\n * - `recordIdNotIn`: the record id is none of `values`.\n */\nexport type SearchIndexDocCondition =\n | { op: 'exists'; key: string }\n | { op: 'eq'; key: string; value: string | number | boolean }\n | { op: 'overlap'; key: string; values: string[] }\n | { op: 'noverlap'; key: string; values: string[] }\n | { op: 'recordIdNotIn'; values: string[] }\n\n/**\n * A predicate over a record's `entity_indexes` row in disjunctive normal form: the record matches\n * when its index row is not deleted and every condition of at least one `anyOf` branch holds.\n * An empty `anyOf` matches nothing; an empty branch matches every indexed record.\n */\nexport type SearchIndexDocFilter = {\n anyOf: SearchIndexDocCondition[][]\n}\n\n// =============================================================================\n// Indexable Record\n// =============================================================================\n\n/**\n * A record prepared for indexing across all strategies.\n */\nexport type IndexableRecord = {\n /** Entity type identifier */\n entityId: EntityId\n /** Record primary key */\n recordId: string\n /** Tenant for isolation */\n tenantId: string\n /** Optional organization for additional filtering */\n organizationId?: string | null\n /** All fields from the record (strategies will filter based on their needs) */\n fields: Record<string, unknown>\n /** Custom-field keys excluded from plaintext fulltext/vector fields; `all` denies every custom field. Tokens retain `fields`; omission preserves legacy direct-client behavior. */\n plaintextExcludedCustomFields?: readonly string[] | 'all'\n /** Optional presenter for result display */\n presenter?: SearchResultPresenter\n /** Primary URL for the record */\n url?: string\n /** Additional action links */\n links?: SearchResultLink[]\n /** Text content for embedding (from buildSource, used by vector strategy) */\n text?: string | string[]\n /** Source object for checksum calculation (change detection) */\n checksumSource?: unknown\n}\n\n// =============================================================================\n// Strategy Interface\n// =============================================================================\n\n/**\n * Interface that all search strategies must implement.\n * Following the cache module's strategy pattern.\n */\nexport interface SearchStrategy {\n /** Unique strategy identifier */\n readonly id: SearchStrategyId\n\n /** Human-readable name for debugging/logging */\n readonly name: string\n\n /** Priority for result merging (higher = more prominent in results) */\n readonly priority: number\n\n /**\n * Whether `search()` applies `SearchOptions.indexDocFilter` inside its ranking query. Absent or\n * `false` means the strategy is skipped for filtered searches (fail closed).\n */\n readonly supportsIndexDocFilter?: boolean\n\n /** Check if strategy is available and configured */\n isAvailable(): Promise<boolean>\n\n /** Initialize strategy resources (lazy, called on first use) */\n ensureReady(): Promise<void>\n\n /** Execute a search query */\n search(query: string, options: SearchOptions): Promise<SearchResult[]>\n\n /** Index a record */\n index(record: IndexableRecord): Promise<void>\n\n /** Delete a record from the index */\n delete(entityId: EntityId, recordId: string, tenantId: string): Promise<void>\n\n /** Bulk index multiple records (optional optimization) */\n bulkIndex?(records: IndexableRecord[]): Promise<void>\n\n /** Purge all records for an entity type (optional) */\n purge?(entityId: EntityId, tenantId: string, organizationId?: string | null): Promise<void>\n}\n\n// =============================================================================\n// Service Configuration\n// =============================================================================\n\n/**\n * Configuration for result merging across strategies.\n */\nexport type ResultMergeConfig = {\n /** How to handle duplicate results: 'highest_score' | 'first' | 'merge_scores' */\n duplicateHandling: 'highest_score' | 'first' | 'merge_scores'\n /** Weight multipliers per strategy (e.g., { fulltext: 1.2, tokens: 0.8 }) */\n strategyWeights?: Record<SearchStrategyId, number>\n /** Minimum score threshold to include in results */\n minScore?: number\n}\n\n/**\n * Callback function to enrich search results with presenter data.\n * Used to load presenter from database when not available from search strategy.\n */\nexport type PresenterEnricherFn = (\n results: SearchResult[],\n tenantId: string,\n organizationId?: string | null,\n) => Promise<SearchResult[]>\n\n/**\n * Options for creating a SearchService instance.\n */\nexport type SearchServiceOptions = {\n /** Array of strategy instances */\n strategies?: SearchStrategy[]\n /** Default strategies to use when not specified in search options */\n defaultStrategies?: SearchStrategyId[]\n /** Fallback strategy when others fail */\n fallbackStrategy?: SearchStrategyId\n /** Configuration for merging results from multiple strategies */\n mergeConfig?: ResultMergeConfig\n /** Callback to enrich results with presenter data from database */\n presenterEnricher?: PresenterEnricherFn\n /** Resolve entity write restrictions; omission uses the registered search configurations. */\n resolveEntityStrategies?: (entityId: EntityId) => SearchStrategyId[] | undefined\n /** TTL (ms) for the per-strategy availability cache. Defaults to 2_000. */\n availabilityCacheTtlMs?: number\n}\n\n// =============================================================================\n// Module Configuration (for modules defining searchable entities)\n// =============================================================================\n\n/**\n * Context passed to buildSource, formatResult, resolveUrl, and resolveLinks.\n * `SearchIndexer` omits custom fields declared `encrypted` from `customFields`, from the record's\n * `cf:` / `cf_` keys and from records loaded through `queryEngine`; when their definitions cannot be\n * read, or the indexer was constructed without `encryptedCustomFieldKeysResolver`, it omits every\n * custom field.\n */\nexport type SearchBuildContext = {\n /** The record being indexed */\n record: Record<string, unknown>\n /** Custom fields for the record */\n customFields: Record<string, unknown>\n /** Organization ID if applicable */\n organizationId?: string | null\n /** Tenant ID */\n tenantId?: string | null\n /** DI container for resolving dependencies */\n container?: unknown\n /** Query engine for loading related records (optional, used by buildSource for entity hydration) */\n queryEngine?: unknown\n}\n\n/**\n * Source data for indexing a record.\n */\nexport type SearchIndexSource = {\n /** Text content for keyword/fuzzy search (single string or array of chunks) */\n text: string | string[]\n /** Optional structured fields for filtering */\n fields?: Record<string, unknown>\n /** Presenter for quick display in search results */\n presenter?: SearchResultPresenter\n /** Deep links for the result */\n links?: SearchResultLink[]\n /** Source object used for checksum calculation (change detection) */\n checksumSource?: unknown\n}\n\n/**\n * Policy defining how fields should be handled for search indexing.\n */\nexport type SearchFieldPolicy = {\n /** Fields safe to send to external providers (fuzzy searchable) */\n searchable?: string[]\n /** Fields for hash-based search only (encrypted/sensitive) */\n hashOnly?: string[]\n /** Fields to exclude from all search */\n excluded?: string[]\n}\n\n/**\n * Configuration for a single searchable entity within a module.\n */\nexport type SearchEntityConfig = {\n /** Entity identifier, e.g., 'customers:customer_person_profile' */\n entityId: EntityId\n /** Enable/disable search for this entity (default: true) */\n enabled?: boolean\n /** Override strategies for this specific entity */\n strategies?: SearchStrategyId[]\n /** Priority for result ordering (higher = more prominent) */\n priority?: number\n /** Build searchable content from record */\n buildSource?: (ctx: SearchBuildContext) => Promise<SearchIndexSource | null> | SearchIndexSource | null\n /** Format result for display in Cmd+K */\n formatResult?: (ctx: SearchBuildContext) => Promise<SearchResultPresenter | null> | SearchResultPresenter | null\n /** Resolve primary URL when result is clicked */\n resolveUrl?: (ctx: SearchBuildContext) => Promise<string | null> | string | null\n /** Resolve additional action links */\n resolveLinks?: (ctx: SearchBuildContext) => Promise<SearchResultLink[] | null> | SearchResultLink[] | null\n /** Define which fields are searchable vs hash-only */\n fieldPolicy?: SearchFieldPolicy\n /**\n * Per-entity view feature(s) required to read this entity's records through\n * data-returning surfaces (e.g. the `search_get` / `search_aggregate` AI tools).\n * These tools must NOT rely on the search-administration `search.view` feature\n * to gate record reads \u2014 callers must additionally hold the owning module's\n * `<entity>.view` feature(s) declared here. When omitted, those tools fail\n * closed (deny) so an entity is never exposed without an explicit grant.\n */\n aclFeatures?: string[]\n}\n\n/**\n * Module-level search configuration (defined in search.ts files).\n */\nexport type SearchModuleConfig = {\n /** Default strategies for all entities in this module */\n defaultStrategies?: SearchStrategyId[]\n /** Entity configurations */\n entities: SearchEntityConfig[]\n}\n\n// =============================================================================\n// Event Payloads (for indexer events)\n// =============================================================================\n\n/**\n * Payload for search.index_record events.\n */\nexport type SearchIndexPayload = {\n entityId: EntityId\n recordId: string\n tenantId: string\n organizationId?: string | null\n record: Record<string, unknown>\n customFields?: Record<string, unknown>\n}\n\n/**\n * Payload for search.delete_record events.\n */\nexport type SearchDeletePayload = {\n entityId: EntityId\n recordId: string\n tenantId: string\n}\n\n// =============================================================================\n// Global Registry for Search Module Configs\n// =============================================================================\n\nlet _searchModuleConfigs: SearchModuleConfig[] | null = null\n\n/**\n * Register search module configurations globally.\n * Called during app bootstrap with configs from search.generated.ts.\n */\nexport function registerSearchModuleConfigs(configs: SearchModuleConfig[]): void {\n if (_searchModuleConfigs !== null && process.env.NODE_ENV === 'development') {\n logger.debug('Search module configs re-registered (this may occur during HMR)')\n }\n _searchModuleConfigs = configs\n}\n\n/**\n * Get registered search module configurations.\n * Returns empty array if not registered (search module may not be enabled).\n */\nexport function getSearchModuleConfigs(): SearchModuleConfig[] {\n return _searchModuleConfigs ?? []\n}\n"],
5
- "mappings": "AACA,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,QAAQ,EAAE,MAAM,EAAE,WAAW,kBAAkB,CAAC;AAsY5E,IAAI,uBAAoD;AAMjD,SAAS,4BAA4B,SAAqC;AAC/E,MAAI,yBAAyB,QAAQ,QAAQ,IAAI,aAAa,eAAe;AAC3E,WAAO,MAAM,iEAAiE;AAAA,EAChF;AACA,yBAAuB;AACzB;AAMO,SAAS,yBAA+C;AAC7D,SAAO,wBAAwB,CAAC;AAClC;",
4
+ "sourcesContent": ["import type { EntityId } from './entities'\nimport { createLogger } from '../lib/logger'\nimport type { AuthContext } from '../lib/auth/server'\n\nconst logger = createLogger('shared').child({ component: 'search-registry' })\n\n// =============================================================================\n// Strategy Identifiers\n// =============================================================================\n\n/**\n * Built-in strategy identifiers plus extensible string for third-party strategies.\n */\nexport type SearchStrategyId = 'tokens' | 'vector' | 'fulltext' | (string & Record<string, never>)\n\n// =============================================================================\n// Result Types\n// =============================================================================\n\n/**\n * Presenter metadata for displaying search results in UI (Cmd+K, global search).\n */\nexport type SearchResultPresenter = {\n title: string\n subtitle?: string\n icon?: string\n /**\n * @deprecated No search UI renders this field, and none is planned \u2014 the Cmd+K dialog,\n * the topbar inline results and `/backend/search` render only `title`, `subtitle` and `icon`.\n * Slated for removal in 0.11.0.\n *\n * For an entity-type label, add a `search.entityType.<module>.<entity>` translation key\n * instead: every search surface already renders one next to the result title, so a badge\n * carrying the same word would render it twice. Declare that key in your own module's\n * `i18n/*.json` \u2014 dictionaries are merged flat across modules, so a `search.*` key\n * contributed by any module resolves normally. For per-record detail (a status, a\n * counterparty, a date), put the value in `subtitle`, which is rendered.\n */\n badge?: string\n}\n\n/**\n * Deep link rendered next to a search result.\n */\nexport type SearchResultLink = {\n href: string\n label: string\n kind?: 'primary' | 'secondary'\n}\n\n/**\n * A single search result returned by a strategy.\n */\nexport type SearchResult = {\n /** Entity type identifier, e.g., 'customers:customer_person_profile' */\n entityId: EntityId\n /** Record primary key */\n recordId: string\n /** Relevance score (normalized 0-1 range preferred, but RRF scores may exceed 1) */\n score: number\n /** Which strategy produced this result */\n source: SearchStrategyId\n /** Optional presenter for quick display */\n presenter?: SearchResultPresenter\n /** Primary URL when result is clicked */\n url?: string\n /** Additional action links */\n links?: SearchResultLink[]\n /** Extra metadata from the strategy */\n metadata?: Record<string, unknown>\n /** Organization scope of the result, when known by the strategy. */\n organizationId?: string | null\n}\n\n// =============================================================================\n// Search Options\n// =============================================================================\n\n/**\n * Options passed to SearchService.search()\n */\nexport type SearchOptions = {\n /** Tenant isolation - required */\n tenantId: string\n /**\n * Optional organization filter.\n * - `string` restricts results to that organization only.\n * - `undefined` or `null` means no organization filter (tenant-wide).\n */\n organizationId?: string | null\n /**\n * Optional organization allowlist.\n * - Non-empty array restricts results to one of those organizations.\n * - Empty array means no organizations are visible and should return no results.\n * - `undefined` or `null` means no organization filter (tenant-wide).\n *\n * `organizationId` takes precedence when both are provided.\n */\n organizationIds?: string[] | null\n /** Filter to specific entity types */\n entityTypes?: EntityId[]\n /** Use only specific strategies (defaults to all available) */\n strategies?: SearchStrategyId[]\n /** Maximum results per strategy before merging */\n limit?: number\n /** Offset for pagination */\n offset?: number\n /** How to combine results: 'or' merges all, 'and' requires match in all strategies */\n combineMode?: 'or' | 'and'\n /**\n * Restricts results to records whose query-index row (`entity_indexes`) matches this predicate,\n * evaluated inside the strategy's ranking query so a restrictive filter never starves the result\n * set (additive, 2026-10-06). Only strategies with `supportsIndexDocFilter: true` receive a\n * filtered search; any other strategy returns no results for it rather than unfiltered ones.\n */\n indexDocFilter?: SearchIndexDocFilter\n /**\n * Caller the search runs for (additive, 2026-11-13). Entities that declare\n * `SearchEntityConfig.filterResults` only return results when it is set: the\n * service passes it to the hook, and drops every result of such an entity when\n * the viewer is missing or the hook throws (fail closed). Entities without the\n * hook ignore it.\n */\n viewer?: SearchViewer\n}\n\n/**\n * Authenticated caller of a search, with the request container its visibility\n * checks resolve services from.\n */\nexport type SearchViewer = {\n auth: NonNullable<AuthContext>\n container?: unknown\n}\n\n/**\n * Input of `SearchEntityConfig.filterResults`: the merged results of one entity,\n * already tenant- and organization-scoped, plus the caller.\n */\nexport type SearchResultVisibilityContext = {\n entityId: EntityId\n results: SearchResult[]\n tenantId: string\n organizationId?: string | null\n organizationIds?: string[] | null\n viewer: SearchViewer\n}\n\n/**\n * One condition over a record's query-index document (`entity_indexes.doc`), with the query\n * engine's index-document semantics:\n * - `exists`: the key is present and not JSON `null`;\n * - `eq`: the key's text value equals `value` (booleans and numbers compare by their JSON text);\n * - `overlap`: the key holds an array sharing at least one entry with `values`; empty `values`\n * matches nothing;\n * - `noverlap`: the key holds an array sharing no entry with `values`; a missing key never matches;\n * - `recordIdNotIn`: the record id is none of `values`.\n */\nexport type SearchIndexDocCondition =\n | { op: 'exists'; key: string }\n | { op: 'eq'; key: string; value: string | number | boolean }\n | { op: 'overlap'; key: string; values: string[] }\n | { op: 'noverlap'; key: string; values: string[] }\n | { op: 'recordIdNotIn'; values: string[] }\n\n/**\n * A predicate over a record's `entity_indexes` row in disjunctive normal form: the record matches\n * when its index row is not deleted and every condition of at least one `anyOf` branch holds.\n * An empty `anyOf` matches nothing; an empty branch matches every indexed record.\n */\nexport type SearchIndexDocFilter = {\n anyOf: SearchIndexDocCondition[][]\n}\n\n// =============================================================================\n// Indexable Record\n// =============================================================================\n\n/**\n * A record prepared for indexing across all strategies.\n */\nexport type IndexableRecord = {\n /** Entity type identifier */\n entityId: EntityId\n /** Record primary key */\n recordId: string\n /** Tenant for isolation */\n tenantId: string\n /** Optional organization for additional filtering */\n organizationId?: string | null\n /** All fields from the record (strategies will filter based on their needs) */\n fields: Record<string, unknown>\n /** Custom-field keys excluded from plaintext fulltext/vector fields; `all` denies every custom field. Tokens retain `fields`; omission preserves legacy direct-client behavior. */\n plaintextExcludedCustomFields?: readonly string[] | 'all'\n /** Optional presenter for result display */\n presenter?: SearchResultPresenter\n /** Primary URL for the record */\n url?: string\n /** Additional action links */\n links?: SearchResultLink[]\n /** Text content for embedding (from buildSource, used by vector strategy) */\n text?: string | string[]\n /** Source object for checksum calculation (change detection) */\n checksumSource?: unknown\n}\n\n// =============================================================================\n// Strategy Interface\n// =============================================================================\n\n/**\n * Interface that all search strategies must implement.\n * Following the cache module's strategy pattern.\n */\nexport interface SearchStrategy {\n /** Unique strategy identifier */\n readonly id: SearchStrategyId\n\n /** Human-readable name for debugging/logging */\n readonly name: string\n\n /** Priority for result merging (higher = more prominent in results) */\n readonly priority: number\n\n /**\n * Whether `search()` applies `SearchOptions.indexDocFilter` inside its ranking query. Absent or\n * `false` means the strategy is skipped for filtered searches (fail closed).\n */\n readonly supportsIndexDocFilter?: boolean\n\n /** Check if strategy is available and configured */\n isAvailable(): Promise<boolean>\n\n /** Initialize strategy resources (lazy, called on first use) */\n ensureReady(): Promise<void>\n\n /** Execute a search query */\n search(query: string, options: SearchOptions): Promise<SearchResult[]>\n\n /** Index a record */\n index(record: IndexableRecord): Promise<void>\n\n /** Delete a record from the index */\n delete(entityId: EntityId, recordId: string, tenantId: string): Promise<void>\n\n /** Bulk index multiple records (optional optimization) */\n bulkIndex?(records: IndexableRecord[]): Promise<void>\n\n /** Purge all records for an entity type (optional) */\n purge?(entityId: EntityId, tenantId: string, organizationId?: string | null): Promise<void>\n}\n\n// =============================================================================\n// Service Configuration\n// =============================================================================\n\n/**\n * Configuration for result merging across strategies.\n */\nexport type ResultMergeConfig = {\n /** How to handle duplicate results: 'highest_score' | 'first' | 'merge_scores' */\n duplicateHandling: 'highest_score' | 'first' | 'merge_scores'\n /** Weight multipliers per strategy (e.g., { fulltext: 1.2, tokens: 0.8 }) */\n strategyWeights?: Record<SearchStrategyId, number>\n /** Minimum score threshold to include in results */\n minScore?: number\n}\n\n/**\n * Callback function to enrich search results with presenter data.\n * Used to load presenter from database when not available from search strategy.\n */\nexport type PresenterEnricherFn = (\n results: SearchResult[],\n tenantId: string,\n organizationId?: string | null,\n) => Promise<SearchResult[]>\n\n/**\n * Options for creating a SearchService instance.\n */\nexport type SearchServiceOptions = {\n /** Array of strategy instances */\n strategies?: SearchStrategy[]\n /** Default strategies to use when not specified in search options */\n defaultStrategies?: SearchStrategyId[]\n /** Fallback strategy when others fail */\n fallbackStrategy?: SearchStrategyId\n /** Configuration for merging results from multiple strategies */\n mergeConfig?: ResultMergeConfig\n /** Callback to enrich results with presenter data from database */\n presenterEnricher?: PresenterEnricherFn\n /** Resolve entity write restrictions; omission uses the registered search configurations. */\n resolveEntityStrategies?: (entityId: EntityId) => SearchStrategyId[] | undefined\n /** Resolve an entity's `filterResults` hook; omission skips per-record visibility filtering. */\n resolveResultFilter?: (entityId: EntityId) => SearchEntityConfig['filterResults'] | undefined\n /** TTL (ms) for the per-strategy availability cache. Defaults to 2_000. */\n availabilityCacheTtlMs?: number\n}\n\n// =============================================================================\n// Module Configuration (for modules defining searchable entities)\n// =============================================================================\n\n/**\n * Context passed to buildSource, formatResult, resolveUrl, and resolveLinks.\n * `SearchIndexer` omits custom fields declared `encrypted` from `customFields`, from the record's\n * `cf:` / `cf_` keys and from records loaded through `queryEngine`; when their definitions cannot be\n * read, or the indexer was constructed without `encryptedCustomFieldKeysResolver`, it omits every\n * custom field.\n */\nexport type SearchBuildContext = {\n /** The record being indexed */\n record: Record<string, unknown>\n /** Custom fields for the record */\n customFields: Record<string, unknown>\n /** Organization ID if applicable */\n organizationId?: string | null\n /** Tenant ID */\n tenantId?: string | null\n /** DI container for resolving dependencies */\n container?: unknown\n /** Query engine for loading related records (optional, used by buildSource for entity hydration) */\n queryEngine?: unknown\n}\n\n/**\n * Source data for indexing a record.\n */\nexport type SearchIndexSource = {\n /** Text content for keyword/fuzzy search (single string or array of chunks) */\n text: string | string[]\n /** Optional structured fields for filtering */\n fields?: Record<string, unknown>\n /** Presenter for quick display in search results */\n presenter?: SearchResultPresenter\n /** Deep links for the result */\n links?: SearchResultLink[]\n /** Source object used for checksum calculation (change detection) */\n checksumSource?: unknown\n}\n\n/**\n * Policy defining how fields should be handled for search indexing.\n */\nexport type SearchFieldPolicy = {\n /** Fields safe to send to external providers (fuzzy searchable) */\n searchable?: string[]\n /** Fields for hash-based search only (encrypted/sensitive) */\n hashOnly?: string[]\n /** Fields to exclude from all search */\n excluded?: string[]\n}\n\n/**\n * Configuration for a single searchable entity within a module.\n */\nexport type SearchEntityConfig = {\n /** Entity identifier, e.g., 'customers:customer_person_profile' */\n entityId: EntityId\n /** Enable/disable search for this entity (default: true) */\n enabled?: boolean\n /** Override strategies for this specific entity */\n strategies?: SearchStrategyId[]\n /** Priority for result ordering (higher = more prominent) */\n priority?: number\n /** Build searchable content from record */\n buildSource?: (ctx: SearchBuildContext) => Promise<SearchIndexSource | null> | SearchIndexSource | null\n /** Format result for display in Cmd+K */\n formatResult?: (ctx: SearchBuildContext) => Promise<SearchResultPresenter | null> | SearchResultPresenter | null\n /** Resolve primary URL when result is clicked */\n resolveUrl?: (ctx: SearchBuildContext) => Promise<string | null> | string | null\n /** Resolve additional action links */\n resolveLinks?: (ctx: SearchBuildContext) => Promise<SearchResultLink[] | null> | SearchResultLink[] | null\n /** Define which fields are searchable vs hash-only */\n fieldPolicy?: SearchFieldPolicy\n /**\n * Per-record index gate, evaluated by the search indexer before any strategy\n * (fulltext, vector, tokens) receives the record \u2014 on live index events,\n * by-id/batch indexing and every reindex path.\n *\n * Return `true` to index the record. Returning `false` \u2014 or throwing \u2014 removes\n * the record from every strategy and skips indexing (fail closed). The context\n * carries `queryEngine` for loading related records (opt-in flags, parents).\n * Omit the hook to index every record of the entity (the default).\n *\n * The query index applies the same gate before writing the entity's\n * `search_tokens`: it evaluates the hook per record (with a base-table query\n * engine) and writes tokens on `true`, or deletes that record's tokens on\n * `false` / a throw. Tokens therefore stay available without fulltext or vector\n * providers, and no token writer can surface a record the hook rejects.\n */\n shouldIndex?: (ctx: SearchBuildContext) => boolean | Promise<boolean>\n /**\n * Per-record result visibility, evaluated by `SearchService.search()` after\n * merging and before presenter enrichment (additive, 2026-11-13). Return the\n * subset of `results` (the same objects) the viewer may see; anything else is\n * dropped, and a returned object the service did not pass in is ignored. When the search has no\n * `SearchOptions.viewer`, or the hook throws, every result of the entity is\n * dropped (fail closed). Filtering runs after the strategies' `limit`, so a\n * search can return fewer results than requested. Omit the hook to keep every\n * scoped result (the default).\n */\n filterResults?: (ctx: SearchResultVisibilityContext) => Promise<SearchResult[]> | SearchResult[]\n /**\n * Per-entity view feature(s) required to read this entity's records through\n * data-returning surfaces (e.g. the `search_get` / `search_aggregate` AI tools).\n * These tools must NOT rely on the search-administration `search.view` feature\n * to gate record reads \u2014 callers must additionally hold the owning module's\n * `<entity>.view` feature(s) declared here. When omitted, those tools fail\n * closed (deny) so an entity is never exposed without an explicit grant.\n */\n aclFeatures?: string[]\n}\n\n/**\n * Module-level search configuration (defined in search.ts files).\n */\nexport type SearchModuleConfig = {\n /** Default strategies for all entities in this module */\n defaultStrategies?: SearchStrategyId[]\n /** Entity configurations */\n entities: SearchEntityConfig[]\n}\n\n// =============================================================================\n// Event Payloads (for indexer events)\n// =============================================================================\n\n/**\n * Payload for search.index_record events.\n */\nexport type SearchIndexPayload = {\n entityId: EntityId\n recordId: string\n tenantId: string\n organizationId?: string | null\n record: Record<string, unknown>\n customFields?: Record<string, unknown>\n}\n\n/**\n * Payload for search.delete_record events.\n */\nexport type SearchDeletePayload = {\n entityId: EntityId\n recordId: string\n tenantId: string\n}\n\n// =============================================================================\n// Global Registry for Search Module Configs\n// =============================================================================\n\nlet _searchModuleConfigs: SearchModuleConfig[] | null = null\n\n/**\n * Register search module configurations globally.\n * Called during app bootstrap with configs from search.generated.ts.\n */\nexport function registerSearchModuleConfigs(configs: SearchModuleConfig[]): void {\n if (_searchModuleConfigs !== null && process.env.NODE_ENV === 'development') {\n logger.debug('Search module configs re-registered (this may occur during HMR)')\n }\n _searchModuleConfigs = configs\n}\n\n/**\n * Get registered search module configurations.\n * Returns empty array if not registered (search module may not be enabled).\n */\nexport function getSearchModuleConfigs(): SearchModuleConfig[] {\n return _searchModuleConfigs ?? []\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAoB;AAG7B,MAAM,SAAS,aAAa,QAAQ,EAAE,MAAM,EAAE,WAAW,kBAAkB,CAAC;AAkc5E,IAAI,uBAAoD;AAMjD,SAAS,4BAA4B,SAAqC;AAC/E,MAAI,yBAAyB,QAAQ,QAAQ,IAAI,aAAa,eAAe;AAC3E,WAAO,MAAM,iEAAiE;AAAA,EAChF;AACA,yBAAuB;AACzB;AAMO,SAAS,yBAA+C;AAC7D,SAAO,wBAAwB,CAAC;AAClC;",
6
6
  "names": []
7
7
  }
@@ -9,9 +9,32 @@ function hasAllFeatures(granted, required) {
9
9
  if (!Array.isArray(granted) || !granted.length) return false;
10
10
  return required.every((feature) => hasFeature(granted, feature));
11
11
  }
12
+ function normalizeFeatures(features) {
13
+ return Array.from(new Set(features)).sort((left, right) => left < right ? -1 : left > right ? 1 : 0);
14
+ }
15
+ function intersectFeatureGrants(first, second) {
16
+ if (first.isSuperAdmin && second.isSuperAdmin) {
17
+ return { features: [], isSuperAdmin: true };
18
+ }
19
+ if (first.isSuperAdmin) {
20
+ return { features: normalizeFeatures(second.features), isSuperAdmin: false };
21
+ }
22
+ if (second.isSuperAdmin) {
23
+ return { features: normalizeFeatures(first.features), isSuperAdmin: false };
24
+ }
25
+ const kept = [];
26
+ for (const left of first.features) {
27
+ for (const right of second.features) {
28
+ if (matchFeature2(left, right)) kept.push(left);
29
+ else if (matchFeature2(right, left)) kept.push(right);
30
+ }
31
+ }
32
+ return { features: normalizeFeatures(kept), isSuperAdmin: false };
33
+ }
12
34
  export {
13
35
  hasAllFeatures,
14
36
  hasFeature,
37
+ intersectFeatureGrants,
15
38
  matchFeature
16
39
  };
17
40
  //# sourceMappingURL=features.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/security/features.ts"],
4
- "sourcesContent": ["export { matchFeature } from '../lib/auth/featureMatch'\nimport { matchFeature } from '../lib/auth/featureMatch'\n\nexport function hasFeature(granted: readonly string[] | undefined, required: string): boolean {\n if (!Array.isArray(granted) || !granted.length) return false\n return granted.some((feature) => matchFeature(required, feature))\n}\n\nexport function hasAllFeatures(\n granted: readonly string[] | undefined,\n required: readonly string[] | undefined\n): boolean {\n if (!required || required.length === 0) return true\n if (!Array.isArray(granted) || !granted.length) return false\n return required.every((feature) => hasFeature(granted, feature))\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,gBAAAA,qBAAoB;AAEtB,SAAS,WAAW,SAAwC,UAA2B;AAC5F,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,CAAC,QAAQ,OAAQ,QAAO;AACvD,SAAO,QAAQ,KAAK,CAAC,YAAYA,cAAa,UAAU,OAAO,CAAC;AAClE;AAEO,SAAS,eACd,SACA,UACS;AACT,MAAI,CAAC,YAAY,SAAS,WAAW,EAAG,QAAO;AAC/C,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,CAAC,QAAQ,OAAQ,QAAO;AACvD,SAAO,SAAS,MAAM,CAAC,YAAY,WAAW,SAAS,OAAO,CAAC;AACjE;",
4
+ "sourcesContent": ["export { matchFeature } from '../lib/auth/featureMatch'\nimport { matchFeature } from '../lib/auth/featureMatch'\n\nexport function hasFeature(granted: readonly string[] | undefined, required: string): boolean {\n if (!Array.isArray(granted) || !granted.length) return false\n return granted.some((feature) => matchFeature(required, feature))\n}\n\nexport function hasAllFeatures(\n granted: readonly string[] | undefined,\n required: readonly string[] | undefined\n): boolean {\n if (!required || required.length === 0) return true\n if (!Array.isArray(granted) || !granted.length) return false\n return required.every((feature) => hasFeature(granted, feature))\n}\n\nexport type FeatureGrantSet = {\n features: readonly string[]\n isSuperAdmin: boolean\n}\n\nfunction normalizeFeatures(features: readonly string[]): string[] {\n return Array.from(new Set(features)).sort((left, right) => (left < right ? -1 : left > right ? 1 : 0))\n}\n\nexport function intersectFeatureGrants(\n first: FeatureGrantSet,\n second: FeatureGrantSet,\n): FeatureGrantSet {\n if (first.isSuperAdmin && second.isSuperAdmin) {\n return { features: [], isSuperAdmin: true }\n }\n if (first.isSuperAdmin) {\n return { features: normalizeFeatures(second.features), isSuperAdmin: false }\n }\n if (second.isSuperAdmin) {\n return { features: normalizeFeatures(first.features), isSuperAdmin: false }\n }\n const kept: string[] = []\n for (const left of first.features) {\n for (const right of second.features) {\n if (matchFeature(left, right)) kept.push(left)\n else if (matchFeature(right, left)) kept.push(right)\n }\n }\n return { features: normalizeFeatures(kept), isSuperAdmin: false }\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,gBAAAA,qBAAoB;AAEtB,SAAS,WAAW,SAAwC,UAA2B;AAC5F,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,CAAC,QAAQ,OAAQ,QAAO;AACvD,SAAO,QAAQ,KAAK,CAAC,YAAYA,cAAa,UAAU,OAAO,CAAC;AAClE;AAEO,SAAS,eACd,SACA,UACS;AACT,MAAI,CAAC,YAAY,SAAS,WAAW,EAAG,QAAO;AAC/C,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,CAAC,QAAQ,OAAQ,QAAO;AACvD,SAAO,SAAS,MAAM,CAAC,YAAY,WAAW,SAAS,OAAO,CAAC;AACjE;AAOA,SAAS,kBAAkB,UAAuC;AAChE,SAAO,MAAM,KAAK,IAAI,IAAI,QAAQ,CAAC,EAAE,KAAK,CAAC,MAAM,UAAW,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI,CAAE;AACvG;AAEO,SAAS,uBACd,OACA,QACiB;AACjB,MAAI,MAAM,gBAAgB,OAAO,cAAc;AAC7C,WAAO,EAAE,UAAU,CAAC,GAAG,cAAc,KAAK;AAAA,EAC5C;AACA,MAAI,MAAM,cAAc;AACtB,WAAO,EAAE,UAAU,kBAAkB,OAAO,QAAQ,GAAG,cAAc,MAAM;AAAA,EAC7E;AACA,MAAI,OAAO,cAAc;AACvB,WAAO,EAAE,UAAU,kBAAkB,MAAM,QAAQ,GAAG,cAAc,MAAM;AAAA,EAC5E;AACA,QAAM,OAAiB,CAAC;AACxB,aAAW,QAAQ,MAAM,UAAU;AACjC,eAAW,SAAS,OAAO,UAAU;AACnC,UAAIA,cAAa,MAAM,KAAK,EAAG,MAAK,KAAK,IAAI;AAAA,eACpCA,cAAa,OAAO,IAAI,EAAG,MAAK,KAAK,KAAK;AAAA,IACrD;AAAA,EACF;AACA,SAAO,EAAE,UAAU,kBAAkB,IAAI,GAAG,cAAc,MAAM;AAClE;",
6
6
  "names": ["matchFeature"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/shared",
3
- "version": "0.10.1-develop.8279.1.7d4003fb64",
3
+ "version": "0.10.1-develop.8287.1.7313a0fe67",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -130,7 +130,7 @@
130
130
  "@mikro-orm/core": "^7.1.14",
131
131
  "@mikro-orm/decorators": "^7.1.14",
132
132
  "@mikro-orm/postgresql": "^7.1.14",
133
- "@open-mercato/cache": "0.10.1-develop.8279.1.7d4003fb64",
133
+ "@open-mercato/cache": "0.10.1-develop.8287.1.7313a0fe67",
134
134
  "@types/html-to-text": "^9.0.4",
135
135
  "@types/sanitize-html": "^2.16.1",
136
136
  "dotenv": "^17.4.2",
@@ -0,0 +1,12 @@
1
+ import { AGENT_REFERENCE_RESOLVER_DI_PREFIX, agentReferenceResolverDiKey } from '../referenceResolver'
2
+
3
+ describe('agentReferenceResolverDiKey', () => {
4
+ it('prefixes the resolver id with the reference resolver DI namespace', () => {
5
+ expect(AGENT_REFERENCE_RESOLVER_DI_PREFIX).toBe('agentReferenceResolver:')
6
+ expect(agentReferenceResolverDiKey('acme_compliance.rule')).toBe('agentReferenceResolver:acme_compliance.rule')
7
+ })
8
+
9
+ it('keeps the resolver id verbatim', () => {
10
+ expect(agentReferenceResolverDiKey('Kb.Article@v2')).toBe('agentReferenceResolver:Kb.Article@v2')
11
+ })
12
+ })
@@ -0,0 +1,124 @@
1
+ import {
2
+ RUN_OBSERVATION_MAX_KNOWLEDGE_KEYS,
3
+ RUN_OBSERVATION_MAX_RETRIEVAL_HITS,
4
+ bindRunObservation,
5
+ createRunObservationCollector,
6
+ getActiveRunObservationCollector,
7
+ reportKnowledgeVersion,
8
+ reportRetrieval,
9
+ } from '../run-observation'
10
+
11
+ const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
12
+
13
+ describe('run observation collector', () => {
14
+ it('is a no-op when no collector is bound', () => {
15
+ expect(getActiveRunObservationCollector()).toBeUndefined()
16
+ expect(() => reportKnowledgeVersion('rules.rule_set', 'v1')).not.toThrow()
17
+ expect(() => reportRetrieval({ source: 'kb', queryHash: 'q1', k: 3, hits: [] })).not.toThrow()
18
+ })
19
+
20
+ it('collects knowledge versions and retrievals inside a bound scope', async () => {
21
+ const collector = createRunObservationCollector()
22
+ const result = await bindRunObservation(collector, async () => {
23
+ reportKnowledgeVersion('rules.rule_set', '2026-10-20.3', { label: 'Rules' })
24
+ await delay(1)
25
+ reportRetrieval({ source: 'knowledge.articles', queryHash: 'abc', k: 2, hits: [{ ref: 'a1', score: 0.9 }] })
26
+ return 'done'
27
+ })
28
+ expect(result).toBe('done')
29
+ expect(collector.snapshot()).toEqual({
30
+ knowledge: { 'rules.rule_set': { version: '2026-10-20.3', label: 'Rules' } },
31
+ retrievals: [{ source: 'knowledge.articles', queryHash: 'abc', k: 2, hits: [{ ref: 'a1', score: 0.9 }] }],
32
+ dropped: { knowledgeKeys: 0, retrievalHits: 0 },
33
+ })
34
+ reportKnowledgeVersion('rules.other', 'v2')
35
+ expect(collector.snapshot().knowledge['rules.other']).toBeUndefined()
36
+ })
37
+
38
+ it('keeps concurrent runs isolated', async () => {
39
+ const first = createRunObservationCollector()
40
+ const second = createRunObservationCollector()
41
+ await Promise.all([
42
+ bindRunObservation(first, async () => {
43
+ await delay(5)
44
+ reportKnowledgeVersion('rules.rule_set', 'first')
45
+ await delay(5)
46
+ reportRetrieval({ source: 'first', queryHash: 'q', k: 1, hits: [] })
47
+ }),
48
+ bindRunObservation(second, async () => {
49
+ reportKnowledgeVersion('rules.rule_set', 'second')
50
+ await delay(8)
51
+ reportRetrieval({ source: 'second', queryHash: 'q', k: 1, hits: [] })
52
+ }),
53
+ ])
54
+ expect(first.snapshot().knowledge['rules.rule_set'].version).toBe('first')
55
+ expect(first.snapshot().retrievals.map((entry) => entry.source)).toEqual(['first'])
56
+ expect(second.snapshot().knowledge['rules.rule_set'].version).toBe('second')
57
+ expect(second.snapshot().retrievals.map((entry) => entry.source)).toEqual(['second'])
58
+ })
59
+
60
+ it('isolates nested binds and restores the outer collector afterwards', () => {
61
+ const outer = createRunObservationCollector()
62
+ const inner = createRunObservationCollector()
63
+ bindRunObservation(outer, () => {
64
+ reportKnowledgeVersion('outer.key', 'v1')
65
+ bindRunObservation(inner, () => {
66
+ reportKnowledgeVersion('inner.key', 'v1')
67
+ })
68
+ reportKnowledgeVersion('outer.after', 'v1')
69
+ })
70
+ expect(Object.keys(outer.snapshot().knowledge)).toEqual(['outer.key', 'outer.after'])
71
+ expect(Object.keys(inner.snapshot().knowledge)).toEqual(['inner.key'])
72
+ })
73
+
74
+ it('lets the last write per key win', () => {
75
+ const collector = createRunObservationCollector()
76
+ bindRunObservation(collector, () => {
77
+ reportKnowledgeVersion('rules.rule_set', 'v1', { label: 'Old' })
78
+ reportKnowledgeVersion('rules.rule_set', 'v2')
79
+ })
80
+ expect(collector.snapshot().knowledge).toEqual({ 'rules.rule_set': { version: 'v2' } })
81
+ })
82
+
83
+ it('ignores and counts invalid keys', () => {
84
+ const collector = createRunObservationCollector()
85
+ bindRunObservation(collector, () => {
86
+ reportKnowledgeVersion('nodot', 'v1')
87
+ reportKnowledgeVersion('Rules.RuleSet', 'v1')
88
+ reportKnowledgeVersion('a.b.c', 'v1')
89
+ reportKnowledgeVersion('rules.', 'v1')
90
+ reportKnowledgeVersion('knowledge.article_set', 'v1')
91
+ })
92
+ const snapshot = collector.snapshot()
93
+ expect(Object.keys(snapshot.knowledge)).toEqual(['knowledge.article_set'])
94
+ expect(snapshot.dropped.knowledgeKeys).toBe(4)
95
+ })
96
+
97
+ it('drops new keys beyond the limit but still updates existing ones', () => {
98
+ const collector = createRunObservationCollector()
99
+ bindRunObservation(collector, () => {
100
+ for (let index = 0; index < RUN_OBSERVATION_MAX_KNOWLEDGE_KEYS + 3; index += 1) {
101
+ reportKnowledgeVersion(`module.key_${index}`, 'v1')
102
+ }
103
+ reportKnowledgeVersion('module.key_0', 'v2')
104
+ })
105
+ const snapshot = collector.snapshot()
106
+ expect(Object.keys(snapshot.knowledge)).toHaveLength(RUN_OBSERVATION_MAX_KNOWLEDGE_KEYS)
107
+ expect(snapshot.knowledge['module.key_0'].version).toBe('v2')
108
+ expect(snapshot.knowledge[`module.key_${RUN_OBSERVATION_MAX_KNOWLEDGE_KEYS}`]).toBeUndefined()
109
+ expect(snapshot.dropped.knowledgeKeys).toBe(3)
110
+ })
111
+
112
+ it('caps hits per retrieval and counts the excess', () => {
113
+ const collector = createRunObservationCollector()
114
+ const hits = Array.from({ length: RUN_OBSERVATION_MAX_RETRIEVAL_HITS + 7 }, (_, index) => ({ ref: `doc-${index}` }))
115
+ bindRunObservation(collector, () => {
116
+ reportRetrieval({ source: 'kb', queryHash: 'q', k: hits.length, hits })
117
+ reportRetrieval({ source: 'kb', queryHash: 'q2', k: 1, hits: [{ ref: 'x' }] })
118
+ })
119
+ const snapshot = collector.snapshot()
120
+ expect(snapshot.retrievals[0].hits).toHaveLength(RUN_OBSERVATION_MAX_RETRIEVAL_HITS)
121
+ expect(snapshot.retrievals[1].hits).toEqual([{ ref: 'x' }])
122
+ expect(snapshot.dropped.retrievalHits).toBe(7)
123
+ })
124
+ })
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The reference resolver contract behind the agent orchestrator's
3
+ * `reference_exists` output-integrity rule (spec
4
+ * `2026-10-21-output-integrity-guardrails` → Rule kinds → `reference_exists`).
5
+ *
6
+ * The type lives in `shared` so OSS and app modules can register resolvers
7
+ * without depending on the enterprise package; the orchestrator resolves them
8
+ * soft-optionally from DI under `agentReferenceResolver:<resolverId>`.
9
+ *
10
+ * A resolver MUST be read-only, filter every lookup by the given scope, read
11
+ * through `findWithDecryption`, and answer the whole batch in one indexed
12
+ * lookup. Ids are compared exactly; a resolver that canonicalises ids (case,
13
+ * prefixes) MUST document it. The returned map is keyed by `ReferenceLookup.id`.
14
+ */
15
+ export type ReferenceResolverScope = { tenantId: string; organizationId: string }
16
+
17
+ export type ReferenceLookup = { id: string; version?: string | null }
18
+
19
+ export type ReferenceResolution =
20
+ | { status: 'exists'; version?: string | null }
21
+ | { status: 'not_found' }
22
+ | { status: 'version_mismatch'; currentVersion?: string | null }
23
+
24
+ export type AgentReferenceResolver = {
25
+ id: string
26
+ contractVersion: 1
27
+ resolve(refs: ReferenceLookup[], scope: ReferenceResolverScope): Promise<Map<string, ReferenceResolution>>
28
+ }
29
+
30
+ export const AGENT_REFERENCE_RESOLVER_DI_PREFIX = 'agentReferenceResolver:'
31
+
32
+ export function agentReferenceResolverDiKey(resolverId: string): string {
33
+ return `${AGENT_REFERENCE_RESOLVER_DI_PREFIX}${resolverId}`
34
+ }
@@ -0,0 +1,110 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks'
2
+
3
+ export const RUN_OBSERVATION_MAX_KNOWLEDGE_KEYS = 50
4
+ export const RUN_OBSERVATION_MAX_RETRIEVAL_HITS = 200
5
+
6
+ const KNOWLEDGE_KEY_PATTERN = /^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/
7
+
8
+ export type RunObservationKnowledgeEntry = {
9
+ version: string
10
+ label?: string
11
+ }
12
+
13
+ export type RunObservationRetrievalHit = {
14
+ ref: string
15
+ score?: number
16
+ version?: string
17
+ }
18
+
19
+ export type RunObservationRetrieval = {
20
+ source: string
21
+ queryHash: string
22
+ k: number
23
+ hits: RunObservationRetrievalHit[]
24
+ }
25
+
26
+ export type RunObservationSnapshot = {
27
+ knowledge: Record<string, RunObservationKnowledgeEntry>
28
+ retrievals: RunObservationRetrieval[]
29
+ dropped: {
30
+ knowledgeKeys: number
31
+ retrievalHits: number
32
+ }
33
+ }
34
+
35
+ export type RunObservationCollector = {
36
+ recordKnowledgeVersion(key: string, version: string, meta?: { label?: string }): void
37
+ recordRetrieval(entry: RunObservationRetrieval): void
38
+ snapshot(): RunObservationSnapshot
39
+ }
40
+
41
+ export function isValidKnowledgeKey(key: string): boolean {
42
+ return KNOWLEDGE_KEY_PATTERN.test(key)
43
+ }
44
+
45
+ export function createRunObservationCollector(): RunObservationCollector {
46
+ const knowledge = new Map<string, RunObservationKnowledgeEntry>()
47
+ const retrievals: RunObservationRetrieval[] = []
48
+ let droppedKnowledgeKeys = 0
49
+ let droppedRetrievalHits = 0
50
+
51
+ return {
52
+ recordKnowledgeVersion(key, version, meta) {
53
+ if (!isValidKnowledgeKey(key)) {
54
+ droppedKnowledgeKeys += 1
55
+ return
56
+ }
57
+ if (!knowledge.has(key) && knowledge.size >= RUN_OBSERVATION_MAX_KNOWLEDGE_KEYS) {
58
+ droppedKnowledgeKeys += 1
59
+ return
60
+ }
61
+ const entry: RunObservationKnowledgeEntry = { version }
62
+ if (meta?.label !== undefined) entry.label = meta.label
63
+ knowledge.set(key, entry)
64
+ },
65
+ recordRetrieval(entry) {
66
+ const keptHits = entry.hits.slice(0, RUN_OBSERVATION_MAX_RETRIEVAL_HITS).map((hit) => ({ ...hit }))
67
+ droppedRetrievalHits += entry.hits.length - keptHits.length
68
+ retrievals.push({ source: entry.source, queryHash: entry.queryHash, k: entry.k, hits: keptHits })
69
+ },
70
+ snapshot() {
71
+ const knowledgeSnapshot: Record<string, RunObservationKnowledgeEntry> = {}
72
+ for (const [key, entry] of knowledge) {
73
+ knowledgeSnapshot[key] = { ...entry }
74
+ }
75
+ return {
76
+ knowledge: knowledgeSnapshot,
77
+ retrievals: retrievals.map((retrieval) => ({
78
+ ...retrieval,
79
+ hits: retrieval.hits.map((hit) => ({ ...hit })),
80
+ })),
81
+ dropped: {
82
+ knowledgeKeys: droppedKnowledgeKeys,
83
+ retrievalHits: droppedRetrievalHits,
84
+ },
85
+ }
86
+ },
87
+ }
88
+ }
89
+
90
+ const runObservationStorage = new AsyncLocalStorage<RunObservationCollector>()
91
+
92
+ export function bindRunObservation<T>(collector: RunObservationCollector, fn: () => T): T {
93
+ return runObservationStorage.run(collector, fn)
94
+ }
95
+
96
+ export function getActiveRunObservationCollector(): RunObservationCollector | undefined {
97
+ return runObservationStorage.getStore()
98
+ }
99
+
100
+ export function reportKnowledgeVersion(key: string, version: string, meta?: { label?: string }): void {
101
+ const collector = runObservationStorage.getStore()
102
+ if (!collector) return
103
+ collector.recordKnowledgeVersion(key, version, meta)
104
+ }
105
+
106
+ export function reportRetrieval(entry: RunObservationRetrieval): void {
107
+ const collector = runObservationStorage.getStore()
108
+ if (!collector) return
109
+ collector.recordRetrieval(entry)
110
+ }
@@ -0,0 +1,48 @@
1
+ import {
2
+ getAmbientAuditCorrelation,
3
+ withAuditCorrelation,
4
+ } from '@open-mercato/shared/lib/commands/auditCorrelationScope'
5
+
6
+ describe('auditCorrelationScope', () => {
7
+ it('returns null outside any scope', () => {
8
+ expect(getAmbientAuditCorrelation()).toBeNull()
9
+ })
10
+
11
+ it('exposes the correlation inside a scope and across awaits', async () => {
12
+ const seen = await withAuditCorrelation({ agentRunId: 'run-1' }, async () => {
13
+ await new Promise((resolve) => setTimeout(resolve, 1))
14
+ return getAmbientAuditCorrelation()
15
+ })
16
+ expect(seen).toEqual({ agentRunId: 'run-1' })
17
+ expect(getAmbientAuditCorrelation()).toBeNull()
18
+ })
19
+
20
+ it('merges nested scopes with the inner scope winning for the same key', () => {
21
+ const seen = withAuditCorrelation({ agentRunId: 'outer', workflowInstanceId: 'wf-1' }, () =>
22
+ withAuditCorrelation({ agentRunId: 'inner', proposalId: 'prop-1' }, () => getAmbientAuditCorrelation()),
23
+ )
24
+ expect(seen).toEqual({ agentRunId: 'inner', workflowInstanceId: 'wf-1', proposalId: 'prop-1' })
25
+ })
26
+
27
+ it('restores the outer correlation after a nested scope ends', () => {
28
+ const seen = withAuditCorrelation({ agentRunId: 'outer' }, () => {
29
+ withAuditCorrelation({ agentRunId: 'inner' }, () => undefined)
30
+ return getAmbientAuditCorrelation()
31
+ })
32
+ expect(seen).toEqual({ agentRunId: 'outer' })
33
+ })
34
+
35
+ it('drops empty and non-string values', () => {
36
+ const correlation = { agentRunId: 'run-1', empty: '', count: 3 } as unknown as Record<string, string>
37
+ const seen = withAuditCorrelation(correlation, () => getAmbientAuditCorrelation())
38
+ expect(seen).toEqual({ agentRunId: 'run-1' })
39
+ })
40
+
41
+ it('returns a copy that callers cannot use to mutate the scope', () => {
42
+ withAuditCorrelation({ agentRunId: 'run-1' }, () => {
43
+ const first = getAmbientAuditCorrelation()
44
+ if (first) first.agentRunId = 'tampered'
45
+ expect(getAmbientAuditCorrelation()).toEqual({ agentRunId: 'run-1' })
46
+ })
47
+ })
48
+ })