@anthusai/papyrus 2.0.0-next.2 → 2.0.0-next.21

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 (103) hide show
  1. package/amplify/data/resource.js +15 -0
  2. package/amplify/data/resource.ts +17 -0
  3. package/amplify/data/schema.js +20 -0
  4. package/amplify/data/schema.ts +22 -0
  5. package/amplify/functions/assignment-action/data-access.js +88 -0
  6. package/amplify/functions/assignment-action/data-access.ts +87 -0
  7. package/amplify/functions/content-actions/handler.py +22 -0
  8. package/amplify/functions/editorial-checks/handler.py +14 -0
  9. package/amplify/functions/editorial-checks/requirements.txt +1 -0
  10. package/amplify/functions/editorial-checks/resource.js +43 -0
  11. package/amplify/functions/editorial-checks/resource.ts +60 -0
  12. package/amplify/functions/editorial-checks/schema.js +92 -0
  13. package/amplify/functions/editorial-checks/schema.ts +94 -0
  14. package/amplify/functions/editorial-checks/wire.js +49 -0
  15. package/amplify/functions/editorial-checks/wire.ts +57 -0
  16. package/amplify/functions/model-attachment-upload/handler.ts +1 -0
  17. package/amplify/functions/monitoring-view/handler.py +11 -0
  18. package/amplify/functions/monitoring-view/resource.js +24 -0
  19. package/amplify/functions/monitoring-view/resource.ts +34 -0
  20. package/amplify/functions/monitoring-view/schema.js +16 -0
  21. package/amplify/functions/monitoring-view/schema.ts +18 -0
  22. package/amplify/functions/monitoring-view/wire.js +37 -0
  23. package/amplify/functions/monitoring-view/wire.ts +47 -0
  24. package/amplify/functions/public-forms/core.js +247 -0
  25. package/amplify/functions/public-forms/core.ts +310 -0
  26. package/amplify/functions/public-forms/handler.ts +41 -0
  27. package/amplify/functions/public-forms/origins.js +35 -0
  28. package/amplify/functions/public-forms/origins.ts +43 -0
  29. package/amplify/functions/public-forms/resource.js +9 -0
  30. package/amplify/functions/public-forms/resource.ts +10 -0
  31. package/amplify/functions/public-forms/wire.js +25 -0
  32. package/amplify/functions/public-forms/wire.ts +32 -0
  33. package/amplify/functions/shared/python-bundle.js +20 -14
  34. package/amplify/functions/shared/python-bundle.ts +25 -18
  35. package/amplify/publication/redirect-and-index.js +83 -0
  36. package/amplify/publication/redirect-rules.js +61 -0
  37. package/amplify/publication/redirect-rules.ts +79 -0
  38. package/amplify/publication/s3-projection.js +5 -1
  39. package/amplify/publication/s3-projection.ts +7 -1
  40. package/amplify/site-backend-config.ts +10 -0
  41. package/amplify/site-backend.js +31 -0
  42. package/amplify/site-backend.ts +38 -0
  43. package/app/api/newsroom/curation/context/route.ts +9 -0
  44. package/app/api/newsroom/curation/priming/route.ts +9 -0
  45. package/app/api/newsroom/curation/publication/route.ts +9 -0
  46. package/bin/papyrus-infra.mjs +20 -1
  47. package/components/editorial-checks-admin-panel.tsx +347 -0
  48. package/components/editorial-finding-card.tsx +162 -0
  49. package/components/editorial-findings-panel.tsx +91 -0
  50. package/components/editorial-preview-popover.tsx +103 -0
  51. package/components/markus-body-editor.tsx +213 -0
  52. package/components/markus-ir-preview.tsx +147 -6
  53. package/components/monitoring-overview-view.tsx +240 -0
  54. package/components/monitoring-panel.tsx +40 -0
  55. package/components/newsroom-article-editor.tsx +136 -11
  56. package/components/newsroom-board-view.tsx +6 -7
  57. package/components/newsroom-curation-bootstrap.tsx +45 -0
  58. package/components/newsroom-ops-shell.tsx +7 -3
  59. package/components/newsroom-organizer.css +74 -61
  60. package/components/newsroom-references-view.tsx +14 -14
  61. package/components/newsroom-theme-fonts/broadsheet-green.css +10 -0
  62. package/components/newsroom-theme-fonts/broadsheet-green.tsx +6 -0
  63. package/components/newsroom-theme-fonts/newspaper-gothic.css +9 -0
  64. package/components/newsroom-theme-fonts/newspaper-gothic.tsx +6 -0
  65. package/components/newsroom-theme-fonts/night-desk.css +10 -0
  66. package/components/newsroom-theme-fonts/night-desk.tsx +6 -0
  67. package/components/newsroom-theme-fonts/refined-newsprint.css +11 -0
  68. package/components/newsroom-theme-fonts/refined-newsprint.tsx +6 -0
  69. package/components/newsroom-theme.css +39 -0
  70. package/components/newsroom-theme.tsx +33 -0
  71. package/components/publication-cyclotron-panel.tsx +10 -10
  72. package/components/reference-add-entry.tsx +75 -0
  73. package/components/reference-curation-controls.tsx +30 -21
  74. package/components/reference-cyclotron-priming.tsx +4 -4
  75. package/components/reference-cyclotron-suggestion.tsx +1 -1
  76. package/components/reference-priming.tsx +14 -10
  77. package/components/reference-section-suggestion.tsx +1 -1
  78. package/components/topic-steering-workspace.tsx +27 -2
  79. package/components/use-editorial-checks.ts +133 -0
  80. package/lib/category-repository.ts +11 -9
  81. package/lib/curation-routes.ts +342 -0
  82. package/lib/editorial-checks-backend.ts +16 -0
  83. package/lib/editorial-checks-client.ts +194 -0
  84. package/lib/editorial-checks-demo.ts +147 -0
  85. package/lib/editorial-checks-settings.ts +27 -0
  86. package/lib/editorial-checks.ts +171 -0
  87. package/lib/editorial-preview.ts +228 -0
  88. package/lib/monitoring-client.ts +29 -0
  89. package/lib/monitoring-overview-fixture.ts +51 -0
  90. package/lib/monitoring-overview.ts +144 -0
  91. package/lib/newsroom-board.ts +27 -2
  92. package/lib/relevance-status.ts +2 -2
  93. package/lib/site-brand-tenant.ts +11 -6
  94. package/lib/site-brand.ts +23 -3
  95. package/package.json +47 -3
  96. package/routes.manifest.json +34 -1
  97. package/components/newsroom-fonts/playfair-display-700.ttf +0 -0
  98. package/components/newsroom-fonts/playfair-display-900.ttf +0 -0
  99. package/components/newsroom-fonts/playfair-display-OFL.txt +0 -93
  100. package/components/newsroom-fonts/plus-jakarta-sans-400.ttf +0 -0
  101. package/components/newsroom-fonts/plus-jakarta-sans-600.ttf +0 -0
  102. package/components/newsroom-fonts/plus-jakarta-sans-OFL.txt +0 -93
  103. package/components/newsroom-newsprint-board.css +0 -7
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Demo-mode editorial checks: no backend, a few stock phrases, canned rewrites.
3
+ * The shapes match Humanus results so the editor, the preview marks and the
4
+ * rewrite flow behave as they do against the real backend.
5
+ */
6
+ import type { EditorialCheckResult, EditorialFinding, EditorialSegment, RewriteResult, Span } from "./editorial-checks";
7
+ import type { EditorialChecksBackend } from "./editorial-checks-backend";
8
+ import { DEFAULT_EDITORIAL_SETTINGS } from "./editorial-checks-settings";
9
+
10
+ type DemoRule = { policyId: string; phrase: RegExp; severity: EditorialFinding["severity"]; message: string; replacement?: string };
11
+
12
+ const RULES: DemoRule[] = [
13
+ { policyId: "promotional-language", phrase: /\bgame[- ]changing\b/gi, severity: "warn", message: "Say what changed instead of calling it game-changing." },
14
+ { policyId: "plain-words", phrase: /\butilize\b/gi, severity: "info", message: "Prefer the plain word.", replacement: "use" },
15
+ { policyId: "formulaic-openers", phrase: /\bIn today's [a-z-]+ world\b/gi, severity: "info", message: "Formulaic opener: start with the point." },
16
+ ];
17
+
18
+ /** Demo rewrites keyed by a phrase in the target; anything else gets a clearly labelled placeholder. */
19
+ const CANNED: Record<string, string[]> = {
20
+ "game-changing": ["Our caching layer cuts build times for teams.", "Teams get faster builds from our caching layer."],
21
+ "Builds finish in 4 minutes": ["Builds now take 4 minutes, down from 9.", "A build takes 4 minutes instead of 9."],
22
+ };
23
+
24
+ export function demoPlainText(source: string): string {
25
+ return source
26
+ .replace(/^#{1,6}\s+/, "")
27
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
28
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
29
+ .replace(/\s?\[@[^\]]+\]/g, "")
30
+ .replace(/(\*\*|__|\*|_|~~|`)/g, "")
31
+ .replace(/\s+/g, " ")
32
+ .trim();
33
+ }
34
+
35
+ function hash(text: string): string {
36
+ let value = 0;
37
+ for (let i = 0; i < text.length; i += 1) value = (value * 31 + text.charCodeAt(i)) >>> 0;
38
+ return value.toString(16).padStart(8, "0");
39
+ }
40
+
41
+ /** Paragraph and sentence segments of a body, by blank lines and sentence-ending punctuation. */
42
+ export function demoSegments(body: string): EditorialSegment[] {
43
+ const segments: EditorialSegment[] = [{ id: "doc", kind: "document", start: 0, end: body.length, textHash: hash(body) }];
44
+ const fence = /^(```|~~~)/;
45
+ let inFence = false;
46
+ for (const match of body.matchAll(/[^\n]+(?:\n[^\n]+)*/g)) {
47
+ const raw = match[0];
48
+ const start = match.index ?? 0;
49
+ if (fence.test(raw.trim())) inFence = !inFence;
50
+ if (inFence || fence.test(raw.trim()) || /^(:::|::|>|\||---)/.test(raw.trim())) continue;
51
+ const block = raw.trim().startsWith("#") ? "heading" : /^([-*+]|\d+\.)\s/.test(raw.trim()) ? "listItem" : "paragraph";
52
+ const sourceStart = start + raw.length - raw.replace(/^(#{1,6}|[-*+]|\d+\.)\s+/, "").length;
53
+ const text = demoPlainText(raw);
54
+ const paragraphId = `p-${hash(text)}`;
55
+ segments.push({ id: paragraphId, kind: "paragraph", block, start: sourceStart, end: start + raw.length, textHash: hash(text), text });
56
+ const sentencePattern = /[^.!?]+[.!?]+(?=\s|$)|[^.!?]+$/g;
57
+ for (const sentence of body.slice(sourceStart, start + raw.length).matchAll(sentencePattern)) {
58
+ const leading = sentence[0].length - sentence[0].trimStart().length;
59
+ const sStart = sourceStart + (sentence.index ?? 0) + leading;
60
+ const sText = sentence[0].trim();
61
+ if (!sText) continue;
62
+ segments.push({
63
+ id: `s-${hash(sText)}`,
64
+ kind: "sentence",
65
+ block,
66
+ parentId: paragraphId,
67
+ start: sStart,
68
+ end: sStart + sText.length,
69
+ textHash: hash(sText),
70
+ text: demoPlainText(sText),
71
+ });
72
+ }
73
+ }
74
+ return segments;
75
+ }
76
+
77
+ export function demoCheck(body: string): EditorialCheckResult {
78
+ const segments = demoSegments(body);
79
+ const sentences = segments.filter((segment) => segment.kind === "sentence");
80
+ const findings: EditorialFinding[] = [];
81
+ for (const rule of RULES) {
82
+ for (const match of body.matchAll(rule.phrase)) {
83
+ const start = match.index ?? 0;
84
+ const end = start + match[0].length;
85
+ const sentence = sentences.find((segment) => segment.start <= start && end <= segment.end);
86
+ if (!sentence) continue;
87
+ findings.push({
88
+ id: `f-${hash(`${rule.policyId}|${sentence.text}|${match[0]}`)}${hash(String(start)).slice(0, 8)}`,
89
+ policyId: rule.policyId,
90
+ policyVersion: 1,
91
+ detectorId: `${rule.policyId}-demo`,
92
+ lane: "rules",
93
+ severity: rule.severity,
94
+ status: "violation",
95
+ segmentId: sentence.id,
96
+ span: { start, end },
97
+ excerpt: match[0],
98
+ excerptText: match[0],
99
+ message: rule.message,
100
+ ...(rule.replacement ? { replacement: rule.replacement } : {}),
101
+ });
102
+ }
103
+ }
104
+ return {
105
+ schemaVersion: 1,
106
+ offsetUnit: "utf16",
107
+ document: { hash: `demo:${hash(body)}`, length: body.length },
108
+ pack: { packId: "demo", version: "1" },
109
+ segments,
110
+ protected: [],
111
+ findings: findings.sort((a, b) => a.span.start - b.span.start),
112
+ coverage: [],
113
+ lanes: { rules: { status: "ran", detectors: RULES.length }, classifier: { status: "disabled" } },
114
+ };
115
+ }
116
+
117
+ export function demoSuggest(body: string, target: { finding: EditorialFinding } | { selection: Span }): RewriteResult {
118
+ let span: Span;
119
+ if ("finding" in target) {
120
+ const sentence = demoSegments(body).find((s) => s.kind === "sentence" && s.start <= target.finding.span.start && target.finding.span.end <= s.end);
121
+ span = sentence ? { start: sentence.start, end: sentence.end } : target.finding.span;
122
+ } else {
123
+ span = target.selection;
124
+ }
125
+ const excerpt = body.slice(span.start, span.end);
126
+ const replacements = Object.entries(CANNED).find(([phrase]) => excerpt.includes(phrase))?.[1] ?? [`${demoPlainText(excerpt)} (demo rewrite)`];
127
+ return {
128
+ target: { ...("finding" in target ? { findingId: target.finding.id } : {}), span, excerpt },
129
+ model: "demo",
130
+ options: replacements.map((replacement, index) => ({
131
+ id: `o-demo-${index}`,
132
+ span,
133
+ replacement,
134
+ rationale: index === 0 ? "Says what changed, plainly." : "An alternative phrasing.",
135
+ factVerificationRequired: false,
136
+ unresolvedQuestions: [],
137
+ })),
138
+ };
139
+ }
140
+
141
+ export const demoEditorialBackend: EditorialChecksBackend = {
142
+ loadSettings: async () => ({ settings: DEFAULT_EDITORIAL_SETTINGS, exists: false }),
143
+ dismissedFindingIds: async () => new Set(),
144
+ check: async (body) => demoCheck(body),
145
+ suggest: async (body, _section, target) => demoSuggest(body, target),
146
+ recordFeedback: async () => undefined,
147
+ };
@@ -0,0 +1,27 @@
1
+ /** Runtime settings for editorial checks, stored in EditorialCheckSettings (id "settings"). */
2
+ export type EditorialSettings = {
3
+ /** Core to every site and on by default; a publication turns its checks off here. */
4
+ enabled: boolean;
5
+ lanes: { rules: boolean; classifier: boolean };
6
+ classifierModel: string;
7
+ rewriteModel: string;
8
+ deadlineSeconds: number;
9
+ maxInputTokens: number;
10
+ maxExamplesPerQuestion: number;
11
+ guidance: string;
12
+ publishWarning: boolean;
13
+ checkWhileTyping: boolean;
14
+ };
15
+
16
+ export const DEFAULT_EDITORIAL_SETTINGS: EditorialSettings = {
17
+ enabled: true,
18
+ lanes: { rules: true, classifier: true },
19
+ classifierModel: "jev-latest",
20
+ rewriteModel: "gpt-6-luna",
21
+ deadlineSeconds: 20,
22
+ maxInputTokens: 500000,
23
+ maxExamplesPerQuestion: 4,
24
+ guidance: "",
25
+ publishWarning: true,
26
+ checkWhileTyping: true,
27
+ };
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Editorial checks: the Humanus result shapes the newsroom uses, and pure helpers
3
+ * over them. Humanus counts offsets in UTF-16 code units, which is exactly how
4
+ * JavaScript indexes strings, so spans apply to the body text as they are.
5
+ */
6
+
7
+ export type Span = { start: number; end: number };
8
+ export type Severity = "info" | "warn" | "error";
9
+
10
+ export type EditorialFinding = {
11
+ id: string;
12
+ policyId: string;
13
+ policyVersion: number;
14
+ detectorId: string;
15
+ lane: "rules" | "classifier";
16
+ severity: Severity;
17
+ status: "violation" | "review";
18
+ segmentId: string;
19
+ span: Span;
20
+ excerpt: string;
21
+ /** The excerpt as a reader sees it (inline markup removed). */
22
+ excerptText?: string;
23
+ message: string;
24
+ probability?: number;
25
+ rawProbability?: number;
26
+ replacement?: string;
27
+ };
28
+
29
+ export type EditorialSegment = {
30
+ id: string;
31
+ kind: "document" | "paragraph" | "sentence";
32
+ block?: "paragraph" | "heading" | "listItem";
33
+ parentId?: string;
34
+ start: number;
35
+ end: number;
36
+ textHash: string;
37
+ /** Plain prose of a paragraph or sentence segment. */
38
+ text?: string;
39
+ };
40
+
41
+ export type LaneStatus = { status: "ran" | "disabled" | "unavailable" | "failed" | "partial"; reason?: string; detectors?: number };
42
+
43
+ export type EditorialCheckResult = {
44
+ schemaVersion: 1;
45
+ offsetUnit: "utf16";
46
+ document: { hash: string; length: number };
47
+ pack: { packId: string; version: string };
48
+ segments: EditorialSegment[];
49
+ protected: { kind: string; start: number; end: number }[];
50
+ findings: EditorialFinding[];
51
+ coverage: unknown[];
52
+ lanes: { rules: LaneStatus; classifier: LaneStatus };
53
+ usage?: Record<string, number>;
54
+ };
55
+
56
+ export type RewriteOption = {
57
+ id: string;
58
+ span: Span;
59
+ replacement: string;
60
+ rationale: string;
61
+ factVerificationRequired: boolean;
62
+ unresolvedQuestions: string[];
63
+ };
64
+
65
+ export type RewriteResult = {
66
+ target: { findingId?: string; span: Span; excerpt: string };
67
+ model: string;
68
+ options: RewriteOption[];
69
+ dropped?: { replacement: string; reason: string }[];
70
+ };
71
+
72
+ export type FeedbackDecision = "accepted" | "fixed" | "dismissed";
73
+
74
+ export type EditorialFeedbackInput = {
75
+ itemId: string;
76
+ findingId: string;
77
+ policyId: string;
78
+ detectorId: string;
79
+ lane: EditorialFinding["lane"];
80
+ probability: number | null;
81
+ decision: FeedbackDecision;
82
+ reason: string | null;
83
+ text: string | null;
84
+ };
85
+
86
+ /** Decisions on an article that has never been saved are kept under this id. */
87
+ export const UNSAVED_ITEM_ID = "unsaved";
88
+
89
+ const SEVERITY_ORDER: Record<Severity, number> = { error: 0, warn: 1, info: 2 };
90
+
91
+ /** Findings worth showing: not dismissed, not covering the whole document, most severe first, then in reading order. */
92
+ export function visibleFindings(findings: EditorialFinding[], dismissed: ReadonlySet<string>): EditorialFinding[] {
93
+ return findings
94
+ .filter((finding) => !dismissed.has(finding.id))
95
+ .sort(
96
+ (a, b) =>
97
+ SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity] ||
98
+ a.span.start - b.span.start ||
99
+ a.policyId.localeCompare(b.policyId),
100
+ );
101
+ }
102
+
103
+ /** Findings that can be marked in the text (document-level ones have no excerpt). */
104
+ export function inlineFindings(findings: EditorialFinding[]): EditorialFinding[] {
105
+ return findings.filter((finding) => finding.excerpt.length > 0 && finding.span.end > finding.span.start);
106
+ }
107
+
108
+ export type FindingGroup = { policyId: string; severity: Severity; findings: EditorialFinding[] };
109
+
110
+ export function groupByPolicy(findings: EditorialFinding[]): FindingGroup[] {
111
+ const groups = new Map<string, FindingGroup>();
112
+ for (const finding of findings) {
113
+ const group = groups.get(finding.policyId) ?? { policyId: finding.policyId, severity: finding.severity, findings: [] };
114
+ group.findings.push(finding);
115
+ if (SEVERITY_ORDER[finding.severity] < SEVERITY_ORDER[group.severity]) group.severity = finding.severity;
116
+ groups.set(finding.policyId, group);
117
+ }
118
+ return [...groups.values()].sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity] || a.policyId.localeCompare(b.policyId));
119
+ }
120
+
121
+ /** Open findings that should make an editor pause before publishing (never a block). */
122
+ export function publishWarnings(findings: EditorialFinding[], dismissed: ReadonlySet<string>): EditorialFinding[] {
123
+ return visibleFindings(findings, dismissed).filter((finding) => finding.severity !== "info" && finding.status === "violation");
124
+ }
125
+
126
+ /** The text of the segment a finding sits in, which becomes a few-shot example for the classifier. */
127
+ export function findingSegmentText(result: EditorialCheckResult, body: string, finding: EditorialFinding): string | null {
128
+ const segment = result.segments.find((candidate) => candidate.id === finding.segmentId);
129
+ if (!segment || segment.kind === "document") return null;
130
+ return body.slice(segment.start, segment.end);
131
+ }
132
+
133
+ export function feedbackFor(
134
+ result: EditorialCheckResult,
135
+ body: string,
136
+ finding: EditorialFinding,
137
+ decision: FeedbackDecision,
138
+ itemId: string | null,
139
+ reason: string | null = null,
140
+ ): EditorialFeedbackInput {
141
+ return {
142
+ itemId: itemId ?? UNSAVED_ITEM_ID,
143
+ findingId: finding.id,
144
+ policyId: finding.policyId,
145
+ detectorId: finding.detectorId,
146
+ lane: finding.lane,
147
+ probability: finding.rawProbability ?? finding.probability ?? null,
148
+ decision,
149
+ reason: reason?.trim() ? reason.trim() : null,
150
+ text: finding.lane === "classifier" ? findingSegmentText(result, body, finding) : null,
151
+ };
152
+ }
153
+
154
+ /** Replace one span of the body; the span must still hold the text it was computed for. */
155
+ export function applyReplacement(body: string, span: Span, expected: string, replacement: string): string | null {
156
+ if (body.slice(span.start, span.end) !== expected) return null;
157
+ return body.slice(0, span.start) + replacement + body.slice(span.end);
158
+ }
159
+
160
+ export function describeProbability(finding: EditorialFinding): string | null {
161
+ if (finding.probability === undefined) return null;
162
+ return `${Math.round(finding.probability * 100)}% sure`;
163
+ }
164
+
165
+ export function laneNotice(result: EditorialCheckResult): string | null {
166
+ const classifier = result.lanes.classifier;
167
+ if (classifier.status === "partial") return `Some sentences were not judged: ${classifier.reason ?? "the check ran out of time"}.`;
168
+ if (classifier.status === "failed") return `The judgment checks failed: ${classifier.reason ?? "unknown error"}. Rule checks still ran.`;
169
+ if (classifier.status === "unavailable" && (classifier.detectors ?? 0) === 0 && classifier.reason) return `Judgment checks are not configured: ${classifier.reason}.`;
170
+ return null;
171
+ }
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Places Humanus findings on the rendered Markus preview.
3
+ *
4
+ * Humanus reports spans in the markup; the preview renders an IR tree with no
5
+ * character offsets. Both sides agree on the words a reader sees, so findings
6
+ * are placed by text: each Humanus paragraph is matched, in document order, to
7
+ * the rendered prose block with the same words, and each finding's plain
8
+ * excerpt is located inside that block. Whitespace is ignored while matching,
9
+ * because rendering and Humanus collapse it differently (citations, breaks).
10
+ *
11
+ * "Rendered text" is defined by `inlineLeaves`, which the preview renderer also
12
+ * uses, so offsets computed here are offsets the renderer can split on.
13
+ */
14
+ import type { EditorialCheckResult, EditorialFinding, Severity, Span } from "./editorial-checks";
15
+ import type { MarkusBlock, MarkusDocument, MarkusInline, MarkusNode } from "./markus-ir";
16
+
17
+ export const CITATION_TOKEN = /PAPYRUSMARKUP\d{5}END/g;
18
+
19
+ export type InlineLeaf =
20
+ | { kind: "text"; node: MarkusInline & { type: "text" }; start: number; pieces: { raw: string; start: number; isToken: boolean }[] }
21
+ | { kind: "code"; node: MarkusInline & { type: "code_span" }; start: number; text: string }
22
+ | { kind: "break"; start: number; text: string }
23
+ | { kind: "opaque"; start: number };
24
+
25
+ /** The reader-visible text of a run of inlines; citation tokens and images take no width. */
26
+ export function inlineLeaves(inlines: MarkusInline[], offset = 0): { leaves: InlineLeaf[]; text: string } {
27
+ const leaves: InlineLeaf[] = [];
28
+ let text = "";
29
+ const walk = (nodes: MarkusInline[]) => {
30
+ for (const node of nodes) {
31
+ const start = offset + text.length;
32
+ switch (node.type) {
33
+ case "text": {
34
+ const pieces: { raw: string; start: number; isToken: boolean }[] = [];
35
+ let cursor = 0;
36
+ let plainLength = 0;
37
+ for (const match of node.text.matchAll(CITATION_TOKEN)) {
38
+ const index = match.index ?? 0;
39
+ if (index > cursor) {
40
+ pieces.push({ raw: node.text.slice(cursor, index), start: start + plainLength, isToken: false });
41
+ plainLength += index - cursor;
42
+ }
43
+ pieces.push({ raw: match[0], start: start + plainLength, isToken: true });
44
+ cursor = index + match[0].length;
45
+ }
46
+ if (cursor < node.text.length) {
47
+ pieces.push({ raw: node.text.slice(cursor), start: start + plainLength, isToken: false });
48
+ plainLength += node.text.length - cursor;
49
+ }
50
+ leaves.push({ kind: "text", node, start, pieces });
51
+ text += pieces.filter((piece) => !piece.isToken).map((piece) => piece.raw).join("");
52
+ break;
53
+ }
54
+ case "code_span":
55
+ leaves.push({ kind: "code", node, start, text: node.code });
56
+ text += node.code;
57
+ break;
58
+ case "soft_break":
59
+ case "hard_break":
60
+ leaves.push({ kind: "break", start, text: " " });
61
+ text += " ";
62
+ break;
63
+ case "emphasis":
64
+ case "strong":
65
+ case "strikethrough":
66
+ case "link":
67
+ walk(node.children);
68
+ break;
69
+ default:
70
+ leaves.push({ kind: "opaque", start });
71
+ }
72
+ }
73
+ };
74
+ walk(inlines);
75
+ return { leaves, text };
76
+ }
77
+
78
+ /** Prose blocks (paragraphs and headings, including those inside lists, quotes and directives) in reading order. */
79
+ export function proseBlocks(document: MarkusDocument): (MarkusBlock & { inline: MarkusInline[] })[] {
80
+ const blocks: (MarkusBlock & { inline: MarkusInline[] })[] = [];
81
+ const visit = (nodes: MarkusNode[]) => {
82
+ for (const node of nodes) {
83
+ if (node.type === "directive") visit(node.children);
84
+ else if (node.type === "paragraph" || node.type === "heading") blocks.push(node);
85
+ else if (node.type === "list") for (const item of node.items) visit(item.children);
86
+ else if (node.type === "blockquote") visit(node.children);
87
+ }
88
+ };
89
+ visit(document.children);
90
+ return blocks;
91
+ }
92
+
93
+ export type PreviewMark = Span & { findingIds: string[]; severity: Severity; status: EditorialFinding["status"] };
94
+ export type PreviewSentence = Span & { segmentId: string; source: Span };
95
+
96
+ /** What the preview needs for one rendered block, in that block's rendered-text offsets. */
97
+ export type BlockAnnotation = { marks: PreviewMark[]; sentences: PreviewSentence[] };
98
+
99
+ export type PreviewPlan = WeakMap<object, BlockAnnotation>;
100
+
101
+ const SEVERITY_RANK: Record<Severity, number> = { error: 0, warn: 1, info: 2 };
102
+
103
+ /** Text without whitespace, with a map from each kept character back to its index in the original. */
104
+ function compact(text: string): { value: string; index: number[] } {
105
+ let value = "";
106
+ const index: number[] = [];
107
+ for (let i = 0; i < text.length; i += 1) {
108
+ if (!/\s/.test(text[i])) {
109
+ value += text[i];
110
+ index.push(i);
111
+ }
112
+ }
113
+ return { value, index };
114
+ }
115
+
116
+ /** Locate `needle` in `haystack` ignoring whitespace; the occurrence nearest `near` (a 0..1 position) wins. */
117
+ export function locate(haystack: string, needle: string, near = 0): Span | null {
118
+ const hay = compact(haystack);
119
+ const want = compact(needle).value;
120
+ if (!want) return null;
121
+ let best: number | null = null;
122
+ for (let at = hay.value.indexOf(want); at !== -1; at = hay.value.indexOf(want, at + 1)) {
123
+ if (best === null || Math.abs(at / Math.max(hay.value.length, 1) - near) < Math.abs(best / Math.max(hay.value.length, 1) - near)) best = at;
124
+ }
125
+ if (best === null) return null;
126
+ return { start: hay.index[best], end: hay.index[best + want.length - 1] + 1 };
127
+ }
128
+
129
+ /** The identity of a block's words: no whitespace, no stray emphasis or code markers. */
130
+ function blockKey(text: string): string {
131
+ return compact(text).value.replace(/[*_`~]/g, "");
132
+ }
133
+
134
+ /** Match every Humanus paragraph to a rendered block and place its findings and sentences there. */
135
+ export function planPreview(
136
+ document: MarkusDocument,
137
+ result: EditorialCheckResult,
138
+ findings: EditorialFinding[],
139
+ ): PreviewPlan {
140
+ const plan: PreviewPlan = new WeakMap();
141
+ const blocks = proseBlocks(document).map((block) => ({ block, text: inlineLeaves(block.inline).text }));
142
+ const paragraphs = result.segments.filter((segment) => segment.kind === "paragraph" && segment.text);
143
+ let cursor = 0;
144
+ for (const paragraph of paragraphs) {
145
+ const wanted = blockKey(paragraph.text ?? "");
146
+ let matched = -1;
147
+ for (let candidate = cursor; candidate < blocks.length; candidate += 1) {
148
+ if (blockKey(blocks[candidate].text) === wanted) {
149
+ matched = candidate;
150
+ break;
151
+ }
152
+ }
153
+ if (matched === -1) continue;
154
+ cursor = matched + 1;
155
+ const { block, text } = blocks[matched];
156
+ const sentences: PreviewSentence[] = [];
157
+ for (const sentence of result.segments.filter((s) => s.kind === "sentence" && s.parentId === paragraph.id)) {
158
+ const near = (sentence.start - paragraph.start) / Math.max(paragraph.end - paragraph.start, 1);
159
+ const span = locate(text, sentence.text ?? "", near);
160
+ if (span) sentences.push({ ...span, segmentId: sentence.id, source: { start: sentence.start, end: sentence.end } });
161
+ }
162
+ const ranges: (Span & { finding: EditorialFinding })[] = [];
163
+ for (const finding of findings) {
164
+ const inParagraph =
165
+ finding.segmentId === paragraph.id ||
166
+ result.segments.some((s) => s.id === finding.segmentId && s.parentId === paragraph.id);
167
+ if (!inParagraph || !finding.excerptText) continue;
168
+ const near = (finding.span.start - paragraph.start) / Math.max(paragraph.end - paragraph.start, 1);
169
+ const span = locate(text, finding.excerptText, near);
170
+ if (span) ranges.push({ ...span, finding });
171
+ }
172
+ plan.set(block, { marks: flatten(ranges), sentences });
173
+ }
174
+ return plan;
175
+ }
176
+
177
+ /** Overlapping finding ranges become non-overlapping marks, each listing every finding it belongs to. */
178
+ function flatten(ranges: (Span & { finding: EditorialFinding })[]): PreviewMark[] {
179
+ const cuts = [...new Set(ranges.flatMap((range) => [range.start, range.end]))].sort((a, b) => a - b);
180
+ const marks: PreviewMark[] = [];
181
+ for (let i = 0; i < cuts.length - 1; i += 1) {
182
+ const start = cuts[i];
183
+ const end = cuts[i + 1];
184
+ const covering = ranges.filter((range) => range.start <= start && end <= range.end).map((range) => range.finding);
185
+ if (covering.length === 0) continue;
186
+ const strongest = [...covering].sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity])[0];
187
+ const previous = marks[marks.length - 1];
188
+ const ids = covering.map((finding) => finding.id).sort();
189
+ if (previous && previous.end === start && previous.findingIds.join() === ids.join()) {
190
+ previous.end = end;
191
+ continue;
192
+ }
193
+ marks.push({
194
+ start,
195
+ end,
196
+ findingIds: ids,
197
+ severity: strongest.severity,
198
+ status: covering.every((finding) => finding.status === "review") ? "review" : "violation",
199
+ });
200
+ }
201
+ return marks;
202
+ }
203
+
204
+ /** A selection on the preview, as the source span of the whole sentences it touches. */
205
+ export function selectionToSource(annotation: BlockAnnotation | undefined, selection: Span): Span | null {
206
+ if (!annotation) return null;
207
+ const touched = annotation.sentences.filter((sentence) => sentence.start < selection.end && selection.start < sentence.end);
208
+ if (touched.length === 0) return null;
209
+ return {
210
+ start: Math.min(...touched.map((sentence) => sentence.source.start)),
211
+ end: Math.max(...touched.map((sentence) => sentence.source.end)),
212
+ };
213
+ }
214
+
215
+ /** Split [start, end) of rendered text at mark boundaries; each piece says which mark (if any) covers it. */
216
+ export function splitByMarks(start: number, end: number, marks: PreviewMark[]): { start: number; end: number; mark: PreviewMark | null }[] {
217
+ const pieces: { start: number; end: number; mark: PreviewMark | null }[] = [];
218
+ let cursor = start;
219
+ for (const mark of marks) {
220
+ if (mark.end <= cursor || mark.start >= end) continue;
221
+ if (mark.start > cursor) pieces.push({ start: cursor, end: mark.start, mark: null });
222
+ const pieceEnd = Math.min(mark.end, end);
223
+ pieces.push({ start: Math.max(mark.start, cursor), end: pieceEnd, mark });
224
+ cursor = pieceEnd;
225
+ }
226
+ if (cursor < end) pieces.push({ start: cursor, end, mark: null });
227
+ return pieces;
228
+ }
@@ -0,0 +1,29 @@
1
+ "use client";
2
+
3
+ import { generateClient } from "aws-amplify/data";
4
+ import type { MonitoringResult } from "./monitoring-overview";
5
+
6
+ type GraphQLResult = { data?: { monitoringOverview?: unknown }; errors?: { message?: string; errorType?: string }[] };
7
+
8
+ /**
9
+ * Reads the monitoring overview through the site's own authenticated API (user pool, editor or admin).
10
+ * The browser holds no table name, key or secret: the function behind the query does the read.
11
+ */
12
+ export async function loadMonitoringOverview(scope: "publication" | "all"): Promise<MonitoringResult> {
13
+ const client = generateClient({ authMode: "userPool" });
14
+ let result: GraphQLResult;
15
+ try {
16
+ result = (await client.graphql({
17
+ query: `query MonitoringOverview($scope: String) { monitoringOverview(scope: $scope) }`,
18
+ variables: { scope },
19
+ })) as GraphQLResult;
20
+ } catch (error) {
21
+ // Amplify throws the response when AppSync returns errors.
22
+ result = (error && typeof error === "object" && "errors" in error ? error : { errors: [{ message: "failed" }] }) as GraphQLResult;
23
+ }
24
+ const refused = result.errors?.some((entry) => /unauthorized|not authorized|forbidden/i.test(`${entry.errorType ?? ""} ${entry.message ?? ""}`));
25
+ if (refused) return { error: "forbidden" };
26
+ if (result.errors?.length || result.data?.monitoringOverview === undefined || result.data.monitoringOverview === null) return { state: "unavailable" };
27
+ const raw = result.data.monitoringOverview;
28
+ return (typeof raw === "string" ? JSON.parse(raw) : raw) as MonitoringResult;
29
+ }
@@ -0,0 +1,51 @@
1
+ import type { MonitoringOverview } from "./monitoring-overview";
2
+
3
+ /** A realistic overview for tests and the `?demo=1` newsroom. Public Hacker News titles only. */
4
+ export const FIXTURE_MONITORING_OVERVIEW: MonitoringOverview = {
5
+ state: "ready",
6
+ asOf: "2026-10-21T02:40:00Z",
7
+ scope: { mode: "publication", publicationId: "desk-a", site: "a.example.test", canViewAll: true },
8
+ feeds: [{ id: "hn", sourceUrl: "https://news.ycombinator.com/rss", intervalSeconds: 900, limit: 30, enabled: true,
9
+ lastStatus: "complete", lastFinishedAt: "2026-10-21T02:33:00Z", nextDueAt: "2026-10-21T02:50:00Z" }],
10
+ runs: [
11
+ { runId: "r3", startedAt: "2026-10-21T02:33:00.000000Z", status: "complete", new: 2, revised: 1, unchanged: 27, itemCount: 30, errorCount: 0, errors: [] },
12
+ { runId: "r1", startedAt: "2026-10-21T02:18:00.000000Z", status: "complete", new: 0, revised: 0, unchanged: 30, itemCount: 30, errorCount: 0, errors: [] },
13
+ { runId: "r0", startedAt: "2026-10-21T02:03:00.000000Z", status: "partial", new: 1, revised: 0, unchanged: 28, itemCount: 30, errorCount: 1, errors: ["ConnectionError: timeout"] },
14
+ ],
15
+ routerRuns: [{ runId: "q2", startedAt: "2026-10-21T02:37:00.000000Z", mode: "live", status: "stopped", stoppedBy: "request_ceiling_reached",
16
+ counts: { examined: 3, decided: 1, delivered: 1, deliveryFailed: 1, routed: 1 }, errorCount: 0 }],
17
+ router: { mode: "live", feedback: true, enabled: true, maxItemsPerRun: 5 },
18
+ usage: { day: "2026-10-21", decisionsToday: 2, decisionsTotal: 3, ceilings: { decisionsTotal: 300, decisionsPerDay: 100, items: 300 } },
19
+ hiddenNotRelevant: 1,
20
+ items: [
21
+ { sourceId: "104", revision: 1, title: "Fresh Show HN", url: "https://example.org/104", discussionUrl: "https://news.ycombinator.com/item?id=104",
22
+ observedAt: "2026-10-21T02:30:00.000000Z", routing: "collected", routingNote: null, decidedAt: null,
23
+ relevance: [{ publicationId: "desk-a", site: "a.example.test", relevant: null, label: null, confidence: null, delivery: { state: null } }] },
24
+ { sourceId: "105", revision: 1, title: "Broken request", url: "https://example.org/105", discussionUrl: "https://news.ycombinator.com/item?id=105",
25
+ observedAt: "2026-10-21T01:30:00.000000Z", routing: "error", routingNote: "invalid request: bad title", decidedAt: null,
26
+ relevance: [{ publicationId: "desk-a", site: "a.example.test", relevant: null, label: null, confidence: null, delivery: { state: null } }] },
27
+ { sourceId: "101", revision: 1, title: "Quantum paper on arXiv", url: "https://example.org/101", discussionUrl: "https://news.ycombinator.com/item?id=101",
28
+ observedAt: "2026-10-21T00:10:00.000000Z", routing: "routed", routingNote: null, decidedAt: "2026-10-21T01:00:00Z",
29
+ relevance: [{ publicationId: "desk-a", site: "a.example.test", relevant: true, label: "include", confidence: 0.91,
30
+ delivery: { state: "delivered", referenceId: "ref-1", referenceLineageId: "lin-1", deliveredAt: "2026-10-21T01:00:05Z" } }] },
31
+ { sourceId: "103", revision: 1, title: "Phishing kit leaks", url: "https://example.org/103", discussionUrl: "https://news.ycombinator.com/item?id=103",
32
+ observedAt: "2026-10-20T23:00:00.000000Z", routing: "decided", routingNote: null, decidedAt: "2026-10-20T23:10:00Z",
33
+ relevance: [{ publicationId: "desk-a", site: "a.example.test", relevant: true, label: "include", confidence: 0.7,
34
+ delivery: { state: "failed", error: "ClientError: throttled", attempts: 2 } }] },
35
+ ],
36
+ };
37
+
38
+ export const FIXTURE_ALL_PIPELINE_OVERVIEW: MonitoringOverview = {
39
+ ...FIXTURE_MONITORING_OVERVIEW,
40
+ scope: { mode: "all", publicationId: "desk-a", site: "a.example.test", canViewAll: true },
41
+ hiddenNotRelevant: 0,
42
+ items: FIXTURE_MONITORING_OVERVIEW.items.map((item) => item.sourceId !== "101" ? item : {
43
+ ...item,
44
+ relevance: [
45
+ ...item.relevance,
46
+ { publicationId: "desk-b", site: "b.example.test", relevant: false, label: "exclude", confidence: 0.8, delivery: { state: "not_applicable" } },
47
+ { publicationId: "desk-c", site: "desk-c", relevant: true, label: "include", confidence: null,
48
+ delivery: { state: "delivered", referenceId: "ref-2", referenceLineageId: "lin-2" } },
49
+ ],
50
+ }),
51
+ };