@blogmcp/mdx-codemods 0.1.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.
package/src/runner.ts ADDED
@@ -0,0 +1,483 @@
1
+ /**
2
+ * MDX codemod runner.
3
+ *
4
+ * Walks every translation row stored at `schemaVersion < effectiveTarget`,
5
+ * applies the chain of registered migrations that brings each row up to
6
+ * the effective target, and persists the rewritten content through the
7
+ * store's optimistic-concurrency write path.
8
+ *
9
+ * Design notes (cross-referenced with `competitor-monitor/docs/internal/optimistic-concurrency.md`
10
+ * and the plan file's PR 3 section):
11
+ *
12
+ * - **Per-translation independent:** Czech and English translations of
13
+ * the same article are separate rows; a failure on one doesn't block
14
+ * the other.
15
+ * - **Pin-respecting:** `effectiveTarget = min(targetVersion, tenantPin ?? targetVersion)`.
16
+ * Tenants pinned below the runtime SCHEMA_VERSION stop migrating at
17
+ * the pin; raising the pin later resumes migration on next boot.
18
+ * - **Skip-and-log:** a transform that throws or a write conflict
19
+ * that exhausts retries → translation recorded in
20
+ * `mdx_codemod_errors`, batch continues.
21
+ * - **Idempotent in aggregate:** transforms must be idempotent
22
+ * individually (author contract). The runner adds:
23
+ * (a) `changed: false` short-circuits the write path entirely,
24
+ * (b) re-running the runner against the same DB state is a no-op
25
+ * (no row matches the `< effectiveTarget` filter once all are
26
+ * stamped at target).
27
+ * - **Cache + embedding invalidation:** after a successful migration
28
+ * chain on at least one of an article's translations, the article
29
+ * is marked for re-embedding and a cache-bust event is emitted.
30
+ */
31
+
32
+ import { gt, gte, lt, valid } from 'semver'
33
+ import type {
34
+ CodemodError,
35
+ CodemodStore,
36
+ Migration,
37
+ RunMigrationsResult,
38
+ StoredTranslation,
39
+ } from './types.js'
40
+
41
+ export interface RunMigrationsOpts {
42
+ /**
43
+ * The runtime's compiled SCHEMA_VERSION. The runner clamps it down
44
+ * to `min(targetVersion, tenantPin)` for the effective target.
45
+ */
46
+ targetVersion: string
47
+
48
+ /**
49
+ * Every migration the runtime knows about. Static array from
50
+ * `migrations.ts` (or a custom subset for tests). The runner sorts
51
+ * by `from` semver ascending before walking, so order in this array
52
+ * is not load-bearing.
53
+ */
54
+ migrations: Migration[]
55
+
56
+ /** Pluggable storage layer. PR 4 wires it to KB API services. */
57
+ store: CodemodStore
58
+
59
+ /** Batch size for fetching translations. Default 50. */
60
+ batchSize?: number
61
+
62
+ /**
63
+ * Max retries on optimistic-write conflict per migration step.
64
+ * Default 3. After the cap the translation is recorded in
65
+ * `mdx_codemod_errors` and the batch continues.
66
+ */
67
+ maxRetries?: number
68
+ }
69
+
70
+ function assertValidSemver(label: string, version: string): void {
71
+ if (!valid(version)) {
72
+ throw new Error(
73
+ `[mdx-codemods] runMigrations: ${label} version "${version}" is not valid semver`,
74
+ )
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Picks the migrations to apply, in order, that bring a translation
80
+ * stamped at `currentVersion` up to `effectiveTarget`.
81
+ *
82
+ * Migrations are sorted by their `from` version ascending. The chain
83
+ * starts at `currentVersion` and walks: for each step, find a
84
+ * migration whose `from === currentVersion` AND `to <= effectiveTarget`,
85
+ * advance `currentVersion = migration.to`, repeat.
86
+ *
87
+ * Multiple migrations starting from the same `from` are not supported
88
+ * (it would make the walk non-deterministic). The classifier should
89
+ * eventually reject that shape; the runner will pick the first match
90
+ * here, which is fine for the well-formed case.
91
+ */
92
+ function planMigrationChain(
93
+ currentVersion: string,
94
+ effectiveTarget: string,
95
+ migrations: Migration[],
96
+ ): Migration[] {
97
+ const sorted = [...migrations].sort((a, b) => {
98
+ if (gt(a.from, b.from)) return 1
99
+ if (lt(a.from, b.from)) return -1
100
+ return 0
101
+ })
102
+ const chain: Migration[] = []
103
+ let cursor = currentVersion
104
+ // Defensive cap: never walk more than the registered migration count.
105
+ for (let i = 0; i < sorted.length; i++) {
106
+ const next = sorted.find(
107
+ m => m.from === cursor && !gt(m.to, effectiveTarget),
108
+ )
109
+ if (!next) break
110
+ chain.push(next)
111
+ cursor = next.to
112
+ if (cursor === effectiveTarget) break
113
+ }
114
+ return chain
115
+ }
116
+
117
+ async function applyChainToTranslation(
118
+ translation: StoredTranslation,
119
+ chain: Migration[],
120
+ store: CodemodStore,
121
+ maxRetries: number,
122
+ ): Promise<
123
+ | { outcome: 'migrated'; finalVersion: string }
124
+ | { outcome: 'skipped' }
125
+ | { outcome: 'failed'; error: CodemodError }
126
+ > {
127
+ let current = translation
128
+ let anyChanged = false
129
+
130
+ for (const migration of chain) {
131
+ let attempt = 0
132
+ while (true) {
133
+ let result: { content: string; changed: boolean }
134
+ try {
135
+ result = migration.transform(current.content)
136
+ } catch (err) {
137
+ const e = err as Error
138
+ return {
139
+ outcome: 'failed',
140
+ error: {
141
+ translationId: translation.id,
142
+ migrationSlug: migration.slug,
143
+ fromVersion: migration.from,
144
+ toVersion: migration.to,
145
+ errorMessage: e.message,
146
+ errorStack: e.stack,
147
+ },
148
+ }
149
+ }
150
+
151
+ if (!result.changed) {
152
+ // Stamp the version forward even on no-op so a later
153
+ // re-invocation doesn't re-walk this row.
154
+ const stamp = await store.writeTranslation(
155
+ current.id,
156
+ current.content,
157
+ migration.to,
158
+ current.schemaVersion,
159
+ migration.slug,
160
+ )
161
+ if (stamp.success) {
162
+ current = { ...current, schemaVersion: migration.to }
163
+ break
164
+ }
165
+ // Fix 8: pin violation is NOT retryable — surface as a failure
166
+ // with a descriptive message. The store already wrote a
167
+ // __pin_violation__ row in mdx_codemod_errors.
168
+ if (stamp.pinViolation) {
169
+ return {
170
+ outcome: 'failed',
171
+ error: {
172
+ translationId: translation.id,
173
+ migrationSlug: migration.slug,
174
+ fromVersion: migration.from,
175
+ toVersion: migration.to,
176
+ errorMessage: 'pin violation — content after migration uses components/props forbidden by the tenant pin',
177
+ },
178
+ }
179
+ }
180
+ // No-op + conflict: re-fetch + retry stamping. Don't count
181
+ // this against the transform retry cap because nothing changed.
182
+ } else {
183
+ const stamp = await store.writeTranslation(
184
+ current.id,
185
+ result.content,
186
+ migration.to,
187
+ current.schemaVersion,
188
+ migration.slug,
189
+ )
190
+ if (stamp.success) {
191
+ current = {
192
+ ...current,
193
+ content: result.content,
194
+ schemaVersion: migration.to,
195
+ }
196
+ anyChanged = true
197
+ break
198
+ }
199
+ // Fix 8: same pin-violation early exit on the changed-content path.
200
+ if (stamp.pinViolation) {
201
+ return {
202
+ outcome: 'failed',
203
+ error: {
204
+ translationId: translation.id,
205
+ migrationSlug: migration.slug,
206
+ fromVersion: migration.from,
207
+ toVersion: migration.to,
208
+ errorMessage: 'pin violation — content after migration uses components/props forbidden by the tenant pin',
209
+ },
210
+ }
211
+ }
212
+ }
213
+
214
+ attempt++
215
+ if (attempt > maxRetries) {
216
+ return {
217
+ outcome: 'failed',
218
+ error: {
219
+ translationId: translation.id,
220
+ migrationSlug: migration.slug,
221
+ fromVersion: migration.from,
222
+ toVersion: migration.to,
223
+ errorMessage: `optimistic-write conflict exceeded ${maxRetries} retries`,
224
+ },
225
+ }
226
+ }
227
+ const refreshed = await store.getTranslation(translation.id)
228
+ if (!refreshed) {
229
+ return {
230
+ outcome: 'failed',
231
+ error: {
232
+ translationId: translation.id,
233
+ migrationSlug: migration.slug,
234
+ fromVersion: migration.from,
235
+ toVersion: migration.to,
236
+ errorMessage: 'translation disappeared during retry (deleted concurrently?)',
237
+ },
238
+ }
239
+ }
240
+ // If the refreshed row has already moved past this migration's
241
+ // `to` (someone else ran the same migration in parallel), stop —
242
+ // the chain may need replanning from the new cursor.
243
+ if (gte(refreshed.schemaVersion, migration.to)) {
244
+ current = refreshed
245
+ break
246
+ }
247
+ current = refreshed
248
+ }
249
+ }
250
+
251
+ if (anyChanged) {
252
+ return { outcome: 'migrated', finalVersion: current.schemaVersion }
253
+ }
254
+ return { outcome: 'skipped' }
255
+ }
256
+
257
+ /**
258
+ * Apply the registered migration chain to a single content blob,
259
+ * outside the DB-backed runner. Used by `restoreVersion` (Fix 5) to
260
+ * bring an older snapshot's content forward to the current runtime's
261
+ * SCHEMA_VERSION before writing it back as the latest version.
262
+ *
263
+ * Differs from `runMigrations` in that:
264
+ * - No store; no batch loop; no per-row error capture. The single
265
+ * content blob is migrated synchronously and the result returned.
266
+ * - It does NOT throw on an unbridged version gap. When no (or only a
267
+ * partial) chain exists, it returns the content unchanged at the
268
+ * highest version it could actually reach (`finalVersion` ≤ target) —
269
+ * the same "leave the row alone" stance `runMigrations` takes for an
270
+ * empty chain. This is correct because the renderer's `prepareProps`
271
+ * shim handles every shimmable (Tier-1/Tier-2) change at render time
272
+ * regardless of the stamped version, and a genuinely Tier-3 gap is
273
+ * left at its true version so the codemod runner reconciles it once a
274
+ * codemod is registered (rather than being silently over-stamped to
275
+ * the target and skipped forever). Keying the decision on the major
276
+ * version was wrong: a Tier-2-only MAJOR bump is shim-only (no
277
+ * codemod) yet would have falsely thrown, and a non-contiguous chain
278
+ * within a major would have silently restamped past a registered
279
+ * codemod.
280
+ * - `changed=false` means every step was a no-op; the content is
281
+ * bit-for-bit identical to the input (with `finalVersion` updated).
282
+ *
283
+ * Idempotency contract is identical to runMigrations — each transform
284
+ * MUST be idempotent.
285
+ */
286
+ // Retained as exported API (re-exported by ArticleService, caught in the
287
+ // articles route) even though `migrateContentToCurrent` no longer throws it —
288
+ // removing it would break those imports, and a future caller may still want it.
289
+ export class UnmigratableContentError extends Error {
290
+ constructor(
291
+ public readonly fromSchemaVersion: string,
292
+ public readonly toSchemaVersion: string,
293
+ ) {
294
+ super(
295
+ `[mdx-codemods] no migration chain from ${fromSchemaVersion} to ${toSchemaVersion} ` +
296
+ `(content predates a registered migration; refusing to silently restore stale schema)`,
297
+ )
298
+ this.name = 'UnmigratableContentError'
299
+ }
300
+ }
301
+
302
+ export interface MigrateContentResult {
303
+ content: string
304
+ finalVersion: string
305
+ changed: boolean
306
+ appliedSlugs: string[]
307
+ }
308
+
309
+ export function migrateContentToCurrent(
310
+ content: string,
311
+ fromSchemaVersion: string,
312
+ toSchemaVersion: string,
313
+ migrations: Migration[],
314
+ ): MigrateContentResult {
315
+ assertValidSemver('fromSchemaVersion', fromSchemaVersion)
316
+ assertValidSemver('toSchemaVersion', toSchemaVersion)
317
+ if (gte(fromSchemaVersion, toSchemaVersion)) {
318
+ // Restoring a version that's already at or ahead of the runtime is
319
+ // a no-op chain (current === target). Stay quiet — this is the
320
+ // common case during a restore-to-recent.
321
+ return {
322
+ content,
323
+ finalVersion: fromSchemaVersion,
324
+ changed: false,
325
+ appliedSlugs: [],
326
+ }
327
+ }
328
+ const chain = planMigrationChain(fromSchemaVersion, toSchemaVersion, migrations)
329
+ if (chain.length === 0) {
330
+ // No registered migration bridges these versions. Leave the content
331
+ // alone at its CURRENT version — exactly what `runMigrations` does for an
332
+ // empty chain (it skips the row, leaving `schema_version` untouched). We do
333
+ // NOT restamp to the target: the content is forward-compatible at render
334
+ // time via `prepareProps` (Tier-1 additive / Tier-2 shim), and returning
335
+ // `fromSchemaVersion` keeps the row eligible for the codemod runner to
336
+ // finish later if a Tier-3 codemod is ever registered for this span. (The
337
+ // previous major()-keyed throw/restamp was wrong both ways — see the
338
+ // function docstring.)
339
+ return {
340
+ content,
341
+ finalVersion: fromSchemaVersion,
342
+ changed: false,
343
+ appliedSlugs: [],
344
+ }
345
+ }
346
+ let current = content
347
+ let cursor = fromSchemaVersion
348
+ let anyChanged = false
349
+ const appliedSlugs: string[] = []
350
+ for (const m of chain) {
351
+ const out = m.transform(current)
352
+ appliedSlugs.push(m.slug)
353
+ if (out.changed) {
354
+ current = out.content
355
+ anyChanged = true
356
+ }
357
+ cursor = m.to
358
+ }
359
+ return {
360
+ content: current,
361
+ finalVersion: cursor,
362
+ changed: anyChanged,
363
+ appliedSlugs,
364
+ }
365
+ }
366
+
367
+ export async function runMigrations(opts: RunMigrationsOpts): Promise<RunMigrationsResult> {
368
+ assertValidSemver('targetVersion', opts.targetVersion)
369
+ for (const m of opts.migrations) {
370
+ assertValidSemver(`migration "${m.slug}".from`, m.from)
371
+ assertValidSemver(`migration "${m.slug}".to`, m.to)
372
+ if (!gt(m.to, m.from)) {
373
+ throw new Error(
374
+ `[mdx-codemods] migration "${m.slug}" has to (${m.to}) not strictly greater than from (${m.from})`,
375
+ )
376
+ }
377
+ }
378
+
379
+ // Fix 15: pin is re-fetched per batch INSIDE the loop, so an operator
380
+ // who lowers the pin mid-run sees the change on the very next batch.
381
+ // The first read also validates the semver up front so an invalid pin
382
+ // surfaces immediately rather than after the first batch worth of
383
+ // wasted work.
384
+ const initialPin = await opts.store.getTenantPin()
385
+ if (initialPin !== null && !valid(initialPin)) {
386
+ throw new Error(
387
+ `[mdx-codemods] runMigrations: tenant pin "${initialPin}" is not valid semver`,
388
+ )
389
+ }
390
+ let effectiveTarget = initialPin !== null && lt(initialPin, opts.targetVersion) ? initialPin : opts.targetVersion
391
+
392
+ const batchSize = opts.batchSize ?? 50
393
+ const maxRetries = opts.maxRetries ?? 3
394
+
395
+ const result: RunMigrationsResult = {
396
+ translationsProcessed: 0,
397
+ translationsMigrated: 0,
398
+ translationsSkipped: 0,
399
+ translationsFailed: 0,
400
+ articlesInvalidated: new Set<string>(),
401
+ effectiveTargetVersion: effectiveTarget,
402
+ }
403
+
404
+ let cursor: string | undefined = undefined
405
+ let prevCursor: string | undefined = undefined
406
+ while (true) {
407
+ // Fix 15: re-fetch the pin per batch so an operator lowering the pin
408
+ // mid-run gets immediate effect. If the new pin drops below an
409
+ // already-stamped row's version, listTranslationsBelow naturally
410
+ // returns 0 rows (the loop exits cleanly). Invalid mid-run pin =
411
+ // log + exit cleanly rather than crashing the worker pod.
412
+ const pin = await opts.store.getTenantPin()
413
+ if (pin !== null && !valid(pin)) {
414
+ // eslint-disable-next-line no-console
415
+ console.warn(
416
+ `[mdx-codemods] tenant pin "${pin}" became invalid mid-run; exiting cleanly`,
417
+ )
418
+ break
419
+ }
420
+ effectiveTarget = pin !== null && lt(pin, opts.targetVersion) ? pin : opts.targetVersion
421
+ result.effectiveTargetVersion = effectiveTarget
422
+
423
+ const batch = await opts.store.listTranslationsBelow(effectiveTarget, {
424
+ batchSize,
425
+ afterId: cursor,
426
+ })
427
+ if (batch.length === 0) break
428
+ cursor = batch[batch.length - 1].id
429
+ // Defensive: if the store hands back a batch whose last id equals
430
+ // the cursor we passed in, it isn't honoring `afterId` and we'd
431
+ // spin forever. Surfaces a store-implementation bug loudly instead
432
+ // of hanging the whole graphile-worker pod.
433
+ if (prevCursor !== undefined && cursor === prevCursor) {
434
+ throw new Error(
435
+ `[mdx-codemods] runner cursor stalled at "${cursor}" — store.listTranslationsBelow ` +
436
+ `is not honoring \`afterId\` (returned the same trailing row twice in a row). ` +
437
+ `Check the store implementation against the contract in src/types.ts.`,
438
+ )
439
+ }
440
+ prevCursor = cursor
441
+
442
+ for (const translation of batch) {
443
+ result.translationsProcessed++
444
+
445
+ // Skip translations whose schemaVersion is already at/past the
446
+ // effective target — defensive, the store query should have
447
+ // filtered these out but pin changes mid-batch are possible.
448
+ if (gte(translation.schemaVersion, effectiveTarget)) {
449
+ result.translationsSkipped++
450
+ continue
451
+ }
452
+
453
+ const chain = planMigrationChain(translation.schemaVersion, effectiveTarget, opts.migrations)
454
+ if (chain.length === 0) {
455
+ // No registered migration knows how to bring this version
456
+ // forward — leave the row alone. (This can happen for legacy
457
+ // versions we never published a codemod for; operator decides
458
+ // whether to backport or leave as-is.)
459
+ result.translationsSkipped++
460
+ continue
461
+ }
462
+
463
+ const applied = await applyChainToTranslation(translation, chain, opts.store, maxRetries)
464
+ if (applied.outcome === 'failed') {
465
+ result.translationsFailed++
466
+ await opts.store.recordError(applied.error)
467
+ continue
468
+ }
469
+ if (applied.outcome === 'skipped') {
470
+ result.translationsSkipped++
471
+ continue
472
+ }
473
+ result.translationsMigrated++
474
+ if (!result.articlesInvalidated.has(translation.articleId)) {
475
+ result.articlesInvalidated.add(translation.articleId)
476
+ await opts.store.invalidateEmbedding(translation.articleId)
477
+ await opts.store.emitCacheBust(translation.articleId)
478
+ }
479
+ }
480
+ }
481
+
482
+ return result
483
+ }
package/src/types.ts ADDED
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Types for the MDX codemod runner.
3
+ *
4
+ * The runner is storage-agnostic — the KB API graphile-worker task that
5
+ * consumes it (PR 4) implements `CodemodStore` against the actual
6
+ * `kb_articles_translations` table + `mdx_codemod_errors` log + tenant
7
+ * settings. Tests pass mock stores to exercise the runner without a DB.
8
+ */
9
+
10
+ /**
11
+ * One MDX content rewriter. Each migration ships as a TypeScript file
12
+ * under `packages/mdx-codemods/src/migrations/<from>-<slug>.ts` and is
13
+ * statically imported into the `ALL_MIGRATIONS` registry.
14
+ *
15
+ * The `from` / `to` versions form a directed graph the runner walks
16
+ * per-translation: applying the chain of migrations whose `from`
17
+ * matches the translation's current `schema_version`, until the
18
+ * translation reaches the target version.
19
+ *
20
+ * **Idempotency contract:** `transform(s)` MUST return the same result
21
+ * when called twice on the same input. The runner may retry on write
22
+ * conflict; non-idempotent transforms produce divergent stored content
23
+ * across retries.
24
+ */
25
+ export interface Migration {
26
+ /**
27
+ * `schema_version` the migration runs against. A translation stamped
28
+ * at this version is a candidate for this migration.
29
+ */
30
+ from: string
31
+
32
+ /**
33
+ * `schema_version` to stamp on the translation after this migration
34
+ * succeeds. Must be strictly greater than `from` (semver `gt`).
35
+ */
36
+ to: string
37
+
38
+ /**
39
+ * Kebab-case slug. Convention: file is named `<to>-<slug>.ts`, so
40
+ * `slug = 'remove-callout-type'` ⇒ file `0.3.0-remove-callout-type.ts`.
41
+ * Used in error logs and `mdx_codemod_errors.migration_slug`.
42
+ */
43
+ slug: string
44
+
45
+ /**
46
+ * One-line description for the operations dashboard + commit log.
47
+ */
48
+ description: string
49
+
50
+ /**
51
+ * The content transform. Receives the raw stored MDX (frontmatter
52
+ * intact); returns the rewritten content plus a flag indicating
53
+ * whether anything actually changed. The runner uses `changed` to
54
+ * skip the write path for no-op invocations (e.g. an article that
55
+ * didn't use the affected component).
56
+ *
57
+ * Throwing from `transform` causes the runner to record a
58
+ * `CodemodError` and skip this translation — the batch continues
59
+ * with the next row.
60
+ */
61
+ transform(content: string): { content: string; changed: boolean }
62
+ }
63
+
64
+ /**
65
+ * A single translation row as seen by the runner. The runner is
66
+ * agnostic to the table layout — the store adapter projects
67
+ * `kb_articles_translations` (or any future equivalent) onto this
68
+ * shape.
69
+ */
70
+ export interface StoredTranslation {
71
+ id: string
72
+ articleId: string
73
+ languageCode: string
74
+ content: string
75
+ schemaVersion: string
76
+ }
77
+
78
+ /**
79
+ * Record of a per-translation migration failure. The runner accumulates
80
+ * these and hands them to the store via `recordError`. The store
81
+ * decides where to log them (PR 4: `mdx_codemod_errors` table).
82
+ */
83
+ export interface CodemodError {
84
+ translationId: string
85
+ migrationSlug: string
86
+ fromVersion: string
87
+ toVersion: string
88
+ errorMessage: string
89
+ errorStack?: string
90
+ }
91
+
92
+ /**
93
+ * Storage adapter implemented by consumers (KB API graphile-worker task).
94
+ *
95
+ * All methods are async — the runner awaits them sequentially per
96
+ * translation. The runner does NOT parallelize writes for a single
97
+ * translation (avoids racing optimistic-concurrency retries) but DOES
98
+ * iterate batches of translations in sequence; the calling task can
99
+ * fan out by sharding the batch range.
100
+ */
101
+ export interface CodemodStore {
102
+ /**
103
+ * Returns translations whose `schemaVersion` is strictly less than
104
+ * `targetVersion`. The store implements **cursor-based** pagination:
105
+ * results are ordered by `id` ascending; when `afterId` is set, only
106
+ * rows with `id > afterId` are returned. The runner stops calling
107
+ * when an empty batch comes back.
108
+ *
109
+ * Why cursor-based and not offset-based: offset breaks when rows
110
+ * fall out of the eligible set mid-iteration (which they do — once
111
+ * a translation is migrated, its `schemaVersion` is no longer
112
+ * `< targetVersion`). Also keeps failed rows past the cursor so a
113
+ * single bad row can't infinite-loop the batch.
114
+ */
115
+ listTranslationsBelow(
116
+ targetVersion: string,
117
+ opts: { batchSize: number; afterId?: string },
118
+ ): Promise<StoredTranslation[]>
119
+
120
+ /**
121
+ * Persists `newContent` as a new version of the translation, going
122
+ * from `expectedSchemaVersion` → `newSchemaVersion`. Uses the
123
+ * existing optimistic-write path (see
124
+ * `competitor-monitor/docs/internal/optimistic-concurrency.md`).
125
+ *
126
+ * Returns `{ success: true }` on a clean write.
127
+ * Returns `{ success: false, conflict: true }` if another writer
128
+ * advanced the translation's `schemaVersion` mid-flight — the
129
+ * runner retries by re-fetching.
130
+ */
131
+ writeTranslation(
132
+ translationId: string,
133
+ newContent: string,
134
+ newSchemaVersion: string,
135
+ expectedSchemaVersion: string,
136
+ migrationSlug: string,
137
+ ): Promise<{ success: boolean; conflict?: boolean; pinViolation?: boolean }>
138
+
139
+ /**
140
+ * Re-fetches a single translation by id. Used after a write conflict
141
+ * to pull the new `schemaVersion` for retry.
142
+ */
143
+ getTranslation(translationId: string): Promise<StoredTranslation | null>
144
+
145
+ /** Records a per-translation migration failure for operator visibility. */
146
+ recordError(error: CodemodError): Promise<void>
147
+
148
+ /**
149
+ * Marks the parent article for re-embedding (clears
150
+ * `kb_articles.embedded_at`). Called once per article after at least
151
+ * one of its translations was rewritten.
152
+ */
153
+ invalidateEmbedding(articleId: string): Promise<void>
154
+
155
+ /**
156
+ * Emits a cache-bust event for the article so the blog's ISR cache
157
+ * + any other downstream caches drop their stale rendering. Called
158
+ * once per article after at least one translation was rewritten.
159
+ */
160
+ emitCacheBust(articleId: string): Promise<void>
161
+
162
+ /**
163
+ * Returns the tenant's `mdx_schema_version_pin`, or `null` when no
164
+ * pin is set. The runner uses this to compute the effective target
165
+ * version (`min(targetVersion, pin)`).
166
+ */
167
+ getTenantPin(): Promise<string | null>
168
+ }
169
+
170
+ /**
171
+ * Aggregate counts emitted at the end of a runner invocation. The
172
+ * graphile-worker task (PR 4) forwards these to the operations
173
+ * dashboard / Prometheus metrics.
174
+ */
175
+ export interface RunMigrationsResult {
176
+ /** Total translations the runner saw in batches. */
177
+ translationsProcessed: number
178
+ /** Translations where at least one migration changed content. */
179
+ translationsMigrated: number
180
+ /** Translations where every applicable migration was a no-op. */
181
+ translationsSkipped: number
182
+ /** Translations that hit a transform throw / unrecoverable write conflict. */
183
+ translationsFailed: number
184
+ /** Distinct article ids whose embeddings + caches were invalidated. */
185
+ articlesInvalidated: Set<string>
186
+ /** Effective target version after pin clamping. */
187
+ effectiveTargetVersion: string
188
+ }