@classytic/repo-core 0.27.1 → 0.29.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 (55) hide show
  1. package/CHANGELOG.md +1263 -1014
  2. package/dist/cache/engine.d.mts +7 -5
  3. package/dist/cache/engine.mjs +34 -16
  4. package/dist/cache/memo.d.mts +4 -0
  5. package/dist/cache/memo.mjs +17 -4
  6. package/dist/cache/memory-adapter.mjs +6 -4
  7. package/dist/cache/plugin/context.mjs +3 -1
  8. package/dist/cache/plugin/read-hooks.mjs +1 -1
  9. package/dist/cache/stable-stringify.d.mts +7 -8
  10. package/dist/cache/stable-stringify.mjs +14 -11
  11. package/dist/cache/tag-index.mjs +1 -2
  12. package/dist/cache/types.d.mts +4 -3
  13. package/dist/errors/codes.d.mts +117 -0
  14. package/dist/errors/codes.mjs +114 -0
  15. package/dist/errors/contract.d.mts +2 -1
  16. package/dist/errors/contract.mjs +9 -3
  17. package/dist/errors/index.d.mts +3 -2
  18. package/dist/errors/index.mjs +2 -2
  19. package/dist/errors/types.d.mts +3 -30
  20. package/dist/filter/builders.mjs +1 -1
  21. package/dist/filter/match-record.mjs +9 -3
  22. package/dist/filter/match.mjs +25 -9
  23. package/dist/idempotency/index.d.mts +462 -0
  24. package/dist/idempotency/index.mjs +419 -0
  25. package/dist/pagination/keyset.mjs +0 -2
  26. package/dist/pagination/types.d.mts +18 -0
  27. package/dist/query-parser/coerce.d.mts +18 -11
  28. package/dist/query-parser/coerce.mjs +37 -69
  29. package/dist/query-parser/errors.d.mts +30 -0
  30. package/dist/query-parser/errors.mjs +32 -0
  31. package/dist/query-parser/grammar.d.mts +107 -0
  32. package/dist/query-parser/grammar.mjs +462 -0
  33. package/dist/query-parser/index.d.mts +5 -2
  34. package/dist/query-parser/index.mjs +5 -2
  35. package/dist/query-parser/parse-url.d.mts +1 -1
  36. package/dist/query-parser/parse-url.mjs +72 -205
  37. package/dist/query-parser/regex-safety.d.mts +31 -0
  38. package/dist/query-parser/regex-safety.mjs +151 -0
  39. package/dist/query-parser/reserved.mjs +1 -0
  40. package/dist/query-parser/types.d.mts +15 -25
  41. package/dist/repository/index.d.mts +2 -2
  42. package/dist/repository/index.mjs +2 -2
  43. package/dist/repository/resilience.d.mts +25 -20
  44. package/dist/repository/resilience.mjs +66 -2
  45. package/dist/repository/types.d.mts +105 -6
  46. package/dist/schema/field-rules.mjs +49 -6
  47. package/dist/schema/standard-schema.mjs +1 -1
  48. package/dist/testing/idempotency-conformance.d.mts +15 -0
  49. package/dist/testing/idempotency-conformance.mjs +315 -0
  50. package/dist/testing/index.d.mts +3 -1
  51. package/dist/testing/index.mjs +3 -1
  52. package/dist/testing/query-grammar-conformance.d.mts +60 -0
  53. package/dist/testing/query-grammar-conformance.mjs +380 -0
  54. package/package.json +6 -2
  55. package/dist/errors/types.mjs +0 -29
package/CHANGELOG.md CHANGED
@@ -1,1014 +1,1263 @@
1
- # Changelog
2
-
3
- All notable changes to `@classytic/repo-core` are documented here.
4
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
- and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
-
7
- ## [0.27.1] - 2026-09-11
8
-
9
- ### Fixed
10
-
11
- - **A failed single-flight fetch with no concurrent waiter raised an
12
- `unhandledRejection`** — in addition to the error the caller had already
13
- caught. `claimPending` creates a deferred for waiters that may never arrive;
14
- rejecting it for nobody made a working `try/catch` a process crash under
15
- `--unhandled-rejections=strict`. Reached from `CacheEngine.prefetch`, so from
16
- every `createTtlMemo` consumer, and from the plugin read path. The deferred is
17
- now marked observed at creation; a waiter that does exist still receives the
18
- rejection. `tests/unit/cache/single-flight-unobserved-rejection.test.ts` pins
19
- the single-caller case the existing two-caller test could never reach.
20
-
21
- ## [0.27.0] - 2026-09-09
22
-
23
- ### Added
24
-
25
- - **`createTtlMemo(load, { ttlMs, keyOf?, maxEntries? })`** on `./cache` — the
26
- one way to memoise a keyed async load for a while. It is `CacheEngine.prefetch`
27
- over the memory adapter, so concurrent misses for one key share ONE load, a
28
- thrown load caches nothing, and a `null` result is an answer.
29
-
30
- Four packages had each hand-rolled `Map<key, { at, value }>` with a TTL, and
31
- every one wrote its entry AFTER the await. Under parallel event dispatch N
32
- callers reach the await together, all miss, and the cache only ever helps the
33
- caller after them — a 30 s TTL that measured nine reads of one row per event.
34
- `tests/unit/cache/ttl-memo.test.ts` pins single flight, expiry, invalidation,
35
- `ttlMs: 0` = off, and refuses an object key without `keyOf` (an
36
- identity-compared key never hits and reads as a caching bug).
37
-
38
- ## [0.26.1] - 2026-09-08
39
-
40
- ### Fixed
41
-
42
- - **`vitest` is no longer declared as a peer dependency.** It was
43
- `peerDependencies: { vitest: "^3.0.0 || ^4.0.0" }` with
44
- `peerDependenciesMeta.optional: true` — and that combination does not do what
45
- it looks like. `optional: true` only silences the *missing* case; npm still
46
- hard-fails `ERESOLVE` on a version **mismatch**. So every consumer on a newer
47
- vitest could not install repo-core at all, even though nothing they imported
48
- touched it.
49
-
50
- Measured: `@classytic/arc` could not move to vitest 5 — `npm install` failed
51
- with `Conflicting peer dependency: vitest@5.0.0`, sourced to this package.
52
- Widening the range to `|| ^5.0.0` would only have moved the wall to vitest 6.
53
-
54
- `vitest` is the CONSUMER's test runner. Anyone importing
55
- `@classytic/repo-core/testing` is by definition already inside a vitest suite
56
- that provides it, so the import resolves from their install; anyone who does
57
- not import it should never have been constrained. It stays in
58
- `devDependencies` for this package's own suite, and `tsdown`'s `neverBundle`
59
- now lists `vitest` so the bundler keeps the import external instead of
60
- inlining a dev-only dependency into shipped output.
61
-
62
- Any vitest exposing the standard `describe` / `it` / `expect` / `beforeEach` /
63
- `afterEach` API works with the `/testing` conformance suites.
64
-
65
- ## [0.26.0] - 2026-09-02
66
-
67
- ### Added
68
-
69
- - **`@classytic/repo-core/loader` — `createBatchLoader`.** Read-side counterpart
70
- of a kit's `bulkWrite`: keys issued anywhere in one tick coalesce into a single
71
- `batch()` call, so a per-item read in a loop costs one round trip instead of N.
72
- Create one per operation — it caches, so its lifetime is a correctness
73
- property and the caller owns it.
74
-
75
- Refuses rather than guesses, in three places that otherwise return a plausible
76
- wrong answer with nothing reported:
77
- - a `batch()` result whose length differs from the keys (a short array shifts
78
- every later value onto the wrong key, and each value is individually valid);
79
- - an object key with no `keyOf` (`String({})` is `[object Object]` for every
80
- object, so the default would merge unrelated keys AND report the collisions
81
- as cache hits);
82
- - a non-integer or `< 1` `maxBatchSize` (`Math.max(1, NaN)` is `NaN`, and a
83
- `NaN` stride abandons every waiter with no error) — same validation
84
- `repository/purge.ts` already applies to this parameter.
85
-
86
- Known limits: chunks beyond `maxBatchSize` run concurrently with no cap, and a
87
- sequential `for … await loader.load(x)` loop batches nothing by construction
88
- (each `await` closes the microtask window). Use `loadMany` or `Promise.all`,
89
- and read `stats.batches` to confirm the round-trip count you expected.
90
-
91
- ## [0.25.0] - 2026-08-24
92
-
93
- ### Added
94
-
95
- - **`CacheAdapterResolver = () => CacheAdapter | undefined`** — a function consulted per call that returns the store for the current scope, or `undefined` for "no cache right now". `undefined` is inert — identical to `enabled: false` — and never falls back to a shared store, because that fallback is the cross-scope leak the scoping exists to prevent.
96
- - **`CacheAdapterSource = CacheAdapter | CacheAdapterResolver`** — `CacheEngine` and `cachePlugin` now accept either a fixed process-lifetime adapter (unchanged behaviour) or a resolver. A bare adapter is sugar for `() => adapter`; normalised at construction so every call site is on one path.
97
- - **`CacheAdapterResolver` and `CacheAdapterSource` exported from `@classytic/repo-core/cache`** and re-exported from the plugin index.
98
-
99
- ## [0.24.0] - 2026-08-17
100
-
101
- Version bump only — republished 0.23.1's contents under a minor so consumers pinning `>=0.24.0` get the tenant guard by a floor rather than a patch. No source changes over 0.23.1.
102
-
103
- ## [0.23.1] - 2026-08-17
104
-
105
- ### Added — `assertNoLegacyTenantKeys(config, pkg, extra?)` (`/tenant`)
106
-
107
- Refuses a config still carrying a pre-consolidation tenant key (`multiTenant`, plus any package-specific retirees passed via `extra`) instead of ignoring it.
108
-
109
- The rename onto `TenantConfig` under `tenant` is trivial; the failure mode when a CALLER misses it is not. Every kernel resolver reads `resolveTenantConfig(config.tenant ?? false)`, so an absent `tenant` resolves to `strategy: 'none'` — no tenant field, no tenant filter, every read spanning ALL tenants, no error, and figures that look plausible. A host that asked for tenancy silently gets none.
110
-
111
- The guard lives beside the resolver every one of those packages already calls, rather than being hand-rolled nine times — nine chances to forget, and the one that forgets ships the leak. Additive and non-breaking: nothing calls it until a package renames.
112
-
113
- ## [0.23.0] - 2026-08-13
114
-
115
- ### Added — transactional-core contracts (Phase 1a + 1d) + fencing (Phase 2, first slice)
116
-
117
- - **Concurrency-conflict taxonomy** (`/errors`): `IsTransientConflictFn` + `neverTransient` default + `conservativeMongoIsTransientConflict` — same ownership rule as `isDuplicateKeyError` (the kit knows its driver; repositories expose `isTransientConflictError`). The default is NO retry: re-running side effects on an unclassified failure is the unsafe direction.
118
- - **`VersionConflictError`** (`/errors`) + `isVersionConflictError` (survives duplicated copies): the optimistic-CAS violation, 409-shaped, distinct from not-found by contract — a stale version THROWS, never returns `null`, because collapsing the two invites a blind retry that clobbers the concurrent write.
119
- - **`WriteOptions.ifVersion`** + `RepoCapabilities.optimisticConcurrency`: CAS write contract — apply only at the expected version, increment on success, throw on the option when the capability is absent (a silently dropped guard is the defect, not a degraded mode).
120
- - **`retryingTransaction(repo, fn, opts)`** (`/repository`): the transactional retry envelope — `withTransaction` re-run on TRANSIENT conflicts only, bounded attempts, full-jitter backoff, abort-aware, classification from the kit predicate. Refuses (throws) a repository without `withTransaction` — no silent degrade. Contains no backoff math of its own: rides `withRetry`.
121
- - **`withRetry` gains `maxDelayMs` + `jitter` + an abortable sleep** — an aborted caller no longer waits out its backoff (mutation-proven: a plain `setTimeout` there times the pinning test out). Defaults unchanged.
122
- - **`TransactionHandle`**: `withTransaction`'s callback gains a second argument `{ session? }` — the raw driver handle, so work OUTSIDE the repository (the outbox writer, canonically) can join the same transaction. Kits MUST pass a handle object (possibly empty, for connection-bound backends); a conformance case pins the argument's presence. `retryingTransaction` forwards it structurally.
123
- - **`LockAdapter.tryAcquireFenced?`** (additive): a successful acquire returns a MONOTONIC token minted by the STORE — a process cannot fence itself. Token increments per ownership CHANGE (extension keeps it; epochs, not heartbeats), so a downstream store can reject a stale ex-holder after lease loss — the overlap serialized renewal narrows but cannot close. `LockState.token`; memory adapter implements it (monotonic for the adapter lifetime — the honest memory limit, documented). Boolean `tryAcquire` unchanged.
124
- - **`RepoCapabilities.transactionRetry: 'managed' | 'caller'`** — WHO owns retry of a conflict-aborted transaction. `retryingTransaction` used to wrap EVERY kit in its own 5-attempt loop, including MongoDB's convenient transaction API, which already re-runs the callback internally on `TransientTransactionError` / `UnknownTransactionCommitResult` for up to 120s. Two stacked policies: the callback's execution count stopped being bounded by `maxAttempts`, `onRetry` reported a fraction of real attempts, every outer attempt opened a NEW session, and misplaced side effects repeated unpredictably. Retry ownership is now DECLARED — `'managed'` is invoked exactly once, `'caller'` gets the envelope's loop. **Absent means `'managed'`**: a missing retry surfaces a conflict as a 409, a nested one re-runs side effects without bound, so silence must mean "don't" (same posture as `neverTransient`). `retryOwner` overrides for repositories that cannot declare.
125
- - **`retryingTransaction` is capability-aware** — a repository that publishes a descriptor is held to it (`transactions !== true` → throw, which `'unknown'` reports, failing closed). Method presence was never the test: kits expose `withTransaction` unconditionally and fail at BEGIN.
126
- - **`asReadOnlyRepo(repo, { reason })` + `RepoCapabilities.readOnly`** (`/repository`) — seal a repository whose rows another writer owns (Better Auth's identity collections, a SQL view, a read replica). Writes throw `ReadOnlyRepositoryError` (synchronously, so a forgotten `await` still crashes); reads pass through. A Proxy rather than a wrapper so a kit method this module has never heard of is sealed BY DEFAULT instead of leaking. `readOnly` lets a host refuse write ROUTES at boot rather than surfacing the wall on the first request.
127
- - **`TransactionHandle` is exported from `/repository`** — it was defined in `types.ts` but never re-exported, so consumers restated it structurally as `{ session?: unknown }` and would silently miss any field added to the contract.
128
- - **Conformance: capability-vs-behaviour assertions** — a transactional repo must declare `transactionRetry`, and `nestedTransactions` must match what a nested `withTransaction` call ACTUALLY does. Both were wrong in a shipped kit: mongokit declared `nestedTransactions: true` while its tx-bound proxy threw on the very same call.
129
- - **Conformance: `ifVersion CAS` block** (gated on `optimisticConcurrency`): matching version applies + increments, stale version throws `VersionConflictError` and the losing write does not apply, not-found stays `null`. New optional harness fields `versionField` / `missingId`.
130
-
131
- ## [0.22.0] - 2026-08-12
132
-
133
- ### Added — `pages: 0` conformance tests for empty results
134
-
135
- - `runStandardRepoConformance` now asserts `pages: 0` for empty offset envelopes (both the primary `getAll` path and the `aggregatePaginate` path). The field had no assertion anywhere in the suite; two kit paths diverged silently: the primary offset path computed `ceil(0/limit) = 0` while aggregate and lookup paths used `Math.max(1, ceil(...)) = 1`. The contract is `0` — zero rows fill zero pages — and it is what every kit's primary path already returned. The missing assertion let the drift reach a consumer as golden-fixture breakage when a `lookups` join rerouted a list read onto the divergent path.
136
-
137
- ## [0.21.0] - 2026-08-10
138
-
139
- ### Added — LRU-bounded `createMemoryCacheAdapter`
140
-
141
- - `createMemoryCacheAdapter(options?)` now accepts `MemoryCacheAdapterOptions` with a `maxEntries` cap (default `10,000`). Past the cap the least-recently-used entry is evicted — read promotion (delete + re-insert) keeps the map ordered by recency so eviction is O(1). A TTL alone does not bound the map: entries only expire when read, so a high-cardinality keyspace (per-tenant, per-commit, per-filter keys) grows monotonically until the process dies. Eviction is always safe for a cache, so the bound is on by default. Set `maxEntries: 0` to restore the previous unbounded behaviour.
142
- - `MemoryCacheAdapterOptions` exported from `@classytic/repo-core/cache`.
143
-
144
- ### Added — timezone-aware date buckets (`AggDateBucket.timezone`)
145
-
146
- - `AggDateBucket.timezone` — IANA zone the bucket boundaries are drawn in; absent means UTC. A UTC day is not a business day in any non-UTC deployment: rows from 18:00 to midnight local fall in the previous UTC day, silently reporting the wrong period in daily/monthly rollups.
147
- - `AggregateOpsSupport.dateBucketTimezone` capability flag — a kit that cannot draw DST-correct boundaries (e.g. SQLite, no tz database) MUST declare `dateBucketTimezone: false` and throw when the field is set rather than silently bucketing in UTC. Mongokit (`$dateTrunc` / `$dateToString` both accept `timezone`) declares `true`.
148
-
149
- ## [0.20.0] - 2026-08-04
150
-
151
- ### Added
152
-
153
- - **`ResolveBetterAuthCollectionsOptions.exclude`** — canonical collection names
154
- to omit from `resolveBetterAuthCollections()` output. Applied before
155
- `modelOverrides` / `usePlural` so a caller names the canonical collection
156
- (`'user'`) and never has to predict the final model name. Solves the collision
157
- when a host registers stub models for BA collections it merely references and a
158
- full `createBetterAuthOverlay` for the one it exposes CRUD on — both for the
159
- same collection would cause mongoose to lock the schema on first `model()`,
160
- silently dropping `additionalFields` and causing the overlay to refuse.
161
-
162
- ## [0.19.0] - 2026-07-29
163
-
164
- ### Added — `coerceFilterDates` + ISO date helpers (`./filter`)
165
-
166
- - **`coerceFilterDates(filter)`** — walks a record-shape filter (Mongo-dialect or bare bracket-op syntax) and coerces ISO-8601 strings on range operators (`gt`/`gte`/`lt`/`lte` and `$`-prefixed equivalents) to `Date`, recursing through `$and`/`$or`/`$nor`/`$not` logical wrappers. Returns a new object; the input is never mutated. Equality operators are deliberately excluded — a string that happens to look like a date is far more likely a string id than a date equality predicate. Fixes silent empty results on aggregation `$match` stages: MongoDB `$match` (unlike `find`) performs no schema casting, so a string compared to a Date column matches nothing.
167
- - **`tryCoerceIsoDate(value)`** — coerces one unknown value to a `Date` when it is an unambiguous ISO-8601 string; returns anything else untouched. Safe to apply unconditionally.
168
- - **`ISO_DATE_PATTERN`** — the single regex source of truth for tight ISO-8601 detection (date-only through millisecond precision + optional timezone). `query-parser/coerce.ts` now imports this instead of keeping a duplicate pattern — one definition means the URL boundary and the compile boundary can never disagree on what "looks like a date".
169
-
170
- All three are exported from `@classytic/repo-core/filter`. Purely additive.
171
-
172
- ## [0.18.0] - 2026-07-27
173
-
174
- ### Added — `definePurgeStep` builder (`./cleanup`) and `resolveTenantField` (`./tenant`)
175
-
176
- #### `./cleanup` — `definePurgeStep`
177
-
178
- - **`definePurgeStep(repository, spec)`** — standard builder for the most common
179
- `CleanupStep` shape: a chunked `purgeByField` over a single scope value.
180
- Nearly every provider step in a domain kernel is this pattern; the builder owns
181
- the invariant core so callers only declare what differs:
182
- - **fail-closed scoping** — missing scope value or unavailable repository is a
183
- `BLOCKER` (not a silent no-op and never an unscoped purge that would hit every
184
- tenant); blocked by `SCOPE_REQUIRED:<param>` / `REPOSITORY_UNAVAILABLE:<id>`.
185
- - **cancellation** — `throwIfCancelled` is called before work starts and the
186
- `signal` is threaded to the kit so a cancel lands between committed chunks.
187
- - **honest failure** — a failing purge returns `ok: false` so the recipe composer
188
- stops (retention §8); thrown errors are caught and reported, never swallowed.
189
- - **verification** — absence is re-queried after the run via `countDocuments`
190
- (`spec.verifyFilter` for steps whose match filter differs from the absence proof).
191
- - **`PurgeStepSpec`** — declaration object: `id`, `resource`, `parameter`, `field`,
192
- `strategy`, optional `retained`, `warnings`, `batchSize`, `guard(scope, ctx)`,
193
- `verifyFilter(scope)`, `verifyName`.
194
- - **`PurgeStepRepository`** — structural subset of `StandardRepo` satisfied by any
195
- kit repository that implements `purgeByField` + `countDocuments`.
196
- - **`SCOPE_REQUIRED`** / **`REPOSITORY_UNAVAILABLE`** — blocker-code prefix constants.
197
-
198
- #### `./tenant` — `resolveTenantField`
199
-
200
- - **`resolveTenantField(config?)`** — returns the single `tenantField` string a
201
- resource layer needs for `defineResource({ tenantField })`, or `false` when the
202
- config disables tenant scoping (`false` / `{ enabled: false }` / `{ strategy: 'none' }`).
203
- Four spine modules hand-rolled equivalent logic independently, each re-deriving
204
- `'organizationId'` as the default; one copy omitted the disable branch, making
205
- that package silently un-configurable. This function is the single definition.
206
-
207
- Both additions are purely additive — no breaking changes.
208
-
209
- ## [0.17.0] - 2026-07-25
210
-
211
- ### Added — `./cleanup`: framework-free cleanup provider step contract
212
-
213
- - **`@classytic/repo-core/cleanup`** — new subpath (pure types, no runtime).
214
- Domain kernels (`@classytic/flow`, `@classytic/order`, `@classytic/facts`,
215
- `@classytic/ledger`, …) export `CleanupStep[]` for the data they own; a host
216
- framework (`@classytic/arc/cleanup`) folds them into a Cleanup Center recipe.
217
- The contract lives in repo-core so kernels stay framework-free: kernels already
218
- depend on repo-core (the chunked-purge mechanics) and MUST NOT depend on arc.
219
- - **`CleanupStep`** — the core provider interface: `id`, `resource`, `destructive`,
220
- optional `rebuildActions`; and three lifecycle methods: `estimate(ctx)` (preview
221
- without mutating), `execute(ctx)` (chunked, idempotent, cancellation-aware),
222
- and optional `verify(ctx)` (post-checks — a delete count alone is never success).
223
- - **Supporting types**: `CleanupStepContext` (injected `now`, `signal`, `ambient`,
224
- `parameters`, `logger`), `CleanupStepExecuteContext` (adds `onProgress` +
225
- `throwIfCancelled`), `CleanupStepEstimate` (row count, `retained`, `blockers`,
226
- `warnings`), `CleanupStepOutcome` (`processed`, `ok`, `error`, `cursor`),
227
- `CleanupStepCheck` (`name`, `ok`, `detail`), `CleanupStepProgress`, `CleanupStepLogger`.
228
-
229
- Purely additive — zero runtime code, type-only subpath export.
230
-
231
- ## [0.16.0] - 2026-07-24
232
-
233
- ### Added — `runPurgeConformance`: cross-kit chunked-purge contract suite
234
-
235
- - **`runPurgeConformance(harness)`** (from `@classytic/repo-core/testing`) —
236
- proves a kit's purge port makes **stable progress for every strategy** when
237
- the match set exceeds `batchSize`. Every scenario seeds more rows than one
238
- batch; a chunk budget converts a non-progressing port's infinite loop into a
239
- crisp assertion failure. Scenarios: hard drain, soft multi-batch WITHOUT
240
- caller-supplied exclusion predicates, anonymize static + function-form,
241
- exact-batch boundary, skip, empty scope, abort-between-chunks.
242
- - **`PurgePort` progression contract (documented, mandatory)** — successive
243
- `purgeChunk` calls MUST advance through the match set for every strategy via
244
- stable keyset progression (`pk > lastSeen`, advanced only after the chunk's
245
- write succeeds). Re-running the bare predicate only self-advances for
246
- `hard`; `soft`/`anonymize` re-select the same first chunk forever. Offsets
247
- are explicitly ruled out. A port instance is single-run state.
248
-
249
- ### Fixed
250
-
251
- - `purgeByField` docstring no longer claims soft/anonymized rows "simply don't
252
- match the next pass" — they generally DO still match; idempotency holds by
253
- outcome convergence, and within-run progression is the port's keyset
254
- responsibility.
255
-
256
- ## [0.15.0] - 2026-07-24
257
-
258
- ### Added — `purgeByFilter`: range/filter-scoped purge + anonymize
259
-
260
- - **`StandardRepo.purgeByFilter?(filter, strategy, options)`** — the
261
- range/filter-scoped sibling of `purgeByField`. Where `purgeByField` matches
262
- a single `field = value` equality, this optional method takes the full
263
- portable `FilterInput` (Filter IR or a plain kit-native record) and runs any
264
- `TenantPurgeStrategy` (`hard` / `soft` / `anonymize` / `skip`) over the
265
- matched slice. THE compliance primitive for "purge/anonymize a dimension
266
- across a RANGE while RETAINING measures" — redact a PII column across a
267
- `civilDate` window, hard-delete rows past a retention cutoff, soft-delete a
268
- compound cohort. Returns the same `TenantPurgeResult` envelope; chunking,
269
- index requirement, idempotency, plugin composition, and narrowed-write
270
- re-assertion are identical to `purgeByField`. Gate on the new
271
- `capabilities.purgeByFilter`.
272
- - **`RepoCapabilities.purgeByFilter?: boolean`** — feature-detection flag,
273
- mirroring `purgeByField`.
274
- - **`PurgePort` doc** clarifies the two bound-predicate forms (equality-bound
275
- vs filter-bound) both satisfy the single port interface, so `runChunkedPurge`
276
- drives both unchanged.
277
-
278
- Strictly additive: `purgeByField`, `TenantPurgeStrategy`, and `runChunkedPurge`
279
- are unchanged; both new members are optional.
280
-
281
- ## [0.14.0] - 2026-07-16
282
-
283
- ### Added — canonical `matchesRecordFilter` (the `DataAdapter.matchesFilter` home)
284
-
285
- - **`matchesRecordFilter(item, record)`** + **`policyRecordToFilter(record)`**
286
- (`@classytic/repo-core/filter`) — THE single, shared implementation of the
287
- `DataAdapter.matchesFilter` seam. Evaluates arc's Mongo-record `_policyFilters`
288
- (`{ ownerId }`, `{ organizationId }`, `{ $or: [{ ownerId }, { _id: { $in } }] }`)
289
- against an already-fetched document IN PROCESS, by converting to the portable
290
- `Filter` IR and delegating to `matchFilter` — the SAME IR kits compile to
291
- SQL/Mongo, so in-memory and DB enforcement agree by construction. Every kit's
292
- adapter now delegates here; **no per-kit matcher, one contract, one IR.**
293
- Operator scope: `$or`/`$and`/`$nor`/`$not`, `$eq`/`$ne`/`$gt`/`$gte`/`$lt`/`$lte`,
294
- `$in`/`$nin`, `$exists`, implicit-eq; fails LOUD on anything else. (Distinct from
295
- `recordToFilter`, the bare-operator query normalizer that does not accept
296
- `$`-prefixed or logical operators.)
297
- - **`matchFilter` is now fully array + id + date aware** (additive superset;
298
- primitive/Date-vs-Date behavior unchanged — strict cases still short-circuit):
299
- - **id coercion** — an id-like object with a meaningful `toString` (Mongo
300
- `ObjectId`, `Buffer`, `Decimal128`) matches its string form, so one shared
301
- matcher serves Mongo (`ObjectId` `_id`) and SQL (primitive ids) alike.
302
- - **array semantics** — dot-paths fan out over subdocument arrays
303
- (`items.sku` on `[{sku},{sku}]`), and a scalar condition on a leaf array
304
- field matches when ANY element satisfies it (`{ tags: 'x' }`,
305
- `{ scores: { $gt: 5 } }`, regex on array elements). All array unwrapping is
306
- concentrated in one helper; the comparators stay pure scalar.
307
- - **Date⇄ISO-string range** — `compare` coerces the string side to a date
308
- instant when the other side is a genuine `Date` (mirrors `equals`), and
309
- never claims ordering across a number/string type boundary (fails closed
310
- instead of matching spuriously).
311
- - **prototype-pollution-safe reads** — path resolution uses `Object.hasOwn`,
312
- so a crafted `{ '__proto__.x': … }` / `{ constructor.name: … }` filter can
313
- never traverse the prototype chain.
314
- - **Ability parity across kits**: mongokit's earlier standalone matcher
315
- (subdocument-array fan-out, array-contains, `$regex`, ObjectId coercion) is now
316
- fully covered by the shared engine — nothing was lost in consolidation.
317
- - **MongoDB-parity hardening** (validated against the MongoDB manual + sift.js +
318
- mingo — the two industry-standard in-memory matchers). The authorization-critical
319
- rule "an absent field participates in comparisons as null/undefined" is now
320
- fully honored:
321
- - `{ field: null }`, `$ne`, `$nin`, and a `null` MEMBER of `$in`/`$nin` all
322
- match a MISSING field (a policy filter `{ status: { $ne: 'archived' } }`
323
- correctly returns docs that lack the field, exactly as MongoDB does — the top
324
- silent-authorization-divergence trap). `$ne: null` remains the exception
325
- (requires present + non-null).
326
- - `$in` accepts RegExp-literal members (`{ name: { $in: [/^a/] } }`).
327
- - Comparison ops are type-bracketed (no cross-type ordering; `$gt: null` matches
328
- nothing); NaN equals NaN for `$eq` (via `Object.is`, not `===`).
329
- - Numeric dot-path segments resolve as positional array indices (`items.0.sku`).
330
- - Documented DELIBERATE divergences: `$exists` = present-and-non-null (matches
331
- the IR `exists` op + SQL `IS NOT NULL` + sift; Mongo/mingo count present-null
332
- as existing); `Date`⇄ISO-string range leniency; array-literal operands are
333
- element-matched not exact-matched.
334
- - New: 41-case matcher suite incl. the 11 researched MongoDB gotchas + adversarial
335
- (prototype pollution, NaN/Infinity, boolean/zero/empty-string, empty
336
- `$in`/`$or`/`$and`/`$nor`, fail-loud on unsupported operators) + a 100k-doc
337
- performance smoke (linear, cached regex).
338
- - **Security hardening** (from a review against sift.js/mingo CVEs + the OWASP
339
- NoSQL-injection / ReDoS / prototype-pollution literature):
340
- - **Prototype-key denylist** on path segments — `__proto__` / `constructor` /
341
- `prototype` resolve to nothing (fail-closed), string-normalized (the
342
- object-path CVE-2021-23434 lesson: an array-typed segment bypassed a `===`
343
- check). Closes the "match an inherited member → wrong auth answer" case and
344
- the `JSON.parse('{"__proto__":…}')` own-property vector, on top of the
345
- already-`Object.hasOwn` reads.
346
- - **`$regex` input-length cap** (64 KiB) — ReDoS is `pattern × input`; a field
347
- value longer than the cap is treated as no-match (fail-closed) so one slow
348
- match can't stall the event loop and amplify across a realtime fan-out
349
- (matcher runs once per subscriber per record). Pattern-side ReDoS is a
350
- non-issue for framework-supplied (trusted) patterns.
351
- - Reaffirmed **fail-closed** posture: comparisons never coerce across a
352
- number/string type boundary (return no-match rather than JS-coerced nonsense
353
- — the classic over-visibility leak), and unsupported operators throw.
354
-
355
- ## [0.13.0] - 2026-07-15
356
-
357
- ### Added — `StandardRepo.applyTransition?()` contract (state-machine CAS with history)
358
-
359
- - **`TransitionMachine`** — the canonical structural contract for the state
360
- machine (`{ name, assertTransition }`). Primitives'
361
- `defineStateMachine()` output and mongokit's local `TransitionMachine`
362
- are structurally identical by design; nobody imports anybody (same
363
- policy as `ClaimTransition`).
364
- - **`TransitionArgs`** — `{ from, to, field?, set?, push?, where?, by?,
365
- note?, history?, at? }`.
366
- - **`StandardRepo.applyTransition?(id, machine, args, options)`** — OPTIONAL
367
- member declaring the state-machine-backed CAS transition mongokit 3.22
368
- ships as a class primitive: legality pre-flight via the machine (which
369
- throws the domain's typed error), CAS via `claim`, `$push`ed status
370
- history, and accurate race-loss diagnosis (machine error from the row's
371
- CURRENT state / 404 `TRANSITION_TARGET_MISSING` / 409
372
- `TRANSITION_RACE_LOST`). Unlike `claim`/`claimVersion` it THROWS rather
373
- than returning `null` — it owns the error liturgy domain packages used
374
- to copy-paste. Promote to required once sqlitekit implements it.
375
-
376
- ### Added — `./usage` subpath (period-bucketed counter contract)
377
-
378
- - **`UsageStore`** — driver-agnostic interface for atomic period-bucketed counters: `increment(bucket, amount)` + `summary(actor, period)`. The storage seam under platform accounting (quotas, plan enforcement, usage-based billing). One cell = `(actor, period, kind)`; one write = atomic upsert; one read = all counters for an actor-period pair. Kits ship adapters (`@classytic/mongokit/usage`, `@classytic/sqlitekit/usage`, …) without depending on arc; `@classytic/arc/usage` consumes this contract structurally.
379
- - **`UsageBucket`** — `{ actor, period, kind }` tuple. `kind` is dot-namespaced: `api.requests`, `ai.tokens.input`, `storage.egress.bytes`.
380
- - **`usagePeriod(date?)`** — canonical UTC calendar-month key (`"2026-07"`). Monthly is the billing-native granularity.
381
- - **`createMemoryUsageStore()`** — in-process reference implementation for tests and single-instance apps. Returns `UsageStore & { clear() }`. Multi-replica deployments need a shared adapter.
382
-
383
- ### Added — `runUsageStoreContract` in `./testing`
384
-
385
- - **`runUsageStoreContract(harness)`** — cross-kit conformance suite. Kits import once and pass their adapter; all canonical scenarios run automatically. Same pattern as `runLockAdapterConformance`. `UsageConformanceHarness` is exported from `./testing` for harness typing.
386
-
387
- ## [0.10.0] - 2026-07-13
388
-
389
- ### Added — `ValidationErrorMeta.path` + `.meta` (field-scoped validation errors)
390
-
391
- - **`ValidationErrorMeta.path?: string`** — dot-path to the offending field
392
- (e.g. `'journalItems.2.account'`). Set by kits with field-scoped validation
393
- (ledger's `FieldError`, Mongoose `ValidationError`). Absent when the kit doesn't
394
- have a field path.
395
- - **`ValidationErrorMeta.meta?: Readonly<Record<string, unknown>>`** — non-PII
396
- structured extra for the field (e.g. `{ value: 'bad' }`). Never include secrets.
397
- - **`toErrorContract`** now forwards `path` and `meta` from each `validationErrors`
398
- entry onto the wire `ErrorDetail`. Previously only `code` and `message` were mapped;
399
- field paths were silently dropped. No breaking change — both fields are optional and
400
- additive. Kits that don't set them produce the same wire shape as before.
401
-
402
- ## [0.9.0] - 2026-07-11
403
-
404
- ### Added — `StandardRepo.getByIds` (batch point-read)
405
-
406
- - **`getByIds?(ids: readonly string[], options?: FindAllOptions): Promise<Map<string, TDoc>>`**
407
- added to `StandardRepo` — the `$in` / `IN (...)` counterpart to `getById`. The N+1
408
- killer for callers resolving many ids in one tick (order-line snapshotting, dashboard
409
- row enrichment, reference expansion).
410
-
411
- **Contract:**
412
- - Kit de-duplicates ids before the driver round-trip.
413
- - Ids with no matching doc are ABSENT from the returned `Map` — never throw on a miss.
414
- - Structurally invalid ids are treated as misses (one malformed id must never fail the
415
- batch).
416
- - Tenant scoping, soft-delete, and hooks apply exactly as they would to `getById`.
417
- - Empty input → empty Map, no round-trip.
418
- - Optional: kits adopt incrementally. Callers feature-detect
419
- (`repo.getByIds ?? per-id fallback`) until their kit floor ships it.
420
- - Sizing is backend-bound (Mongo: 16 MB query document); keep batches ≤ ~10k ids and
421
- chunk beyond.
422
-
423
- - **`events.ts` clarification** — `getByIds` has no `BEFORE_GET_BY_IDS` event by design.
424
- It routes through `findAll`, so observers see the batch as `before:findAll` / `after:findAll`
425
- with an `$in` filter. The comment guards against accidentally adding a separate event.
426
-
427
- - **New type-level contract test** (`tests/unit/repository/get-by-ids-contract.test.ts`) —
428
- pins the `getByIds` shape for kits implementing it: `Map<string, TDoc>` keyed by
429
- stringified id, `readonly string[]` input. Verifies that kits without `getByIds` still
430
- conform (the member is optional).
431
-
432
- ### Changed
433
-
434
- - `ChangesPage.changes` type: `ReadonlyArray<ChangeEntry<TDoc>>` → `readonly ChangeEntry<TDoc>[]`
435
- (canonical form — functionally identical).
436
- - devDeps: `tsdown ^0.21.8 → ^0.22.5`, `typescript ^6.0.3 → ^7.0.2`.
437
-
438
- ## [0.8.1] - 2026-07-11
439
-
440
- ### Docs — `DataAdapter.close()` ownership rule
441
-
442
- - Clarified the `close?()` contract (doc-only, no type/runtime change): the adapter does **not** own the database connection — the host does, and `close()` must release only adapter/kit-owned resources (TTL/vacuum timers, change streams), never disconnect a shared client/pool. Kits that genuinely own a connection gate its disposal behind an explicit opt-in. This standardizes cleanup semantics across mongokit/sqlitekit/pgkit/prismakit.
443
-
444
- ## [0.8.0] - 2026-07-08
445
-
446
- ### Added — data-lifecycle contract (archive, streaming, distribution awareness)
447
-
448
- Additive release: existing kits on 0.7 semantics compile and pass conformance unchanged (new scenarios are capability-gated and default to skipped).
449
-
450
- - **`archiveByFilter` + `runChunkedArchive`** (`repository/archive.ts`) — the cold-storage twin of `purgeByField`. Hosts provide an `ArchiveSink` (archive table/collection, JSONL, warehouse loader); kits provide an `ArchivePort` (`readChunk` in stable PK order / `deleteChunk` by docs). The orchestrator enforces **write-before-delete** (a crash re-archives, never loses; sinks must be duplicate-tolerant — at-least-once by design), chunked `batchSize` (default 1000), per-step retry via the shared `RetryPolicy`, abort between chunks, cumulative progress, and phase-tagged errors (`read` / `sink` / `delete` — a `sink` failure guarantees rows are still hot). New capability flag: `archiveByFilter`.
451
- - **`cursor()` declared on `StandardRepo`** (+ `CursorOptions`) — the streaming-reads method mongokit and sqlitekit already implement is now part of the portable contract (`AsyncIterable<TDoc>`, internal `batchSize` fetching, non-snapshot semantics documented). Gated by the existing `streaming` capability.
452
- - **Distribution-key awareness** (`repository/distribution.ts`) — `DistributionConfig` (`key`, `onMissingKey: 'warn' | 'throw' | 'off'`, `exemptOperations`) + `createDistributionGuard` + `filterReferencesKey` (Filter IR via `collectFields`, raw records incl. `$and`/`$or`/`AND`/`OR` branches). Catches shard/partition-key-missing scatter-gather queries at the access layer; deliberately does NOT implement routing/rebalancing/partition DDL — those stay database-native (Mongo sharding, pg_partman/Timescale).
453
- - **Conformance**: new capability-gated scenario groups — `archiveByFilter` (sink round-trip, write-before-delete on sink failure, chunking + progress, idempotent re-run, abort partial) and `cursor` (exact-once iteration across batch boundaries, early-break safety).
454
-
455
- ## [0.7.0] - 2026-07-04
456
-
457
- ### Added — `./sync` change-log / cursor contract
458
-
459
- Storage-agnostic data-sync spine for offline-first + incremental replication:
460
- `ChangeLogStore`, `ChangeEntry` (tombstone deletes), pull `ChangesPage`
461
- (opaque exclusive cursors, `hasMore` paging), Replicache-style `PushMutation`
462
- / `PushVerdict` (idempotent client mutation ids, server-authoritative
463
- conflicts), `CursorExpiredError` (compaction horizon → full resync), and the
464
- `MemoryChangeLogStore` reference impl pinning the contract semantics.
465
-
466
- Synthesized from CouchDB `_changes` (tombstones/checkpoints), Drive/Graph
467
- delta APIs (opaque server-issued cursors), Mongo change-stream resume tokens,
468
- and Replicache push/pull. Contract only — kits (mongokit/prismakit/sqlitekit)
469
- implement capture + durable stores via repository plugins; arc re-exports the
470
- surface at `@classytic/arc/sync`; sync HTTP endpoints are an arc module.
471
-
472
- ## [0.6.1] - 2026-07-04
473
-
474
- ### Changed — `TenantConfig` optionals widened to `T | undefined` (P10)
475
-
476
- Every optional prop on `TenantConfig` (`strategy`, `enabled`, `tenantField`,
477
- `fieldType`, `ref`, `contextKey`, `required`, `resolve`) is now typed
478
- `T | undefined`, so downstream packages compiling with
479
- `exactOptionalPropertyTypes: true` can extend it without redeclaring props
480
- (unblocks `@classytic/ledger`'s `MultiTenantConfig.required` exception).
481
-
482
- `resolveTenantConfig` strips explicit-`undefined` keys before spreading
483
- over `DEFAULT_TENANT_CONFIG`, so `{ required: maybeUndefined }` can never
484
- clobber a default with `undefined` — previously the un-widened type made
485
- that unrepresentable; now it's handled at runtime and pinned by tests.
486
- `DEFAULT_TENANT_CONFIG`'s annotation moved from `Required<Pick<...>>` to an
487
- `Exclude<..., undefined>` mapping (`-?` does not strip an explicit
488
- undefined union member). No runtime behavior change for existing callers.
489
-
490
- ## [0.6.0] - 2026-06-11
491
-
492
- Standardization release. Coordinated with mongokit 3.16 + sqlitekit 0.6.
493
-
494
- ### Added
495
-
496
- - **`StandardRepo.capabilities: RepoCapabilities`** (required) — runtime feature detection (`arrayOperators`, `changeStreams`, `regexFilter`, `lean`, `streaming`, `lookupPopulate`, + conformance flags). `ConformanceFeatures` is now an alias of the same type — runtime declaration and conformance gating cannot drift.
497
- - **Standard Schema validation** — `RepositoryBaseOptions.schema` / `updateSchema` accept any Zod / Valibot / ArkType / Effect schema; runs at new `HOOK_PRIORITY.VALIDATION` (150). Failures throw `HttpError` 400 with `validationErrors`. Vendored `StandardSchemaV1` types + `validateStandardSchema()` on `/schema`.
498
- - **Domain events** (`/events` subpath) — `RepositoryBaseOptions.events: { transport }` publishes `<resource>.<verb>` events through any arc/primitives-compatible transport. Publish failures never fail the op (routed to `error:events`).
499
- - **Change feed contract** — optional `StandardRepo.watch?()` returning `AsyncIterable<ChangeEvent<TDoc>>`; gated by `capabilities.changeStreams`.
500
- - **Resilience** — `QueryOptions.signal` + `QueryOptions.retryPolicy`; shared `withRetry()` / `throwIfAborted()` helpers.
501
- - **`recordToFilter()`** on `/filter` — promoted from per-kit copies.
502
- - `STANDARD_REPO_OPTION_KEYS` gains `'traceId'`.
503
-
504
- ### Changed
505
-
506
- - `PurgeRetryPolicy` → **`RetryPolicy`** (rename, identical shape; was declared twice — now once). Clean break, no alias.
507
- - `AggregateOpsSupport` moved to `repository/capabilities.ts` (still re-exported from `/testing`).
508
-
509
- ## [0.5.0] - 2026-05-17
510
-
511
- ### Added — compliance-grade tenant cleanup primitive
512
-
513
- Cross-kit foundation for "what happens to this data on org-delete?" —
514
- GDPR right-to-be-forgotten, SOC 2 deletion timelines, HIPAA / PCI
515
- retention rules. Every kit (mongokit, sqlitekit, future pgkit) gets
516
- the same surface; arc's `cascadeDeleteForOrganization` runner composes
517
- on top.
518
-
519
- - **`StandardRepo.purgeByField?(field, value, strategy, options)`** — new optional method. Processes every row matching `field = value` under a declared strategy, chunked under the hood. Optional because not every store needs the surface; arc's cascade runner checks for the method at boot.
520
- - **`TenantPurgeStrategy`** discriminated union — four variants:
521
- - `{ type: 'hard' }` — permanent removal (GDPR right-to-be-forgotten).
522
- - `{ type: 'soft', deletedField?, deletedAtField? }` — recoverable; pairs with TTL indexes for eventual hard-purge.
523
- - `{ type: 'anonymize', fields }` — retain rows but overwrite declared fields (HIPAA / PCI / SOX-compatible).
524
- - `{ type: 'skip', reason }` — explicit opt-out with **mandatory** `reason` (compliance forcing function — silent skips are leaks).
525
- - **`TenantPurgeOptions`** — `batchSize`, `session`, `onProgress`, `signal`. Chunking is mandatory (10M-row tenants can't run as a single `deleteMany`); abort signal is checked between chunks (never mid-write); aborted runs return `ok: false` with cumulative `processed` count (at-least-once cleanup semantics).
526
- - **`TenantPurgeResult`** + **`TenantPurgeProgress`** — typed result envelope + per-chunk progress event.
527
-
528
- ### Added — kit-agnostic orchestrator (`runChunkedPurge`)
529
-
530
- The chunk-loop logic — abort handling, progress emission, error-wrapping into result envelope, natural-exit on non-full batch — is identical across kits. Extracting it here means a single bug fix lands for every kit, and the surface a new kit has to implement shrinks to ~80 lines.
531
-
532
- - **`runChunkedPurge(strategy, options, port)`** — pure orchestrator (130 lines, no I/O).
533
- - **`PurgePort`** interface — the driving port. Each kit implements a single closure: `purgeChunk(strategy, limit)` — one method lets each driver pick its own round-trip shape (sqlite hard-strategy compiles to one `DELETE … LIMIT`; a two-method `selectChunkIds` + `applyStrategy` split would force 2 round-trips per chunk for every kit).
534
- - **`WritingPurgeStrategy`** — strategy union with `skip` excluded (orchestrator handles `skip` before the port is consulted, so ports only see `hard` / `soft` / `anonymize`).
535
-
536
- Hexagonal pattern: orchestrator is the use-case, `PurgePort` is the driving port, each kit's port factory is the adapter. Adding a new strategy (e.g. `archive`) = one union member + one case per port. Adding a new kit = one port file + ~10-line method.
537
-
538
- ### Added — 8 cross-kit conformance scenarios
539
-
540
- In `src/testing/conformance.ts`, gated by the new `ConformanceFeatures.purgeByField?: boolean` flag. When both mongokit and sqlitekit pass the same scenarios, cross-kit byte-stability for tenant cleanup is provable:
541
-
542
- 1. `hard` removes every matching row, leaves others intact
543
- 2. `hard` empty match → `processed: 0`, `ok: true`
544
- 3. `anonymize` overwrites declared fields, keeps the row
545
- 4. `skip` is a no-op, returns reason
546
- 5. Chunking: `batchSize` honored, `onProgress` fires per chunk
547
- 6. Idempotent: re-running on the same tenant is a no-op
548
- 7. Scoping: only matching rows affected (cross-tenant safety)
549
- 8. Abort signal: stops between chunks, returns partial count + `ok: false`
550
-
551
- The `soft` strategy is intentionally NOT in the conformance suite — it requires writable `deleted` / `deletedAt` fields not present on the shared `ConformanceDoc`; each kit covers `soft` in its own integration tests.
552
-
553
- ### Migration notes
554
-
555
- - **Existing kits:** the new method is optional — kits don't break. mongokit 3.14.0 and sqlitekit 0.4.0 ship implementations; older kit versions continue to work, they just can't honor a `purgeByField` call.
556
- - **Existing hosts:** no breaking changes. Hosts using arc's `cascadeDeleteForOrganization` automatically pick up the new strategy surface once arc 2.16.0 lands.
557
- - **Build sync (workspace dev):** kits need `cp -r dist/* ../mongokit/node_modules/@classytic/repo-core/dist/` etc. after a workspace bump until npm publish.
558
-
559
- ## [0.4.0] - 2026-05-04
560
-
561
- ### Added — kit-shared building blocks (consolidation)
562
-
563
- - **`@classytic/repo-core/aggregate`** (new subpath) — kit-neutral aggregate IR helpers that every backend's compiler consumes identically: `normalizeGroupBy`, `validateMeasures`, `encodeAggCursor`, `decodeAggCursor`, `isKeysetMode`, `DecodedCursor`. mongokit + sqlitekit shipped byte-identical copies of these for the prior several releases; promoting them here keeps the IR contract honest. The driver-specific predicate builders (`buildKeysetPredicate` in mongokit, `buildKeysetHaving` in sqlitekit) stay kit-local.
564
- - **`@classytic/repo-core/plugins`** (new subpath) — kit-neutral plugin building blocks. Currently exports `payloadHasTenantField` (handles all 5 policy keys: data, dataArray, query, filters, operations) and `adminBypass` (skipWhen-compatible role-bypass factory). Both kits now consume these instead of shipping their own copies. Sqlitekit gains `adminBypass` for free as a side effect.
565
-
566
- ### ⚠️ BREAKING — `cache/deferred.ts` removed (use `Promise.withResolvers()`)
567
-
568
- - **`createDeferred()` and `Deferred<T>` no longer exported from `@classytic/repo-core/cache`.** Both were thin wrappers around `Promise.withResolvers()`, which Node 22+ ships natively (the package's platform floor). The cache engine's single-flight map now uses the native primitive directly with zero indirection.
569
- - **Migration:** if you imported them, replace `import { createDeferred } from '@classytic/repo-core/cache'` with `Promise.withResolvers<T>()`. Same shape (`{ promise, resolve, reject }`); behavior is identical.
570
-
571
- ### Fixed — security & robustness hardening
572
-
573
- - **DoS surface in URL parser**: `parseUrl` now drops parameter keys longer than 256 chars before bracket-regex parsing. Without the cap, a hostile 1MB key forced repeated full-string regex scans. Legitimate URL params don't approach the bound. (`src/query-parser/parse-url.ts`)
574
- - **Cursor payload type validation**: `decodeCursor` now type-checks every payload field, not just presence. A corrupted token shaped `{ v: { evil: true } }` previously slipped past the `'v' in p` guard and produced opaque errors downstream. (`src/pagination/cursor.ts`)
575
- - **Regex compile-per-doc on in-memory filter**: `matchFilter`'s `like` and `regex` cases now use a bounded LRU cache (256 entries) keyed by `(pattern, flags)`. Prior implementation compiled a fresh `RegExp` on every call — measurable cost when `asPredicate(filter)` runs over 100k docs. (`src/filter/match.ts`)
576
-
577
- ### Cache hash upgrade (djb2 → FNV-1a 64-bit)
578
-
579
- - **`buildCacheKey` now uses FNV-1a 64-bit** (was djb2 32-bit). At multi-tenant fleet scale (10k tenants × dozens of cached aggregations each), djb2's 32-bit space hit ~50% birthday-paradox collision around 65k distinct keys. FNV-1a 64-bit pushes that threshold to ~4B keys. Same call site, same key shape, same regex-compatible base-36 output.
580
- - **Operational note for deployment:** existing Redis entries hash differently after the swap, so cold cache for one TTL cycle post-deploy. The collection-version orphan path already handles this for write-driven invalidation.
581
-
582
- ### Cache layer — atomic counters, parallel invalidation, prefetch, timeout
583
-
584
- - **`CacheAdapter.increment(key, by, ttl)`** — optional atomic counter primitive. When the adapter ships it (Redis `INCRBY`, in-memory `Map`, future driver-native impls), `bumpModelVersion` produces strictly-monotonic versions across concurrent multi-pod writes — no lost bumps. Adapters without `increment` (Cloudflare KV, etc.) fall back to `get → max → set`; correct in single-pod, accepts a tiny race window in multi-pod (mitigated by `Date.now()` floor).
585
- - **Parallelized `invalidateByTags`** — fan-out reads + fan-out deletes via `Promise.all`. For Redis-backed adapters with pipelining, 5 tags × 100 keys completes in ~2 RTTs instead of 510. ~10× speedup on hot tags.
586
- - **`CacheEngine.prefetch(key, opts, fetcher)`** — TanStack-equivalent cache warming. Single-flight semantics: 100 concurrent prefetches for the same key run the fetcher exactly once. Returns cached on hit, fetches + stores on miss, dedupes via the engine's pending map.
587
- - **`withTimeout(adapter, { ms, onTimeout, onSlow })`** — adapter decorator that fail-fasts on slow backends. `onTimeout: 'miss'` (default) makes slow gets behave as cache misses (kit serves uncached); `'throw'` propagates `CacheTimeoutError`. `onSlow` callback for observability.
588
- - **`scheduleBackground`** is now a public export from `@classytic/repo-core/cache` — hosts can use the same cross-runtime primitive for their own post-response work.
589
-
590
- ### Cache layer — production hardening (TanStack-aligned) + cross-runtime
591
-
592
- Six gaps in the v1 unified cache layer fixed before any prod traffic:
593
-
594
- 1. **Single-flight on miss** — `CacheEngine.claimPending()` / `getPending()` / `resolvePending()` / `rejectPending()`. Concurrent misses for the same key wait on the first claimer's promise instead of running N redundant fetches. Cache-stampede prevention; TanStack `QueryClient`-equivalent.
595
- 2. **Per-scope version-bump** — `bumpModelVersion(model, scopeKey?)` and `getModelVersion(model, scopeKey?)`. Writes inside `org:abc` no longer invalidate `org:xyz`'s cached reads. Targeted invalidation; matches TanStack's "exact match" semantics.
596
- 3. **Cross-runtime SWR scheduling** — new `runtime.ts` exposes `scheduleBackground` that picks `setImmediate` on Node / Bun and `setTimeout(0)` on Cloudflare Workers / Deno Deploy / browser. Either way the callback fires after the current sync block + microtask queue, ensuring the user's response writes to the socket BEFORE the bg fetch's first await. (Old impl used `setImmediate` directly — `ReferenceError` on edge runtimes.)
597
- 4. **TTL-bounded tag index** — index entries inherit their cached entries' TTLs (capped at 24h). Old impl used `ttlSeconds: 0` ("never expire" in Redis); side-index grew unboundedly on hot tags.
598
- 5. **`error:<op>` rejects pending** — when the claimer's executor errors, the plugin's `error:<op>` hook rejects the deferred so single-flight waiters fail-fast. No hanging promises, no double-fetch on transient backend failures.
599
- 6. **Allowlist-per-op shape keys** — `DEFAULT_SHAPE_KEYS_BY_OP` maps each read op to the fields that actually affect result shape. Only those fields participate in the cache key. Replaces the prior denylist (which would silently include any new context field a kit added — exploding miss rates if e.g. `requestId` slipped through). Hosts can override per-op via `cachePlugin({ shapeKeysByOp })`.
600
-
601
- ### Code organization
602
-
603
- The unified plugin (`@classytic/repo-core/cache`) is now split into focused modules:
604
-
605
- ```
606
- cache/
607
- plugin/
608
- index.ts # cachePlugin factory + types + handle (~200 LOC)
609
- context.ts # typed context slots + extraction + shape-keys (~170 LOC)
610
- read-hooks.ts # before/after/error for read ops (~180 LOC)
611
- invalidation-hooks.ts # after for write ops (~60 LOC)
612
- swr.ts # background-refresh scheduler (~50 LOC)
613
- engine.ts # TTL + SWR + tag + version + single-flight (~220 LOC)
614
- runtime.ts # cross-runtime scheduleBackground (~50 LOC)
615
- ...
616
- ```
617
-
618
- Each module has one purpose. Replaces the prior 564-LOC `plugin.ts` mega-file.
619
-
620
- ### Added — `Deferred<T>` utility
621
-
622
- `createDeferred<T>()` exported from `@classytic/repo-core/cache` — a Promise plus its `resolve`/`reject` handles, externalized. Same primitive `Promise.withResolvers()` provides natively in Node 22+; we ship our own to keep the contract explicit and support older runtimes.
623
-
624
- ### Added — Unified cache layer (`@classytic/repo-core/cache`)
625
-
626
- One `cachePlugin({ adapter })` for every kit + arc + Express/Nest hosts. Replaces three independent SWR/TTL/tag implementations (mongokit's CRUD `cachePlugin` + aggregate `withAggCache`, sqlitekit's local `cachePlugin`, arc's `QueryCache`) with one canonical hook integration.
627
-
628
- #### Public surface (`@classytic/repo-core/cache`)
629
-
630
- ```ts
631
- import {
632
- cachePlugin, // hook integration — plugs into RepositoryBase
633
- CacheEngine, // direct SWR + TTL + tag flow over a CacheAdapter
634
- buildEnvelope, inspectEnvelope, type CacheEnvelope,
635
- buildCacheKey, extractScopeTags, type BuildKeyInput,
636
- appendKeyToTags, invalidateByTags as invalidateByTagsImpl,
637
- bumpModelVersion, getModelVersion,
638
- resolveCacheOptions, type CacheOptions, type ResolvedCacheOptions, type CacheReadResult,
639
- // already shipped:
640
- type CacheAdapter, createMemoryCacheAdapter, stableStringify,
641
- } from '@classytic/repo-core/cache';
642
- ```
643
-
644
- #### TanStack Query-shaped per-call options
645
-
646
- Same shape across CRUD + aggregate, kit-agnostic:
647
-
648
- ```ts
649
- {
650
- staleTime?: number; // seconds fresh
651
- gcTime?: number; // seconds retained past stale (default 60)
652
- swr?: boolean; // serve-stale + bg refresh
653
- tags?: readonly string[];
654
- bypass?: boolean;
655
- enabled?: boolean;
656
- key?: string; // explicit override
657
- }
658
- ```
659
-
660
- #### What the plugin does
661
-
662
- 1. Subscribes to `before:<op>` / `after:<op>` for every read op (`getById`, `getAll`, `getOne`, `getByQuery`, `count`, `exists`, `distinct`, `aggregate`, `aggregatePaginate`) — configurable via `enabled: [...]`.
663
- 2. Subscribes to `after:<op>` for every mutating op (`create`, `update`, `delete`, `claim`, ...) — configurable via `invalidating: [...]`. Bumps the model's version (orphans every cached read in O(1)) AND invalidates the model-tag (cross-aggregation invalidation).
664
- 3. Auto-injects scope tags (`org:<id>`, `user:<id>`) from `context.filter` so cross-tenant cache poisoning is structurally impossible.
665
- 4. Hooks register at `HOOK_PRIORITY.CACHE` (200) — multi-tenant + soft-delete (POLICY = 100) run first so their filter mutations land in the cache key.
666
- 5. Attaches `repo.cache` handle exposing `invalidateByTags(tags)`, `bumpModelVersion(model)`, `clear()`.
667
-
668
- #### Strictly-monotonic version bumps
669
-
670
- `bumpModelVersion` uses `max(Date.now(), previous + 1)` so same-millisecond writes (cache prime + write hit at the same ms) don't collide, fixing a real correctness gap the prior `Date.now()`-only impl had.
671
-
672
- #### `AggCacheOptions` is now an alias for `CacheOptions`
673
-
674
- Same shape across CRUD + aggregate. Old field names (`ttl`, `staleWhileRevalidate`) removed — migrate to `staleTime`, `swr`. Ecosystem packages (mongokit, sqlitekit, arc) all consume the unified type.
675
-
676
- #### Removed
677
-
678
- - `/aggregate-cache` subpath — superseded by the unified `/cache` plugin (which handles aggregate ops natively via the `before:aggregate` hook).
679
-
680
- #### Migration (kit + host)
681
-
682
- ```ts
683
- // Before — kit-specific cache plugins + constructor option
684
- new Repository(model, [cachePlugin({ adapter, ttlSeconds: 60 })], {}, {
685
- aggregateCache: adapter, // separate constructor option
686
- });
687
- repo.aggregate({ measures, cache: { ttl: 60, staleWhileRevalidate: true } });
688
-
689
- // After — one plugin, one shape
690
- new Repository(model, [
691
- multiTenantPlugin({ tenantField: 'orgId' }),
692
- cachePlugin({ adapter, defaults: { staleTime: 60, gcTime: 300, swr: true } }),
693
- ]);
694
- repo.aggregate({ measures, cache: { staleTime: 60, swr: true, tags: ['orders'] } });
695
- repo.getAll(filter, { cache: { staleTime: 30 } });
696
- await repo.cache?.invalidateByTags(['orders']);
697
- ```
698
-
699
- ### Added — `StandardRepo.claim()` and `claimVersion()` (atomic CAS, REQUIRED on the contract)
700
-
701
- Standardizes the canonical state-machine write that every domain package was hand-rolling on top of `findOneAndUpdate`:
702
-
703
- ```ts
704
- const claimed = await repo.claim?.(runId, { from: 'waiting', to: 'running' }, {
705
- lastHeartbeat: new Date(),
706
- workerId: 'worker-12',
707
- });
708
- if (!claimed) return; // someone else got it
709
- ```
710
-
711
- **Cross-kit portable.** Mongokit compiles to `findOneAndUpdate({ _id, status: from }, { $set: { status: to, ...patch } })`. SQL kits compile to `UPDATE x SET ... WHERE id = ? AND status = <from> RETURNING *`. Prismakit compiles to `prisma.x.updateMany({ where: { id, status: from }, data: ... })` followed by a `findUnique` when `count > 0`. Same input, same null-on-race semantics across every backend.
712
-
713
- **Pairs with `@classytic/primitives/state-machine`** — different layers:
714
- - `defineStateMachine()` answers "is `from → to` legal in the model?" (compile-time table + early throw)
715
- - `claim()` answers "did we win the transition vs concurrent writers?" (runtime null on race)
716
-
717
- The state field defaults to `'status'` (matches the convention across `streamline`, `@classytic/order`, `revenue`, `invoice`); pass `{ field: 'phase', from, to }` for state machines keyed off a different column.
718
-
719
- #### New types exported from `@classytic/repo-core/repository`
720
-
721
- - `ClaimTransition` — `{ field?, from, to, where? }` argument shape for `claim` (`where` is the compound-CAS predicate slot — see below).
722
- - `ClaimVersionTransition` — `{ field?, from: number | undefined, by?, where? }` argument shape for `claimVersion`. `from === undefined` is admitted for first-write CAS (matches docs whose version field is null OR missing).
723
-
724
- #### Added to `StandardRepo<TDoc>` — REQUIRED methods (not optional)
725
-
726
- ```ts
727
- claim(
728
- id: string,
729
- transition: ClaimTransition,
730
- patch?: Partial<TDoc>,
731
- options?: WriteOptions,
732
- ): Promise<TDoc | null>;
733
-
734
- claimVersion(
735
- id: string,
736
- transition: ClaimVersionTransition,
737
- update: Record<string, unknown>,
738
- options?: WriteOptions,
739
- ): Promise<TDoc | null>;
740
- ```
741
-
742
- **Required, not optional.** During pre-release dev iterations, `claim?` was optional as scaffolding while kits implemented. Both mongokit and sqlitekit ship them as concrete class primitives, and downstream domain packages (~10 in the classytic codebase) carry FSM verbs depending on them — none gracefully degrade. Required-on-the-contract removes the `if (repo.claim) { ... }` boilerplate at every call site and surfaces missing implementations at the conformance gate instead of at runtime.
743
-
744
- #### `ClaimTransition.where` — compound-CAS predicate
745
-
746
- Real-world audit (streamline, commission, yard, revenue, order, invoice): the bare `{ [idField]: id, [field]: from }` filter shape fits ~5% of atomic-claim sites in production. The other 95% carry compound predicates — paused guards, retry-time guards, heartbeat-staleness, sub-document `$elemMatch`, `$or` for missing-or-stale fields. Without a way to express those, `claim()` covered the textbook example but couldn't replace the hand-rolled CAS calls in production.
747
-
748
- `ClaimTransition.where` AND-merges arbitrary predicates alongside the canonical id + state-field match:
749
-
750
- ```ts
751
- const claimed = await repo.claim?.(runId, {
752
- from: 'waiting',
753
- to: 'running',
754
- where: {
755
- paused: { $ne: true },
756
- 'scheduling.retryAfter': { $lte: new Date() },
757
- },
758
- }, { lastHeartbeat: new Date() });
759
- ```
760
-
761
- Cross-kit notes:
762
- - Mongokit: ANDed into the `findOneAndUpdate` filter.
763
- - SQL kits: ANDed into the `WHERE` clause (raw column literals accepted; portable Filter IR is compiled).
764
- - Prismakit: merged as additional keys on the `where` object.
765
-
766
- Null-on-race semantics unchanged — if no doc matches the full compound filter (state OR any `where` predicate), `claim` returns `null`. The caller can't distinguish "lost race" from "guard predicate failed"; both mean "don't proceed."
767
-
768
- Driven by streamline's audit (1 of 21 sites fit the bare shape; 21 of 21 fit the compound shape). Same pattern across the other audited packages.
769
-
770
- #### `ClaimTransition.from` widened to `unknown | readonly unknown[]` — multi-source CAS
771
-
772
- Single-value `from` covers the textbook one-source transition (`waiting → running`). Real-world state machines also need to claim from one of multiple source states — commission's `voidRecord` / `markClawedBack` / `endAgreement` / `_transition` (4 sites), media-kit's `pending|processing → error` catch-block. `from` now accepts an array; kit compilers emit `[stateField] IN (...)` (SQL) or `[stateField]: { $in: [...] }` (mongo).
773
-
774
- ```ts
775
- // "From any non-terminal state to voided"
776
- await repo.claim?.(id, { from: ['pending', 'approved', 'sent'], to: 'voided' });
777
- ```
778
-
779
- Single-value `from` is unchanged (back-compatible). Array form is opt-in — pass an array to enable.
780
-
781
- **`from === to` is allowed** — the documented idempotent re-claim semantic. Yard's `reviseDeparture` writes `departed → departed` to atomically refresh the row's payload while asserting it hasn't moved on. The CAS still returns `null` if the row left the source state, so race-loss semantics hold.
782
-
783
- #### Migration
784
-
785
- Pre-0.4.0 callers wrote:
786
-
787
- ```ts
788
- const claimed = await repo.findOneAndUpdate(
789
- { _id: id, status: 'waiting' },
790
- { $set: { status: 'running', lastHeartbeat: new Date() }, },
791
- );
792
- ```
793
-
794
- Post-0.4.0:
795
-
796
- ```ts
797
- const claimed = await repo.claim?.(id, { from: 'waiting', to: 'running' }, { lastHeartbeat: new Date() });
798
- ```
799
-
800
- The old form keeps working — `claim()` is an additive optional method, not a rename.
801
-
802
- ## [0.3.0] - 2026-04-29
803
-
804
- ### Added — Aggregate pagination shapes
805
-
806
- - `AggregatePaginationResultCore<TDoc>` and `AggregatePaginationResult<TDoc, TExtra>` join `Offset*` / `Keyset*` as the third pagination shape every kit reports. Mirrors offset (page / total / pages / hasNext / hasPrev) with `method: 'aggregate'` discriminant. Mongokit's existing local `AggregatePaginationResult` (3.10.x) becomes redundant — to be deleted in mongokit 4.0.
807
- - `AnyPaginationResult<TDoc, TExtra>` — union over the three result shapes. Use as the input type to anything that converts repo results into HTTP envelopes.
808
-
809
- ### Added — HTTP wire envelopes
810
-
811
- The repository result shapes (`OffsetPaginationResult`, etc.) carry the `method` discriminant, so the corresponding HTTP wire envelope is just `{ success: true } & Result`. Adding the literal here closes the **server/client envelope mismatch** — arc's HTTP server was emitting flattened paginated responses without the `method` field while arc-next's typed responses required it.
812
-
813
- - `OffsetPaginationResponse<TDoc, TExtra>` = `{ success: true } & OffsetPaginationResult<TDoc, TExtra>`
814
- - `KeysetPaginationResponse<TDoc, TExtra>` = same for keyset
815
- - `AggregatePaginationResponse<TDoc, TExtra>` = same for aggregate
816
- - `BareListResponse<TDoc>` = `{ success: true; docs: TDoc[] }` for endpoints that don't paginate
817
- - `PaginatedResponse<TDoc, TExtra>` = union over all four. The discriminated-union contract is `success: true` literal first, `method` second — typed clients (arc-next, SDKs) narrow with `if (res.success && 'method' in res && res.method === 'offset')`.
818
-
819
- ### Added — `toCanonicalList()` runtime normalizer
820
-
821
- ```ts
822
- import { toCanonicalList } from '@classytic/repo-core/pagination';
823
-
824
- const result = await userRepo.getAll(query);
825
- reply.send(toCanonicalList(result)); // → PaginatedResponse<User>
826
-
827
- reply.send(toCanonicalList([u1, u2])); // → BareListResponse<User>
828
- ```
829
-
830
- The single point where an internal `Result` becomes an external `Response`. Three overloads route bare arrays / paginated results to the right wire shape; `TExtra` fields (mongokit's `warning?: string`, etc.) flow through.
831
-
832
- **Subtle behavior**: `success: true` is stamped *after* the spread, so a stale `success: false` accidentally present on the input cannot override the literal — paginated success path is always `success: true`. Tested.
833
-
834
- ### Added — `isPaginatedResult()` type guard
835
-
836
- Branches on the `method` discriminant rather than `Array.isArray`, so an empty paginated result still routes through the paginated branch. Used internally by `toCanonicalList`; exported for consumers writing custom envelope logic.
837
-
838
- ### Test delta
839
-
840
- 230 → 303 tests across 0.3.0. New coverage includes `tests/unit/pagination/canonical.test.ts` and the type-level coverage extensions in `result-types.test.ts` (35 tests landed with the aggregate / wire-envelope / `toCanonicalList` work), plus `tests/unit/repository/base-plugin-validation.test.ts` (6 tests for the `assertValidPlugin` guard).
841
-
842
- ### Added — `SchemaGenerator<TModel>` interface in `/schema`
843
-
844
- Canonical contract for repository kits' CRUD-schema generators. Mongokit's `buildCrudSchemasFromModel` and sqlitekit's `buildCrudSchemasFromTable` (and any future kit's equivalent) `satisfies SchemaGenerator<TKitModel>` at the call site, so arc's `MongooseAdapter.schemaGenerator` / `DrizzleAdapter.schemaGenerator` accept them by structural typing — no glue, no inheritance, no inline function signatures duplicated in every adapter.
845
-
846
- - `SchemaGenerator<TModel = unknown>` — `(model, options?, context?) => CrudSchemas | Record<string, unknown>`.
847
- - `SchemaGeneratorContext` — resource-level context threaded at boot (`idField`, `resourceName`).
848
- - `isSchemaGenerator(value)` — runtime predicate (arity 1-3 functions). Conservative — doesn't invoke.
849
-
850
- Each kit ships a compile-time conformance check (same playbook as mongokit's `RepositoryLike` conformance gate):
851
-
852
- ```ts
853
- const _conformance: SchemaGenerator<Model<unknown>> = buildCrudSchemasFromModel;
854
- ```
855
-
856
- Drift surfaces in the kit's typecheck immediately, before any consumer sees it.
857
-
858
- 10 new tests in `tests/unit/schema/generator.test.ts`. Total repo-core: 293 → 303.
859
-
860
- ### Added — `errors` module: canonical wire + throwable error contract
861
-
862
- `@classytic/repo-core/errors` is now the single source of truth for error contracts across the org. Two complementary shapes:
863
-
864
- - **`HttpError extends Error`** — the *throwable* shape. Plain `Error` with `status`, optional `code`, `meta`, `validationErrors`, `duplicate`. Kits classify their driver-specific errors into this shape; framework layers (arc) catch and serialize. Existing `HttpError` extended in 0.3 with `code?: string` and `meta?: Record<string, unknown>` (mongokit had these locally pre-3.12).
865
- - **`ErrorContract`** — the *wire* shape (RFC 7807 / Stripe-style). What gets serialized to JSON responses, dead-letter records, audit trails, inter-service envelopes. Flat top-level `code` / `message` / `status` matches the org-wide `{ success, ... }` envelope convention.
866
- - **`ErrorDetail`** — single field-scoped error (path / code / message). `ErrorContract.details` is `ReadonlyArray<ErrorDetail>`.
867
- - **`ERROR_CODES` + `ErrorCode`** — canonical lowercase + snake_case codes (`'validation_error'`, `'not_found'`, `'conflict'`, `'unauthorized'`, `'forbidden'`, `'rate_limited'`, `'idempotency_conflict'`, `'precondition_failed'`, `'internal_error'`, `'service_unavailable'`, `'timeout'`). Domain packages extend hierarchically (`'order.validation.missing_line'`).
868
- - **`toErrorContract(error)`** — converts any `Error` / `HttpError` / non-`Error` value to the canonical wire `ErrorContract`. `code` cascade: explicit `error.code` → status-derived → `'internal_error'`. Flattens mongokit-shaped `validationErrors` and `duplicate.fields` into the canonical `details[]` array.
869
- - **`statusToErrorCode(status)`** — well-known HTTP status → canonical code. Conservative mapping; unknown statuses fall through to `'internal_error'` so domain handlers explicitly opt in.
870
-
871
- Consumed by mongokit (drops local `HttpError`), arc (`ArcError implements HttpError` with `status` getter), and any future kit / service. Relocated from `@classytic/primitives/errors` (which had `ErrorContract` + `ERROR_CODES` but not the throwable contract) — same playbook as the pagination, tenant, and events relocations: errors are infrastructure-shaped, not domain primitives.
872
-
873
- 14 new tests in `tests/unit/errors/contract.test.ts`. Total repo-core: 279 → 293.
874
-
875
- ### Added — `tenant` subpath (canonical home for tenant scope contract)
876
-
877
- New subpath `@classytic/repo-core/tenant` ships:
878
- - `TenantConfig` — static config (`strategy`, `enabled`, `tenantField`, `fieldType`, `ref`, `contextKey`, `required`, `resolve`).
879
- - `TenantStrategy = 'field' | 'none' | 'custom'`, `TenantFieldType = 'objectId' | 'string'`.
880
- - `ResolvedTenantConfig` — the resolved-with-defaults shape returned by `resolveTenantConfig`.
881
- - `DEFAULT_TENANT_CONFIG` — sensible org-wide defaults (`tenantField: 'organizationId'`, `fieldType: 'objectId'`, `ref: 'organization'`, `required: true`).
882
- - `resolveTenantConfig(config?)` — normaliser; validates `'custom'` strategy requires `resolve`.
883
-
884
- Relocated from `@classytic/primitives/tenant` (which has been removed in primitives 0.3 cleanup). Tenant scope is **infrastructure-shaped** — describes how queries get scoped, not a domain primitive like Money or Address. Repo-core is its proper home: it sits next to `context`, `filter`, `hooks`, `schema`, `cache` — every other repository contract — and lets mongokit / sqlitekit / future kits consume it through the existing `@classytic/repo-core` peer dep without pulling primitives just for one type.
885
-
886
- **Custom tenancy escape hatch** unchanged: `strategy: 'custom'` + `resolve: (ctx) => filterShape` covers multi-field composites, region+partner shards, hash-derived filters, anything that doesn't fit `field === id`.
887
-
888
- 14 new tests in `tests/unit/tenant/resolve.test.ts` (ported from primitives' suite). Total repo-core: 265 → 279 tests.
889
-
890
- ### Added — schema-builder vocabulary
891
-
892
- - **`SchemaBuilderOptions.excludeFields`** — global field exclusion. Fields listed here are dropped from create / update / response schemas in one place. Equivalent to setting `create.omitFields`, `update.omitFields`, AND `response.omitFields` to the same list. Use for fields that should never appear in any HTTP-facing schema.
893
- - **`SchemaBuilderOptions.response`** with `omitFields?: string[]` — response-schema overrides. Drops extra fields from the response shape without marking them globally hidden.
894
- - **`CrudSchemas.response?: JsonSchema`** — optional response-shape schema. Includes server-set fields (`createdAt`, `updatedAt`, `_id`, immutable / readonly / systemManaged) since those ARE returned to clients. Only `fieldRules[field].hidden: true` strips automatically. Set `additionalProperties: true` so virtuals / computed fields pass through.
895
- - **`FieldRule.hidden?: boolean`** — strips the field from the response shape. Distinct from `systemManaged` (request-body concern). Use for passwords, secrets, internal scoring.
896
- - **`collectFieldsToOmit(options, 'response')`** — third purpose alongside `'create'` / `'update'`. Implements the response policy (only `hidden` + `excludeFields` + `response.omitFields`).
897
-
898
- These are the contracts mongokit 3.12 implements, arc 2.12's MongooseAdapter consumes, and any future kit (sqlitekit, prismakit) inherits for free.
899
-
900
- ### Hardened — `RepositoryBase` plugin-shape validation
901
-
902
- `RepositoryBase.use()` and the constructor's plugin loop now reject malformed plugin entries up front via `assertValidPlugin()`. The motivating field bug: `new Repository(Model, ['organizationId'], opts)` — passing a tenant-field string array where the constructor expected `plugins[]` — used to crash deep in the call site with `TypeError: plugin.apply is not a function`, cascade-failing every test that booted the app. The validator now throws a single descriptive `TypeError` at construction with the offending index and a hint about the common `tenantField`-in-the-wrong-slot mistake:
903
-
904
- ```
905
- [repo-core] Repository "Foo": plugin at index 0 has wrong type.
906
- Expected a function or { name, apply(repo) } object — got string 'organizationId'.
907
- Common cause: `new Repository(Model, [tenantField], opts)` — second argument must be a plugins array.
908
- ```
909
-
910
- Lock-in: `tests/unit/repository/base-plugin-validation.test.ts` (6 cases covering string/null/object-without-apply/function/object/post-construction `use()` paths).
911
-
912
- ### Migration — mongokit 4.0, arc 2.12, arc-next 0.6
913
-
914
- Three downstream changes drop their local copies and import directly:
915
-
916
- 1. **mongokit 4.0** — deletes its local `AggregatePaginationResult` declaration and `PaginationResult` union; consumers that imported them from `@classytic/mongokit` must switch to `@classytic/repo-core/pagination`. (Breaking.)
917
- 2. **arc 2.12** — `fastifyAdapter` calls `toCanonicalList()` once instead of inline-flattening offset and falling through keyset/aggregate as nested `data`. Closes a real wire-envelope-mismatch bug.
918
- 3. **arc-next 0.6** — adds `@classytic/repo-core` as peer dep, deletes its local `OffsetPaginationResponse` / `KeysetPaginationResponse` / `AggregatePaginationResponse` / `PaginatedResponse` types. Server and client now share one declaration — the `method` field asymmetry is impossible by construction.
919
-
920
- No breaking changes inside `@classytic/repo-core` itself — purely additive.
921
-
922
- ## [0.2.0] - 2026-04-22
923
-
924
- ### Added — Update IR (portable write-side primitive)
925
-
926
- - **New `@classytic/repo-core/update` subpath.** The write-side counterpart to `@classytic/repo-core/filter`. Plugins and arc's infrastructure stores compose an `UpdateSpec` once; each kit compiles it to its native shape.
927
- - **Types:** `UpdateSpec` (tagged union on `op: 'update'`, four buckets: `set` / `unset` / `setOnInsert` / `inc`), `UpdateInput` (union of `UpdateSpec` | kit-native `Record<string, unknown>` | Mongo pipeline `Record<string, unknown>[]`).
928
- - **Builders:** `update({ set, unset, setOnInsert, inc })` (root), `setFields`, `unsetFields(...f)`, `setOnInsertFields`, `incFields`, `combineUpdates(...specs)` (later-wins merge, `unset` de-duplicates).
929
- - **Guards:** `isUpdateSpec` (routes portable IR to the compiler), `isUpdatePipeline` (lets SQL kits short-circuit with `UnsupportedOperationError`).
930
- - **Compilers:** `compileUpdateSpecToMongo(spec)` emits `{ $set, $unset, $setOnInsert, $inc }`. `compileUpdateSpecToSql(spec)` emits a `SqlUpdatePlan` with `data` / `unset` / `inc` / `insertDefaults` buckets, leaving SQL generation (quoting, `ON CONFLICT`, parameter binding) to the kit.
931
- - **`StandardRepo.findOneAndUpdate` + `updateMany` widened to `UpdateInput`.** Accepts all three forms — portable `UpdateSpec`, kit-native record, Mongo aggregation pipeline. Kits dispatch with `isUpdateSpec`. The existing raw-record and pipeline paths remain unchanged; the IR is purely additive so consumers don't need to migrate. Arc's infrastructure stores (outbox, idempotency, audit) will switch to the IR over a subsequent release to close the "Mongo-shaped store" gap flagged in the April 2026 cross-surface review.
932
-
933
- **Motivation (Arc April 2026 review):** arc's `EventOutbox`, `IdempotencyStore`, and `AuditStore` adapters use Mongo operator records (`$set`, `$inc`, `$unset`, `$setOnInsert`, `$or`, `$lte`, ...) directly against `RepositoryLike.findOneAndUpdate`. That works on mongokit but fails on sqlitekit — whose `findOneAndUpdate` treats `data` as flat column overwrites and would literally set a column named `$set`. The Update IR closes the gap without forcing every kit to ship its own Mongo-operator compatibility layer.
934
-
935
- **Rationale for scope:** the IR covers the subset every backend supports (atomic set / unset / inc / insert-default). Kit-native features — Mongo `$push`/`$pull`/`$addToSet`, aggregation pipeline updates, Postgres `jsonb_set`, SQL `CASE` expressions — stay on the kit-native path via `UpdateInput`'s raw-record and pipeline forms. No lowest-common-denominator bloat; no feature loss for kits that already offer more.
936
-
937
- **Test delta**: 193 → 230 tests (37 new across `tests/unit/update/builders`, `/guard`, `/compile`).
938
-
939
- ### Changed — breaking: `StandardRepo` write signatures
940
-
941
- `StandardRepo.findOneAndUpdate(filter, update, ...)` and `updateMany(filter, data, ...)` — the second parameter is now typed `UpdateInput` (was `Record<string, unknown> | Record<string, unknown>[]` and `Record<string, unknown>` respectively). Every call site that compiled against 0.1.0 keeps compiling: `Record<string, unknown>` and `Record<string, unknown>[]` are subtypes of `UpdateInput`. The break is on the **implementer** side — any kit that declared only the old parameter type no longer structurally satisfies `StandardRepo` under strict contravariance. mongokit 3.11.0 and sqlitekit 0.1.1 already ship with the widened signatures; third-party kits need to widen before bumping their `@classytic/repo-core` peer dep.
942
-
943
- ### Changed — breaking: `updateMany` + `deleteMany` promoted to required members of `StandardRepo`
944
-
945
- Both methods were optional (`updateMany?` / `deleteMany?`) in 0.1.0; they're required in 0.2.0. Rationale: every real backend has a native bulk-update and bulk-delete primitive, and arc's infrastructure stores (outbox, idempotency, audit cleanup) assume both are callable without feature-detection. Leaving them optional invited the "forgot to wire `batchOperationsPlugin`" runtime `TypeError` footgun that earlier releases of mongokit shipped — with the promotion, the type system catches missing implementations at the kit boundary.
946
-
947
- **Impact**:
948
- - **Kits**: any kit declaring `class FooRepo<T> implements StandardRepo<T>` must provide `updateMany` and `deleteMany` or fail to compile. mongokit 3.11.0 and sqlitekit 0.1.1 both ship these as class primitives, so their conformance stays green.
949
- - **Consumers of `RepositoryLike<T> = MinimalRepo<T> & Partial<StandardRepo<T>>`** (arc's pattern) are unaffected — `Partial` reimposes optionality for feature detection at the arc adapter boundary. `if (repo.updateMany)` guards keep working.
950
- - `bulkWrite` stays optional — the mongoose-shaped `BulkWriteOperation` has no clean SQL analogue, and every kit would ship an uninteresting fan-out wrapper otherwise.
951
-
952
- ### Naming — `UpdateInput` collision with mongokit
953
-
954
- `@classytic/repo-core/update` exports `UpdateInput` as the union `UpdateSpec | Record<string, unknown> | Record<string, unknown>[]`. `@classytic/mongokit` currently **also** exports a type named `UpdateInput<TDoc> = Partial<Omit<TDoc, '_id' | 'createdAt' | '__v'>>` — a completely different, document-typed shape used by `repo.update(id, data)`. If you write `import { UpdateInput } from '@classytic/mongokit'`, you get mongokit's generic; if you write `import type { UpdateInput } from '@classytic/repo-core/update'`, you get the union. Both names may appear in the same consumer file — import at least one with an alias (`import type { UpdateInput as UpdatePatch } from '@classytic/mongokit'`). mongokit will rename its local type in a follow-up release to close the collision permanently.
955
-
956
- ### Added
957
- - Phase 0 scaffold: package.json, tsconfig, tsdown, biome, vitest (4-tier), knip
958
- - `@classytic/repo-core/hooks` — `HOOK_PRIORITY` constants + `HookPriority` type
959
- - `@classytic/repo-core/operations` — `CORE_OP_REGISTRY`, `extendRegistry`, `listOperations`, `mutatingOperations`, `readOperations`, `operationsByPolicyKey`, `describe`; 17 core ops, driver-free
960
- - `@classytic/repo-core/errors` — `HttpError`, `createError`, `isHttpError`, `conservativeMongoIsDuplicateKey`, `toDuplicateKeyHttpError`
961
- - `@classytic/repo-core/pagination` — `encodeCursor`/`decodeCursor` (URL-safe base64, mongokit ≤3.x compat), `validateCursorSort`, `validateCursorVersion`, `normalizeSort`, `validateKeysetSort`, `invertSort`, `getPrimaryField`, `validateLimit`, `validatePage`, `shouldWarnDeepPagination`, `calculateSkip`, `calculateTotalPages`
962
- - INFRA.md tracking doc + 4-tier test structure per monorepo testing-infrastructure.md
963
- - 74 unit tests across 6 files, full suite runs in ~360 ms
964
- - `@classytic/repo-core/filter` — Filter IR types (`Filter` discriminated union), combinators (`eq`, `ne`, `gt`/`gte`/`lt`/`lte`, `in_`/`anyOf`, `nin`/`noneOf`, `like`, `regex`, `exists`, `and`, `or`, `not`/`invert`), constants (`TRUE`, `FALSE`), runtime guard (`isFilter`), traversal (`walkFilter`, `mapFilter`, `collectFields`), in-memory evaluator (`matchFilter`, `asPredicate`). Boolean absorbing/identity elimination baked in.
965
- - `@classytic/repo-core/repository` — arc-aligned contract types: `MinimalRepo<TDoc>` (5-method floor), `StandardRepo<TDoc>` (recommended surface), option/result types (`QueryOptions`, `WriteOptions`, `DeleteOptions`, `FindOneAndUpdateOptions`, `DeleteResult`, `DeleteManyResult`, `UpdateManyResult`, `PaginationParams`), `RepositorySession`, `InferDoc<R>`.
966
- - 43 additional unit tests (builders, walk, match) bringing total to 117.
967
- - **Filter IR expansion** — sugar builders: `between`, `startsWith`, `endsWith`, `contains`, `iEq`, `isNull`, `isNotNull` (desugar to existing ops); new `raw` escape-hatch op for driver-native fragments (e.g. pgvector `<=>`, SQLite JSON1 path, Mongo `$geoWithin`).
968
- - `@classytic/repo-core/query-parser` — URL → `ParsedQuery<Filter>` driver-agnostic parser. Bracket grammar (`field[gte]=18`, `field[in]=a,b`, `field[contains]=text`). Shared types (`ParsedQuery`, `ParsedSort`, `ParsedSelect`, `ParsedPopulate`, `QueryParserOptions`, `BracketOperator`) consumed identically by every kit and both frontends (arc-next, fluid).
969
- - 36 more unit tests covering sugar builders + QueryParser. Total: **153 tests, 11 files, green on vitest 4**.
970
- - Upgraded to **vitest 4.1**, **typescript 6.0**, **biome 2.4.12**. Vitest config migrated to new `pool` / `fileParallelism` top-level API.
971
- - **M3 landed: `RepositoryBase` abstract class** at `@classytic/repo-core/repository`. Owns `HookEngine`, plugin installation, context builder, `_emitAfter` / `_emitError`, and the `_cachedValue` cache-short-circuit helper. Kits extend it instead of reinventing the hook layer.
972
- - **M4 landed: 5 portable plugins** — `@classytic/repo-core/plugins/timestamp`, `/multi-tenant`, `/soft-delete`, `/audit`, `/cache`. All Filter-IR-native. Multi-tenant + soft-delete inject scope via `and(existing, eq(...))` / `and(existing, isNull(...))` — no Mongo-specific `$`-operators. Cache includes pluggable `CacheAdapter` interface + reference `createMemoryCacheAdapter`.
973
- - **Tightened the scope rule for plugins** — skipped observability / validation-chain / field-filter / cascade / custom-id. Rule: a plugin lives in repo-core only if every backend needs it AND no backend provides it natively. The skipped ones are either arc's job (field-filter), host cookbook (observability, custom-id), zod's job (validation-chain), or SQL-native (cascade).
974
- - **`StandardRepo.withTransaction` signature fixed** — was `(session) => T`, mongoose leak. Now `(txRepo: this) => T` — caller writes `await txRepo.create(...)`, never touches session. SQL / Prisma kits bind the tx connection to a new repo; mongokit returns a session-threaded proxy.
975
- - `QueryOptions.session` re-documented as mongoose-specific.
976
- - `RepositoryBase.on` / `off` now generic over listener-data type so typed plugins (`(ctx: RepositoryContext) => void`) don't need casts.
977
- - **HookEngine** exposed at `@classytic/repo-core/hooks` — `DEFAULT_LISTENER_PRIORITY`, `HookEngine` class, `HookListener`, `HookMode`, `PrioritizedHook`, `EventPhase` types.
978
- - **Context subpath** at `@classytic/repo-core/context` — `RepositoryContext` type exposed independently for plugin authors.
979
- - **`HookEngine.listeners()`** — read-only snapshot of the listener registry (frozen buckets). Lets kits expose a back-compat `_hooks: Map<event, PrioritizedHook[]>` getter without handing out mutable internal state. Used by mongokit 3.10's read-through `_hooks` shim.
980
- - **`RepositoryBase._buildContext` always awaits `before:*` hooks** regardless of engine mode — policy plugins must mutate context synchronously before the driver call fires. After- and error-hooks still honor `hooks: 'sync'` for fire-and-forget observability. Previous behavior (fire-and-forget in sync mode) would let driver calls race ahead of tenant/soft-delete scope injection; tracked as a latent bug surfaced by the mongokit 3.10 migration.
981
-
982
- ### Changed — plugins move out, primitives move in
983
-
984
- - **All 5 plugins deleted from `@classytic/repo-core/plugins/*`** — `timestamp`, `soft-delete`, `multi-tenant`, `audit`, `cache` no longer ship from this package. Rationale: end-users install a kit, never repo-core directly, so plugins belong in the namespace users actually import. Each kit (mongokit, sqlitekit, pgkit, prismakit) owns its own plugin implementations, which lets each use driver-native features (mongoose native timestamps, SQLite triggers, Postgres `now()`, Prisma `@default`) instead of a lowest-common-denominator JS emulation.
985
- - **New `@classytic/repo-core/cache` subpath** — the plugin-composition primitives that every kit's cachePlugin shares:
986
- - `CacheAdapter` interface (get / set / del / delByPattern)
987
- - `stableStringify` — deterministic JSON keying for cache buckets
988
- - `createMemoryCacheAdapter` — reference in-memory adapter for tests + single-process apps
989
- - **New scope helpers in `@classytic/repo-core/filter`** — `buildTenantScope(existing, tenantField, tenantId)` and `mergeScope(existing, scope)`. Every policy plugin (multi-tenant / soft-delete / org-boundary) AND-s a predicate into an existing filter while handling three shapes (undefined / Filter IR / flat record). Lifted into `/filter` so each kit's plugin composes the same merge semantics.
990
- - **Architectural principle codified** — "Repo-core is invisible infrastructure. End-users install a kit; repo-core exists for kit authors." See INFRA.md §3.
991
-
992
- ### Arc integration review — 2026-04-19
993
-
994
- Changes landed in response to the Arc 2.10 maintainer's end-to-end integration report (see `ARC_INTEGRATION_REPORT.md`). All three non-blocking enhancements adopted; sqlitekit-side blockers are tracked on the sqlitekit package, not here.
995
-
996
- - **`OffsetPaginationResult<TDoc, TExtra>` + `KeysetPaginationResult<TDoc, TExtra>`** — added an optional second generic so kits can surface typed extras alongside the core envelope (mongokit emits `warning?: string` on deep-page reads, pgkit could surface `queryPlan`, sqlitekit could surface vacuum hints). Defaults to `Record<string, never>` so existing consumers (`OffsetPaginationResult<User>`) see zero behavioral change. Both types also export their core interface (`OffsetPaginationResultCore` / `KeysetPaginationResultCore`) for StandardRepo contract references. The `method` discriminant carries through the intersection so `if (result.method === 'offset')` narrowing keeps working.
997
- - **`HOOK_EVENTS` constant + `HookEventName` type** at `@classytic/repo-core/hooks` — canonical string-constant registry for every `before:* / after:* / error:*` event across the MinimalRepo + StandardRepo op set (17 ops × 3 phases = 51 events). Plugin authors subscribe via `HOOK_EVENTS.BEFORE_CREATE` instead of raw strings so typos become compile errors instead of silent no-ops. Kits with additional native ops (mongokit's `aggregate` / `bulkWrite`) compose their own extended constant on top. Cross-kit plugins written against `HOOK_EVENTS` work identically on every kit for the shared op set.
998
- - **`CacheAdapter.clear?(pattern?)`** replaces the previous `delByPattern?(pattern)` — aligns with mongokit's `CacheAdapter` and Arc's `CacheStore` so one Redis / KV / Memcached implementation plugs into every consumer. `clear()` with no argument wipes everything; `clear('prefix:*')` is glob-matched. `createMemoryCacheAdapter` reference impl updated. Breaking change for anything calling `adapter.delByPattern` directly — sqlitekit's cache plugin (the only in-tree caller) migrated in the same commit.
999
- - **`CacheAdapter.delete(key)`** — renamed from `del(key)` for consistency with JavaScript's native `Map.delete` / `Set.delete`, `MinimalRepo.delete(id)` in this same package, arc's `RepositoryLike.delete`, and every higher-level cache library (Keyv, etc.). Redis clients keep their own `.del()` — the adapter implementation translates. Applied across `@classytic/repo-core/cache` (interface + `createMemoryCacheAdapter`) and `@classytic/mongokit` (its own `CacheAdapter` type + `createMemoryCache` reference impl + every test adapter). The rename arrived **before first publish**, so no migration cost for external consumers — it's simply the shipping name.
1000
- - **TTL unit stays seconds** (`ttlSeconds`) — matches Redis `SET EX seconds` and mongokit's existing `ttl` semantics. Arc's `ttlMs` was the outlier; the Arc team agreed to align on seconds.
1001
- - **Sync-or-async return types preserved** on `CacheAdapter` — memory-backed adapters return synchronously without a microtask hop; Redis adapters return Promises. Consumers `await` either way at no runtime cost.
1002
-
1003
- **Test delta**: 153 → 177 tests (24 new covering HOOK_EVENTS exhaustiveness, pagination TExtra narrowing, and CacheAdapter + stableStringify round-trip).
1004
-
1005
- ### Unified `withTransaction` contract — mongokit caught up
1006
-
1007
- The `StandardRepo.withTransaction` contract at `@classytic/repo-core/repository` has always specified `fn: (txRepo: this) => Promise<T>` — the bound-tx shape sqlitekit has implemented since 0.1. Mongokit 3.9 deviated from the contract and passed a raw `ClientSession` instead. Mongokit 3.10 fixes that: its `withTransaction` now hands over a session-threaded proxy repository matching the canonical signature. Cross-kit plugins and apps that depend on `StandardRepo.withTransaction` now work identically against mongokit and sqlitekit — one contract, no kit-specific branches.
1008
-
1009
- The contract docstring in `src/repository/types.ts` was already accurate; this is the mongokit-side implementation catching up. See `@classytic/mongokit` 3.10 release notes for the migration diff — this is a **breaking change for mongokit 3.x users** but repo-core's shape is unchanged.
1010
-
1011
- ### Consumed by
1012
-
1013
- - **`@classytic/mongokit`** — `Repository extends RepositoryBase`; hook engine, plugin-order validator, and `HOOK_PRIORITY` sourced from repo-core. Ships its own Mongo-optimized plugins (unchanged from 3.9).
1014
- - **`@classytic/sqlitekit`** — extends `RepositoryBase`; ships its own SQLite-optimized plugins at `@classytic/sqlitekit/plugins/{timestamp,soft-delete,multi-tenant,audit,cache}`. Imports `CacheAdapter` + `stableStringify` + `buildTenantScope` from repo-core.
1
+ # Changelog
2
+
3
+ All notable changes to `@classytic/repo-core` are documented here.
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [0.29.0] - 2026-09-23
8
+
9
+ ### ⚠ Changed — ONE list-query grammar, held to by every parser (`./query-parser`)
10
+
11
+ The URL grammar is now an explicit contract in repo-core, and arc's `ArcQueryParser` and
12
+ mongokit's `QueryParser` read requests through it, so a query means the same thing everywhere.
13
+ Before, the three parsers disagreed on 32 of 43 probed query strings. A few disagreements were
14
+ security holes (`$where` passing through `parseUrl`, malformed keys dropped), and some silently
15
+ returned wrong rows (date ranges compared as strings, `007` read as `7`).
16
+
17
+ - **`readFilterClauses` / `clausesToFilter`**: keys are `field` or `field[op]` (a dot path).
18
+ Operators are closed: `eq ne gt gte lt lte in nin exists contains startsWith endsWith ieq
19
+ regex`, plus `like` (= `contains`), `between=a,b` and `options` (regex flags). A kit adds its
20
+ own via `extensionOperators`.
21
+ - Text operators match LITERAL text case-insensitively; only `regex` is a pattern, and an unsafe
22
+ one is refused.
23
+ - `ne` / `nin` / `exists` follow the IR: null and missing never match a value.
24
+ - Membership is a union: `status=a&status=b`, repeated `[in]` and `eq`+`in` become one `in`.
25
+ - An empty value is no filter.
26
+ - **`coerceQueryValue`** replaces `coerceValue` / `coerceList`. A declared type is exact, and a
27
+ value that doesn't fit is refused. Without one: `null`, `true`/`false`, safe numbers without
28
+ leading zeros (15 chars max for equality, any length for a range bound), and ISO dates for
29
+ range operands only.
30
+ - **`readPageRequest` / `readSort` / `readSelect` / `readSearch`**:
31
+ - `limit` and `page` are positive integers; a limit over the cap is clamped.
32
+ - An invalid or disallowed sort/select field is refused, and an over-long search is refused,
33
+ never truncated. Sort/select accept commas or Mongoose's spaces.
34
+ - **`QueryGrammarError`** (400, `INVALID_QUERY_INPUT`, `validationErrors[0].path`) carries a
35
+ `kind` of `syntax` | `policy` | `value`, so a lenient parser can relax allowlists without
36
+ tolerating smuggled operators. `onInvalid` is drop mode, and structural refusals reach it too.
37
+ - **`parseUrl`** is rebuilt on the grammar: allowlists refuse rather than drop, populate `match`
38
+ is field equality only, and `maxFilterDepth` is removed (the flat grammar has no nesting to
39
+ bound). The default `maxLimit` is 1000, matching arc and mongokit.
40
+ - **`filter`** is a reserved param (the envelope).
41
+
42
+ ### Added — `runQueryGrammarConformance` (`./testing`)
43
+
44
+ A semantic suite: one fixture (nulls, missing fields, codes, dates, `.` and `%` in text) and
45
+ every case must select the same rows or be refused with a 400. arc and mongokit run it, mongokit
46
+ also against a real MongoDB, and sqlitekit against a real SQLite. A new parser passes by agreeing
47
+ on RESULTS. `unsupportedOperators` lets a backend that cannot run an operator (SQLite without
48
+ REGEXP) be held to REFUSING it with a 400 instead.
49
+
50
+ ### Fixed — the in-memory matcher disagreed with every kit's compiler
51
+
52
+ - `matchFilter`: `ne` / `nin` now exclude null and missing (SQL three-valued logic, pinned by
53
+ `runStandardRepoConformance`), and `eq null` matches missing as well as null. Before, an
54
+ in-memory policy check could admit a row the same filter excluded in the database. `in` with a
55
+ `null` member likewise matches a missing field (IS NULL), as Mongo and SQL do.
56
+ - `matchFilter`'s LIKE now honours the `\` escape every kit uses, so `contains('note', '50%')`
57
+ matches the literal `%`. `escapeLikePattern` escapes `\` itself.
58
+ - `policyRecordToFilter` keeps the Mongo record dialect's own meaning: `$ne: v` becomes
59
+ `not(eq)` (a missing field matches, as in Mongo). A `$nin` listing `null` becomes the strict
60
+ IR `nin`, which compiles back to a single `$nin`.
61
+
62
+
63
+ ### Added — the wire error-code catalog (`./errors`)
64
+
65
+ `ARC_ERROR_CODES` and `ARC_REASON_CODES` join `ERROR_CODES` in `src/errors/codes.ts`: every code
66
+ arc puts on `ErrorContract.code`, owned by the contract package so a client SDK reads the wire
67
+ vocabulary without depending on the server. Arc emits from these constants and its test suite
68
+ fails on an uncatalogued `arc.*` literal. `DUPLICATE_KEY_DETAIL_CODE` names the `details[].code`
69
+ `toErrorContract` already emitted. `ERROR_CODES` moved out of `types.ts` (same export path).
70
+
71
+ ### Added — `assessRegex` / `escapeRegex` (`./query-parser`): the one ReDoS analyser
72
+
73
+ Structural, not a regex over the regex: the pattern is walked with a group stack, so a repeated
74
+ group containing a VARIABLE repetition or an alternation — `(a+)+`, `(a*)*`, `(.*)*`, `(a|aa)+` —
75
+ is refused however it is spelled, as are backreferences, more than 20 unbounded quantifiers, a
76
+ complexity budget (more than 8 groups, more than 10 alternations, quantifiers × groups over 40)
77
+ and invalid syntax. `(a{2})+` is allowed (a fixed count is unambiguous). `parseUrl` drops an
78
+ unsafe `regex` leaf; mongokit's and arc's parsers now use it instead of their own heuristics,
79
+ which both missed `(a*)*`.
80
+
81
+ ### Fixed — invalidation could be undone by timing
82
+
83
+ - `createTtlMemo`: a load in flight when `invalidate()` ran wrote its superseded result back, and a
84
+ `get` after the invalidation could join that stale load. Slots now carry a generation, so an old
85
+ load writes where nothing reads.
86
+ - `addToSet` kept a set's CREATION expiry (`NX`), so a tag index could expire while newer tagged
87
+ entries lived on and tag invalidation missed them. The contract is now `GT` — extend, never
88
+ shorten (Redis ≥ 7: `EXPIRE key ttl GT`) — and the GET/SET fallback refreshes a re-cached
89
+ entry's index too.
90
+
91
+ Pinned in `tests/unit/cache/invalidation-races.test.ts`.
92
+
93
+ ### ⚠ Fixed — `stableStringify` / `contentHash` collided on dates and regexes
94
+
95
+ Every `Date` serialised as `{}` (it has no enumerable keys), so two payloads differing only by a
96
+ date had the SAME `contentHash` — contradicting its own contract — and every `RegExp` collided the
97
+ same way in cache keys. It now has wire semantics: `toJSON` applied (a `Date` is its ISO string, an
98
+ ObjectId its hex), `undefined` absent, a `RegExp` as `{"$regex","$options"}`, and keys ordered by
99
+ code unit instead of `localeCompare`. `fingerprintRequest` already normalised its input and is
100
+ unchanged. Digests of values holding dates, regexes or ObjectIds change once.
101
+
102
+ ### Fixed — single-flight could hand one scope's result to another
103
+
104
+ `CacheEngine`'s in-flight map was keyed by cache-key alone while the STORE was resolved per scope
105
+ (`adapter: () => requestScopedCache()`), so two concurrent reads of one key in different scopes
106
+ coalesced and the second received the first's result. In-flight fetches are now partitioned by
107
+ the resolved adapter, and a read with no store in scope (or bypassed) never joins another
108
+ caller's fetch. Dedup within one scope is unchanged. Pinned in
109
+ `tests/unit/cache/single-flight-scope.test.ts`.
110
+
111
+ ### Added — `@classytic/repo-core/idempotency`: run a command at most once per key
112
+
113
+ The one claim contract for every layer, beside `./lock` for the same reason: the store
114
+ contract is driver-free and every kit already depends on this package. Kernels, spine modules,
115
+ arc and hosts had kept at least four claims tables, each re-deriving the decision.
116
+
117
+ - `runIdempotent({ store, identity, requestFingerprint, execute, … })` — claim → execute →
118
+ complete. Outcomes `executed | replayed | in_flight | exhausted`; the same key with a
119
+ different body throws `FINGERPRINT_MISMATCH`; a terminal failure replays as
120
+ `IdempotentReplayError`. `execute` gets `{ progress, context, checkpoint }` — recovery points
121
+ a takeover resumes from; `checkpoint(progress, { session })` commits one inside the side
122
+ effect's own transaction. `classifyFailure` → `terminal | transient | ambiguous` (ambiguous
123
+ keeps the claim and lapses its lease now). `maxAttempts` → `exhausted`. `storeOptions.session`
124
+ joins the caller's transaction.
125
+ - `IdempotencyClaimStore` — `get`, `insert` (iff absent), `swap` / `release` (iff the in-flight
126
+ lease matches), `listLapsed` (for sweeps). `createMemoryIdempotencyStore()` is the reference.
127
+ - `runIdempotencyStoreConformance` / `idempotencyStoreCases` (`./testing`) — every kit's store
128
+ runs it; its concurrency cases reject a read-then-write store.
129
+ - `decideClaim`, `identityKey` (code-point ordered — never locale-sensitive), `fingerprintRequest`
130
+ (`contentHash` of the wire form; `undefined` dropped, `toJSON` honoured, refuses past 100 levels
131
+ with `UNFINGERPRINTABLE`).
132
+
133
+ ### Added — `KeysetPaginationResultCore.end`
134
+
135
+ The cursor at a page's LAST row, minted whether or not more rows exist. Feed it back as
136
+ `after` to resume later: a change feed that walked to its end (`next: null`) continues from
137
+ `end` and reads only what changed since, instead of re-reading everything. Optional —
138
+ absent means the kit does not mint it.
139
+
140
+ ### Fixed — `fieldRules` value constraints on ARRAY fields
141
+
142
+ `mergeFieldRuleConstraints` wrote `enum`, `pattern`, `minLength`, `maxLength`,
143
+ `min` and `max` onto the property regardless of its type. On an array property
144
+ that is wrong in two directions, and neither one throws:
145
+
146
+ - **`enum` refused every write.** It compares the WHOLE array to each member, and
147
+ a list of strings never equals a string. A body that omitted the field was
148
+ refused too, with an error naming a field the caller never sent. This made an
149
+ admin settings screen unable to save a single row.
150
+ - **`pattern` / `minLength` / `maxLength` / `min` / `max` validated nothing.**
151
+ They are string and number keywords, and JSON Schema ignores them on an array —
152
+ so a rule read as enforced while checking nothing. A typed-in email address was
153
+ never validated at the API.
154
+
155
+ Value constraints now land on the ELEMENT schema of an array (every position of a
156
+ tuple `items`, every array branch of an `anyOf`), and an array with no `items`
157
+ gets one so the constraint is never dropped. `description` and `nullable` still
158
+ describe the field itself: a nullable array may be `null`, its elements may not.
159
+
160
+ `min` / `max` bound each element's VALUE, not the item count — one meaning per
161
+ keyword, rather than one that depends on a type the author never wrote.
162
+
163
+ **Behaviour change for every kit** (mongokit, sqlitekit, pgkit, mysqlkit): array
164
+ fields carrying a `pattern`/`minLength`/`maxLength`/`min`/`max` rule are now
165
+ actually enforced, so a write that previously slipped through may be refused.
166
+ That write was always invalid by the rule's own definition.
167
+
168
+ This function had no tests. It now has 16, compiled against a validator rather
169
+ than compared as shapes — a schema can look right and still accept what it
170
+ exists to refuse.
171
+
172
+ ## [0.28.0] - 2026-09-14
173
+
174
+ ### Changed — BREAKING: `RetryPolicy.shouldRetry` no longer defaults to retrying everything
175
+
176
+ `shouldRetry` defaulted to `() => true`, with a comment conceding it was unsafe
177
+ and asking callers to pass their own. That is a documented hazard, not a fence:
178
+ a policy added for network blips also re-ran the write on a duplicate key, a
179
+ validation failure and a permission denial — three times, with backoff. Against
180
+ a slow-but-succeeding server and a non-idempotent write, that is a double write.
181
+
182
+ The default is now **`isTransientError`** (exported from `./repository`): retry
183
+ a failure that MAY not have happened — failover, write conflict, lock timeout,
184
+ socket error — never one the server answered deterministically. A 4xx-shaped
185
+ `statusCode` is treated as final, since `HttpError` carries one and every kit
186
+ maps validation and permission failures onto it.
187
+
188
+ **Migration:** a caller relying on retry-everything passes `shouldRetry: () => true`
189
+ explicitly. The point is that it is now a decision rather than an inheritance.
190
+ Tests exercising retry MECHANICS should pass a predicate too, so they stop
191
+ depending on how a generic `Error` happens to be classified.
192
+
193
+ ### Added
194
+
195
+ - **`resumeToken` on `ChangeEvent`, `startAfter` on `WatchOptions`.** `watch()`
196
+ already accepted a resume token but a consumer had no way to obtain one, so
197
+ the documented at-least-once-across-restarts contract was unfulfillable.
198
+ Persist the last event's `resumeToken` and hand it back as `resumeAfter` (or
199
+ `startAfter`, which also resumes past an invalidate event) to continue from
200
+ that point. Additive — a kit whose feed is not resumable leaves the field
201
+ absent.
202
+
203
+ - **`AggRequest.countDistinctStrategy`** — `'accumulator'` (default) or
204
+ `'grouped'`. The default holds every distinct value of a group in that
205
+ group's accumulator, so memory grows with the data and MongoDB caps it at
206
+ 100MB; `'grouped'` pre-groups by the distinct field so each value becomes a
207
+ row instead, and nothing accumulates. Results are identical — including that
208
+ a missing field is not a distinct value while an explicit `null` is. Kits
209
+ refuse the measure combinations they cannot recombine (`avg`, `percentile`,
210
+ `stddev`, a second `countDistinct`) rather than approximating them.
211
+
212
+ - **`prev` / `hasPrev` on `KeysetPaginationResultCore`** — the backward half of
213
+ cursor pagination, for kits that implement a `before` cursor (mongokit does,
214
+ >= 3.39.0). Both are OPTIONAL, so a kit that only pages forward is unchanged.
215
+
216
+ `prev === undefined` means *"this kit does not answer the question"*, NOT
217
+ *"there is no previous page"*. A UI must read `hasPrev` to decide whether to
218
+ offer the control and treat absent as unknown — reading `undefined` as `false`
219
+ hides a control that should be there.
220
+
221
+ ### Changed
222
+
223
+ - **`validateKeysetSort` accepts mixed sort directions.** `{ priority: 1,
224
+ createdAt: -1 }` — the ESR-shaped compound index — used to throw. The keyset
225
+ predicate is a tuple comparison whose operator is chosen per position, so the
226
+ directions never needed to agree; rejecting them pushed callers onto offset
227
+ `skip(n)`, the cost keyset exists to avoid. `_id` now keeps the direction the
228
+ caller gave it, and still follows the primary field when absent.
229
+
230
+ **A kit's filter builder must read the direction PER FIELD** to consume this
231
+ safely. mongokit's `buildKeysetFilter` does (>= 3.39.0). A kit that derives
232
+ one operator from the primary field will now silently mis-paginate a
233
+ mixed-direction sort instead of being protected by the throw — audit yours
234
+ before upgrading.
235
+
236
+ ### Fixed
237
+
238
+ - **A cached `getAll` page was served to a caller that asked for a different
239
+ count strategy.** `countStrategy` / `countLimit` were missing from
240
+ `DEFAULT_SHAPE_KEYS_BY_OP.getAll`, so every strategy shared one cache key —
241
+ and the strategies disagree about `total` BY DESIGN: `'none'` reports `0`,
242
+ `'capped'` reports a flagged ceiling, `'exact'` reports the truth. A list
243
+ asking for an exact count could therefore render `0 results` over a full page
244
+ of rows, with nothing reporting an error. Both keys are now on the allowlist.
245
+
246
+ `mode` remains off it deliberately — it selects which ENVELOPE comes back, and
247
+ offset vs keyset are already separated by `page` vs `after`.
248
+
249
+ **On deploy this invalidates existing `getAll` cache entries once** (the key
250
+ shape changed); the next read repopulates them.
251
+
252
+ Pinned by mongokit's `plugin-composition-security.test.ts`, whose
253
+ `countStrategy` case had been `it.skip`ped with a comment documenting the hole
254
+ rather than closing it.
255
+
256
+ ## [0.27.1] - 2026-09-11
257
+
258
+ ### Fixed
259
+
260
+ - **A failed single-flight fetch with no concurrent waiter raised an
261
+ `unhandledRejection`** — in addition to the error the caller had already
262
+ caught. `claimPending` creates a deferred for waiters that may never arrive;
263
+ rejecting it for nobody made a working `try/catch` a process crash under
264
+ `--unhandled-rejections=strict`. Reached from `CacheEngine.prefetch`, so from
265
+ every `createTtlMemo` consumer, and from the plugin read path. The deferred is
266
+ now marked observed at creation; a waiter that does exist still receives the
267
+ rejection. `tests/unit/cache/single-flight-unobserved-rejection.test.ts` pins
268
+ the single-caller case the existing two-caller test could never reach.
269
+
270
+ ## [0.27.0] - 2026-09-09
271
+
272
+ ### Added
273
+
274
+ - **`createTtlMemo(load, { ttlMs, keyOf?, maxEntries? })`** on `./cache` — the
275
+ one way to memoise a keyed async load for a while. It is `CacheEngine.prefetch`
276
+ over the memory adapter, so concurrent misses for one key share ONE load, a
277
+ thrown load caches nothing, and a `null` result is an answer.
278
+
279
+ Four packages had each hand-rolled `Map<key, { at, value }>` with a TTL, and
280
+ every one wrote its entry AFTER the await. Under parallel event dispatch N
281
+ callers reach the await together, all miss, and the cache only ever helps the
282
+ caller after them — a 30 s TTL that measured nine reads of one row per event.
283
+ `tests/unit/cache/ttl-memo.test.ts` pins single flight, expiry, invalidation,
284
+ `ttlMs: 0` = off, and refuses an object key without `keyOf` (an
285
+ identity-compared key never hits and reads as a caching bug).
286
+
287
+ ## [0.26.1] - 2026-09-08
288
+
289
+ ### Fixed
290
+
291
+ - **`vitest` is no longer declared as a peer dependency.** It was
292
+ `peerDependencies: { vitest: "^3.0.0 || ^4.0.0" }` with
293
+ `peerDependenciesMeta.optional: true` — and that combination does not do what
294
+ it looks like. `optional: true` only silences the *missing* case; npm still
295
+ hard-fails `ERESOLVE` on a version **mismatch**. So every consumer on a newer
296
+ vitest could not install repo-core at all, even though nothing they imported
297
+ touched it.
298
+
299
+ Measured: `@classytic/arc` could not move to vitest 5 — `npm install` failed
300
+ with `Conflicting peer dependency: vitest@5.0.0`, sourced to this package.
301
+ Widening the range to `|| ^5.0.0` would only have moved the wall to vitest 6.
302
+
303
+ `vitest` is the CONSUMER's test runner. Anyone importing
304
+ `@classytic/repo-core/testing` is by definition already inside a vitest suite
305
+ that provides it, so the import resolves from their install; anyone who does
306
+ not import it should never have been constrained. It stays in
307
+ `devDependencies` for this package's own suite, and `tsdown`'s `neverBundle`
308
+ now lists `vitest` so the bundler keeps the import external instead of
309
+ inlining a dev-only dependency into shipped output.
310
+
311
+ Any vitest exposing the standard `describe` / `it` / `expect` / `beforeEach` /
312
+ `afterEach` API works with the `/testing` conformance suites.
313
+
314
+ ## [0.26.0] - 2026-09-02
315
+
316
+ ### Added
317
+
318
+ - **`@classytic/repo-core/loader` — `createBatchLoader`.** Read-side counterpart
319
+ of a kit's `bulkWrite`: keys issued anywhere in one tick coalesce into a single
320
+ `batch()` call, so a per-item read in a loop costs one round trip instead of N.
321
+ Create one per operation — it caches, so its lifetime is a correctness
322
+ property and the caller owns it.
323
+
324
+ Refuses rather than guesses, in three places that otherwise return a plausible
325
+ wrong answer with nothing reported:
326
+ - a `batch()` result whose length differs from the keys (a short array shifts
327
+ every later value onto the wrong key, and each value is individually valid);
328
+ - an object key with no `keyOf` (`String({})` is `[object Object]` for every
329
+ object, so the default would merge unrelated keys AND report the collisions
330
+ as cache hits);
331
+ - a non-integer or `< 1` `maxBatchSize` (`Math.max(1, NaN)` is `NaN`, and a
332
+ `NaN` stride abandons every waiter with no error) — same validation
333
+ `repository/purge.ts` already applies to this parameter.
334
+
335
+ Known limits: chunks beyond `maxBatchSize` run concurrently with no cap, and a
336
+ sequential `for … await loader.load(x)` loop batches nothing by construction
337
+ (each `await` closes the microtask window). Use `loadMany` or `Promise.all`,
338
+ and read `stats.batches` to confirm the round-trip count you expected.
339
+
340
+ ## [0.25.0] - 2026-08-24
341
+
342
+ ### Added
343
+
344
+ - **`CacheAdapterResolver = () => CacheAdapter | undefined`** — a function consulted per call that returns the store for the current scope, or `undefined` for "no cache right now". `undefined` is inert — identical to `enabled: false` — and never falls back to a shared store, because that fallback is the cross-scope leak the scoping exists to prevent.
345
+ - **`CacheAdapterSource = CacheAdapter | CacheAdapterResolver`** — `CacheEngine` and `cachePlugin` now accept either a fixed process-lifetime adapter (unchanged behaviour) or a resolver. A bare adapter is sugar for `() => adapter`; normalised at construction so every call site is on one path.
346
+ - **`CacheAdapterResolver` and `CacheAdapterSource` exported from `@classytic/repo-core/cache`** and re-exported from the plugin index.
347
+
348
+ ## [0.24.0] - 2026-08-17
349
+
350
+ Version bump only — republished 0.23.1's contents under a minor so consumers pinning `>=0.24.0` get the tenant guard by a floor rather than a patch. No source changes over 0.23.1.
351
+
352
+ ## [0.23.1] - 2026-08-17
353
+
354
+ ### Added — `assertNoLegacyTenantKeys(config, pkg, extra?)` (`/tenant`)
355
+
356
+ Refuses a config still carrying a pre-consolidation tenant key (`multiTenant`, plus any package-specific retirees passed via `extra`) instead of ignoring it.
357
+
358
+ The rename onto `TenantConfig` under `tenant` is trivial; the failure mode when a CALLER misses it is not. Every kernel resolver reads `resolveTenantConfig(config.tenant ?? false)`, so an absent `tenant` resolves to `strategy: 'none'` — no tenant field, no tenant filter, every read spanning ALL tenants, no error, and figures that look plausible. A host that asked for tenancy silently gets none.
359
+
360
+ The guard lives beside the resolver every one of those packages already calls, rather than being hand-rolled nine times — nine chances to forget, and the one that forgets ships the leak. Additive and non-breaking: nothing calls it until a package renames.
361
+
362
+ ## [0.23.0] - 2026-08-13
363
+
364
+ ### Added — transactional-core contracts (Phase 1a + 1d) + fencing (Phase 2, first slice)
365
+
366
+ - **Concurrency-conflict taxonomy** (`/errors`): `IsTransientConflictFn` + `neverTransient` default + `conservativeMongoIsTransientConflict` — same ownership rule as `isDuplicateKeyError` (the kit knows its driver; repositories expose `isTransientConflictError`). The default is NO retry: re-running side effects on an unclassified failure is the unsafe direction.
367
+ - **`VersionConflictError`** (`/errors`) + `isVersionConflictError` (survives duplicated copies): the optimistic-CAS violation, 409-shaped, distinct from not-found by contract — a stale version THROWS, never returns `null`, because collapsing the two invites a blind retry that clobbers the concurrent write.
368
+ - **`WriteOptions.ifVersion`** + `RepoCapabilities.optimisticConcurrency`: CAS write contract — apply only at the expected version, increment on success, throw on the option when the capability is absent (a silently dropped guard is the defect, not a degraded mode).
369
+ - **`retryingTransaction(repo, fn, opts)`** (`/repository`): the transactional retry envelope — `withTransaction` re-run on TRANSIENT conflicts only, bounded attempts, full-jitter backoff, abort-aware, classification from the kit predicate. Refuses (throws) a repository without `withTransaction` — no silent degrade. Contains no backoff math of its own: rides `withRetry`.
370
+ - **`withRetry` gains `maxDelayMs` + `jitter` + an abortable sleep** — an aborted caller no longer waits out its backoff (mutation-proven: a plain `setTimeout` there times the pinning test out). Defaults unchanged.
371
+ - **`TransactionHandle`**: `withTransaction`'s callback gains a second argument `{ session? }` — the raw driver handle, so work OUTSIDE the repository (the outbox writer, canonically) can join the same transaction. Kits MUST pass a handle object (possibly empty, for connection-bound backends); a conformance case pins the argument's presence. `retryingTransaction` forwards it structurally.
372
+ - **`LockAdapter.tryAcquireFenced?`** (additive): a successful acquire returns a MONOTONIC token minted by the STORE — a process cannot fence itself. Token increments per ownership CHANGE (extension keeps it; epochs, not heartbeats), so a downstream store can reject a stale ex-holder after lease loss — the overlap serialized renewal narrows but cannot close. `LockState.token`; memory adapter implements it (monotonic for the adapter lifetime — the honest memory limit, documented). Boolean `tryAcquire` unchanged.
373
+ - **`RepoCapabilities.transactionRetry: 'managed' | 'caller'`** — WHO owns retry of a conflict-aborted transaction. `retryingTransaction` used to wrap EVERY kit in its own 5-attempt loop, including MongoDB's convenient transaction API, which already re-runs the callback internally on `TransientTransactionError` / `UnknownTransactionCommitResult` for up to 120s. Two stacked policies: the callback's execution count stopped being bounded by `maxAttempts`, `onRetry` reported a fraction of real attempts, every outer attempt opened a NEW session, and misplaced side effects repeated unpredictably. Retry ownership is now DECLARED — `'managed'` is invoked exactly once, `'caller'` gets the envelope's loop. **Absent means `'managed'`**: a missing retry surfaces a conflict as a 409, a nested one re-runs side effects without bound, so silence must mean "don't" (same posture as `neverTransient`). `retryOwner` overrides for repositories that cannot declare.
374
+ - **`retryingTransaction` is capability-aware** — a repository that publishes a descriptor is held to it (`transactions !== true` → throw, which `'unknown'` reports, failing closed). Method presence was never the test: kits expose `withTransaction` unconditionally and fail at BEGIN.
375
+ - **`asReadOnlyRepo(repo, { reason })` + `RepoCapabilities.readOnly`** (`/repository`) — seal a repository whose rows another writer owns (Better Auth's identity collections, a SQL view, a read replica). Writes throw `ReadOnlyRepositoryError` (synchronously, so a forgotten `await` still crashes); reads pass through. A Proxy rather than a wrapper so a kit method this module has never heard of is sealed BY DEFAULT instead of leaking. `readOnly` lets a host refuse write ROUTES at boot rather than surfacing the wall on the first request.
376
+ - **`TransactionHandle` is exported from `/repository`** — it was defined in `types.ts` but never re-exported, so consumers restated it structurally as `{ session?: unknown }` and would silently miss any field added to the contract.
377
+ - **Conformance: capability-vs-behaviour assertions** — a transactional repo must declare `transactionRetry`, and `nestedTransactions` must match what a nested `withTransaction` call ACTUALLY does. Both were wrong in a shipped kit: mongokit declared `nestedTransactions: true` while its tx-bound proxy threw on the very same call.
378
+ - **Conformance: `ifVersion CAS` block** (gated on `optimisticConcurrency`): matching version applies + increments, stale version throws `VersionConflictError` and the losing write does not apply, not-found stays `null`. New optional harness fields `versionField` / `missingId`.
379
+
380
+ ## [0.22.0] - 2026-08-12
381
+
382
+ ### Added — `pages: 0` conformance tests for empty results
383
+
384
+ - `runStandardRepoConformance` now asserts `pages: 0` for empty offset envelopes (both the primary `getAll` path and the `aggregatePaginate` path). The field had no assertion anywhere in the suite; two kit paths diverged silently: the primary offset path computed `ceil(0/limit) = 0` while aggregate and lookup paths used `Math.max(1, ceil(...)) = 1`. The contract is `0` — zero rows fill zero pages — and it is what every kit's primary path already returned. The missing assertion let the drift reach a consumer as golden-fixture breakage when a `lookups` join rerouted a list read onto the divergent path.
385
+
386
+ ## [0.21.0] - 2026-08-10
387
+
388
+ ### Added — LRU-bounded `createMemoryCacheAdapter`
389
+
390
+ - `createMemoryCacheAdapter(options?)` now accepts `MemoryCacheAdapterOptions` with a `maxEntries` cap (default `10,000`). Past the cap the least-recently-used entry is evicted — read promotion (delete + re-insert) keeps the map ordered by recency so eviction is O(1). A TTL alone does not bound the map: entries only expire when read, so a high-cardinality keyspace (per-tenant, per-commit, per-filter keys) grows monotonically until the process dies. Eviction is always safe for a cache, so the bound is on by default. Set `maxEntries: 0` to restore the previous unbounded behaviour.
391
+ - `MemoryCacheAdapterOptions` exported from `@classytic/repo-core/cache`.
392
+
393
+ ### Added — timezone-aware date buckets (`AggDateBucket.timezone`)
394
+
395
+ - `AggDateBucket.timezone` — IANA zone the bucket boundaries are drawn in; absent means UTC. A UTC day is not a business day in any non-UTC deployment: rows from 18:00 to midnight local fall in the previous UTC day, silently reporting the wrong period in daily/monthly rollups.
396
+ - `AggregateOpsSupport.dateBucketTimezone` capability flag — a kit that cannot draw DST-correct boundaries (e.g. SQLite, no tz database) MUST declare `dateBucketTimezone: false` and throw when the field is set rather than silently bucketing in UTC. Mongokit (`$dateTrunc` / `$dateToString` both accept `timezone`) declares `true`.
397
+
398
+ ## [0.20.0] - 2026-08-04
399
+
400
+ ### Added
401
+
402
+ - **`ResolveBetterAuthCollectionsOptions.exclude`** — canonical collection names
403
+ to omit from `resolveBetterAuthCollections()` output. Applied before
404
+ `modelOverrides` / `usePlural` so a caller names the canonical collection
405
+ (`'user'`) and never has to predict the final model name. Solves the collision
406
+ when a host registers stub models for BA collections it merely references and a
407
+ full `createBetterAuthOverlay` for the one it exposes CRUD on — both for the
408
+ same collection would cause mongoose to lock the schema on first `model()`,
409
+ silently dropping `additionalFields` and causing the overlay to refuse.
410
+
411
+ ## [0.19.0] - 2026-07-29
412
+
413
+ ### Added — `coerceFilterDates` + ISO date helpers (`./filter`)
414
+
415
+ - **`coerceFilterDates(filter)`** — walks a record-shape filter (Mongo-dialect or bare bracket-op syntax) and coerces ISO-8601 strings on range operators (`gt`/`gte`/`lt`/`lte` and `$`-prefixed equivalents) to `Date`, recursing through `$and`/`$or`/`$nor`/`$not` logical wrappers. Returns a new object; the input is never mutated. Equality operators are deliberately excluded — a string that happens to look like a date is far more likely a string id than a date equality predicate. Fixes silent empty results on aggregation `$match` stages: MongoDB `$match` (unlike `find`) performs no schema casting, so a string compared to a Date column matches nothing.
416
+ - **`tryCoerceIsoDate(value)`** — coerces one unknown value to a `Date` when it is an unambiguous ISO-8601 string; returns anything else untouched. Safe to apply unconditionally.
417
+ - **`ISO_DATE_PATTERN`** — the single regex source of truth for tight ISO-8601 detection (date-only through millisecond precision + optional timezone). `query-parser/coerce.ts` now imports this instead of keeping a duplicate pattern — one definition means the URL boundary and the compile boundary can never disagree on what "looks like a date".
418
+
419
+ All three are exported from `@classytic/repo-core/filter`. Purely additive.
420
+
421
+ ## [0.18.0] - 2026-07-27
422
+
423
+ ### Added — `definePurgeStep` builder (`./cleanup`) and `resolveTenantField` (`./tenant`)
424
+
425
+ #### `./cleanup` — `definePurgeStep`
426
+
427
+ - **`definePurgeStep(repository, spec)`** — standard builder for the most common
428
+ `CleanupStep` shape: a chunked `purgeByField` over a single scope value.
429
+ Nearly every provider step in a domain kernel is this pattern; the builder owns
430
+ the invariant core so callers only declare what differs:
431
+ - **fail-closed scoping** — missing scope value or unavailable repository is a
432
+ `BLOCKER` (not a silent no-op and never an unscoped purge that would hit every
433
+ tenant); blocked by `SCOPE_REQUIRED:<param>` / `REPOSITORY_UNAVAILABLE:<id>`.
434
+ - **cancellation** — `throwIfCancelled` is called before work starts and the
435
+ `signal` is threaded to the kit so a cancel lands between committed chunks.
436
+ - **honest failure** — a failing purge returns `ok: false` so the recipe composer
437
+ stops (retention §8); thrown errors are caught and reported, never swallowed.
438
+ - **verification** — absence is re-queried after the run via `countDocuments`
439
+ (`spec.verifyFilter` for steps whose match filter differs from the absence proof).
440
+ - **`PurgeStepSpec`** — declaration object: `id`, `resource`, `parameter`, `field`,
441
+ `strategy`, optional `retained`, `warnings`, `batchSize`, `guard(scope, ctx)`,
442
+ `verifyFilter(scope)`, `verifyName`.
443
+ - **`PurgeStepRepository`** — structural subset of `StandardRepo` satisfied by any
444
+ kit repository that implements `purgeByField` + `countDocuments`.
445
+ - **`SCOPE_REQUIRED`** / **`REPOSITORY_UNAVAILABLE`** — blocker-code prefix constants.
446
+
447
+ #### `./tenant` — `resolveTenantField`
448
+
449
+ - **`resolveTenantField(config?)`** — returns the single `tenantField` string a
450
+ resource layer needs for `defineResource({ tenantField })`, or `false` when the
451
+ config disables tenant scoping (`false` / `{ enabled: false }` / `{ strategy: 'none' }`).
452
+ Four spine modules hand-rolled equivalent logic independently, each re-deriving
453
+ `'organizationId'` as the default; one copy omitted the disable branch, making
454
+ that package silently un-configurable. This function is the single definition.
455
+
456
+ Both additions are purely additive — no breaking changes.
457
+
458
+ ## [0.17.0] - 2026-07-25
459
+
460
+ ### Added — `./cleanup`: framework-free cleanup provider step contract
461
+
462
+ - **`@classytic/repo-core/cleanup`** — new subpath (pure types, no runtime).
463
+ Domain kernels (`@classytic/flow`, `@classytic/order`, `@classytic/facts`,
464
+ `@classytic/ledger`, …) export `CleanupStep[]` for the data they own; a host
465
+ framework (`@classytic/arc/cleanup`) folds them into a Cleanup Center recipe.
466
+ The contract lives in repo-core so kernels stay framework-free: kernels already
467
+ depend on repo-core (the chunked-purge mechanics) and MUST NOT depend on arc.
468
+ - **`CleanupStep`** — the core provider interface: `id`, `resource`, `destructive`,
469
+ optional `rebuildActions`; and three lifecycle methods: `estimate(ctx)` (preview
470
+ without mutating), `execute(ctx)` (chunked, idempotent, cancellation-aware),
471
+ and optional `verify(ctx)` (post-checks — a delete count alone is never success).
472
+ - **Supporting types**: `CleanupStepContext` (injected `now`, `signal`, `ambient`,
473
+ `parameters`, `logger`), `CleanupStepExecuteContext` (adds `onProgress` +
474
+ `throwIfCancelled`), `CleanupStepEstimate` (row count, `retained`, `blockers`,
475
+ `warnings`), `CleanupStepOutcome` (`processed`, `ok`, `error`, `cursor`),
476
+ `CleanupStepCheck` (`name`, `ok`, `detail`), `CleanupStepProgress`, `CleanupStepLogger`.
477
+
478
+ Purely additive — zero runtime code, type-only subpath export.
479
+
480
+ ## [0.16.0] - 2026-07-24
481
+
482
+ ### Added — `runPurgeConformance`: cross-kit chunked-purge contract suite
483
+
484
+ - **`runPurgeConformance(harness)`** (from `@classytic/repo-core/testing`) —
485
+ proves a kit's purge port makes **stable progress for every strategy** when
486
+ the match set exceeds `batchSize`. Every scenario seeds more rows than one
487
+ batch; a chunk budget converts a non-progressing port's infinite loop into a
488
+ crisp assertion failure. Scenarios: hard drain, soft multi-batch WITHOUT
489
+ caller-supplied exclusion predicates, anonymize static + function-form,
490
+ exact-batch boundary, skip, empty scope, abort-between-chunks.
491
+ - **`PurgePort` progression contract (documented, mandatory)** — successive
492
+ `purgeChunk` calls MUST advance through the match set for every strategy via
493
+ stable keyset progression (`pk > lastSeen`, advanced only after the chunk's
494
+ write succeeds). Re-running the bare predicate only self-advances for
495
+ `hard`; `soft`/`anonymize` re-select the same first chunk forever. Offsets
496
+ are explicitly ruled out. A port instance is single-run state.
497
+
498
+ ### Fixed
499
+
500
+ - `purgeByField` docstring no longer claims soft/anonymized rows "simply don't
501
+ match the next pass" — they generally DO still match; idempotency holds by
502
+ outcome convergence, and within-run progression is the port's keyset
503
+ responsibility.
504
+
505
+ ## [0.15.0] - 2026-07-24
506
+
507
+ ### Added — `purgeByFilter`: range/filter-scoped purge + anonymize
508
+
509
+ - **`StandardRepo.purgeByFilter?(filter, strategy, options)`** — the
510
+ range/filter-scoped sibling of `purgeByField`. Where `purgeByField` matches
511
+ a single `field = value` equality, this optional method takes the full
512
+ portable `FilterInput` (Filter IR or a plain kit-native record) and runs any
513
+ `TenantPurgeStrategy` (`hard` / `soft` / `anonymize` / `skip`) over the
514
+ matched slice. THE compliance primitive for "purge/anonymize a dimension
515
+ across a RANGE while RETAINING measures" — redact a PII column across a
516
+ `civilDate` window, hard-delete rows past a retention cutoff, soft-delete a
517
+ compound cohort. Returns the same `TenantPurgeResult` envelope; chunking,
518
+ index requirement, idempotency, plugin composition, and narrowed-write
519
+ re-assertion are identical to `purgeByField`. Gate on the new
520
+ `capabilities.purgeByFilter`.
521
+ - **`RepoCapabilities.purgeByFilter?: boolean`** — feature-detection flag,
522
+ mirroring `purgeByField`.
523
+ - **`PurgePort` doc** clarifies the two bound-predicate forms (equality-bound
524
+ vs filter-bound) both satisfy the single port interface, so `runChunkedPurge`
525
+ drives both unchanged.
526
+
527
+ Strictly additive: `purgeByField`, `TenantPurgeStrategy`, and `runChunkedPurge`
528
+ are unchanged; both new members are optional.
529
+
530
+ ## [0.14.0] - 2026-07-16
531
+
532
+ ### Added — canonical `matchesRecordFilter` (the `DataAdapter.matchesFilter` home)
533
+
534
+ - **`matchesRecordFilter(item, record)`** + **`policyRecordToFilter(record)`**
535
+ (`@classytic/repo-core/filter`) — THE single, shared implementation of the
536
+ `DataAdapter.matchesFilter` seam. Evaluates arc's Mongo-record `_policyFilters`
537
+ (`{ ownerId }`, `{ organizationId }`, `{ $or: [{ ownerId }, { _id: { $in } }] }`)
538
+ against an already-fetched document IN PROCESS, by converting to the portable
539
+ `Filter` IR and delegating to `matchFilter` — the SAME IR kits compile to
540
+ SQL/Mongo, so in-memory and DB enforcement agree by construction. Every kit's
541
+ adapter now delegates here; **no per-kit matcher, one contract, one IR.**
542
+ Operator scope: `$or`/`$and`/`$nor`/`$not`, `$eq`/`$ne`/`$gt`/`$gte`/`$lt`/`$lte`,
543
+ `$in`/`$nin`, `$exists`, implicit-eq; fails LOUD on anything else. (Distinct from
544
+ `recordToFilter`, the bare-operator query normalizer that does not accept
545
+ `$`-prefixed or logical operators.)
546
+ - **`matchFilter` is now fully array + id + date aware** (additive superset;
547
+ primitive/Date-vs-Date behavior unchanged — strict cases still short-circuit):
548
+ - **id coercion** — an id-like object with a meaningful `toString` (Mongo
549
+ `ObjectId`, `Buffer`, `Decimal128`) matches its string form, so one shared
550
+ matcher serves Mongo (`ObjectId` `_id`) and SQL (primitive ids) alike.
551
+ - **array semantics** — dot-paths fan out over subdocument arrays
552
+ (`items.sku` on `[{sku},{sku}]`), and a scalar condition on a leaf array
553
+ field matches when ANY element satisfies it (`{ tags: 'x' }`,
554
+ `{ scores: { $gt: 5 } }`, regex on array elements). All array unwrapping is
555
+ concentrated in one helper; the comparators stay pure scalar.
556
+ - **Date⇄ISO-string range** — `compare` coerces the string side to a date
557
+ instant when the other side is a genuine `Date` (mirrors `equals`), and
558
+ never claims ordering across a number/string type boundary (fails closed
559
+ instead of matching spuriously).
560
+ - **prototype-pollution-safe reads** — path resolution uses `Object.hasOwn`,
561
+ so a crafted `{ '__proto__.x': … }` / `{ constructor.name: … }` filter can
562
+ never traverse the prototype chain.
563
+ - **Ability parity across kits**: mongokit's earlier standalone matcher
564
+ (subdocument-array fan-out, array-contains, `$regex`, ObjectId coercion) is now
565
+ fully covered by the shared engine — nothing was lost in consolidation.
566
+ - **MongoDB-parity hardening** (validated against the MongoDB manual + sift.js +
567
+ mingo — the two industry-standard in-memory matchers). The authorization-critical
568
+ rule "an absent field participates in comparisons as null/undefined" is now
569
+ fully honored:
570
+ - `{ field: null }`, `$ne`, `$nin`, and a `null` MEMBER of `$in`/`$nin` all
571
+ match a MISSING field (a policy filter `{ status: { $ne: 'archived' } }`
572
+ correctly returns docs that lack the field, exactly as MongoDB does — the top
573
+ silent-authorization-divergence trap). `$ne: null` remains the exception
574
+ (requires present + non-null).
575
+ - `$in` accepts RegExp-literal members (`{ name: { $in: [/^a/] } }`).
576
+ - Comparison ops are type-bracketed (no cross-type ordering; `$gt: null` matches
577
+ nothing); NaN equals NaN for `$eq` (via `Object.is`, not `===`).
578
+ - Numeric dot-path segments resolve as positional array indices (`items.0.sku`).
579
+ - Documented DELIBERATE divergences: `$exists` = present-and-non-null (matches
580
+ the IR `exists` op + SQL `IS NOT NULL` + sift; Mongo/mingo count present-null
581
+ as existing); `Date`⇄ISO-string range leniency; array-literal operands are
582
+ element-matched not exact-matched.
583
+ - New: 41-case matcher suite incl. the 11 researched MongoDB gotchas + adversarial
584
+ (prototype pollution, NaN/Infinity, boolean/zero/empty-string, empty
585
+ `$in`/`$or`/`$and`/`$nor`, fail-loud on unsupported operators) + a 100k-doc
586
+ performance smoke (linear, cached regex).
587
+ - **Security hardening** (from a review against sift.js/mingo CVEs + the OWASP
588
+ NoSQL-injection / ReDoS / prototype-pollution literature):
589
+ - **Prototype-key denylist** on path segments — `__proto__` / `constructor` /
590
+ `prototype` resolve to nothing (fail-closed), string-normalized (the
591
+ object-path CVE-2021-23434 lesson: an array-typed segment bypassed a `===`
592
+ check). Closes the "match an inherited member → wrong auth answer" case and
593
+ the `JSON.parse('{"__proto__":…}')` own-property vector, on top of the
594
+ already-`Object.hasOwn` reads.
595
+ - **`$regex` input-length cap** (64 KiB) — ReDoS is `pattern × input`; a field
596
+ value longer than the cap is treated as no-match (fail-closed) so one slow
597
+ match can't stall the event loop and amplify across a realtime fan-out
598
+ (matcher runs once per subscriber per record). Pattern-side ReDoS is a
599
+ non-issue for framework-supplied (trusted) patterns.
600
+ - Reaffirmed **fail-closed** posture: comparisons never coerce across a
601
+ number/string type boundary (return no-match rather than JS-coerced nonsense
602
+ — the classic over-visibility leak), and unsupported operators throw.
603
+
604
+ ## [0.13.0] - 2026-07-15
605
+
606
+ ### Added — `StandardRepo.applyTransition?()` contract (state-machine CAS with history)
607
+
608
+ - **`TransitionMachine`** — the canonical structural contract for the state
609
+ machine (`{ name, assertTransition }`). Primitives'
610
+ `defineStateMachine()` output and mongokit's local `TransitionMachine`
611
+ are structurally identical by design; nobody imports anybody (same
612
+ policy as `ClaimTransition`).
613
+ - **`TransitionArgs`** — `{ from, to, field?, set?, push?, where?, by?,
614
+ note?, history?, at? }`.
615
+ - **`StandardRepo.applyTransition?(id, machine, args, options)`** — OPTIONAL
616
+ member declaring the state-machine-backed CAS transition mongokit 3.22
617
+ ships as a class primitive: legality pre-flight via the machine (which
618
+ throws the domain's typed error), CAS via `claim`, `$push`ed status
619
+ history, and accurate race-loss diagnosis (machine error from the row's
620
+ CURRENT state / 404 `TRANSITION_TARGET_MISSING` / 409
621
+ `TRANSITION_RACE_LOST`). Unlike `claim`/`claimVersion` it THROWS rather
622
+ than returning `null` — it owns the error liturgy domain packages used
623
+ to copy-paste. Promote to required once sqlitekit implements it.
624
+
625
+ ### Added — `./usage` subpath (period-bucketed counter contract)
626
+
627
+ - **`UsageStore`** — driver-agnostic interface for atomic period-bucketed counters: `increment(bucket, amount)` + `summary(actor, period)`. The storage seam under platform accounting (quotas, plan enforcement, usage-based billing). One cell = `(actor, period, kind)`; one write = atomic upsert; one read = all counters for an actor-period pair. Kits ship adapters (`@classytic/mongokit/usage`, `@classytic/sqlitekit/usage`, …) without depending on arc; `@classytic/arc/usage` consumes this contract structurally.
628
+ - **`UsageBucket`** — `{ actor, period, kind }` tuple. `kind` is dot-namespaced: `api.requests`, `ai.tokens.input`, `storage.egress.bytes`.
629
+ - **`usagePeriod(date?)`** — canonical UTC calendar-month key (`"2026-07"`). Monthly is the billing-native granularity.
630
+ - **`createMemoryUsageStore()`** — in-process reference implementation for tests and single-instance apps. Returns `UsageStore & { clear() }`. Multi-replica deployments need a shared adapter.
631
+
632
+ ### Added — `runUsageStoreContract` in `./testing`
633
+
634
+ - **`runUsageStoreContract(harness)`** — cross-kit conformance suite. Kits import once and pass their adapter; all canonical scenarios run automatically. Same pattern as `runLockAdapterConformance`. `UsageConformanceHarness` is exported from `./testing` for harness typing.
635
+
636
+ ## [0.10.0] - 2026-07-13
637
+
638
+ ### Added — `ValidationErrorMeta.path` + `.meta` (field-scoped validation errors)
639
+
640
+ - **`ValidationErrorMeta.path?: string`** — dot-path to the offending field
641
+ (e.g. `'journalItems.2.account'`). Set by kits with field-scoped validation
642
+ (ledger's `FieldError`, Mongoose `ValidationError`). Absent when the kit doesn't
643
+ have a field path.
644
+ - **`ValidationErrorMeta.meta?: Readonly<Record<string, unknown>>`** — non-PII
645
+ structured extra for the field (e.g. `{ value: 'bad' }`). Never include secrets.
646
+ - **`toErrorContract`** now forwards `path` and `meta` from each `validationErrors`
647
+ entry onto the wire `ErrorDetail`. Previously only `code` and `message` were mapped;
648
+ field paths were silently dropped. No breaking change — both fields are optional and
649
+ additive. Kits that don't set them produce the same wire shape as before.
650
+
651
+ ## [0.9.0] - 2026-07-11
652
+
653
+ ### Added — `StandardRepo.getByIds` (batch point-read)
654
+
655
+ - **`getByIds?(ids: readonly string[], options?: FindAllOptions): Promise<Map<string, TDoc>>`**
656
+ added to `StandardRepo` — the `$in` / `IN (...)` counterpart to `getById`. The N+1
657
+ killer for callers resolving many ids in one tick (order-line snapshotting, dashboard
658
+ row enrichment, reference expansion).
659
+
660
+ **Contract:**
661
+ - Kit de-duplicates ids before the driver round-trip.
662
+ - Ids with no matching doc are ABSENT from the returned `Map` — never throw on a miss.
663
+ - Structurally invalid ids are treated as misses (one malformed id must never fail the
664
+ batch).
665
+ - Tenant scoping, soft-delete, and hooks apply exactly as they would to `getById`.
666
+ - Empty input → empty Map, no round-trip.
667
+ - Optional: kits adopt incrementally. Callers feature-detect
668
+ (`repo.getByIds ?? per-id fallback`) until their kit floor ships it.
669
+ - Sizing is backend-bound (Mongo: 16 MB query document); keep batches ≤ ~10k ids and
670
+ chunk beyond.
671
+
672
+ - **`events.ts` clarification** — `getByIds` has no `BEFORE_GET_BY_IDS` event by design.
673
+ It routes through `findAll`, so observers see the batch as `before:findAll` / `after:findAll`
674
+ with an `$in` filter. The comment guards against accidentally adding a separate event.
675
+
676
+ - **New type-level contract test** (`tests/unit/repository/get-by-ids-contract.test.ts`) —
677
+ pins the `getByIds` shape for kits implementing it: `Map<string, TDoc>` keyed by
678
+ stringified id, `readonly string[]` input. Verifies that kits without `getByIds` still
679
+ conform (the member is optional).
680
+
681
+ ### Changed
682
+
683
+ - `ChangesPage.changes` type: `ReadonlyArray<ChangeEntry<TDoc>>` → `readonly ChangeEntry<TDoc>[]`
684
+ (canonical form — functionally identical).
685
+ - devDeps: `tsdown ^0.21.8 → ^0.22.5`, `typescript ^6.0.3 → ^7.0.2`.
686
+
687
+ ## [0.8.1] - 2026-07-11
688
+
689
+ ### Docs — `DataAdapter.close()` ownership rule
690
+
691
+ - Clarified the `close?()` contract (doc-only, no type/runtime change): the adapter does **not** own the database connection — the host does, and `close()` must release only adapter/kit-owned resources (TTL/vacuum timers, change streams), never disconnect a shared client/pool. Kits that genuinely own a connection gate its disposal behind an explicit opt-in. This standardizes cleanup semantics across mongokit/sqlitekit/pgkit/prismakit.
692
+
693
+ ## [0.8.0] - 2026-07-08
694
+
695
+ ### Added — data-lifecycle contract (archive, streaming, distribution awareness)
696
+
697
+ Additive release: existing kits on 0.7 semantics compile and pass conformance unchanged (new scenarios are capability-gated and default to skipped).
698
+
699
+ - **`archiveByFilter` + `runChunkedArchive`** (`repository/archive.ts`) — the cold-storage twin of `purgeByField`. Hosts provide an `ArchiveSink` (archive table/collection, JSONL, warehouse loader); kits provide an `ArchivePort` (`readChunk` in stable PK order / `deleteChunk` by docs). The orchestrator enforces **write-before-delete** (a crash re-archives, never loses; sinks must be duplicate-tolerant — at-least-once by design), chunked `batchSize` (default 1000), per-step retry via the shared `RetryPolicy`, abort between chunks, cumulative progress, and phase-tagged errors (`read` / `sink` / `delete` — a `sink` failure guarantees rows are still hot). New capability flag: `archiveByFilter`.
700
+ - **`cursor()` declared on `StandardRepo`** (+ `CursorOptions`) — the streaming-reads method mongokit and sqlitekit already implement is now part of the portable contract (`AsyncIterable<TDoc>`, internal `batchSize` fetching, non-snapshot semantics documented). Gated by the existing `streaming` capability.
701
+ - **Distribution-key awareness** (`repository/distribution.ts`) — `DistributionConfig` (`key`, `onMissingKey: 'warn' | 'throw' | 'off'`, `exemptOperations`) + `createDistributionGuard` + `filterReferencesKey` (Filter IR via `collectFields`, raw records incl. `$and`/`$or`/`AND`/`OR` branches). Catches shard/partition-key-missing scatter-gather queries at the access layer; deliberately does NOT implement routing/rebalancing/partition DDL — those stay database-native (Mongo sharding, pg_partman/Timescale).
702
+ - **Conformance**: new capability-gated scenario groups — `archiveByFilter` (sink round-trip, write-before-delete on sink failure, chunking + progress, idempotent re-run, abort partial) and `cursor` (exact-once iteration across batch boundaries, early-break safety).
703
+
704
+ ## [0.7.0] - 2026-07-04
705
+
706
+ ### Added — `./sync` change-log / cursor contract
707
+
708
+ Storage-agnostic data-sync spine for offline-first + incremental replication:
709
+ `ChangeLogStore`, `ChangeEntry` (tombstone deletes), pull `ChangesPage`
710
+ (opaque exclusive cursors, `hasMore` paging), Replicache-style `PushMutation`
711
+ / `PushVerdict` (idempotent client mutation ids, server-authoritative
712
+ conflicts), `CursorExpiredError` (compaction horizon → full resync), and the
713
+ `MemoryChangeLogStore` reference impl pinning the contract semantics.
714
+
715
+ Synthesized from CouchDB `_changes` (tombstones/checkpoints), Drive/Graph
716
+ delta APIs (opaque server-issued cursors), Mongo change-stream resume tokens,
717
+ and Replicache push/pull. Contract only — kits (mongokit/prismakit/sqlitekit)
718
+ implement capture + durable stores via repository plugins; arc re-exports the
719
+ surface at `@classytic/arc/sync`; sync HTTP endpoints are an arc module.
720
+
721
+ ## [0.6.1] - 2026-07-04
722
+
723
+ ### Changed — `TenantConfig` optionals widened to `T | undefined` (P10)
724
+
725
+ Every optional prop on `TenantConfig` (`strategy`, `enabled`, `tenantField`,
726
+ `fieldType`, `ref`, `contextKey`, `required`, `resolve`) is now typed
727
+ `T | undefined`, so downstream packages compiling with
728
+ `exactOptionalPropertyTypes: true` can extend it without redeclaring props
729
+ (unblocks `@classytic/ledger`'s `MultiTenantConfig.required` exception).
730
+
731
+ `resolveTenantConfig` strips explicit-`undefined` keys before spreading
732
+ over `DEFAULT_TENANT_CONFIG`, so `{ required: maybeUndefined }` can never
733
+ clobber a default with `undefined` — previously the un-widened type made
734
+ that unrepresentable; now it's handled at runtime and pinned by tests.
735
+ `DEFAULT_TENANT_CONFIG`'s annotation moved from `Required<Pick<...>>` to an
736
+ `Exclude<..., undefined>` mapping (`-?` does not strip an explicit
737
+ undefined union member). No runtime behavior change for existing callers.
738
+
739
+ ## [0.6.0] - 2026-06-11
740
+
741
+ Standardization release. Coordinated with mongokit 3.16 + sqlitekit 0.6.
742
+
743
+ ### Added
744
+
745
+ - **`StandardRepo.capabilities: RepoCapabilities`** (required) — runtime feature detection (`arrayOperators`, `changeStreams`, `regexFilter`, `lean`, `streaming`, `lookupPopulate`, + conformance flags). `ConformanceFeatures` is now an alias of the same type — runtime declaration and conformance gating cannot drift.
746
+ - **Standard Schema validation** — `RepositoryBaseOptions.schema` / `updateSchema` accept any Zod / Valibot / ArkType / Effect schema; runs at new `HOOK_PRIORITY.VALIDATION` (150). Failures throw `HttpError` 400 with `validationErrors`. Vendored `StandardSchemaV1` types + `validateStandardSchema()` on `/schema`.
747
+ - **Domain events** (`/events` subpath) — `RepositoryBaseOptions.events: { transport }` publishes `<resource>.<verb>` events through any arc/primitives-compatible transport. Publish failures never fail the op (routed to `error:events`).
748
+ - **Change feed contract** — optional `StandardRepo.watch?()` returning `AsyncIterable<ChangeEvent<TDoc>>`; gated by `capabilities.changeStreams`.
749
+ - **Resilience** — `QueryOptions.signal` + `QueryOptions.retryPolicy`; shared `withRetry()` / `throwIfAborted()` helpers.
750
+ - **`recordToFilter()`** on `/filter` — promoted from per-kit copies.
751
+ - `STANDARD_REPO_OPTION_KEYS` gains `'traceId'`.
752
+
753
+ ### Changed
754
+
755
+ - `PurgeRetryPolicy` → **`RetryPolicy`** (rename, identical shape; was declared twice — now once). Clean break, no alias.
756
+ - `AggregateOpsSupport` moved to `repository/capabilities.ts` (still re-exported from `/testing`).
757
+
758
+ ## [0.5.0] - 2026-05-17
759
+
760
+ ### Added — compliance-grade tenant cleanup primitive
761
+
762
+ Cross-kit foundation for "what happens to this data on org-delete?" —
763
+ GDPR right-to-be-forgotten, SOC 2 deletion timelines, HIPAA / PCI
764
+ retention rules. Every kit (mongokit, sqlitekit, future pgkit) gets
765
+ the same surface; arc's `cascadeDeleteForOrganization` runner composes
766
+ on top.
767
+
768
+ - **`StandardRepo.purgeByField?(field, value, strategy, options)`** — new optional method. Processes every row matching `field = value` under a declared strategy, chunked under the hood. Optional because not every store needs the surface; arc's cascade runner checks for the method at boot.
769
+ - **`TenantPurgeStrategy`** discriminated union — four variants:
770
+ - `{ type: 'hard' }` — permanent removal (GDPR right-to-be-forgotten).
771
+ - `{ type: 'soft', deletedField?, deletedAtField? }` — recoverable; pairs with TTL indexes for eventual hard-purge.
772
+ - `{ type: 'anonymize', fields }` — retain rows but overwrite declared fields (HIPAA / PCI / SOX-compatible).
773
+ - `{ type: 'skip', reason }` — explicit opt-out with **mandatory** `reason` (compliance forcing function — silent skips are leaks).
774
+ - **`TenantPurgeOptions`** — `batchSize`, `session`, `onProgress`, `signal`. Chunking is mandatory (10M-row tenants can't run as a single `deleteMany`); abort signal is checked between chunks (never mid-write); aborted runs return `ok: false` with cumulative `processed` count (at-least-once cleanup semantics).
775
+ - **`TenantPurgeResult`** + **`TenantPurgeProgress`** — typed result envelope + per-chunk progress event.
776
+
777
+ ### Added — kit-agnostic orchestrator (`runChunkedPurge`)
778
+
779
+ The chunk-loop logic — abort handling, progress emission, error-wrapping into result envelope, natural-exit on non-full batch — is identical across kits. Extracting it here means a single bug fix lands for every kit, and the surface a new kit has to implement shrinks to ~80 lines.
780
+
781
+ - **`runChunkedPurge(strategy, options, port)`** — pure orchestrator (130 lines, no I/O).
782
+ - **`PurgePort`** interface — the driving port. Each kit implements a single closure: `purgeChunk(strategy, limit)` — one method lets each driver pick its own round-trip shape (sqlite hard-strategy compiles to one `DELETE … LIMIT`; a two-method `selectChunkIds` + `applyStrategy` split would force 2 round-trips per chunk for every kit).
783
+ - **`WritingPurgeStrategy`** — strategy union with `skip` excluded (orchestrator handles `skip` before the port is consulted, so ports only see `hard` / `soft` / `anonymize`).
784
+
785
+ Hexagonal pattern: orchestrator is the use-case, `PurgePort` is the driving port, each kit's port factory is the adapter. Adding a new strategy (e.g. `archive`) = one union member + one case per port. Adding a new kit = one port file + ~10-line method.
786
+
787
+ ### Added — 8 cross-kit conformance scenarios
788
+
789
+ In `src/testing/conformance.ts`, gated by the new `ConformanceFeatures.purgeByField?: boolean` flag. When both mongokit and sqlitekit pass the same scenarios, cross-kit byte-stability for tenant cleanup is provable:
790
+
791
+ 1. `hard` removes every matching row, leaves others intact
792
+ 2. `hard` empty match → `processed: 0`, `ok: true`
793
+ 3. `anonymize` overwrites declared fields, keeps the row
794
+ 4. `skip` is a no-op, returns reason
795
+ 5. Chunking: `batchSize` honored, `onProgress` fires per chunk
796
+ 6. Idempotent: re-running on the same tenant is a no-op
797
+ 7. Scoping: only matching rows affected (cross-tenant safety)
798
+ 8. Abort signal: stops between chunks, returns partial count + `ok: false`
799
+
800
+ The `soft` strategy is intentionally NOT in the conformance suite — it requires writable `deleted` / `deletedAt` fields not present on the shared `ConformanceDoc`; each kit covers `soft` in its own integration tests.
801
+
802
+ ### Migration notes
803
+
804
+ - **Existing kits:** the new method is optional — kits don't break. mongokit 3.14.0 and sqlitekit 0.4.0 ship implementations; older kit versions continue to work, they just can't honor a `purgeByField` call.
805
+ - **Existing hosts:** no breaking changes. Hosts using arc's `cascadeDeleteForOrganization` automatically pick up the new strategy surface once arc 2.16.0 lands.
806
+ - **Build sync (workspace dev):** kits need `cp -r dist/* ../mongokit/node_modules/@classytic/repo-core/dist/` etc. after a workspace bump until npm publish.
807
+
808
+ ## [0.4.0] - 2026-05-04
809
+
810
+ ### Added — kit-shared building blocks (consolidation)
811
+
812
+ - **`@classytic/repo-core/aggregate`** (new subpath) — kit-neutral aggregate IR helpers that every backend's compiler consumes identically: `normalizeGroupBy`, `validateMeasures`, `encodeAggCursor`, `decodeAggCursor`, `isKeysetMode`, `DecodedCursor`. mongokit + sqlitekit shipped byte-identical copies of these for the prior several releases; promoting them here keeps the IR contract honest. The driver-specific predicate builders (`buildKeysetPredicate` in mongokit, `buildKeysetHaving` in sqlitekit) stay kit-local.
813
+ - **`@classytic/repo-core/plugins`** (new subpath) — kit-neutral plugin building blocks. Currently exports `payloadHasTenantField` (handles all 5 policy keys: data, dataArray, query, filters, operations) and `adminBypass` (skipWhen-compatible role-bypass factory). Both kits now consume these instead of shipping their own copies. Sqlitekit gains `adminBypass` for free as a side effect.
814
+
815
+ ### ⚠️ BREAKING — `cache/deferred.ts` removed (use `Promise.withResolvers()`)
816
+
817
+ - **`createDeferred()` and `Deferred<T>` no longer exported from `@classytic/repo-core/cache`.** Both were thin wrappers around `Promise.withResolvers()`, which Node 22+ ships natively (the package's platform floor). The cache engine's single-flight map now uses the native primitive directly with zero indirection.
818
+ - **Migration:** if you imported them, replace `import { createDeferred } from '@classytic/repo-core/cache'` with `Promise.withResolvers<T>()`. Same shape (`{ promise, resolve, reject }`); behavior is identical.
819
+
820
+ ### Fixed — security & robustness hardening
821
+
822
+ - **DoS surface in URL parser**: `parseUrl` now drops parameter keys longer than 256 chars before bracket-regex parsing. Without the cap, a hostile 1MB key forced repeated full-string regex scans. Legitimate URL params don't approach the bound. (`src/query-parser/parse-url.ts`)
823
+ - **Cursor payload type validation**: `decodeCursor` now type-checks every payload field, not just presence. A corrupted token shaped `{ v: { evil: true } }` previously slipped past the `'v' in p` guard and produced opaque errors downstream. (`src/pagination/cursor.ts`)
824
+ - **Regex compile-per-doc on in-memory filter**: `matchFilter`'s `like` and `regex` cases now use a bounded LRU cache (256 entries) keyed by `(pattern, flags)`. Prior implementation compiled a fresh `RegExp` on every call — measurable cost when `asPredicate(filter)` runs over 100k docs. (`src/filter/match.ts`)
825
+
826
+ ### Cache hash upgrade (djb2 → FNV-1a 64-bit)
827
+
828
+ - **`buildCacheKey` now uses FNV-1a 64-bit** (was djb2 32-bit). At multi-tenant fleet scale (10k tenants × dozens of cached aggregations each), djb2's 32-bit space hit ~50% birthday-paradox collision around 65k distinct keys. FNV-1a 64-bit pushes that threshold to ~4B keys. Same call site, same key shape, same regex-compatible base-36 output.
829
+ - **Operational note for deployment:** existing Redis entries hash differently after the swap, so cold cache for one TTL cycle post-deploy. The collection-version orphan path already handles this for write-driven invalidation.
830
+
831
+ ### Cache layer — atomic counters, parallel invalidation, prefetch, timeout
832
+
833
+ - **`CacheAdapter.increment(key, by, ttl)`** — optional atomic counter primitive. When the adapter ships it (Redis `INCRBY`, in-memory `Map`, future driver-native impls), `bumpModelVersion` produces strictly-monotonic versions across concurrent multi-pod writes — no lost bumps. Adapters without `increment` (Cloudflare KV, etc.) fall back to `get → max → set`; correct in single-pod, accepts a tiny race window in multi-pod (mitigated by `Date.now()` floor).
834
+ - **Parallelized `invalidateByTags`** — fan-out reads + fan-out deletes via `Promise.all`. For Redis-backed adapters with pipelining, 5 tags × 100 keys completes in ~2 RTTs instead of 510. ~10× speedup on hot tags.
835
+ - **`CacheEngine.prefetch(key, opts, fetcher)`** — TanStack-equivalent cache warming. Single-flight semantics: 100 concurrent prefetches for the same key run the fetcher exactly once. Returns cached on hit, fetches + stores on miss, dedupes via the engine's pending map.
836
+ - **`withTimeout(adapter, { ms, onTimeout, onSlow })`** — adapter decorator that fail-fasts on slow backends. `onTimeout: 'miss'` (default) makes slow gets behave as cache misses (kit serves uncached); `'throw'` propagates `CacheTimeoutError`. `onSlow` callback for observability.
837
+ - **`scheduleBackground`** is now a public export from `@classytic/repo-core/cache` — hosts can use the same cross-runtime primitive for their own post-response work.
838
+
839
+ ### Cache layer — production hardening (TanStack-aligned) + cross-runtime
840
+
841
+ Six gaps in the v1 unified cache layer fixed before any prod traffic:
842
+
843
+ 1. **Single-flight on miss** — `CacheEngine.claimPending()` / `getPending()` / `resolvePending()` / `rejectPending()`. Concurrent misses for the same key wait on the first claimer's promise instead of running N redundant fetches. Cache-stampede prevention; TanStack `QueryClient`-equivalent.
844
+ 2. **Per-scope version-bump** — `bumpModelVersion(model, scopeKey?)` and `getModelVersion(model, scopeKey?)`. Writes inside `org:abc` no longer invalidate `org:xyz`'s cached reads. Targeted invalidation; matches TanStack's "exact match" semantics.
845
+ 3. **Cross-runtime SWR scheduling** — new `runtime.ts` exposes `scheduleBackground` that picks `setImmediate` on Node / Bun and `setTimeout(0)` on Cloudflare Workers / Deno Deploy / browser. Either way the callback fires after the current sync block + microtask queue, ensuring the user's response writes to the socket BEFORE the bg fetch's first await. (Old impl used `setImmediate` directly — `ReferenceError` on edge runtimes.)
846
+ 4. **TTL-bounded tag index** — index entries inherit their cached entries' TTLs (capped at 24h). Old impl used `ttlSeconds: 0` ("never expire" in Redis); side-index grew unboundedly on hot tags.
847
+ 5. **`error:<op>` rejects pending** — when the claimer's executor errors, the plugin's `error:<op>` hook rejects the deferred so single-flight waiters fail-fast. No hanging promises, no double-fetch on transient backend failures.
848
+ 6. **Allowlist-per-op shape keys** — `DEFAULT_SHAPE_KEYS_BY_OP` maps each read op to the fields that actually affect result shape. Only those fields participate in the cache key. Replaces the prior denylist (which would silently include any new context field a kit added — exploding miss rates if e.g. `requestId` slipped through). Hosts can override per-op via `cachePlugin({ shapeKeysByOp })`.
849
+
850
+ ### Code organization
851
+
852
+ The unified plugin (`@classytic/repo-core/cache`) is now split into focused modules:
853
+
854
+ ```
855
+ cache/
856
+ plugin/
857
+ index.ts # cachePlugin factory + types + handle (~200 LOC)
858
+ context.ts # typed context slots + extraction + shape-keys (~170 LOC)
859
+ read-hooks.ts # before/after/error for read ops (~180 LOC)
860
+ invalidation-hooks.ts # after for write ops (~60 LOC)
861
+ swr.ts # background-refresh scheduler (~50 LOC)
862
+ engine.ts # TTL + SWR + tag + version + single-flight (~220 LOC)
863
+ runtime.ts # cross-runtime scheduleBackground (~50 LOC)
864
+ ...
865
+ ```
866
+
867
+ Each module has one purpose. Replaces the prior 564-LOC `plugin.ts` mega-file.
868
+
869
+ ### Added — `Deferred<T>` utility
870
+
871
+ `createDeferred<T>()` exported from `@classytic/repo-core/cache` — a Promise plus its `resolve`/`reject` handles, externalized. Same primitive `Promise.withResolvers()` provides natively in Node 22+; we ship our own to keep the contract explicit and support older runtimes.
872
+
873
+ ### Added — Unified cache layer (`@classytic/repo-core/cache`)
874
+
875
+ One `cachePlugin({ adapter })` for every kit + arc + Express/Nest hosts. Replaces three independent SWR/TTL/tag implementations (mongokit's CRUD `cachePlugin` + aggregate `withAggCache`, sqlitekit's local `cachePlugin`, arc's `QueryCache`) with one canonical hook integration.
876
+
877
+ #### Public surface (`@classytic/repo-core/cache`)
878
+
879
+ ```ts
880
+ import {
881
+ cachePlugin, // hook integration — plugs into RepositoryBase
882
+ CacheEngine, // direct SWR + TTL + tag flow over a CacheAdapter
883
+ buildEnvelope, inspectEnvelope, type CacheEnvelope,
884
+ buildCacheKey, extractScopeTags, type BuildKeyInput,
885
+ appendKeyToTags, invalidateByTags as invalidateByTagsImpl,
886
+ bumpModelVersion, getModelVersion,
887
+ resolveCacheOptions, type CacheOptions, type ResolvedCacheOptions, type CacheReadResult,
888
+ // already shipped:
889
+ type CacheAdapter, createMemoryCacheAdapter, stableStringify,
890
+ } from '@classytic/repo-core/cache';
891
+ ```
892
+
893
+ #### TanStack Query-shaped per-call options
894
+
895
+ Same shape across CRUD + aggregate, kit-agnostic:
896
+
897
+ ```ts
898
+ {
899
+ staleTime?: number; // seconds fresh
900
+ gcTime?: number; // seconds retained past stale (default 60)
901
+ swr?: boolean; // serve-stale + bg refresh
902
+ tags?: readonly string[];
903
+ bypass?: boolean;
904
+ enabled?: boolean;
905
+ key?: string; // explicit override
906
+ }
907
+ ```
908
+
909
+ #### What the plugin does
910
+
911
+ 1. Subscribes to `before:<op>` / `after:<op>` for every read op (`getById`, `getAll`, `getOne`, `getByQuery`, `count`, `exists`, `distinct`, `aggregate`, `aggregatePaginate`) — configurable via `enabled: [...]`.
912
+ 2. Subscribes to `after:<op>` for every mutating op (`create`, `update`, `delete`, `claim`, ...) — configurable via `invalidating: [...]`. Bumps the model's version (orphans every cached read in O(1)) AND invalidates the model-tag (cross-aggregation invalidation).
913
+ 3. Auto-injects scope tags (`org:<id>`, `user:<id>`) from `context.filter` so cross-tenant cache poisoning is structurally impossible.
914
+ 4. Hooks register at `HOOK_PRIORITY.CACHE` (200) — multi-tenant + soft-delete (POLICY = 100) run first so their filter mutations land in the cache key.
915
+ 5. Attaches `repo.cache` handle exposing `invalidateByTags(tags)`, `bumpModelVersion(model)`, `clear()`.
916
+
917
+ #### Strictly-monotonic version bumps
918
+
919
+ `bumpModelVersion` uses `max(Date.now(), previous + 1)` so same-millisecond writes (cache prime + write hit at the same ms) don't collide, fixing a real correctness gap the prior `Date.now()`-only impl had.
920
+
921
+ #### `AggCacheOptions` is now an alias for `CacheOptions`
922
+
923
+ Same shape across CRUD + aggregate. Old field names (`ttl`, `staleWhileRevalidate`) removed — migrate to `staleTime`, `swr`. Ecosystem packages (mongokit, sqlitekit, arc) all consume the unified type.
924
+
925
+ #### Removed
926
+
927
+ - `/aggregate-cache` subpath — superseded by the unified `/cache` plugin (which handles aggregate ops natively via the `before:aggregate` hook).
928
+
929
+ #### Migration (kit + host)
930
+
931
+ ```ts
932
+ // Before — kit-specific cache plugins + constructor option
933
+ new Repository(model, [cachePlugin({ adapter, ttlSeconds: 60 })], {}, {
934
+ aggregateCache: adapter, // separate constructor option
935
+ });
936
+ repo.aggregate({ measures, cache: { ttl: 60, staleWhileRevalidate: true } });
937
+
938
+ // After — one plugin, one shape
939
+ new Repository(model, [
940
+ multiTenantPlugin({ tenantField: 'orgId' }),
941
+ cachePlugin({ adapter, defaults: { staleTime: 60, gcTime: 300, swr: true } }),
942
+ ]);
943
+ repo.aggregate({ measures, cache: { staleTime: 60, swr: true, tags: ['orders'] } });
944
+ repo.getAll(filter, { cache: { staleTime: 30 } });
945
+ await repo.cache?.invalidateByTags(['orders']);
946
+ ```
947
+
948
+ ### Added — `StandardRepo.claim()` and `claimVersion()` (atomic CAS, REQUIRED on the contract)
949
+
950
+ Standardizes the canonical state-machine write that every domain package was hand-rolling on top of `findOneAndUpdate`:
951
+
952
+ ```ts
953
+ const claimed = await repo.claim?.(runId, { from: 'waiting', to: 'running' }, {
954
+ lastHeartbeat: new Date(),
955
+ workerId: 'worker-12',
956
+ });
957
+ if (!claimed) return; // someone else got it
958
+ ```
959
+
960
+ **Cross-kit portable.** Mongokit compiles to `findOneAndUpdate({ _id, status: from }, { $set: { status: to, ...patch } })`. SQL kits compile to `UPDATE x SET ... WHERE id = ? AND status = <from> RETURNING *`. Prismakit compiles to `prisma.x.updateMany({ where: { id, status: from }, data: ... })` followed by a `findUnique` when `count > 0`. Same input, same null-on-race semantics across every backend.
961
+
962
+ **Pairs with `@classytic/primitives/state-machine`** — different layers:
963
+ - `defineStateMachine()` answers "is `from → to` legal in the model?" (compile-time table + early throw)
964
+ - `claim()` answers "did we win the transition vs concurrent writers?" (runtime null on race)
965
+
966
+ The state field defaults to `'status'` (matches the convention across `streamline`, `@classytic/order`, `revenue`, `invoice`); pass `{ field: 'phase', from, to }` for state machines keyed off a different column.
967
+
968
+ #### New types exported from `@classytic/repo-core/repository`
969
+
970
+ - `ClaimTransition` — `{ field?, from, to, where? }` argument shape for `claim` (`where` is the compound-CAS predicate slot — see below).
971
+ - `ClaimVersionTransition` — `{ field?, from: number | undefined, by?, where? }` argument shape for `claimVersion`. `from === undefined` is admitted for first-write CAS (matches docs whose version field is null OR missing).
972
+
973
+ #### Added to `StandardRepo<TDoc>` — REQUIRED methods (not optional)
974
+
975
+ ```ts
976
+ claim(
977
+ id: string,
978
+ transition: ClaimTransition,
979
+ patch?: Partial<TDoc>,
980
+ options?: WriteOptions,
981
+ ): Promise<TDoc | null>;
982
+
983
+ claimVersion(
984
+ id: string,
985
+ transition: ClaimVersionTransition,
986
+ update: Record<string, unknown>,
987
+ options?: WriteOptions,
988
+ ): Promise<TDoc | null>;
989
+ ```
990
+
991
+ **Required, not optional.** During pre-release dev iterations, `claim?` was optional as scaffolding while kits implemented. Both mongokit and sqlitekit ship them as concrete class primitives, and downstream domain packages (~10 in the classytic codebase) carry FSM verbs depending on them — none gracefully degrade. Required-on-the-contract removes the `if (repo.claim) { ... }` boilerplate at every call site and surfaces missing implementations at the conformance gate instead of at runtime.
992
+
993
+ #### `ClaimTransition.where` — compound-CAS predicate
994
+
995
+ Real-world audit (streamline, commission, yard, revenue, order, invoice): the bare `{ [idField]: id, [field]: from }` filter shape fits ~5% of atomic-claim sites in production. The other 95% carry compound predicates — paused guards, retry-time guards, heartbeat-staleness, sub-document `$elemMatch`, `$or` for missing-or-stale fields. Without a way to express those, `claim()` covered the textbook example but couldn't replace the hand-rolled CAS calls in production.
996
+
997
+ `ClaimTransition.where` AND-merges arbitrary predicates alongside the canonical id + state-field match:
998
+
999
+ ```ts
1000
+ const claimed = await repo.claim?.(runId, {
1001
+ from: 'waiting',
1002
+ to: 'running',
1003
+ where: {
1004
+ paused: { $ne: true },
1005
+ 'scheduling.retryAfter': { $lte: new Date() },
1006
+ },
1007
+ }, { lastHeartbeat: new Date() });
1008
+ ```
1009
+
1010
+ Cross-kit notes:
1011
+ - Mongokit: ANDed into the `findOneAndUpdate` filter.
1012
+ - SQL kits: ANDed into the `WHERE` clause (raw column literals accepted; portable Filter IR is compiled).
1013
+ - Prismakit: merged as additional keys on the `where` object.
1014
+
1015
+ Null-on-race semantics unchanged — if no doc matches the full compound filter (state OR any `where` predicate), `claim` returns `null`. The caller can't distinguish "lost race" from "guard predicate failed"; both mean "don't proceed."
1016
+
1017
+ Driven by streamline's audit (1 of 21 sites fit the bare shape; 21 of 21 fit the compound shape). Same pattern across the other audited packages.
1018
+
1019
+ #### `ClaimTransition.from` widened to `unknown | readonly unknown[]` — multi-source CAS
1020
+
1021
+ Single-value `from` covers the textbook one-source transition (`waiting → running`). Real-world state machines also need to claim from one of multiple source states — commission's `voidRecord` / `markClawedBack` / `endAgreement` / `_transition` (4 sites), media-kit's `pending|processing → error` catch-block. `from` now accepts an array; kit compilers emit `[stateField] IN (...)` (SQL) or `[stateField]: { $in: [...] }` (mongo).
1022
+
1023
+ ```ts
1024
+ // "From any non-terminal state to voided"
1025
+ await repo.claim?.(id, { from: ['pending', 'approved', 'sent'], to: 'voided' });
1026
+ ```
1027
+
1028
+ Single-value `from` is unchanged (back-compatible). Array form is opt-in — pass an array to enable.
1029
+
1030
+ **`from === to` is allowed** — the documented idempotent re-claim semantic. Yard's `reviseDeparture` writes `departed → departed` to atomically refresh the row's payload while asserting it hasn't moved on. The CAS still returns `null` if the row left the source state, so race-loss semantics hold.
1031
+
1032
+ #### Migration
1033
+
1034
+ Pre-0.4.0 callers wrote:
1035
+
1036
+ ```ts
1037
+ const claimed = await repo.findOneAndUpdate(
1038
+ { _id: id, status: 'waiting' },
1039
+ { $set: { status: 'running', lastHeartbeat: new Date() }, },
1040
+ );
1041
+ ```
1042
+
1043
+ Post-0.4.0:
1044
+
1045
+ ```ts
1046
+ const claimed = await repo.claim?.(id, { from: 'waiting', to: 'running' }, { lastHeartbeat: new Date() });
1047
+ ```
1048
+
1049
+ The old form keeps working — `claim()` is an additive optional method, not a rename.
1050
+
1051
+ ## [0.3.0] - 2026-04-29
1052
+
1053
+ ### Added — Aggregate pagination shapes
1054
+
1055
+ - `AggregatePaginationResultCore<TDoc>` and `AggregatePaginationResult<TDoc, TExtra>` join `Offset*` / `Keyset*` as the third pagination shape every kit reports. Mirrors offset (page / total / pages / hasNext / hasPrev) with `method: 'aggregate'` discriminant. Mongokit's existing local `AggregatePaginationResult` (3.10.x) becomes redundant — to be deleted in mongokit 4.0.
1056
+ - `AnyPaginationResult<TDoc, TExtra>` — union over the three result shapes. Use as the input type to anything that converts repo results into HTTP envelopes.
1057
+
1058
+ ### Added — HTTP wire envelopes
1059
+
1060
+ The repository result shapes (`OffsetPaginationResult`, etc.) carry the `method` discriminant, so the corresponding HTTP wire envelope is just `{ success: true } & Result`. Adding the literal here closes the **server/client envelope mismatch** — arc's HTTP server was emitting flattened paginated responses without the `method` field while arc-next's typed responses required it.
1061
+
1062
+ - `OffsetPaginationResponse<TDoc, TExtra>` = `{ success: true } & OffsetPaginationResult<TDoc, TExtra>`
1063
+ - `KeysetPaginationResponse<TDoc, TExtra>` = same for keyset
1064
+ - `AggregatePaginationResponse<TDoc, TExtra>` = same for aggregate
1065
+ - `BareListResponse<TDoc>` = `{ success: true; docs: TDoc[] }` for endpoints that don't paginate
1066
+ - `PaginatedResponse<TDoc, TExtra>` = union over all four. The discriminated-union contract is `success: true` literal first, `method` second — typed clients (arc-next, SDKs) narrow with `if (res.success && 'method' in res && res.method === 'offset')`.
1067
+
1068
+ ### Added — `toCanonicalList()` runtime normalizer
1069
+
1070
+ ```ts
1071
+ import { toCanonicalList } from '@classytic/repo-core/pagination';
1072
+
1073
+ const result = await userRepo.getAll(query);
1074
+ reply.send(toCanonicalList(result)); // → PaginatedResponse<User>
1075
+
1076
+ reply.send(toCanonicalList([u1, u2])); // → BareListResponse<User>
1077
+ ```
1078
+
1079
+ The single point where an internal `Result` becomes an external `Response`. Three overloads route bare arrays / paginated results to the right wire shape; `TExtra` fields (mongokit's `warning?: string`, etc.) flow through.
1080
+
1081
+ **Subtle behavior**: `success: true` is stamped *after* the spread, so a stale `success: false` accidentally present on the input cannot override the literal — paginated success path is always `success: true`. Tested.
1082
+
1083
+ ### Added — `isPaginatedResult()` type guard
1084
+
1085
+ Branches on the `method` discriminant rather than `Array.isArray`, so an empty paginated result still routes through the paginated branch. Used internally by `toCanonicalList`; exported for consumers writing custom envelope logic.
1086
+
1087
+ ### Test delta
1088
+
1089
+ 230 → 303 tests across 0.3.0. New coverage includes `tests/unit/pagination/canonical.test.ts` and the type-level coverage extensions in `result-types.test.ts` (35 tests landed with the aggregate / wire-envelope / `toCanonicalList` work), plus `tests/unit/repository/base-plugin-validation.test.ts` (6 tests for the `assertValidPlugin` guard).
1090
+
1091
+ ### Added — `SchemaGenerator<TModel>` interface in `/schema`
1092
+
1093
+ Canonical contract for repository kits' CRUD-schema generators. Mongokit's `buildCrudSchemasFromModel` and sqlitekit's `buildCrudSchemasFromTable` (and any future kit's equivalent) `satisfies SchemaGenerator<TKitModel>` at the call site, so arc's `MongooseAdapter.schemaGenerator` / `DrizzleAdapter.schemaGenerator` accept them by structural typing — no glue, no inheritance, no inline function signatures duplicated in every adapter.
1094
+
1095
+ - `SchemaGenerator<TModel = unknown>` — `(model, options?, context?) => CrudSchemas | Record<string, unknown>`.
1096
+ - `SchemaGeneratorContext` — resource-level context threaded at boot (`idField`, `resourceName`).
1097
+ - `isSchemaGenerator(value)` — runtime predicate (arity 1-3 functions). Conservative — doesn't invoke.
1098
+
1099
+ Each kit ships a compile-time conformance check (same playbook as mongokit's `RepositoryLike` conformance gate):
1100
+
1101
+ ```ts
1102
+ const _conformance: SchemaGenerator<Model<unknown>> = buildCrudSchemasFromModel;
1103
+ ```
1104
+
1105
+ Drift surfaces in the kit's typecheck immediately, before any consumer sees it.
1106
+
1107
+ 10 new tests in `tests/unit/schema/generator.test.ts`. Total repo-core: 293 → 303.
1108
+
1109
+ ### Added — `errors` module: canonical wire + throwable error contract
1110
+
1111
+ `@classytic/repo-core/errors` is now the single source of truth for error contracts across the org. Two complementary shapes:
1112
+
1113
+ - **`HttpError extends Error`** — the *throwable* shape. Plain `Error` with `status`, optional `code`, `meta`, `validationErrors`, `duplicate`. Kits classify their driver-specific errors into this shape; framework layers (arc) catch and serialize. Existing `HttpError` extended in 0.3 with `code?: string` and `meta?: Record<string, unknown>` (mongokit had these locally pre-3.12).
1114
+ - **`ErrorContract`** — the *wire* shape (RFC 7807 / Stripe-style). What gets serialized to JSON responses, dead-letter records, audit trails, inter-service envelopes. Flat top-level `code` / `message` / `status` matches the org-wide `{ success, ... }` envelope convention.
1115
+ - **`ErrorDetail`** — single field-scoped error (path / code / message). `ErrorContract.details` is `ReadonlyArray<ErrorDetail>`.
1116
+ - **`ERROR_CODES` + `ErrorCode`** — canonical lowercase + snake_case codes (`'validation_error'`, `'not_found'`, `'conflict'`, `'unauthorized'`, `'forbidden'`, `'rate_limited'`, `'idempotency_conflict'`, `'precondition_failed'`, `'internal_error'`, `'service_unavailable'`, `'timeout'`). Domain packages extend hierarchically (`'order.validation.missing_line'`).
1117
+ - **`toErrorContract(error)`** — converts any `Error` / `HttpError` / non-`Error` value to the canonical wire `ErrorContract`. `code` cascade: explicit `error.code` → status-derived → `'internal_error'`. Flattens mongokit-shaped `validationErrors` and `duplicate.fields` into the canonical `details[]` array.
1118
+ - **`statusToErrorCode(status)`** — well-known HTTP status → canonical code. Conservative mapping; unknown statuses fall through to `'internal_error'` so domain handlers explicitly opt in.
1119
+
1120
+ Consumed by mongokit (drops local `HttpError`), arc (`ArcError implements HttpError` with `status` getter), and any future kit / service. Relocated from `@classytic/primitives/errors` (which had `ErrorContract` + `ERROR_CODES` but not the throwable contract) — same playbook as the pagination, tenant, and events relocations: errors are infrastructure-shaped, not domain primitives.
1121
+
1122
+ 14 new tests in `tests/unit/errors/contract.test.ts`. Total repo-core: 279 → 293.
1123
+
1124
+ ### Added — `tenant` subpath (canonical home for tenant scope contract)
1125
+
1126
+ New subpath `@classytic/repo-core/tenant` ships:
1127
+ - `TenantConfig` — static config (`strategy`, `enabled`, `tenantField`, `fieldType`, `ref`, `contextKey`, `required`, `resolve`).
1128
+ - `TenantStrategy = 'field' | 'none' | 'custom'`, `TenantFieldType = 'objectId' | 'string'`.
1129
+ - `ResolvedTenantConfig` — the resolved-with-defaults shape returned by `resolveTenantConfig`.
1130
+ - `DEFAULT_TENANT_CONFIG` — sensible org-wide defaults (`tenantField: 'organizationId'`, `fieldType: 'objectId'`, `ref: 'organization'`, `required: true`).
1131
+ - `resolveTenantConfig(config?)` — normaliser; validates `'custom'` strategy requires `resolve`.
1132
+
1133
+ Relocated from `@classytic/primitives/tenant` (which has been removed in primitives 0.3 cleanup). Tenant scope is **infrastructure-shaped** — describes how queries get scoped, not a domain primitive like Money or Address. Repo-core is its proper home: it sits next to `context`, `filter`, `hooks`, `schema`, `cache` — every other repository contract — and lets mongokit / sqlitekit / future kits consume it through the existing `@classytic/repo-core` peer dep without pulling primitives just for one type.
1134
+
1135
+ **Custom tenancy escape hatch** unchanged: `strategy: 'custom'` + `resolve: (ctx) => filterShape` covers multi-field composites, region+partner shards, hash-derived filters, anything that doesn't fit `field === id`.
1136
+
1137
+ 14 new tests in `tests/unit/tenant/resolve.test.ts` (ported from primitives' suite). Total repo-core: 265 → 279 tests.
1138
+
1139
+ ### Added — schema-builder vocabulary
1140
+
1141
+ - **`SchemaBuilderOptions.excludeFields`** — global field exclusion. Fields listed here are dropped from create / update / response schemas in one place. Equivalent to setting `create.omitFields`, `update.omitFields`, AND `response.omitFields` to the same list. Use for fields that should never appear in any HTTP-facing schema.
1142
+ - **`SchemaBuilderOptions.response`** with `omitFields?: string[]` — response-schema overrides. Drops extra fields from the response shape without marking them globally hidden.
1143
+ - **`CrudSchemas.response?: JsonSchema`** — optional response-shape schema. Includes server-set fields (`createdAt`, `updatedAt`, `_id`, immutable / readonly / systemManaged) since those ARE returned to clients. Only `fieldRules[field].hidden: true` strips automatically. Set `additionalProperties: true` so virtuals / computed fields pass through.
1144
+ - **`FieldRule.hidden?: boolean`** — strips the field from the response shape. Distinct from `systemManaged` (request-body concern). Use for passwords, secrets, internal scoring.
1145
+ - **`collectFieldsToOmit(options, 'response')`** — third purpose alongside `'create'` / `'update'`. Implements the response policy (only `hidden` + `excludeFields` + `response.omitFields`).
1146
+
1147
+ These are the contracts mongokit 3.12 implements, arc 2.12's MongooseAdapter consumes, and any future kit (sqlitekit, prismakit) inherits for free.
1148
+
1149
+ ### Hardened — `RepositoryBase` plugin-shape validation
1150
+
1151
+ `RepositoryBase.use()` and the constructor's plugin loop now reject malformed plugin entries up front via `assertValidPlugin()`. The motivating field bug: `new Repository(Model, ['organizationId'], opts)` — passing a tenant-field string array where the constructor expected `plugins[]` — used to crash deep in the call site with `TypeError: plugin.apply is not a function`, cascade-failing every test that booted the app. The validator now throws a single descriptive `TypeError` at construction with the offending index and a hint about the common `tenantField`-in-the-wrong-slot mistake:
1152
+
1153
+ ```
1154
+ [repo-core] Repository "Foo": plugin at index 0 has wrong type.
1155
+ Expected a function or { name, apply(repo) } object — got string 'organizationId'.
1156
+ Common cause: `new Repository(Model, [tenantField], opts)` — second argument must be a plugins array.
1157
+ ```
1158
+
1159
+ Lock-in: `tests/unit/repository/base-plugin-validation.test.ts` (6 cases covering string/null/object-without-apply/function/object/post-construction `use()` paths).
1160
+
1161
+ ### Migration — mongokit 4.0, arc 2.12, arc-next 0.6
1162
+
1163
+ Three downstream changes drop their local copies and import directly:
1164
+
1165
+ 1. **mongokit 4.0** — deletes its local `AggregatePaginationResult` declaration and `PaginationResult` union; consumers that imported them from `@classytic/mongokit` must switch to `@classytic/repo-core/pagination`. (Breaking.)
1166
+ 2. **arc 2.12** — `fastifyAdapter` calls `toCanonicalList()` once instead of inline-flattening offset and falling through keyset/aggregate as nested `data`. Closes a real wire-envelope-mismatch bug.
1167
+ 3. **arc-next 0.6** — adds `@classytic/repo-core` as peer dep, deletes its local `OffsetPaginationResponse` / `KeysetPaginationResponse` / `AggregatePaginationResponse` / `PaginatedResponse` types. Server and client now share one declaration — the `method` field asymmetry is impossible by construction.
1168
+
1169
+ No breaking changes inside `@classytic/repo-core` itself — purely additive.
1170
+
1171
+ ## [0.2.0] - 2026-04-22
1172
+
1173
+ ### Added — Update IR (portable write-side primitive)
1174
+
1175
+ - **New `@classytic/repo-core/update` subpath.** The write-side counterpart to `@classytic/repo-core/filter`. Plugins and arc's infrastructure stores compose an `UpdateSpec` once; each kit compiles it to its native shape.
1176
+ - **Types:** `UpdateSpec` (tagged union on `op: 'update'`, four buckets: `set` / `unset` / `setOnInsert` / `inc`), `UpdateInput` (union of `UpdateSpec` | kit-native `Record<string, unknown>` | Mongo pipeline `Record<string, unknown>[]`).
1177
+ - **Builders:** `update({ set, unset, setOnInsert, inc })` (root), `setFields`, `unsetFields(...f)`, `setOnInsertFields`, `incFields`, `combineUpdates(...specs)` (later-wins merge, `unset` de-duplicates).
1178
+ - **Guards:** `isUpdateSpec` (routes portable IR to the compiler), `isUpdatePipeline` (lets SQL kits short-circuit with `UnsupportedOperationError`).
1179
+ - **Compilers:** `compileUpdateSpecToMongo(spec)` emits `{ $set, $unset, $setOnInsert, $inc }`. `compileUpdateSpecToSql(spec)` emits a `SqlUpdatePlan` with `data` / `unset` / `inc` / `insertDefaults` buckets, leaving SQL generation (quoting, `ON CONFLICT`, parameter binding) to the kit.
1180
+ - **`StandardRepo.findOneAndUpdate` + `updateMany` widened to `UpdateInput`.** Accepts all three forms — portable `UpdateSpec`, kit-native record, Mongo aggregation pipeline. Kits dispatch with `isUpdateSpec`. The existing raw-record and pipeline paths remain unchanged; the IR is purely additive so consumers don't need to migrate. Arc's infrastructure stores (outbox, idempotency, audit) will switch to the IR over a subsequent release to close the "Mongo-shaped store" gap flagged in the April 2026 cross-surface review.
1181
+
1182
+ **Motivation (Arc April 2026 review):** arc's `EventOutbox`, `IdempotencyStore`, and `AuditStore` adapters use Mongo operator records (`$set`, `$inc`, `$unset`, `$setOnInsert`, `$or`, `$lte`, ...) directly against `RepositoryLike.findOneAndUpdate`. That works on mongokit but fails on sqlitekit — whose `findOneAndUpdate` treats `data` as flat column overwrites and would literally set a column named `$set`. The Update IR closes the gap without forcing every kit to ship its own Mongo-operator compatibility layer.
1183
+
1184
+ **Rationale for scope:** the IR covers the subset every backend supports (atomic set / unset / inc / insert-default). Kit-native features — Mongo `$push`/`$pull`/`$addToSet`, aggregation pipeline updates, Postgres `jsonb_set`, SQL `CASE` expressions — stay on the kit-native path via `UpdateInput`'s raw-record and pipeline forms. No lowest-common-denominator bloat; no feature loss for kits that already offer more.
1185
+
1186
+ **Test delta**: 193 → 230 tests (37 new across `tests/unit/update/builders`, `/guard`, `/compile`).
1187
+
1188
+ ### Changed — breaking: `StandardRepo` write signatures
1189
+
1190
+ `StandardRepo.findOneAndUpdate(filter, update, ...)` and `updateMany(filter, data, ...)` — the second parameter is now typed `UpdateInput` (was `Record<string, unknown> | Record<string, unknown>[]` and `Record<string, unknown>` respectively). Every call site that compiled against 0.1.0 keeps compiling: `Record<string, unknown>` and `Record<string, unknown>[]` are subtypes of `UpdateInput`. The break is on the **implementer** side — any kit that declared only the old parameter type no longer structurally satisfies `StandardRepo` under strict contravariance. mongokit 3.11.0 and sqlitekit 0.1.1 already ship with the widened signatures; third-party kits need to widen before bumping their `@classytic/repo-core` peer dep.
1191
+
1192
+ ### Changed — breaking: `updateMany` + `deleteMany` promoted to required members of `StandardRepo`
1193
+
1194
+ Both methods were optional (`updateMany?` / `deleteMany?`) in 0.1.0; they're required in 0.2.0. Rationale: every real backend has a native bulk-update and bulk-delete primitive, and arc's infrastructure stores (outbox, idempotency, audit cleanup) assume both are callable without feature-detection. Leaving them optional invited the "forgot to wire `batchOperationsPlugin`" runtime `TypeError` footgun that earlier releases of mongokit shipped — with the promotion, the type system catches missing implementations at the kit boundary.
1195
+
1196
+ **Impact**:
1197
+ - **Kits**: any kit declaring `class FooRepo<T> implements StandardRepo<T>` must provide `updateMany` and `deleteMany` or fail to compile. mongokit 3.11.0 and sqlitekit 0.1.1 both ship these as class primitives, so their conformance stays green.
1198
+ - **Consumers of `RepositoryLike<T> = MinimalRepo<T> & Partial<StandardRepo<T>>`** (arc's pattern) are unaffected — `Partial` reimposes optionality for feature detection at the arc adapter boundary. `if (repo.updateMany)` guards keep working.
1199
+ - `bulkWrite` stays optional — the mongoose-shaped `BulkWriteOperation` has no clean SQL analogue, and every kit would ship an uninteresting fan-out wrapper otherwise.
1200
+
1201
+ ### Naming — `UpdateInput` collision with mongokit
1202
+
1203
+ `@classytic/repo-core/update` exports `UpdateInput` as the union `UpdateSpec | Record<string, unknown> | Record<string, unknown>[]`. `@classytic/mongokit` currently **also** exports a type named `UpdateInput<TDoc> = Partial<Omit<TDoc, '_id' | 'createdAt' | '__v'>>` — a completely different, document-typed shape used by `repo.update(id, data)`. If you write `import { UpdateInput } from '@classytic/mongokit'`, you get mongokit's generic; if you write `import type { UpdateInput } from '@classytic/repo-core/update'`, you get the union. Both names may appear in the same consumer file — import at least one with an alias (`import type { UpdateInput as UpdatePatch } from '@classytic/mongokit'`). mongokit will rename its local type in a follow-up release to close the collision permanently.
1204
+
1205
+ ### Added
1206
+ - Phase 0 scaffold: package.json, tsconfig, tsdown, biome, vitest (4-tier), knip
1207
+ - `@classytic/repo-core/hooks` — `HOOK_PRIORITY` constants + `HookPriority` type
1208
+ - `@classytic/repo-core/operations` — `CORE_OP_REGISTRY`, `extendRegistry`, `listOperations`, `mutatingOperations`, `readOperations`, `operationsByPolicyKey`, `describe`; 17 core ops, driver-free
1209
+ - `@classytic/repo-core/errors` — `HttpError`, `createError`, `isHttpError`, `conservativeMongoIsDuplicateKey`, `toDuplicateKeyHttpError`
1210
+ - `@classytic/repo-core/pagination` — `encodeCursor`/`decodeCursor` (URL-safe base64, mongokit ≤3.x compat), `validateCursorSort`, `validateCursorVersion`, `normalizeSort`, `validateKeysetSort`, `invertSort`, `getPrimaryField`, `validateLimit`, `validatePage`, `shouldWarnDeepPagination`, `calculateSkip`, `calculateTotalPages`
1211
+ - INFRA.md tracking doc + 4-tier test structure per monorepo testing-infrastructure.md
1212
+ - 74 unit tests across 6 files, full suite runs in ~360 ms
1213
+ - `@classytic/repo-core/filter` — Filter IR types (`Filter` discriminated union), combinators (`eq`, `ne`, `gt`/`gte`/`lt`/`lte`, `in_`/`anyOf`, `nin`/`noneOf`, `like`, `regex`, `exists`, `and`, `or`, `not`/`invert`), constants (`TRUE`, `FALSE`), runtime guard (`isFilter`), traversal (`walkFilter`, `mapFilter`, `collectFields`), in-memory evaluator (`matchFilter`, `asPredicate`). Boolean absorbing/identity elimination baked in.
1214
+ - `@classytic/repo-core/repository` — arc-aligned contract types: `MinimalRepo<TDoc>` (5-method floor), `StandardRepo<TDoc>` (recommended surface), option/result types (`QueryOptions`, `WriteOptions`, `DeleteOptions`, `FindOneAndUpdateOptions`, `DeleteResult`, `DeleteManyResult`, `UpdateManyResult`, `PaginationParams`), `RepositorySession`, `InferDoc<R>`.
1215
+ - 43 additional unit tests (builders, walk, match) bringing total to 117.
1216
+ - **Filter IR expansion** — sugar builders: `between`, `startsWith`, `endsWith`, `contains`, `iEq`, `isNull`, `isNotNull` (desugar to existing ops); new `raw` escape-hatch op for driver-native fragments (e.g. pgvector `<=>`, SQLite JSON1 path, Mongo `$geoWithin`).
1217
+ - `@classytic/repo-core/query-parser` — URL → `ParsedQuery<Filter>` driver-agnostic parser. Bracket grammar (`field[gte]=18`, `field[in]=a,b`, `field[contains]=text`). Shared types (`ParsedQuery`, `ParsedSort`, `ParsedSelect`, `ParsedPopulate`, `QueryParserOptions`, `BracketOperator`) consumed identically by every kit and both frontends (arc-next, fluid).
1218
+ - 36 more unit tests covering sugar builders + QueryParser. Total: **153 tests, 11 files, green on vitest 4**.
1219
+ - Upgraded to **vitest 4.1**, **typescript 6.0**, **biome 2.4.12**. Vitest config migrated to new `pool` / `fileParallelism` top-level API.
1220
+ - **M3 landed: `RepositoryBase` abstract class** at `@classytic/repo-core/repository`. Owns `HookEngine`, plugin installation, context builder, `_emitAfter` / `_emitError`, and the `_cachedValue` cache-short-circuit helper. Kits extend it instead of reinventing the hook layer.
1221
+ - **M4 landed: 5 portable plugins** — `@classytic/repo-core/plugins/timestamp`, `/multi-tenant`, `/soft-delete`, `/audit`, `/cache`. All Filter-IR-native. Multi-tenant + soft-delete inject scope via `and(existing, eq(...))` / `and(existing, isNull(...))` — no Mongo-specific `$`-operators. Cache includes pluggable `CacheAdapter` interface + reference `createMemoryCacheAdapter`.
1222
+ - **Tightened the scope rule for plugins** — skipped observability / validation-chain / field-filter / cascade / custom-id. Rule: a plugin lives in repo-core only if every backend needs it AND no backend provides it natively. The skipped ones are either arc's job (field-filter), host cookbook (observability, custom-id), zod's job (validation-chain), or SQL-native (cascade).
1223
+ - **`StandardRepo.withTransaction` signature fixed** — was `(session) => T`, mongoose leak. Now `(txRepo: this) => T` — caller writes `await txRepo.create(...)`, never touches session. SQL / Prisma kits bind the tx connection to a new repo; mongokit returns a session-threaded proxy.
1224
+ - `QueryOptions.session` re-documented as mongoose-specific.
1225
+ - `RepositoryBase.on` / `off` now generic over listener-data type so typed plugins (`(ctx: RepositoryContext) => void`) don't need casts.
1226
+ - **HookEngine** exposed at `@classytic/repo-core/hooks` — `DEFAULT_LISTENER_PRIORITY`, `HookEngine` class, `HookListener`, `HookMode`, `PrioritizedHook`, `EventPhase` types.
1227
+ - **Context subpath** at `@classytic/repo-core/context` — `RepositoryContext` type exposed independently for plugin authors.
1228
+ - **`HookEngine.listeners()`** — read-only snapshot of the listener registry (frozen buckets). Lets kits expose a back-compat `_hooks: Map<event, PrioritizedHook[]>` getter without handing out mutable internal state. Used by mongokit 3.10's read-through `_hooks` shim.
1229
+ - **`RepositoryBase._buildContext` always awaits `before:*` hooks** regardless of engine mode — policy plugins must mutate context synchronously before the driver call fires. After- and error-hooks still honor `hooks: 'sync'` for fire-and-forget observability. Previous behavior (fire-and-forget in sync mode) would let driver calls race ahead of tenant/soft-delete scope injection; tracked as a latent bug surfaced by the mongokit 3.10 migration.
1230
+
1231
+ ### Changed — plugins move out, primitives move in
1232
+
1233
+ - **All 5 plugins deleted from `@classytic/repo-core/plugins/*`** — `timestamp`, `soft-delete`, `multi-tenant`, `audit`, `cache` no longer ship from this package. Rationale: end-users install a kit, never repo-core directly, so plugins belong in the namespace users actually import. Each kit (mongokit, sqlitekit, pgkit, prismakit) owns its own plugin implementations, which lets each use driver-native features (mongoose native timestamps, SQLite triggers, Postgres `now()`, Prisma `@default`) instead of a lowest-common-denominator JS emulation.
1234
+ - **New `@classytic/repo-core/cache` subpath** — the plugin-composition primitives that every kit's cachePlugin shares:
1235
+ - `CacheAdapter` interface (get / set / del / delByPattern)
1236
+ - `stableStringify` — deterministic JSON keying for cache buckets
1237
+ - `createMemoryCacheAdapter` — reference in-memory adapter for tests + single-process apps
1238
+ - **New scope helpers in `@classytic/repo-core/filter`** — `buildTenantScope(existing, tenantField, tenantId)` and `mergeScope(existing, scope)`. Every policy plugin (multi-tenant / soft-delete / org-boundary) AND-s a predicate into an existing filter while handling three shapes (undefined / Filter IR / flat record). Lifted into `/filter` so each kit's plugin composes the same merge semantics.
1239
+ - **Architectural principle codified** — "Repo-core is invisible infrastructure. End-users install a kit; repo-core exists for kit authors." See INFRA.md §3.
1240
+
1241
+ ### Arc integration review — 2026-04-19
1242
+
1243
+ Changes landed in response to the Arc 2.10 maintainer's end-to-end integration report (see `ARC_INTEGRATION_REPORT.md`). All three non-blocking enhancements adopted; sqlitekit-side blockers are tracked on the sqlitekit package, not here.
1244
+
1245
+ - **`OffsetPaginationResult<TDoc, TExtra>` + `KeysetPaginationResult<TDoc, TExtra>`** — added an optional second generic so kits can surface typed extras alongside the core envelope (mongokit emits `warning?: string` on deep-page reads, pgkit could surface `queryPlan`, sqlitekit could surface vacuum hints). Defaults to `Record<string, never>` so existing consumers (`OffsetPaginationResult<User>`) see zero behavioral change. Both types also export their core interface (`OffsetPaginationResultCore` / `KeysetPaginationResultCore`) for StandardRepo contract references. The `method` discriminant carries through the intersection so `if (result.method === 'offset')` narrowing keeps working.
1246
+ - **`HOOK_EVENTS` constant + `HookEventName` type** at `@classytic/repo-core/hooks` — canonical string-constant registry for every `before:* / after:* / error:*` event across the MinimalRepo + StandardRepo op set (17 ops × 3 phases = 51 events). Plugin authors subscribe via `HOOK_EVENTS.BEFORE_CREATE` instead of raw strings so typos become compile errors instead of silent no-ops. Kits with additional native ops (mongokit's `aggregate` / `bulkWrite`) compose their own extended constant on top. Cross-kit plugins written against `HOOK_EVENTS` work identically on every kit for the shared op set.
1247
+ - **`CacheAdapter.clear?(pattern?)`** replaces the previous `delByPattern?(pattern)` — aligns with mongokit's `CacheAdapter` and Arc's `CacheStore` so one Redis / KV / Memcached implementation plugs into every consumer. `clear()` with no argument wipes everything; `clear('prefix:*')` is glob-matched. `createMemoryCacheAdapter` reference impl updated. Breaking change for anything calling `adapter.delByPattern` directly — sqlitekit's cache plugin (the only in-tree caller) migrated in the same commit.
1248
+ - **`CacheAdapter.delete(key)`** — renamed from `del(key)` for consistency with JavaScript's native `Map.delete` / `Set.delete`, `MinimalRepo.delete(id)` in this same package, arc's `RepositoryLike.delete`, and every higher-level cache library (Keyv, etc.). Redis clients keep their own `.del()` — the adapter implementation translates. Applied across `@classytic/repo-core/cache` (interface + `createMemoryCacheAdapter`) and `@classytic/mongokit` (its own `CacheAdapter` type + `createMemoryCache` reference impl + every test adapter). The rename arrived **before first publish**, so no migration cost for external consumers — it's simply the shipping name.
1249
+ - **TTL unit stays seconds** (`ttlSeconds`) — matches Redis `SET EX seconds` and mongokit's existing `ttl` semantics. Arc's `ttlMs` was the outlier; the Arc team agreed to align on seconds.
1250
+ - **Sync-or-async return types preserved** on `CacheAdapter` — memory-backed adapters return synchronously without a microtask hop; Redis adapters return Promises. Consumers `await` either way at no runtime cost.
1251
+
1252
+ **Test delta**: 153 → 177 tests (24 new covering HOOK_EVENTS exhaustiveness, pagination TExtra narrowing, and CacheAdapter + stableStringify round-trip).
1253
+
1254
+ ### Unified `withTransaction` contract — mongokit caught up
1255
+
1256
+ The `StandardRepo.withTransaction` contract at `@classytic/repo-core/repository` has always specified `fn: (txRepo: this) => Promise<T>` — the bound-tx shape sqlitekit has implemented since 0.1. Mongokit 3.9 deviated from the contract and passed a raw `ClientSession` instead. Mongokit 3.10 fixes that: its `withTransaction` now hands over a session-threaded proxy repository matching the canonical signature. Cross-kit plugins and apps that depend on `StandardRepo.withTransaction` now work identically against mongokit and sqlitekit — one contract, no kit-specific branches.
1257
+
1258
+ The contract docstring in `src/repository/types.ts` was already accurate; this is the mongokit-side implementation catching up. See `@classytic/mongokit` 3.10 release notes for the migration diff — this is a **breaking change for mongokit 3.x users** but repo-core's shape is unchanged.
1259
+
1260
+ ### Consumed by
1261
+
1262
+ - **`@classytic/mongokit`** — `Repository extends RepositoryBase`; hook engine, plugin-order validator, and `HOOK_PRIORITY` sourced from repo-core. Ships its own Mongo-optimized plugins (unchanged from 3.9).
1263
+ - **`@classytic/sqlitekit`** — extends `RepositoryBase`; ships its own SQLite-optimized plugins at `@classytic/sqlitekit/plugins/{timestamp,soft-delete,multi-tenant,audit,cache}`. Imports `CacheAdapter` + `stableStringify` + `buildTenantScope` from repo-core.