@openlup/platform 0.29.0 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/CHANGELOG.md +150 -138
  2. package/README.md +80 -3
  3. package/dist/composition/nodeHost.d.ts +1 -1
  4. package/dist/composition/nodeHost.js +3 -2
  5. package/dist/lifecycle/appUpgrade.d.ts +52 -0
  6. package/dist/lifecycle/appUpgrade.js +180 -0
  7. package/dist/lifecycle/index.d.ts +2 -0
  8. package/dist/lifecycle/index.js +2 -0
  9. package/dist/lifecycle/postgresInstallQualification.d.ts +51 -0
  10. package/dist/lifecycle/postgresInstallQualification.js +74 -0
  11. package/dist/migrations/postgresRunner.d.ts +9 -0
  12. package/dist/migrations/postgresRunner.js +17 -10
  13. package/dist/operations/adminAlertsSchemas.d.ts +153 -0
  14. package/dist/operations/adminAlertsSchemas.js +69 -0
  15. package/dist/operations/adminAlertsView.d.ts +73 -0
  16. package/dist/operations/adminAlertsView.js +184 -0
  17. package/dist/operations/alertPagingPolicy.d.ts +15 -0
  18. package/dist/operations/alertPagingPolicy.js +43 -0
  19. package/dist/operations/alertThrottlePolicy.d.ts +3 -0
  20. package/dist/operations/alertThrottlePolicy.js +18 -0
  21. package/dist/operations/clients.d.ts +17 -0
  22. package/dist/operations/clients.js +32 -0
  23. package/dist/operations/contracts/admin.d.ts +93 -0
  24. package/dist/operations/contracts/admin.js +1 -0
  25. package/dist/operations/contracts/adminAlertsContracts.d.ts +40 -0
  26. package/dist/operations/contracts/adminAlertsContracts.js +1 -0
  27. package/dist/operations/contracts/alertHumanContext.d.ts +7 -0
  28. package/dist/operations/contracts/alertHumanContext.js +1 -0
  29. package/dist/operations/contracts/index.d.ts +6 -0
  30. package/dist/operations/contracts/index.js +6 -0
  31. package/dist/operations/contracts/observabilityContracts.d.ts +41 -0
  32. package/dist/operations/contracts/observabilityContracts.js +1 -0
  33. package/dist/operations/contracts/observabilityPorts.d.ts +18 -0
  34. package/dist/operations/contracts/observabilityPorts.js +1 -0
  35. package/dist/operations/contracts/ports.d.ts +19 -0
  36. package/dist/operations/contracts/ports.js +1 -0
  37. package/dist/operations/errors.d.ts +6 -0
  38. package/dist/operations/errors.js +6 -0
  39. package/dist/operations/index.d.ts +9 -0
  40. package/dist/operations/index.js +9 -0
  41. package/dist/operations/schemas.d.ts +138 -0
  42. package/dist/operations/schemas.js +104 -0
  43. package/dist/operations/server/adminAlertsHandlers.d.ts +16 -0
  44. package/dist/operations/server/adminAlertsHandlers.js +35 -0
  45. package/dist/operations/server/adminPipelineHandlers.d.ts +12 -0
  46. package/dist/operations/server/adminPipelineHandlers.js +48 -0
  47. package/dist/operations/server/adminSettingsHandlers.d.ts +14 -0
  48. package/dist/operations/server/adminSettingsHandlers.js +82 -0
  49. package/dist/operations/server/controlPlaneHandler.d.ts +7 -0
  50. package/dist/operations/server/controlPlaneHandler.js +54 -0
  51. package/dist/operations/server/controlPlaneStore.d.ts +12 -0
  52. package/dist/operations/server/controlPlaneStore.js +138 -0
  53. package/dist/operations/server/controlPlaneWatchdog.d.ts +7 -0
  54. package/dist/operations/server/controlPlaneWatchdog.js +20 -0
  55. package/dist/operations/server/index.d.ts +12 -0
  56. package/dist/operations/server/index.js +12 -0
  57. package/dist/operations/server/migrations.d.ts +14 -0
  58. package/dist/operations/server/migrations.js +7 -0
  59. package/dist/operations/server/platformWatchdogDecision.d.ts +34 -0
  60. package/dist/operations/server/platformWatchdogDecision.js +71 -0
  61. package/dist/operations/server/platformWatchdogDeliveryPolicy.d.ts +10 -0
  62. package/dist/operations/server/platformWatchdogDeliveryPolicy.js +53 -0
  63. package/dist/operations/server/platformWatchdogQueue.d.ts +11 -0
  64. package/dist/operations/server/platformWatchdogQueue.js +94 -0
  65. package/dist/operations/server/platformWatchdogService.d.ts +47 -0
  66. package/dist/operations/server/platformWatchdogService.js +105 -0
  67. package/dist/operations/validation.d.ts +2 -0
  68. package/dist/operations/validation.js +3 -0
  69. package/dist/portability/filesystemObjects.d.ts +12 -0
  70. package/dist/portability/filesystemObjects.js +191 -0
  71. package/dist/portability/index.d.ts +5 -0
  72. package/dist/portability/index.js +4 -0
  73. package/dist/portability/objects.d.ts +63 -0
  74. package/dist/portability/objects.js +138 -0
  75. package/dist/portability/postgresRows.d.ts +64 -0
  76. package/dist/portability/postgresRows.js +182 -0
  77. package/dist/scheduler/advisoryLock.js +20 -2
  78. package/dist/scheduler/nodeScheduler.d.ts +2 -2
  79. package/dist/scheduler/nodeScheduler.js +35 -6
  80. package/package.json +27 -2
  81. package/release-gates.json +73 -7
  82. package/sql/20260814010000_platform_control_plane.sql +286 -0
  83. package/src/composition/nodeHost.ts +4 -3
  84. package/src/lifecycle/appUpgrade.ts +186 -0
  85. package/src/lifecycle/index.ts +19 -0
  86. package/src/lifecycle/postgresInstallQualification.ts +125 -0
  87. package/src/migrations/postgresRunner.ts +24 -9
  88. package/src/operations/adminAlertsSchemas.ts +78 -0
  89. package/src/operations/adminAlertsView.ts +238 -0
  90. package/src/operations/alertPagingPolicy.ts +50 -0
  91. package/src/operations/alertThrottlePolicy.ts +22 -0
  92. package/src/operations/clients.ts +44 -0
  93. package/src/operations/contracts/admin.ts +24 -0
  94. package/src/operations/contracts/adminAlertsContracts.ts +13 -0
  95. package/src/operations/contracts/alertHumanContext.ts +17 -0
  96. package/src/operations/contracts/index.ts +6 -0
  97. package/src/operations/contracts/observabilityContracts.ts +40 -0
  98. package/src/operations/contracts/observabilityPorts.ts +30 -0
  99. package/src/operations/contracts/ports.ts +22 -0
  100. package/src/operations/errors.ts +6 -0
  101. package/src/operations/index.ts +9 -0
  102. package/src/operations/schemas.ts +122 -0
  103. package/src/operations/server/adminAlertsHandlers.ts +61 -0
  104. package/src/operations/server/adminPipelineHandlers.ts +73 -0
  105. package/src/operations/server/adminSettingsHandlers.ts +114 -0
  106. package/src/operations/server/controlPlaneHandler.ts +56 -0
  107. package/src/operations/server/controlPlaneStore.ts +150 -0
  108. package/src/operations/server/controlPlaneWatchdog.ts +28 -0
  109. package/src/operations/server/index.ts +12 -0
  110. package/src/operations/server/migrations.ts +7 -0
  111. package/src/operations/server/platformWatchdogDecision.ts +93 -0
  112. package/src/operations/server/platformWatchdogDeliveryPolicy.ts +92 -0
  113. package/src/operations/server/platformWatchdogQueue.ts +96 -0
  114. package/src/operations/server/platformWatchdogService.ts +209 -0
  115. package/src/operations/validation.ts +3 -0
  116. package/src/portability/filesystemObjects.ts +138 -0
  117. package/src/portability/index.ts +12 -0
  118. package/src/portability/objects.ts +160 -0
  119. package/src/portability/postgresRows.ts +169 -0
  120. package/src/scheduler/advisoryLock.ts +20 -5
  121. package/src/scheduler/nodeScheduler.ts +28 -8
@@ -0,0 +1,73 @@
1
+ import type { AdminAlert, AdminAlertHealth, AdminAlertLane, AdminAlertSeverity, AdminAlertsHeartbeat, AdminAlertsOverviewResponse, AdminAlertsSummary } from "./contracts/adminAlertsContracts.js";
2
+ /**
3
+ * Pure projection of platform_alerts rows onto the admin shell's badges.
4
+ *
5
+ * All filtering lives here rather than in SQL so the `now` boundary is injectable
6
+ * and every rule is unit-testable without a database.
7
+ */
8
+ /** Raw ledger row as selected from public.platform_alerts. */
9
+ export type PlatformAlertLedgerRow = {
10
+ id: string;
11
+ dedupe_key: string;
12
+ owner: string;
13
+ severity: string;
14
+ status: string;
15
+ title: string;
16
+ message: string | null;
17
+ support_code: string | null;
18
+ runbook_url: string | null;
19
+ first_seen_at: string;
20
+ last_seen_at: string;
21
+ snoozed_until: string | null;
22
+ };
23
+ export type WatchdogHeartbeatRow = {
24
+ last_success_at: string | null;
25
+ } | null;
26
+ /**
27
+ * Generic scheduled-job alerts inherit `owner` from the job catalog entry, so a
28
+ * commerce-owned job leaks engineer-only noise ("this cron failed") into what
29
+ * should be an operator's queue. They still count toward platform health.
30
+ */
31
+ export declare const GENERIC_JOB_DEDUPE_PREFIXES: readonly ["job_failed:", "job_missed:", "job_never_succeeded:", "job_stuck_running:", "job_ledger_missing:"];
32
+ /**
33
+ * How old a watchdog heartbeat may be before the health pill stops trusting it.
34
+ *
35
+ * The development-preview reference uses a conservative six-hour stale window
36
+ * independent from any scheduler cadence. It is a policy default, not a
37
+ * scheduling SLA; adopters must review it against their expected maximum
38
+ * heartbeat delay and queue jitter.
39
+ */
40
+ export declare const WATCHDOG_STALE_AFTER_SECONDS: number;
41
+ export declare function isGenericJobAlert(dedupeKey: string): boolean;
42
+ /**
43
+ * Display bucket. `commerce` means "a business operator can act on this".
44
+ *
45
+ * `commerce/platform` is deliberately excluded: despite the prefix it owns
46
+ * engineering-run plumbing (outbox-dispatch, outbox-prune, abandoned-cart,
47
+ * review-request, reorder-reminder).
48
+ */
49
+ export declare function classifyLane(owner: string, dedupeKey: string): AdminAlertLane;
50
+ export declare function isSnoozed(snoozedUntil: string | null, now: Date): boolean;
51
+ /**
52
+ * Pageable means "this would wake someone up": live and above the paging floor.
53
+ * Acknowledged rows stay pageable on purpose — acknowledged is not resolved, the
54
+ * system is still broken.
55
+ */
56
+ export declare function isPageable(row: PlatformAlertLedgerRow, now: Date): boolean;
57
+ export declare function toAdminAlert(row: PlatformAlertLedgerRow, now: Date): AdminAlert;
58
+ export declare function worstSeverity(alerts: readonly AdminAlert[]): AdminAlertSeverity | null;
59
+ /**
60
+ * `commercePageableCount` and `platformPageableCount` partition the pageable set,
61
+ * so no alert that would page is ever invisible in the popover.
62
+ */
63
+ export declare function summarizeAlerts(alerts: readonly AdminAlert[]): AdminAlertsSummary;
64
+ export declare function buildHeartbeat(row: WatchdogHeartbeatRow, now: Date): AdminAlertsHeartbeat;
65
+ /**
66
+ * Staleness beats severity: if the watchdog has not reported recently we do not
67
+ * know the current state, and "unknown" is the only honest answer. There is no
68
+ * path here that renders a green "systems ok" from missing data.
69
+ */
70
+ export declare function deriveHealth(summary: AdminAlertsSummary, heartbeat: AdminAlertsHeartbeat): AdminAlertHealth;
71
+ /** Alerts returned to the client; counts above stay accurate even when this is truncated. */
72
+ export declare const ADMIN_ALERTS_LIST_LIMIT = 50;
73
+ export declare function buildAlertsOverview(rows: readonly PlatformAlertLedgerRow[], heartbeatRow: WatchdogHeartbeatRow, now: Date): AdminAlertsOverviewResponse;
@@ -0,0 +1,184 @@
1
+ import { DEFAULT_PAGING_MIN_SEVERITY, shouldPage } from "./alertPagingPolicy.js";
2
+ /**
3
+ * Generic scheduled-job alerts inherit `owner` from the job catalog entry, so a
4
+ * commerce-owned job leaks engineer-only noise ("this cron failed") into what
5
+ * should be an operator's queue. They still count toward platform health.
6
+ */
7
+ export const GENERIC_JOB_DEDUPE_PREFIXES = [
8
+ "job_failed:",
9
+ "job_missed:",
10
+ "job_never_succeeded:",
11
+ "job_stuck_running:",
12
+ "job_ledger_missing:",
13
+ ];
14
+ /**
15
+ * How old a watchdog heartbeat may be before the health pill stops trusting it.
16
+ *
17
+ * The development-preview reference uses a conservative six-hour stale window
18
+ * independent from any scheduler cadence. It is a policy default, not a
19
+ * scheduling SLA; adopters must review it against their expected maximum
20
+ * heartbeat delay and queue jitter.
21
+ */
22
+ export const WATCHDOG_STALE_AFTER_SECONDS = 6 * 60 * 60;
23
+ const SEVERITY_RANK = { p0: 0, p1: 1, p2: 2, p3: 3 };
24
+ /**
25
+ * Derived from the paging policy's DEFAULT floor, not from the live threshold:
26
+ * this is a pure projection with no access to PLATFORM_ALERT_PAGING_MIN_SEVERITY,
27
+ * so an operator who overrides that variable makes panel and pager disagree
28
+ * again. Threading the parsed floor through the admin BFF is wave-3 work.
29
+ */
30
+ function isPageableSeverity(severity) {
31
+ return shouldPage(severity, DEFAULT_PAGING_MIN_SEVERITY);
32
+ }
33
+ export function isGenericJobAlert(dedupeKey) {
34
+ return GENERIC_JOB_DEDUPE_PREFIXES.some((prefix) => dedupeKey.startsWith(prefix));
35
+ }
36
+ /**
37
+ * Display bucket. `commerce` means "a business operator can act on this".
38
+ *
39
+ * `commerce/platform` is deliberately excluded: despite the prefix it owns
40
+ * engineering-run plumbing (outbox-dispatch, outbox-prune, abandoned-cart,
41
+ * review-request, reorder-reminder).
42
+ */
43
+ export function classifyLane(owner, dedupeKey) {
44
+ if (isGenericJobAlert(dedupeKey))
45
+ return "platform";
46
+ if (!owner.startsWith("commerce/"))
47
+ return "platform";
48
+ if (owner === "commerce/platform")
49
+ return "platform";
50
+ return "commerce";
51
+ }
52
+ export function isSnoozed(snoozedUntil, now) {
53
+ if (!snoozedUntil)
54
+ return false;
55
+ const until = Date.parse(snoozedUntil);
56
+ return Number.isFinite(until) && until > now.getTime();
57
+ }
58
+ /**
59
+ * Unknown severities are treated as p0 — mirrors alertPagingPolicy's fail-safe,
60
+ * where an unrecognised severity always pages rather than silently disappearing.
61
+ */
62
+ function normalizeSeverity(severity) {
63
+ return severity in SEVERITY_RANK ? severity : "p0";
64
+ }
65
+ function normalizeIso(value) {
66
+ const parsed = Date.parse(value);
67
+ return Number.isFinite(parsed) ? new Date(parsed).toISOString() : value;
68
+ }
69
+ /** Unresolved ledger state, including a controlled snoozed exception. */
70
+ function isOpen(row) {
71
+ if (row.status !== "open" && row.status !== "acknowledged")
72
+ return false;
73
+ return true;
74
+ }
75
+ /** Live enough to affect the health badge and paging. */
76
+ function isLive(row, now) {
77
+ return isOpen(row) && !isSnoozed(row.snoozed_until, now);
78
+ }
79
+ /**
80
+ * Pageable means "this would wake someone up": live and above the paging floor.
81
+ * Acknowledged rows stay pageable on purpose — acknowledged is not resolved, the
82
+ * system is still broken.
83
+ */
84
+ export function isPageable(row, now) {
85
+ return isLive(row, now) && isPageableSeverity(normalizeSeverity(row.severity));
86
+ }
87
+ export function toAdminAlert(row, now) {
88
+ return {
89
+ id: row.id,
90
+ dedupeKey: row.dedupe_key,
91
+ lane: classifyLane(row.owner, row.dedupe_key),
92
+ owner: row.owner,
93
+ severity: normalizeSeverity(row.severity),
94
+ status: row.status === "acknowledged" ? "acknowledged" : "open",
95
+ pageable: isPageable(row, now),
96
+ title: row.title,
97
+ message: row.message ?? "",
98
+ supportCode: row.support_code,
99
+ runbookUrl: row.runbook_url,
100
+ firstSeenAt: normalizeIso(row.first_seen_at),
101
+ lastSeenAt: normalizeIso(row.last_seen_at),
102
+ snoozedUntil: row.snoozed_until ? normalizeIso(row.snoozed_until) : null,
103
+ };
104
+ }
105
+ export function worstSeverity(alerts) {
106
+ let worst = null;
107
+ for (const alert of alerts) {
108
+ if (!worst || SEVERITY_RANK[alert.severity] < SEVERITY_RANK[worst])
109
+ worst = alert.severity;
110
+ }
111
+ return worst;
112
+ }
113
+ /**
114
+ * `commercePageableCount` and `platformPageableCount` partition the pageable set,
115
+ * so no alert that would page is ever invisible in the popover.
116
+ */
117
+ export function summarizeAlerts(alerts) {
118
+ const pageable = alerts.filter((alert) => alert.pageable);
119
+ return {
120
+ commercePageableCount: pageable.filter((alert) => alert.lane === "commerce").length,
121
+ commerceTotalCount: alerts.filter((alert) => alert.lane === "commerce").length,
122
+ platformPageableCount: pageable.filter((alert) => alert.lane === "platform").length,
123
+ snoozedCount: 0,
124
+ maxOpenSeverity: worstSeverity(alerts),
125
+ };
126
+ }
127
+ export function buildHeartbeat(row, now) {
128
+ const lastSuccessAt = row?.last_success_at ?? null;
129
+ const parsed = lastSuccessAt ? Date.parse(lastSuccessAt) : Number.NaN;
130
+ const stale = !Number.isFinite(parsed) || now.getTime() - parsed > WATCHDOG_STALE_AFTER_SECONDS * 1000;
131
+ return {
132
+ lastSuccessAt: Number.isFinite(parsed) ? new Date(parsed).toISOString() : null,
133
+ staleAfterSeconds: WATCHDOG_STALE_AFTER_SECONDS,
134
+ stale,
135
+ };
136
+ }
137
+ /**
138
+ * Staleness beats severity: if the watchdog has not reported recently we do not
139
+ * know the current state, and "unknown" is the only honest answer. There is no
140
+ * path here that renders a green "systems ok" from missing data.
141
+ */
142
+ export function deriveHealth(summary, heartbeat) {
143
+ if (heartbeat.stale)
144
+ return "unknown";
145
+ if (summary.maxOpenSeverity === "p0")
146
+ return "down";
147
+ if (summary.maxOpenSeverity === "p1")
148
+ return "degraded";
149
+ return "ok";
150
+ }
151
+ /** Alerts returned to the client; counts above stay accurate even when this is truncated. */
152
+ export const ADMIN_ALERTS_LIST_LIMIT = 50;
153
+ function compareForDisplay(a, b) {
154
+ const bySeverity = SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity];
155
+ if (bySeverity !== 0)
156
+ return bySeverity;
157
+ return Date.parse(b.lastSeenAt) - Date.parse(a.lastSeenAt);
158
+ }
159
+ export function buildAlertsOverview(rows, heartbeatRow, now) {
160
+ const openRows = rows.filter(isOpen);
161
+ const alerts = openRows
162
+ .filter((row) => isLive(row, now))
163
+ .map((row) => toAdminAlert(row, now))
164
+ .sort(compareForDisplay);
165
+ const snoozedAlerts = openRows
166
+ .filter((row) => isSnoozed(row.snoozed_until, now))
167
+ .map((row) => toAdminAlert(row, now))
168
+ .sort(compareForDisplay);
169
+ const summary = {
170
+ ...summarizeAlerts(alerts),
171
+ snoozedCount: snoozedAlerts.length,
172
+ };
173
+ const heartbeat = buildHeartbeat(heartbeatRow, now);
174
+ return {
175
+ health: deriveHealth(summary, heartbeat),
176
+ summary,
177
+ heartbeat,
178
+ alerts: alerts.slice(0, ADMIN_ALERTS_LIST_LIMIT),
179
+ // Deliberately separate from the active list's limit: controlled exceptions
180
+ // are relevant audit context, but must not turn the health pill red.
181
+ snoozedAlerts,
182
+ generatedAt: now.toISOString(),
183
+ };
184
+ }
@@ -0,0 +1,15 @@
1
+ import type { AlertSeverity } from "./contracts/observabilityContracts.js";
2
+ /** Alerts at or above this severity page by default; below it are ledger-only. */
3
+ export declare const DEFAULT_PAGING_MIN_SEVERITY: AlertSeverity;
4
+ /**
5
+ * Whether an alert of `severity` should page given the `minSeverity` threshold.
6
+ *
7
+ * Fail-safe: an unknown/unparseable severity always pages (treated as most
8
+ * urgent). Silence must never be the result of a classification error.
9
+ */
10
+ export declare function shouldPage(severity: string, minSeverity?: AlertSeverity): boolean;
11
+ /**
12
+ * Parse a paging threshold from configuration (e.g. an env var), falling back to
13
+ * {@link DEFAULT_PAGING_MIN_SEVERITY} for any missing or invalid value.
14
+ */
15
+ export declare function parsePagingMinSeverity(value: string | null | undefined): AlertSeverity;
@@ -0,0 +1,43 @@
1
+ const ALERT_SEVERITIES = ["p0", "p1", "p2", "p3"];
2
+ /**
3
+ * Paging policy for platform watchdog alerts.
4
+ *
5
+ * The alert ledger records every severity, but only sufficiently severe alerts
6
+ * should page an on-call channel (e.g. ntfy). Lower-severity alerts stay
7
+ * ledger-only so real incidents are not buried under routine noise.
8
+ *
9
+ * The tiering is settled: **p0 pages** (customers cannot buy, renewals cannot
10
+ * charge, the platform or database is down); **p1 is panel-urgent** and turns
11
+ * the admin health pill `degraded` without waking anyone; **p2/p3** are the
12
+ * panel list and the ledger. An unknown severity still pages: the fail-open
13
+ * rule is unchanged, because silence must never be the result of a
14
+ * classification error.
15
+ *
16
+ * Lower rank == more severe.
17
+ */
18
+ const SEVERITY_RANK = { p0: 0, p1: 1, p2: 2, p3: 3 };
19
+ /** Alerts at or above this severity page by default; below it are ledger-only. */
20
+ export const DEFAULT_PAGING_MIN_SEVERITY = "p0";
21
+ /**
22
+ * Whether an alert of `severity` should page given the `minSeverity` threshold.
23
+ *
24
+ * Fail-safe: an unknown/unparseable severity always pages (treated as most
25
+ * urgent). Silence must never be the result of a classification error.
26
+ */
27
+ export function shouldPage(severity, minSeverity = DEFAULT_PAGING_MIN_SEVERITY) {
28
+ const rank = SEVERITY_RANK[severity];
29
+ if (rank === undefined)
30
+ return true;
31
+ return rank <= SEVERITY_RANK[minSeverity];
32
+ }
33
+ /**
34
+ * Parse a paging threshold from configuration (e.g. an env var), falling back to
35
+ * {@link DEFAULT_PAGING_MIN_SEVERITY} for any missing or invalid value.
36
+ */
37
+ export function parsePagingMinSeverity(value) {
38
+ const normalized = value?.trim().toLowerCase();
39
+ if (normalized && ALERT_SEVERITIES.includes(normalized)) {
40
+ return normalized;
41
+ }
42
+ return DEFAULT_PAGING_MIN_SEVERITY;
43
+ }
@@ -0,0 +1,3 @@
1
+ /** Fallback window for an unknown/unparseable severity. */
2
+ export declare const DEFAULT_THROTTLE_SECONDS: number;
3
+ export declare function throttleSecondsForSeverity(severity: string): number;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Per-severity re-notification cadence for platform watchdog alerts.
3
+ *
4
+ * A firing alert re-pages at most once per this window (keyed off
5
+ * `last_notified_at`). Lower severities re-page less often so a persistent
6
+ * low-severity alert cannot flood the channel, while p0 stays loud.
7
+ */
8
+ const THROTTLE_SECONDS_BY_SEVERITY = {
9
+ p0: 1 * 60 * 60, // 1h
10
+ p1: 4 * 60 * 60, // 4h
11
+ p2: 12 * 60 * 60, // 12h
12
+ p3: 24 * 60 * 60, // 24h
13
+ };
14
+ /** Fallback window for an unknown/unparseable severity. */
15
+ export const DEFAULT_THROTTLE_SECONDS = 60 * 60;
16
+ export function throttleSecondsForSeverity(severity) {
17
+ return THROTTLE_SECONDS_BY_SEVERITY[severity] ?? DEFAULT_THROTTLE_SECONDS;
18
+ }
@@ -0,0 +1,17 @@
1
+ import type { z } from "zod";
2
+ import type { AdminSettingsReadResponse, AdminSettingsUpdateRequest, AdminSettingsUpdateResponse, AdminPipelineReadResponse } from "./contracts/admin.js";
3
+ import type { AdminAlertsOverviewResponse } from "./contracts/adminAlertsContracts.js";
4
+ /** The existing BFF requester owns fetch, envelope validation, cancellation and diagnostics. */
5
+ export interface OperationsRequestOptions extends Omit<RequestInit, "body"> {
6
+ body?: unknown;
7
+ fetcher?: typeof fetch;
8
+ timeoutMs?: number;
9
+ }
10
+ export type OperationsRequestBff = <T>(path: string, schema: z.ZodType<T>, options?: OperationsRequestOptions) => Promise<T>;
11
+ /** Bind the existing browser calls without installing an ambient fetch implementation. */
12
+ export declare function createOperationsClients(requestBff: OperationsRequestBff): {
13
+ getAdminSettings(accessToken: string, options?: OperationsRequestOptions): Promise<AdminSettingsReadResponse>;
14
+ updateAdminSetting(accessToken: string, request: AdminSettingsUpdateRequest, options?: OperationsRequestOptions): Promise<AdminSettingsUpdateResponse>;
15
+ getAdminPipeline(accessToken: string, options?: OperationsRequestOptions): Promise<AdminPipelineReadResponse>;
16
+ getAdminAlertsOverview(accessToken: string, options?: OperationsRequestOptions): Promise<AdminAlertsOverviewResponse>;
17
+ };
@@ -0,0 +1,32 @@
1
+ import { adminSettingsReadResponseSchema, adminSettingsUpdateResponseSchema, adminPipelineReadResponseSchema } from "./schemas.js";
2
+ import { adminAlertsOverviewResponseSchema } from "./adminAlertsSchemas.js";
3
+ /** Bind the existing browser calls without installing an ambient fetch implementation. */
4
+ export function createOperationsClients(requestBff) {
5
+ return {
6
+ getAdminSettings(accessToken, options = {}) {
7
+ return requestBff("/api/bff/admin/platform/settings", adminSettingsReadResponseSchema, {
8
+ ...options, method: "GET", headers: authHeaders(accessToken, options),
9
+ });
10
+ },
11
+ updateAdminSetting(accessToken, request, options = {}) {
12
+ return requestBff("/api/bff/admin/platform/settings/update", adminSettingsUpdateResponseSchema, {
13
+ ...options, method: "POST", headers: authHeaders(accessToken, options), body: request,
14
+ });
15
+ },
16
+ getAdminPipeline(accessToken, options = {}) {
17
+ return requestBff("/api/bff/admin/platform/pipeline", adminPipelineReadResponseSchema, {
18
+ ...options, method: "GET", headers: authHeaders(accessToken, options),
19
+ });
20
+ },
21
+ getAdminAlertsOverview(accessToken, options = {}) {
22
+ return requestBff("/api/bff/admin/platform/alerts", adminAlertsOverviewResponseSchema, {
23
+ ...options, method: "GET", headers: authHeaders(accessToken, options),
24
+ });
25
+ },
26
+ };
27
+ }
28
+ function authHeaders(accessToken, options) {
29
+ const headers = new Headers(options.headers);
30
+ headers.set("Authorization", `Bearer ${accessToken}`);
31
+ return headers;
32
+ }
@@ -0,0 +1,93 @@
1
+ /** DTOs for the existing operational settings, pipeline and control-plane surfaces. */
2
+ export type AdminPipelineTester = {
3
+ id: string;
4
+ status: string;
5
+ email_sequence_step: number | null;
6
+ email_sequence_paused: boolean | null;
7
+ };
8
+ export type AdminPipelineEmailTemplate = {
9
+ id: string;
10
+ name: string;
11
+ sequence_order: number | null;
12
+ };
13
+ export type AdminPipelineEmailEvent = {
14
+ event_type: string;
15
+ };
16
+ export type AdminPipelineReadRequest = Record<string, never>;
17
+ export type AdminPipelineReadResponse = {
18
+ testers: AdminPipelineTester[];
19
+ templates: AdminPipelineEmailTemplate[];
20
+ emailSendCount: number;
21
+ emailEvents: AdminPipelineEmailEvent[];
22
+ };
23
+ export type AdminPipelineDhlTrackingRefreshRequest = Record<string, never>;
24
+ export type AdminPipelineDhlTrackingRefreshResponse = {
25
+ checked: number;
26
+ updated: number;
27
+ };
28
+ export type AdminSettingsAdminUser = {
29
+ id: string;
30
+ email: string | null;
31
+ role: string | null;
32
+ };
33
+ export type AdminSettingsReadRequest = Record<string, never>;
34
+ export type AdminSettingsReadResponse = {
35
+ settings: Record<string, unknown>;
36
+ adminUsers: AdminSettingsAdminUser[];
37
+ };
38
+ export type AdminSettingWriteValue = string | number | boolean | null;
39
+ export type AdminSettingsUpdateRequest = {
40
+ key: string;
41
+ value: AdminSettingWriteValue;
42
+ };
43
+ export type AdminSettingsUpdateResponse = {
44
+ key: string;
45
+ saved: true;
46
+ };
47
+ export type PlatformControlPlaneReadRequest = Record<string, never>;
48
+ export type PlatformControlPlaneReadResponse = {
49
+ controls: {
50
+ controlKey: string;
51
+ enabled: boolean;
52
+ revision: number;
53
+ updatedAt: string;
54
+ }[];
55
+ jobs: {
56
+ jobName: string;
57
+ enabled: boolean;
58
+ activeDriver: "worker" | "scheduler" | "operator";
59
+ lastStatus: "running" | "success" | "failed" | "skipped" | null;
60
+ lastStartedAt: string | null;
61
+ lastFinishedAt: string | null;
62
+ lastSuccessAt: string | null;
63
+ }[];
64
+ alerts: {
65
+ dedupeKey: string;
66
+ severity: "p0" | "p1" | "p2" | "p3";
67
+ status: "open" | "acknowledged" | "resolved";
68
+ owner: string;
69
+ title: string;
70
+ firstSeenAt: string;
71
+ lastSeenAt: string;
72
+ resolvedAt: string | null;
73
+ }[];
74
+ };
75
+ export type PlatformControlPlaneMutation = {
76
+ action: "set-control";
77
+ idempotencyKey: string;
78
+ controlKey: string;
79
+ enabled: boolean;
80
+ } | {
81
+ action: "record-heartbeat";
82
+ idempotencyKey: string;
83
+ health: "healthy" | "degraded" | "failed";
84
+ firingCount: number;
85
+ maxSeverity: "p0" | "p1" | "p2" | "p3" | null;
86
+ promotionReady: boolean;
87
+ };
88
+ export type PlatformControlPlaneMutationResponse = {
89
+ action: "set-control" | "record-heartbeat";
90
+ replayed: boolean;
91
+ revision: number | null;
92
+ recordedAt: string;
93
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,40 @@
1
+ /** Operator projection; persistence and read authority remain host-owned. */
2
+ export type AdminAlertSeverity = "p0" | "p1" | "p2" | "p3";
3
+ export type AdminAlertLane = "commerce" | "platform";
4
+ export type AdminAlertHealth = "ok" | "degraded" | "down" | "unknown";
5
+ export type AdminAlert = {
6
+ id: string;
7
+ dedupeKey: string;
8
+ lane: AdminAlertLane;
9
+ owner: string;
10
+ severity: AdminAlertSeverity;
11
+ status: "open" | "acknowledged";
12
+ pageable: boolean;
13
+ title: string;
14
+ message: string;
15
+ supportCode: string | null;
16
+ runbookUrl: string | null;
17
+ firstSeenAt: string;
18
+ lastSeenAt: string;
19
+ snoozedUntil: string | null;
20
+ };
21
+ export type AdminAlertsHeartbeat = {
22
+ lastSuccessAt: string | null;
23
+ staleAfterSeconds: number;
24
+ stale: boolean;
25
+ };
26
+ export type AdminAlertsSummary = {
27
+ commercePageableCount: number;
28
+ commerceTotalCount: number;
29
+ platformPageableCount: number;
30
+ snoozedCount: number;
31
+ maxOpenSeverity: AdminAlertSeverity | null;
32
+ };
33
+ export type AdminAlertsOverviewResponse = {
34
+ health: AdminAlertHealth;
35
+ summary: AdminAlertsSummary;
36
+ heartbeat: AdminAlertsHeartbeat;
37
+ alerts: AdminAlert[];
38
+ snoozedAlerts: AdminAlert[];
39
+ generatedAt: string;
40
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,7 @@
1
+ export type AlertIncidentClass = "customer_communication_failure" | "scheduled_job_failed" | "scheduled_job_missed" | "fulfillment_tracking_stalled" | "configuration_drift" | "data_integrity" | "queue_backlog" | "recipient_configuration_failure" | "platform_watchdog";
2
+ export type AlertHumanContext = {
3
+ incidentClass: AlertIncidentClass;
4
+ impact: string;
5
+ firstAction: string;
6
+ urgency: string;
7
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ export * from "./admin.js";
2
+ export * from "./adminAlertsContracts.js";
3
+ export * from "./ports.js";
4
+ export * from "./observabilityContracts.js";
5
+ export * from "./observabilityPorts.js";
6
+ export * from "./alertHumanContext.js";
@@ -0,0 +1,6 @@
1
+ export * from "./admin.js";
2
+ export * from "./adminAlertsContracts.js";
3
+ export * from "./ports.js";
4
+ export * from "./observabilityContracts.js";
5
+ export * from "./observabilityPorts.js";
6
+ export * from "./alertHumanContext.js";
@@ -0,0 +1,41 @@
1
+ export type AlertSeverity = "p0" | "p1" | "p2" | "p3";
2
+ /** Opaque host-owned transport key; this module declares no vendor capability. */
3
+ export type AlertChannel = string;
4
+ export type WatchdogSnapshot = {
5
+ checkedAt: string;
6
+ };
7
+ export type AlertDecision<Channel extends string = AlertChannel> = {
8
+ dedupeKey: string;
9
+ severity: AlertSeverity;
10
+ owner: string;
11
+ runbookUrl: string;
12
+ title: string;
13
+ message: string;
14
+ humanContext?: import("./alertHumanContext.js").AlertHumanContext;
15
+ channels: Channel[];
16
+ payload: Record<string, unknown>;
17
+ paging?: "default" | "never";
18
+ };
19
+ export type OpenAlert = {
20
+ id: string;
21
+ dedupeKey: string;
22
+ status: "open" | "acknowledged";
23
+ severity: AlertSeverity;
24
+ lastNotifiedAt: string | null;
25
+ /** Most recent watchdog delivery decision, including skipped/failed attempts. */
26
+ lastNotificationAttemptAt?: string | null;
27
+ lastNotificationStatus?: AlertNotificationOutcome["status"] | null;
28
+ /** Earliest time the watchdog may create another delivery-attempt ledger row. */
29
+ nextNotificationAttemptAt?: string | null;
30
+ /** Consecutive failed webhook attempts; reset by sent/skipped outcomes. */
31
+ notificationFailureCount?: number;
32
+ /** Operator silence window; when set and in the future, paging is suppressed. */
33
+ snoozedUntil?: string | null;
34
+ };
35
+ export type AlertNotificationOutcome<Channel extends string = AlertChannel> = {
36
+ channel: Channel;
37
+ status: "sent" | "failed" | "skipped";
38
+ provider?: string | null;
39
+ providerResponse?: Record<string, unknown> | null;
40
+ error?: string | null;
41
+ };
@@ -0,0 +1,18 @@
1
+ import type { AlertDecision, AlertNotificationOutcome, WatchdogSnapshot, OpenAlert } from "./observabilityContracts.js";
2
+ export type ObservabilityEvidencePort<Snapshot extends WatchdogSnapshot = WatchdogSnapshot> = {
3
+ collectSnapshot(now: Date): Promise<Snapshot>;
4
+ };
5
+ export type AlertLedgerPort<Channel extends string = string> = {
6
+ listOpenAlerts(): Promise<OpenAlert[]>;
7
+ upsertOpenAlert: (decision: AlertDecision<Channel>, now: Date) => Promise<OpenAlert>;
8
+ resolveAlert(dedupeKey: string, now: Date): Promise<void>;
9
+ recordNotification: (alertId: string,
10
+ /** The kernel retains its existing webhook-keyed skipped-attempt audit rows. */
11
+ outcome: AlertNotificationOutcome<Channel | "webhook">, now: Date, schedule: {
12
+ nextAttemptAt: Date;
13
+ failureCount: number;
14
+ }) => Promise<void>;
15
+ };
16
+ export type AlertSinkPort<Channel extends string = string> = {
17
+ send: (decision: AlertDecision<Channel>, alert: OpenAlert) => Promise<AlertNotificationOutcome<Channel>>;
18
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ import type { AdminPipelineReadRequest, AdminPipelineReadResponse, AdminSettingsReadRequest, AdminSettingsReadResponse, AdminSettingsUpdateRequest, AdminSettingsUpdateResponse, PlatformControlPlaneReadRequest, PlatformControlPlaneReadResponse, PlatformControlPlaneMutation, PlatformControlPlaneMutationResponse } from "./admin.js";
2
+ export interface AdminPipelineReadPort {
3
+ readPipeline(request: AdminPipelineReadRequest): Promise<AdminPipelineReadResponse>;
4
+ }
5
+ export interface AdminSettingsOperationsPort {
6
+ readSettings(request: AdminSettingsReadRequest): Promise<AdminSettingsReadResponse>;
7
+ updateSetting(request: AdminSettingsUpdateRequest): Promise<AdminSettingsUpdateResponse>;
8
+ }
9
+ export interface PlatformControlPlanePort {
10
+ readControlPlane(request: PlatformControlPlaneReadRequest): Promise<PlatformControlPlaneReadResponse>;
11
+ mutateControlPlane(request: PlatformControlPlaneMutation): Promise<PlatformControlPlaneMutationResponse>;
12
+ }
13
+ export type OperationsAuthorizationResult = {
14
+ ok: true;
15
+ } | {
16
+ ok: false;
17
+ code: "UNAUTHORIZED" | "FORBIDDEN";
18
+ message: string;
19
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ export declare class PlatformControlPlaneConflictError extends Error {
2
+ readonly name = "PlatformControlPlaneConflictError";
3
+ }
4
+ export declare class PlatformControlPlaneUnavailableError extends Error {
5
+ readonly name = "PlatformControlPlaneUnavailableError";
6
+ }