create-safest-tools 0.6.0 → 0.7.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 (172) hide show
  1. package/README.md +3 -3
  2. package/package.json +2 -2
  3. package/src/config.mjs +2 -2
  4. package/src/update.mjs +10 -1
  5. package/template/README.md +2 -2
  6. package/template/console/README.md +2 -2
  7. package/template/console/analytics/AnalyticsWorkspace.tsx +49 -36
  8. package/template/console/analytics/controller.ts +10 -2
  9. package/template/console/analytics/types.ts +7 -0
  10. package/template/console/appeals/AppealFollowup.tsx +171 -0
  11. package/template/console/appeals/AppealWorkspace.tsx +33 -4
  12. package/template/console/appeals/RecordAppealDialog.tsx +42 -0
  13. package/template/console/appeals/appeal-corrections.css +29 -0
  14. package/template/console/appeals/controller.ts +40 -14
  15. package/template/console/appeals/events.ts +1 -0
  16. package/template/console/appeals/types.ts +6 -0
  17. package/template/console/appeals/useAppealDraftGuard.ts +12 -0
  18. package/template/console/assistant/AssistantWorkspace.tsx +28 -5
  19. package/template/console/command/CommandCentre.tsx +101 -64
  20. package/template/console/command/controller.ts +80 -70
  21. package/template/console/command/events.ts +1 -2
  22. package/template/console/command/presentation.ts +29 -0
  23. package/template/console/command/store.ts +4 -4
  24. package/template/console/command/types.ts +26 -21
  25. package/template/console/configuration/ConfigurationBuilders.tsx +101 -0
  26. package/template/console/configuration/ConfigurationDialog.tsx +28 -13
  27. package/template/console/configuration/ConfigurationWorkspace.tsx +21 -8
  28. package/template/console/configuration/types.ts +1 -1
  29. package/template/console/lib/priority.ts +13 -0
  30. package/template/console/operations/CaseEscalations.tsx +142 -0
  31. package/template/console/operations/OperationsWorkspace.tsx +2 -0
  32. package/template/console/operations/case-escalations.css +20 -0
  33. package/template/console/people/PeopleWorkspace.tsx +8 -4
  34. package/template/console/people/PersonAccessDialog.tsx +40 -0
  35. package/template/console/people/types.ts +1 -0
  36. package/template/console/profile/ProfileWorkspace.tsx +1 -1
  37. package/template/console/registry/IntegrationSetup.tsx +41 -0
  38. package/template/console/registry/IntegrationVerification.tsx +54 -0
  39. package/template/console/registry/RegistryDetailsDialog.tsx +2 -2
  40. package/template/console/registry/RegistryDialog.tsx +56 -27
  41. package/template/console/registry/RegistryWorkspace.tsx +10 -5
  42. package/template/console/registry/integration-verification.css +25 -0
  43. package/template/console/reports/CaseActions.tsx +81 -0
  44. package/template/console/reports/CaseContinuity.tsx +27 -0
  45. package/template/console/reports/CaseNotices.tsx +48 -0
  46. package/template/console/reports/CaseOwnership.tsx +78 -0
  47. package/template/console/reports/CaseReviewTasks.tsx +148 -0
  48. package/template/console/reports/EnrichmentFindings.tsx +148 -0
  49. package/template/console/reports/InvestigationBrief.tsx +29 -0
  50. package/template/console/reports/ReportDrawer.tsx +122 -67
  51. package/template/console/reports/ReportWorkspace.tsx +112 -23
  52. package/template/console/reports/controller.ts +125 -60
  53. package/template/console/reports/events.ts +9 -2
  54. package/template/console/reports/load-inbox.ts +17 -0
  55. package/template/console/reports/presence-presentation.ts +52 -0
  56. package/template/console/reports/private-drafts.ts +32 -0
  57. package/template/console/reports/store.ts +2 -2
  58. package/template/console/reports/types.ts +50 -2
  59. package/template/console/reports/use-editing-access.ts +13 -0
  60. package/template/console/settings/SettingsWorkspace.tsx +1 -1
  61. package/template/console/shell/WorkspaceShell.tsx +55 -29
  62. package/template/console/shell/WorkspaceUpdateNotice.tsx +48 -0
  63. package/template/console/shell/controller.ts +23 -16
  64. package/template/console/shell/navigation.ts +30 -39
  65. package/template/console/workflows/CreatePlaybookDialog.tsx +73 -0
  66. package/template/console/workflows/PlaybookExamples.tsx +160 -0
  67. package/template/console/workflows/PlaybookFields.tsx +109 -0
  68. package/template/console/workflows/PlaybookGuideEditor.tsx +125 -0
  69. package/template/console/workflows/PlaybookHistory.tsx +106 -0
  70. package/template/console/workflows/WorkflowDialogs.tsx +2 -1
  71. package/template/console/workflows/WorkflowStudio.tsx +108 -39
  72. package/template/console/workflows/WorkflowWorkspace.tsx +9 -7
  73. package/template/console/workflows/templates.ts +3 -3
  74. package/template/console/workflows/types.ts +11 -0
  75. package/template/migrations/0001_safest_resolve_baseline.sql +0 -1
  76. package/template/migrations/0002_playbook_publication_evidence.sql +36 -0
  77. package/template/migrations/0003_action_confirmation.sql +24 -0
  78. package/template/migrations/0004_notice_recovery.sql +22 -0
  79. package/template/migrations/0005_appeal_continuity.sql +17 -0
  80. package/template/migrations/0006_case_ownership.sql +23 -0
  81. package/template/migrations/0007_integration_verification.sql +21 -0
  82. package/template/migrations/0008_case_escalations.sql +135 -0
  83. package/template/migrations/0009_participant_continuation.sql +61 -0
  84. package/template/migrations/0010_appeal_corrections.sql +41 -0
  85. package/template/npm-shrinkwrap.json +8036 -0
  86. package/template/package.json +31 -22
  87. package/template/public/_headers +16 -1
  88. package/template/public/console/auth-shell.js +22151 -14847
  89. package/template/public/console/release.json +1 -0
  90. package/template/public/console/workspace-features.css +2 -0
  91. package/template/public/embed/embed.css +3 -0
  92. package/template/public/embed/embed.js +19 -1
  93. package/template/public/embed/index.html +2 -0
  94. package/template/public/index.html +9 -6
  95. package/template/public/participant.css +2 -0
  96. package/template/public/participant.html +13 -0
  97. package/template/public/participant.js +111 -0
  98. package/template/public/public-report.js +21 -1
  99. package/template/public/report/index.html +1 -1
  100. package/template/public/styles.css +599 -83
  101. package/template/public/workspace.css +124 -0
  102. package/template/scripts/reports-plan.mjs +1 -1
  103. package/template/shared/case-escalations.ts +31 -0
  104. package/template/shared/integration-progress.ts +27 -0
  105. package/template/shared/notice-inputs.ts +3 -0
  106. package/template/shared/playbook-resources.ts +14 -0
  107. package/template/shared/playbooks.ts +249 -0
  108. package/template/src/agent-executor.ts +25 -8
  109. package/template/src/ai-observability.ts +14 -13
  110. package/template/src/ai-registry-validation.ts +1 -1
  111. package/template/src/appeal-continuity.ts +75 -0
  112. package/template/src/appeal-correction-state.ts +46 -0
  113. package/template/src/appeal-corrections.ts +112 -0
  114. package/template/src/appeal-decisions.ts +85 -0
  115. package/template/src/assistant.ts +3 -4
  116. package/template/src/case-escalations.ts +223 -0
  117. package/template/src/case-investigator.ts +179 -0
  118. package/template/src/component-executor.ts +5 -4
  119. package/template/src/configuration-registry.ts +4 -1
  120. package/template/src/connection-oauth.ts +12 -3
  121. package/template/src/database-readiness.ts +14 -0
  122. package/template/src/human-tasks.ts +152 -55
  123. package/template/src/index.ts +191 -29
  124. package/template/src/installation-admin.ts +2 -1
  125. package/template/src/integration-progress.ts +45 -0
  126. package/template/src/integration-verification.ts +249 -0
  127. package/template/src/investigation-evidence.ts +95 -0
  128. package/template/src/investigator-fixture.ts +30 -0
  129. package/template/src/notice-delivery.ts +19 -0
  130. package/template/src/notice-recovery.ts +81 -0
  131. package/template/src/operator-scope.ts +31 -0
  132. package/template/src/participant-access.ts +163 -0
  133. package/template/src/participant-case.ts +87 -0
  134. package/template/src/participant-customer-access.ts +93 -0
  135. package/template/src/participant-recovery.ts +43 -0
  136. package/template/src/participant-routes.ts +67 -0
  137. package/template/src/platform-registry-validation.ts +25 -2
  138. package/template/src/platform-registry.ts +10 -7
  139. package/template/src/playbook-resources.ts +58 -0
  140. package/template/src/report-admin.ts +9 -2
  141. package/template/src/report-auth.ts +1 -28
  142. package/template/src/report-better-auth.ts +18 -6
  143. package/template/src/report-delivery.ts +149 -148
  144. package/template/src/report-email-inbound.ts +33 -22
  145. package/template/src/report-email-template.ts +5 -2
  146. package/template/src/report-email.ts +7 -30
  147. package/template/src/report-governance.ts +42 -45
  148. package/template/src/report-http.ts +37 -2
  149. package/template/src/report-operations.ts +30 -67
  150. package/template/src/report-operator-accounts.ts +7 -6
  151. package/template/src/report-ownership.ts +64 -0
  152. package/template/src/report-presence.ts +15 -9
  153. package/template/src/report-repository.ts +16 -7
  154. package/template/src/report-turnstile.ts +7 -3
  155. package/template/src/report-types.ts +1 -0
  156. package/template/src/report-workflow.ts +183 -249
  157. package/template/src/workflow-actions.ts +248 -156
  158. package/template/src/workflow-compiler.ts +63 -12
  159. package/template/src/workflow-dynamic-runtime.ts +20 -9
  160. package/template/src/workflow-effects.ts +117 -39
  161. package/template/src/workflow-event-transport.ts +16 -0
  162. package/template/src/workflow-expressions.ts +30 -0
  163. package/template/src/workflow-loader-code.ts +21 -0
  164. package/template/src/workflow-platform-types.ts +3 -0
  165. package/template/src/workflow-platform-validation.ts +23 -1
  166. package/template/src/workflow-repository.ts +131 -28
  167. package/template/src/workflow-runs.ts +61 -13
  168. package/template/src/workflow-simulator.ts +7 -4
  169. package/template/src/workspace-governance.ts +6 -4
  170. package/template/tsconfig.json +1 -0
  171. package/template/vite.console.config.ts +30 -2
  172. package/template/worker-configuration.d.ts +3 -2
@@ -1,32 +1,11 @@
1
- export type AuthenticationEmailBinding = {
2
- send(message: {
3
- from: { email: string; name?: string };
4
- to: string | string[];
5
- subject: string;
6
- text: string;
7
- html: string;
8
- replyTo?: string | { email: string; name?: string };
9
- headers?: Record<string, string>;
10
- }): Promise<unknown>;
11
- };
12
-
13
- export type ReporterEmailBinding = {
14
- send(message: {
15
- from: string | { email: string; name?: string };
16
- to: string | { email: string; name?: string };
17
- subject: string;
18
- text: string;
19
- html?: string;
20
- replyTo?: string | { email: string; name?: string };
21
- headers?: Record<string, string>;
22
- }): Promise<{ messageId?: string }>;
23
- };
1
+ import { decryptReportContact, sha256 } from "./report-crypto";
2
+ import type { ParticipantAudience } from "./report-types";
24
3
 
25
4
  type EmailEnvironment = {
26
- AUTH_EMAIL?: AuthenticationEmailBinding;
27
- REPORTER_EMAIL?: ReporterEmailBinding;
5
+ AUTH_EMAIL?: SendEmail;
6
+ REPORTER_EMAIL?: SendEmail;
28
7
  /** Compatibility with installations created before the email channels were separated. */
29
- EMAIL?: AuthenticationEmailBinding & ReporterEmailBinding;
8
+ EMAIL?: SendEmail;
30
9
  AUTH_EMAIL_FROM?: string;
31
10
  REPORTER_EMAIL_FROM?: string;
32
11
  REPORTER_EMAIL_SUBJECT_PREFIX?: string;
@@ -39,12 +18,12 @@ function emailEnvironment(env: unknown): EmailEnvironment {
39
18
  return env as EmailEnvironment;
40
19
  }
41
20
 
42
- export function authenticationEmailBinding(env: unknown): AuthenticationEmailBinding | undefined {
21
+ export function authenticationEmailBinding(env: unknown): SendEmail | undefined {
43
22
  const bindings = emailEnvironment(env);
44
23
  return bindings.AUTH_EMAIL ?? bindings.EMAIL;
45
24
  }
46
25
 
47
- export function reporterEmailBinding(env: unknown): ReporterEmailBinding | undefined {
26
+ export function reporterEmailBinding(env: unknown): SendEmail | undefined {
48
27
  const bindings = emailEnvironment(env);
49
28
  return bindings.REPORTER_EMAIL ?? bindings.EMAIL;
50
29
  }
@@ -190,5 +169,3 @@ export async function selectParticipantDelivery(input: {
190
169
  }
191
170
  return { channel: null, state: "suppressed" };
192
171
  }
193
- import { decryptReportContact, sha256 } from "./report-crypto";
194
- import type { ParticipantAudience } from "./report-types";
@@ -100,57 +100,49 @@ function percentile(values: number[], ratio: number): number | null {
100
100
  return Math.round(values[index] ?? 0);
101
101
  }
102
102
 
103
- export async function loadAnalytics(db: D1Database, days = 30): Promise<Record<string, unknown>> {
103
+ export async function loadAnalytics(db: D1Database, days = 30, queueScope: string[] | null = null): Promise<Record<string, unknown>> {
104
104
  const generatedAt = now();
105
105
  const boundedDays = Math.max(1, Math.min(366, days));
106
106
  const fromDate = subtractDays(generatedAt, boundedDays).slice(0, 10);
107
- const [series, durations, backlog, aiUsage] = await Promise.all([
108
- db.prepare(`
109
- SELECT aggregate_date AS aggregateDate, metric_key AS metricKey, dimension_key AS dimensionKey,
110
- dimension_value AS dimensionValue, value
111
- FROM daily_aggregates WHERE aggregate_date >= ?1
112
- ORDER BY aggregate_date, metric_key, dimension_key, dimension_value LIMIT 10000
113
- `).bind(fromDate).all<Record<string, unknown>>(),
114
- db.prepare(`
115
- SELECT CAST((julianday(resolved_at) - julianday(received_at)) * 86400 AS INTEGER) AS seconds
116
- FROM reports WHERE resolved_at IS NOT NULL AND received_at >= ?1
117
- ORDER BY seconds LIMIT 10000
118
- `).bind(`${fromDate}T00:00:00.000Z`).all<{ seconds: number }>(),
119
- db.prepare(`
120
- SELECT queue_id AS queueId, state, COUNT(*) AS count,
121
- CAST(MAX((julianday(?1) - julianday(received_at)) * 86400) AS INTEGER) AS oldestAgeSeconds
122
- FROM reports WHERE state IN ('received', 'human_review', 'ai_review', 'awaiting_reporter', 'human_review_requested', 'appealed')
123
- GROUP BY queue_id, state ORDER BY queue_id, state
124
- `).bind(generatedAt).all<Record<string, unknown>>(),
125
- db.prepare(`
126
- SELECT usage_date AS usageDate, SUM(reports_started) AS reportsStarted,
127
- SUM(reports_resolved) AS reportsResolved, SUM(reports_escalated) AS reportsEscalated,
128
- SUM(failures) AS failures, SUM(estimated_cost_microusd) AS estimatedCostMicrousd,
129
- SUM(eligible_reports) AS eligibleReports, SUM(waiting_for_reporter) AS waitingForReporter,
130
- SUM(human_review_requests) AS humanReviewRequests, SUM(appeals_filed) AS appealsFiled,
131
- SUM(appeal_reversals) AS appealReversals, SUM(invalid_outputs) AS invalidOutputs,
132
- SUM(provider_errors) AS providerErrors, SUM(timeouts) AS timeouts
133
- FROM ai_usage_daily WHERE usage_date >= ?1 GROUP BY usage_date ORDER BY usage_date
134
- `).bind(fromDate).all<Record<string, unknown>>(),
107
+ const from = `${fromDate}T00:00:00.000Z`;
108
+ const scope = queueScope === null ? null : JSON.stringify(queueScope);
109
+ const visible = `WITH visible_reports AS (SELECT * FROM reports WHERE (?2 IS NULL OR queue_id IN (SELECT value FROM json_each(?2))))`;
110
+ const query = (sql: string) => db.prepare(`${visible} ${sql}`).bind(from, scope);
111
+ const [series, durations, backlog, evidence, actions, notices, appeals, audits] = await Promise.all([
112
+ query(`SELECT substr(received_at,1,10) AS aggregateDate, 'reports_received' AS metricKey, 'source' AS dimensionKey, source AS dimensionValue, COUNT(*) AS value FROM visible_reports WHERE received_at >= ?1 GROUP BY aggregateDate, source
113
+ UNION ALL SELECT substr(received_at,1,10), 'reports_received', 'reason', reason_code, COUNT(*) FROM visible_reports WHERE received_at >= ?1 GROUP BY substr(received_at,1,10), reason_code
114
+ UNION ALL SELECT substr(d.created_at,1,10), 'decisions', 'maker_type', d.maker_type, COUNT(*) FROM decisions d JOIN visible_reports r ON r.id=d.report_id WHERE d.created_at >= ?1 GROUP BY substr(d.created_at,1,10), d.maker_type
115
+ UNION ALL SELECT substr(d.created_at,1,10), 'decisions', 'outcome', d.decision_code, COUNT(*) FROM decisions d JOIN visible_reports r ON r.id=d.report_id WHERE d.created_at >= ?1 GROUP BY substr(d.created_at,1,10), d.decision_code
116
+ ORDER BY 1,2,3,4 LIMIT 10000`).all<Record<string, unknown>>(),
117
+ query(`SELECT CAST((julianday(resolved_at)-julianday(received_at))*86400 AS INTEGER) AS seconds FROM visible_reports WHERE resolved_at IS NOT NULL AND received_at >= ?1 ORDER BY seconds LIMIT 10000`).all<{ seconds: number }>(),
118
+ // Backlog is current, irrespective of the selected reporting period.
119
+ db.prepare(`${visible} SELECT queue_id AS queueId, (SELECT name FROM queue_definitions WHERE id=queue_id) AS queueName, state, COUNT(*) AS count, CAST(MAX((julianday(?1)-julianday(received_at))*86400) AS INTEGER) AS oldestAgeSeconds
120
+ FROM visible_reports WHERE state IN ('received','human_review','ai_review','awaiting_reporter','human_review_requested','appealed') GROUP BY queue_id,state ORDER BY queue_id,state`).bind(generatedAt, scope).all<Record<string, unknown>>(),
121
+ query(`SELECT COUNT(*) AS receivedCases,
122
+ COALESCE(SUM(EXISTS(SELECT 1 FROM findings f WHERE f.report_id=r.id AND f.status='available' AND (f.expires_at IS NULL OR f.expires_at > ?3))),0) AS withRetrievedEvidence,
123
+ COALESCE(SUM(EXISTS(SELECT 1 FROM findings f WHERE f.report_id=r.id AND (f.status IN ('unavailable','invalid','stale') OR (f.status='available' AND f.expires_at <= ?3)))),0) AS withEvidenceGaps,
124
+ COALESCE(SUM(EXISTS(SELECT 1 FROM findings f WHERE f.report_id=r.id AND f.status='available' AND json_array_length(f.uncertainty_json)>0)),0) AS withRecordedUncertainty
125
+ FROM visible_reports r WHERE received_at >= ?1`).bind(from, scope, generatedAt).first<Record<string, number>>(),
126
+ query(`SELECT 'playbook' AS pipeline, CASE WHEN a.accepted_at IS NOT NULL AND a.delivery_terminal = 0 THEN 'awaiting_confirmation' ELSE a.state END AS state, COUNT(*) AS count FROM action_proposals a JOIN visible_reports r ON r.id=a.report_id WHERE a.created_at >= ?1 GROUP BY 2
127
+ UNION ALL SELECT 'legacy', a.status, COUNT(*) FROM decision_action_outbox a JOIN visible_reports r ON r.id=a.report_id WHERE a.created_at >= ?1 GROUP BY a.status`).all<Record<string, unknown>>(),
128
+ query(`SELECT n.audience, n.delivery_state AS state, COUNT(*) AS count FROM notices n JOIN visible_reports r ON r.id=n.report_id WHERE n.created_at >= ?1 GROUP BY n.audience,n.delivery_state`).all<Record<string, unknown>>(),
129
+ query(`SELECT a.state, COUNT(*) AS count FROM appeals a JOIN visible_reports r ON r.id=a.report_id WHERE a.submitted_at >= ?1 GROUP BY a.state`).all<Record<string, unknown>>(),
130
+ query(`SELECT s.sample_reason AS reason, COUNT(*) AS selected, SUM(EXISTS(SELECT 1 FROM quality_reviews q WHERE q.sample_id=s.id)) AS reviewed FROM ai_quality_samples s JOIN visible_reports r ON r.id=s.report_id WHERE s.selected_at >= ?1 GROUP BY s.sample_reason`).all<Record<string, unknown>>(),
135
131
  ]);
136
- const seconds = durations.results.map((row) => row.seconds).filter((value) => Number.isFinite(value));
132
+ const seconds = durations.results.map(row => row.seconds).filter(value => Number.isFinite(value) && value >= 0);
137
133
  return {
138
- generatedAt,
139
- fromDate,
140
- days: boundedDays,
141
- series: series.results,
142
- backlog: backlog.results,
143
- resolutionSeconds: {
144
- count: seconds.length,
145
- median: percentile(seconds, 0.5),
146
- p90: percentile(seconds, 0.9),
147
- p95: percentile(seconds, 0.95),
148
- },
149
- aiUsage: aiUsage.results,
134
+ generatedAt, fromDate, days: boundedDays, queueScope,
135
+ series: series.results, backlog: backlog.results,
136
+ resolutionSeconds: { count: seconds.length, median: percentile(seconds,0.5), p90: percentile(seconds,0.9), p95: percentile(seconds,0.95) },
137
+ evidenceCoverage: evidence, actions: actions.results, notices: notices.results, appeals: appeals.results, audits: audits.results,
150
138
  limitations: [
151
- "Counts describe reports and decisions, not verified real-world incidents.",
152
- "No rate denominator is calculated unless the customer supplies one.",
139
+ "Counts describe recorded cases and decisions, not verified real-world incidents.",
140
+ "Evidence coverage counts stored, available findings; it does not establish that an allegation is true.",
141
+ "Delivered notices were handed to a delivery provider; recipient reading is not measured.",
142
+ "Appeal outcomes and quality samples describe reviewed work, not an overall accuracy score.",
143
+ ...(queueScope !== null ? ["Only cases in your current queue scope are included."] : []),
153
144
  ...(durations.results.length >= 10000 ? ["Resolution percentiles are bounded to the first 10,000 records in the selected period."] : []),
145
+ ...(series.results.length >= 10000 ? ["Daily breakdowns are limited to 10,000 rows; narrow the period for a complete breakdown."] : []),
154
146
  ],
155
147
  };
156
148
  }
@@ -179,6 +171,7 @@ async function anonymizeReport(
179
171
  ]);
180
172
  if (scope === "all_permitted_data") {
181
173
  await db.batch([
174
+ db.prepare(`UPDATE report_handoffs SET note = '[removed by retention]', redacted_at = COALESCE(redacted_at, ?2) WHERE report_id = ?1`).bind(reportId, at),
182
175
  db.prepare(`UPDATE case_messages SET body = '[removed by retention]', sender_id = 'redacted', redacted_at = COALESCE(redacted_at, ?2) WHERE report_id = ?1`).bind(reportId, at),
183
176
  db.prepare(`
184
177
  UPDATE report_targets SET target_reference = 'redacted:' || id, owner_reference = NULL,
@@ -189,7 +182,7 @@ async function anonymizeReport(
189
182
  db.prepare(`UPDATE decisions SET rationale = '[removed by retention]', evidence_references_json = '[]', sensitive_redacted_at = ?2 WHERE report_id = ?1 AND sensitive_redacted_at IS NULL`).bind(reportId, at),
190
183
  db.prepare(`UPDATE notices SET rendered_body = '[removed by retention]', redacted_at = ?2 WHERE report_id = ?1 AND redacted_at IS NULL`).bind(reportId, at),
191
184
  db.prepare(`
192
- UPDATE appeal_decisions SET rationale = '[removed by retention]', rationale_redacted_at = ?2
185
+ UPDATE appeal_decisions SET rationale = '[removed by retention]', rationale_redacted_at = ?2, correction_reference = NULL, correction_note = NULL
193
186
  WHERE appeal_id IN (SELECT id FROM appeals WHERE report_id = ?1) AND rationale_redacted_at IS NULL
194
187
  `).bind(reportId, at),
195
188
  db.prepare(`
@@ -249,6 +242,10 @@ export async function runScheduledRetention(db: D1Database, messageRetentionDays
249
242
  SELECT 1 FROM legal_holds h WHERE h.report_id = notices.report_id AND h.state = 'active'
250
243
  )
251
244
  `).bind(messageCutoff, startedAt).run();
245
+ await db.prepare(`UPDATE report_handoffs SET note = '[removed by retention]', redacted_at = ?2
246
+ WHERE redacted_at IS NULL AND created_at < ?1 AND NOT EXISTS (
247
+ SELECT 1 FROM legal_holds h WHERE h.report_id = report_handoffs.report_id AND h.state = 'active'
248
+ )`).bind(messageCutoff, startedAt).run();
252
249
  const candidates = await db.prepare(`
253
250
  SELECT id FROM reports r
254
251
  WHERE r.updated_at < ?1 AND r.state IN ('resolved_by_human', 'resolved_by_ai', 'closed')
@@ -41,13 +41,48 @@ export function apiErrorResponse(error: unknown): Response {
41
41
  return json({ error: { code: "internal_error", message: "The request could not be completed." } }, { status: 500 });
42
42
  }
43
43
 
44
+ export async function readBoundedBytes(
45
+ body: ReadableStream<Uint8Array> | null,
46
+ maximumBytes: number,
47
+ tooLarge: () => Error,
48
+ ): Promise<Uint8Array> {
49
+ if (!body) return new Uint8Array();
50
+ const reader = body.getReader();
51
+ const chunks: Uint8Array[] = [];
52
+ let size = 0;
53
+ try {
54
+ while (true) {
55
+ const { done, value } = await reader.read();
56
+ if (done) break;
57
+ size += value.byteLength;
58
+ if (size > maximumBytes) {
59
+ await reader.cancel("body size limit exceeded").catch(() => undefined);
60
+ throw tooLarge();
61
+ }
62
+ chunks.push(value);
63
+ }
64
+ } finally {
65
+ reader.releaseLock();
66
+ }
67
+ const bytes = new Uint8Array(size);
68
+ let offset = 0;
69
+ for (const chunk of chunks) {
70
+ bytes.set(chunk, offset);
71
+ offset += chunk.byteLength;
72
+ }
73
+ return bytes;
74
+ }
75
+
44
76
  export async function readJsonObject(request: Request, maximumBytes = 64 * 1024): Promise<Record<string, unknown>> {
45
77
  const contentType = request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
46
78
  if (contentType !== "application/json") throw new ApiError(415, "unsupported_media_type", "Content-Type must be application/json.");
47
79
  const declared = Number.parseInt(request.headers.get("content-length") ?? "0", 10);
48
80
  if (Number.isFinite(declared) && declared > maximumBytes) throw new ApiError(413, "request_too_large", "The request body is too large.");
49
- const bytes = new Uint8Array(await request.arrayBuffer());
50
- if (bytes.byteLength > maximumBytes) throw new ApiError(413, "request_too_large", "The request body is too large.");
81
+ const bytes = await readBoundedBytes(
82
+ request.body,
83
+ maximumBytes,
84
+ () => new ApiError(413, "request_too_large", "The request body is too large."),
85
+ );
51
86
  let value: unknown;
52
87
  try {
53
88
  value = JSON.parse(new TextDecoder().decode(bytes));
@@ -182,16 +182,17 @@ export async function recordDeadLetter(
182
182
  db.prepare(`
183
183
  UPDATE workflow_dispatch_outbox
184
184
  SET state = 'dead_letter', lease_expires_at = NULL,
185
- last_error_code = 'queue_retries_exhausted', updated_at = ?2
185
+ last_error_code = COALESCE(last_error_code, 'queue_retries_exhausted'), updated_at = ?2
186
186
  WHERE id = ?1 AND state != 'delivered'
187
187
  `).bind(job.outboxId, createdAt),
188
188
  db.prepare(`
189
189
  UPDATE workflow_runs
190
190
  SET state = 'repair_required', error_code = 'workflow_dispatch_queue_retries_exhausted',
191
- error_summary = 'Workflow dispatch exhausted infrastructure Queue retries.',
192
- updated_at = ?2, revision = revision + 1
191
+ error_summary = 'Workflow dispatch exhausted infrastructure Queue retries. Last error: '
192
+ || COALESCE((SELECT last_error_code FROM workflow_dispatch_outbox WHERE id = ?2), 'unknown'),
193
+ updated_at = ?3, revision = revision + 1
193
194
  WHERE id = ?1 AND state IN ('created','dispatch_pending','queued')
194
- `).bind(job.runId, createdAt),
195
+ `).bind(job.runId, job.outboxId, createdAt),
195
196
  auditEvent(db, {
196
197
  idempotencyKey: `dead-letter:${fingerprint}`,
197
198
  targetType: "workflow_run",
@@ -216,60 +217,21 @@ export async function recordDeadLetter(
216
217
  createdAt,
217
218
  }),
218
219
  );
219
- } else if (job?.type === "deliver_notification") {
220
- statements.push(
221
- db.prepare(`
222
- UPDATE notification_outbox
223
- SET status = 'failed', terminal = 1, lease_expires_at = NULL,
224
- last_error_code = 'queue_retries_exhausted', updated_at = ?2
225
- WHERE id = ?1 AND terminal = 0
226
- `).bind(job.outboxId, createdAt),
227
- db.prepare(`
228
- UPDATE notices SET delivery_state = 'failed', updated_at = ?2
229
- WHERE id = (SELECT notice_id FROM notification_outbox WHERE id = ?1)
230
- `).bind(job.outboxId, createdAt),
231
- db.prepare(`
232
- UPDATE case_messages SET delivery_state = 'failed'
233
- WHERE id = (
234
- SELECT n.message_id FROM notices n
235
- JOIN notification_outbox o ON o.notice_id = n.id
236
- WHERE o.id = ?1
237
- )
238
- `).bind(job.outboxId),
239
- auditEvent(db, {
240
- idempotencyKey: `dead-letter:${fingerprint}`,
241
- targetType: "notification",
242
- targetId: job.outboxId,
243
- details: { sourceQueue, errorCode: "queue_retries_exhausted" },
244
- createdAt,
245
- }),
246
- );
247
- } else if (job?.type === "deliver_email") {
248
- statements.push(
249
- db.prepare(`
250
- UPDATE email_deliveries SET state = 'failed',
251
- last_error_code = 'queue_retries_exhausted', updated_at = ?2
252
- WHERE id = ?1 AND state != 'delivered'
253
- `).bind(job.outboxId, createdAt),
254
- db.prepare(`
255
- UPDATE case_messages SET delivery_state = 'failed'
256
- WHERE id = (SELECT message_id FROM email_deliveries WHERE id = ?1)
257
- AND delivery_state != 'delivered'
258
- `).bind(job.outboxId),
259
- auditEvent(db, {
260
- idempotencyKey: `dead-letter:${fingerprint}`,
261
- targetType: "email_delivery",
262
- targetId: job.outboxId,
263
- details: { sourceQueue, errorCode: "queue_retries_exhausted" },
264
- createdAt,
265
- }),
266
- );
220
+ } else if (job?.type === "deliver_notification" || job?.type === "deliver_email") {
221
+ // Queue messages may arrive after an operator retry or a confirmed handoff.
222
+ // The outbox's bounded attempts govern delivery; DLQ cannot replace a receipt.
223
+ statements.push(job.type === "deliver_notification"
224
+ ? db.prepare(`UPDATE notification_outbox SET last_error_code = 'queue_retries_exhausted'
225
+ WHERE id = ?1 AND terminal = 0 AND status IN ('pending','failed')`).bind(job.outboxId)
226
+ : db.prepare(`UPDATE email_deliveries SET last_error_code = 'queue_retries_exhausted'
227
+ WHERE id = ?1 AND (state = 'pending' OR (state = 'failed' AND next_attempt_at IS NOT NULL))`).bind(job.outboxId));
267
228
  } else if (job?.type === "apply_action_proposal") {
268
229
  statements.push(
269
230
  db.prepare(`
270
231
  UPDATE action_proposals SET state = 'failed', delivery_terminal = 1,
271
232
  lease_expires_at = NULL, last_error_code = 'queue_retries_exhausted', updated_at = ?2
272
- WHERE id = ?1 AND state != 'applied'
233
+ WHERE id = ?1 AND delivery_terminal = 0 AND accepted_at IS NULL
234
+ AND (state IN ('queued','failed') OR (state = 'applying' AND lease_expires_at <= ?2))
273
235
  `).bind(job.proposalId, createdAt),
274
236
  auditEvent(db, {
275
237
  idempotencyKey: `dead-letter:${fingerprint}`,
@@ -566,6 +528,7 @@ export async function retryOperationsIncident(
566
528
  let entityType: string;
567
529
  let entityId: string;
568
530
  let repair: D1PreparedStatement;
531
+ let relatedRepairs: D1PreparedStatement[] = [];
569
532
  if (item.jobType === "route_report" || item.jobType === "process_ai_report") {
570
533
  if (!item.jobId) throw new ApiError(409, "operations_repair_reference_missing", "The background job reference is missing.");
571
534
  entityType = "background_job"; entityId = item.jobId;
@@ -582,29 +545,29 @@ export async function retryOperationsIncident(
582
545
  entityType = "workflow_dispatch_outbox"; entityId = item.outboxId;
583
546
  repair = db.prepare(`UPDATE workflow_dispatch_outbox SET state = 'pending', attempt_count = 0, available_at = ?2, lease_expires_at = NULL, last_error_code = NULL, updated_at = ?2 WHERE id = ?1`)
584
547
  .bind(entityId, timestamp);
585
- } else if (item.jobType === "deliver_action" || item.jobType === "deliver_notification") {
548
+ relatedRepairs = [db.prepare(`
549
+ UPDATE workflow_runs SET state = 'dispatch_pending', cloudflare_instance_id = NULL,
550
+ error_code = NULL, error_summary = NULL,
551
+ updated_at = ?2, revision = revision + 1
552
+ WHERE id = (SELECT run_id FROM workflow_dispatch_outbox WHERE id = ?1)
553
+ AND state = 'repair_required'
554
+ `).bind(entityId, timestamp)];
555
+ } else if (item.jobType === "deliver_notification" || item.jobType === "deliver_email") {
556
+ throw new ApiError(409, "notice_retry_requires_case_review", "Open this case’s Outcome section to inspect the original participant notice and retry its delivery.");
557
+ } else if (item.jobType === "deliver_action") {
586
558
  if (!item.outboxId) throw new ApiError(409, "operations_repair_reference_missing", "The delivery outbox reference is missing.");
587
- entityType = item.jobType === "deliver_action" ? "decision_action_outbox" : "notification_outbox";
588
- entityId = item.outboxId;
589
- const table = item.jobType === "deliver_action" ? "decision_action_outbox" : "notification_outbox";
590
- repair = db.prepare(`UPDATE ${table} SET status = 'pending', terminal = 0, attempt_count = 0, next_attempt_at = ?2, lease_expires_at = NULL, last_error_code = NULL, updated_at = ?2 WHERE id = ?1`)
591
- .bind(entityId, timestamp);
592
- } else if (item.jobType === "deliver_email") {
593
- if (!item.outboxId) throw new ApiError(409, "operations_repair_reference_missing", "The email delivery reference is missing.");
594
- entityType = "email_delivery"; entityId = item.outboxId;
595
- repair = db.prepare(`UPDATE email_deliveries SET state = 'pending', attempt_count = 0, next_attempt_at = ?2, last_error_code = NULL, updated_at = ?2 WHERE id = ?1`)
559
+ entityType = "decision_action_outbox"; entityId = item.outboxId;
560
+ repair = db.prepare(`UPDATE decision_action_outbox SET status = 'pending', terminal = 0, attempt_count = 0, next_attempt_at = ?2, lease_expires_at = NULL, last_error_code = NULL, updated_at = ?2 WHERE id = ?1`)
596
561
  .bind(entityId, timestamp);
597
562
  } else if (item.jobType === "apply_action_proposal") {
598
- if (!item.jobId?.startsWith("action-proposal:")) throw new ApiError(409, "operations_repair_reference_missing", "The action proposal reference is missing.");
599
- entityType = "action_proposal"; entityId = item.jobId.slice("action-proposal:".length);
600
- repair = db.prepare(`UPDATE action_proposals SET state = 'queued', delivery_terminal = 0, delivery_attempt_count = 0, next_attempt_at = ?2, lease_expires_at = NULL, last_error_code = NULL, updated_at = ?2 WHERE id = ?1 AND state != 'applied'`)
601
- .bind(entityId, timestamp);
563
+ throw new ApiError(409, "action_retry_requires_case_review", "Open this case’s Outcome section to inspect the customer receipt and retry the same approved action.");
602
564
  } else {
603
565
  throw new ApiError(409, "operations_incident_not_repairable", "This incident cannot be repaired automatically.");
604
566
  }
605
567
  const repairActionId = crypto.randomUUID();
606
568
  await db.batch([
607
569
  repair,
570
+ ...relatedRepairs,
608
571
  db.prepare(`INSERT INTO repair_actions (id, incident_id, action_type, entity_type, entity_id, operation_key, state, before_json, after_json, planned_by, planned_at, applied_at) VALUES (?1, ?2, 'retry_authoritative_record', ?3, ?4, ?5, 'applied', ?6, ?7, ?8, ?9, ?9)`)
609
572
  .bind(repairActionId, incidentId, entityType, entityId, key, canonicalJson({ deadLetterId: item.id, state: "dead_letter" }), canonicalJson({ state: "pending", automaticAttemptsReset: true }), session.actor.id, timestamp),
610
573
  db.prepare(`UPDATE operations_incidents SET state = 'acknowledged', acknowledged_by = ?2, acknowledged_at = COALESCE(acknowledged_at, ?3) WHERE id = ?1`).bind(incidentId, session.actor.id, timestamp),
@@ -1,5 +1,5 @@
1
1
  import { canonicalJson } from "./audit";
2
- import { ApiError } from "./report-http";
2
+ import { ApiError, readBoundedBytes } from "./report-http";
3
3
  import type { OperatorRole, OperatorSession } from "./report-types";
4
4
 
5
5
  const encoder = new TextEncoder();
@@ -782,11 +782,12 @@ async function boundedProfilePicture(request: Request): Promise<{ bytes: Uint8Ar
782
782
  const declaredType = request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
783
783
  const extension = profilePictureExtension(declaredType);
784
784
  if (!extension) throw new ApiError(415, "unsupported_profile_picture", "Use a JPEG, PNG, or WebP profile picture.");
785
- const bytes = new Uint8Array(await request.arrayBuffer());
786
- if (!bytes.length || bytes.length > PROFILE_PICTURE_MAX_BYTES) {
787
- throw new ApiError(bytes.length ? 413 : 400, bytes.length ? "profile_picture_too_large" : "profile_picture_empty",
788
- bytes.length ? "Profile pictures must be 2 MB or smaller." : "Choose a profile picture to upload.");
789
- }
785
+ const bytes = await readBoundedBytes(
786
+ request.body,
787
+ PROFILE_PICTURE_MAX_BYTES,
788
+ () => new ApiError(413, "profile_picture_too_large", "Profile pictures must be 2 MB or smaller."),
789
+ );
790
+ if (!bytes.length) throw new ApiError(400, "profile_picture_empty", "Choose a profile picture to upload.");
790
791
  if (detectProfilePictureContentType(bytes) !== declaredType) {
791
792
  throw new ApiError(400, "profile_picture_type_mismatch", "The selected file does not match its image type.");
792
793
  }
@@ -0,0 +1,64 @@
1
+ import { canonicalJson } from "./audit";
2
+ import { ApiError } from "./report-http";
3
+ import { assertOperatorReportAccess } from "./operator-scope";
4
+ import type { OperatorSession } from "./report-types";
5
+
6
+ // Matches operatorAuthorization's role and queue-scope union. Reused in the
7
+ // write predicate so a concurrent suspension/scope change cannot admit a transfer.
8
+ const eligibleOwner = `u.status = 'active' AND (
9
+ EXISTS (SELECT 1 FROM json_each(u.roles_json) WHERE value = 'owner') OR (
10
+ (EXISTS (SELECT 1 FROM role_bindings b WHERE b.installation_id = 'default' AND b.principal_type = 'operator_user' AND b.principal_id = u.id AND b.revoked_at IS NULL AND b.role IN ('administrator','reviewer'))
11
+ OR (NOT EXISTS (SELECT 1 FROM role_bindings b WHERE b.installation_id = 'default' AND b.principal_type = 'operator_user' AND b.principal_id = u.id AND b.revoked_at IS NULL)
12
+ AND EXISTS (SELECT 1 FROM json_each(u.roles_json) WHERE value IN ('administrator','reviewer'))))
13
+ AND (NOT EXISTS (SELECT 1 FROM role_bindings b WHERE b.installation_id = 'default' AND b.principal_type = 'operator_user' AND b.principal_id = u.id AND b.revoked_at IS NULL)
14
+ OR EXISTS (SELECT 1 FROM role_bindings b WHERE b.installation_id = 'default' AND b.principal_type = 'operator_user' AND b.principal_id = u.id AND b.revoked_at IS NULL
15
+ AND (json_array_length(b.queue_scope_json) = 0 OR r.queue_id IN (SELECT value FROM json_each(b.queue_scope_json)))))
16
+ ))`;
17
+
18
+ export async function eligibleReportOwners(db: D1Database, reportId: string): Promise<{ id: string; displayName: string }[]> {
19
+ const result = await db.prepare(`SELECT u.id, u.display_name AS displayName FROM operator_users u
20
+ JOIN reports r ON r.id = ?1 WHERE ${eligibleOwner} ORDER BY u.display_name, u.id LIMIT 500`).bind(reportId).all<{ id: string; displayName: string }>();
21
+ return result.results;
22
+ }
23
+
24
+ export async function changeReportOwner(db: D1Database, reportId: string, session: OperatorSession, input: {
25
+ reviewerId: string | null; version: number; note: string;
26
+ }): Promise<void> {
27
+ if (!session.permissions.reassignReports) throw new ApiError(403, "assignment_denied", "Your role cannot change case ownership.");
28
+ await assertOperatorReportAccess(db, session, reportId);
29
+ if (!Number.isSafeInteger(input.version) || input.version < 1 || typeof input.note !== "string" || !input.note.trim() || input.note.trim().length > 4000
30
+ || (input.reviewerId !== null && (typeof input.reviewerId !== "string" || !input.reviewerId || input.reviewerId.length > 200))) {
31
+ throw new ApiError(400, "handoff_invalid", "Choose a reviewer and write a handoff note of 1 to 4,000 characters.");
32
+ }
33
+ const assignment = await db.prepare("SELECT reviewer_id AS reviewerId, version FROM review_claims WHERE report_id = ?1").bind(reportId).first<{ reviewerId: string; version: number }>();
34
+ if (!assignment || assignment.version !== input.version || (assignment.reviewerId !== session.actor.id && !session.permissions.manageConfiguration)) {
35
+ throw new ApiError(409, "assignment_changed", "Case ownership changed. Refresh the case before returning or transferring it.");
36
+ }
37
+ if (input.reviewerId && (input.reviewerId === assignment.reviewerId || !(await eligibleReportOwners(db, reportId)).some(person => person.id === input.reviewerId))) {
38
+ throw new ApiError(400, "reviewer_ineligible", "Choose a different active reviewer who can access this queue.");
39
+ }
40
+ const id = crypto.randomUUID(), timestamp = new Date().toISOString();
41
+ const gate = "EXISTS (SELECT 1 FROM report_handoffs WHERE id = ?1)";
42
+ const writes = await db.batch([
43
+ db.prepare(`INSERT INTO report_handoffs (id,report_id,from_reviewer_id,to_reviewer_id,actor_id,note,created_at)
44
+ SELECT ?1,r.id,c.reviewer_id,?2,?3,?4,?5 FROM reports r JOIN review_claims c ON c.report_id = r.id
45
+ WHERE r.id = ?6 AND c.version = ?7 AND c.reviewer_id = ?8
46
+ AND r.state IN ('human_review','human_review_requested','awaiting_reporter')
47
+ AND (?9 = 1 OR r.queue_id IN (SELECT value FROM json_each(?10)))
48
+ AND (?2 IS NULL OR EXISTS (SELECT 1 FROM operator_users u WHERE u.id = ?2 AND ${eligibleOwner}))`)
49
+ .bind(id,input.reviewerId,session.actor.id,input.note.trim(),timestamp,reportId,input.version,assignment.reviewerId,session.queueScope == null ? 1 : 0,canonicalJson(session.queueScope ?? [])),
50
+ input.reviewerId
51
+ ? db.prepare(`UPDATE review_claims SET reviewer_id = ?2, claimed_at = ?3, expires_at = '1970-01-01T00:00:00.000Z', version = version + 1 WHERE report_id = ?4 AND ${gate}`).bind(id,input.reviewerId,timestamp,reportId)
52
+ : db.prepare(`DELETE FROM review_claims WHERE report_id = ?2 AND ${gate}`).bind(id,reportId),
53
+ db.prepare(`UPDATE human_task_claims SET released_at = ?2, release_reason = 'case_handoff' WHERE operator_id = ?3 AND released_at IS NULL
54
+ AND task_id IN (SELECT id FROM human_tasks WHERE report_id = ?4 AND appeal_id IS NULL AND state IN ('open','claimed')) AND ${gate}`)
55
+ .bind(id,timestamp,assignment.reviewerId,reportId),
56
+ db.prepare(`UPDATE human_tasks SET state = 'open', assigned_operator_id = NULL, updated_at = ?2
57
+ WHERE report_id = ?3 AND appeal_id IS NULL AND assigned_operator_id = ?4 AND state IN ('open','claimed') AND ${gate}`)
58
+ .bind(id,timestamp,reportId,assignment.reviewerId),
59
+ db.prepare(`INSERT INTO audit_events (id,idempotency_key,action,actor_type,actor_id,target_type,target_id,details_json,created_at)
60
+ SELECT ?1,?1,?2,?3,?4,'report',?5,?6,?7 WHERE ${gate}`)
61
+ .bind(id,input.reviewerId ? "report.transferred" : "report.returned_to_queue",session.actor.type,session.actor.id,reportId,canonicalJson({ fromReviewerId:assignment.reviewerId,toReviewerId:input.reviewerId,handoffId:id,version:input.version + 1 }),timestamp),
62
+ ]);
63
+ if (writes[0]?.meta.changes !== 1) throw new ApiError(409,"assignment_changed","Case ownership or reviewer access changed. Refresh and try again. Your note has not been shared.");
64
+ }
@@ -43,6 +43,8 @@ interface PresenceRow {
43
43
  last_seen_at: string;
44
44
  }
45
45
 
46
+ type PresenceDatabase = Pick<D1Database, "prepare" | "batch">;
47
+
46
48
  const colors = ["#315d4d", "#5d4f82", "#8a5a3b", "#2f657a", "#7a4b57", "#59683d", "#6b5635", "#3f5f88"];
47
49
  const activities = new Set<AnalystActivity>(["online", "viewing", "editing", "away"]);
48
50
  const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
@@ -129,7 +131,7 @@ export async function recordAnalystAuthentication(db: D1Database, session: Opera
129
131
  }
130
132
 
131
133
  export async function listAnalystPresence(
132
- db: D1Database,
134
+ db: PresenceDatabase,
133
135
  staleAfterSeconds = 45,
134
136
  allowedQueueIds?: string[] | null,
135
137
  ): Promise<AnalystPresence[]> {
@@ -172,7 +174,7 @@ export async function listAnalystPresence(
172
174
  }
173
175
 
174
176
  export async function touchAnalystSession(
175
- db: D1Database,
177
+ db: PresenceDatabase,
176
178
  input: {
177
179
  sessionId: string;
178
180
  actorId: string;
@@ -282,14 +284,16 @@ export class WorkspacePresence extends DurableObject<Env> {
282
284
  if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(value));
283
285
  }
284
286
 
285
- private async broadcastSnapshot(): Promise<void> {
287
+ private async broadcastSnapshot(db: PresenceDatabase = this.env.DB): Promise<void> {
286
288
  const snapshots = new Map<string, AnalystPresence[]>();
287
289
  for (const ws of this.ctx.getWebSockets()) {
288
- const scope = attachment(ws.deserializeAttachment())?.allowedQueueIds ?? [];
290
+ const current = attachment(ws.deserializeAttachment());
291
+ if (!current) continue;
292
+ const scope = current.allowedQueueIds;
289
293
  const key = canonicalJson(scope);
290
294
  let analysts = snapshots.get(key);
291
295
  if (!analysts) {
292
- analysts = await listAnalystPresence(this.env.DB, 45, scope);
296
+ analysts = await listAnalystPresence(db, 45, scope);
293
297
  snapshots.set(key, analysts);
294
298
  }
295
299
  this.send(ws, { type: "presence_snapshot", analysts, sent_at: now() });
@@ -306,7 +310,8 @@ export class WorkspacePresence extends DurableObject<Env> {
306
310
  if (!validActorId(actorId) || !uuid.test(sessionId)) {
307
311
  return new Response("Invalid presence session", { status: 400 });
308
312
  }
309
- await touchAnalystSession(this.env.DB, {
313
+ const db = this.env.DB.withSession("first-primary");
314
+ await touchAnalystSession(db, {
310
315
  sessionId, actorId, activity: "online", activeReportId: null,
311
316
  allowedQueueIds,
312
317
  claimTtlMinutes: Number.parseInt(this.env.CLAIM_TTL_MINUTES, 10) || 15,
@@ -318,7 +323,7 @@ export class WorkspacePresence extends DurableObject<Env> {
318
323
  };
319
324
  server.serializeAttachment(state);
320
325
  this.ctx.acceptWebSocket(server);
321
- await this.broadcastSnapshot();
326
+ await this.broadcastSnapshot(db);
322
327
  return new Response(null, { status: 101, webSocket: client });
323
328
  }
324
329
 
@@ -346,7 +351,8 @@ export class WorkspacePresence extends DurableObject<Env> {
346
351
  activity: message.activity,
347
352
  activeReportId: message.reportId,
348
353
  };
349
- const result = await touchAnalystSession(this.env.DB, {
354
+ const db = this.env.DB.withSession("first-primary");
355
+ const result = await touchAnalystSession(db, {
350
356
  sessionId: next.sessionId,
351
357
  actorId: next.actorId,
352
358
  activity: next.activity,
@@ -357,7 +363,7 @@ export class WorkspacePresence extends DurableObject<Env> {
357
363
  next.activeReportId = result.activeReportId;
358
364
  ws.serializeAttachment(next);
359
365
  this.send(ws, { type: "heartbeat_ack", sent_at: now(), claim_renewed: result.claimRenewed });
360
- if (message.type !== "heartbeat" || result.claimRenewed) await this.broadcastSnapshot();
366
+ if (message.type !== "heartbeat" || result.claimRenewed) await this.broadcastSnapshot(db);
361
367
  }
362
368
 
363
369
  async webSocketClose(ws: WebSocket): Promise<void> {
@@ -353,6 +353,10 @@ export async function createReport(
353
353
  INSERT INTO report_participants (id, report_id, audience, reference, contact_mode, contact_ciphertext, created_at)
354
354
  VALUES (?1, ?2, 'reporter', ?3, ?4, ?5, ?6)
355
355
  `).bind(reporterParticipantId, reportId, submission.reporter.reference ?? null, submission.reporter.contactMode, contactCiphertext, receivedAt),
356
+ db.prepare(`INSERT INTO report_participants (id, report_id, audience, reference, contact_mode, created_at)
357
+ SELECT ?1, ?2, 'affected_user', ?3, 'customer_notification', ?4
358
+ WHERE ?3 IS NOT NULL AND ?5 IN ('server_api','signed_widget')`)
359
+ .bind(crypto.randomUUID(), reportId, submission.target.ownerReference ?? null, receivedAt, submission.source),
356
360
  db.prepare(`
357
361
  INSERT INTO report_targets (
358
362
  id, report_id, target_type, target_reference, owner_reference, customer_url,
@@ -521,11 +525,11 @@ export async function createReport(
521
525
  export async function markJobEnqueued(db: D1Database, jobId: string): Promise<void> {
522
526
  await db.prepare(`
523
527
  UPDATE background_jobs SET state = 'enqueued', last_error_code = NULL, updated_at = ?2
524
- WHERE id = ?1 AND state IN ('pending', 'failed')
528
+ WHERE id = ?1 AND state IN ('pending', 'failed', 'enqueued')
525
529
  `).bind(jobId, isoNow()).run();
526
530
  await db.prepare(`
527
531
  UPDATE reports SET routing_status = 'enqueued', routing_error_code = NULL, updated_at = ?2
528
- WHERE id = (SELECT report_id FROM background_jobs WHERE id = ?1) AND routing_status IN ('pending', 'failed')
532
+ WHERE id = (SELECT report_id FROM background_jobs WHERE id = ?1) AND routing_status IN ('pending', 'failed', 'enqueued')
529
533
  `).bind(jobId, isoNow()).run();
530
534
  }
531
535
 
@@ -545,13 +549,15 @@ export async function markJobEnqueueFailed(db: D1Database, jobId: string, errorC
545
549
  ]);
546
550
  }
547
551
 
552
+ // Re-send an accepted but unclaimed job after a bounded grace period. The
553
+ // consumer claims it atomically, so queue delays/restarts cannot strand intake.
548
554
  export async function pendingRoutingJobs(db: D1Database, limit = 50): Promise<Array<{ id: string; reportId: string }>> {
549
555
  const staleBefore = new Date(Date.now() - 5 * 60_000).toISOString();
550
556
  const result = await db.prepare(`
551
557
  SELECT id, report_id AS reportId
552
558
  FROM background_jobs
553
559
  WHERE job_type = 'route_report'
554
- AND (state IN ('pending', 'failed') OR (state = 'processing' AND updated_at <= ?3))
560
+ AND (state IN ('pending', 'failed') OR (state IN ('enqueued', 'processing') AND updated_at <= ?3))
555
561
  AND available_at <= ?1
556
562
  ORDER BY available_at ASC, id ASC
557
563
  LIMIT ?2
@@ -897,8 +903,7 @@ export async function listInboxReports(
897
903
  OR (r.priority = ?${priorityBinding} AND r.received_at = ?${receivedAtBinding} AND r.id > ?${idBinding})
898
904
  )`);
899
905
  }
900
- bindings.push(isoNow());
901
- const atBinding = bindings.length;
906
+ const queriedAt = isoNow();
902
907
  const limit = Math.max(1, Math.min(100, options.limit));
903
908
  bindings.push(limit + 1);
904
909
  const limitBinding = bindings.length;
@@ -911,7 +916,7 @@ export async function listInboxReports(
911
916
  p.avatar_color AS analystAvatarColor
912
917
  FROM reports r
913
918
  JOIN report_targets t ON t.report_id = r.id
914
- LEFT JOIN review_claims c ON c.report_id = r.id AND c.expires_at > ?${atBinding}
919
+ LEFT JOIN review_claims c ON c.report_id = r.id
915
920
  LEFT JOIN analyst_profiles p ON p.actor_id = c.reviewer_id
916
921
  WHERE ${clauses.join(" AND ")}
917
922
  ORDER BY r.priority DESC, r.received_at ASC, r.id ASC
@@ -930,7 +935,11 @@ export async function listInboxReports(
930
935
  receivedAt: row.receivedAt,
931
936
  updatedAt: row.updatedAt,
932
937
  dueAt: row.dueAt,
933
- claim: row.claimReviewerId && row.claimedAt && row.claimExpiresAt ? {
938
+ claim: row.claimReviewerId && row.claimedAt && row.claimExpiresAt && row.claimExpiresAt > queriedAt ? {
939
+ reviewerId: row.claimReviewerId, claimedAt: row.claimedAt, expiresAt: row.claimExpiresAt,
940
+ analyst: { displayName: row.analystDisplayName ?? row.claimReviewerId, avatarUrl: row.analystAvatarUrl, avatarColor: row.analystAvatarColor ?? analystAvatarColor(row.claimReviewerId) },
941
+ } : null,
942
+ assignment: row.claimReviewerId && row.claimedAt && row.claimExpiresAt ? {
934
943
  reviewerId: row.claimReviewerId,
935
944
  claimedAt: row.claimedAt,
936
945
  expiresAt: row.claimExpiresAt,