@open-mercato/shared 0.10.1-develop.8279.1.7d4003fb64 → 0.10.1-develop.8289.1.9a25111d49

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,3 +1,3 @@
1
1
  [generate-countries] up to date (259 countries)
2
- [build:shared] found 333 entry points
2
+ [build:shared] found 336 entry points
3
3
  [build:shared] built successfully
@@ -0,0 +1,9 @@
1
+ const AGENT_REFERENCE_RESOLVER_DI_PREFIX = "agentReferenceResolver:";
2
+ function agentReferenceResolverDiKey(resolverId) {
3
+ return `${AGENT_REFERENCE_RESOLVER_DI_PREFIX}${resolverId}`;
4
+ }
5
+ export {
6
+ AGENT_REFERENCE_RESOLVER_DI_PREFIX,
7
+ agentReferenceResolverDiKey
8
+ };
9
+ //# sourceMappingURL=referenceResolver.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/lib/ai/referenceResolver.ts"],
4
+ "sourcesContent": ["/**\n * The reference resolver contract behind the agent orchestrator's\n * `reference_exists` output-integrity rule (spec\n * `2026-10-21-output-integrity-guardrails` \u2192 Rule kinds \u2192 `reference_exists`).\n *\n * The type lives in `shared` so OSS and app modules can register resolvers\n * without depending on the enterprise package; the orchestrator resolves them\n * soft-optionally from DI under `agentReferenceResolver:<resolverId>`.\n *\n * A resolver MUST be read-only, filter every lookup by the given scope, read\n * through `findWithDecryption`, and answer the whole batch in one indexed\n * lookup. Ids are compared exactly; a resolver that canonicalises ids (case,\n * prefixes) MUST document it. The returned map is keyed by `ReferenceLookup.id`.\n */\nexport type ReferenceResolverScope = { tenantId: string; organizationId: string }\n\nexport type ReferenceLookup = { id: string; version?: string | null }\n\nexport type ReferenceResolution =\n | { status: 'exists'; version?: string | null }\n | { status: 'not_found' }\n | { status: 'version_mismatch'; currentVersion?: string | null }\n\nexport type AgentReferenceResolver = {\n id: string\n contractVersion: 1\n resolve(refs: ReferenceLookup[], scope: ReferenceResolverScope): Promise<Map<string, ReferenceResolution>>\n}\n\nexport const AGENT_REFERENCE_RESOLVER_DI_PREFIX = 'agentReferenceResolver:'\n\nexport function agentReferenceResolverDiKey(resolverId: string): string {\n return `${AGENT_REFERENCE_RESOLVER_DI_PREFIX}${resolverId}`\n}\n"],
5
+ "mappings": "AA6BO,MAAM,qCAAqC;AAE3C,SAAS,4BAA4B,YAA4B;AACtE,SAAO,GAAG,kCAAkC,GAAG,UAAU;AAC3D;",
6
+ "names": []
7
+ }
@@ -0,0 +1,78 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ const RUN_OBSERVATION_MAX_KNOWLEDGE_KEYS = 50;
3
+ const RUN_OBSERVATION_MAX_RETRIEVAL_HITS = 200;
4
+ const KNOWLEDGE_KEY_PATTERN = /^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/;
5
+ function isValidKnowledgeKey(key) {
6
+ return KNOWLEDGE_KEY_PATTERN.test(key);
7
+ }
8
+ function createRunObservationCollector() {
9
+ const knowledge = /* @__PURE__ */ new Map();
10
+ const retrievals = [];
11
+ let droppedKnowledgeKeys = 0;
12
+ let droppedRetrievalHits = 0;
13
+ return {
14
+ recordKnowledgeVersion(key, version, meta) {
15
+ if (!isValidKnowledgeKey(key)) {
16
+ droppedKnowledgeKeys += 1;
17
+ return;
18
+ }
19
+ if (!knowledge.has(key) && knowledge.size >= RUN_OBSERVATION_MAX_KNOWLEDGE_KEYS) {
20
+ droppedKnowledgeKeys += 1;
21
+ return;
22
+ }
23
+ const entry = { version };
24
+ if (meta?.label !== void 0) entry.label = meta.label;
25
+ knowledge.set(key, entry);
26
+ },
27
+ recordRetrieval(entry) {
28
+ const keptHits = entry.hits.slice(0, RUN_OBSERVATION_MAX_RETRIEVAL_HITS).map((hit) => ({ ...hit }));
29
+ droppedRetrievalHits += entry.hits.length - keptHits.length;
30
+ retrievals.push({ source: entry.source, queryHash: entry.queryHash, k: entry.k, hits: keptHits });
31
+ },
32
+ snapshot() {
33
+ const knowledgeSnapshot = {};
34
+ for (const [key, entry] of knowledge) {
35
+ knowledgeSnapshot[key] = { ...entry };
36
+ }
37
+ return {
38
+ knowledge: knowledgeSnapshot,
39
+ retrievals: retrievals.map((retrieval) => ({
40
+ ...retrieval,
41
+ hits: retrieval.hits.map((hit) => ({ ...hit }))
42
+ })),
43
+ dropped: {
44
+ knowledgeKeys: droppedKnowledgeKeys,
45
+ retrievalHits: droppedRetrievalHits
46
+ }
47
+ };
48
+ }
49
+ };
50
+ }
51
+ const runObservationStorage = new AsyncLocalStorage();
52
+ function bindRunObservation(collector, fn) {
53
+ return runObservationStorage.run(collector, fn);
54
+ }
55
+ function getActiveRunObservationCollector() {
56
+ return runObservationStorage.getStore();
57
+ }
58
+ function reportKnowledgeVersion(key, version, meta) {
59
+ const collector = runObservationStorage.getStore();
60
+ if (!collector) return;
61
+ collector.recordKnowledgeVersion(key, version, meta);
62
+ }
63
+ function reportRetrieval(entry) {
64
+ const collector = runObservationStorage.getStore();
65
+ if (!collector) return;
66
+ collector.recordRetrieval(entry);
67
+ }
68
+ export {
69
+ RUN_OBSERVATION_MAX_KNOWLEDGE_KEYS,
70
+ RUN_OBSERVATION_MAX_RETRIEVAL_HITS,
71
+ bindRunObservation,
72
+ createRunObservationCollector,
73
+ getActiveRunObservationCollector,
74
+ isValidKnowledgeKey,
75
+ reportKnowledgeVersion,
76
+ reportRetrieval
77
+ };
78
+ //# sourceMappingURL=run-observation.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/lib/ai/run-observation.ts"],
4
+ "sourcesContent": ["import { AsyncLocalStorage } from 'node:async_hooks'\n\nexport const RUN_OBSERVATION_MAX_KNOWLEDGE_KEYS = 50\nexport const RUN_OBSERVATION_MAX_RETRIEVAL_HITS = 200\n\nconst KNOWLEDGE_KEY_PATTERN = /^[a-z][a-z0-9_]*\\.[a-z][a-z0-9_]*$/\n\nexport type RunObservationKnowledgeEntry = {\n version: string\n label?: string\n}\n\nexport type RunObservationRetrievalHit = {\n ref: string\n score?: number\n version?: string\n}\n\nexport type RunObservationRetrieval = {\n source: string\n queryHash: string\n k: number\n hits: RunObservationRetrievalHit[]\n}\n\nexport type RunObservationSnapshot = {\n knowledge: Record<string, RunObservationKnowledgeEntry>\n retrievals: RunObservationRetrieval[]\n dropped: {\n knowledgeKeys: number\n retrievalHits: number\n }\n}\n\nexport type RunObservationCollector = {\n recordKnowledgeVersion(key: string, version: string, meta?: { label?: string }): void\n recordRetrieval(entry: RunObservationRetrieval): void\n snapshot(): RunObservationSnapshot\n}\n\nexport function isValidKnowledgeKey(key: string): boolean {\n return KNOWLEDGE_KEY_PATTERN.test(key)\n}\n\nexport function createRunObservationCollector(): RunObservationCollector {\n const knowledge = new Map<string, RunObservationKnowledgeEntry>()\n const retrievals: RunObservationRetrieval[] = []\n let droppedKnowledgeKeys = 0\n let droppedRetrievalHits = 0\n\n return {\n recordKnowledgeVersion(key, version, meta) {\n if (!isValidKnowledgeKey(key)) {\n droppedKnowledgeKeys += 1\n return\n }\n if (!knowledge.has(key) && knowledge.size >= RUN_OBSERVATION_MAX_KNOWLEDGE_KEYS) {\n droppedKnowledgeKeys += 1\n return\n }\n const entry: RunObservationKnowledgeEntry = { version }\n if (meta?.label !== undefined) entry.label = meta.label\n knowledge.set(key, entry)\n },\n recordRetrieval(entry) {\n const keptHits = entry.hits.slice(0, RUN_OBSERVATION_MAX_RETRIEVAL_HITS).map((hit) => ({ ...hit }))\n droppedRetrievalHits += entry.hits.length - keptHits.length\n retrievals.push({ source: entry.source, queryHash: entry.queryHash, k: entry.k, hits: keptHits })\n },\n snapshot() {\n const knowledgeSnapshot: Record<string, RunObservationKnowledgeEntry> = {}\n for (const [key, entry] of knowledge) {\n knowledgeSnapshot[key] = { ...entry }\n }\n return {\n knowledge: knowledgeSnapshot,\n retrievals: retrievals.map((retrieval) => ({\n ...retrieval,\n hits: retrieval.hits.map((hit) => ({ ...hit })),\n })),\n dropped: {\n knowledgeKeys: droppedKnowledgeKeys,\n retrievalHits: droppedRetrievalHits,\n },\n }\n },\n }\n}\n\nconst runObservationStorage = new AsyncLocalStorage<RunObservationCollector>()\n\nexport function bindRunObservation<T>(collector: RunObservationCollector, fn: () => T): T {\n return runObservationStorage.run(collector, fn)\n}\n\nexport function getActiveRunObservationCollector(): RunObservationCollector | undefined {\n return runObservationStorage.getStore()\n}\n\nexport function reportKnowledgeVersion(key: string, version: string, meta?: { label?: string }): void {\n const collector = runObservationStorage.getStore()\n if (!collector) return\n collector.recordKnowledgeVersion(key, version, meta)\n}\n\nexport function reportRetrieval(entry: RunObservationRetrieval): void {\n const collector = runObservationStorage.getStore()\n if (!collector) return\n collector.recordRetrieval(entry)\n}\n"],
5
+ "mappings": "AAAA,SAAS,yBAAyB;AAE3B,MAAM,qCAAqC;AAC3C,MAAM,qCAAqC;AAElD,MAAM,wBAAwB;AAmCvB,SAAS,oBAAoB,KAAsB;AACxD,SAAO,sBAAsB,KAAK,GAAG;AACvC;AAEO,SAAS,gCAAyD;AACvE,QAAM,YAAY,oBAAI,IAA0C;AAChE,QAAM,aAAwC,CAAC;AAC/C,MAAI,uBAAuB;AAC3B,MAAI,uBAAuB;AAE3B,SAAO;AAAA,IACL,uBAAuB,KAAK,SAAS,MAAM;AACzC,UAAI,CAAC,oBAAoB,GAAG,GAAG;AAC7B,gCAAwB;AACxB;AAAA,MACF;AACA,UAAI,CAAC,UAAU,IAAI,GAAG,KAAK,UAAU,QAAQ,oCAAoC;AAC/E,gCAAwB;AACxB;AAAA,MACF;AACA,YAAM,QAAsC,EAAE,QAAQ;AACtD,UAAI,MAAM,UAAU,OAAW,OAAM,QAAQ,KAAK;AAClD,gBAAU,IAAI,KAAK,KAAK;AAAA,IAC1B;AAAA,IACA,gBAAgB,OAAO;AACrB,YAAM,WAAW,MAAM,KAAK,MAAM,GAAG,kCAAkC,EAAE,IAAI,CAAC,SAAS,EAAE,GAAG,IAAI,EAAE;AAClG,8BAAwB,MAAM,KAAK,SAAS,SAAS;AACrD,iBAAW,KAAK,EAAE,QAAQ,MAAM,QAAQ,WAAW,MAAM,WAAW,GAAG,MAAM,GAAG,MAAM,SAAS,CAAC;AAAA,IAClG;AAAA,IACA,WAAW;AACT,YAAM,oBAAkE,CAAC;AACzE,iBAAW,CAAC,KAAK,KAAK,KAAK,WAAW;AACpC,0BAAkB,GAAG,IAAI,EAAE,GAAG,MAAM;AAAA,MACtC;AACA,aAAO;AAAA,QACL,WAAW;AAAA,QACX,YAAY,WAAW,IAAI,CAAC,eAAe;AAAA,UACzC,GAAG;AAAA,UACH,MAAM,UAAU,KAAK,IAAI,CAAC,SAAS,EAAE,GAAG,IAAI,EAAE;AAAA,QAChD,EAAE;AAAA,QACF,SAAS;AAAA,UACP,eAAe;AAAA,UACf,eAAe;AAAA,QACjB;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,MAAM,wBAAwB,IAAI,kBAA2C;AAEtE,SAAS,mBAAsB,WAAoC,IAAgB;AACxF,SAAO,sBAAsB,IAAI,WAAW,EAAE;AAChD;AAEO,SAAS,mCAAwE;AACtF,SAAO,sBAAsB,SAAS;AACxC;AAEO,SAAS,uBAAuB,KAAa,SAAiB,MAAiC;AACpG,QAAM,YAAY,sBAAsB,SAAS;AACjD,MAAI,CAAC,UAAW;AAChB,YAAU,uBAAuB,KAAK,SAAS,IAAI;AACrD;AAEO,SAAS,gBAAgB,OAAsC;AACpE,QAAM,YAAY,sBAAsB,SAAS;AACjD,MAAI,CAAC,UAAW;AAChB,YAAU,gBAAgB,KAAK;AACjC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,32 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ const AUDIT_CORRELATION_STORAGE_KEY = /* @__PURE__ */ Symbol.for("@open-mercato/shared/commands/audit-correlation");
3
+ function resolveAuditCorrelationStorage() {
4
+ const scope = globalThis;
5
+ if (!scope[AUDIT_CORRELATION_STORAGE_KEY]) {
6
+ scope[AUDIT_CORRELATION_STORAGE_KEY] = new AsyncLocalStorage();
7
+ }
8
+ return scope[AUDIT_CORRELATION_STORAGE_KEY];
9
+ }
10
+ const auditCorrelationStorage = resolveAuditCorrelationStorage();
11
+ function sanitizeCorrelation(correlation) {
12
+ const sanitized = {};
13
+ if (!correlation || typeof correlation !== "object" || Array.isArray(correlation)) return sanitized;
14
+ for (const [key, value] of Object.entries(correlation)) {
15
+ if (typeof value === "string" && value.length > 0) sanitized[key] = value;
16
+ }
17
+ return sanitized;
18
+ }
19
+ function withAuditCorrelation(correlation, fn) {
20
+ const merged = { ...auditCorrelationStorage.getStore() ?? {}, ...sanitizeCorrelation(correlation) };
21
+ return auditCorrelationStorage.run(Object.freeze(merged), fn);
22
+ }
23
+ function getAmbientAuditCorrelation() {
24
+ const current = auditCorrelationStorage.getStore();
25
+ if (!current || Object.keys(current).length === 0) return null;
26
+ return { ...current };
27
+ }
28
+ export {
29
+ getAmbientAuditCorrelation,
30
+ withAuditCorrelation
31
+ };
32
+ //# sourceMappingURL=auditCorrelationScope.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/lib/commands/auditCorrelationScope.ts"],
4
+ "sourcesContent": ["import { AsyncLocalStorage } from 'node:async_hooks'\n\n/**\n * Keyed off globalThis so duplicated bundle chunks of this module share one\n * AsyncLocalStorage; otherwise a scope entered through one copy would be\n * invisible to the command bus reading another (same fix as the cache tenant\n * context).\n */\nconst AUDIT_CORRELATION_STORAGE_KEY = Symbol.for('@open-mercato/shared/commands/audit-correlation')\n\ntype AuditCorrelation = Readonly<Record<string, string>>\n\ntype GlobalWithAuditCorrelationStorage = typeof globalThis & {\n [AUDIT_CORRELATION_STORAGE_KEY]?: AsyncLocalStorage<AuditCorrelation>\n}\n\nfunction resolveAuditCorrelationStorage(): AsyncLocalStorage<AuditCorrelation> {\n const scope = globalThis as GlobalWithAuditCorrelationStorage\n if (!scope[AUDIT_CORRELATION_STORAGE_KEY]) {\n scope[AUDIT_CORRELATION_STORAGE_KEY] = new AsyncLocalStorage<AuditCorrelation>()\n }\n return scope[AUDIT_CORRELATION_STORAGE_KEY]\n}\n\nconst auditCorrelationStorage = resolveAuditCorrelationStorage()\n\nfunction sanitizeCorrelation(correlation: Record<string, unknown> | null | undefined): Record<string, string> {\n const sanitized: Record<string, string> = {}\n if (!correlation || typeof correlation !== 'object' || Array.isArray(correlation)) return sanitized\n for (const [key, value] of Object.entries(correlation)) {\n if (typeof value === 'string' && value.length > 0) sanitized[key] = value\n }\n return sanitized\n}\n\n/**\n * Runs `fn` with an ambient audit correlation that the command bus merges into\n * every action log written inside the async scope. Nested scopes merge, with\n * the inner scope winning for the same key. Explicit `ctx.auditCorrelation`\n * and existing log context keys always take precedence over the ambient value.\n */\nexport function withAuditCorrelation<T>(correlation: Record<string, string>, fn: () => T): T\nexport function withAuditCorrelation<T>(correlation: Record<string, string>, fn: () => Promise<T>): Promise<T>\nexport function withAuditCorrelation<T>(correlation: Record<string, string>, fn: () => T | Promise<T>): T | Promise<T> {\n const merged = { ...(auditCorrelationStorage.getStore() ?? {}), ...sanitizeCorrelation(correlation) }\n return auditCorrelationStorage.run(Object.freeze(merged), fn)\n}\n\nexport function getAmbientAuditCorrelation(): Record<string, string> | null {\n const current = auditCorrelationStorage.getStore()\n if (!current || Object.keys(current).length === 0) return null\n return { ...current }\n}\n"],
5
+ "mappings": "AAAA,SAAS,yBAAyB;AAQlC,MAAM,gCAAgC,uBAAO,IAAI,iDAAiD;AAQlG,SAAS,iCAAsE;AAC7E,QAAM,QAAQ;AACd,MAAI,CAAC,MAAM,6BAA6B,GAAG;AACzC,UAAM,6BAA6B,IAAI,IAAI,kBAAoC;AAAA,EACjF;AACA,SAAO,MAAM,6BAA6B;AAC5C;AAEA,MAAM,0BAA0B,+BAA+B;AAE/D,SAAS,oBAAoB,aAAiF;AAC5G,QAAM,YAAoC,CAAC;AAC3C,MAAI,CAAC,eAAe,OAAO,gBAAgB,YAAY,MAAM,QAAQ,WAAW,EAAG,QAAO;AAC1F,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,WAAW,GAAG;AACtD,QAAI,OAAO,UAAU,YAAY,MAAM,SAAS,EAAG,WAAU,GAAG,IAAI;AAAA,EACtE;AACA,SAAO;AACT;AAUO,SAAS,qBAAwB,aAAqC,IAA0C;AACrH,QAAM,SAAS,EAAE,GAAI,wBAAwB,SAAS,KAAK,CAAC,GAAI,GAAG,oBAAoB,WAAW,EAAE;AACpG,SAAO,wBAAwB,IAAI,OAAO,OAAO,MAAM,GAAG,EAAE;AAC9D;AAEO,SAAS,6BAA4D;AAC1E,QAAM,UAAU,wBAAwB,SAAS;AACjD,MAAI,CAAC,WAAW,OAAO,KAAK,OAAO,EAAE,WAAW,EAAG,QAAO;AAC1D,SAAO,EAAE,GAAG,QAAQ;AACtB;",
6
+ "names": []
7
+ }
@@ -19,6 +19,7 @@ import { CommandInterceptorError } from "./errors.js";
19
19
  import { isReadProjectionAlwaysConsistent } from "@open-mercato/shared/lib/data/consistency";
20
20
  import { createLogger } from "../logger/index.js";
21
21
  import { withAtomicFlush } from "./flush.js";
22
+ import { getAmbientAuditCorrelation } from "./auditCorrelationScope.js";
22
23
  import { getTelemetryRuntime } from "../telemetry/runtime.js";
23
24
  import {
24
25
  getTransactionLifetime,
@@ -56,6 +57,24 @@ function asRecord(input) {
56
57
  if (!input || typeof input !== "object" || Array.isArray(input)) return null;
57
58
  return input;
58
59
  }
60
+ function mergeAuditCorrelation(baseContext, auditCorrelation) {
61
+ const incoming = asRecord(auditCorrelation);
62
+ if (!incoming) return null;
63
+ const context = baseContext ?? {};
64
+ const existingValue = context.correlation;
65
+ const existing = asRecord(existingValue);
66
+ if (existingValue !== void 0 && existingValue !== null && !existing) return null;
67
+ const merged = { ...existing ?? {} };
68
+ let added = false;
69
+ for (const [key, value] of Object.entries(incoming)) {
70
+ if (typeof value !== "string" || value.length === 0) continue;
71
+ if (Object.prototype.hasOwnProperty.call(merged, key)) continue;
72
+ merged[key] = value;
73
+ added = true;
74
+ }
75
+ if (!added) return null;
76
+ return { ...context, correlation: merged };
77
+ }
59
78
  function extractPrimaryIdFromCommandResult(result) {
60
79
  const r = asRecord(result);
61
80
  if (!r) return null;
@@ -842,6 +861,10 @@ class CommandBus {
842
861
  const baseContext = asRecord(payload.context) ?? {};
843
862
  payload.context = { ...baseContext, source: runAs.source };
844
863
  }
864
+ const correlationContext = mergeAuditCorrelation(asRecord(payload.context), options.ctx.auditCorrelation);
865
+ if (correlationContext) payload.context = correlationContext;
866
+ const ambientCorrelationContext = mergeAuditCorrelation(asRecord(payload.context), getAmbientAuditCorrelation());
867
+ if (ambientCorrelationContext) payload.context = ambientCorrelationContext;
845
868
  if (metadata.replayable === false) {
846
869
  delete payload.commandPayload;
847
870
  } else {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/commands/command-bus.ts"],
4
- "sourcesContent": ["import type { ActionLog } from '@open-mercato/core/modules/audit_logs/data/entities'\nimport type { ActionLogCreateInput } from '@open-mercato/core/modules/audit_logs/data/validators'\nimport { commandRegistry } from './registry'\nimport type {\n BulkImportSuppression,\n CommandExecutionOptions,\n CommandExecuteResult,\n CommandHandler,\n CommandLogBuilderArgs,\n CommandLogMetadata,\n CommandRuntimeContext,\n CommandUndoLogEntry,\n} from './types'\nimport { defaultUndoToken } from './types'\nimport type { AwilixContainer } from 'awilix'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport {\n canonicalizeResourceTag,\n deriveResourceFromCommandId,\n invalidateCrudCache,\n pickFirstIdentifier,\n isCrudCacheDebugEnabled,\n} from '@open-mercato/shared/lib/crud/cache'\nimport { normalizeCustomFieldKey } from '@open-mercato/shared/lib/custom-fields/keys'\nimport { getAllCommandInterceptorInstances } from './command-interceptor-store'\nimport {\n runCommandInterceptorsBefore,\n runCommandInterceptorsAfter,\n runCommandInterceptorsBeforeUndo,\n runCommandInterceptorsAfterUndo,\n} from './command-interceptor-runner'\nimport type { CommandInterceptorContext } from './command-interceptor'\nimport { CommandInterceptorError } from './errors'\nimport { isReadProjectionAlwaysConsistent } from '@open-mercato/shared/lib/data/consistency'\nimport { createLogger } from '../logger'\nimport { withAtomicFlush } from './flush'\nimport { getTelemetryRuntime } from '../telemetry/runtime'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n getTransactionLifetime,\n onTransactionLifetimeComplete,\n ownsTransactionLifetime,\n type TransactionLifetime,\n} from './transaction-lifetime'\n\nconst logger = createLogger('shared').child({ component: 'commands' })\n\ntype CommandActionLogService = {\n findByUndoToken(undoToken: string): Promise<ActionLog | null>\n claimForUndo(id: string, transactionalEm?: EntityManager): Promise<boolean>\n releaseUndoClaim(id: string, transactionalEm?: EntityManager): Promise<boolean>\n markUndone(id: string, traceInput?: ActionLogCreateInput, transactionalEm?: EntityManager): Promise<ActionLog | null | void>\n claimForRedo(id: string, transactionalEm?: EntityManager): Promise<boolean>\n releaseRedoClaim?(id: string, transactionalEm?: EntityManager): Promise<boolean>\n log(input: ActionLogCreateInput, transactionalEm?: EntityManager): Promise<ActionLog | null>\n}\n\ntype AtomicReplayTransaction = {\n em: EntityManager\n joinsAmbient: boolean\n}\n\nfunction isInTransaction(em: EntityManager): boolean {\n const probe = (em as { isInTransaction?: () => boolean }).isInTransaction\n return typeof probe === 'function' && probe.call(em)\n}\n\nfunction resolveAtomicReplayTransaction(ctx: CommandRuntimeContext): AtomicReplayTransaction {\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager)\n const joinsAmbient = isInTransaction(em)\n if (joinsAmbient && !ownsTransactionLifetime(em, ctx.transactionLifetime)) {\n throw new Error('[internal] Ambient atomic replay requires its outer transaction lifetime owner')\n }\n return { em, joinsAmbient }\n}\n\nfunction bindReplayTransactionContext(\n ctx: CommandRuntimeContext,\n em: EntityManager,\n expectedLifetime?: TransactionLifetime,\n): CommandRuntimeContext {\n const transactionLifetime = getTransactionLifetime(em)\n if (!transactionLifetime || (expectedLifetime && transactionLifetime !== expectedLifetime)) {\n throw new Error('[internal] Atomic replay transaction lifetime owner changed before replay')\n }\n return { ...ctx, transactionalEm: em, transactionLifetime }\n}\n\nconst SKIPPED_ACTION_LOG_RESOURCE_KINDS = new Set<string>([\n 'audit_logs.access',\n 'audit_logs.action',\n 'dashboards.layout',\n 'dashboards.user_widgets',\n 'dashboards.role_widgets',\n])\n\nfunction asRecord(input: unknown): Record<string, unknown> | null {\n if (!input || typeof input !== 'object' || Array.isArray(input)) return null\n return input as Record<string, unknown>\n}\n\n/** Command handlers often return domain keys (e.g. warehouseId) without `id`; cache invalidation must still resolve the record. */\nfunction extractPrimaryIdFromCommandResult(result: unknown): string | null {\n const r = asRecord(result)\n if (!r) return null\n const direct = pickFirstIdentifier(r.id, r.entityId, r.recordId)\n if (direct) return direct\n for (const key of [\n 'warehouseId',\n 'zoneId',\n 'locationId',\n 'lotId',\n 'reservationId',\n 'profileId',\n 'movementId',\n 'balanceId',\n ]) {\n const v = r[key]\n if (typeof v === 'string' && v.trim().length > 0) return v.trim()\n }\n return null\n}\n\nfunction toISOString(value: unknown): string | null {\n if (value instanceof Date) {\n const iso = value.toISOString()\n return Number.isNaN(value.getTime()) ? null : iso\n }\n if (typeof value === 'string') {\n const parsed = new Date(value)\n return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString()\n }\n return null\n}\n\nfunction deepEqual(a: unknown, b: unknown, seen?: Set<unknown>): boolean {\n if (Object.is(a, b)) return true\n if (a instanceof Date || b instanceof Date) {\n const aIso = toISOString(a)\n const bIso = toISOString(b)\n if (aIso != null && bIso != null) return aIso === bIso\n return false\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false\n return a.every((value, index) => deepEqual(value, b[index], seen))\n }\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n if (!seen) seen = new Set()\n // `seen` is the current path: an object met again on it is a cycle. An object reached twice by\n // different paths (the items of one array held under two keys) is compared like any other.\n if (seen.has(a) || seen.has(b)) return false\n seen.add(a)\n seen.add(b)\n try {\n const aRec = a as Record<string, unknown>\n const bRec = b as Record<string, unknown>\n const keysA = Object.keys(aRec)\n const keysB = Object.keys(bRec)\n if (keysA.length !== keysB.length) return false\n return keysA.every((key) => deepEqual(aRec[key], bRec[key], seen))\n } finally {\n seen.delete(a)\n seen.delete(b)\n }\n }\n return false\n}\n\nconst CUSTOM_FIELD_CONTAINER_KEYS = new Set(['custom', 'customFields', 'customValues', 'cf'])\nconst SKIPPED_CHANGE_KEYS = new Set(['updatedAt', 'updated_at'])\n\nfunction appendCustomFieldChanges(\n changes: Record<string, { from: unknown; to: unknown }>,\n before: unknown,\n after: unknown\n): boolean {\n const beforeRec = asRecord(before)\n const afterRec = asRecord(after)\n if (!beforeRec && !afterRec) return false\n const left = beforeRec ?? {}\n const right = afterRec ?? {}\n const keys = new Set([...Object.keys(left), ...Object.keys(right)])\n for (const key of keys) {\n const from = left[key]\n const to = right[key]\n if (!deepEqual(from, to)) {\n changes[normalizeCustomFieldKey(key)] = { from, to }\n }\n }\n return true\n}\n\nfunction buildRecordChanges(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n): Record<string, { from: unknown; to: unknown }> {\n return buildRecordChangesDeep(before, after)\n}\n\nfunction buildRecordChangesDeep(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n prefix?: string,\n seen?: Set<unknown>,\n): Record<string, { from: unknown; to: unknown }> {\n const changes: Record<string, { from: unknown; to: unknown }> = {}\n if (!seen) seen = new Set()\n if (seen.has(before) || seen.has(after)) return changes\n seen.add(before)\n seen.add(after)\n const keys = new Set([...Object.keys(before), ...Object.keys(after)])\n for (const key of keys) {\n if (SKIPPED_CHANGE_KEYS.has(key)) continue\n if (CUSTOM_FIELD_CONTAINER_KEYS.has(key)) {\n const handled = appendCustomFieldChanges(changes, before[key], after[key])\n if (handled) continue\n }\n const from = before[key]\n const to = after[key]\n const path = prefix ? `${prefix}.${key}` : key\n const fromRec = asRecord(from)\n const toRec = asRecord(to)\n if (fromRec && toRec) {\n const nested = buildRecordChangesDeep(fromRec, toRec, path, seen)\n if (Object.keys(nested).length) {\n Object.assign(changes, nested)\n continue\n }\n }\n if (!deepEqual(from, to)) {\n changes[path] = { from, to }\n }\n }\n return changes\n}\n\nfunction deriveChangesFromSnapshots(\n before: unknown,\n after: unknown,\n): Record<string, { from: unknown; to: unknown }> | null {\n const beforeRec = asRecord(before)\n const afterRec = asRecord(after)\n if (!beforeRec || !afterRec) return null\n const changes = buildRecordChanges(beforeRec, afterRec)\n return Object.keys(changes).length ? changes : null\n}\n\nfunction invertRecordedChanges(\n changes: unknown,\n): Record<string, { from: unknown; to: unknown }> | null {\n const source = asRecord(changes)\n if (!source) return null\n const inverted: Record<string, { from: unknown; to: unknown }> = {}\n for (const [key, value] of Object.entries(source)) {\n const entry = asRecord(value)\n if (!entry || (!('from' in entry) && !('to' in entry))) continue\n inverted[key] = {\n from: entry.to,\n to: entry.from,\n }\n }\n return Object.keys(inverted).length ? inverted : null\n}\n\nfunction extractAliasList(source: unknown): string[] {\n if (!source || typeof source !== 'object' || Array.isArray(source)) return []\n const record = source as Record<string, unknown>\n const raw = record.cacheAliases\n if (!Array.isArray(raw)) return []\n const aliases = new Set<string>()\n for (const value of raw) {\n if (typeof value !== 'string') continue\n const normalized = canonicalizeResourceTag(value)\n if (normalized) aliases.add(normalized)\n }\n return Array.from(aliases)\n}\n\nexport class CommandBus {\n async execute<TInput = unknown, TResult = unknown>(\n commandId: string,\n options: CommandExecutionOptions<TInput>\n ): Promise<CommandExecuteResult<TResult>> {\n const handler = await this.resolveHandler<TInput, TResult>(commandId)\n\n const replayLogEntry = options.redoLogEntry ?? null\n const isAtomicReplay = replayLogEntry !== null && handler.atomicReplay === true\n const allInterceptors = getAllCommandInterceptorInstances()\n let interceptorMetadata = new Map<string, Record<string, unknown>>()\n let effectiveOptions = options\n let userFeatures: string[] = []\n const runBeforeExecuteInterceptors = async (baseOptions: CommandExecutionOptions<TInput>) => {\n const resolvedUserFeatures = allInterceptors.length\n ? await this.resolveUserFeaturesForInterceptors(baseOptions.ctx)\n : []\n if (!allInterceptors.length) {\n return {\n effectiveOptions: baseOptions,\n metadata: new Map<string, Record<string, unknown>>(),\n userFeatures: resolvedUserFeatures,\n }\n }\n const interceptorCtx: CommandInterceptorContext = {\n commandId,\n auth: baseOptions.ctx.auth ?? null,\n selectedOrganizationId: baseOptions.ctx.selectedOrganizationId ?? baseOptions.ctx.auth?.orgId ?? null,\n container: baseOptions.ctx.container,\n organizationScope: baseOptions.ctx.organizationScope ?? null,\n request: baseOptions.ctx.request ?? null,\n }\n const beforeResult = await runCommandInterceptorsBefore(\n allInterceptors, commandId, baseOptions.input, interceptorCtx, resolvedUserFeatures,\n )\n if (!beforeResult.ok) {\n const blocked = beforeResult.error!\n throw new CommandInterceptorError(blocked.message, { status: blocked.status, body: blocked.body })\n }\n const preparedOptions = beforeResult.modifiedInput\n ? {\n ...baseOptions,\n input: { ...(baseOptions.input as object), ...beforeResult.modifiedInput } as TInput,\n }\n : baseOptions\n return {\n effectiveOptions: preparedOptions,\n metadata: beforeResult.metadataByInterceptor,\n userFeatures: resolvedUserFeatures,\n }\n }\n\n if (replayLogEntry && !isAtomicReplay) {\n await this.runReplayTransactionGuard(options.ctx, 'redo', replayLogEntry)\n if (handler.authorizeReplay) {\n await handler.authorizeReplay({\n operation: 'redo',\n input: options.input,\n ctx: options.ctx,\n logEntry: replayLogEntry,\n })\n }\n }\n\n if (!isAtomicReplay) {\n const prepared = await runBeforeExecuteInterceptors(options)\n effectiveOptions = prepared.effectiveOptions\n interceptorMetadata = prepared.metadata\n userFeatures = prepared.userFeatures\n }\n\n const executeCore = async (coreOptions: CommandExecutionOptions<TInput>) => {\n const snapshots: { before?: unknown } = {}\n let executionOptions = coreOptions\n if (handler.prepareSnapshotInsideTransaction && handler.prepare) {\n const prepare = handler.prepare\n const originalCtx = coreOptions.ctx\n const originalBeforeTransactionalWrite = originalCtx.beforeTransactionalWrite\n let prepared = false\n let transactionalCtx: CommandRuntimeContext\n transactionalCtx = {\n ...originalCtx,\n beforeTransactionalWrite: async (em, input) => {\n await originalBeforeTransactionalWrite?.(em, input)\n if (prepared) return\n Object.assign(\n snapshots,\n (await prepare(coreOptions.input, { ...transactionalCtx, transactionalEm: em })) ?? {},\n )\n prepared = true\n },\n }\n executionOptions = { ...coreOptions, ctx: transactionalCtx }\n } else {\n Object.assign(snapshots, await this.prepareSnapshots(handler, coreOptions))\n }\n effectiveOptions = executionOptions\n const sourceLog = executionOptions.redoLogEntry ?? null\n const result =\n sourceLog && typeof handler.redo === 'function'\n ? await handler.redo({ input: executionOptions.input, ctx: executionOptions.ctx, logEntry: sourceLog })\n : await handler.execute(executionOptions.input, executionOptions.ctx)\n const afterSnapshot = await this.captureAfter(handler, executionOptions, result)\n const snapshotsWithAfter = { ...snapshots, after: afterSnapshot }\n const logMeta = await this.buildLog(handler, executionOptions, result, snapshotsWithAfter)\n let mergedMeta = this.mergeMetadata(executionOptions.metadata, logMeta)\n // Interceptors opt into audit-log enrichment with a reserved `logContext` key rather\n // than the generic `context` one, so the metadata an interceptor already passes to its\n // own afterExecute hook is never silently promoted into audit storage.\n // Map iteration order is interceptor priority order (see collectMatching), so a\n // later-priority interceptor overrides an earlier one on key collisions.\n let interceptorContextMerged: Record<string, unknown> = {}\n for (const meta of interceptorMetadata.values()) {\n const logContextRecord = asRecord(asRecord(meta)?.logContext)\n if (!logContextRecord) continue\n interceptorContextMerged = {\n ...interceptorContextMerged,\n ...logContextRecord,\n }\n }\n const baseContext = asRecord(executionOptions.metadata?.context) ?? {}\n const logMetaContext = asRecord(logMeta?.context) ?? {}\n if (Object.keys(interceptorContextMerged).length > 0 || Object.keys(baseContext).length > 0 || Object.keys(logMetaContext).length > 0) {\n mergedMeta = mergedMeta ?? {}\n mergedMeta.context = {\n ...baseContext,\n ...interceptorContextMerged,\n ...logMetaContext,\n }\n }\n const undoable = this.isUndoable(handler)\n if (undoable && mergedMeta?.replayable !== false) {\n mergedMeta = mergedMeta ?? {}\n if (!mergedMeta.undoToken) mergedMeta.undoToken = defaultUndoToken()\n if (mergedMeta.actorUserId === undefined) mergedMeta.actorUserId = executionOptions.ctx.auth?.sub ?? null\n } else if (mergedMeta?.replayable === false) {\n mergedMeta.undoToken = null\n }\n if (afterSnapshot !== undefined && afterSnapshot !== null) {\n if (!mergedMeta) {\n mergedMeta = { snapshotAfter: afterSnapshot }\n } else if (!mergedMeta.snapshotAfter) {\n mergedMeta.snapshotAfter = afterSnapshot\n }\n }\n if (snapshots.before) {\n if (!mergedMeta) {\n mergedMeta = { snapshotBefore: snapshots.before }\n } else if (!mergedMeta.snapshotBefore) {\n mergedMeta.snapshotBefore = snapshots.before\n }\n }\n if (mergedMeta?.snapshotBefore !== undefined && mergedMeta?.snapshotAfter !== undefined) {\n const currentChanges = mergedMeta.changes\n const shouldInfer =\n currentChanges === undefined ||\n currentChanges === null ||\n (typeof currentChanges === 'object' && !Array.isArray(currentChanges) && Object.keys(currentChanges).length === 0)\n if (shouldInfer) {\n const inferred = deriveChangesFromSnapshots(mergedMeta.snapshotBefore, mergedMeta.snapshotAfter)\n if (inferred) mergedMeta.changes = inferred\n }\n }\n const logEntry = await this.persistLog(commandId, executionOptions, mergedMeta)\n return { result, mergedMeta, logEntry }\n }\n\n let replaySourceFinalized = false\n let coreResult: Awaited<ReturnType<typeof executeCore>>\n const atomicSourceLog = options.redoLogEntry ?? null\n let ambientReplay: AtomicReplayTransaction | null = null\n let replayTransactionLifetime: TransactionLifetime | null = null\n if (atomicSourceLog && isAtomicReplay) {\n ambientReplay = resolveAtomicReplayTransaction(options.ctx)\n const replayEm = ambientReplay.em\n await withAtomicFlush(replayEm, [async () => {\n const replayCtx = bindReplayTransactionContext(\n options.ctx,\n replayEm,\n ambientReplay?.joinsAmbient ? options.ctx.transactionLifetime : undefined,\n )\n replayTransactionLifetime = replayCtx.transactionLifetime ?? null\n const transactionalBaseOptions: CommandExecutionOptions<TInput> = {\n ...options,\n ctx: replayCtx,\n }\n if (!atomicSourceLog.id) throw new Error('[internal] Atomic redo source log id is required')\n if (handler.stabilizeReplay) {\n await handler.stabilizeReplay({\n operation: 'redo',\n input: transactionalBaseOptions.input,\n ctx: transactionalBaseOptions.ctx,\n logEntry: atomicSourceLog,\n })\n }\n await this.runReplayTransactionGuard(\n transactionalBaseOptions.ctx,\n 'redo',\n atomicSourceLog,\n replayEm,\n )\n const prepared = await runBeforeExecuteInterceptors(transactionalBaseOptions)\n effectiveOptions = prepared.effectiveOptions\n interceptorMetadata = prepared.metadata\n userFeatures = prepared.userFeatures\n const service = effectiveOptions.ctx.container.resolve('actionLogService') as CommandActionLogService\n if (handler.authorizeReplay) {\n await handler.authorizeReplay({\n operation: 'redo',\n input: effectiveOptions.input,\n ctx: effectiveOptions.ctx,\n logEntry: atomicSourceLog,\n })\n }\n const claimed = await service.claimForRedo(atomicSourceLog.id, replayEm)\n if (!claimed) throw new Error('[internal] Redo source already consumed')\n coreResult = await executeCore(effectiveOptions)\n }], { transaction: true, label: `${commandId}.redo` })\n replaySourceFinalized = !ambientReplay.joinsAmbient\n } else if (replayLogEntry?.id) {\n const redoClaimRelease = await this.claimRedoSource(effectiveOptions.ctx, commandId, replayLogEntry.id)\n try {\n coreResult = await executeCore(effectiveOptions)\n } catch (err) {\n await redoClaimRelease?.()\n throw err\n }\n replaySourceFinalized = redoClaimRelease !== null\n } else {\n coreResult = await executeCore(effectiveOptions)\n }\n const { result, mergedMeta, logEntry } = coreResult!\n\n const runPostCommit = async () => {\n let finalResult = result\n if (allInterceptors.length) {\n const interceptorCtx: CommandInterceptorContext = {\n commandId,\n auth: effectiveOptions.ctx.auth ?? null,\n selectedOrganizationId: effectiveOptions.ctx.selectedOrganizationId ?? effectiveOptions.ctx.auth?.orgId ?? null,\n container: effectiveOptions.ctx.container,\n organizationScope: effectiveOptions.ctx.organizationScope ?? null,\n request: effectiveOptions.ctx.request ?? null,\n }\n const afterResult = await runCommandInterceptorsAfter(\n allInterceptors, commandId, effectiveOptions.input, result, interceptorCtx,\n userFeatures, interceptorMetadata,\n )\n if (afterResult.modifiedResult && typeof result === 'object' && result) {\n finalResult = { ...(result as object), ...afterResult.modifiedResult } as Awaited<TResult>\n }\n }\n\n if (!effectiveOptions.skipCacheInvalidation) {\n await this.invalidateCacheAfterExecute(commandId, effectiveOptions, finalResult, mergedMeta)\n }\n // Bulk-import backfills defer heavy per-record side effects: the ctx flags are read here and\n // threaded as a local into the flush (never stored on the shared dataEngine), so a concurrent\n // command with different flags can't observe them. Reindex is restored by the caller's\n // end-of-run `query_index rebuild`. Mirrors `skipCacheInvalidation` above.\n await this.flushCrudSideEffects(effectiveOptions.ctx.container, effectiveOptions.ctx?.bulkImport)\n return finalResult\n }\n\n const executionResult: CommandExecuteResult<TResult> = {\n result,\n logEntry,\n replaySourceFinalized,\n }\n if (ambientReplay?.joinsAmbient) {\n if (!replayTransactionLifetime || !ownsTransactionLifetime(ambientReplay.em, replayTransactionLifetime)) {\n throw new Error('[internal] Ambient atomic replay lost its outer transaction lifetime owner')\n }\n onTransactionLifetimeComplete(ambientReplay.em, async (outcome) => {\n if (outcome !== 'committed') return\n executionResult.result = await runPostCommit()\n executionResult.replaySourceFinalized = true\n })\n return executionResult\n }\n\n executionResult.result = await runPostCommit()\n return executionResult\n }\n\n async undo(undoToken: string, ctx: CommandRuntimeContext): Promise<void> {\n const service = (ctx.container.resolve('actionLogService') as CommandActionLogService)\n const log = await service.findByUndoToken(undoToken)\n if (!log) throw new Error('Undo token expired or not found')\n const handler = await this.resolveHandler(log.commandId)\n if (!handler.undo || this.isUndoable(handler) === false) {\n throw new Error(`Command ${log.commandId} is not undoable`)\n }\n\n const isAtomicReplay = handler.atomicReplay === true\n const allInterceptors = getAllCommandInterceptorInstances()\n let undoInterceptorMetadata = new Map<string, Record<string, unknown>>()\n let userFeatures: string[] = []\n const runBeforeUndoInterceptors = async (replayCtx: CommandRuntimeContext) => {\n const resolvedUserFeatures = allInterceptors.length\n ? await this.resolveUserFeaturesForInterceptors(replayCtx)\n : []\n if (!allInterceptors.length) {\n return {\n metadata: new Map<string, Record<string, unknown>>(),\n userFeatures: resolvedUserFeatures,\n }\n }\n const undoCtx = { input: log.commandPayload, logEntry: log, undoToken }\n const interceptorCtx: CommandInterceptorContext = {\n commandId: log.commandId,\n auth: replayCtx.auth ?? null,\n selectedOrganizationId: replayCtx.selectedOrganizationId ?? replayCtx.auth?.orgId ?? null,\n container: replayCtx.container,\n organizationScope: replayCtx.organizationScope ?? null,\n request: replayCtx.request ?? null,\n }\n const beforeResult = await runCommandInterceptorsBeforeUndo(\n allInterceptors, log.commandId, undoCtx, interceptorCtx, resolvedUserFeatures,\n )\n if (!beforeResult.ok) {\n const blocked = beforeResult.error!\n throw new CommandInterceptorError(blocked.message, { status: blocked.status, body: blocked.body })\n }\n return {\n metadata: beforeResult.metadataByInterceptor,\n userFeatures: resolvedUserFeatures,\n }\n }\n\n if (!isAtomicReplay) {\n await this.runReplayTransactionGuard(ctx, 'undo', log)\n if (handler.authorizeReplay) {\n await handler.authorizeReplay({\n operation: 'undo',\n input: log.commandPayload as Parameters<NonNullable<typeof handler.authorizeReplay>>[0]['input'],\n ctx,\n logEntry: log,\n })\n }\n }\n\n const claimUndo = async (replayEm?: EntityManager) => {\n // Two contenders can both pass the initial lookup; only the compare-and-set\n // below may proceed. On the atomic path this state is still uncommitted and\n // rolls back with every handler/log write if anything later fails.\n const claimed = replayEm\n ? await service.claimForUndo(log.id, replayEm)\n : await service.claimForUndo(log.id)\n if (!claimed) throw new Error('[internal] Undo token already consumed')\n }\n const finishUndo = async (replayCtx: CommandRuntimeContext, replayEm?: EntityManager) => {\n await handler.undo!({\n input: log.commandPayload as Parameters<NonNullable<typeof handler.undo>>[0]['input'],\n ctx: replayCtx,\n logEntry: log,\n })\n const traceLog = this.buildUndoTraceLog(log, replayCtx)\n if (replayEm) {\n await service.markUndone(log.id, traceLog, replayEm)\n } else {\n await service.markUndone(log.id, traceLog)\n }\n }\n\n let ambientReplay: AtomicReplayTransaction | null = null\n let replayTransactionLifetime: TransactionLifetime | null = null\n if (isAtomicReplay) {\n ambientReplay = resolveAtomicReplayTransaction(ctx)\n const replayEm = ambientReplay.em\n await withAtomicFlush(replayEm, [async () => {\n const replayCtx = bindReplayTransactionContext(\n ctx,\n replayEm,\n ambientReplay?.joinsAmbient ? ctx.transactionLifetime : undefined,\n )\n replayTransactionLifetime = replayCtx.transactionLifetime ?? null\n if (handler.stabilizeReplay) {\n await handler.stabilizeReplay({\n operation: 'undo',\n input: log.commandPayload as Parameters<NonNullable<typeof handler.stabilizeReplay>>[0]['input'],\n ctx: replayCtx,\n logEntry: log,\n })\n }\n await this.runReplayTransactionGuard(replayCtx, 'undo', log, replayEm)\n const prepared = await runBeforeUndoInterceptors(replayCtx)\n undoInterceptorMetadata = prepared.metadata\n userFeatures = prepared.userFeatures\n if (handler.authorizeReplay) {\n await handler.authorizeReplay({\n operation: 'undo',\n input: log.commandPayload as Parameters<NonNullable<typeof handler.authorizeReplay>>[0]['input'],\n ctx: replayCtx,\n logEntry: log,\n })\n }\n await claimUndo(replayEm)\n await finishUndo(replayCtx, replayEm)\n }], {\n transaction: true,\n label: `${log.commandId}.undo`,\n })\n } else {\n let undoClaimed = false\n try {\n // Preserve the established non-atomic lifecycle exactly: authorization,\n // source claim, before-undo interceptors, handler, then finalization.\n await claimUndo()\n undoClaimed = true\n const prepared = await runBeforeUndoInterceptors(ctx)\n undoInterceptorMetadata = prepared.metadata\n userFeatures = prepared.userFeatures\n await finishUndo(ctx)\n } catch (err) {\n // Legacy handlers retain their compensating release behavior because\n // their domain mutation may not share the action-log transaction.\n if (undoClaimed) {\n await service.releaseUndoClaim(log.id).catch((releaseErr: unknown) => {\n logger.error('Failed to release undo claim', { commandId: log.commandId, logId: log.id, err: releaseErr })\n getTelemetryRuntime()?.reportError(releaseErr, {\n module: 'shared',\n code: 'shared.undo_claim_release_failed',\n })\n })\n }\n throw err\n }\n }\n\n const runPostCommit = async () => {\n // Post-commit hooks and side effects run only after an atomic replay has\n // durably committed both the domain state and source/trace log state.\n if (allInterceptors.length) {\n const undoCtx = { input: log.commandPayload, logEntry: log, undoToken }\n const interceptorCtx: CommandInterceptorContext = {\n commandId: log.commandId,\n auth: ctx.auth ?? null,\n selectedOrganizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n container: ctx.container,\n organizationScope: ctx.organizationScope ?? null,\n request: ctx.request ?? null,\n }\n await runCommandInterceptorsAfterUndo(\n allInterceptors, log.commandId, undoCtx, interceptorCtx,\n userFeatures, undoInterceptorMetadata,\n )\n }\n\n await this.invalidateCacheAfterUndo(log, ctx)\n await this.flushCrudSideEffects(ctx.container)\n }\n\n if (ambientReplay?.joinsAmbient) {\n if (!replayTransactionLifetime || !ownsTransactionLifetime(ambientReplay.em, replayTransactionLifetime)) {\n throw new Error('[internal] Ambient atomic replay lost its outer transaction lifetime owner')\n }\n onTransactionLifetimeComplete(ambientReplay.em, async (outcome) => {\n if (outcome === 'committed') await runPostCommit()\n })\n return\n }\n\n await runPostCommit()\n }\n\n private buildUndoTraceLog(log: ActionLog, ctx: CommandRuntimeContext): ActionLogCreateInput | undefined {\n const snapshotBefore = log.snapshotAfter ?? null\n const snapshotAfter = log.snapshotBefore ?? null\n const changes =\n deriveChangesFromSnapshots(snapshotBefore, snapshotAfter)\n ?? invertRecordedChanges(log.changesJson)\n ?? undefined\n\n const baseContext = asRecord(log.contextJson) ?? {}\n const context = {\n ...baseContext,\n historyAction: 'undo',\n sourceLogId: log.id,\n sourceCommandId: log.commandId,\n }\n\n return {\n tenantId: log.tenantId ?? ctx.auth?.tenantId ?? null,\n organizationId: log.organizationId ?? ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n actorUserId: ctx.auth?.sub ?? log.actorUserId ?? null,\n commandId: log.commandId,\n actionLabel: log.actionLabel ?? undefined,\n resourceKind: log.resourceKind ?? undefined,\n resourceId: log.resourceId ?? undefined,\n parentResourceKind: log.parentResourceKind ?? null,\n parentResourceId: log.parentResourceId ?? null,\n relatedResourceKind: log.relatedResourceKind ?? null,\n relatedResourceId: log.relatedResourceId ?? null,\n snapshotBefore,\n snapshotAfter,\n changes,\n context,\n }\n }\n\n private async resolveUserFeaturesForInterceptors(ctx: CommandRuntimeContext): Promise<string[]> {\n if (!ctx.auth) return []\n type RbacLike = {\n getGrantedFeatures: (\n userId: string,\n opts: { tenantId: string | null; organizationId: string | null },\n ) => Promise<string[]>\n getGrantedFeaturesWithEntityManager?: (\n em: EntityManager,\n userId: string,\n opts: { tenantId: string | null; organizationId: string | null },\n ) => Promise<string[]>\n }\n let rbac: RbacLike | undefined\n try {\n rbac = ctx.container.resolve('rbacService') as RbacLike | undefined\n } catch {\n // Intentional: rbacService is not registered in all runtime contexts (CLI, tests, bootstrap).\n return []\n }\n const scope = {\n tenantId: ctx.auth.tenantId,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth.orgId,\n }\n if (ctx.transactionalEm) {\n if (!rbac?.getGrantedFeaturesWithEntityManager) return []\n return await rbac.getGrantedFeaturesWithEntityManager(\n ctx.transactionalEm,\n ctx.auth.sub,\n scope,\n )\n }\n try {\n if (rbac?.getGrantedFeatures) {\n return await rbac.getGrantedFeatures(ctx.auth.sub, scope)\n }\n } catch {\n // Outside a transaction a failed lookup cannot poison anything; interceptors without\n // feature gating still run. Inside one the error is rethrown above, because the failed\n // query has already aborted the transaction.\n }\n return []\n }\n\n private async runReplayTransactionGuard(\n ctx: CommandRuntimeContext,\n operation: 'undo' | 'redo',\n logEntry: CommandUndoLogEntry,\n transactionalEm?: EntityManager,\n ): Promise<void> {\n if (!ctx.replayTransactionGuard) return\n if (transactionalEm) {\n await ctx.replayTransactionGuard({ operation, logEntry, transactionalEm })\n return\n }\n const requestEm = ctx.container.resolve('em') as EntityManager\n const guardEm = typeof requestEm.fork === 'function' ? requestEm.fork() : requestEm\n await withAtomicFlush(guardEm, [async () => {\n await ctx.replayTransactionGuard!({ operation, logEntry, transactionalEm: guardEm })\n }], { transaction: true, label: `${logEntry.commandId}.${operation}.request-guard` })\n }\n\n private async claimRedoSource(\n ctx: CommandRuntimeContext,\n commandId: string,\n sourceLogId: string,\n ): Promise<(() => Promise<void>) | null> {\n let service: CommandActionLogService | null = null\n try {\n service = ctx.container.resolve('actionLogService') as CommandActionLogService\n } catch {\n service = null\n }\n if (!service || typeof service.claimForRedo !== 'function' || typeof service.releaseRedoClaim !== 'function') {\n logger.warn('Redo source claim unavailable; replaying without an atomic claim', { commandId, sourceLogId })\n return null\n }\n const releaseClaim = service.releaseRedoClaim.bind(service)\n const transactionalEm = ctx.transactionalEm\n const claimed = transactionalEm\n ? await service.claimForRedo(sourceLogId, transactionalEm)\n : await service.claimForRedo(sourceLogId)\n if (!claimed) throw new Error('[internal] Redo source already consumed')\n return async () => {\n try {\n const released = transactionalEm\n ? await releaseClaim(sourceLogId, transactionalEm)\n : await releaseClaim(sourceLogId)\n if (!released) logger.warn('Redo source claim was not held at release', { commandId, sourceLogId })\n } catch (releaseErr) {\n logger.error('Failed to release redo source claim', { commandId, sourceLogId, err: releaseErr })\n getTelemetryRuntime()?.reportError(releaseErr, {\n module: 'shared',\n code: 'shared.redo_claim_release_failed',\n })\n }\n }\n }\n\n private async resolveHandler<TInput, TResult>(commandId: string): Promise<CommandHandler<TInput, TResult>> {\n const handler =\n commandRegistry.get<TInput, TResult>(commandId) ??\n ((await commandRegistry.load(commandId)) as CommandHandler<TInput, TResult> | null)\n if (!handler) {\n const moduleName = commandId.split('.')[0]\n const registered = commandRegistry.list()\n const sameModule = registered.filter((id) => id.split('.')[0] === moduleName)\n const registeredLoaders = commandRegistry.listLoaders()\n const sameModuleLoaders = registeredLoaders.filter((id) => id === commandId || id.startsWith(`${moduleName}:`))\n const hint = sameModule.length > 0\n ? ` Registered commands for module \"${moduleName}\": [${sameModule.join(', ')}].`\n : sameModuleLoaders.length > 0\n ? ` Command loaders for module \"${moduleName}\" were registered but none loaded \"${commandId}\".`\n : ` No commands or command loaders registered for module \"${moduleName}\". Ensure the command file is imported or generated lazy command loaders are registered.`\n throw new Error(`Command handler not registered for id ${commandId}.${hint}`)\n }\n return handler\n }\n\n private async prepareSnapshots<TInput, TResult>(\n handler: CommandHandler<TInput, TResult>,\n options: CommandExecutionOptions<TInput>\n ): Promise<{ before?: unknown }> {\n if (!handler.prepare) return {}\n try {\n return (await handler.prepare(options.input, options.ctx)) || {}\n } catch (err) {\n throw err\n }\n }\n\n private async captureAfter<TInput, TResult>(\n handler: CommandHandler<TInput, TResult>,\n options: CommandExecutionOptions<TInput>,\n result: TResult\n ): Promise<unknown> {\n if (!handler.captureAfter) return undefined\n return handler.captureAfter(options.input, result, options.ctx)\n }\n\n private async buildLog<TInput, TResult>(\n handler: CommandHandler<TInput, TResult>,\n options: CommandExecutionOptions<TInput>,\n result: TResult,\n snapshots: { before?: unknown; after?: unknown }\n ): Promise<CommandLogMetadata | null> {\n if (!handler.buildLog) return null\n const args: CommandLogBuilderArgs<TInput, TResult> = {\n input: options.input,\n result,\n ctx: options.ctx,\n snapshots,\n }\n return (await handler.buildLog(args)) || null\n }\n\n private mergeMetadata(primary?: CommandLogMetadata | null, secondary?: CommandLogMetadata | null): CommandLogMetadata | null {\n if (!primary && !secondary) return null\n return {\n skipLog: secondary?.skipLog ?? primary?.skipLog ?? false,\n replayable:\n secondary?.replayable === false || primary?.replayable === false\n ? false\n : secondary?.replayable ?? primary?.replayable,\n tenantId: secondary?.tenantId ?? primary?.tenantId ?? null,\n organizationId: secondary?.organizationId ?? primary?.organizationId ?? null,\n actorUserId: secondary?.actorUserId ?? primary?.actorUserId ?? null,\n onBehalfOfUserId: secondary?.onBehalfOfUserId ?? primary?.onBehalfOfUserId ?? null,\n actionLabel: secondary?.actionLabel ?? primary?.actionLabel ?? null,\n resourceKind: secondary?.resourceKind ?? primary?.resourceKind ?? null,\n resourceId: secondary?.resourceId ?? primary?.resourceId ?? null,\n parentResourceKind: secondary?.parentResourceKind ?? primary?.parentResourceKind ?? null,\n parentResourceId: secondary?.parentResourceId ?? primary?.parentResourceId ?? null,\n relatedResourceKind: secondary?.relatedResourceKind ?? primary?.relatedResourceKind ?? null,\n relatedResourceId: secondary?.relatedResourceId ?? primary?.relatedResourceId ?? null,\n undoToken: secondary?.undoToken ?? primary?.undoToken ?? null,\n // A redacted redo input always wins: it exists precisely because the raw\n // input carries a secret that must not reach `action_logs`.\n redoInput: secondary?.redoInput !== undefined ? secondary.redoInput : primary?.redoInput,\n payload: secondary?.payload ?? primary?.payload ?? null,\n snapshotBefore: secondary?.snapshotBefore ?? primary?.snapshotBefore ?? null,\n snapshotAfter: secondary?.snapshotAfter ?? primary?.snapshotAfter ?? null,\n changes: secondary?.changes ?? primary?.changes ?? null,\n context: secondary?.context ?? primary?.context ?? null,\n }\n }\n\n private async persistLog<TInput>(\n commandId: string,\n options: CommandExecutionOptions<TInput>,\n metadata: CommandLogMetadata | null\n ): Promise<ActionLog | null> {\n if (!metadata) return null\n if (metadata.skipLog) return null\n const resourceKind =\n typeof metadata.resourceKind === 'string' ? metadata.resourceKind : null\n if (resourceKind && SKIPPED_ACTION_LOG_RESOURCE_KINDS.has(resourceKind)) {\n return null\n }\n let service: CommandActionLogService | null = null\n try {\n service = (options.ctx.container.resolve('actionLogService') as CommandActionLogService)\n } catch {\n service = null\n }\n if (!service) return null\n\n const tenantId = metadata.tenantId ?? options.ctx.auth?.tenantId ?? null\n const organizationId =\n metadata.organizationId ?? options.ctx.selectedOrganizationId ?? options.ctx.auth?.orgId ?? null\n // On-behalf-of attribution (Wave 4 P2): when `ctx.runAs` is set the actor is\n // the agent principal and the human it acts for is recorded separately. This\n // funnels agent writes through the SAME ActionLog path as a human's \u2014 only the\n // attribution differs (actorUserId=agent, onBehalfOfUserId=human, source='agent').\n const runAs = options.ctx.runAs ?? null\n const actorUserId = runAs?.actorUserId ?? metadata.actorUserId ?? options.ctx.auth?.sub ?? null\n const onBehalfOfUserId = runAs ? (runAs.onBehalfOfUserId ?? null) : (metadata.onBehalfOfUserId ?? null)\n const systemActorContext = !actorUserId && options.ctx.systemActor === true\n ? { systemActor: 'system:command' }\n : null\n const payload: Record<string, unknown> = {\n tenantId: tenantId ?? undefined,\n organizationId: organizationId ?? undefined,\n actorUserId: actorUserId ?? undefined,\n onBehalfOfUserId: onBehalfOfUserId ?? undefined,\n commandId,\n }\n\n if (metadata) {\n if ('actionLabel' in metadata && metadata.actionLabel != null) payload.actionLabel = metadata.actionLabel\n if ('resourceKind' in metadata && metadata.resourceKind != null) payload.resourceKind = metadata.resourceKind\n if ('resourceId' in metadata && metadata.resourceId != null) payload.resourceId = metadata.resourceId\n if ('parentResourceKind' in metadata && metadata.parentResourceKind != null) payload.parentResourceKind = metadata.parentResourceKind\n if ('parentResourceId' in metadata && metadata.parentResourceId != null) payload.parentResourceId = metadata.parentResourceId\n if ('relatedResourceKind' in metadata && metadata.relatedResourceKind != null) payload.relatedResourceKind = metadata.relatedResourceKind\n if ('relatedResourceId' in metadata && metadata.relatedResourceId != null) payload.relatedResourceId = metadata.relatedResourceId\n if ('undoToken' in metadata && metadata.undoToken != null) payload.undoToken = metadata.undoToken\n if ('payload' in metadata && metadata.payload !== undefined) payload.commandPayload = metadata.payload\n if ('snapshotBefore' in metadata && metadata.snapshotBefore !== undefined) payload.snapshotBefore = metadata.snapshotBefore\n if ('snapshotAfter' in metadata && metadata.snapshotAfter !== undefined) payload.snapshotAfter = metadata.snapshotAfter\n if ('changes' in metadata && metadata.changes !== undefined && metadata.changes !== null) payload.changes = metadata.changes\n if ('context' in metadata && metadata.context !== undefined && metadata.context !== null) {\n payload.context = { ...(systemActorContext ?? {}), ...metadata.context }\n } else if (systemActorContext) {\n payload.context = systemActorContext\n }\n }\n\n if (runAs) {\n // Stamp the audit source so `deriveActionLogSource` projects `sourceKey='agent'`.\n // Merge into any caller-provided context rather than replacing it.\n const baseContext = asRecord(payload.context) ?? {}\n payload.context = { ...baseContext, source: runAs.source }\n }\n\n if (metadata.replayable === false) {\n delete payload.commandPayload\n } else {\n const redoInput = metadata.redoInput !== undefined ? metadata.redoInput : options.input\n const redoEnvelope = wrapRedoPayload('commandPayload' in payload ? (payload.commandPayload as unknown) : undefined, redoInput)\n payload.commandPayload = redoEnvelope\n }\n\n return options.ctx.transactionalEm\n ? await service.log(payload as ActionLogCreateInput, options.ctx.transactionalEm)\n : await service.log(payload as ActionLogCreateInput)\n }\n\n private isUndoable(handler: CommandHandler<unknown, unknown>): boolean {\n return handler.isUndoable !== false && typeof handler.undo === 'function'\n }\n\n private async invalidateCacheAfterExecute<TResult>(\n commandId: string,\n options: CommandExecutionOptions<unknown>,\n result: TResult,\n metadata: CommandLogMetadata | null\n ): Promise<void> {\n const resource = typeof metadata?.resourceKind === 'string' ? metadata.resourceKind : null\n if (!resource) return\n try {\n const ctx = options.ctx\n const resultRecord = asRecord(result)\n const resultEntity = asRecord(resultRecord?.entity)\n const inputRecord = asRecord(options.input)\n const inputEntity = asRecord(inputRecord?.entity)\n\n const recordId = pickFirstIdentifier(\n metadata?.resourceId,\n extractPrimaryIdFromCommandResult(result),\n resultRecord?.entityId,\n resultRecord?.id,\n resultRecord?.recordId,\n resultEntity?.id,\n inputRecord?.id,\n inputRecord?.entityId,\n inputRecord?.recordId,\n inputEntity?.id\n )\n\n const organizationId = pickFirstIdentifier(\n metadata?.organizationId,\n resultRecord?.organizationId,\n resultEntity?.organizationId,\n inputRecord?.organizationId,\n inputEntity?.organizationId,\n ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null\n )\n\n const tenantId = pickFirstIdentifier(\n metadata?.tenantId,\n resultRecord?.tenantId,\n resultEntity?.tenantId,\n inputRecord?.tenantId,\n inputEntity?.tenantId,\n ctx.auth?.tenantId ?? null\n )\n\n const fallbackTenant = pickFirstIdentifier(metadata?.tenantId, ctx.auth?.tenantId ?? null)\n\n const aliasSet = new Set<string>()\n for (const alias of extractAliasList(metadata?.context ?? null)) {\n aliasSet.add(alias)\n }\n const derived = deriveResourceFromCommandId(commandId)\n if (derived) aliasSet.add(derived)\n const aliasExtras = Array.from(aliasSet)\n await invalidateCrudCache(\n ctx.container,\n resource,\n { id: recordId, organizationId, tenantId },\n fallbackTenant,\n `command:${commandId}:execute`,\n aliasExtras\n )\n } catch (err) {\n if (isCrudCacheDebugEnabled()) {\n try {\n logger.debug('Cache execute-invalidation failed', { commandId, err })\n } catch {}\n }\n }\n }\n\n private async invalidateCacheAfterUndo(log: ActionLog, ctx: CommandRuntimeContext): Promise<void> {\n const resource = typeof log.resourceKind === 'string' ? log.resourceKind : null\n if (!resource) return\n try {\n const recordId = pickFirstIdentifier(log.resourceId)\n const organizationId = pickFirstIdentifier(log.organizationId, ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null)\n const tenantId = pickFirstIdentifier(log.tenantId, ctx.auth?.tenantId ?? null)\n const fallbackTenant = pickFirstIdentifier(log.tenantId, ctx.auth?.tenantId ?? null)\n const aliasSet = new Set<string>()\n for (const alias of extractAliasList(log.contextJson ?? null)) {\n aliasSet.add(alias)\n }\n const derived = deriveResourceFromCommandId(log.commandId)\n if (derived) aliasSet.add(derived)\n const aliasExtras = Array.from(aliasSet)\n await invalidateCrudCache(\n ctx.container,\n resource,\n { id: recordId, organizationId, tenantId },\n fallbackTenant,\n `command:${log.commandId}:undo`,\n aliasExtras\n )\n } catch (err) {\n if (isCrudCacheDebugEnabled()) {\n try {\n logger.debug('Cache undo-invalidation failed', { commandId: log.commandId, err })\n } catch {}\n }\n }\n }\n\n private async flushCrudSideEffects(container: AwilixContainer, suppress?: BulkImportSuppression): Promise<void> {\n try {\n const dataEngine = (container.resolve('dataEngine') as DataEngine)\n await dataEngine.flushOrmEntityChanges(suppress)\n } catch (error) {\n if (isReadProjectionAlwaysConsistent()) {\n throw error\n }\n // best-effort: failures should not block command execution\n }\n }\n}\n\ntype RedoEnvelope = {\n __redoInput: unknown\n [key: string]: unknown\n}\n\nfunction wrapRedoPayload(existing: unknown, input: unknown): RedoEnvelope {\n if (!existing || typeof existing !== 'object' || Array.isArray(existing)) {\n const envelope: RedoEnvelope = { __redoInput: input }\n if (existing !== undefined) envelope.value = existing\n return envelope\n }\n const current = existing as Record<string, unknown>\n if ('__redoInput' in current && current.__redoInput !== undefined) {\n return current as RedoEnvelope\n }\n return { __redoInput: input, ...current }\n}\n"],
5
- "mappings": "AAEA,SAAS,uBAAuB;AAWhC,SAAS,wBAAwB;AAGjC;AAAA,E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{ ActionLogCreateInput } from '@open-mercato/core/modules/audit_logs/data/validators'\nimport { commandRegistry } from './registry'\nimport type {\n BulkImportSuppression,\n CommandExecutionOptions,\n CommandExecuteResult,\n CommandHandler,\n CommandLogBuilderArgs,\n CommandLogMetadata,\n CommandRuntimeContext,\n CommandUndoLogEntry,\n} from './types'\nimport { defaultUndoToken } from './types'\nimport type { AwilixContainer } from 'awilix'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport {\n canonicalizeResourceTag,\n deriveResourceFromCommandId,\n invalidateCrudCache,\n pickFirstIdentifier,\n isCrudCacheDebugEnabled,\n} from '@open-mercato/shared/lib/crud/cache'\nimport { normalizeCustomFieldKey } from '@open-mercato/shared/lib/custom-fields/keys'\nimport { getAllCommandInterceptorInstances } from './command-interceptor-store'\nimport {\n runCommandInterceptorsBefore,\n runCommandInterceptorsAfter,\n runCommandInterceptorsBeforeUndo,\n runCommandInterceptorsAfterUndo,\n} from './command-interceptor-runner'\nimport type { CommandInterceptorContext } from './command-interceptor'\nimport { CommandInterceptorError } from './errors'\nimport { isReadProjectionAlwaysConsistent } from '@open-mercato/shared/lib/data/consistency'\nimport { createLogger } from '../logger'\nimport { withAtomicFlush } from './flush'\nimport { getAmbientAuditCorrelation } from './auditCorrelationScope'\nimport { getTelemetryRuntime } from '../telemetry/runtime'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n getTransactionLifetime,\n onTransactionLifetimeComplete,\n ownsTransactionLifetime,\n type TransactionLifetime,\n} from './transaction-lifetime'\n\nconst logger = createLogger('shared').child({ component: 'commands' })\n\ntype CommandActionLogService = {\n findByUndoToken(undoToken: string): Promise<ActionLog | null>\n claimForUndo(id: string, transactionalEm?: EntityManager): Promise<boolean>\n releaseUndoClaim(id: string, transactionalEm?: EntityManager): Promise<boolean>\n markUndone(id: string, traceInput?: ActionLogCreateInput, transactionalEm?: EntityManager): Promise<ActionLog | null | void>\n claimForRedo(id: string, transactionalEm?: EntityManager): Promise<boolean>\n releaseRedoClaim?(id: string, transactionalEm?: EntityManager): Promise<boolean>\n log(input: ActionLogCreateInput, transactionalEm?: EntityManager): Promise<ActionLog | null>\n}\n\ntype AtomicReplayTransaction = {\n em: EntityManager\n joinsAmbient: boolean\n}\n\nfunction isInTransaction(em: EntityManager): boolean {\n const probe = (em as { isInTransaction?: () => boolean }).isInTransaction\n return typeof probe === 'function' && probe.call(em)\n}\n\nfunction resolveAtomicReplayTransaction(ctx: CommandRuntimeContext): AtomicReplayTransaction {\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager)\n const joinsAmbient = isInTransaction(em)\n if (joinsAmbient && !ownsTransactionLifetime(em, ctx.transactionLifetime)) {\n throw new Error('[internal] Ambient atomic replay requires its outer transaction lifetime owner')\n }\n return { em, joinsAmbient }\n}\n\nfunction bindReplayTransactionContext(\n ctx: CommandRuntimeContext,\n em: EntityManager,\n expectedLifetime?: TransactionLifetime,\n): CommandRuntimeContext {\n const transactionLifetime = getTransactionLifetime(em)\n if (!transactionLifetime || (expectedLifetime && transactionLifetime !== expectedLifetime)) {\n throw new Error('[internal] Atomic replay transaction lifetime owner changed before replay')\n }\n return { ...ctx, transactionalEm: em, transactionLifetime }\n}\n\nconst SKIPPED_ACTION_LOG_RESOURCE_KINDS = new Set<string>([\n 'audit_logs.access',\n 'audit_logs.action',\n 'dashboards.layout',\n 'dashboards.user_widgets',\n 'dashboards.role_widgets',\n])\n\nfunction asRecord(input: unknown): Record<string, unknown> | null {\n if (!input || typeof input !== 'object' || Array.isArray(input)) return null\n return input as Record<string, unknown>\n}\n\nfunction mergeAuditCorrelation(\n baseContext: Record<string, unknown> | null,\n auditCorrelation: Record<string, unknown> | null | undefined,\n): Record<string, unknown> | null {\n const incoming = asRecord(auditCorrelation)\n if (!incoming) return null\n const context = baseContext ?? {}\n const existingValue = context.correlation\n const existing = asRecord(existingValue)\n if (existingValue !== undefined && existingValue !== null && !existing) return null\n const merged: Record<string, unknown> = { ...(existing ?? {}) }\n let added = false\n for (const [key, value] of Object.entries(incoming)) {\n if (typeof value !== 'string' || value.length === 0) continue\n if (Object.prototype.hasOwnProperty.call(merged, key)) continue\n merged[key] = value\n added = true\n }\n if (!added) return null\n return { ...context, correlation: merged }\n}\n\n/** Command handlers often return domain keys (e.g. warehouseId) without `id`; cache invalidation must still resolve the record. */\nfunction extractPrimaryIdFromCommandResult(result: unknown): string | null {\n const r = asRecord(result)\n if (!r) return null\n const direct = pickFirstIdentifier(r.id, r.entityId, r.recordId)\n if (direct) return direct\n for (const key of [\n 'warehouseId',\n 'zoneId',\n 'locationId',\n 'lotId',\n 'reservationId',\n 'profileId',\n 'movementId',\n 'balanceId',\n ]) {\n const v = r[key]\n if (typeof v === 'string' && v.trim().length > 0) return v.trim()\n }\n return null\n}\n\nfunction toISOString(value: unknown): string | null {\n if (value instanceof Date) {\n const iso = value.toISOString()\n return Number.isNaN(value.getTime()) ? null : iso\n }\n if (typeof value === 'string') {\n const parsed = new Date(value)\n return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString()\n }\n return null\n}\n\nfunction deepEqual(a: unknown, b: unknown, seen?: Set<unknown>): boolean {\n if (Object.is(a, b)) return true\n if (a instanceof Date || b instanceof Date) {\n const aIso = toISOString(a)\n const bIso = toISOString(b)\n if (aIso != null && bIso != null) return aIso === bIso\n return false\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false\n return a.every((value, index) => deepEqual(value, b[index], seen))\n }\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n if (!seen) seen = new Set()\n // `seen` is the current path: an object met again on it is a cycle. An object reached twice by\n // different paths (the items of one array held under two keys) is compared like any other.\n if (seen.has(a) || seen.has(b)) return false\n seen.add(a)\n seen.add(b)\n try {\n const aRec = a as Record<string, unknown>\n const bRec = b as Record<string, unknown>\n const keysA = Object.keys(aRec)\n const keysB = Object.keys(bRec)\n if (keysA.length !== keysB.length) return false\n return keysA.every((key) => deepEqual(aRec[key], bRec[key], seen))\n } finally {\n seen.delete(a)\n seen.delete(b)\n }\n }\n return false\n}\n\nconst CUSTOM_FIELD_CONTAINER_KEYS = new Set(['custom', 'customFields', 'customValues', 'cf'])\nconst SKIPPED_CHANGE_KEYS = new Set(['updatedAt', 'updated_at'])\n\nfunction appendCustomFieldChanges(\n changes: Record<string, { from: unknown; to: unknown }>,\n before: unknown,\n after: unknown\n): boolean {\n const beforeRec = asRecord(before)\n const afterRec = asRecord(after)\n if (!beforeRec && !afterRec) return false\n const left = beforeRec ?? {}\n const right = afterRec ?? {}\n const keys = new Set([...Object.keys(left), ...Object.keys(right)])\n for (const key of keys) {\n const from = left[key]\n const to = right[key]\n if (!deepEqual(from, to)) {\n changes[normalizeCustomFieldKey(key)] = { from, to }\n }\n }\n return true\n}\n\nfunction buildRecordChanges(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n): Record<string, { from: unknown; to: unknown }> {\n return buildRecordChangesDeep(before, after)\n}\n\nfunction buildRecordChangesDeep(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n prefix?: string,\n seen?: Set<unknown>,\n): Record<string, { from: unknown; to: unknown }> {\n const changes: Record<string, { from: unknown; to: unknown }> = {}\n if (!seen) seen = new Set()\n if (seen.has(before) || seen.has(after)) return changes\n seen.add(before)\n seen.add(after)\n const keys = new Set([...Object.keys(before), ...Object.keys(after)])\n for (const key of keys) {\n if (SKIPPED_CHANGE_KEYS.has(key)) continue\n if (CUSTOM_FIELD_CONTAINER_KEYS.has(key)) {\n const handled = appendCustomFieldChanges(changes, before[key], after[key])\n if (handled) continue\n }\n const from = before[key]\n const to = after[key]\n const path = prefix ? `${prefix}.${key}` : key\n const fromRec = asRecord(from)\n const toRec = asRecord(to)\n if (fromRec && toRec) {\n const nested = buildRecordChangesDeep(fromRec, toRec, path, seen)\n if (Object.keys(nested).length) {\n Object.assign(changes, nested)\n continue\n }\n }\n if (!deepEqual(from, to)) {\n changes[path] = { from, to }\n }\n }\n return changes\n}\n\nfunction deriveChangesFromSnapshots(\n before: unknown,\n after: unknown,\n): Record<string, { from: unknown; to: unknown }> | null {\n const beforeRec = asRecord(before)\n const afterRec = asRecord(after)\n if (!beforeRec || !afterRec) return null\n const changes = buildRecordChanges(beforeRec, afterRec)\n return Object.keys(changes).length ? changes : null\n}\n\nfunction invertRecordedChanges(\n changes: unknown,\n): Record<string, { from: unknown; to: unknown }> | null {\n const source = asRecord(changes)\n if (!source) return null\n const inverted: Record<string, { from: unknown; to: unknown }> = {}\n for (const [key, value] of Object.entries(source)) {\n const entry = asRecord(value)\n if (!entry || (!('from' in entry) && !('to' in entry))) continue\n inverted[key] = {\n from: entry.to,\n to: entry.from,\n }\n }\n return Object.keys(inverted).length ? inverted : null\n}\n\nfunction extractAliasList(source: unknown): string[] {\n if (!source || typeof source !== 'object' || Array.isArray(source)) return []\n const record = source as Record<string, unknown>\n const raw = record.cacheAliases\n if (!Array.isArray(raw)) return []\n const aliases = new Set<string>()\n for (const value of raw) {\n if (typeof value !== 'string') continue\n const normalized = canonicalizeResourceTag(value)\n if (normalized) aliases.add(normalized)\n }\n return Array.from(aliases)\n}\n\nexport class CommandBus {\n async execute<TInput = unknown, TResult = unknown>(\n commandId: string,\n options: CommandExecutionOptions<TInput>\n ): Promise<CommandExecuteResult<TResult>> {\n const handler = await this.resolveHandler<TInput, TResult>(commandId)\n\n const replayLogEntry = options.redoLogEntry ?? null\n const isAtomicReplay = replayLogEntry !== null && handler.atomicReplay === true\n const allInterceptors = getAllCommandInterceptorInstances()\n let interceptorMetadata = new Map<string, Record<string, unknown>>()\n let effectiveOptions = options\n let userFeatures: string[] = []\n const runBeforeExecuteInterceptors = async (baseOptions: CommandExecutionOptions<TInput>) => {\n const resolvedUserFeatures = allInterceptors.length\n ? await this.resolveUserFeaturesForInterceptors(baseOptions.ctx)\n : []\n if (!allInterceptors.length) {\n return {\n effectiveOptions: baseOptions,\n metadata: new Map<string, Record<string, unknown>>(),\n userFeatures: resolvedUserFeatures,\n }\n }\n const interceptorCtx: CommandInterceptorContext = {\n commandId,\n auth: baseOptions.ctx.auth ?? null,\n selectedOrganizationId: baseOptions.ctx.selectedOrganizationId ?? baseOptions.ctx.auth?.orgId ?? null,\n container: baseOptions.ctx.container,\n organizationScope: baseOptions.ctx.organizationScope ?? null,\n request: baseOptions.ctx.request ?? null,\n }\n const beforeResult = await runCommandInterceptorsBefore(\n allInterceptors, commandId, baseOptions.input, interceptorCtx, resolvedUserFeatures,\n )\n if (!beforeResult.ok) {\n const blocked = beforeResult.error!\n throw new CommandInterceptorError(blocked.message, { status: blocked.status, body: blocked.body })\n }\n const preparedOptions = beforeResult.modifiedInput\n ? {\n ...baseOptions,\n input: { ...(baseOptions.input as object), ...beforeResult.modifiedInput } as TInput,\n }\n : baseOptions\n return {\n effectiveOptions: preparedOptions,\n metadata: beforeResult.metadataByInterceptor,\n userFeatures: resolvedUserFeatures,\n }\n }\n\n if (replayLogEntry && !isAtomicReplay) {\n await this.runReplayTransactionGuard(options.ctx, 'redo', replayLogEntry)\n if (handler.authorizeReplay) {\n await handler.authorizeReplay({\n operation: 'redo',\n input: options.input,\n ctx: options.ctx,\n logEntry: replayLogEntry,\n })\n }\n }\n\n if (!isAtomicReplay) {\n const prepared = await runBeforeExecuteInterceptors(options)\n effectiveOptions = prepared.effectiveOptions\n interceptorMetadata = prepared.metadata\n userFeatures = prepared.userFeatures\n }\n\n const executeCore = async (coreOptions: CommandExecutionOptions<TInput>) => {\n const snapshots: { before?: unknown } = {}\n let executionOptions = coreOptions\n if (handler.prepareSnapshotInsideTransaction && handler.prepare) {\n const prepare = handler.prepare\n const originalCtx = coreOptions.ctx\n const originalBeforeTransactionalWrite = originalCtx.beforeTransactionalWrite\n let prepared = false\n let transactionalCtx: CommandRuntimeContext\n transactionalCtx = {\n ...originalCtx,\n beforeTransactionalWrite: async (em, input) => {\n await originalBeforeTransactionalWrite?.(em, input)\n if (prepared) return\n Object.assign(\n snapshots,\n (await prepare(coreOptions.input, { ...transactionalCtx, transactionalEm: em })) ?? {},\n )\n prepared = true\n },\n }\n executionOptions = { ...coreOptions, ctx: transactionalCtx }\n } else {\n Object.assign(snapshots, await this.prepareSnapshots(handler, coreOptions))\n }\n effectiveOptions = executionOptions\n const sourceLog = executionOptions.redoLogEntry ?? null\n const result =\n sourceLog && typeof handler.redo === 'function'\n ? await handler.redo({ input: executionOptions.input, ctx: executionOptions.ctx, logEntry: sourceLog })\n : await handler.execute(executionOptions.input, executionOptions.ctx)\n const afterSnapshot = await this.captureAfter(handler, executionOptions, result)\n const snapshotsWithAfter = { ...snapshots, after: afterSnapshot }\n const logMeta = await this.buildLog(handler, executionOptions, result, snapshotsWithAfter)\n let mergedMeta = this.mergeMetadata(executionOptions.metadata, logMeta)\n // Interceptors opt into audit-log enrichment with a reserved `logContext` key rather\n // than the generic `context` one, so the metadata an interceptor already passes to its\n // own afterExecute hook is never silently promoted into audit storage.\n // Map iteration order is interceptor priority order (see collectMatching), so a\n // later-priority interceptor overrides an earlier one on key collisions.\n let interceptorContextMerged: Record<string, unknown> = {}\n for (const meta of interceptorMetadata.values()) {\n const logContextRecord = asRecord(asRecord(meta)?.logContext)\n if (!logContextRecord) continue\n interceptorContextMerged = {\n ...interceptorContextMerged,\n ...logContextRecord,\n }\n }\n const baseContext = asRecord(executionOptions.metadata?.context) ?? {}\n const logMetaContext = asRecord(logMeta?.context) ?? {}\n if (Object.keys(interceptorContextMerged).length > 0 || Object.keys(baseContext).length > 0 || Object.keys(logMetaContext).length > 0) {\n mergedMeta = mergedMeta ?? {}\n mergedMeta.context = {\n ...baseContext,\n ...interceptorContextMerged,\n ...logMetaContext,\n }\n }\n const undoable = this.isUndoable(handler)\n if (undoable && mergedMeta?.replayable !== false) {\n mergedMeta = mergedMeta ?? {}\n if (!mergedMeta.undoToken) mergedMeta.undoToken = defaultUndoToken()\n if (mergedMeta.actorUserId === undefined) mergedMeta.actorUserId = executionOptions.ctx.auth?.sub ?? null\n } else if (mergedMeta?.replayable === false) {\n mergedMeta.undoToken = null\n }\n if (afterSnapshot !== undefined && afterSnapshot !== null) {\n if (!mergedMeta) {\n mergedMeta = { snapshotAfter: afterSnapshot }\n } else if (!mergedMeta.snapshotAfter) {\n mergedMeta.snapshotAfter = afterSnapshot\n }\n }\n if (snapshots.before) {\n if (!mergedMeta) {\n mergedMeta = { snapshotBefore: snapshots.before }\n } else if (!mergedMeta.snapshotBefore) {\n mergedMeta.snapshotBefore = snapshots.before\n }\n }\n if (mergedMeta?.snapshotBefore !== undefined && mergedMeta?.snapshotAfter !== undefined) {\n const currentChanges = mergedMeta.changes\n const shouldInfer =\n currentChanges === undefined ||\n currentChanges === null ||\n (typeof currentChanges === 'object' && !Array.isArray(currentChanges) && Object.keys(currentChanges).length === 0)\n if (shouldInfer) {\n const inferred = deriveChangesFromSnapshots(mergedMeta.snapshotBefore, mergedMeta.snapshotAfter)\n if (inferred) mergedMeta.changes = inferred\n }\n }\n const logEntry = await this.persistLog(commandId, executionOptions, mergedMeta)\n return { result, mergedMeta, logEntry }\n }\n\n let replaySourceFinalized = false\n let coreResult: Awaited<ReturnType<typeof executeCore>>\n const atomicSourceLog = options.redoLogEntry ?? null\n let ambientReplay: AtomicReplayTransaction | null = null\n let replayTransactionLifetime: TransactionLifetime | null = null\n if (atomicSourceLog && isAtomicReplay) {\n ambientReplay = resolveAtomicReplayTransaction(options.ctx)\n const replayEm = ambientReplay.em\n await withAtomicFlush(replayEm, [async () => {\n const replayCtx = bindReplayTransactionContext(\n options.ctx,\n replayEm,\n ambientReplay?.joinsAmbient ? options.ctx.transactionLifetime : undefined,\n )\n replayTransactionLifetime = replayCtx.transactionLifetime ?? null\n const transactionalBaseOptions: CommandExecutionOptions<TInput> = {\n ...options,\n ctx: replayCtx,\n }\n if (!atomicSourceLog.id) throw new Error('[internal] Atomic redo source log id is required')\n if (handler.stabilizeReplay) {\n await handler.stabilizeReplay({\n operation: 'redo',\n input: transactionalBaseOptions.input,\n ctx: transactionalBaseOptions.ctx,\n logEntry: atomicSourceLog,\n })\n }\n await this.runReplayTransactionGuard(\n transactionalBaseOptions.ctx,\n 'redo',\n atomicSourceLog,\n replayEm,\n )\n const prepared = await runBeforeExecuteInterceptors(transactionalBaseOptions)\n effectiveOptions = prepared.effectiveOptions\n interceptorMetadata = prepared.metadata\n userFeatures = prepared.userFeatures\n const service = effectiveOptions.ctx.container.resolve('actionLogService') as CommandActionLogService\n if (handler.authorizeReplay) {\n await handler.authorizeReplay({\n operation: 'redo',\n input: effectiveOptions.input,\n ctx: effectiveOptions.ctx,\n logEntry: atomicSourceLog,\n })\n }\n const claimed = await service.claimForRedo(atomicSourceLog.id, replayEm)\n if (!claimed) throw new Error('[internal] Redo source already consumed')\n coreResult = await executeCore(effectiveOptions)\n }], { transaction: true, label: `${commandId}.redo` })\n replaySourceFinalized = !ambientReplay.joinsAmbient\n } else if (replayLogEntry?.id) {\n const redoClaimRelease = await this.claimRedoSource(effectiveOptions.ctx, commandId, replayLogEntry.id)\n try {\n coreResult = await executeCore(effectiveOptions)\n } catch (err) {\n await redoClaimRelease?.()\n throw err\n }\n replaySourceFinalized = redoClaimRelease !== null\n } else {\n coreResult = await executeCore(effectiveOptions)\n }\n const { result, mergedMeta, logEntry } = coreResult!\n\n const runPostCommit = async () => {\n let finalResult = result\n if (allInterceptors.length) {\n const interceptorCtx: CommandInterceptorContext = {\n commandId,\n auth: effectiveOptions.ctx.auth ?? null,\n selectedOrganizationId: effectiveOptions.ctx.selectedOrganizationId ?? effectiveOptions.ctx.auth?.orgId ?? null,\n container: effectiveOptions.ctx.container,\n organizationScope: effectiveOptions.ctx.organizationScope ?? null,\n request: effectiveOptions.ctx.request ?? null,\n }\n const afterResult = await runCommandInterceptorsAfter(\n allInterceptors, commandId, effectiveOptions.input, result, interceptorCtx,\n userFeatures, interceptorMetadata,\n )\n if (afterResult.modifiedResult && typeof result === 'object' && result) {\n finalResult = { ...(result as object), ...afterResult.modifiedResult } as Awaited<TResult>\n }\n }\n\n if (!effectiveOptions.skipCacheInvalidation) {\n await this.invalidateCacheAfterExecute(commandId, effectiveOptions, finalResult, mergedMeta)\n }\n // Bulk-import backfills defer heavy per-record side effects: the ctx flags are read here and\n // threaded as a local into the flush (never stored on the shared dataEngine), so a concurrent\n // command with different flags can't observe them. Reindex is restored by the caller's\n // end-of-run `query_index rebuild`. Mirrors `skipCacheInvalidation` above.\n await this.flushCrudSideEffects(effectiveOptions.ctx.container, effectiveOptions.ctx?.bulkImport)\n return finalResult\n }\n\n const executionResult: CommandExecuteResult<TResult> = {\n result,\n logEntry,\n replaySourceFinalized,\n }\n if (ambientReplay?.joinsAmbient) {\n if (!replayTransactionLifetime || !ownsTransactionLifetime(ambientReplay.em, replayTransactionLifetime)) {\n throw new Error('[internal] Ambient atomic replay lost its outer transaction lifetime owner')\n }\n onTransactionLifetimeComplete(ambientReplay.em, async (outcome) => {\n if (outcome !== 'committed') return\n executionResult.result = await runPostCommit()\n executionResult.replaySourceFinalized = true\n })\n return executionResult\n }\n\n executionResult.result = await runPostCommit()\n return executionResult\n }\n\n async undo(undoToken: string, ctx: CommandRuntimeContext): Promise<void> {\n const service = (ctx.container.resolve('actionLogService') as CommandActionLogService)\n const log = await service.findByUndoToken(undoToken)\n if (!log) throw new Error('Undo token expired or not found')\n const handler = await this.resolveHandler(log.commandId)\n if (!handler.undo || this.isUndoable(handler) === false) {\n throw new Error(`Command ${log.commandId} is not undoable`)\n }\n\n const isAtomicReplay = handler.atomicReplay === true\n const allInterceptors = getAllCommandInterceptorInstances()\n let undoInterceptorMetadata = new Map<string, Record<string, unknown>>()\n let userFeatures: string[] = []\n const runBeforeUndoInterceptors = async (replayCtx: CommandRuntimeContext) => {\n const resolvedUserFeatures = allInterceptors.length\n ? await this.resolveUserFeaturesForInterceptors(replayCtx)\n : []\n if (!allInterceptors.length) {\n return {\n metadata: new Map<string, Record<string, unknown>>(),\n userFeatures: resolvedUserFeatures,\n }\n }\n const undoCtx = { input: log.commandPayload, logEntry: log, undoToken }\n const interceptorCtx: CommandInterceptorContext = {\n commandId: log.commandId,\n auth: replayCtx.auth ?? null,\n selectedOrganizationId: replayCtx.selectedOrganizationId ?? replayCtx.auth?.orgId ?? null,\n container: replayCtx.container,\n organizationScope: replayCtx.organizationScope ?? null,\n request: replayCtx.request ?? null,\n }\n const beforeResult = await runCommandInterceptorsBeforeUndo(\n allInterceptors, log.commandId, undoCtx, interceptorCtx, resolvedUserFeatures,\n )\n if (!beforeResult.ok) {\n const blocked = beforeResult.error!\n throw new CommandInterceptorError(blocked.message, { status: blocked.status, body: blocked.body })\n }\n return {\n metadata: beforeResult.metadataByInterceptor,\n userFeatures: resolvedUserFeatures,\n }\n }\n\n if (!isAtomicReplay) {\n await this.runReplayTransactionGuard(ctx, 'undo', log)\n if (handler.authorizeReplay) {\n await handler.authorizeReplay({\n operation: 'undo',\n input: log.commandPayload as Parameters<NonNullable<typeof handler.authorizeReplay>>[0]['input'],\n ctx,\n logEntry: log,\n })\n }\n }\n\n const claimUndo = async (replayEm?: EntityManager) => {\n // Two contenders can both pass the initial lookup; only the compare-and-set\n // below may proceed. On the atomic path this state is still uncommitted and\n // rolls back with every handler/log write if anything later fails.\n const claimed = replayEm\n ? await service.claimForUndo(log.id, replayEm)\n : await service.claimForUndo(log.id)\n if (!claimed) throw new Error('[internal] Undo token already consumed')\n }\n const finishUndo = async (replayCtx: CommandRuntimeContext, replayEm?: EntityManager) => {\n await handler.undo!({\n input: log.commandPayload as Parameters<NonNullable<typeof handler.undo>>[0]['input'],\n ctx: replayCtx,\n logEntry: log,\n })\n const traceLog = this.buildUndoTraceLog(log, replayCtx)\n if (replayEm) {\n await service.markUndone(log.id, traceLog, replayEm)\n } else {\n await service.markUndone(log.id, traceLog)\n }\n }\n\n let ambientReplay: AtomicReplayTransaction | null = null\n let replayTransactionLifetime: TransactionLifetime | null = null\n if (isAtomicReplay) {\n ambientReplay = resolveAtomicReplayTransaction(ctx)\n const replayEm = ambientReplay.em\n await withAtomicFlush(replayEm, [async () => {\n const replayCtx = bindReplayTransactionContext(\n ctx,\n replayEm,\n ambientReplay?.joinsAmbient ? ctx.transactionLifetime : undefined,\n )\n replayTransactionLifetime = replayCtx.transactionLifetime ?? null\n if (handler.stabilizeReplay) {\n await handler.stabilizeReplay({\n operation: 'undo',\n input: log.commandPayload as Parameters<NonNullable<typeof handler.stabilizeReplay>>[0]['input'],\n ctx: replayCtx,\n logEntry: log,\n })\n }\n await this.runReplayTransactionGuard(replayCtx, 'undo', log, replayEm)\n const prepared = await runBeforeUndoInterceptors(replayCtx)\n undoInterceptorMetadata = prepared.metadata\n userFeatures = prepared.userFeatures\n if (handler.authorizeReplay) {\n await handler.authorizeReplay({\n operation: 'undo',\n input: log.commandPayload as Parameters<NonNullable<typeof handler.authorizeReplay>>[0]['input'],\n ctx: replayCtx,\n logEntry: log,\n })\n }\n await claimUndo(replayEm)\n await finishUndo(replayCtx, replayEm)\n }], {\n transaction: true,\n label: `${log.commandId}.undo`,\n })\n } else {\n let undoClaimed = false\n try {\n // Preserve the established non-atomic lifecycle exactly: authorization,\n // source claim, before-undo interceptors, handler, then finalization.\n await claimUndo()\n undoClaimed = true\n const prepared = await runBeforeUndoInterceptors(ctx)\n undoInterceptorMetadata = prepared.metadata\n userFeatures = prepared.userFeatures\n await finishUndo(ctx)\n } catch (err) {\n // Legacy handlers retain their compensating release behavior because\n // their domain mutation may not share the action-log transaction.\n if (undoClaimed) {\n await service.releaseUndoClaim(log.id).catch((releaseErr: unknown) => {\n logger.error('Failed to release undo claim', { commandId: log.commandId, logId: log.id, err: releaseErr })\n getTelemetryRuntime()?.reportError(releaseErr, {\n module: 'shared',\n code: 'shared.undo_claim_release_failed',\n })\n })\n }\n throw err\n }\n }\n\n const runPostCommit = async () => {\n // Post-commit hooks and side effects run only after an atomic replay has\n // durably committed both the domain state and source/trace log state.\n if (allInterceptors.length) {\n const undoCtx = { input: log.commandPayload, logEntry: log, undoToken }\n const interceptorCtx: CommandInterceptorContext = {\n commandId: log.commandId,\n auth: ctx.auth ?? null,\n selectedOrganizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n container: ctx.container,\n organizationScope: ctx.organizationScope ?? null,\n request: ctx.request ?? null,\n }\n await runCommandInterceptorsAfterUndo(\n allInterceptors, log.commandId, undoCtx, interceptorCtx,\n userFeatures, undoInterceptorMetadata,\n )\n }\n\n await this.invalidateCacheAfterUndo(log, ctx)\n await this.flushCrudSideEffects(ctx.container)\n }\n\n if (ambientReplay?.joinsAmbient) {\n if (!replayTransactionLifetime || !ownsTransactionLifetime(ambientReplay.em, replayTransactionLifetime)) {\n throw new Error('[internal] Ambient atomic replay lost its outer transaction lifetime owner')\n }\n onTransactionLifetimeComplete(ambientReplay.em, async (outcome) => {\n if (outcome === 'committed') await runPostCommit()\n })\n return\n }\n\n await runPostCommit()\n }\n\n private buildUndoTraceLog(log: ActionLog, ctx: CommandRuntimeContext): ActionLogCreateInput | undefined {\n const snapshotBefore = log.snapshotAfter ?? null\n const snapshotAfter = log.snapshotBefore ?? null\n const changes =\n deriveChangesFromSnapshots(snapshotBefore, snapshotAfter)\n ?? invertRecordedChanges(log.changesJson)\n ?? undefined\n\n const baseContext = asRecord(log.contextJson) ?? {}\n const context = {\n ...baseContext,\n historyAction: 'undo',\n sourceLogId: log.id,\n sourceCommandId: log.commandId,\n }\n\n return {\n tenantId: log.tenantId ?? ctx.auth?.tenantId ?? null,\n organizationId: log.organizationId ?? ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n actorUserId: ctx.auth?.sub ?? log.actorUserId ?? null,\n commandId: log.commandId,\n actionLabel: log.actionLabel ?? undefined,\n resourceKind: log.resourceKind ?? undefined,\n resourceId: log.resourceId ?? undefined,\n parentResourceKind: log.parentResourceKind ?? null,\n parentResourceId: log.parentResourceId ?? null,\n relatedResourceKind: log.relatedResourceKind ?? null,\n relatedResourceId: log.relatedResourceId ?? null,\n snapshotBefore,\n snapshotAfter,\n changes,\n context,\n }\n }\n\n private async resolveUserFeaturesForInterceptors(ctx: CommandRuntimeContext): Promise<string[]> {\n if (!ctx.auth) return []\n type RbacLike = {\n getGrantedFeatures: (\n userId: string,\n opts: { tenantId: string | null; organizationId: string | null },\n ) => Promise<string[]>\n getGrantedFeaturesWithEntityManager?: (\n em: EntityManager,\n userId: string,\n opts: { tenantId: string | null; organizationId: string | null },\n ) => Promise<string[]>\n }\n let rbac: RbacLike | undefined\n try {\n rbac = ctx.container.resolve('rbacService') as RbacLike | undefined\n } catch {\n // Intentional: rbacService is not registered in all runtime contexts (CLI, tests, bootstrap).\n return []\n }\n const scope = {\n tenantId: ctx.auth.tenantId,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth.orgId,\n }\n if (ctx.transactionalEm) {\n if (!rbac?.getGrantedFeaturesWithEntityManager) return []\n return await rbac.getGrantedFeaturesWithEntityManager(\n ctx.transactionalEm,\n ctx.auth.sub,\n scope,\n )\n }\n try {\n if (rbac?.getGrantedFeatures) {\n return await rbac.getGrantedFeatures(ctx.auth.sub, scope)\n }\n } catch {\n // Outside a transaction a failed lookup cannot poison anything; interceptors without\n // feature gating still run. Inside one the error is rethrown above, because the failed\n // query has already aborted the transaction.\n }\n return []\n }\n\n private async runReplayTransactionGuard(\n ctx: CommandRuntimeContext,\n operation: 'undo' | 'redo',\n logEntry: CommandUndoLogEntry,\n transactionalEm?: EntityManager,\n ): Promise<void> {\n if (!ctx.replayTransactionGuard) return\n if (transactionalEm) {\n await ctx.replayTransactionGuard({ operation, logEntry, transactionalEm })\n return\n }\n const requestEm = ctx.container.resolve('em') as EntityManager\n const guardEm = typeof requestEm.fork === 'function' ? requestEm.fork() : requestEm\n await withAtomicFlush(guardEm, [async () => {\n await ctx.replayTransactionGuard!({ operation, logEntry, transactionalEm: guardEm })\n }], { transaction: true, label: `${logEntry.commandId}.${operation}.request-guard` })\n }\n\n private async claimRedoSource(\n ctx: CommandRuntimeContext,\n commandId: string,\n sourceLogId: string,\n ): Promise<(() => Promise<void>) | null> {\n let service: CommandActionLogService | null = null\n try {\n service = ctx.container.resolve('actionLogService') as CommandActionLogService\n } catch {\n service = null\n }\n if (!service || typeof service.claimForRedo !== 'function' || typeof service.releaseRedoClaim !== 'function') {\n logger.warn('Redo source claim unavailable; replaying without an atomic claim', { commandId, sourceLogId })\n return null\n }\n const releaseClaim = service.releaseRedoClaim.bind(service)\n const transactionalEm = ctx.transactionalEm\n const claimed = transactionalEm\n ? await service.claimForRedo(sourceLogId, transactionalEm)\n : await service.claimForRedo(sourceLogId)\n if (!claimed) throw new Error('[internal] Redo source already consumed')\n return async () => {\n try {\n const released = transactionalEm\n ? await releaseClaim(sourceLogId, transactionalEm)\n : await releaseClaim(sourceLogId)\n if (!released) logger.warn('Redo source claim was not held at release', { commandId, sourceLogId })\n } catch (releaseErr) {\n logger.error('Failed to release redo source claim', { commandId, sourceLogId, err: releaseErr })\n getTelemetryRuntime()?.reportError(releaseErr, {\n module: 'shared',\n code: 'shared.redo_claim_release_failed',\n })\n }\n }\n }\n\n private async resolveHandler<TInput, TResult>(commandId: string): Promise<CommandHandler<TInput, TResult>> {\n const handler =\n commandRegistry.get<TInput, TResult>(commandId) ??\n ((await commandRegistry.load(commandId)) as CommandHandler<TInput, TResult> | null)\n if (!handler) {\n const moduleName = commandId.split('.')[0]\n const registered = commandRegistry.list()\n const sameModule = registered.filter((id) => id.split('.')[0] === moduleName)\n const registeredLoaders = commandRegistry.listLoaders()\n const sameModuleLoaders = registeredLoaders.filter((id) => id === commandId || id.startsWith(`${moduleName}:`))\n const hint = sameModule.length > 0\n ? ` Registered commands for module \"${moduleName}\": [${sameModule.join(', ')}].`\n : sameModuleLoaders.length > 0\n ? ` Command loaders for module \"${moduleName}\" were registered but none loaded \"${commandId}\".`\n : ` No commands or command loaders registered for module \"${moduleName}\". Ensure the command file is imported or generated lazy command loaders are registered.`\n throw new Error(`Command handler not registered for id ${commandId}.${hint}`)\n }\n return handler\n }\n\n private async prepareSnapshots<TInput, TResult>(\n handler: CommandHandler<TInput, TResult>,\n options: CommandExecutionOptions<TInput>\n ): Promise<{ before?: unknown }> {\n if (!handler.prepare) return {}\n try {\n return (await handler.prepare(options.input, options.ctx)) || {}\n } catch (err) {\n throw err\n }\n }\n\n private async captureAfter<TInput, TResult>(\n handler: CommandHandler<TInput, TResult>,\n options: CommandExecutionOptions<TInput>,\n result: TResult\n ): Promise<unknown> {\n if (!handler.captureAfter) return undefined\n return handler.captureAfter(options.input, result, options.ctx)\n }\n\n private async buildLog<TInput, TResult>(\n handler: CommandHandler<TInput, TResult>,\n options: CommandExecutionOptions<TInput>,\n result: TResult,\n snapshots: { before?: unknown; after?: unknown }\n ): Promise<CommandLogMetadata | null> {\n if (!handler.buildLog) return null\n const args: CommandLogBuilderArgs<TInput, TResult> = {\n input: options.input,\n result,\n ctx: options.ctx,\n snapshots,\n }\n return (await handler.buildLog(args)) || null\n }\n\n private mergeMetadata(primary?: CommandLogMetadata | null, secondary?: CommandLogMetadata | null): CommandLogMetadata | null {\n if (!primary && !secondary) return null\n return {\n skipLog: secondary?.skipLog ?? primary?.skipLog ?? false,\n replayable:\n secondary?.replayable === false || primary?.replayable === false\n ? false\n : secondary?.replayable ?? primary?.replayable,\n tenantId: secondary?.tenantId ?? primary?.tenantId ?? null,\n organizationId: secondary?.organizationId ?? primary?.organizationId ?? null,\n actorUserId: secondary?.actorUserId ?? primary?.actorUserId ?? null,\n onBehalfOfUserId: secondary?.onBehalfOfUserId ?? primary?.onBehalfOfUserId ?? null,\n actionLabel: secondary?.actionLabel ?? primary?.actionLabel ?? null,\n resourceKind: secondary?.resourceKind ?? primary?.resourceKind ?? null,\n resourceId: secondary?.resourceId ?? primary?.resourceId ?? null,\n parentResourceKind: secondary?.parentResourceKind ?? primary?.parentResourceKind ?? null,\n parentResourceId: secondary?.parentResourceId ?? primary?.parentResourceId ?? null,\n relatedResourceKind: secondary?.relatedResourceKind ?? primary?.relatedResourceKind ?? null,\n relatedResourceId: secondary?.relatedResourceId ?? primary?.relatedResourceId ?? null,\n undoToken: secondary?.undoToken ?? primary?.undoToken ?? null,\n // A redacted redo input always wins: it exists precisely because the raw\n // input carries a secret that must not reach `action_logs`.\n redoInput: secondary?.redoInput !== undefined ? secondary.redoInput : primary?.redoInput,\n payload: secondary?.payload ?? primary?.payload ?? null,\n snapshotBefore: secondary?.snapshotBefore ?? primary?.snapshotBefore ?? null,\n snapshotAfter: secondary?.snapshotAfter ?? primary?.snapshotAfter ?? null,\n changes: secondary?.changes ?? primary?.changes ?? null,\n context: secondary?.context ?? primary?.context ?? null,\n }\n }\n\n private async persistLog<TInput>(\n commandId: string,\n options: CommandExecutionOptions<TInput>,\n metadata: CommandLogMetadata | null\n ): Promise<ActionLog | null> {\n if (!metadata) return null\n if (metadata.skipLog) return null\n const resourceKind =\n typeof metadata.resourceKind === 'string' ? metadata.resourceKind : null\n if (resourceKind && SKIPPED_ACTION_LOG_RESOURCE_KINDS.has(resourceKind)) {\n return null\n }\n let service: CommandActionLogService | null = null\n try {\n service = (options.ctx.container.resolve('actionLogService') as CommandActionLogService)\n } catch {\n service = null\n }\n if (!service) return null\n\n const tenantId = metadata.tenantId ?? options.ctx.auth?.tenantId ?? null\n const organizationId =\n metadata.organizationId ?? options.ctx.selectedOrganizationId ?? options.ctx.auth?.orgId ?? null\n // On-behalf-of attribution (Wave 4 P2): when `ctx.runAs` is set the actor is\n // the agent principal and the human it acts for is recorded separately. This\n // funnels agent writes through the SAME ActionLog path as a human's \u2014 only the\n // attribution differs (actorUserId=agent, onBehalfOfUserId=human, source='agent').\n const runAs = options.ctx.runAs ?? null\n const actorUserId = runAs?.actorUserId ?? metadata.actorUserId ?? options.ctx.auth?.sub ?? null\n const onBehalfOfUserId = runAs ? (runAs.onBehalfOfUserId ?? null) : (metadata.onBehalfOfUserId ?? null)\n const systemActorContext = !actorUserId && options.ctx.systemActor === true\n ? { systemActor: 'system:command' }\n : null\n const payload: Record<string, unknown> = {\n tenantId: tenantId ?? undefined,\n organizationId: organizationId ?? undefined,\n actorUserId: actorUserId ?? undefined,\n onBehalfOfUserId: onBehalfOfUserId ?? undefined,\n commandId,\n }\n\n if (metadata) {\n if ('actionLabel' in metadata && metadata.actionLabel != null) payload.actionLabel = metadata.actionLabel\n if ('resourceKind' in metadata && metadata.resourceKind != null) payload.resourceKind = metadata.resourceKind\n if ('resourceId' in metadata && metadata.resourceId != null) payload.resourceId = metadata.resourceId\n if ('parentResourceKind' in metadata && metadata.parentResourceKind != null) payload.parentResourceKind = metadata.parentResourceKind\n if ('parentResourceId' in metadata && metadata.parentResourceId != null) payload.parentResourceId = metadata.parentResourceId\n if ('relatedResourceKind' in metadata && metadata.relatedResourceKind != null) payload.relatedResourceKind = metadata.relatedResourceKind\n if ('relatedResourceId' in metadata && metadata.relatedResourceId != null) payload.relatedResourceId = metadata.relatedResourceId\n if ('undoToken' in metadata && metadata.undoToken != null) payload.undoToken = metadata.undoToken\n if ('payload' in metadata && metadata.payload !== undefined) payload.commandPayload = metadata.payload\n if ('snapshotBefore' in metadata && metadata.snapshotBefore !== undefined) payload.snapshotBefore = metadata.snapshotBefore\n if ('snapshotAfter' in metadata && metadata.snapshotAfter !== undefined) payload.snapshotAfter = metadata.snapshotAfter\n if ('changes' in metadata && metadata.changes !== undefined && metadata.changes !== null) payload.changes = metadata.changes\n if ('context' in metadata && metadata.context !== undefined && metadata.context !== null) {\n payload.context = { ...(systemActorContext ?? {}), ...metadata.context }\n } else if (systemActorContext) {\n payload.context = systemActorContext\n }\n }\n\n if (runAs) {\n // Stamp the audit source so `deriveActionLogSource` projects `sourceKey='agent'`.\n // Merge into any caller-provided context rather than replacing it.\n const baseContext = asRecord(payload.context) ?? {}\n payload.context = { ...baseContext, source: runAs.source }\n }\n\n const correlationContext = mergeAuditCorrelation(asRecord(payload.context), options.ctx.auditCorrelation)\n if (correlationContext) payload.context = correlationContext\n const ambientCorrelationContext = mergeAuditCorrelation(asRecord(payload.context), getAmbientAuditCorrelation())\n if (ambientCorrelationContext) payload.context = ambientCorrelationContext\n\n if (metadata.replayable === false) {\n delete payload.commandPayload\n } else {\n const redoInput = metadata.redoInput !== undefined ? metadata.redoInput : options.input\n const redoEnvelope = wrapRedoPayload('commandPayload' in payload ? (payload.commandPayload as unknown) : undefined, redoInput)\n payload.commandPayload = redoEnvelope\n }\n\n return options.ctx.transactionalEm\n ? await service.log(payload as ActionLogCreateInput, options.ctx.transactionalEm)\n : await service.log(payload as ActionLogCreateInput)\n }\n\n private isUndoable(handler: CommandHandler<unknown, unknown>): boolean {\n return handler.isUndoable !== false && typeof handler.undo === 'function'\n }\n\n private async invalidateCacheAfterExecute<TResult>(\n commandId: string,\n options: CommandExecutionOptions<unknown>,\n result: TResult,\n metadata: CommandLogMetadata | null\n ): Promise<void> {\n const resource = typeof metadata?.resourceKind === 'string' ? metadata.resourceKind : null\n if (!resource) return\n try {\n const ctx = options.ctx\n const resultRecord = asRecord(result)\n const resultEntity = asRecord(resultRecord?.entity)\n const inputRecord = asRecord(options.input)\n const inputEntity = asRecord(inputRecord?.entity)\n\n const recordId = pickFirstIdentifier(\n metadata?.resourceId,\n extractPrimaryIdFromCommandResult(result),\n resultRecord?.entityId,\n resultRecord?.id,\n resultRecord?.recordId,\n resultEntity?.id,\n inputRecord?.id,\n inputRecord?.entityId,\n inputRecord?.recordId,\n inputEntity?.id\n )\n\n const organizationId = pickFirstIdentifier(\n metadata?.organizationId,\n resultRecord?.organizationId,\n resultEntity?.organizationId,\n inputRecord?.organizationId,\n inputEntity?.organizationId,\n ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null\n )\n\n const tenantId = pickFirstIdentifier(\n metadata?.tenantId,\n resultRecord?.tenantId,\n resultEntity?.tenantId,\n inputRecord?.tenantId,\n inputEntity?.tenantId,\n ctx.auth?.tenantId ?? null\n )\n\n const fallbackTenant = pickFirstIdentifier(metadata?.tenantId, ctx.auth?.tenantId ?? null)\n\n const aliasSet = new Set<string>()\n for (const alias of extractAliasList(metadata?.context ?? null)) {\n aliasSet.add(alias)\n }\n const derived = deriveResourceFromCommandId(commandId)\n if (derived) aliasSet.add(derived)\n const aliasExtras = Array.from(aliasSet)\n await invalidateCrudCache(\n ctx.container,\n resource,\n { id: recordId, organizationId, tenantId },\n fallbackTenant,\n `command:${commandId}:execute`,\n aliasExtras\n )\n } catch (err) {\n if (isCrudCacheDebugEnabled()) {\n try {\n logger.debug('Cache execute-invalidation failed', { commandId, err })\n } catch {}\n }\n }\n }\n\n private async invalidateCacheAfterUndo(log: ActionLog, ctx: CommandRuntimeContext): Promise<void> {\n const resource = typeof log.resourceKind === 'string' ? log.resourceKind : null\n if (!resource) return\n try {\n const recordId = pickFirstIdentifier(log.resourceId)\n const organizationId = pickFirstIdentifier(log.organizationId, ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null)\n const tenantId = pickFirstIdentifier(log.tenantId, ctx.auth?.tenantId ?? null)\n const fallbackTenant = pickFirstIdentifier(log.tenantId, ctx.auth?.tenantId ?? null)\n const aliasSet = new Set<string>()\n for (const alias of extractAliasList(log.contextJson ?? null)) {\n aliasSet.add(alias)\n }\n const derived = deriveResourceFromCommandId(log.commandId)\n if (derived) aliasSet.add(derived)\n const aliasExtras = Array.from(aliasSet)\n await invalidateCrudCache(\n ctx.container,\n resource,\n { id: recordId, organizationId, tenantId },\n fallbackTenant,\n `command:${log.commandId}:undo`,\n aliasExtras\n )\n } catch (err) {\n if (isCrudCacheDebugEnabled()) {\n try {\n logger.debug('Cache undo-invalidation failed', { commandId: log.commandId, err })\n } catch {}\n }\n }\n }\n\n private async flushCrudSideEffects(container: AwilixContainer, suppress?: BulkImportSuppression): Promise<void> {\n try {\n const dataEngine = (container.resolve('dataEngine') as DataEngine)\n await dataEngine.flushOrmEntityChanges(suppress)\n } catch (error) {\n if (isReadProjectionAlwaysConsistent()) {\n throw error\n }\n // best-effort: failures should not block command execution\n }\n }\n}\n\ntype RedoEnvelope = {\n __redoInput: unknown\n [key: string]: unknown\n}\n\nfunction wrapRedoPayload(existing: unknown, input: unknown): RedoEnvelope {\n if (!existing || typeof existing !== 'object' || Array.isArray(existing)) {\n const envelope: RedoEnvelope = { __redoInput: input }\n if (existing !== undefined) envelope.value = existing\n return envelope\n }\n const current = existing as Record<string, unknown>\n if ('__redoInput' in current && current.__redoInput !== undefined) {\n return current as RedoEnvelope\n }\n return { __redoInput: input, ...current }\n}\n"],
5
+ "mappings": "AAEA,SAAS,uBAAuB;AAWhC,SAAS,wBAAwB;AAGjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,+BAA+B;AACxC,SAAS,yCAAyC;AAClD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,+BAA+B;AACxC,SAAS,wCAAwC;AACjD,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB;AAChC,SAAS,kCAAkC;AAC3C,SAAS,2BAA2B;AAEpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAEP,MAAM,SAAS,aAAa,QAAQ,EAAE,MAAM,EAAE,WAAW,WAAW,CAAC;AAiBrE,SAAS,gBAAgB,IAA4B;AACnD,QAAM,QAAS,GAA2C;AAC1D,SAAO,OAAO,UAAU,cAAc,MAAM,KAAK,EAAE;AACrD;AAEA,SAAS,+BAA+B,KAAqD;AAC3F,QAAM,KAAK,IAAI,mBAAoB,IAAI,UAAU,QAAQ,IAAI;AAC7D,QAAM,eAAe,gBAAgB,EAAE;AACvC,MAAI,gBAAgB,CAAC,wBAAwB,IAAI,IAAI,mBAAmB,GAAG;AACzE,UAAM,IAAI,MAAM,gFAAgF;AAAA,EAClG;AACA,SAAO,EAAE,IAAI,aAAa;AAC5B;AAEA,SAAS,6BACP,KACA,IACA,kBACuB;AACvB,QAAM,sBAAsB,uBAAuB,EAAE;AACrD,MAAI,CAAC,uBAAwB,oBAAoB,wBAAwB,kBAAmB;AAC1F,UAAM,IAAI,MAAM,2EAA2E;AAAA,EAC7F;AACA,SAAO,EAAE,GAAG,KAAK,iBAAiB,IAAI,oBAAoB;AAC5D;AAEA,MAAM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4BAA4B,IAAI,SAAS;AACzD,UAAI,QAAS,UAAS,IAAI,OAAO;AACjC,YAAM,cAAc,MAAM,KAAK,QAAQ;AACvC,YAAM;AAAA,QACJ,IAAI;AAAA,QACJ;AAAA,QACA,EAAE,IAAI,UAAU,gBAAgB,SAAS;AAAA,QACzC;AAAA,QACA,WAAW,IAAI,SAAS;AAAA,QACxB;AAAA,MACF;AAAA,IACF,SAAS,KAAK;AACZ,UAAI,wBAAwB,GAAG;AAC7B,YAAI;AACF,iBAAO,MAAM,kCAAkC,EAAE,WAAW,IAAI,WAAW,IAAI,CAAC;AAAA,QAClF,QAAQ;AAAA,QAAC;AAAA,MACX;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAc,qBAAqB,WAA4B,UAAiD;AAC9G,QAAI;AACF,YAAM,aAAc,UAAU,QAAQ,YAAY;AAClD,YAAM,WAAW,sBAAsB,QAAQ;AAAA,IACjD,SAAS,OAAO;AACd,UAAI,iCAAiC,GAAG;AACtC,cAAM;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACF;AAOA,SAAS,gBAAgB,UAAmB,OAA8B;AACxE,MAAI,CAAC,YAAY,OAAO,aAAa,YAAY,MAAM,QAAQ,QAAQ,GAAG;AACxE,UAAM,WAAyB,EAAE,aAAa,MAAM;AACpD,QAAI,aAAa,OAAW,UAAS,QAAQ;AAC7C,WAAO;AAAA,EACT;AACA,QAAM,UAAU;AAChB,MAAI,iBAAiB,WAAW,QAAQ,gBAAgB,QAAW;AACjE,WAAO;AAAA,EACT;AACA,SAAO,EAAE,aAAa,OAAO,GAAG,QAAQ;AAC1C;",
6
6
  "names": ["result", "mergedMeta", "logEntry"]
7
7
  }
@@ -17,14 +17,17 @@ import {
17
17
  import {
18
18
  runCrudCommandWrite
19
19
  } from "./runCrudCommandWrite.js";
20
+ import { withAuditCorrelation, getAmbientAuditCorrelation } from "./auditCorrelationScope.js";
20
21
  export {
21
22
  CommandBus,
22
23
  CommandInterceptorError,
24
+ getAmbientAuditCorrelation,
23
25
  getCommandInterceptorHttpRejection,
24
26
  getTransactionLifetime,
25
27
  isCommandInterceptorError,
26
28
  onTransactionLifetimeComplete,
27
29
  ownsTransactionLifetime,
28
- runCrudCommandWrite
30
+ runCrudCommandWrite,
31
+ withAuditCorrelation
29
32
  };
30
33
  //# sourceMappingURL=index.js.map