@molecule/api-ai-moderation-pipeline 1.0.0 → 1.0.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.
Files changed (2) hide show
  1. package/README.md +287 -0
  2. package/package.json +15 -9
package/README.md ADDED
@@ -0,0 +1,287 @@
1
+ <!--
2
+ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
+ Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
+ Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
+ To change this document, edit the module-level JSDoc in src/index.ts.
6
+ Generated: 2026-08-04T01:47:34.367Z
7
+ -->
8
+
9
+ # @molecule/api-ai-moderation-pipeline
10
+
11
+ > **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
12
+ > It is written to be read by coding agents as much as by people, and is generated from this
13
+ > package's source — edit `src/index.ts` JSDoc, not this file.
14
+
15
+ `@molecule/api-ai-moderation-pipeline` — content moderation built on
16
+ the bonded AI provider. Classify → policy-match → action → audit-log.
17
+
18
+ Extracted from ai-content-moderator flagship.
19
+
20
+ ## Quick Start
21
+
22
+ ```ts
23
+ import { moderate, DEFAULT_POLICY } from '@molecule/api-ai-moderation-pipeline'
24
+
25
+ const decision = await moderate({
26
+ content: userComment,
27
+ ownerId: userId,
28
+ resource: { type: 'comment', id: commentId },
29
+ })
30
+ if (decision.action === 'block') return res.status(403).end()
31
+ if (decision.action === 'flag') void notifyMods(decision)
32
+ ```
33
+
34
+ ## Type
35
+
36
+ `utility`
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ npm install @molecule/api-ai-moderation-pipeline @molecule/api-ai @molecule/api-bonds-default-express @molecule/api-database @molecule/api-i18n @molecule/api-logger @molecule/api-middleware-validation
42
+ ```
43
+
44
+ ## API
45
+
46
+ ### Interfaces
47
+
48
+ #### `AuditLogRow`
49
+
50
+ Database row shape for a single moderation audit-log entry.
51
+
52
+ ```typescript
53
+ interface AuditLogRow {
54
+ id: string
55
+ owner_id: string | null
56
+ content_excerpt: string
57
+ decision: ModerationAction
58
+ matched_category: ModerationCategory | null
59
+ scores: ModerationScore[]
60
+ reasoning: string
61
+ resource_type: string | null
62
+ resource_id: string | null
63
+ created_at: string | Date
64
+ }
65
+ ```
66
+
67
+ #### `ClassificationResult`
68
+
69
+ Result of a single classification attempt against the bonded AI provider.
70
+
71
+ ```typescript
72
+ interface ClassificationResult {
73
+ scores: ModerationScore[]
74
+ reasoning: string
75
+ /**
76
+ * Set when the classifier FAILED to produce a usable signal — a provider
77
+ * error/timeout, an in-band `error` event, or malformed model output. When
78
+ * present, `scores` is empty; the pipeline routes per `policy.onError`
79
+ * instead of treating the empty scores as an allow. `moderate()` handles this
80
+ * for you; direct `classify()` callers MUST check `error` before trusting an
81
+ * empty-scores result.
82
+ */
83
+ error?: Error
84
+ }
85
+ ```
86
+
87
+ #### `ModerationDecision`
88
+
89
+ Final verdict returned by the pipeline for a piece of content.
90
+
91
+ ```typescript
92
+ interface ModerationDecision {
93
+ action: ModerationAction
94
+ scores: ModerationScore[]
95
+ reasoning: string
96
+ /** Most severe matched category, if any. */
97
+ matched_category: ModerationCategory | null
98
+ /** True if any non-safe category exceeded its policy threshold. */
99
+ flagged: boolean
100
+ /**
101
+ * True when this decision came from a classifier FAILURE routed through
102
+ * `policy.onError` (no real moderation signal), rather than a real verdict.
103
+ * Lets callers/audits distinguish a fail-safe `'flag'`/`'block'` from a
104
+ * genuine one. Absent (undefined) on normal decisions.
105
+ */
106
+ errored?: boolean
107
+ }
108
+ ```
109
+
110
+ #### `ModerationPolicy`
111
+
112
+ Per-category thresholds and actions that govern moderation decisions.
113
+
114
+ ```typescript
115
+ interface ModerationPolicy {
116
+ /** Threshold per category — content above this score triggers the action. */
117
+ thresholds: Partial<Record<ModerationCategory, number>>
118
+ /** What action to take when any threshold is exceeded. */
119
+ action: ModerationAction
120
+ /** Default action when no threshold is exceeded. */
121
+ defaultAction?: ModerationAction
122
+ /**
123
+ * What to do when classification FAILS (provider error/timeout or malformed
124
+ * output) — i.e. when there is no real moderation signal. Defaults to
125
+ * `'flag'` (route to human review) so a transient classifier blip never
126
+ * silently ALLOWS un-moderated content. Set `'allow'` to explicitly opt into
127
+ * fail-open, or `'block'` to fail closed. When omitted, the
128
+ * `MODERATION_ON_ERROR` env var is consulted, then falls back to `'flag'`.
129
+ */
130
+ onError?: ModerationErrorAction
131
+ }
132
+ ```
133
+
134
+ #### `ModerationScore`
135
+
136
+ Per-category confidence score produced by a moderation classifier.
137
+
138
+ ```typescript
139
+ interface ModerationScore {
140
+ category: ModerationCategory
141
+ /** 0..1 confidence. */
142
+ score: number
143
+ }
144
+ ```
145
+
146
+ ### Types
147
+
148
+ #### `ModerationAction`
149
+
150
+ Action the pipeline takes after evaluating content against policy.
151
+
152
+ ```typescript
153
+ type ModerationAction = 'allow' | 'flag' | 'block' | 'redact'
154
+ ```
155
+
156
+ #### `ModerationCategory`
157
+
158
+ Content category assigned by the moderation pipeline.
159
+
160
+ ```typescript
161
+ type ModerationCategory =
162
+ | 'hate'
163
+ | 'harassment'
164
+ | 'sexual'
165
+ | 'self_harm'
166
+ | 'violence'
167
+ | 'illegal'
168
+ | 'spam'
169
+ | 'misinformation'
170
+ | 'pii'
171
+ | 'safe'
172
+ ```
173
+
174
+ #### `ModerationErrorAction`
175
+
176
+ Action taken when the classifier itself FAILS to produce a usable signal —
177
+ a provider error/timeout, an in-band `error` event, or malformed model output.
178
+ There is no real moderation verdict in that case, so the pipeline routes per
179
+ this policy instead of silently allowing un-moderated content.
180
+
181
+ - `'flag'` — route to human review (safe default; never a silent allow).
182
+ - `'block'` — fail closed (deny the content).
183
+ - `'allow'` — explicit opt-in to fail OPEN (content passes un-moderated).
184
+
185
+ ```typescript
186
+ type ModerationErrorAction = 'allow' | 'flag' | 'block'
187
+ ```
188
+
189
+ ### Functions
190
+
191
+ #### `applyPolicy(scores, reasoning, policy?)`
192
+
193
+ Apply a policy to classifier scores → moderation decision.
194
+
195
+ ```typescript
196
+ function applyPolicy(
197
+ scores: ModerationScore[],
198
+ reasoning: string,
199
+ policy?: ModerationPolicy,
200
+ ): ModerationDecision
201
+ ```
202
+
203
+ #### `classify(content)`
204
+
205
+ Classify content using the bonded AI provider.
206
+
207
+ On a provider error/timeout, an in-band `error` stream event, or malformed
208
+ model output, this resolves to empty `scores` with `error` set — it does NOT
209
+ throw and does NOT fabricate a benign result. `moderate()` routes that
210
+ failure per `policy.onError`; direct callers MUST check `result.error` before
211
+ trusting an empty-scores result (an empty result with no `error` means the
212
+ model genuinely scored everything at 0).
213
+
214
+ ```typescript
215
+ function classify(content: string): Promise<ClassificationResult>
216
+ ```
217
+
218
+ - `content` — The content to classify.
219
+
220
+ **Returns:** The classification result — scores + reasoning, or `error` on failure.
221
+
222
+ #### `moderate(opts)`
223
+
224
+ Full pipeline — classify + decide + audit. Returns the decision.
225
+
226
+ ```typescript
227
+ function moderate(opts: {
228
+ content: string
229
+ policy?: ModerationPolicy
230
+ ownerId?: string | null
231
+ resource?: { type: string; id: string }
232
+ audit?: boolean
233
+ }): Promise<ModerationDecision>
234
+ ```
235
+
236
+ ### Constants
237
+
238
+ #### `DEFAULT_POLICY`
239
+
240
+ Default moderation policy applied when no explicit policy is provided.
241
+
242
+ ```typescript
243
+ const DEFAULT_POLICY: ModerationPolicy
244
+ ```
245
+
246
+ ## Injection Notes
247
+
248
+ ### Requirements
249
+
250
+ Peer dependencies:
251
+
252
+ - `@molecule/api-bonds-default-express` ^1.0.1
253
+ - `@molecule/api-database` ^1.0.1
254
+ - `@molecule/api-i18n` ^1.0.1
255
+ - `@molecule/api-logger` ^1.0.1
256
+ - `@molecule/api-middleware-validation` ^1.0.1
257
+ - `@molecule/api-ai` ^1.0.1
258
+
259
+ ### Runtime Dependencies
260
+
261
+ - `@molecule/api-ai`
262
+ - `@molecule/api-bonds-default-express`
263
+ - `@molecule/api-database`
264
+ - `@molecule/api-i18n`
265
+ - `@molecule/api-logger`
266
+ - `@molecule/api-middleware-validation`
267
+
268
+ Tables: `src/__setup__/moderation_audit_log.sql` creates
269
+ `moderation_audit_log`. An mlcl-scaffolded API replays `__setup__/*.sql`
270
+ automatically on migrate; anywhere else run it once. Audit writes are
271
+ best-effort (a DB failure never blocks the moderation decision) but are NO
272
+ LONGER silent: a failed write is logged via `logger.warn({ error })`, so a
273
+ missing table surfaces in logs instead of vanishing.
274
+
275
+ Requires a bonded `ai` chat provider (`@molecule/api-ai`) — `classify()` /
276
+ `moderate()` throw if none is bonded (a misconfiguration, surfaced loudly).
277
+
278
+ FAILS SAFE on classifier failure. When the classifier can't produce a signal
279
+ — a provider error/timeout, an in-band `error` stream event, or malformed
280
+ model output — `classify()` returns empty `scores` WITH `error` set, and
281
+ `moderate()` routes per `policy.onError`, ALWAYS logging the failure via
282
+ `logger.error({ error })`. `onError` defaults to `'flag'` (route to human
283
+ review — never a silent allow); set `'block'` to fail closed or `'allow'` to
284
+ explicitly opt into fail-open. The env var `MODERATION_ON_ERROR` overrides
285
+ the default when a policy omits `onError`. Such decisions carry
286
+ `errored: true`. Direct `classify()` callers (bypassing `moderate()`) MUST
287
+ check `result.error` before trusting empty `scores`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/api-ai-moderation-pipeline",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "AI content moderation pipeline — classify, policy-match, action, audit-log",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -17,7 +17,8 @@
17
17
  }
18
18
  },
19
19
  "files": [
20
- "dist"
20
+ "dist",
21
+ "README.md"
21
22
  ],
22
23
  "keywords": [
23
24
  "molecule",
@@ -28,18 +29,23 @@
28
29
  "resource"
29
30
  ],
30
31
  "license": "Apache-2.0",
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "https://github.com/molecule-dev/molecule.git",
35
+ "directory": "packages/api/ai/moderation-pipeline"
36
+ },
31
37
  "devDependencies": {
32
- "@molecule/api-logger": "1.0.0",
38
+ "@molecule/api-logger": "1.0.1",
33
39
  "@types/node": "26.1.2",
34
40
  "typescript": "6.0.3",
35
41
  "vitest": "4.1.10"
36
42
  },
37
43
  "peerDependencies": {
38
- "@molecule/api-bonds-default-express": "^1.0.0",
39
- "@molecule/api-database": "^1.0.0",
40
- "@molecule/api-i18n": "^1.0.0",
41
- "@molecule/api-logger": "^1.0.0",
42
- "@molecule/api-middleware-validation": "^1.0.0",
43
- "@molecule/api-ai": "^1.0.0"
44
+ "@molecule/api-bonds-default-express": "^1.0.1",
45
+ "@molecule/api-database": "^1.0.1",
46
+ "@molecule/api-i18n": "^1.0.1",
47
+ "@molecule/api-logger": "^1.0.1",
48
+ "@molecule/api-middleware-validation": "^1.0.1",
49
+ "@molecule/api-ai": "^1.0.1"
44
50
  }
45
51
  }