@classytic/supplier-performance 0.3.1 → 0.4.1

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.
package/CHANGELOG.md CHANGED
@@ -1,89 +1,7 @@
1
- # Changelog
2
-
3
- ## [0.3.1] — 2026-07-16
1
+ # Changelog
4
2
 
5
- ### Fixed
3
+ ## Unreleased
6
4
 
7
- - injectTenantField no longer force-indexes the tenant field: the compound
8
- prepend makes the tenant the leading key of every index, so the bare single
9
- was a redundant prefix paid on every insert (PACKAGE_RULES P11.1, fleet
10
- index audit). A dedicated tenant index is still created when a schema
11
- declares no compounds to prepend. Index-declaration change only.
5
+ ## 0.4.1 — 2026-11-28
12
6
 
13
- ## [0.3.0] — unpublished (2026-07-15)
14
-
15
- ### Changed — kit refresh (peer floors: mongokit >=3.22.0, repo-core >=0.13.0, primitives >=0.11.0)
16
-
17
- - Verified clean against the mongokit 3.22 sweep (no FSM boilerplate, no
18
- fences needed). Clean registry install; suite green.
19
-
20
- ## 0.2.1
21
-
22
- Patch — outbox support, §P8.1 session guard, awaited publish, tenant-isolation fix.
23
-
24
- ## 0.2.0
25
-
26
- Stack upgrade + tenant-isolation fix + PACKAGE_RULES compliance + real test
27
- coverage. No new features.
28
-
29
- ### Fixed (security)
30
-
31
- - **Cross-tenant leak — `multiTenantPlugin` was never wired.** Both
32
- repositories were constructed with only `methodRegistryPlugin()`, so reads
33
- and writes were NOT tenant-scoped despite the schema carrying an
34
- `organizationId` field. The engine now derives one resolved tenant config
35
- (via repo-core's `resolveTenantConfig`) and wires `multiTenantPlugin` on
36
- every repo — scoping is enforced at POLICY priority and missing
37
- `organizationId` throws (fail-closed). A `tenant-plugin-probe` integration
38
- test plus an end-to-end isolation test guard this.
39
-
40
- ### Changed (breaking)
41
-
42
- - **Peers:** `@classytic/mongokit` `>=3.13.0` → `>=3.16.0`; **added**
43
- `@classytic/repo-core >=0.6.0` (rule 11 — the code imports
44
- `@classytic/repo-core/tenant` and `/errors`); **added** `zod >=4.0.0`
45
- (event catalog). `@classytic/primitives` stays `>=0.5.0` (devDep bumped to
46
- `^0.7.2`).
47
- - **Tenant config clean break.** Dropped the legacy
48
- `{ tenantFieldType, multiTenant }` shape and the `'string'` default. Tenant
49
- config is now a repo-core `TenantConfig` (or boolean), defaulting to
50
- repo-core's standard `fieldType: 'objectId'`, `required: true`. Hosts with
51
- string/UUID org ids pass `{ fieldType: 'string' }`. Mongokit-runtime knobs
52
- (`skipWhen`, `resolveContext`, `allowDataInjection`, `onMismatch`,
53
- `skipOperations`) forward through the `tenant` object.
54
- - **Errors.** Removed `RecordEventValidationError extends Error`. Validation now
55
- throws `SupplierPerformanceValidationError implements HttpError` (status 400,
56
- code `supplier_performance.validation.invalid_input`) so arc serializes it
57
- correctly.
58
-
59
- ### Added
60
-
61
- - **Zod event catalog (rule 18):** `supplierPerformanceEventDefinitions`
62
- exported from the package root AND the new `./events` subpath; per-event Zod
63
- schemas (`z.iso.datetime()` timestamps), a no-drift invariant test, and
64
- safeParse happy/rejection tests.
65
- - **Cancellation / retry threading:** `SupplierPerformanceContext` now carries
66
- `signal` / `retryPolicy`, forwarded to repo calls via `repoOptionsFromCtx`.
67
- - **Test coverage** raised from one unit file to five files / 21 tests:
68
- event-catalog no-drift, tenant probe + isolation, computeScore aggregation +
69
- idempotency (re-run does not double-aggregate, exactly one snapshot row),
70
- model-collision policy.
71
-
72
- ### Build hygiene
73
-
74
- - `tsconfig.json`: enabled `exactOptionalPropertyTypes`; disabled
75
- `declarationMap` and `sourceMap` (no source leaks). `InProcessSupplierPerformanceBus`
76
- gained `close()`. `CHANGELOG.md` added to published `files`.
77
-
78
- ### Notes (verified, intentionally NOT changed)
79
-
80
- - **No outbox / P8 dispatch machinery.** Durable delivery is host-composed
81
- (§5.5 / §16); only a transport is wired, so publish failures are swallowed
82
- (rule 14). Not a gap.
83
- - **No capabilities boot gate.** The package uses no transactions — every verb
84
- is a single-doc read/write/upsert — so the gate (transactions-only) does not
85
- apply.
86
- - **No rating-state CAS.** Scorecards are recomputable snapshots, not a state
87
- machine; `computeScore` idempotency rests on the unique index + upsert.
88
- - **`recordEvent` dedup stays host-owned** by design (hosts key differently:
89
- PO-line vs PO+SKU). The kernel does not enforce a metric-dedup unique index.
7
+ - Peer floors raised to what the package is tested against: `@classytic/mongokit >=3.47.0`, `@classytic/primitives >=0.39.0`, `@classytic/repo-core >=0.39.0`, `mongoose >=9.13.1`. Consumers: none to change.
package/LICENSE CHANGED
@@ -1,21 +1,75 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Classytic
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ Classytic Source-Available License (Community & Commercial), Version 1.0
2
+
3
+ Copyright (c) 2026 Classytic LLC. All rights reserved.
4
+
5
+ This software is source-available, not open source. Please read this License
6
+ before using it.
7
+
8
+ 1. DEFINITIONS
9
+ "Software" means the contents of this package and any accompanying source
10
+ code, object code, or documentation, in any form.
11
+ "Licensor" means Classytic LLC, a limited liability company organized in the
12
+ United States.
13
+ "You" means the individual or legal entity exercising rights under this
14
+ License.
15
+ "Evaluation Use" means use for evaluation, development, testing,
16
+ experimentation, or internal non-commercial purposes only.
17
+ "Production Use" means any use of the Software that is live, commercial,
18
+ revenue-generating, or customer-facing, or any use other than Evaluation Use.
19
+ "Commercial License" means a separate written agreement executed with
20
+ Licensor that grants Production Use rights.
21
+
22
+ 2. OWNERSHIP
23
+ The Software is licensed, not sold. Licensor retains all right, title, and
24
+ interest in and to the Software, including all intellectual property rights.
25
+ All rights not expressly granted in this License are reserved by Licensor.
26
+
27
+ 3. EVALUATION GRANT
28
+ Subject to Your compliance with this License, Licensor grants You a
29
+ worldwide, royalty-free, non-exclusive, non-transferable, revocable license
30
+ to download, install, run, and modify the Software solely for Evaluation Use.
31
+
32
+ 4. PRODUCTION USE REQUIRES A COMMERCIAL LICENSE
33
+ Production Use of the Software is NOT permitted under this License and
34
+ requires a Commercial License from Licensor. A Commercial License may be
35
+ granted at Licensor's discretion, with or without a fee, and may confer
36
+ perpetual, irrevocable, and transferable Production Use rights as set out in
37
+ that agreement. Contact licensing@classytic.com to obtain one.
38
+
39
+ 5. RESTRICTIONS
40
+ You may not:
41
+ (a) make any Production Use of the Software without a Commercial License;
42
+ (b) redistribute, resell, rent, sublicense, or otherwise make the Software
43
+ (in whole or in part, original or modified) available to third parties as
44
+ a stand-alone product, framework, library, or hosted/managed service that
45
+ competes with the Software or with Licensor;
46
+ (c) remove, obscure, or alter any copyright, license, or attribution notice.
47
+
48
+ 6. FEEDBACK AND CONTRIBUTIONS
49
+ Any feedback, suggestions, or contributions You provide relating to the
50
+ Software may be used by Licensor for any purpose without obligation to You.
51
+
52
+ 7. TERMINATION
53
+ This License and the Evaluation Grant terminate automatically if You breach
54
+ any term. Upon termination You must cease all use of the Software and destroy
55
+ all copies in Your possession. Rights under a Commercial License are governed
56
+ by that agreement's own terms and survive termination of this License to the
57
+ extent stated there.
58
+
59
+ 8. DISCLAIMER OF WARRANTY
60
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
61
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
62
+ FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.
63
+
64
+ 9. LIMITATION OF LIABILITY
65
+ TO THE MAXIMUM EXTENT PERMITTED BY LAW, IN NO EVENT SHALL LICENSOR BE LIABLE
66
+ FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
67
+ TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE
68
+ OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
69
+
70
+ 10. GOVERNING LAW
71
+ This License is governed by the laws of the State of Delaware, United States,
72
+ without regard to its conflict-of-laws principles. (Adjust to Your LLC's state
73
+ of formation.)
74
+
75
+ For commercial licensing, contact: licensing@classytic.com
@@ -1,4 +1,5 @@
1
- import { createEvent, matchEventPattern } from "@classytic/primitives/events";
1
+ import { createEvent } from "@classytic/primitives/events";
2
+ import { InProcessEventBus } from "@classytic/primitives/event-infra";
2
3
  import { z } from "zod";
3
4
  //#region src/domain/enums/event-type.enum.ts
4
5
  /**
@@ -60,46 +61,23 @@ function createEvent$1(type, payload, ctx, meta) {
60
61
  //#endregion
61
62
  //#region src/events/in-process-bus.ts
62
63
  /**
63
- * Zero-dep in-process event bus. Subscribers can use glob patterns
64
- * (`supplier_performance:*`, `*`, exact type). Subscriber errors are
65
- * caught and logged — they never break the emitter or sibling
66
- * subscribers.
64
+ * In-process fan-out transport — the default when the host injects none.
67
65
  *
68
- * Drop-in compatible with any `EventTransport` — hosts replace it by
69
- * passing their own at `createSupplierPerformance({ eventTransport })`.
66
+ * A thin subclass of `@classytic/primitives/event-infra`'s shared
67
+ * `InProcessEventBus` (the single implementation every kernel now defaults
68
+ * to). Prior semantics preserved exactly: glob matching via
69
+ * `matchEventPattern` (exact / `*` / `prefix.*` / `prefix:*`), Set-dedup so a
70
+ * handler matched by multiple patterns fires once, per-handler error
71
+ * isolation (errors logged; default `console`), idempotent `close()`.
72
+ * Structurally identical to arc's `MemoryEventTransport`.
70
73
  */
71
- var InProcessSupplierPerformanceBus = class {
72
- name = "in-process-supplier-performance";
73
- patterns = /* @__PURE__ */ new Map();
74
- logger;
74
+ var InProcessSupplierPerformanceBus = class extends InProcessEventBus {
75
75
  constructor(options = {}) {
76
- this.logger = options.logger ?? console;
77
- }
78
- async publish(event) {
79
- for (const [pattern, handlers] of this.patterns) {
80
- if (!matchEventPattern(pattern, event.type)) continue;
81
- for (const fn of handlers) try {
82
- await fn(event);
83
- } catch (err) {
84
- this.logger.error(`[supplier-performance] subscriber threw on ${event.type}: ${err.message}`, err);
85
- }
86
- }
87
- }
88
- async subscribe(pattern, handler) {
89
- let set = this.patterns.get(pattern);
90
- if (!set) {
91
- set = /* @__PURE__ */ new Set();
92
- this.patterns.set(pattern, set);
93
- }
94
- set.add(handler);
95
- return () => {
96
- const s = this.patterns.get(pattern);
97
- s?.delete(handler);
98
- if (s && s.size === 0) this.patterns.delete(pattern);
99
- };
100
- }
101
- async close() {
102
- this.patterns.clear();
76
+ super({
77
+ name: "in-process-supplier-performance",
78
+ logLabel: "supplier-performance",
79
+ ...options
80
+ });
103
81
  }
104
82
  };
105
83
  //#endregion
@@ -1,8 +1,7 @@
1
- import { DomainEvent, EventHandler, EventMeta, EventTransport } from "@classytic/primitives/events";
1
+ import { DomainEvent, EventMeta } from "@classytic/primitives/events";
2
+ import { InProcessEventBus, InProcessEventBusOptions } from "@classytic/primitives/event-infra";
2
3
  import { z } from "zod";
3
-
4
4
  //#region src/events/event-constants.d.ts
5
-
6
5
  /**
7
6
  * Canonical event names emitted by `@classytic/supplier-performance`.
8
7
  *
@@ -136,28 +135,9 @@ interface SupplierPerformanceContext {
136
135
  declare function createEvent$1<T>(type: SupplierPerformanceEventName, payload: T, ctx?: SupplierPerformanceContext, meta?: Partial<EventMeta>): DomainEvent<T>;
137
136
  //#endregion
138
137
  //#region src/events/in-process-bus.d.ts
139
- interface InProcessBusOptions {
140
- logger?: {
141
- error(message: string, ...args: unknown[]): void;
142
- };
143
- }
144
- /**
145
- * Zero-dep in-process event bus. Subscribers can use glob patterns
146
- * (`supplier_performance:*`, `*`, exact type). Subscriber errors are
147
- * caught and logged — they never break the emitter or sibling
148
- * subscribers.
149
- *
150
- * Drop-in compatible with any `EventTransport` — hosts replace it by
151
- * passing their own at `createSupplierPerformance({ eventTransport })`.
152
- */
153
- declare class InProcessSupplierPerformanceBus implements EventTransport {
154
- readonly name = "in-process-supplier-performance";
155
- private patterns;
156
- private logger;
138
+ type InProcessBusOptions = InProcessEventBusOptions;
139
+ declare class InProcessSupplierPerformanceBus extends InProcessEventBus {
157
140
  constructor(options?: InProcessBusOptions);
158
- publish(event: DomainEvent): Promise<void>;
159
- subscribe(pattern: string, handler: EventHandler): Promise<() => void>;
160
- close(): Promise<void>;
161
141
  }
162
142
  //#endregion
163
143
  export { ScoreComputed as a, supplierPerformanceEventDefinitions as c, PerformanceEventType as d, PerformanceEventTypeValue as f, EventRecorded as i, SupplierPerformanceEventPayloads as l, SupplierPerformanceEvents as m, createEvent$1 as n, SupplierPerformanceEventDefinition as o, SupplierPerformanceEventName as p, SupplierPerformanceContext as r, SupplierPerformanceEventSchema as s, InProcessSupplierPerformanceBus as t, PERFORMANCE_EVENT_TYPE_VALUES as u };
package/dist/index.d.ts CHANGED
@@ -1,11 +1,10 @@
1
1
  import { a as ScoreComputed, c as supplierPerformanceEventDefinitions, d as PerformanceEventType, f as PerformanceEventTypeValue, i as EventRecorded, l as SupplierPerformanceEventPayloads, m as SupplierPerformanceEvents, n as createEvent, o as SupplierPerformanceEventDefinition, p as SupplierPerformanceEventName, r as SupplierPerformanceContext, s as SupplierPerformanceEventSchema, t as InProcessSupplierPerformanceBus, u as PERFORMANCE_EVENT_TYPE_VALUES } from "./in-process-bus.js";
2
- import { PluginType, Repository, RepositoryContext } from "@classytic/mongokit";
2
+ import { ModelBlueprint, PluginType, Repository, RepositoryContext } from "@classytic/mongokit";
3
3
  import { ResolvedTenantConfig, TenantConfig } from "@classytic/repo-core/tenant";
4
4
  import { ClientSession, Connection, Document, Model, Schema, Types } from "mongoose";
5
5
  import { EventTransport } from "@classytic/primitives/events";
6
6
  import { OutboxStore } from "@classytic/primitives/outbox";
7
7
  import { HttpError } from "@classytic/repo-core/errors";
8
-
9
8
  //#region src/models/performance-event.model.d.ts
10
9
  interface PerformanceEventDocument extends Document {
11
10
  organizationId: unknown;
@@ -19,14 +18,15 @@ interface PerformanceEventDocument extends Document {
19
18
  createdAt: Date;
20
19
  updatedAt: Date;
21
20
  }
22
- interface PerformanceEventModelConfig {
23
- collectionPrefix?: string | undefined;
24
- forceRecreate?: boolean;
25
- }
26
- declare class PerformanceEventModelCollisionError extends Error {
27
- constructor(name: string);
28
- }
29
- declare function createPerformanceEventModel(connection: Connection, tenant: ResolvedTenantConfig, config?: PerformanceEventModelConfig): Model<PerformanceEventDocument>;
21
+ /** Base collection name (before any host-supplied prefix). */
22
+ declare const PERFORMANCE_EVENT_COLLECTION = "supplier_performance_events";
23
+ /**
24
+ * Build the PerformanceEvent schema for a resolved tenant config. Pure — the
25
+ * `defineSupplierPerformanceModels` blueprint invokes this factory once, only
26
+ * when the model is actually registered (§5.2). The collection name (incl. any
27
+ * host prefix) is supplied to `connection.model()` by the blueprint, not here.
28
+ */
29
+ declare function buildPerformanceEventSchema(tenant: ResolvedTenantConfig): Schema<PerformanceEventDocument>;
30
30
  //#endregion
31
31
  //#region src/models/supplier-score.model.d.ts
32
32
  interface SupplierScoreDocument extends Document {
@@ -43,27 +43,36 @@ interface SupplierScoreDocument extends Document {
43
43
  createdAt: Date;
44
44
  updatedAt: Date;
45
45
  }
46
- interface SupplierScoreModelConfig {
47
- collectionPrefix?: string | undefined;
48
- forceRecreate?: boolean;
49
- }
50
- declare class SupplierScoreModelCollisionError extends Error {
51
- constructor(name: string);
52
- }
53
- declare function createSupplierScoreModel(connection: Connection, tenant: ResolvedTenantConfig, config?: SupplierScoreModelConfig): Model<SupplierScoreDocument>;
46
+ /** Base collection name (before any host-supplied prefix). */
47
+ declare const SUPPLIER_SCORE_COLLECTION = "supplier_scores";
48
+ /**
49
+ * Build the SupplierScore schema for a resolved tenant config. Pure — the
50
+ * `defineSupplierPerformanceModels` blueprint invokes this factory once, only
51
+ * when the model is actually registered (§5.2). The collection name (incl. any
52
+ * host prefix) is supplied to `connection.model()` by the blueprint, not here.
53
+ */
54
+ declare function buildSupplierScoreSchema(tenant: ResolvedTenantConfig): Schema<SupplierScoreDocument>;
54
55
  //#endregion
55
56
  //#region src/models/create-models.d.ts
56
- interface SupplierPerformanceModelBundle {
57
- PerformanceEvent: ReturnType<typeof createPerformanceEventModel>;
58
- SupplierScore: ReturnType<typeof createSupplierScoreModel>;
57
+ interface SupplierPerformanceModels {
58
+ PerformanceEvent: Model<PerformanceEventDocument>;
59
+ SupplierScore: Model<SupplierScoreDocument>;
59
60
  }
60
- interface CreateSupplierPerformanceModelsOptions {
61
- /** Resolved tenant config, or a `TenantConfig` / boolean to resolve. */
62
- tenant?: ResolvedTenantConfig | TenantConfig | boolean;
61
+ interface DefineSupplierPerformanceModelsConfig {
62
+ /** Resolved tenant config — drives schema field type + compound-index prefix. */
63
+ tenant: ResolvedTenantConfig;
64
+ /** Optional collection name prefix (PACKAGE_RULES §20.1). */
63
65
  collectionPrefix?: string | undefined;
64
- forceRecreate?: boolean | undefined;
66
+ /** Mongoose auto-index builds. Default `true` (dev); `false` in prod (§35). */
67
+ autoIndex?: boolean;
68
+ /** On a name collision: `false` (default) throws; `true` re-registers (test/dev fixtures). */
69
+ forceRecreate?: boolean;
65
70
  }
66
- declare function createSupplierPerformanceModels(connection: Connection, options?: CreateSupplierPerformanceModelsOptions): SupplierPerformanceModelBundle;
71
+ /**
72
+ * Describe the supplier-performance model set as a connection-free blueprint.
73
+ * Pure — builds no schema and registers nothing until `.bind(connection)`.
74
+ */
75
+ declare function defineSupplierPerformanceModels(config: DefineSupplierPerformanceModelsConfig): ModelBlueprint<SupplierPerformanceModels>;
67
76
  //#endregion
68
77
  //#region src/repositories/performance-event.repository.d.ts
69
78
  interface PerformanceEventRepositoryConfig {
@@ -116,8 +125,19 @@ interface ScoreMetrics {
116
125
  unitsReceived: number;
117
126
  /** Total defective units (sum of `metrics.quantity` on defect events). */
118
127
  defectiveUnits: number;
119
- /** Fraction in [0, 1]. `defectiveUnits / unitsReceived`. */
128
+ /**
129
+ * Fraction CLAMPED to [0, 1]. `min(defectiveUnits / unitsReceived, 1)`.
130
+ * Clamped so the persisted value satisfies the model's `max: 1` schema —
131
+ * see `rawDefectRate` for the un-capped signal.
132
+ */
120
133
  defectRate: number;
134
+ /**
135
+ * Un-clamped `defectiveUnits / unitsReceived`. Can exceed 1 when defects
136
+ * are reported against goods received in a prior period (or a mis-wired
137
+ * supplierId). Diagnostic only — a value > 1 is a data-integrity signal
138
+ * worth alerting on; the composite uses the clamped `defectRate`.
139
+ */
140
+ rawDefectRate: number;
121
141
  /** Number of price-variance events in window. */
122
142
  priceVarianceCount: number;
123
143
  /** Average variance fraction (e.g. 0.04 = 4% over expected). */
@@ -128,6 +148,14 @@ interface ScoreMetrics {
128
148
  * Pure roll-up; hosts with custom weights re-score from the rates.
129
149
  */
130
150
  compositeScore: number;
151
+ /**
152
+ * `true` when the period carries no evidence (no deliveries, no received
153
+ * units, no price-variance events). The `compositeScore` still resolves to
154
+ * the documented ~50 "new supplier" baseline for backwards compatibility;
155
+ * this flag lets consumers treat a no-data scorecard as an
156
+ * insufficient-signal sentinel instead of a real middling grade.
157
+ */
158
+ insufficientSignal: boolean;
131
159
  }
132
160
  interface ComputeScoreInput {
133
161
  supplierId: string;
@@ -259,10 +287,25 @@ declare class ScoreService {
259
287
  private logger;
260
288
  constructor(config: ScoreServiceConfig);
261
289
  /**
262
- * Append a single performance event to the log. Idempotent on the
263
- * caller's side via `metadata.idempotencyKey` if hosts wire their own
264
- * dedup index — this kernel doesn't enforce it (different hosts have
265
- * different keying preferences: PO-line, PO+SKU, etc.).
290
+ * Append a single performance event to the log.
291
+ *
292
+ * NOT idempotent by construction — a double-fired host bridge writes two
293
+ * rows and double-counts the delivery. This kernel deliberately does NOT
294
+ * ship a default unique dedup index: hosts key idempotency differently
295
+ * (PO-line, PO+SKU, receipt id), and a blanket unique index would be wrong
296
+ * for all of them (and would reject the many events that legitimately carry
297
+ * no key). HOST REQUIREMENT: to make replays safe, dedup upstream (skip if
298
+ * already recorded) OR add an opt-in partial-unique index on your chosen
299
+ * key, e.g. on `metadata.idempotencyKey` / `sourceRef`:
300
+ *
301
+ * schema.index(
302
+ * { organizationId: 1, 'metadata.idempotencyKey': 1 },
303
+ * { unique: true,
304
+ * partialFilterExpression: { 'metadata.idempotencyKey': { $exists: true } } },
305
+ * );
306
+ *
307
+ * `computeScore` remains fully idempotent regardless — it re-aggregates the
308
+ * current event log and upserts one snapshot per (supplier, period).
266
309
  */
267
310
  recordEvent(input: RecordEventInput, ctx: SupplierPerformanceContext): Promise<PerformanceEventDocument>;
268
311
  /**
@@ -307,18 +350,12 @@ interface SupplierPerformanceTenantOptions extends TenantConfig {
307
350
  allowDataInjection?: boolean | undefined;
308
351
  onMismatch?: 'throw' | 'overwrite' | undefined;
309
352
  }
310
- interface SupplierPerformanceConfig {
311
- /** Shared mongoose connection. */
312
- connection: Connection;
313
- /**
314
- * Optional event transport. Any object matching `@classytic/primitives`
315
- * `EventTransport` — Arc's MemoryEventTransport, a Redis transport, or
316
- * the bundled `InProcessSupplierPerformanceBus`. Omit to skip event
317
- * emission entirely.
318
- */
319
- /** Optional durable outbox — enables host-session (relay-only) mode. */
320
- outbox?: OutboxStore | undefined;
321
- eventTransport?: EventTransport | undefined;
353
+ /**
354
+ * DESCRIBE-time shape — everything that determines the persistence SHAPE and
355
+ * needs no connection or I/O to inspect. Nothing here opens a socket or reads a
356
+ * secret (§6.2).
357
+ */
358
+ interface SupplierPerformanceShape {
322
359
  /**
323
360
  * Tenant scoping config — `TenantConfig` from `@classytic/repo-core/tenant`
324
361
  * (plus mongokit-runtime knobs) or a boolean shorthand. One resolved value
@@ -331,8 +368,26 @@ interface SupplierPerformanceConfig {
331
368
  tenant?: SupplierPerformanceTenantOptions | boolean | undefined;
332
369
  /** Optional collection name prefix (PACKAGE_RULES §20.1). */
333
370
  collectionPrefix?: string | undefined;
334
- /** Hot-reload / test fixtures only. Default `false`. */
371
+ /** Mongoose auto-index builds. Default `true` (dev); pass `false` in prod (§35). */
372
+ autoIndex?: boolean | undefined;
373
+ /** Hot-reload / test fixtures only. Default `false`. Maps to mongokit `replace`. */
335
374
  forceRecreate?: boolean | undefined;
375
+ }
376
+ /**
377
+ * BIND-time runtime collaborators — the live connection is the first `bind`
378
+ * arg; these are the rest. A transport, outbox, logger or per-repo plugin set
379
+ * belongs here, not in the shape (§6.2).
380
+ */
381
+ interface SupplierPerformanceRuntime {
382
+ /**
383
+ * Optional event transport. Any object matching `@classytic/primitives`
384
+ * `EventTransport` — Arc's MemoryEventTransport, a Redis transport, or the
385
+ * bundled `InProcessSupplierPerformanceBus`. Omit and the engine creates (and
386
+ * owns) an in-process bus; supply one and its lifecycle stays with the host.
387
+ */
388
+ eventTransport?: EventTransport | undefined;
389
+ /** Optional durable outbox — enables host-session (relay-only) mode. */
390
+ outbox?: OutboxStore | undefined;
336
391
  /** Optional per-repo plugins. Stacked AFTER the built-in plugins. */
337
392
  repositoryPlugins?: {
338
393
  performanceEvent?: PluginType[] | undefined;
@@ -345,18 +400,34 @@ interface SupplierPerformanceRepositories {
345
400
  supplierScore: SupplierScoreRepository;
346
401
  }
347
402
  interface SupplierPerformanceEngine {
348
- models: SupplierPerformanceModelBundle;
403
+ models: SupplierPerformanceModels;
349
404
  repositories: SupplierPerformanceRepositories;
350
405
  services: {
351
406
  score: ScoreService;
352
407
  };
353
408
  events: EventTransport;
354
409
  syncIndexes(): Promise<void>;
355
- destroy(): Promise<void>;
410
+ /** The ONLY teardown verb (§6.4). Closes only an internally-created transport. */
411
+ close(): Promise<void>;
412
+ }
413
+ /**
414
+ * The DESCRIBE/BIND blueprint returned by `defineSupplierPerformance`. Pure to
415
+ * construct; `bind` compiles the models on the supplied connection and wires the
416
+ * engine.
417
+ */
418
+ interface SupplierPerformanceBlueprint {
419
+ readonly id: 'supplier-performance';
420
+ /** The model names this blueprint registers — known without a connection. */
421
+ readonly modelNames: readonly string[];
422
+ bind(connection: Connection, runtime?: SupplierPerformanceRuntime): SupplierPerformanceEngine;
356
423
  }
357
424
  //#endregion
358
- //#region src/engine/create-supplier-performance.d.ts
359
- declare function createSupplierPerformance(config: SupplierPerformanceConfig): Promise<SupplierPerformanceEngine>;
425
+ //#region src/engine/define-supplier-performance.d.ts
426
+ /**
427
+ * Describe the supplier-performance engine. Pure — registers no model, builds no
428
+ * schema, performs no I/O.
429
+ */
430
+ declare function defineSupplierPerformance(shape?: SupplierPerformanceShape): SupplierPerformanceBlueprint;
360
431
  //#endregion
361
432
  //#region src/domain/errors/supplier-performance.errors.d.ts
362
433
  declare class SupplierPerformanceError extends Error implements HttpError {
@@ -364,11 +435,6 @@ declare class SupplierPerformanceError extends Error implements HttpError {
364
435
  readonly status: number;
365
436
  constructor(message: string, code: string, status: number);
366
437
  }
367
- /**
368
- * Thrown when a host passes ctx.session but no OutboxStore is wired —
369
- * publishing mid-transaction would leak ghost events on rollback (§P8.1).
370
- */
371
-
372
438
  /** Invalid input to `recordEvent` / `computeScore` (missing supplierId, bad period). */
373
439
  declare class SupplierPerformanceValidationError extends SupplierPerformanceError {
374
440
  constructor(message: string);
@@ -379,6 +445,16 @@ declare class SupplierPerformanceValidationError extends SupplierPerformanceErro
379
445
  * Aggregate raw performance events into a scorecard. Events outside the
380
446
  * `period` window are filtered out (defensive — callers should already
381
447
  * have queried within the window).
448
+ *
449
+ * ON-TIME SEMANTICS (host-owned): a delivery's on-time/late classification
450
+ * is decided by the event TYPE the host records — `delivery_received` is
451
+ * on-time, `delivery_late` is late. This kernel does NOT re-derive that
452
+ * verdict from `metrics.expectedAt`/`actualAt`; those timestamp fields are
453
+ * ADVISORY (drill-down / audit context), not authoritative. `delayDays` is
454
+ * likewise read as a host-supplied denormalization on `delivery_late` events
455
+ * only. Hosts that want timestamp-derived classification classify upstream
456
+ * and emit the matching type — the kernel never silently overrides the
457
+ * host's own verdict. (Intentional; see fix-3 in the scorecard hardening.)
382
458
  */
383
459
  declare function scoreFromEvents(events: ReadonlyArray<PerformanceEvent>, period: ScorePeriod): ScoreMetrics;
384
460
  //#endregion
@@ -394,6 +470,7 @@ declare function resolveSupplierPerformanceTenant(input?: TenantConfig | boolean
394
470
  * existing compound index (so queries are index-efficient under
395
471
  * multi-tenant scoping, rule 36).
396
472
  */
473
+ declare function injectTenantField(schema: Schema, tenant: ResolvedTenantConfig): void;
397
474
  //#endregion
398
475
  //#region src/repositories/repo-options.d.ts
399
476
  interface RepoOptions {
@@ -409,4 +486,4 @@ interface RepoOptions {
409
486
  }
410
487
  declare function repoOptionsFromCtx(ctx: SupplierPerformanceContext): RepoOptions;
411
488
  //#endregion
412
- export { type ComputeScoreInput, type CreateSupplierPerformanceModelsOptions, EventRecorded, InProcessSupplierPerformanceBus, PERFORMANCE_EVENT_TYPE_VALUES, type PerformanceEvent, type PerformanceEventDocument, PerformanceEventModelCollisionError, PerformanceEventRepository, type PerformanceEventRepositoryConfig, PerformanceEventType, type PerformanceEventTypeValue, type PerformanceMetrics, type RecordEventInput, type RepoOptions, ScoreComputed, type ScoreMetrics, type ScorePeriod, ScoreService, type ScoreServiceConfig, type SupplierPerformanceConfig, type SupplierPerformanceContext, type SupplierPerformanceEngine, SupplierPerformanceError, type SupplierPerformanceEventDefinition, type SupplierPerformanceEventName, type SupplierPerformanceEventPayloads, type SupplierPerformanceEventSchema, SupplierPerformanceEvents, type SupplierPerformanceLogger, type SupplierPerformanceModelBundle, type SupplierPerformanceRepositories, type SupplierPerformanceTenantOptions, SupplierPerformanceValidationError, type SupplierScore, type SupplierScoreDocument, SupplierScoreModelCollisionError, SupplierScoreRepository, type SupplierScoreRepositoryConfig, type UpsertScoreInput, createEvent, createPerformanceEventModel, createSupplierPerformance, createSupplierPerformanceModels, createSupplierScoreModel, repoOptionsFromCtx, resolveSupplierPerformanceTenant, scoreFromEvents, supplierPerformanceEventDefinitions };
489
+ export { type ComputeScoreInput, type DefineSupplierPerformanceModelsConfig, EventRecorded, InProcessSupplierPerformanceBus, PERFORMANCE_EVENT_COLLECTION, PERFORMANCE_EVENT_TYPE_VALUES, type PerformanceEvent, type PerformanceEventDocument, PerformanceEventRepository, type PerformanceEventRepositoryConfig, PerformanceEventType, type PerformanceEventTypeValue, type PerformanceMetrics, type RecordEventInput, type RepoOptions, SUPPLIER_SCORE_COLLECTION, ScoreComputed, type ScoreMetrics, type ScorePeriod, ScoreService, type ScoreServiceConfig, type SupplierPerformanceBlueprint, type SupplierPerformanceContext, type SupplierPerformanceEngine, SupplierPerformanceError, type SupplierPerformanceEventDefinition, type SupplierPerformanceEventName, type SupplierPerformanceEventPayloads, type SupplierPerformanceEventSchema, SupplierPerformanceEvents, type SupplierPerformanceLogger, type SupplierPerformanceModels, type SupplierPerformanceRepositories, type SupplierPerformanceRuntime, type SupplierPerformanceShape, type SupplierPerformanceTenantOptions, SupplierPerformanceValidationError, type SupplierScore, type SupplierScoreDocument, SupplierScoreRepository, type SupplierScoreRepositoryConfig, type UpsertScoreInput, buildPerformanceEventSchema, buildSupplierScoreSchema, createEvent, defineSupplierPerformance, defineSupplierPerformanceModels, injectTenantField, repoOptionsFromCtx, resolveSupplierPerformanceTenant, scoreFromEvents, supplierPerformanceEventDefinitions };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { a as createEvent, c as PerformanceEventType, i as InProcessSupplierPerformanceBus, n as ScoreComputed, o as SupplierPerformanceEvents, r as supplierPerformanceEventDefinitions, s as PERFORMANCE_EVENT_TYPE_VALUES, t as EventRecorded } from "./event-catalog.js";
2
- import { Repository, createOptionsExtractor, methodRegistryPlugin, multiTenantPlugin } from "@classytic/mongokit";
3
- import { resolveTenantConfig } from "@classytic/repo-core/tenant";
2
+ import { Repository, createOptionsExtractor, defineModels, methodRegistryPlugin, multiTenantPlugin } from "@classytic/mongokit";
3
+ import { assertNoLegacyTenantKeys, resolveTenantConfig } from "@classytic/repo-core/tenant";
4
4
  import mongoose, { Schema } from "mongoose";
5
5
  //#region src/models/inject-tenant.ts
6
6
  /**
@@ -47,6 +47,8 @@ function injectTenantField(schema, tenant) {
47
47
  }
48
48
  //#endregion
49
49
  //#region src/models/performance-event.model.ts
50
+ /** Base collection name (before any host-supplied prefix). */
51
+ const PERFORMANCE_EVENT_COLLECTION = "supplier_performance_events";
50
52
  const metricsSchema$1 = new Schema({
51
53
  quantity: {
52
54
  type: Number,
@@ -68,6 +70,12 @@ const metricsSchema$1 = new Schema({
68
70
  _id: false,
69
71
  strict: false
70
72
  });
73
+ /**
74
+ * Build the PerformanceEvent schema for a resolved tenant config. Pure — the
75
+ * `defineSupplierPerformanceModels` blueprint invokes this factory once, only
76
+ * when the model is actually registered (§5.2). The collection name (incl. any
77
+ * host prefix) is supplied to `connection.model()` by the blueprint, not here.
78
+ */
71
79
  function buildPerformanceEventSchema(tenant) {
72
80
  const schema = new Schema({
73
81
  supplierId: {
@@ -91,10 +99,7 @@ function buildPerformanceEventSchema(tenant) {
91
99
  sourceRef: String,
92
100
  sourceType: String,
93
101
  metadata: { type: Schema.Types.Mixed }
94
- }, {
95
- timestamps: true,
96
- collection: "supplier_performance_events"
97
- });
102
+ }, { timestamps: true });
98
103
  schema.index({
99
104
  supplierId: 1,
100
105
  occurredAt: 1
@@ -106,20 +111,10 @@ function buildPerformanceEventSchema(tenant) {
106
111
  injectTenantField(schema, tenant);
107
112
  return schema;
108
113
  }
109
- var PerformanceEventModelCollisionError = class extends Error {
110
- constructor(name) {
111
- super(`[supplier-performance] Mongoose model "${name}" already exists on this connection. Pass \`forceRecreate: true\` for hot-reload, or use two Mongoose connections.`);
112
- this.name = "PerformanceEventModelCollisionError";
113
- }
114
- };
115
- function createPerformanceEventModel(connection, tenant, config = {}) {
116
- if (connection.models.PerformanceEvent) if (config.forceRecreate) connection.deleteModel("PerformanceEvent");
117
- else throw new PerformanceEventModelCollisionError("PerformanceEvent");
118
- const collection = (config.collectionPrefix ?? "") + "supplier_performance_events";
119
- return connection.model("PerformanceEvent", buildPerformanceEventSchema(tenant), collection);
120
- }
121
114
  //#endregion
122
115
  //#region src/models/supplier-score.model.ts
116
+ /** Base collection name (before any host-supplied prefix). */
117
+ const SUPPLIER_SCORE_COLLECTION = "supplier_scores";
123
118
  const periodSchema = new Schema({
124
119
  start: {
125
120
  type: Date,
@@ -168,6 +163,11 @@ const metricsSchema = new Schema({
168
163
  min: 0,
169
164
  max: 1
170
165
  },
166
+ rawDefectRate: {
167
+ type: Number,
168
+ default: 0,
169
+ min: 0
170
+ },
171
171
  priceVarianceCount: {
172
172
  type: Number,
173
173
  default: 0,
@@ -182,8 +182,18 @@ const metricsSchema = new Schema({
182
182
  default: 0,
183
183
  min: 0,
184
184
  max: 100
185
+ },
186
+ insufficientSignal: {
187
+ type: Boolean,
188
+ default: false
185
189
  }
186
190
  }, { _id: false });
191
+ /**
192
+ * Build the SupplierScore schema for a resolved tenant config. Pure — the
193
+ * `defineSupplierPerformanceModels` blueprint invokes this factory once, only
194
+ * when the model is actually registered (§5.2). The collection name (incl. any
195
+ * host prefix) is supplied to `connection.model()` by the blueprint, not here.
196
+ */
187
197
  function buildSupplierScoreSchema(tenant) {
188
198
  const schema = new Schema({
189
199
  supplierId: {
@@ -209,10 +219,7 @@ function buildSupplierScoreSchema(tenant) {
209
219
  default: 0,
210
220
  min: 0
211
221
  }
212
- }, {
213
- timestamps: true,
214
- collection: "supplier_scores"
215
- });
222
+ }, { timestamps: true });
216
223
  schema.index({
217
224
  supplierId: 1,
218
225
  "period.start": 1,
@@ -225,35 +232,55 @@ function buildSupplierScoreSchema(tenant) {
225
232
  injectTenantField(schema, tenant);
226
233
  return schema;
227
234
  }
228
- var SupplierScoreModelCollisionError = class extends Error {
229
- constructor(name) {
230
- super(`[supplier-performance] Mongoose model "${name}" already exists on this connection. Pass \`forceRecreate: true\` for hot-reload, or use two Mongoose connections.`);
231
- this.name = "SupplierScoreModelCollisionError";
232
- }
233
- };
234
- function createSupplierScoreModel(connection, tenant, config = {}) {
235
- if (connection.models.SupplierScore) if (config.forceRecreate) connection.deleteModel("SupplierScore");
236
- else throw new SupplierScoreModelCollisionError("SupplierScore");
237
- const collection = (config.collectionPrefix ?? "") + "supplier_scores";
238
- return connection.model("SupplierScore", buildSupplierScoreSchema(tenant), collection);
239
- }
240
235
  //#endregion
241
236
  //#region src/models/create-models.ts
242
- function toResolved(tenant) {
243
- if (typeof tenant === "object" && tenant !== null && "strategy" in tenant && "enabled" in tenant && "tenantField" in tenant) return tenant;
244
- if (tenant !== void 0) return resolveSupplierPerformanceTenant(tenant);
245
- return resolveSupplierPerformanceTenant();
246
- }
247
- function createSupplierPerformanceModels(connection, options = {}) {
248
- const tenant = toResolved(options.tenant);
249
- const modelConfig = {
250
- ...options.collectionPrefix !== void 0 ? { collectionPrefix: options.collectionPrefix } : {},
251
- ...options.forceRecreate !== void 0 ? { forceRecreate: options.forceRecreate } : {}
252
- };
253
- return {
254
- PerformanceEvent: createPerformanceEventModel(connection, tenant, modelConfig),
255
- SupplierScore: createSupplierScoreModel(connection, tenant, modelConfig)
256
- };
237
+ /**
238
+ * Supplier-performance model specification — the ONE authoritative place the
239
+ * PerformanceEvent + SupplierScore models are described.
240
+ *
241
+ * `defineSupplierPerformanceModels(config)` returns a connection-free mongokit
242
+ * `ModelBlueprint`; `defineSupplierPerformance` binds it during engine
243
+ * construction. Collision handling, auto-index, tenant field shape and
244
+ * collection prefixing live here once (PACKAGE_RULES §20/§21, §P11). A name
245
+ * collision surfaces as mongokit's typed `ModelCollisionError` — no
246
+ * kernel-specific collision error.
247
+ */
248
+ /**
249
+ * Describe the supplier-performance model set as a connection-free blueprint.
250
+ * Pure — builds no schema and registers nothing until `.bind(connection)`.
251
+ */
252
+ function defineSupplierPerformanceModels(config) {
253
+ const autoIndex = config.autoIndex ?? true;
254
+ const prefix = config.collectionPrefix ?? "";
255
+ const existing = config.forceRecreate ? {
256
+ mode: "replace",
257
+ environment: "test"
258
+ } : { mode: "throw" };
259
+ return defineModels({
260
+ models: [{
261
+ name: "PerformanceEvent",
262
+ collection: prefix + PERFORMANCE_EVENT_COLLECTION,
263
+ schema: () => {
264
+ const schema = buildPerformanceEventSchema(config.tenant);
265
+ schema.set("autoIndex", autoIndex);
266
+ return schema;
267
+ },
268
+ existing
269
+ }, {
270
+ name: "SupplierScore",
271
+ collection: prefix + SUPPLIER_SCORE_COLLECTION,
272
+ schema: () => {
273
+ const schema = buildSupplierScoreSchema(config.tenant);
274
+ schema.set("autoIndex", autoIndex);
275
+ return schema;
276
+ },
277
+ existing
278
+ }],
279
+ assemble: (models) => Object.freeze({
280
+ PerformanceEvent: models.get("PerformanceEvent"),
281
+ SupplierScore: models.get("SupplierScore")
282
+ })
283
+ });
257
284
  }
258
285
  //#endregion
259
286
  //#region src/repositories/repo-options.ts
@@ -397,6 +424,16 @@ const COMPOSITE_WEIGHTS = {
397
424
  * Aggregate raw performance events into a scorecard. Events outside the
398
425
  * `period` window are filtered out (defensive — callers should already
399
426
  * have queried within the window).
427
+ *
428
+ * ON-TIME SEMANTICS (host-owned): a delivery's on-time/late classification
429
+ * is decided by the event TYPE the host records — `delivery_received` is
430
+ * on-time, `delivery_late` is late. This kernel does NOT re-derive that
431
+ * verdict from `metrics.expectedAt`/`actualAt`; those timestamp fields are
432
+ * ADVISORY (drill-down / audit context), not authoritative. `delayDays` is
433
+ * likewise read as a host-supplied denormalization on `delivery_late` events
434
+ * only. Hosts that want timestamp-derived classification classify upstream
435
+ * and emit the matching type — the kernel never silently overrides the
436
+ * host's own verdict. (Intentional; see fix-3 in the scorecard hardening.)
400
437
  */
401
438
  function scoreFromEvents(events, period) {
402
439
  const inWindow = events.filter((e) => e.occurredAt >= period.start && e.occurredAt < period.end);
@@ -410,7 +447,7 @@ function scoreFromEvents(events, period) {
410
447
  let totalVariancePct = 0;
411
448
  for (const event of inWindow) {
412
449
  const metrics = event.metrics ?? {};
413
- const qty = Number(metrics.quantity ?? 1);
450
+ const qty = finiteOr(metrics.quantity, 1);
414
451
  switch (event.type) {
415
452
  case "delivery_received":
416
453
  deliveryCount++;
@@ -421,7 +458,7 @@ function scoreFromEvents(events, period) {
421
458
  deliveryCount++;
422
459
  lateCount++;
423
460
  unitsReceived += qty;
424
- const delay = Number(metrics.delayDays ?? 0);
461
+ const delay = finiteOr(metrics.delayDays, 0);
425
462
  if (delay > 0) totalDelayDays += delay;
426
463
  break;
427
464
  }
@@ -430,14 +467,15 @@ function scoreFromEvents(events, period) {
430
467
  break;
431
468
  case "price_variance":
432
469
  priceVarianceCount++;
433
- totalVariancePct += Number(metrics.variancePct ?? 0);
434
- break;
470
+ totalVariancePct += finiteOr(metrics.variancePct, 0);
435
471
  }
436
472
  }
437
473
  const onTimeRate = deliveryCount > 0 ? onTimeCount / deliveryCount : 0;
438
474
  const avgDelayDays = lateCount > 0 ? totalDelayDays / lateCount : 0;
439
- const defectRate = unitsReceived > 0 ? defectiveUnits / unitsReceived : 0;
475
+ const rawDefectRate = unitsReceived > 0 ? defectiveUnits / unitsReceived : 0;
476
+ const defectRate = Math.min(rawDefectRate, 1);
440
477
  const avgPriceVariance = priceVarianceCount > 0 ? totalVariancePct / priceVarianceCount : 0;
478
+ const insufficientSignal = deliveryCount === 0 && unitsReceived === 0 && priceVarianceCount === 0;
441
479
  const composite = onTimeRate * COMPOSITE_WEIGHTS.onTime + (1 - defectRate) * COMPOSITE_WEIGHTS.defectFree + (1 - Math.min(Math.abs(avgPriceVariance), 1)) * COMPOSITE_WEIGHTS.pricedToPlan;
442
480
  return {
443
481
  deliveryCount,
@@ -447,11 +485,24 @@ function scoreFromEvents(events, period) {
447
485
  unitsReceived,
448
486
  defectiveUnits,
449
487
  defectRate: round(defectRate, 4),
488
+ rawDefectRate: round(rawDefectRate, 4),
450
489
  priceVarianceCount,
451
490
  avgPriceVariance: round(avgPriceVariance, 4),
452
- compositeScore: round(Math.max(0, Math.min(100, composite * 100)), 2)
491
+ compositeScore: round(Math.max(0, Math.min(100, composite * 100)), 2),
492
+ insufficientSignal
453
493
  };
454
494
  }
495
+ /**
496
+ * Coerce a possibly-untrusted metric to a finite number, falling back to
497
+ * `fallback` on `NaN`/`Infinity`/non-numeric input. The event `metrics`
498
+ * subdoc is `strict: false`, so a host can persist `quantity: "abc"`; without
499
+ * this guard `Number("abc")` → `NaN` propagates into the composite and lands a
500
+ * `NaN`/CastError on the score doc, poisoning the whole scorecard.
501
+ */
502
+ function finiteOr(value, fallback) {
503
+ const n = Number(value ?? fallback);
504
+ return Number.isFinite(n) ? n : fallback;
505
+ }
455
506
  function round(value, digits) {
456
507
  const factor = 10 ** digits;
457
508
  return Math.round(value * factor) / factor;
@@ -484,10 +535,25 @@ var ScoreService = class {
484
535
  this.logger = config.logger ?? console;
485
536
  }
486
537
  /**
487
- * Append a single performance event to the log. Idempotent on the
488
- * caller's side via `metadata.idempotencyKey` if hosts wire their own
489
- * dedup index — this kernel doesn't enforce it (different hosts have
490
- * different keying preferences: PO-line, PO+SKU, etc.).
538
+ * Append a single performance event to the log.
539
+ *
540
+ * NOT idempotent by construction — a double-fired host bridge writes two
541
+ * rows and double-counts the delivery. This kernel deliberately does NOT
542
+ * ship a default unique dedup index: hosts key idempotency differently
543
+ * (PO-line, PO+SKU, receipt id), and a blanket unique index would be wrong
544
+ * for all of them (and would reject the many events that legitimately carry
545
+ * no key). HOST REQUIREMENT: to make replays safe, dedup upstream (skip if
546
+ * already recorded) OR add an opt-in partial-unique index on your chosen
547
+ * key, e.g. on `metadata.idempotencyKey` / `sourceRef`:
548
+ *
549
+ * schema.index(
550
+ * { organizationId: 1, 'metadata.idempotencyKey': 1 },
551
+ * { unique: true,
552
+ * partialFilterExpression: { 'metadata.idempotencyKey': { $exists: true } } },
553
+ * );
554
+ *
555
+ * `computeScore` remains fully idempotent regardless — it re-aggregates the
556
+ * current event log and upserts one snapshot per (supplier, period).
491
557
  */
492
558
  async recordEvent(input, ctx) {
493
559
  if (!input.supplierId) throw new SupplierPerformanceValidationError("supplierId is required");
@@ -595,63 +661,117 @@ function normalizePeriod(period) {
595
661
  return period;
596
662
  }
597
663
  //#endregion
598
- //#region src/engine/create-supplier-performance.ts
599
- async function createSupplierPerformance(config) {
600
- if (!config.connection) throw new Error("createSupplierPerformance: config.connection is required");
601
- const logger = config.logger ?? console;
602
- const events = config.eventTransport ?? new InProcessSupplierPerformanceBus({ logger });
603
- const tenant = resolveTenantConfig(config.tenant);
604
- const models = createSupplierPerformanceModels(config.connection, {
664
+ //#region src/engine/define-supplier-performance.ts
665
+ /**
666
+ * `defineSupplierPerformance` — the DESCRIBE/BIND blueprint for the supplier
667
+ * performance engine (STANDARDIZATION-PLAN §6). Splits construction into two
668
+ * phases:
669
+ *
670
+ * - **describe** (`defineSupplierPerformance(shape)`): pure. Resolves the
671
+ * tenant config and freezes the model names via mongokit's `defineModels()`.
672
+ * No connection, no schema built, no I/O — safe at import / module-composition
673
+ * time.
674
+ * - **bind** (`blueprint.bind(connection, runtime)`): compiles the schemas on
675
+ * the supplied connection, registers the models, wires the tenant plugin /
676
+ * repositories / service / transport, and returns the frozen
677
+ * `SupplierPerformanceEngine`.
678
+ *
679
+ * This is the sole construction API — there is no `createSupplierPerformance`
680
+ * wrapper.
681
+ */
682
+ /**
683
+ * Describe the supplier-performance engine. Pure — registers no model, builds no
684
+ * schema, performs no I/O.
685
+ */
686
+ function defineSupplierPerformance(shape = {}) {
687
+ /**
688
+ * The pre-consolidation tenant keys are REFUSED, never absorbed.
689
+ *
690
+ * Tenancy resolves from `shape.tenant`, so a leftover `multiTenant` /
691
+ * `tenantFieldType` is invisible here and scoping silently falls back to the
692
+ * package default instead of what the host configured — no error, and every
693
+ * read afterwards returns plausible rows from the wrong scope.
694
+ *
695
+ * tsc cannot cover it: excess-property checking does not fire for a typed
696
+ * variable, a spread, or a shape handed over from a dependency's dist.
697
+ */
698
+ assertNoLegacyTenantKeys(shape, "defineSupplierPerformance", [["tenantFieldType", "tenant.fieldType"]]);
699
+ const tenant = resolveTenantConfig(shape.tenant);
700
+ if (tenant.strategy === "custom") throw new Error("[supplier-performance] tenant.strategy 'custom' is unsupported: supplier-performance repositories require one concrete tenant field");
701
+ const tenantExtras = typeof shape.tenant === "object" && shape.tenant !== null ? shape.tenant : void 0;
702
+ const modelBlueprint = defineSupplierPerformanceModels({
605
703
  tenant,
606
- ...config.collectionPrefix !== void 0 ? { collectionPrefix: config.collectionPrefix } : {},
607
- ...config.forceRecreate !== void 0 ? { forceRecreate: config.forceRecreate } : {}
608
- });
609
- const tenantPlugins = (() => {
610
- if (!tenant.enabled || tenant.strategy !== "field") return [];
611
- const extras = typeof config.tenant === "object" ? config.tenant : void 0;
612
- return [multiTenantPlugin({
613
- tenantField: tenant.tenantField,
614
- fieldType: tenant.fieldType,
615
- contextKey: tenant.contextKey,
616
- required: tenant.required,
617
- ...extras?.skipOperations !== void 0 ? { skipOperations: extras.skipOperations } : {},
618
- ...extras?.skipWhen !== void 0 ? { skipWhen: extras.skipWhen } : {},
619
- ...extras?.resolveContext !== void 0 ? { resolveContext: extras.resolveContext } : {},
620
- ...extras?.allowDataInjection !== void 0 ? { allowDataInjection: extras.allowDataInjection } : {},
621
- ...extras?.onMismatch !== void 0 ? { onMismatch: extras.onMismatch } : {}
622
- })];
623
- })();
624
- const repoPlugins = config.repositoryPlugins ?? {};
625
- const performanceEvent = new PerformanceEventRepository({
626
- model: models.PerformanceEvent,
627
- plugins: [...tenantPlugins, ...repoPlugins.performanceEvent ?? []]
628
- });
629
- const supplierScore = new SupplierScoreRepository({
630
- model: models.SupplierScore,
631
- plugins: [...tenantPlugins, ...repoPlugins.supplierScore ?? []]
632
- });
633
- const score = new ScoreService({
634
- events: performanceEvent,
635
- scores: supplierScore,
636
- eventTransport: events,
637
- ...config.outbox !== void 0 ? { outbox: config.outbox } : {},
638
- logger
704
+ ...shape.collectionPrefix !== void 0 ? { collectionPrefix: shape.collectionPrefix } : {},
705
+ ...shape.autoIndex !== void 0 ? { autoIndex: shape.autoIndex } : {},
706
+ ...shape.forceRecreate !== void 0 ? { forceRecreate: shape.forceRecreate } : {}
639
707
  });
640
708
  return {
641
- models,
642
- repositories: {
643
- performanceEvent,
644
- supplierScore
645
- },
646
- services: { score },
647
- events,
648
- async syncIndexes() {
649
- await Promise.all([models.PerformanceEvent.syncIndexes(), models.SupplierScore.syncIndexes()]);
650
- },
651
- async destroy() {
652
- await events.close?.();
709
+ id: "supplier-performance",
710
+ modelNames: modelBlueprint.modelNames,
711
+ bind(connection, runtime = {}) {
712
+ /**
713
+ * §11 outbox atomicity — checked BEFORE the models bind, so a refused bind
714
+ * leaves the connection's model registry untouched.
715
+ *
716
+ * `OutboxWriteOptions.session` is best-effort BY CONTRACT (see
717
+ * `@classytic/primitives/outbox`), so a hand-rolled store satisfies
718
+ * `OutboxStore` and then keeps the row when the transaction aborts:
719
+ * a delivery/defect signal that survives a rolled-back write scores a supplier on an
720
+ * event that never happened — and scorecards drive sourcing decisions and penalties.
721
+ * Nothing throws on either side — the divergence only ever shows up
722
+ * downstream, as a consumer acting on something that never happened.
723
+ *
724
+ * Discovering that in production is far worse than at boot.
725
+ */
726
+ if (runtime.outbox && runtime.outbox.transactionalSave !== true) throw new Error("defineSupplierPerformance.bind: the configured OutboxStore does not declare `transactionalSave: true`, so it does not promise that `save()` enlists `ctx.session` (see @classytic/primitives/outbox — the option is best-effort by contract). Supplier-performance writes its event rows inside the transaction of its caller; a store that ignores the session scores suppliers on signals that rolled back, so a scorecard — which drives sourcing decisions and contractual penalties — is computed from deliveries that were never recorded. Arc's `repositoryAsOutboxStore` declares it; the in-memory `MemoryOutboxStore` must not — pass no outbox instead.");
727
+ const models = modelBlueprint.bind(connection);
728
+ const logger = runtime.logger ?? console;
729
+ const ownsTransport = runtime.eventTransport === void 0;
730
+ const transport = runtime.eventTransport ?? new InProcessSupplierPerformanceBus({ logger });
731
+ const tenantPlugins = !tenant.enabled || tenant.strategy !== "field" ? [] : [multiTenantPlugin({
732
+ tenantField: tenant.tenantField,
733
+ fieldType: tenant.fieldType,
734
+ contextKey: tenant.contextKey,
735
+ required: tenant.required,
736
+ ...tenantExtras?.skipOperations !== void 0 ? { skipOperations: tenantExtras.skipOperations } : {},
737
+ ...tenantExtras?.skipWhen !== void 0 ? { skipWhen: tenantExtras.skipWhen } : {},
738
+ ...tenantExtras?.resolveContext !== void 0 ? { resolveContext: tenantExtras.resolveContext } : {},
739
+ ...tenantExtras?.allowDataInjection !== void 0 ? { allowDataInjection: tenantExtras.allowDataInjection } : {},
740
+ ...tenantExtras?.onMismatch !== void 0 ? { onMismatch: tenantExtras.onMismatch } : {}
741
+ })];
742
+ const repoPlugins = runtime.repositoryPlugins ?? {};
743
+ const performanceEvent = new PerformanceEventRepository({
744
+ model: models.PerformanceEvent,
745
+ plugins: [...tenantPlugins, ...repoPlugins.performanceEvent ?? []]
746
+ });
747
+ const supplierScore = new SupplierScoreRepository({
748
+ model: models.SupplierScore,
749
+ plugins: [...tenantPlugins, ...repoPlugins.supplierScore ?? []]
750
+ });
751
+ const score = new ScoreService({
752
+ events: performanceEvent,
753
+ scores: supplierScore,
754
+ eventTransport: transport,
755
+ ...runtime.outbox !== void 0 ? { outbox: runtime.outbox } : {},
756
+ logger
757
+ });
758
+ return Object.freeze({
759
+ models,
760
+ repositories: Object.freeze({
761
+ performanceEvent,
762
+ supplierScore
763
+ }),
764
+ services: Object.freeze({ score }),
765
+ events: transport,
766
+ async syncIndexes() {
767
+ await Promise.all([models.PerformanceEvent.syncIndexes(), models.SupplierScore.syncIndexes()]);
768
+ },
769
+ async close() {
770
+ if (ownsTransport) await transport.close?.();
771
+ }
772
+ });
653
773
  }
654
774
  };
655
775
  }
656
776
  //#endregion
657
- export { EventRecorded, InProcessSupplierPerformanceBus, PERFORMANCE_EVENT_TYPE_VALUES, PerformanceEventModelCollisionError, PerformanceEventRepository, PerformanceEventType, ScoreComputed, ScoreService, SupplierPerformanceError, SupplierPerformanceEvents, SupplierPerformanceValidationError, SupplierScoreModelCollisionError, SupplierScoreRepository, createEvent, createPerformanceEventModel, createSupplierPerformance, createSupplierPerformanceModels, createSupplierScoreModel, repoOptionsFromCtx, resolveSupplierPerformanceTenant, scoreFromEvents, supplierPerformanceEventDefinitions };
777
+ export { EventRecorded, InProcessSupplierPerformanceBus, PERFORMANCE_EVENT_COLLECTION, PERFORMANCE_EVENT_TYPE_VALUES, PerformanceEventRepository, PerformanceEventType, SUPPLIER_SCORE_COLLECTION, ScoreComputed, ScoreService, SupplierPerformanceError, SupplierPerformanceEvents, SupplierPerformanceValidationError, SupplierScoreRepository, buildPerformanceEventSchema, buildSupplierScoreSchema, createEvent, defineSupplierPerformance, defineSupplierPerformanceModels, injectTenantField, repoOptionsFromCtx, resolveSupplierPerformanceTenant, scoreFromEvents, supplierPerformanceEventDefinitions };
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@classytic/supplier-performance",
3
- "version": "0.3.1",
3
+ "version": "0.4.1",
4
4
  "description": "Framework-agnostic supplier performance engine — on-time-delivery, defect, and price-variance tracking with append-only event log + cached scorecards. Powered by MongoDB via @classytic/mongokit. Zero framework deps — usable from Arc, Express, Nest, Next.js, or raw Node.",
5
5
  "author": "Classytic",
6
- "license": "MIT",
6
+ "license": "SEE LICENSE IN LICENSE",
7
7
  "homepage": "https://www.npmjs.com/package/@classytic/supplier-performance",
8
8
  "bugs": {
9
9
  "url": "https://github.com/classytic/supplier-performance/issues"
@@ -34,10 +34,12 @@
34
34
  },
35
35
  "exports": {
36
36
  ".": {
37
+ "@classytic/source": "./src/index.ts",
37
38
  "types": "./dist/index.d.ts",
38
39
  "default": "./dist/index.js"
39
40
  },
40
41
  "./events": {
42
+ "@classytic/source": "./src/events.ts",
41
43
  "types": "./dist/events.d.ts",
42
44
  "default": "./dist/events.js"
43
45
  }
@@ -60,21 +62,22 @@
60
62
  "release": "npm run push -- main && npm run release:tag && npm publish"
61
63
  },
62
64
  "peerDependencies": {
63
- "@classytic/mongokit": ">=3.22.0",
64
- "@classytic/repo-core": ">=0.13.0",
65
- "@classytic/primitives": ">=0.11.0",
66
- "mongoose": ">=9.4.1",
65
+ "@classytic/mongokit": ">=3.47.0",
66
+ "@classytic/primitives": ">=0.39.0",
67
+ "@classytic/repo-core": ">=0.39.0",
68
+ "mongoose": ">=9.13.1",
67
69
  "zod": ">=4.0.0"
68
70
  },
69
71
  "devDependencies": {
70
72
  "@classytic/dev-tools": "^0.2.0",
71
- "@classytic/mongokit": "^3.22.1",
72
- "@classytic/repo-core": "^0.13.0",
73
- "@classytic/primitives": "^0.11.0",
73
+ "@classytic/mongokit": "^3.47.0",
74
+ "@classytic/primitives": "^0.39.0",
75
+ "@classytic/repo-core": "^0.39.0",
74
76
  "@types/node": "^25.5.0",
75
- "mongodb-memory-server": "^10.2.3",
76
- "mongoose": "^9.4.1",
77
- "tsdown": "^0.14.2",
77
+ "mongodb-memory-server": "^11.4.0",
78
+ "mongoose": "^9.13.1",
79
+ "publint": "^0.3.23",
80
+ "tsdown": "^0.22.14",
78
81
  "typescript": "^5.8.2",
79
82
  "vitest": "^3.2.4",
80
83
  "zod": "^4.0.0"