@classytic/arc 2.23.0 → 2.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.md +2 -0
  2. package/dist/{BaseController-BQ8KNvWC.mjs → BaseController-B65zbz9m.mjs} +94 -23
  3. package/dist/QueryCache-DOMT_iq7.d.mts +72 -0
  4. package/dist/actionPermissions-CAphcmUG.mjs +24 -0
  5. package/dist/{applyPermissionResult-Tw4iXtlf.mjs → applyPermissionResult-BnyVE9eD.mjs} +10 -0
  6. package/dist/audit/index.d.mts +32 -3
  7. package/dist/audit/index.mjs +7 -4
  8. package/dist/auth/index.d.mts +2 -2
  9. package/dist/auth/index.mjs +263 -259
  10. package/dist/{buildHandler-D_2ULWxZ.mjs → buildHandler-Dtwd8fdz.mjs} +1 -1
  11. package/dist/cache/index.d.mts +41 -3
  12. package/dist/cache/index.mjs +33 -4
  13. package/dist/cleanup/index.d.mts +313 -0
  14. package/dist/cleanup/index.mjs +1267 -0
  15. package/dist/cli/commands/describe.d.mts +1 -1
  16. package/dist/cli/commands/docs.mjs +1 -1
  17. package/dist/cli/commands/generate.mjs +1 -1
  18. package/dist/cli/commands/init.mjs +1 -1
  19. package/dist/cli/index.mjs +2 -2
  20. package/dist/context/index.mjs +2 -64
  21. package/dist/core/index.d.mts +3 -3
  22. package/dist/core/index.mjs +5 -4
  23. package/dist/core-BGa8TXJR.mjs +221 -0
  24. package/dist/{createActionRouter-BuOv-m4Y.mjs → createActionRouter-C-N7z2EL.mjs} +3 -2
  25. package/dist/{createAggregationRouter-CgJv_BU_.mjs → createAggregationRouter-wzwFa_dW.mjs} +3 -3
  26. package/dist/{createApp-CjOeWJ9_.mjs → createApp-Du5G54TM.mjs} +187 -96
  27. package/dist/{core-DQ6rDTyH.mjs → defineResource-2zvVVpxg.mjs} +297 -230
  28. package/dist/docs/index.d.mts +1 -1
  29. package/dist/docs/index.mjs +2 -2
  30. package/dist/{elevation-COpYKt2h.mjs → elevation-CIz1GjGm.mjs} +4 -3
  31. package/dist/{eventPlugin-A6EbthXR.d.mts → eventPlugin-Bg3cP2_u.d.mts} +38 -3
  32. package/dist/{eventPlugin-DJG2D7sy.mjs → eventPlugin-DrQ_FesK.mjs} +22 -4
  33. package/dist/events/index.d.mts +83 -314
  34. package/dist/events/index.mjs +183 -95
  35. package/dist/events/transports/redis-stream-entry.d.mts +1 -1
  36. package/dist/events/transports/redis-stream-entry.mjs +24 -2
  37. package/dist/factory/index.d.mts +5 -5
  38. package/dist/factory/index.mjs +30 -8
  39. package/dist/{fastify-augmentation-g_f9omSc.d.mts → fastify-augmentation-OzYGIiU1.d.mts} +26 -2
  40. package/dist/{generate-usRSdQmP.mjs → generate-D0wZupBg.mjs} +1 -1
  41. package/dist/headers-BvlQSDMB.mjs +45 -0
  42. package/dist/health-CB_m4S32.mjs +377 -0
  43. package/dist/hooks/index.d.mts +1 -1
  44. package/dist/idempotency/index.mjs +27 -3
  45. package/dist/{index-wMoWBLkn.d.mts → index-BMnbzvtO.d.mts} +3 -3
  46. package/dist/{integrations/jobs.d.mts → index-CG4yqMDB.d.mts} +82 -2
  47. package/dist/index-CZY4EGga.d.mts +107 -0
  48. package/dist/{index-CC5ruDGh.d.mts → index-CjVg-Epg.d.mts} +37 -5
  49. package/dist/{index-BBsvQt7U.d.mts → index-DPRH0Cme.d.mts} +36 -106
  50. package/dist/index.d.mts +6 -6
  51. package/dist/index.mjs +7 -6
  52. package/dist/{init-CjO4p_q1.mjs → init-tlRSt667.mjs} +206 -208
  53. package/dist/integrations/event-gateway.d.mts +1 -1
  54. package/dist/integrations/event-gateway.mjs +1 -1
  55. package/dist/integrations/index.d.mts +3 -3
  56. package/dist/integrations/jobs/index.d.mts +2 -0
  57. package/dist/integrations/{jobs.mjs → jobs/index.mjs} +110 -67
  58. package/dist/integrations/mcp/index.d.mts +4 -4
  59. package/dist/integrations/mcp/index.mjs +2 -2
  60. package/dist/integrations/mcp/testing.d.mts +1 -1
  61. package/dist/integrations/mcp/testing.mjs +1 -1
  62. package/dist/integrations/webhooks.d.mts +37 -30
  63. package/dist/integrations/webhooks.mjs +51 -62
  64. package/dist/integrations/websocket-redis.d.mts +1 -1
  65. package/dist/integrations/websocket.d.mts +1 -1
  66. package/dist/integrations/websocket.mjs +41 -14
  67. package/dist/{interface-C1_WLTMK.d.mts → interface-BGZCzOGL.d.mts} +24 -31
  68. package/dist/{mcpPlugin-BtzIL_kM.mjs → mcpPlugin-Cs6nRGCt.mjs} +12 -10
  69. package/dist/{memory-CLXA2VeJ.mjs → memory-CmnzXE5Z.mjs} +29 -0
  70. package/dist/middleware/index.d.mts +17 -1
  71. package/dist/middleware/index.mjs +1 -1
  72. package/dist/migrations/index.d.mts +94 -44
  73. package/dist/migrations/index.mjs +196 -44
  74. package/dist/module-_-M7C5ES.mjs +29 -0
  75. package/dist/{multipartBody-CHEQSZ6G.mjs → multipartBody-D0eBvkeq.mjs} +17 -0
  76. package/dist/{openapi-jSDx-VDv.mjs → openapi-BLV4OMXb.mjs} +3 -3
  77. package/dist/permissions/index.d.mts +2 -2
  78. package/dist/permissions/index.mjs +3 -3
  79. package/dist/{permissions-tbxFHxjZ.mjs → permissions-BrtiBKGs.mjs} +229 -229
  80. package/dist/pipeline/index.d.mts +1 -1
  81. package/dist/{actionPermissions-lszoJle1.mjs → pipeline-BGRnV-To.mjs} +4 -27
  82. package/dist/plugins/index.d.mts +6 -77
  83. package/dist/plugins/index.mjs +11 -95
  84. package/dist/plugins/response-cache.mjs +1 -0
  85. package/dist/plugins/tracing-entry.mjs +1 -1
  86. package/dist/{index-Ba10fdKp.d.mts → preloadResources-CM4uUaFv.d.mts} +51 -50
  87. package/dist/preloadResources-DSY5HGpS.mjs +45 -0
  88. package/dist/presets/filesUpload.d.mts +3 -3
  89. package/dist/presets/filesUpload.mjs +3 -3
  90. package/dist/presets/index.d.mts +2 -1
  91. package/dist/presets/index.mjs +1 -1
  92. package/dist/presets/multiTenant.d.mts +1 -1
  93. package/dist/presets/multiTenant.mjs +1 -1
  94. package/dist/presets/search.d.mts +2 -2
  95. package/dist/presets/search.mjs +1 -1
  96. package/dist/{presets-BOe4Ugkl.mjs → presets-DwFDVKP0.mjs} +2 -2
  97. package/dist/{queryCachePlugin-DzqLN904.mjs → queryCachePlugin-DSGuSVLW.mjs} +39 -8
  98. package/dist/{queryCachePlugin-CfYWq-Ak.d.mts → queryCachePlugin-br4otiqF.d.mts} +2 -2
  99. package/dist/{registerRoute-CWO6mdYe.mjs → rateLimit-DrED-C4v.mjs} +2 -109
  100. package/dist/{realtime-I8OrfnMR.mjs → realtime-DEuDu9io.mjs} +3 -3
  101. package/dist/{redis-stream-iVR2l7aS.d.mts → redis-stream-uIaauNpZ.d.mts} +22 -0
  102. package/dist/registerRoute-DTp18Ah_.mjs +108 -0
  103. package/dist/registry/index.d.mts +2 -2
  104. package/dist/registry/index.mjs +1 -1
  105. package/dist/{registry-vcOCtPij.mjs → registry-9km_w1aP.mjs} +15 -0
  106. package/dist/renewingLease-3cuQH7h8.mjs +44 -0
  107. package/dist/{requestContext-BZKOr13H.mjs → requestContext-MrlJwECf.mjs} +2 -2
  108. package/dist/schedules-CjOd2MG9.mjs +113 -0
  109. package/dist/schemas/index.d.mts +67 -67
  110. package/dist/schemas/index.mjs +2 -3
  111. package/dist/scim/index.mjs +1 -2
  112. package/dist/scope/index.d.mts +2 -2
  113. package/dist/scope/index.mjs +4 -4
  114. package/dist/{scope-LONQ3mfZ.mjs → scope-DfaPntpo.mjs} +4 -5
  115. package/dist/{sse-0u4P4-OI.mjs → sse-BQ1w0dfl.mjs} +1 -1
  116. package/dist/testing/cleanupStoreContract.d.mts +10 -0
  117. package/dist/testing/cleanupStoreContract.mjs +375 -0
  118. package/dist/testing/index.d.mts +5 -3
  119. package/dist/testing/index.mjs +4 -2
  120. package/dist/testing/outboxStoreContract.d.mts +13 -0
  121. package/dist/testing/outboxStoreContract.mjs +247 -0
  122. package/dist/transactionContext-PNdoyLLm.mjs +64 -0
  123. package/dist/types/index.d.mts +4 -4
  124. package/dist/{types-bHblZ9YN.mjs → types-CSyCxl2V.mjs} +38 -7
  125. package/dist/types-C_ZZRcD6.d.mts +450 -0
  126. package/dist/{module-B4u10iOJ.d.mts → types-Cu6vVJmh.d.mts} +196 -60
  127. package/dist/{types-DH0GupI7.d.mts → types-DjC-KUCz.d.mts} +118 -20
  128. package/dist/{types-Csxga7d3.d.mts → types-Dmw-6Qeo.d.mts} +96 -4
  129. package/dist/{types-5OuqeTDX.d.mts → types-QFGc3Cjv.d.mts} +1 -1
  130. package/dist/usage/index.d.mts +3 -52
  131. package/dist/usage/index.mjs +0 -0
  132. package/dist/userHelpers-Cg_y3fBz.mjs +29 -0
  133. package/dist/utils/index.d.mts +58 -85
  134. package/dist/utils/index.mjs +4 -2
  135. package/dist/{utils-CZyeRXTh.mjs → utils-taUVD4p3.mjs} +47 -337
  136. package/dist/{validate-C2mGgSXg.mjs → validate-Bk44F2yT.mjs} +1 -1
  137. package/dist/{versioning-D6PvCwpq.d.mts → versioning-DXgY5BUm.d.mts} +11 -29
  138. package/dist/{versioning-Dk-71iIz.mjs → versioning-gKWyryT3.mjs} +8 -1
  139. package/dist/{websocket-uuWqM6UY.d.mts → websocket-_Pd0CgR0.d.mts} +15 -1
  140. package/package.json +541 -513
  141. package/skills/arc/references/api-reference.md +3 -1
  142. package/skills/arc/references/integrations.md +20 -11
  143. package/dist/QueryCache-Z1B38koh.d.mts +0 -40
  144. package/dist/betterAuthOpenApi-CV1lxpRX.mjs +0 -2
  145. package/dist/health-ScyjIVo5.mjs +0 -202
  146. package/dist/requestId-5BhTVzBv.mjs +0 -113
  147. package/dist/types-XTApa8b6.mjs +0 -24
@@ -0,0 +1,64 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ //#region src/context/transactionContext.ts
3
+ /**
4
+ * Transaction Context via AsyncLocalStorage
5
+ *
6
+ * Provides a Unit-of-Work (UoW) hook so any code in the call stack can
7
+ * retrieve the active database session/transaction without it being threaded
8
+ * through every function parameter.
9
+ *
10
+ * Arc is DB-agnostic — the session type is `unknown` so any backend
11
+ * (Mongoose session, Prisma transaction, pg client, Drizzle client) can
12
+ * participate. Kit adapters call `runInTransaction(session, fn)` to install
13
+ * the active context; the outbox's `store()` reads it automatically when no
14
+ * explicit `options.session` is passed.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * // In a Mongoose-backed service (mongokit adapter)
19
+ * import { transactionContext } from '@classytic/arc/context';
20
+ *
21
+ * await mongoose.connection.withSession(async (session) => {
22
+ * await session.withTransaction(async () => {
23
+ * await transactionContext.run(session, async () => {
24
+ * await orders.insertOne(order, { session });
25
+ * // outbox.store() auto-picks up `session` — no manual threading
26
+ * await outbox.store(orderCreatedEvent);
27
+ * });
28
+ * });
29
+ * });
30
+ * ```
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * // Opt-out: explicit session always wins over the ALS context
35
+ * await outbox.store(event, { session: explicitSession });
36
+ * ```
37
+ */
38
+ const storage = new AsyncLocalStorage();
39
+ /**
40
+ * Transaction context API.
41
+ *
42
+ * - `run(session, fn)` — install an active DB session for the duration of `fn`
43
+ * - `get()` — read the current session (undefined if outside a transaction scope)
44
+ */
45
+ const transactionContext = {
46
+ /**
47
+ * Run `fn` with `session` as the active DB transaction context.
48
+ * Any call to `get()` within `fn`'s async call stack returns `session`.
49
+ */
50
+ run(session, fn) {
51
+ return storage.run(session, fn);
52
+ },
53
+ /**
54
+ * Get the current DB session, or `undefined` if not inside a
55
+ * `transactionContext.run(...)` scope.
56
+ */
57
+ get() {
58
+ return storage.getStore();
59
+ },
60
+ /** The underlying AsyncLocalStorage instance. Exposed for advanced integrations. */
61
+ storage
62
+ };
63
+ //#endregion
64
+ export { transactionContext as t };
@@ -1,5 +1,5 @@
1
- import { $ as OpenApiSchemas, $t as UserLike, A as RequestIdOptions, At as RouteDefinition, Bt as RouteHandler, C as RequestContext, D as HealthCheck, Dt as ActionEntry, E as GracefulShutdownOptions, Et as ActionDefinition, F as FastifyWithDecorators, Ft as ControllerLike, G as OnTenantDeleteConfig, Gt as AuthenticatorContext, H as CrudController, Ht as AuthHelpers, I as MiddlewareHandler, In as BaseControllerOptions, It as FastifyHandler, J as PresetHook, Jt as AnyRecord, K as ResolvedTenantPurge, Kt as JwtContext, L as RequestWithExtras, Lt as IController, M as EventsDecorator, Mt as RouteMethod, N as FastifyRequestExtras, Nt as RateLimitConfig, O as HealthOptions, Ot as ActionHandlerFn, P as FastifyWithAuth, Pt as ControllerHandler, Q as MiddlewareConfig, Qt as ObjectId, Rt as IControllerResponse, S as QueryParserInterface, T as CrudRouterOptions, Tt as ResourceCacheConfig, U as ResourceConfig, Ut as AuthPluginOptions, W as ResourcePermissions, Wt as Authenticator, X as CrudRouteKey, Xt as ArcRequest, Y as PresetResult, Yt as ApiResponse, Z as CrudSchemas, Zt as JWTPayload, _ as ControllerQueryOptions, a as InferAdapterDoc, at as ResourceExtensions, b as ParsedQuery, c as TypedController, d as PaginationResult, en as UserOrganization, et as RouteSchemaOptions, f as IntrospectionData, g as ArcInternalMetadata, h as ResourceMetadata, i as ValidationResult, it as ResourceHooks, j as ArcDecorator, jt as RouteMcpConfig, k as IntrospectionPluginOptions, kt as ActionsMap, l as TypedRepository, m as RegistryStats, n as ConfigError, nt as FieldRule, o as InferDocType, ot as EventDefinition, p as RegistryEntry, q as PresetFunction, qt as TokenPair, r as ValidateOptions, rt as ResourceHookContext, s as InferResourceDoc, t as RouteHandlerMethod, tt as ArcFieldRule, u as TypedResourceConfig, v as LookupOption, w as ServiceContext, x as PopulateOption, y as OwnershipCheck, zt as IRequestContext } from "../index-BBsvQt7U.mjs";
2
- import { i as RequestScope } from "../types-DH0GupI7.mjs";
3
- import { i as UserBase, n as PermissionContext, r as PermissionResult, t as PermissionCheck } from "../types-Csxga7d3.mjs";
1
+ import { $ as OpenApiSchemas, A as RequestIdOptions, At as RouteDefinition, Bt as RouteHandler, C as RequestContext, D as HealthCheck, Dt as ActionEntry, E as GracefulShutdownOptions, Et as ActionDefinition, F as FastifyWithDecorators, Ft as ControllerLike, G as OnTenantDeleteConfig, Gt as AuthenticatorContext, H as CrudController, Ht as AuthHelpers, I as MiddlewareHandler, It as FastifyHandler, J as PresetHook, K as ResolvedTenantPurge, Kt as JwtContext, L as RequestWithExtras, Lt as IController, M as EventsDecorator, Mt as RouteMethod, N as FastifyRequestExtras, Nt as RateLimitConfig, O as HealthOptions, Ot as ActionHandlerFn, P as FastifyWithAuth, Pt as ControllerHandler, Q as MiddlewareConfig, Rt as IControllerResponse, S as QueryParserInterface, T as CrudRouterOptions, Tt as ResourceCacheConfig, U as ResourceConfig, Ut as AuthPluginOptions, W as ResourcePermissions, Wt as Authenticator, X as CrudRouteKey, Y as PresetResult, Z as CrudSchemas, _ as ControllerQueryOptions, a as InferAdapterDoc, at as ResourceExtensions, b as ParsedQuery, c as TypedController, d as PaginationResult, et as RouteSchemaOptions, f as IntrospectionData, g as ArcInternalMetadata, h as ResourceMetadata, i as ValidationResult, it as ResourceHooks, j as ArcDecorator, jt as RouteMcpConfig, k as IntrospectionPluginOptions, kn as BaseControllerOptions, kt as ActionsMap, l as TypedRepository, m as RegistryStats, n as ConfigError, nt as FieldRule, o as InferDocType, ot as EventDefinition, p as RegistryEntry, q as PresetFunction, qt as TokenPair, r as ValidateOptions, rt as ResourceHookContext, s as InferResourceDoc, t as RouteHandlerMethod, tt as ArcFieldRule, u as TypedResourceConfig, v as LookupOption, w as ServiceContext, x as PopulateOption, y as OwnershipCheck, zt as IRequestContext } from "../index-DPRH0Cme.mjs";
2
+ import { i as RequestScope } from "../types-DjC-KUCz.mjs";
3
+ import { c as AnyRecord, d as ObjectId, f as UserLike, i as UserBase, l as ArcRequest, n as PermissionContext, p as UserOrganization, r as PermissionResult, t as PermissionCheck, u as JWTPayload } from "../types-Dmw-6Qeo.mjs";
4
4
  import { n as ElevationOptions, t as ElevationEvent } from "../elevation-C9s5hFP_.mjs";
5
- export type { ActionDefinition, ActionEntry, ActionHandlerFn, ActionsMap, AnyRecord, ApiResponse, ArcDecorator, ArcFieldRule, ArcInternalMetadata, ArcRequest, AuthHelpers, AuthPluginOptions, Authenticator, AuthenticatorContext, BaseControllerOptions, ConfigError, ControllerHandler, ControllerLike, ControllerQueryOptions, CrudController, CrudRouteKey, CrudRouterOptions, CrudSchemas, ElevationEvent, ElevationOptions, EventDefinition, EventsDecorator, FastifyHandler, FastifyRequestExtras, FastifyWithAuth, FastifyWithDecorators, FieldRule, GracefulShutdownOptions, HealthCheck, HealthOptions, IController, IControllerResponse, IRequestContext, InferAdapterDoc, InferDocType, InferResourceDoc, IntrospectionData, IntrospectionPluginOptions, JWTPayload, JwtContext, LookupOption, MiddlewareConfig, MiddlewareHandler, ObjectId, OnTenantDeleteConfig, OpenApiSchemas, OwnershipCheck, PaginationResult, ParsedQuery, PermissionCheck, PermissionContext, PermissionResult, PopulateOption, PresetFunction, PresetHook, PresetResult, QueryParserInterface, RateLimitConfig, RegistryEntry, RegistryStats, RequestContext, RequestIdOptions, RequestScope, RequestWithExtras, ResolvedTenantPurge, ResourceCacheConfig, ResourceConfig, ResourceExtensions, ResourceHookContext, ResourceHooks, ResourceMetadata, ResourcePermissions, RouteDefinition, RouteHandler, RouteHandlerMethod, RouteMcpConfig, RouteMethod, RouteSchemaOptions, ServiceContext, TokenPair, TypedController, TypedRepository, TypedResourceConfig, UserBase, UserLike, UserOrganization, ValidateOptions, ValidationResult };
5
+ export type { ActionDefinition, ActionEntry, ActionHandlerFn, ActionsMap, AnyRecord, ArcDecorator, ArcFieldRule, ArcInternalMetadata, ArcRequest, AuthHelpers, AuthPluginOptions, Authenticator, AuthenticatorContext, BaseControllerOptions, ConfigError, ControllerHandler, ControllerLike, ControllerQueryOptions, CrudController, CrudRouteKey, CrudRouterOptions, CrudSchemas, ElevationEvent, ElevationOptions, EventDefinition, EventsDecorator, FastifyHandler, FastifyRequestExtras, FastifyWithAuth, FastifyWithDecorators, FieldRule, GracefulShutdownOptions, HealthCheck, HealthOptions, IController, IControllerResponse, IRequestContext, InferAdapterDoc, InferDocType, InferResourceDoc, IntrospectionData, IntrospectionPluginOptions, JWTPayload, JwtContext, LookupOption, MiddlewareConfig, MiddlewareHandler, ObjectId, OnTenantDeleteConfig, OpenApiSchemas, OwnershipCheck, PaginationResult, ParsedQuery, PermissionCheck, PermissionContext, PermissionResult, PopulateOption, PresetFunction, PresetHook, PresetResult, QueryParserInterface, RateLimitConfig, RegistryEntry, RegistryStats, RequestContext, RequestIdOptions, RequestScope, RequestWithExtras, ResolvedTenantPurge, ResourceCacheConfig, ResourceConfig, ResourceExtensions, ResourceHookContext, ResourceHooks, ResourceMetadata, ResourcePermissions, RouteDefinition, RouteHandler, RouteHandlerMethod, RouteMcpConfig, RouteMethod, RouteSchemaOptions, ServiceContext, TokenPair, TypedController, TypedRepository, TypedResourceConfig, UserBase, UserLike, UserOrganization, ValidateOptions, ValidationResult };
@@ -1,4 +1,6 @@
1
1
  import { l as UnauthorizedError, o as OrgRequiredError } from "./errors-DkO8Nk6-.mjs";
2
+ import { n as requireSingleHeaderValue } from "./headers-BvlQSDMB.mjs";
3
+ import { t as getUserId$1 } from "./userHelpers-Cg_y3fBz.mjs";
2
4
  //#region src/scope/types.ts
3
5
  /**
4
6
  * Request Scope — The One Standard
@@ -87,8 +89,7 @@ function getTenantFromRequest(req, options = {}) {
87
89
  };
88
90
  }
89
91
  const headerName = (options.header ?? "x-organization-id").toLowerCase();
90
- const raw = req.headers[headerName];
91
- const headerValue = Array.isArray(raw) ? raw[0] : raw;
92
+ const headerValue = requireSingleHeaderValue(req.headers, headerName);
92
93
  if (typeof headerValue === "string" && headerValue.length > 0) return {
93
94
  organizationId: headerValue,
94
95
  source: "header"
@@ -259,8 +260,13 @@ function isOrgInScope(scope, targetOrgId) {
259
260
  * ```
260
261
  */
261
262
  function getUserId(scope) {
262
- if (scope.kind === "public") return void 0;
263
- return scope.userId;
263
+ switch (scope.kind) {
264
+ case "authenticated":
265
+ case "member":
266
+ case "elevated": return scope.userId;
267
+ case "public":
268
+ case "service": return;
269
+ }
264
270
  }
265
271
  /**
266
272
  * Throwing variant of `getOrgId`. Returns the organization id when the
@@ -356,9 +362,12 @@ function getUserRoles(scope) {
356
362
  */
357
363
  function getOrgContext(request) {
358
364
  const scope = request.scope ?? { kind: "public" };
365
+ const requestedOrgId = requireSingleHeaderValue(request.headers, "x-organization-id");
366
+ const rawOrganizationId = request.user?.organizationId;
367
+ const userOrganizationId = rawOrganizationId === void 0 || rawOrganizationId === null ? void 0 : String(rawOrganizationId) || void 0;
359
368
  return {
360
- userId: getUserId(scope) ?? request.user?.id ?? request.user?._id,
361
- organizationId: getOrgId(scope) ?? request.user?.organizationId ?? request.headers?.["x-organization-id"],
369
+ userId: getUserId(scope) ?? getUserId$1(request.user),
370
+ organizationId: getOrgId(scope) ?? userOrganizationId ?? requestedOrgId,
362
371
  roles: getUserRoles(scope),
363
372
  orgRoles: getOrgRoles(scope)
364
373
  };
@@ -389,9 +398,31 @@ function getOrgContext(request) {
389
398
  function getRequestScope(request) {
390
399
  return request.scope ?? PUBLIC_SCOPE;
391
400
  }
401
+ function scopeFirstCtx(req, options = {}) {
402
+ let actorId;
403
+ let organizationId;
404
+ const s = req.scope;
405
+ if (s && "kind" in s) {
406
+ actorId = getUserId(s) ?? getClientId(s);
407
+ organizationId = getOrgId(s);
408
+ } else if (s) {
409
+ actorId = s.userId;
410
+ organizationId = s.organizationId;
411
+ }
412
+ actorId = actorId ?? options.fallbackActorId;
413
+ if (!organizationId && options.orgHeader !== false && req.headers) {
414
+ const headerName = (options.orgHeader ?? "x-organization-id").toLowerCase();
415
+ const headerValue = requireSingleHeaderValue(req.headers, headerName);
416
+ if (typeof headerValue === "string" && headerValue.length > 0) organizationId = headerValue;
417
+ }
418
+ return {
419
+ ...actorId !== void 0 ? { actorId } : {},
420
+ ...organizationId !== void 0 ? { organizationId } : {}
421
+ };
422
+ }
392
423
  /** Default public scope — used as initial decoration value */
393
424
  const PUBLIC_SCOPE = Object.freeze({ kind: "public" });
394
425
  /** Default authenticated scope — used when user is logged in but no org */
395
426
  const AUTHENTICATED_SCOPE = Object.freeze({ kind: "authenticated" });
396
427
  //#endregion
397
- export { isService as C, requireUserId as D, requireTeamId as E, isOrgInScope as S, requireOrgId as T, getUserRoles as _, getDPoPJkt as a, isElevated as b, getOrgId as c, getScopeContext as d, getScopeContextMap as f, getUserId as g, getTenantFromRequest as h, getClientId as i, getOrgRoles as l, getTeamId as m, PUBLIC_SCOPE as n, getMandate as o, getServiceScopes as p, getAncestorOrgIds as r, getOrgContext as s, AUTHENTICATED_SCOPE as t, getRequestScope as u, hasOrgAccess as v, requireClientId as w, isMember as x, isAuthenticated as y };
428
+ export { isService as C, requireUserId as D, requireTeamId as E, scopeFirstCtx as O, isOrgInScope as S, requireOrgId as T, getUserRoles as _, getDPoPJkt as a, isElevated as b, getOrgId as c, getScopeContext as d, getScopeContextMap as f, getUserId as g, getTenantFromRequest as h, getClientId as i, getOrgRoles as l, getTeamId as m, PUBLIC_SCOPE as n, getMandate as o, getServiceScopes as p, getAncestorOrgIds as r, getOrgContext as s, AUTHENTICATED_SCOPE as t, getRequestScope as u, hasOrgAccess as v, requireClientId as w, isMember as x, isAuthenticated as y };
@@ -0,0 +1,450 @@
1
+ import { PurgeActor, PurgeEvidence, PurgeResourceResult, PurgeStrategyKind as PurgeStrategyKind$1, PurgeVerificationSummary } from "@classytic/primitives/retention";
2
+ //#region src/cleanup/types.d.ts
3
+ /** Ambient context every recipe method receives. Host-injected — never global. */
4
+ interface CleanupContext {
5
+ /** Who requested the operation. */
6
+ readonly actor: PurgeActor;
7
+ /** Injected clock — recipes never call `new Date()` directly (testability). */
8
+ readonly now: Date;
9
+ /** Cooperative cancellation — checked between chunks/steps. */
10
+ readonly signal?: AbortSignal | undefined;
11
+ /** Optional structured logger. */
12
+ readonly logger?: CleanupLogger | undefined;
13
+ /**
14
+ * Opaque host-provided ambient values (e.g. the resolved company/branch
15
+ * scope). MUST be JSON-serializable — it is persisted on the run so a worker
16
+ * (different process) can rebuild the exact operation context. Recipes read
17
+ * what they declared they need; the framework never inspects it.
18
+ */
19
+ readonly ambient?: Readonly<Record<string, unknown>> | undefined;
20
+ }
21
+ interface CleanupLogger {
22
+ info(msg: string, meta?: Record<string, unknown>): void;
23
+ warn(msg: string, meta?: Record<string, unknown>): void;
24
+ error(msg: string, meta?: Record<string, unknown>): void;
25
+ }
26
+ /**
27
+ * Execution-time context — adds progress reporting + the run/operation ids +
28
+ * cooperative cancellation.
29
+ */
30
+ interface CleanupExecutionContext extends CleanupContext {
31
+ /** Durable run id this execution belongs to. */
32
+ readonly runId: string;
33
+ /** Stable operation id threaded through logs, audit, and evidence. */
34
+ readonly operationId: string;
35
+ /**
36
+ * Report one committed chunk. Updates the run's BOUNDED progress summary
37
+ * (counts / current resource / cursor / heartbeat) — it does NOT retain
38
+ * every step in memory. Also refreshes the cancellation view: after a chunk
39
+ * commits, call this so the executor learns of a cancel request promptly.
40
+ */
41
+ onStep(step: CleanupStepResult): Promise<void>;
42
+ /**
43
+ * Throw `CleanupCancelled` if a cancel has been requested for this run. Cheap
44
+ * to call between chunks; backed by the durable `cancelRequested` flag (the
45
+ * source of truth) plus the in-process `signal`.
46
+ */
47
+ throwIfCancelled(): Promise<void>;
48
+ }
49
+ /** Whether a recipe may run right now, and why not. */
50
+ interface Availability {
51
+ readonly available: boolean;
52
+ /** Required when `available` is false — surfaced to the operator. */
53
+ readonly reason?: string | undefined;
54
+ }
55
+ /** Operator-supplied recipe parameters (branch, module set, before-date, …). */
56
+ interface CleanupInput {
57
+ readonly parameters?: Readonly<Record<string, unknown>> | undefined;
58
+ }
59
+ /** One logical line in the preview — a business record class, never a collection. */
60
+ interface CleanupPlanItem {
61
+ /** Logical module / resource label, e.g. `'orders'`, `'journal entries'`. */
62
+ readonly resource: string;
63
+ /** Estimated records affected. */
64
+ readonly estimated: number;
65
+ /** What is retained for this line (e.g. `'measures kept, PII redacted'`). */
66
+ readonly retained?: string | undefined;
67
+ /** Domain blockers preventing this line (e.g. `'OPEN_TRANSFER'`). */
68
+ readonly blockers?: readonly string[] | undefined;
69
+ }
70
+ /**
71
+ * A recipe's plan BEFORE the framework seals it — the recipe returns this; the
72
+ * service computes {@link CleanupPlan.digest} + stamps {@link CleanupPlan.recipeId}.
73
+ */
74
+ interface CleanupPlanDraft {
75
+ readonly items: readonly CleanupPlanItem[];
76
+ /** Top-level categories the recipe explicitly RETAINS. */
77
+ readonly retains?: readonly string[] | undefined;
78
+ /**
79
+ * Top-level blockers. A NON-EMPTY blockers list is a HARD STOP — the service
80
+ * refuses `execute` with `CLEANUP_BLOCKED`. Preview surfaces them so the
81
+ * operator resolves them (or the recipe stops listing them) before running.
82
+ */
83
+ readonly blockers?: readonly string[] | undefined;
84
+ /** Projection/scaffolding rebuilds the recipe will perform after cleanup. */
85
+ readonly rebuildActions?: readonly string[] | undefined;
86
+ /** Non-blocking warnings for the operator. */
87
+ readonly warnings?: readonly string[] | undefined;
88
+ /**
89
+ * The exact phrase the operator must type to confirm a destructive run.
90
+ * Defaults (in the service) to the recipe id when omitted.
91
+ */
92
+ readonly confirmationPhrase?: string | undefined;
93
+ }
94
+ /** A sealed, digest-stamped plan. The digest makes confirmation tamper-evident. */
95
+ interface CleanupPlan {
96
+ readonly recipeId: string;
97
+ readonly parameters: Readonly<Record<string, unknown>>;
98
+ readonly items: readonly CleanupPlanItem[];
99
+ readonly retains: readonly string[];
100
+ readonly blockers: readonly string[];
101
+ readonly rebuildActions: readonly string[];
102
+ readonly warnings: readonly string[];
103
+ readonly estimatedTotal: number;
104
+ readonly confirmationPhrase: string;
105
+ /** Deterministic checksum of the plan's material content — see `computePlanDigest`. */
106
+ readonly digest: string;
107
+ }
108
+ /** One committed step's outcome — reported via `onStep`, folded into the summary. */
109
+ interface CleanupStepResult {
110
+ readonly resource: string;
111
+ readonly processed: number;
112
+ readonly ok: boolean;
113
+ readonly error?: string | undefined;
114
+ /** Opaque resume cursor the recipe may surface for observability. */
115
+ readonly cursor?: string | undefined;
116
+ readonly startedAt?: Date | undefined;
117
+ readonly completedAt?: Date | undefined;
118
+ }
119
+ /**
120
+ * BOUNDED progress summary persisted on the run (design "Node.js memory"): a
121
+ * fixed-size aggregate, never an unbounded per-chunk array. Detailed steps, if a
122
+ * host wants them, go to a separate capped sink — not this document.
123
+ */
124
+ interface CleanupProgressSummary {
125
+ /** Running total of processed records across all steps. */
126
+ readonly processed: number;
127
+ /** Count of steps reported so far. */
128
+ readonly steps: number;
129
+ /** Resource the last step touched. */
130
+ readonly currentResource?: string | undefined;
131
+ /** Last resume cursor reported. */
132
+ readonly lastCursor?: string | undefined;
133
+ /** When the last step landed — liveness/heartbeat. */
134
+ readonly heartbeatAt?: Date | undefined;
135
+ /** Count of failed steps (a run with any is never a clean success). */
136
+ readonly failed?: number | undefined;
137
+ }
138
+ /** One verification invariant's outcome. */
139
+ interface VerificationCheck {
140
+ readonly name: string;
141
+ readonly ok: boolean;
142
+ readonly detail?: string | undefined;
143
+ }
144
+ /** The recipe's own post-checks — a delete count alone is never success (§9). */
145
+ interface VerificationResult {
146
+ readonly ok: boolean;
147
+ readonly checks: readonly VerificationCheck[];
148
+ }
149
+ type CleanupOutcomeStatus = "completed" | "partial" | "failed" | "cancelled";
150
+ /** What `execute` returns — the per-step results + a terminal status. */
151
+ interface CleanupResult {
152
+ readonly status: Exclude<CleanupOutcomeStatus, "cancelled">;
153
+ readonly results: readonly CleanupStepResult[];
154
+ }
155
+ /**
156
+ * The finalization payload persisted ON the run BEFORE it enters `finalizing`
157
+ * (same CAS patch). This is what makes a `finalizing` crash recoverable
158
+ * WITHOUT re-executing the recipe: a recovering worker replays ONLY
159
+ * `evidenceStore.finalize()` + the terminal CAS from this durable snapshot —
160
+ * never `recipe.execute()` again.
161
+ */
162
+ interface CleanupFinalizationPayload {
163
+ readonly status: CleanupOutcomeStatus;
164
+ readonly results: readonly CleanupStepResult[];
165
+ readonly verification: VerificationResult;
166
+ /** Count of verification checks dropped by `maxChecks` truncation. */
167
+ readonly checksTruncated?: number | undefined;
168
+ readonly failureReason?: string | undefined;
169
+ }
170
+ /**
171
+ * A cleanup recipe — the unit operators choose. Pure provider: the four
172
+ * methods are the only surface arc calls. A recipe delegates the actual
173
+ * domain work to kernel-provided steps; it never runs a raw Mongo cascade.
174
+ */
175
+ interface CleanupRecipe {
176
+ /** Stable machine id, e.g. `'cleanup.pre-live-reset'`. Unique in a registry. */
177
+ readonly id: string;
178
+ /** Plain-language name for the UI. */
179
+ readonly label: string;
180
+ /** Whether this recipe removes data (gates confirmation + single-run fence). */
181
+ readonly destructive: boolean;
182
+ /**
183
+ * Recipe/plan-schema version. Persisted on the run; a retry that finds a
184
+ * different current version requires a fresh preview rather than replaying an
185
+ * incompatible sealed plan. Defaults to `'1'`.
186
+ */
187
+ readonly version?: string;
188
+ /**
189
+ * The purge strategy this recipe's evidence records (`'hard'` deletion,
190
+ * `'soft'` deactivation, `'anonymize'` redaction). Defaults to `'hard'`.
191
+ * A pure projection-rebuild recipe should declare `'soft'` (nothing about the
192
+ * SOURCE data is removed) or, better, the closest honest label — evidence
193
+ * must never overstate destructiveness.
194
+ */
195
+ readonly evidenceStrategy?: PurgeStrategyKind$1;
196
+ /** Whether this recipe may run right now (e.g. pre-go-live only). */
197
+ available(ctx: CleanupContext): Promise<Availability>;
198
+ /** Compute a preview WITHOUT mutating anything. Idempotent + side-effect-free. */
199
+ plan(input: CleanupInput, ctx: CleanupContext): Promise<CleanupPlanDraft>;
200
+ /** Execute the sealed plan. Must be chunked, idempotent, and cancellation-aware. */
201
+ execute(plan: CleanupPlan, ctx: CleanupExecutionContext): Promise<CleanupResult>;
202
+ /** Verify the post-state — the recipe owns what "clean" means. */
203
+ verify(plan: CleanupPlan, ctx: CleanupContext): Promise<VerificationResult>;
204
+ }
205
+ type CleanupRunStatus = "planned" | "queued" | "running" | "finalizing" | "completed" | "failed" | "cancelled";
206
+ /** Terminal states — no further transition is valid. */
207
+ declare const CLEANUP_TERMINAL_STATUSES: readonly CleanupRunStatus[];
208
+ interface CleanupRun {
209
+ readonly id: string;
210
+ readonly recipeId: string;
211
+ readonly recipeVersion: string;
212
+ readonly status: CleanupRunStatus;
213
+ readonly planDigest: string;
214
+ /** The immutable sealed plan — replayed verbatim by the worker / a retry. */
215
+ readonly sealedPlan: CleanupPlan;
216
+ /** The operator-supplied parameters (also inside sealedPlan; kept explicit). */
217
+ readonly parameters: Readonly<Record<string, unknown>>;
218
+ /** The authorizing actor — persisted so a worker attributes the op correctly. */
219
+ readonly actor: PurgeActor;
220
+ /** Serializable ambient scope captured at request time (branch/company). */
221
+ readonly ambient?: Readonly<Record<string, unknown>> | undefined;
222
+ readonly requestedBy: string;
223
+ readonly reason: string;
224
+ readonly operationId: string;
225
+ /**
226
+ * Whether the recipe was destructive at request time — persisted so a
227
+ * GENERIC store can enforce the single-destructive-run policy without
228
+ * consulting the registry (and so non-destructive rebuilds need not
229
+ * serialize behind it).
230
+ */
231
+ readonly destructive: boolean;
232
+ /**
233
+ * Admission-control key the store serializes on (e.g. `'global-destructive'`).
234
+ * Absent for runs that need no mutual exclusion. Hosts may shard it later
235
+ * (`'branch:<id>'`) without an arc change.
236
+ */
237
+ readonly concurrencyKey?: string | undefined;
238
+ /** How many times a worker has claimed this run (1 = first execution). */
239
+ readonly attempt: number;
240
+ /**
241
+ * Exclusive worker lease. A run in `running`/`finalizing` with an UNEXPIRED
242
+ * lease is owned — `claim` refuses it. Progress + status writes carry the
243
+ * token so a stalled ex-owner that wakes past expiry cannot clobber the new
244
+ * owner's writes.
245
+ */
246
+ readonly leaseToken?: string | undefined;
247
+ readonly leaseExpiresAt?: Date | undefined;
248
+ readonly progress: CleanupProgressSummary;
249
+ /** Durable cancellation request — the source of truth the executor polls. */
250
+ readonly cancelRequested: boolean;
251
+ /** Who requested the cancel + why + when (audit — §8, cancel evidence). */
252
+ readonly cancelRequestedBy?: PurgeActor | undefined;
253
+ readonly cancelReason?: string | undefined;
254
+ readonly cancelRequestedAt?: Date | undefined;
255
+ /** Durable finalization snapshot — see {@link CleanupFinalizationPayload}. */
256
+ readonly finalization?: CleanupFinalizationPayload | undefined;
257
+ readonly queuedAt?: Date | undefined;
258
+ readonly startedAt?: Date | undefined;
259
+ readonly completedAt?: Date | undefined;
260
+ readonly failureReason?: string | undefined;
261
+ }
262
+ /** Immutable proof of a completed run (§5) — deterministically checksummed. */
263
+ interface CleanupManifest {
264
+ readonly runId: string;
265
+ readonly recipeId: string;
266
+ readonly recipeVersion: string;
267
+ readonly operationId: string;
268
+ readonly planDigest: string;
269
+ readonly status: CleanupOutcomeStatus;
270
+ readonly actor: PurgeActor;
271
+ readonly reason: string;
272
+ readonly results: readonly CleanupStepResult[];
273
+ readonly verification: VerificationResult;
274
+ /**
275
+ * Count of verification checks DROPPED by the `maxChecks` cap. Present and
276
+ * non-zero whenever `verification.checks` is not the complete set — evidence
277
+ * must say so rather than silently show only the retained checks.
278
+ */
279
+ readonly checksTruncated?: number | undefined;
280
+ readonly completedAt: Date;
281
+ /**
282
+ * Integrity CHECKSUM of the manifest content (not tamper-PROOF: plain SHA-256
283
+ * does not stop an attacker with write access from replacing the record and
284
+ * recomputing the digest — pair with access control / keyed signatures for
285
+ * that). Detects accidental corruption + drift.
286
+ */
287
+ readonly manifestDigest: string;
288
+ }
289
+ type CleanupRunCreateResult = {
290
+ readonly created: true;
291
+ } | {
292
+ readonly created: false;
293
+ readonly activeRunId: string;
294
+ };
295
+ /** Fields a status transition may also patch. */
296
+ interface CleanupRunTransitionPatch {
297
+ readonly queuedAt?: Date;
298
+ readonly startedAt?: Date;
299
+ readonly completedAt?: Date;
300
+ readonly failureReason?: string;
301
+ readonly progress?: CleanupProgressSummary;
302
+ /** Reset the cancellation flag — used when a terminal run is re-armed on retry. */
303
+ readonly cancelRequested?: boolean;
304
+ /** Persist the durable finalization snapshot (set entering `finalizing`). */
305
+ readonly finalization?: CleanupFinalizationPayload;
306
+ }
307
+ /** An exclusive worker lease on a run. */
308
+ interface CleanupLease {
309
+ /** Opaque token identifying THIS worker's ownership of the run. */
310
+ readonly token: string;
311
+ /** When the lease lapses and the run becomes claimable again. */
312
+ readonly expiresAt: Date;
313
+ }
314
+ /** Metadata persisted with a durable cancel request (audit). */
315
+ interface CleanupCancelRequest {
316
+ readonly actor?: PurgeActor | undefined;
317
+ readonly reason?: string | undefined;
318
+ readonly requestedAt: Date;
319
+ }
320
+ /**
321
+ * Durable store for cleanup runs. The host owns persistence (Mongo/SQL/…) AND
322
+ * the atomicity of these operations — the framework's safety rests on them:
323
+ *
324
+ * - `createIfPermitted` MUST be atomic: for a run with a `concurrencyKey` it
325
+ * inserts ONLY if no other run with the same key is in a non-terminal
326
+ * state, backed by a unique partial index / conditional insert / lock. A
327
+ * check-then-create is NOT sufficient. Runs WITHOUT a key are always
328
+ * admitted.
329
+ * - `claim` MUST be atomic and EXCLUSIVE: grant the lease ONLY if the run is
330
+ * `queued`, OR is `running`/`finalizing` with an ABSENT or EXPIRED lease
331
+ * (`leaseExpiresAt <= now`). On grant it sets `leaseToken`/`leaseExpiresAt`,
332
+ * increments `attempt`, and returns the run (status UNCHANGED — the service
333
+ * branches on it: `finalizing` recovers finalization only, never
334
+ * re-executes). A run whose lease is live is OWNED — return `null`.
335
+ * - `compareAndTransition` MUST be a compare-and-set: apply the transition
336
+ * ONLY if the current status is one of `expected` AND, when `leaseToken`
337
+ * is given, the run's current lease token matches. This is the ONLY way
338
+ * status changes — it makes cancel-vs-complete AND stale-ex-owner races
339
+ * safe.
340
+ * - `reArmIfPermitted` MUST apply the same admission policy as
341
+ * `createIfPermitted` atomically with the terminal→`queued` transition
342
+ * (a retry must not slip past the single-destructive-run guard).
343
+ */
344
+ interface CleanupRunStore {
345
+ /** Atomic conditional insert (admission control by `concurrencyKey`, §8). */
346
+ createIfPermitted(run: CleanupRun): Promise<CleanupRunCreateResult>;
347
+ get(id: string): Promise<CleanupRun | null>;
348
+ /**
349
+ * Atomically acquire the exclusive worker lease (see contract above).
350
+ * Returns the claimed run with the lease applied, or `null` if the run is
351
+ * owned, terminal, or missing.
352
+ */
353
+ claim(id: string, lease: CleanupLease): Promise<CleanupRun | null>;
354
+ /**
355
+ * CAS the status: set `status=to` (+ `patch`) ONLY if current status ∈
356
+ * `expected` and (when given) `leaseToken` matches the run's current lease.
357
+ * Returns the updated run, or `null` if the CAS lost the race.
358
+ */
359
+ compareAndTransition(id: string, expected: readonly CleanupRunStatus[], to: CleanupRunStatus, patch?: CleanupRunTransitionPatch, leaseToken?: string): Promise<CleanupRun | null>;
360
+ /**
361
+ * Atomically re-arm a terminal (`failed`/`cancelled`) run back to `queued`
362
+ * under the SAME admission policy as `createIfPermitted` (its
363
+ * `concurrencyKey` must not collide with another non-terminal run). Clears
364
+ * the cancel flag/metadata + lease. Returns `{created:false}`-style refusal
365
+ * via `null` + the blocking run id in the second tuple slot is NOT modeled —
366
+ * a `null` simply means "not permitted or not in a terminal state."
367
+ */
368
+ reArmIfPermitted(id: string, patch: CleanupRunTransitionPatch): Promise<CleanupRun | null>;
369
+ /**
370
+ * Set `cancelRequested = true` (+ audit metadata, idempotent — first request
371
+ * wins). Does NOT change `status`.
372
+ */
373
+ requestCancel(id: string, request?: CleanupCancelRequest): Promise<CleanupRun | null>;
374
+ /**
375
+ * Overwrite the small bounded progress summary (frequent, non-status).
376
+ * When `lease` is given, ALSO extend `leaseExpiresAt` (heartbeat renewal) —
377
+ * and apply ONLY if the run's current lease token matches `lease.token`.
378
+ */
379
+ saveProgress(id: string, progress: CleanupProgressSummary, lease?: CleanupLease): Promise<void>;
380
+ }
381
+ /**
382
+ * Durable store for the evidence + manifest a run leaves behind. `finalize`
383
+ * MUST be idempotent by `evidence.operationId` — a retry / restart that
384
+ * re-finalizes the same operation is a no-op (or an upsert), never a duplicate.
385
+ * Ideally the host writes both in one transaction (with the terminal run
386
+ * transition); the framework tolerates a `finalizing` intermediate + re-run.
387
+ */
388
+ interface CleanupEvidenceStore {
389
+ finalize(input: {
390
+ evidence: PurgeEvidence;
391
+ manifest: CleanupManifest;
392
+ }): Promise<void>;
393
+ }
394
+ /** A serializable job — everything the worker needs is the run id. */
395
+ interface CleanupJob {
396
+ readonly runId: string;
397
+ }
398
+ /**
399
+ * Durable job queue (§8). `execute()` enqueues a `{ runId }`; a worker later
400
+ * dequeues and calls `service.processRun(runId)` — a DIFFERENT process can do
401
+ * this because the run carries the whole sealed operation. The default in-proc
402
+ * queue defers to a microtask (still off the request path within one process);
403
+ * production injects BullMQ / SQS / a repo-backed queue for cross-process
404
+ * durability, claim/lease, and restart recovery.
405
+ */
406
+ interface CleanupJobQueue {
407
+ enqueue(job: CleanupJob): Promise<void>;
408
+ }
409
+ /**
410
+ * A company/target write fence (§8) — blocks new writes for the duration of a
411
+ * destructive run. Acquire/release keyed by the operation id so a crashed run's
412
+ * fence is recoverable by op id.
413
+ *
414
+ * `acquire` MAY return a fencing token; when it does, the service passes the
415
+ * SAME token back to `release`, and the fence MUST refuse a release carrying a
416
+ * stale token. This closes the distributed race where a stalled ex-owner wakes
417
+ * after lease expiry and releases the fence out from under the new owner.
418
+ * Implementations without cross-process workers may return `undefined` and
419
+ * ignore the token.
420
+ */
421
+ interface CleanupWriteFence {
422
+ acquire(operationId: string): Promise<string | undefined | void>;
423
+ release(operationId: string, token?: string): Promise<void>;
424
+ }
425
+ interface CleanupPermissions {
426
+ /** May preview/observe runs. */
427
+ view: CleanupPermissionCheck;
428
+ /** May execute a run. Superadmin in the reference host. */
429
+ execute: CleanupPermissionCheck;
430
+ /** May cancel/retry a run. Defaults to `execute` when omitted. */
431
+ manage?: CleanupPermissionCheck;
432
+ }
433
+ /** Host permission predicate — receives whatever the host passes as the request scope. */
434
+ type CleanupPermissionCheck = (scope: unknown) => boolean | Promise<boolean>;
435
+ /** Framework size caps that keep runs + documents bounded (design "memory"). */
436
+ interface CleanupLimits {
437
+ /** Max plan items. Default 500. */
438
+ readonly maxPlanItems: number;
439
+ /** Max per-run result rows folded into the manifest. Default 1000. */
440
+ readonly maxResults: number;
441
+ /** Max verification checks. Default 200. */
442
+ readonly maxChecks: number;
443
+ /** Max reason string length. Default 2000. */
444
+ readonly maxReasonLength: number;
445
+ /** Max nesting depth of the parameters object. Default 8. */
446
+ readonly maxParamDepth: number;
447
+ }
448
+ declare const DEFAULT_CLEANUP_LIMITS: CleanupLimits;
449
+ //#endregion
450
+ export { CleanupWriteFence as A, CleanupResult as C, CleanupRunStore as D, CleanupRunStatus as E, PurgeStrategyKind$1 as F, PurgeVerificationSummary as I, VerificationCheck as L, PurgeActor as M, PurgeEvidence as N, CleanupRunTransitionPatch as O, PurgeResourceResult as P, VerificationResult as R, CleanupRecipe as S, CleanupRunCreateResult as T, CleanupPermissions as _, CleanupEvidenceStore as a, CleanupPlanItem as b, CleanupInput as c, CleanupLease as d, CleanupLimits as f, CleanupPermissionCheck as g, CleanupOutcomeStatus as h, CleanupContext as i, DEFAULT_CLEANUP_LIMITS as j, CleanupStepResult as k, CleanupJob as l, CleanupManifest as m, CLEANUP_TERMINAL_STATUSES as n, CleanupExecutionContext as o, CleanupLogger as p, CleanupCancelRequest as r, CleanupFinalizationPayload as s, Availability as t, CleanupJobQueue as u, CleanupPlan as v, CleanupRun as w, CleanupProgressSummary as x, CleanupPlanDraft as y };