@growth-labs/cms 0.8.2 → 0.8.3

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 (77) hide show
  1. package/dist/engine/ai-dek-notifications.d.ts +2 -0
  2. package/dist/engine/ai-dek-notifications.d.ts.map +1 -1
  3. package/dist/engine/ai-dek-notifications.js +11 -2
  4. package/dist/engine/ai-dek-notifications.js.map +1 -1
  5. package/dist/engine/ai-dek.d.ts +23 -0
  6. package/dist/engine/ai-dek.d.ts.map +1 -1
  7. package/dist/engine/ai-dek.js +94 -31
  8. package/dist/engine/ai-dek.js.map +1 -1
  9. package/dist/engine/foundry-dispatch.d.ts +13 -3
  10. package/dist/engine/foundry-dispatch.d.ts.map +1 -1
  11. package/dist/engine/foundry-dispatch.js +80 -25
  12. package/dist/engine/foundry-dispatch.js.map +1 -1
  13. package/dist/engine/fronts-publish-intent.d.ts +55 -0
  14. package/dist/engine/fronts-publish-intent.d.ts.map +1 -1
  15. package/dist/engine/fronts-publish-intent.js +181 -55
  16. package/dist/engine/fronts-publish-intent.js.map +1 -1
  17. package/dist/engine/fronts-publish.d.ts +11 -0
  18. package/dist/engine/fronts-publish.d.ts.map +1 -1
  19. package/dist/engine/fronts-publish.js +106 -4
  20. package/dist/engine/fronts-publish.js.map +1 -1
  21. package/dist/engine/index.d.ts +1 -1
  22. package/dist/engine/index.d.ts.map +1 -1
  23. package/dist/engine/index.js +1 -1
  24. package/dist/engine/index.js.map +1 -1
  25. package/dist/engine/podcast-source.d.ts +3 -2
  26. package/dist/engine/podcast-source.d.ts.map +1 -1
  27. package/dist/engine/podcast-source.js +6 -4
  28. package/dist/engine/podcast-source.js.map +1 -1
  29. package/dist/engine/publisher.d.ts.map +1 -1
  30. package/dist/engine/publisher.js +16 -8
  31. package/dist/engine/publisher.js.map +1 -1
  32. package/dist/engine/soft-delete.d.ts +3 -1
  33. package/dist/engine/soft-delete.d.ts.map +1 -1
  34. package/dist/engine/soft-delete.js +21 -5
  35. package/dist/engine/soft-delete.js.map +1 -1
  36. package/dist/engine/video-source.d.ts +4 -2
  37. package/dist/engine/video-source.d.ts.map +1 -1
  38. package/dist/engine/video-source.js +7 -4
  39. package/dist/engine/video-source.js.map +1 -1
  40. package/dist/routes/content.d.ts +14 -0
  41. package/dist/routes/content.d.ts.map +1 -1
  42. package/dist/routes/content.js +37 -24
  43. package/dist/routes/content.js.map +1 -1
  44. package/dist/routes/context.d.ts +6 -0
  45. package/dist/routes/context.d.ts.map +1 -1
  46. package/dist/routes/context.js.map +1 -1
  47. package/dist/routes/fronts-publish.d.ts +2 -0
  48. package/dist/routes/fronts-publish.d.ts.map +1 -1
  49. package/dist/routes/fronts-publish.js +178 -2
  50. package/dist/routes/fronts-publish.js.map +1 -1
  51. package/dist/ui/api/_content-config.d.ts.map +1 -1
  52. package/dist/ui/api/_content-config.js +7 -0
  53. package/dist/ui/api/_content-config.js.map +1 -1
  54. package/dist/ui/api/fronts/schedule.d.ts +2 -0
  55. package/dist/ui/api/fronts/schedule.d.ts.map +1 -1
  56. package/dist/ui/api/fronts/schedule.js +2 -0
  57. package/dist/ui/api/fronts/schedule.js.map +1 -1
  58. package/dist/ui/editor/ContentForm.d.ts.map +1 -1
  59. package/dist/ui/editor/ContentForm.js +2 -2
  60. package/dist/ui/editor/ContentForm.js.map +1 -1
  61. package/package.json +1 -1
  62. package/src/engine/ai-dek-notifications.ts +19 -2
  63. package/src/engine/ai-dek.ts +131 -40
  64. package/src/engine/foundry-dispatch.ts +110 -24
  65. package/src/engine/fronts-publish-intent.ts +289 -65
  66. package/src/engine/fronts-publish.ts +121 -4
  67. package/src/engine/index.ts +1 -0
  68. package/src/engine/podcast-source.ts +6 -4
  69. package/src/engine/publisher.ts +20 -8
  70. package/src/engine/soft-delete.ts +28 -8
  71. package/src/engine/video-source.ts +7 -4
  72. package/src/routes/content.ts +56 -31
  73. package/src/routes/context.ts +6 -0
  74. package/src/routes/fronts-publish.ts +213 -2
  75. package/src/ui/api/_content-config.ts +15 -0
  76. package/src/ui/api/fronts/schedule.ts +4 -0
  77. package/src/ui/editor/ContentForm.tsx +4 -5
@@ -793,7 +793,10 @@ export async function updateContentItem(
793
793
  // Resolve all media identity/duration invariants before the base content row,
794
794
  // tags, or relations can be mutated. D1 does not provide a transaction on the
795
795
  // structural surface used here, so validation must be a strict preflight.
796
- if (input.content && existing.type === 'video') {
796
+ if (
797
+ (input.content || input.slug !== undefined || input.visibility !== undefined) &&
798
+ existing.type === 'video'
799
+ ) {
797
800
  const current = await db
798
801
  .prepare(
799
802
  `SELECT script, video_id, duration_seconds, thumbnail_image_id,
@@ -813,7 +816,7 @@ export async function updateContentItem(
813
816
  }>()
814
817
 
815
818
  if (current) {
816
- const videoContent = input.content as Partial<VideoInput['content']>
819
+ const videoContent = (input.content ?? {}) as Partial<VideoInput['content']>
817
820
  const sourceUrl = hasOwn(videoContent, 'processingSourceUrl')
818
821
  ? (videoContent.processingSourceUrl ?? null)
819
822
  : current.processing_source_url
@@ -851,14 +854,19 @@ export async function updateContentItem(
851
854
  : current.thumbnail_image_id,
852
855
  sourceUrl,
853
856
  sourceKind,
854
- sourceChanged,
857
+ sourceChanged:
858
+ sourceChanged ||
859
+ resolvedDuration !== current.duration_seconds ||
860
+ (input.slug !== undefined && input.slug !== existing.slug) ||
861
+ (input.visibility !== undefined && input.visibility !== existing.visibility) ||
862
+ (hasOwn(videoContent, 'videoId') && videoContent.videoId !== current.video_id),
855
863
  }
856
864
  } else {
857
865
  videoUpdatePlan = null
858
866
  }
859
867
  }
860
868
 
861
- if (input.content && existing.type === 'podcast') {
869
+ if ((input.content || input.slug !== undefined) && existing.type === 'podcast') {
862
870
  const current = await db
863
871
  .prepare(
864
872
  `SELECT transcript, audio_r2_key, duration_seconds, processing_trigger_token,
@@ -878,7 +886,7 @@ export async function updateContentItem(
878
886
  }>()
879
887
 
880
888
  if (current) {
881
- const podcastContent = input.content as Partial<PodcastInput['content']>
889
+ const podcastContent = (input.content ?? {}) as Partial<PodcastInput['content']>
882
890
  const audioR2Key = hasOwn(podcastContent, 'audioR2Key')
883
891
  ? (podcastContent.audioR2Key ?? current.audio_r2_key)
884
892
  : current.audio_r2_key
@@ -910,9 +918,13 @@ export async function updateContentItem(
910
918
  )
911
919
  const replacementTranscriptProvided =
912
920
  hasOwn(podcastContent, 'transcript') && typeof podcastContent.transcript === 'string'
921
+ const preparationChanged =
922
+ sourceChanged ||
923
+ resolvedDuration !== current.duration_seconds ||
924
+ (input.slug !== undefined && input.slug !== existing.slug)
913
925
 
914
926
  podcastUpdatePlan = {
915
- transcript: sourceChanged
927
+ transcript: preparationChanged
916
928
  ? replacementTranscriptProvided
917
929
  ? (podcastContent.transcript as string)
918
930
  : ''
@@ -924,7 +936,7 @@ export async function updateContentItem(
924
936
  durationProvided || sourceChanged
925
937
  ? resolvedDuration
926
938
  : (resolvedDuration ?? current.duration_seconds),
927
- processingTriggerToken: sourceChanged ? null : current.processing_trigger_token,
939
+ processingTriggerToken: preparationChanged ? null : current.processing_trigger_token,
928
940
  sourceUrl,
929
941
  sourceKind,
930
942
  }
@@ -1196,7 +1208,7 @@ export async function updateContentItem(
1196
1208
  }
1197
1209
  if (!options.expectedMediaSource) await updateBaseContent()
1198
1210
 
1199
- if (input.content) {
1211
+ if (input.content || videoUpdatePlan || podcastUpdatePlan) {
1200
1212
  if (isBodyBackedContentType(existing.type)) {
1201
1213
  const current = await db
1202
1214
  .prepare(
@@ -1,4 +1,21 @@
1
- import type { D1Database } from './d1.js'
1
+ import type { D1Database, D1PreparedStatement } from './d1.js'
2
+
3
+ /** V2 metadata-stable captures must not survive an invalidating lifecycle transition. */
4
+ export function invalidateMediaCaptureStatements(
5
+ db: D1Database,
6
+ id: string,
7
+ ): D1PreparedStatement[] {
8
+ return [
9
+ db
10
+ .prepare(`UPDATE video_content SET processing_trigger_token = NULL, processing_correlation_id = NULL
11
+ WHERE content_id = ? AND processing_trigger_token LIKE 'fronts-source-v2:%'`)
12
+ .bind(id),
13
+ db
14
+ .prepare(`UPDATE podcast_content SET processing_trigger_token = NULL
15
+ WHERE content_id = ? AND processing_trigger_token LIKE 'fronts-source-v2:%'`)
16
+ .bind(id),
17
+ ]
18
+ }
2
19
 
3
20
  export async function softDeleteContent(
4
21
  db: D1Database,
@@ -6,13 +23,16 @@ export async function softDeleteContent(
6
23
  now?: number,
7
24
  ): Promise<boolean> {
8
25
  const ts = now ?? Math.floor(Date.now() / 1000)
9
- const res = await db
10
- .prepare(
11
- 'UPDATE content_items SET deleted_at = ?, updated_at = unixepoch(), canonical_version = canonical_version + 1 WHERE id = ? AND deleted_at IS NULL',
12
- )
13
- .bind(ts, id)
14
- .run()
15
- return Boolean(res.meta && (res.meta as { changes?: number }).changes)
26
+ const results = await db.batch([
27
+ ...invalidateMediaCaptureStatements(db, id),
28
+ db
29
+ .prepare(
30
+ 'UPDATE content_items SET deleted_at = ?, updated_at = unixepoch(), canonical_version = canonical_version + 1 WHERE id = ? AND deleted_at IS NULL',
31
+ )
32
+ .bind(ts, id),
33
+ ])
34
+ const res = results[2]
35
+ return Boolean(res?.meta && (res.meta as { changes?: number }).changes)
16
36
  }
17
37
 
18
38
  export async function restoreContent(db: D1Database, id: string): Promise<boolean> {
@@ -9,8 +9,10 @@ export interface FrontsVideoSourceSnapshot {
9
9
  }
10
10
 
11
11
  /**
12
- * Stable over polling, machine media callbacks and rescheduling; canonical
13
- * editor/source changes invalidate the old production. The raw trigger token
12
+ * V1 captures retain their original canonical-version binding. New v2 capture
13
+ * tokens separate media identity from editorial revisions: a title/body edit
14
+ * or reschedule cannot cancel useful media work. Slug/source/token changes
15
+ * still change the generation. The raw trigger token
14
16
  * and URL never need to appear in callback or notification identities. The
15
17
  * Go consumer's contract is `fronts-video-source.v1` (foundry
16
18
  * `publishplane/masthead/videosource.schema.json`, exported by
@@ -19,12 +21,13 @@ export interface FrontsVideoSourceSnapshot {
19
21
  export async function frontsVideoSourceGeneration(
20
22
  input: FrontsVideoSourceSnapshot,
21
23
  ): Promise<string> {
24
+ const version = input.processing_trigger_token?.startsWith('fronts-source-v2:') ? 2 : 1
22
25
  const bytes = new TextEncoder().encode(
23
26
  JSON.stringify([
24
- 'fronts-video-source.v1',
27
+ `fronts-video-source.v${version}`,
25
28
  input.content_id,
26
29
  input.slug,
27
- input.canonical_version,
30
+ ...(version === 1 ? [input.canonical_version] : []),
28
31
  input.processing_source_url,
29
32
  input.processing_source_kind,
30
33
  input.processing_trigger_token,
@@ -33,6 +33,10 @@ import {
33
33
  type ProcessingState,
34
34
  verifyHmac,
35
35
  } from '../engine/foundry-dispatch.js'
36
+ import {
37
+ parseFrontsDefaultChannelTargets,
38
+ setFrontsChannelTargets,
39
+ } from '../engine/fronts-publish-intent.js'
36
40
  import { evaluateArticleBody } from '../engine/publish-guard.js'
37
41
  import {
38
42
  createContent,
@@ -55,7 +59,7 @@ import {
55
59
  restoreRevision,
56
60
  } from '../engine/revisions.js'
57
61
  import { applySlugRenameRedirects } from '../engine/slug-redirects.js'
58
- import { softDeleteContent } from '../engine/soft-delete.js'
62
+ import { invalidateMediaCaptureStatements, softDeleteContent } from '../engine/soft-delete.js'
59
63
  import { normalizeSourceSections } from '../engine/source-sections.js'
60
64
  import { TagInputError } from '../engine/taxonomy.js'
61
65
  import type { ValidationError } from '../engine/validator/index.js'
@@ -190,7 +194,23 @@ export type PublishReadinessHook = (input: {
190
194
  status: string
191
195
  }) => Promise<PublishReadinessOutcome>
192
196
 
197
+ export type FrontsScheduleMaintenanceOperation =
198
+ | 'recover-video-sources'
199
+ | 'reconcile-article-enrichment'
200
+
201
+ /** Host-owned bounded recovery/repair work invoked by the signed Fronts schedule route. */
202
+ export type FrontsScheduleMaintenanceHook = (input: {
203
+ ctx: RouteContext
204
+ operation: FrontsScheduleMaintenanceOperation
205
+ limit: 3 | 5
206
+ signal: AbortSignal
207
+ }) => Promise<{ contentIds: string[] }>
208
+
193
209
  export interface ContentRouteConfig extends CmsRouteConfig {
210
+ /** Host-configured publish destinations; only absent stored targets are armed. No global default. */
211
+ frontsDefaultChannelTargets?: readonly string[]
212
+ /** Optional host-owned bounded recovery/repair hook for the signed schedule POST. */
213
+ frontsScheduleMaintenance?: FrontsScheduleMaintenanceHook
194
214
  /** Optional Foundry takeaways dispatcher (bead 08). Omit to disable. */
195
215
  dispatchTakeaways?: DispatchTakeawaysHook
196
216
  /** Optional FAQ enrichment dispatcher (P4 Task 7). Omit to disable. */
@@ -836,6 +856,17 @@ export function createContentRoutes(config: ContentRouteConfig): ContentRouteHan
836
856
  const dispatchWebhook = config.dispatchWebhook
837
857
  const publishReadiness = config.publishReadiness
838
858
  const activeWorkspaceId = config.activeWorkspaceId ?? 'default'
859
+ const targetDefaults =
860
+ config.frontsDefaultChannelTargets === undefined
861
+ ? null
862
+ : parseFrontsDefaultChannelTargets(config.frontsDefaultChannelTargets)
863
+ const defaultTargetsError = () =>
864
+ targetDefaults && 'error' in targetDefaults ? json({ error: targetDefaults.error }, 500) : null
865
+ async function armDefaultTargets(ctx: RouteContext, contentId: string): Promise<void> {
866
+ if (targetDefaults && 'targets' in targetDefaults) {
867
+ await setFrontsChannelTargets(ctx.db, contentId, targetDefaults.targets, { onlyIfNull: true })
868
+ }
869
+ }
839
870
 
840
871
  async function loadStoredMediaSource(
841
872
  db: D1Database,
@@ -1305,6 +1336,8 @@ export function createContentRoutes(config: ContentRouteConfig): ContentRouteHan
1305
1336
  }
1306
1337
 
1307
1338
  if (op === 'schedule') {
1339
+ const configError = defaultTargetsError()
1340
+ if (configError) return configError
1308
1341
  const { publishAt } = parsed.data
1309
1342
  const publishAtMs = Date.parse(publishAt)
1310
1343
  if (!Number.isFinite(publishAtMs)) {
@@ -1313,6 +1346,7 @@ export function createContentRoutes(config: ContentRouteConfig): ContentRouteHan
1313
1346
  const publishAtSeconds = Math.floor(publishAtMs / 1000)
1314
1347
  for (const id of ids) {
1315
1348
  await scheduleContent(ctx.db, id, publishAtSeconds)
1349
+ await armDefaultTargets(ctx, id)
1316
1350
  }
1317
1351
  return json({ scheduled: ids })
1318
1352
  }
@@ -1329,6 +1363,8 @@ export function createContentRoutes(config: ContentRouteConfig): ContentRouteHan
1329
1363
  const ownAuthor = actor?.subject ?? ctx.userId ?? null
1330
1364
  const denied = await requireContentAction(ctx, 'write', ownAuthor)
1331
1365
  if (denied) return denied
1366
+ const configError = defaultTargetsError()
1367
+ if (configError) return configError
1332
1368
 
1333
1369
  const parsed = CreateSchema.safeParse(await readJson(ctx))
1334
1370
  if (!parsed.success) {
@@ -1360,6 +1396,7 @@ export function createContentRoutes(config: ContentRouteConfig): ContentRouteHan
1360
1396
  if (conflict) return conflict
1361
1397
  throw error
1362
1398
  }
1399
+ await armDefaultTargets(ctx, created.id)
1363
1400
  const podcastAttempt: PodcastFoundryAttempt =
1364
1401
  parsed.data.type === 'podcast'
1365
1402
  ? await dispatchPodcastAfterSave(ctx, created.id)
@@ -1484,6 +1521,8 @@ export function createContentRoutes(config: ContentRouteConfig): ContentRouteHan
1484
1521
  if (config.updateStatusConstraint && existing.status !== config.updateStatusConstraint) {
1485
1522
  return json({ error: 'update_status_conflict', state: existing.status }, 409)
1486
1523
  }
1524
+ const configError = defaultTargetsError()
1525
+ if (configError) return configError
1487
1526
 
1488
1527
  const parsed = UpdateSchema.safeParse(await readJson(ctx))
1489
1528
  if (!parsed.success) {
@@ -1607,6 +1646,7 @@ export function createContentRoutes(config: ContentRouteConfig): ContentRouteHan
1607
1646
  if (updated.mediaSourceConflict) {
1608
1647
  return json({ error: 'media_source_conflict' }, 409)
1609
1648
  }
1649
+ await armDefaultTargets(ctx, id)
1610
1650
  const podcastAttempt: PodcastFoundryAttempt =
1611
1651
  existing.type === 'podcast'
1612
1652
  ? await dispatchPodcastAfterSave(ctx, id)
@@ -1649,6 +1689,8 @@ export function createContentRoutes(config: ContentRouteConfig): ContentRouteHan
1649
1689
  if (denied) return denied
1650
1690
 
1651
1691
  if (action === 'schedule') {
1692
+ const configError = defaultTargetsError()
1693
+ if (configError) return configError
1652
1694
  const parsed = ScheduleSchema.safeParse(await readJson(ctx))
1653
1695
  if (!parsed.success) {
1654
1696
  return json({ error: 'Invalid request', details: parsed.error.flatten() }, 400)
@@ -1680,6 +1722,7 @@ export function createContentRoutes(config: ContentRouteConfig): ContentRouteHan
1680
1722
  }
1681
1723
 
1682
1724
  await scheduleContent(ctx.db, id, publishAtSeconds as number, publishTimeZone)
1725
+ await armDefaultTargets(ctx, id)
1683
1726
 
1684
1727
  // Fire content.scheduled webhook.
1685
1728
  await fireWebhook(ctx, 'content.scheduled', {
@@ -1895,12 +1938,14 @@ export function createContentRoutes(config: ContentRouteConfig): ContentRouteHan
1895
1938
  }
1896
1939
 
1897
1940
  if (action === 'archive') {
1898
- await ctx.db
1899
- .prepare(
1900
- "UPDATE content_items SET status = 'archived', updated_at = unixepoch(), canonical_version = canonical_version + 1 WHERE id = ? AND status <> 'archived'",
1901
- )
1902
- .bind(id)
1903
- .run()
1941
+ await ctx.db.batch([
1942
+ ...invalidateMediaCaptureStatements(ctx.db, id),
1943
+ ctx.db
1944
+ .prepare(
1945
+ "UPDATE content_items SET status = 'archived', updated_at = unixepoch(), canonical_version = canonical_version + 1 WHERE id = ? AND status <> 'archived'",
1946
+ )
1947
+ .bind(id),
1948
+ ])
1904
1949
 
1905
1950
  // Fire content.deleted (archive = soft delete lifecycle) webhook.
1906
1951
  await fireWebhook(ctx, 'content.deleted', {
@@ -2005,36 +2050,16 @@ export function createContentRoutes(config: ContentRouteConfig): ContentRouteHan
2005
2050
  if (!resolved.hooks.foundryVideo) {
2006
2051
  return json({ error: 'Foundry video dispatch is not configured' }, 501)
2007
2052
  }
2008
- if (existing.type === 'podcast') {
2009
- const row = await ctx.db
2010
- .prepare(
2011
- `SELECT processing_trigger_token
2012
- FROM podcast_content
2013
- WHERE content_id = ?
2014
- LIMIT 1`,
2015
- )
2016
- .bind(id)
2017
- .first<{ processing_trigger_token: string | null }>()
2018
- const existingToken = row?.processing_trigger_token?.trim() ?? ''
2019
- if (existingToken) {
2020
- return json(
2021
- {
2022
- status: 'queued',
2023
- correlationId: null,
2024
- triggerToken: existingToken,
2025
- skipped: true,
2026
- },
2027
- 202,
2028
- )
2029
- }
2030
- }
2031
2053
  try {
2032
- const result = await dispatchToFoundry(ctx.db, id, resolved.hooks.foundryVideo)
2054
+ const result = await dispatchToFoundry(ctx.db, id, resolved.hooks.foundryVideo, {
2055
+ ifUncaptured: url.searchParams.get('capture') === '1',
2056
+ })
2033
2057
  return json(
2034
2058
  {
2035
2059
  status: 'queued',
2036
2060
  correlationId: result.correlationId,
2037
2061
  triggerToken: result.triggerToken,
2062
+ ...(result.skipped ? { skipped: true } : {}),
2038
2063
  },
2039
2064
  202,
2040
2065
  )
@@ -119,6 +119,12 @@ export interface Authz {
119
119
  export interface RouteContext {
120
120
  /** The inbound request (standard Fetch `Request`). */
121
121
  request: Request
122
+ /**
123
+ * Host-supplied execution-lifetime bridge. Maintenance-capable adapters
124
+ * provide this so abort cleanup can settle after the HTTP response; adapters
125
+ * must bind methods that depend on their original receiver.
126
+ */
127
+ waitUntil?: (promise: Promise<unknown>) => void
122
128
  /** Route params (e.g. `{ id }` for `/content/[id]`). */
123
129
  params: Record<string, string | undefined>
124
130
  /** The site's D1 binding. */
@@ -2,6 +2,7 @@
2
2
  // the out-of-process Fronts publish worker (foundryd) drives:
3
3
  //
4
4
  // GET /admin/api/fronts/schedule?window=<from>..<to> — the poll surface.
5
+ // POST /admin/api/fronts/schedule — bounded schedule maintenance.
5
6
  // POST /admin/api/fronts/publish-callback — the callback receiver.
6
7
  //
7
8
  // AUTH reuses the existing M2M primitive (`verifyHmac` + `X-Foundry-Signature`
@@ -18,11 +19,12 @@
18
19
  // CONSTANT — so one captured URL+header pair would be a permanent bearer
19
20
  // credential for the pre-publication embargo schedule.
20
21
  //
21
- // Both endpoints ship ENABLED behind FRONTS_PUBLISH_ENABLED (a rollback lever,
22
+ // The endpoints ship ENABLED behind FRONTS_PUBLISH_ENABLED (a rollback lever,
22
23
  // default ON). Failures are loud: bad/stale HMAC → 401 + warn log; a `live`
23
24
  // callback that cannot commit through the ledger → 500 + error log; disabled → 503.
24
25
 
25
26
  import { z } from 'zod'
27
+ import { createDekFailureNotifications } from '../engine/ai-dek-notifications.js'
26
28
  import { verifyHmac } from '../engine/foundry-dispatch.js'
27
29
  import {
28
30
  applyFrontsPublishCallback,
@@ -30,12 +32,19 @@ import {
30
32
  listFrontsPublishSchedule,
31
33
  } from '../engine/fronts-publish.js'
32
34
  import {
35
+ backfillFrontsChannelTargets,
33
36
  FrontsScheduleOverflowError,
37
+ hydrateFrontsMediaPreparations,
34
38
  hydrateFrontsPublishIntents,
39
+ parseFrontsDefaultChannelTargets,
35
40
  } from '../engine/fronts-publish-intent.js'
36
41
  import { publicUrlFor } from '../ui/screens/public-url.js'
37
42
  import { resolveConfig } from './config.js'
38
- import type { ContentRouteConfig } from './content.js'
43
+ import type {
44
+ ContentRouteConfig,
45
+ FrontsScheduleMaintenanceHook,
46
+ FrontsScheduleMaintenanceOperation,
47
+ } from './content.js'
39
48
  import { json, type RouteContext } from './context.js'
40
49
 
41
50
  /**
@@ -130,9 +139,92 @@ const CallbackSchema = z
130
139
  })
131
140
  .strip()
132
141
 
142
+ const ArmChannelTargetsSchema = z
143
+ .object({
144
+ operation: z.literal('arm-channel-targets'),
145
+ limit: z.number().int().min(1).max(50).default(50),
146
+ })
147
+ .strict()
148
+
149
+ const FrontsScheduleMaintenanceSchema = z.union([
150
+ z
151
+ .object({
152
+ operation: z.literal('recover-video-sources'),
153
+ limit: z.literal(3).default(3),
154
+ })
155
+ .strict(),
156
+ z
157
+ .object({
158
+ operation: z.literal('reconcile-article-enrichment'),
159
+ limit: z.literal(5).default(5),
160
+ })
161
+ .strict(),
162
+ ])
163
+
164
+ const FRONTS_SCHEDULE_MAINTENANCE_TIMEOUT_MS = 25_000
165
+
166
+ class FrontsScheduleMaintenanceTimeoutError extends Error {}
167
+
168
+ function isMaintenanceOperation(value: unknown): value is FrontsScheduleMaintenanceOperation {
169
+ return value === 'recover-video-sources' || value === 'reconcile-article-enrichment'
170
+ }
171
+
172
+ function validateMaintenanceResult(result: unknown, limit: 3 | 5): { contentIds: string[] } | null {
173
+ const parsed = z
174
+ .object({
175
+ contentIds: z.array(z.string().refine((id) => id.trim().length > 0)).max(limit),
176
+ })
177
+ .strict()
178
+ .safeParse(result)
179
+ if (!parsed.success || new Set(parsed.data.contentIds).size !== parsed.data.contentIds.length)
180
+ return null
181
+ return parsed.data
182
+ }
183
+
184
+ async function runScheduleMaintenance(
185
+ ctx: RouteContext,
186
+ hook: FrontsScheduleMaintenanceHook,
187
+ operation: FrontsScheduleMaintenanceOperation,
188
+ limit: 3 | 5,
189
+ ): Promise<{ contentIds: string[] }> {
190
+ const controller = new AbortController()
191
+ let rejectDeadline: (error: FrontsScheduleMaintenanceTimeoutError) => void = () => undefined
192
+ let deadlineReached = false
193
+ const deadline = new Promise<never>((_resolve, reject) => {
194
+ rejectDeadline = reject
195
+ })
196
+ const abort = () => {
197
+ if (deadlineReached) return
198
+ deadlineReached = true
199
+ rejectDeadline(new FrontsScheduleMaintenanceTimeoutError())
200
+ controller.abort()
201
+ }
202
+ if (ctx.request.signal.aborted) abort()
203
+ else ctx.request.signal.addEventListener('abort', abort, { once: true })
204
+ const timer = setTimeout(abort, FRONTS_SCHEDULE_MAINTENANCE_TIMEOUT_MS)
205
+ const work = Promise.resolve().then(() =>
206
+ hook({ ctx, operation, limit, signal: controller.signal }),
207
+ )
208
+ // Keep the already-running hook alive through abort cleanup while observing
209
+ // either settlement so a late private rejection cannot escape the runtime.
210
+ const observedWork = work.then(
211
+ () => undefined,
212
+ () => undefined,
213
+ )
214
+ ctx.waitUntil?.(observedWork)
215
+ try {
216
+ return await Promise.race([work, deadline])
217
+ } finally {
218
+ clearTimeout(timer)
219
+ ctx.request.signal.removeEventListener('abort', abort)
220
+ }
221
+ }
222
+
133
223
  export interface FrontsPublishRouteHandlers {
134
224
  /** GET /fronts/schedule?window=<from>..<to> — items due for foundryd to publish. */
135
225
  schedule(ctx: RouteContext): Promise<Response>
226
+ /** POST /fronts/schedule — bounded target arming or host-owned maintenance. */
227
+ maintainSchedule(ctx: RouteContext): Promise<Response>
136
228
  /** POST /fronts/publish-callback — foundryd's outbound lifecycle callback. */
137
229
  publishCallback(ctx: RouteContext): Promise<Response>
138
230
  }
@@ -164,6 +256,90 @@ function parseWindow(
164
256
  export function createFrontsPublishRoutes(config: ContentRouteConfig): FrontsPublishRouteHandlers {
165
257
  const resolved = resolveConfig(config)
166
258
  return {
259
+ async maintainSchedule(ctx) {
260
+ let responseOperation: 'arm-channel-targets' | FrontsScheduleMaintenanceOperation =
261
+ 'arm-channel-targets'
262
+ const respond = (body: Record<string, unknown>, status = 200) =>
263
+ json({ version: 1, operation: responseOperation, ...body }, status)
264
+ const hmacSecret = await resolveFoundryHmacSecret(ctx.env)
265
+ if (!hmacSecret)
266
+ return respond({ ok: false, error: 'foundry_hmac_secret_not_configured' }, 500)
267
+ let rawBody: string
268
+ try {
269
+ rawBody = await ctx.request.text()
270
+ } catch {
271
+ return respond({ ok: false, error: 'invalid_channel_targets_request' }, 400)
272
+ }
273
+ const denied = await verifyFoundrySignedRequest(
274
+ ctx.request,
275
+ hmacSecret,
276
+ rawBody,
277
+ 'fronts/schedule.arm-channel-targets',
278
+ )
279
+ if (denied) return respond({ ok: false, error: 'invalid_foundry_signature' }, denied.status)
280
+ if (!isFrontsPublishEnabled(ctx.env))
281
+ return respond({ ok: false, error: 'fronts_publish_disabled' }, 503)
282
+ let raw: unknown
283
+ try {
284
+ raw = JSON.parse(rawBody)
285
+ } catch {
286
+ return respond({ ok: false, error: 'invalid_channel_targets_request' }, 400)
287
+ }
288
+ const rawOperation =
289
+ typeof raw === 'object' && raw !== null && 'operation' in raw
290
+ ? (raw as { operation?: unknown }).operation
291
+ : undefined
292
+ if (isMaintenanceOperation(rawOperation)) {
293
+ responseOperation = rawOperation
294
+ const parsed = FrontsScheduleMaintenanceSchema.safeParse(raw)
295
+ if (!parsed.success)
296
+ return respond({ ok: false, error: 'invalid_fronts_schedule_maintenance_request' }, 400)
297
+ if (!config.frontsScheduleMaintenance)
298
+ return respond({ ok: false, error: 'fronts_schedule_maintenance_unconfigured' }, 503)
299
+ try {
300
+ const rawResult = await runScheduleMaintenance(
301
+ ctx,
302
+ config.frontsScheduleMaintenance,
303
+ parsed.data.operation,
304
+ parsed.data.limit,
305
+ )
306
+ const result = validateMaintenanceResult(rawResult, parsed.data.limit)
307
+ if (!result)
308
+ return respond({ ok: false, error: 'fronts_schedule_maintenance_invalid_result' }, 500)
309
+ return respond({
310
+ ok: true,
311
+ limit: parsed.data.limit,
312
+ completed: result.contentIds.length,
313
+ contentIds: result.contentIds,
314
+ })
315
+ } catch (error) {
316
+ if (error instanceof FrontsScheduleMaintenanceTimeoutError)
317
+ return respond({ ok: false, error: 'fronts_schedule_maintenance_timeout' }, 503)
318
+ console.error('[cms] fronts/schedule host maintenance failed')
319
+ return respond({ ok: false, error: 'fronts_schedule_maintenance_failed' }, 500)
320
+ }
321
+ }
322
+ const parsed = ArmChannelTargetsSchema.safeParse(raw)
323
+ if (!parsed.success)
324
+ return respond({ ok: false, error: 'invalid_channel_targets_request' }, 400)
325
+ const defaults = parseFrontsDefaultChannelTargets(config.frontsDefaultChannelTargets)
326
+ if ('error' in defaults)
327
+ return respond(
328
+ { ok: false, error: defaults.error },
329
+ defaults.error === 'missing_fronts_default_channel_targets' ? 503 : 500,
330
+ )
331
+ try {
332
+ const result = await backfillFrontsChannelTargets(
333
+ ctx.db,
334
+ defaults.targets,
335
+ parsed.data.limit,
336
+ )
337
+ return respond({ ok: true, limit: parsed.data.limit, ...result })
338
+ } catch (error) {
339
+ console.error('[cms] fronts/schedule target arming failed', error)
340
+ return respond({ ok: false, error: 'fronts_channel_targets_backfill_failed' }, 500)
341
+ }
342
+ },
167
343
  async schedule(ctx) {
168
344
  const hmacSecret = await resolveFoundryHmacSecret(ctx.env)
169
345
  if (!hmacSecret) return json({ error: 'FOUNDRY_HMAC_SECRET is not configured' }, 500)
@@ -210,6 +386,10 @@ export function createFrontsPublishRoutes(config: ContentRouteConfig): FrontsPub
210
386
  // origin is deliberately deferred (packages-docs/cms.md).
211
387
  resolveContentUrl: (row) => publicUrlFor(row),
212
388
  })
389
+ const preparations = await hydrateFrontsMediaPreparations(ctx.db, {
390
+ podcastSourceProductionEnabled: config.podcastSourceProductionEnabled,
391
+ videoSourceProductionEnabled: config.videoSourceProductionEnabled,
392
+ })
213
393
  return json({
214
394
  ok: true,
215
395
  now,
@@ -218,6 +398,7 @@ export function createFrontsPublishRoutes(config: ContentRouteConfig): FrontsPub
218
398
  items,
219
399
  intents: hydrated.intents,
220
400
  incomplete: hydrated.incomplete,
401
+ preparations,
221
402
  })
222
403
  } catch (error) {
223
404
  if (error instanceof FrontsScheduleOverflowError) {
@@ -279,6 +460,7 @@ export function createFrontsPublishRoutes(config: ContentRouteConfig): FrontsPub
279
460
  occurredAt: parsed.data.occurred_at ?? null,
280
461
  receipt: parsed.data.receipt ?? null,
281
462
  error: parsed.data.error ?? null,
463
+ llm: resolved.hooks.llm,
282
464
  checkReadiness: config.publishReadiness
283
465
  ? (item) =>
284
466
  config.publishReadiness!({
@@ -323,6 +505,35 @@ export function createFrontsPublishRoutes(config: ContentRouteConfig): FrontsPub
323
505
  500,
324
506
  )
325
507
  }
508
+ const newlyPublished =
509
+ result.ok && result.published && !result.deduped && result.attemptId !== null
510
+ if (newlyPublished && result.publishedItem) {
511
+ if (result.dekFailureReason) {
512
+ try {
513
+ await createDekFailureNotifications({
514
+ db: ctx.db,
515
+ workspaceId: config.activeWorkspaceId ?? 'default',
516
+ contentId: result.publishedItem.id,
517
+ title: result.publishedItem.title,
518
+ reason: result.dekFailureReason,
519
+ occurrenceId: `${eventId}:${result.attemptId}`,
520
+ })
521
+ } catch {
522
+ console.error('[cms] failed to create post-publication dek notification')
523
+ }
524
+ }
525
+ if (config.dispatchWebhook) {
526
+ try {
527
+ await config.dispatchWebhook(ctx, {
528
+ eventType: 'content.published',
529
+ workspaceId: config.activeWorkspaceId ?? 'default',
530
+ data: result.publishedItem,
531
+ })
532
+ } catch {
533
+ console.error('[cms] content.published webhook dispatch failed')
534
+ }
535
+ }
536
+ }
326
537
 
327
538
  return json({
328
539
  ok: true,