@anthusai/papyrus 5.43.0-next.2 → 5.43.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 (85) hide show
  1. package/amplify/data/resource.js +6 -0
  2. package/amplify/data/resource.ts +7 -0
  3. package/amplify/data/schema.js +6 -0
  4. package/amplify/data/schema.ts +7 -0
  5. package/amplify/functions/category-action/handler.ts +2 -1
  6. package/amplify/functions/content-actions/handler.py +8 -0
  7. package/amplify/functions/model-attachment-upload/handler.ts +1 -0
  8. package/amplify/functions/monitoring-view/schema.js +16 -0
  9. package/amplify/functions/monitoring-view/schema.ts +16 -0
  10. package/amplify/functions/procedure-action/handler.ts +2 -10
  11. package/amplify/functions/proposal-actions/proposals.py +20 -3
  12. package/amplify/plugins/reader-steering/function/handler.py +1 -3
  13. package/amplify/plugins/reader-steering/function/moderation.py +19 -0
  14. package/bin/papyrus-app.mjs +12 -1
  15. package/bin/papyrus-infra.mjs +21 -1
  16. package/components/dev-sandbox-editor-sign-in.tsx +2 -2
  17. package/components/monitoring-overview-view.tsx +143 -21
  18. package/components/monitoring-panel.tsx +64 -4
  19. package/components/needs-me-bodies.tsx +290 -0
  20. package/components/needs-me-detail.tsx +23 -0
  21. package/components/needs-me-feed.tsx +561 -0
  22. package/components/needs-me-reference-detail.tsx +77 -0
  23. package/components/needs-me-shared.tsx +39 -0
  24. package/components/news-desk-client-provider.tsx +24 -3
  25. package/components/news-desk-page.tsx +2 -1
  26. package/components/news-desk-taxonomy-client.ts +2 -1
  27. package/components/newsroom-access-gate.tsx +7 -5
  28. package/components/newsroom-client-shell.tsx +2 -1
  29. package/components/newsroom-ops-overview.tsx +64 -55
  30. package/components/newsroom-ops-shell.tsx +4 -2
  31. package/components/newsroom-organizer.css +60 -2
  32. package/components/newsroom-references-view.tsx +301 -138
  33. package/components/notification-cards.tsx +369 -0
  34. package/components/notification-center.tsx +324 -213
  35. package/components/papyrus-console-shell.tsx +2 -1
  36. package/components/proposals-panel.tsx +21 -24
  37. package/components/proposals-view.tsx +4 -2
  38. package/components/reference-capture-client.ts +110 -0
  39. package/components/reference-capture-panel.tsx +180 -0
  40. package/components/reference-feed.tsx +503 -0
  41. package/components/reference-review-card.tsx +110 -141
  42. package/components/references-page-loading.tsx +61 -0
  43. package/components/references-prefetch.ts +52 -0
  44. package/components/review-rating-grid.tsx +180 -0
  45. package/components/topic-steering-workspace.tsx +44 -9
  46. package/components/use-media-query.ts +16 -0
  47. package/components/use-reference-preview-attachments.ts +101 -0
  48. package/components/use-reference-ratings.ts +134 -0
  49. package/infra/amplify-app-shell.js +18 -2
  50. package/infra/amplify-app-shell.ts +18 -2
  51. package/infra/chat-stack.js +222 -0
  52. package/infra/chat-stack.ts +250 -0
  53. package/infra/chat.test.js +142 -0
  54. package/infra/chat.test.ts +151 -0
  55. package/infra/index.js +1 -0
  56. package/infra/site-config.js +58 -1
  57. package/infra/site-config.ts +78 -1
  58. package/lib/category-repository.ts +6 -1
  59. package/lib/content-actions-client.ts +18 -0
  60. package/lib/local-preview-feed-fixture.ts +63 -0
  61. package/lib/local-preview-synthetic-rejects.ts +41 -0
  62. package/lib/monitoring-client.ts +29 -2
  63. package/lib/monitoring-overview.ts +52 -1
  64. package/lib/monitoring-paging.ts +58 -0
  65. package/lib/needs-me-items.ts +289 -0
  66. package/lib/needs-me-ranking.ts +315 -0
  67. package/lib/newsroom-chat-identity.ts +2 -1
  68. package/lib/newsroom-nav.ts +1 -1
  69. package/lib/newsroom-organizer-nav.ts +2 -1
  70. package/lib/notification-feed.ts +212 -0
  71. package/lib/proposals-client.ts +29 -0
  72. package/lib/reader-subject.ts +3 -2
  73. package/lib/reference-capture.ts +293 -0
  74. package/lib/reference-feed-cache.ts +170 -0
  75. package/lib/reference-feed-ranking.ts +235 -0
  76. package/lib/reference-preview.ts +112 -0
  77. package/lib/review-client.ts +55 -5
  78. package/lib/review-drafts.ts +252 -0
  79. package/lib/review-fixture.ts +56 -2
  80. package/lib/review-requests.ts +64 -24
  81. package/lib/site-brand.ts +2 -0
  82. package/lib/staff-groups.ts +23 -0
  83. package/lib/staging-gate.ts +2 -2
  84. package/package.json +29 -1
  85. package/routes.manifest.json +1 -1
@@ -0,0 +1,235 @@
1
+ /**
2
+ * How the References feed is ordered, and which cards belong in which tab.
3
+ *
4
+ * Plain words, as the "How this feed is ranked" popover says them:
5
+ * 1. The Cyclotron's prediction becomes a probability that you will Accept (P). A prediction of Accept at 80% is
6
+ * P = 0.8; a prediction of Reject at 80% is P = 0.2; no prediction is P = 0.5.
7
+ * 2. Old items lose their say. The score is 0.5 + (P - 0.5) * w, where w = exp(-age / tau) is a freshness weight.
8
+ * Age pulls an item toward "uncertain" (0.5), never to the bottom.
9
+ * 3. tau is learned from how old the References you accepted were when you accepted them
10
+ * (tau = median age / ln 2). With fewer than 10 accepted examples nothing is guessed: no decay.
11
+ * 4. Highest score first. The strongest Reject predictions end up last. Ties go to the newest item.
12
+ * 5. Unrated items older than 3 tau move to "Earlier" at the bottom. Nothing is deleted.
13
+ *
14
+ * The same recipe ranks monitor stories (`learn_freshness` in src/papyrus_content/ideas/monitor_stories.py).
15
+ */
16
+ import type { ReferenceRecord } from "./category-repository";
17
+ import type { RelevanceDecisionView } from "./relevance-decisions";
18
+ import { normalizeReferenceCurationStatus } from "./reference-policy";
19
+ import { referenceLineageId } from "./newsroom-references";
20
+
21
+ /** Fewer accepted examples than this and there is no freshness weight: a constant is never guessed. */
22
+ export const MINIMUM_FRESHNESS_EXAMPLES = 10;
23
+ /** An unrated item whose age passes this many tau has a weight below exp(-3), about 5%, and moves to Earlier. */
24
+ export const EARLIER_AFTER_TAUS = 3;
25
+ /** The probability that stands for "no prediction". */
26
+ export const UNDECIDED_PROBABILITY = 0.5;
27
+ /** A prediction that recorded a label but no confidence is a mild lean, not a coin toss and not a certainty. */
28
+ export const UNRECORDED_CONFIDENCE = 0.6;
29
+
30
+ const DAY_MILLISECONDS = 86_400_000;
31
+
32
+ export type FeedFreshness = {
33
+ /** Null when there were too few accepted examples to learn from: no decay at all. */
34
+ tauDays: number | null;
35
+ medianAgeDays: number | null;
36
+ examples: number;
37
+ };
38
+
39
+ function timeOf(value: string | null | undefined): number | null {
40
+ if (!value) return null;
41
+ const parsed = Date.parse(value);
42
+ return Number.isFinite(parsed) ? parsed : null;
43
+ }
44
+
45
+ /** When the item reached the newsroom. The same arrival the monitor stories use. */
46
+ export function referenceArrivalTime(reference: ReferenceRecord): number | null {
47
+ return timeOf(reference.createdAt) ?? timeOf(reference.importedAt) ?? timeOf(reference.retrievedAt) ?? timeOf(reference.sourcePublishedAt);
48
+ }
49
+
50
+ /** The date a card shows: when the source says it was published, else when it arrived. */
51
+ export function referenceDisplayTime(reference: ReferenceRecord): number | null {
52
+ return timeOf(reference.sourcePublishedAt) ?? timeOf(reference.sourceUpdatedAt) ?? referenceArrivalTime(reference);
53
+ }
54
+
55
+ /**
56
+ * tau from the age at acceptance of accepted References: median / ln 2, since the median age of an exponential
57
+ * exp(-age / tau) is tau * ln 2. `ignore` keeps the item an editor just rated from moving the very ranking they are looking at.
58
+ */
59
+ export function learnFreshness(references: ReferenceRecord[], ignore: ReadonlySet<string> = new Set()): FeedFreshness {
60
+ const ages: number[] = [];
61
+ for (const reference of references) {
62
+ if (normalizeReferenceCurationStatus(reference.curationStatus) !== "accepted" || ignore.has(referenceLineageId(reference))) continue;
63
+ const arrived = referenceArrivalTime(reference);
64
+ const decided = timeOf(reference.curationStatusUpdatedAt);
65
+ if (arrived === null || decided === null) continue;
66
+ const age = (decided - arrived) / DAY_MILLISECONDS;
67
+ if (age > 0) ages.push(age);
68
+ }
69
+ if (ages.length < MINIMUM_FRESHNESS_EXAMPLES) return { tauDays: null, medianAgeDays: null, examples: ages.length };
70
+ ages.sort((left, right) => left - right);
71
+ const middle = Math.floor(ages.length / 2);
72
+ const median = ages.length % 2 ? ages[middle] : (ages[middle - 1] + ages[middle]) / 2;
73
+ return { tauDays: median / Math.LN2, medianAgeDays: median, examples: ages.length };
74
+ }
75
+
76
+ /** exp(-age / tau) at `now`; 1 without a learned tau or an unreadable arrival. */
77
+ export function freshnessWeight(reference: ReferenceRecord, freshness: FeedFreshness, now: number): number {
78
+ const arrived = referenceArrivalTime(reference);
79
+ if (freshness.tauDays === null || arrived === null) return 1;
80
+ return Math.exp(-Math.max(now - arrived, 0) / DAY_MILLISECONDS / freshness.tauDays);
81
+ }
82
+
83
+ /** P(the editor accepts), from the Cyclotron's decision: its confidence is in the label it chose. */
84
+ export function acceptProbability(decision: RelevanceDecisionView | undefined): number {
85
+ if (!decision) return UNDECIDED_PROBABILITY;
86
+ const confidence = decision.confidence ?? UNRECORDED_CONFIDENCE;
87
+ const accepts = decision.label === (decision.positiveLabel ?? "include");
88
+ return accepts ? confidence : 1 - confidence;
89
+ }
90
+
91
+ export type FeedItem = {
92
+ reference: ReferenceRecord;
93
+ lineageId: string;
94
+ decision: RelevanceDecisionView | undefined;
95
+ /** P(accept) before freshness. */
96
+ probability: number;
97
+ weight: number;
98
+ /** 0.5 + (P - 0.5) * weight. Highest is first. */
99
+ score: number;
100
+ /** True when this unrated item is older than the Earlier threshold. */
101
+ earlier: boolean;
102
+ };
103
+
104
+ export function scoreFeedItem(reference: ReferenceRecord, decision: RelevanceDecisionView | undefined, freshness: FeedFreshness, now: number): FeedItem {
105
+ const probability = acceptProbability(decision);
106
+ const weight = freshnessWeight(reference, freshness, now);
107
+ const arrived = referenceArrivalTime(reference);
108
+ const earlier = freshness.tauDays !== null && arrived !== null && (now - arrived) / DAY_MILLISECONDS > EARLIER_AFTER_TAUS * freshness.tauDays;
109
+ return {
110
+ reference,
111
+ lineageId: referenceLineageId(reference),
112
+ decision,
113
+ probability,
114
+ weight,
115
+ score: UNDECIDED_PROBABILITY + (probability - UNDECIDED_PROBABILITY) * weight,
116
+ earlier,
117
+ };
118
+ }
119
+
120
+ /** Highest score first; ties go to the newest item, then to a stable id order. */
121
+ export function compareFeedItems(left: FeedItem, right: FeedItem): number {
122
+ if (right.score !== left.score) return right.score - left.score;
123
+ const newest = (referenceDisplayTime(right.reference) ?? 0) - (referenceDisplayTime(left.reference) ?? 0);
124
+ return newest || left.lineageId.localeCompare(right.lineageId);
125
+ }
126
+
127
+ export type ReferenceFeedTabKey = "feed" | "rated" | "earlier";
128
+
129
+ export type ReferenceFeedPartition = {
130
+ freshness: FeedFreshness;
131
+ /** Pending items, plus the ones rated during this visit (they keep their place), best prediction first. */
132
+ feed: FeedItem[];
133
+ /** Everything an editor has answered, most recent answer first. */
134
+ rated: FeedItem[];
135
+ /** Unrated items past the freshness threshold, ranked like the feed. Still ratable. */
136
+ earlier: FeedItem[];
137
+ };
138
+
139
+ /**
140
+ * Splits canonical References into the three tabs.
141
+ * `visitRated` holds lineage ids rated since the page opened: they stay in Feed, in place, showing the answer.
142
+ */
143
+ export function partitionReferenceFeed(
144
+ references: ReferenceRecord[],
145
+ decisions: ReadonlyMap<string, RelevanceDecisionView> | undefined,
146
+ options: { now: number; visitRated?: ReadonlySet<string>; tauDaysOverride?: number | null },
147
+ ): ReferenceFeedPartition {
148
+ const visitRated = options.visitRated ?? new Set<string>();
149
+ const learned = learnFreshness(references, visitRated);
150
+ const freshness: FeedFreshness = options.tauDaysOverride && options.tauDaysOverride > 0
151
+ ? { ...learned, tauDays: options.tauDaysOverride }
152
+ : learned;
153
+ const feed: FeedItem[] = [];
154
+ const rated: FeedItem[] = [];
155
+ const earlier: FeedItem[] = [];
156
+ for (const reference of references) {
157
+ const status = normalizeReferenceCurationStatus(reference.curationStatus);
158
+ const lineageId = referenceLineageId(reference);
159
+ const item = scoreFeedItem(reference, decisions?.get(lineageId), freshness, options.now);
160
+ if (status === "archived") continue;
161
+ if (status === "accepted" || status === "rejected") {
162
+ rated.push(item);
163
+ if (visitRated.has(lineageId)) (item.earlier ? earlier : feed).push(item);
164
+ } else if (item.earlier) earlier.push(item);
165
+ else feed.push(item);
166
+ }
167
+ feed.sort(compareFeedItems);
168
+ earlier.sort(compareFeedItems);
169
+ rated.sort((left, right) => (timeOf(right.reference.curationStatusUpdatedAt) ?? 0) - (timeOf(left.reference.curationStatusUpdatedAt) ?? 0)
170
+ || left.lineageId.localeCompare(right.lineageId));
171
+ return { freshness, feed, rated, earlier };
172
+ }
173
+
174
+ export type FeedGroupKey = "top" | "more" | "least";
175
+
176
+ /**
177
+ * The feed's sections, from the ranked list (already best first). No fixed counts: Top predictions are the Accepts at least half as
178
+ * strong as the strongest one, Least likely are the predicted Rejects, and More for you is everything between (weaker Accepts and
179
+ * items with no prediction). A group with no members is absent.
180
+ */
181
+ export function groupFeedItems(items: FeedItem[]): Array<{ key: FeedGroupKey; items: FeedItem[] }> {
182
+ const strongest = items.reduce((best, item) => Math.max(best, item.score - UNDECIDED_PROBABILITY), 0);
183
+ const groups: Record<FeedGroupKey, FeedItem[]> = { top: [], more: [], least: [] };
184
+ for (const item of items) {
185
+ const strength = item.score - UNDECIDED_PROBABILITY;
186
+ if (strength < 0) groups.least.push(item);
187
+ else if (strength > 0 && strength >= strongest / 2) groups.top.push(item);
188
+ else groups.more.push(item);
189
+ }
190
+ return (["top", "more", "least"] as const).filter((key) => groups[key].length).map((key) => ({ key, items: groups[key] }));
191
+ }
192
+
193
+ /**
194
+ * The order of the feed, taken once per visit when it loads and then left alone: selecting, rating, a background refresh and a cache
195
+ * revalidation never re-rank it. Items that arrive later are counted as new and wait behind a "N new items: show" pill.
196
+ */
197
+ export type FeedOrderSnapshot = {
198
+ /** Every Reference lineage the snapshot knew about (pending, rated and earlier): anything else is new. */
199
+ known: ReadonlySet<string>;
200
+ feed: string[];
201
+ earlier: string[];
202
+ groups: Array<{ key: FeedGroupKey; ids: string[] }>;
203
+ leadId: string | undefined;
204
+ };
205
+
206
+ export function takeFeedOrderSnapshot(partition: ReferenceFeedPartition): FeedOrderSnapshot {
207
+ const groups = groupFeedItems(partition.feed);
208
+ return {
209
+ known: new Set([...partition.feed, ...partition.earlier, ...partition.rated].map((item) => item.lineageId)),
210
+ feed: partition.feed.map((item) => item.lineageId),
211
+ earlier: partition.earlier.map((item) => item.lineageId),
212
+ groups: groups.map((group) => ({ key: group.key, ids: group.items.map((item) => item.lineageId) })),
213
+ leadId: groups[0]?.key !== "least" ? groups[0]?.items[0]?.lineageId : undefined,
214
+ };
215
+ }
216
+
217
+ /** The live partition with its feed order, sections and lead taken from the snapshot; records and scores stay current. */
218
+ export function applyFeedOrderSnapshot(snapshot: FeedOrderSnapshot, live: ReferenceFeedPartition): {
219
+ partition: ReferenceFeedPartition;
220
+ groups: Array<{ key: FeedGroupKey; items: FeedItem[] }>;
221
+ leadId: string | undefined;
222
+ newCount: number;
223
+ } {
224
+ const byId = new Map<string, FeedItem>();
225
+ for (const item of [...live.rated, ...live.earlier, ...live.feed]) byId.set(item.lineageId, item);
226
+ const pick = (ids: string[]) => ids.flatMap((id) => { const item = byId.get(id); return item ? [item] : []; });
227
+ const groups = snapshot.groups.map((group) => ({ key: group.key, items: pick(group.ids) })).filter((group) => group.items.length);
228
+ const newCount = [...live.feed, ...live.earlier].filter((item) => !snapshot.known.has(item.lineageId)).length;
229
+ return {
230
+ partition: { ...live, feed: pick(snapshot.feed), earlier: pick(snapshot.earlier) },
231
+ groups,
232
+ leadId: snapshot.leadId && byId.has(snapshot.leadId) ? snapshot.leadId : undefined,
233
+ newCount,
234
+ };
235
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * What a Reference card shows besides its title: the source page's preview image, a one-line dek and the site name.
3
+ *
4
+ * Storage: a `ReferenceAttachment` with role "preview" (sort key "002-preview"), no schema change. `sourceUri` is the
5
+ * page's og:image / twitter:image address and `metadata` holds `{ description, siteName, title, fetchedAt }`. The newsroom
6
+ * already loads every attachment with the References, so the feed needs no extra request. `papyrus references enrich-images`
7
+ * (src/papyrus_content/reference_images.py) writes them.
8
+ */
9
+ import type { ReferenceAttachmentRecord, ReferenceRecord } from "./category-repository";
10
+
11
+ export const REFERENCE_PREVIEW_ROLE = "preview";
12
+
13
+ export type ReferencePreview = {
14
+ imageUrl: string | null;
15
+ description: string | null;
16
+ siteName: string | null;
17
+ title: string | null;
18
+ };
19
+
20
+ function record(value: unknown): Record<string, unknown> {
21
+ if (typeof value === "string") {
22
+ try { return record(JSON.parse(value)); } catch { return {}; }
23
+ }
24
+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
25
+ }
26
+
27
+ function text(value: unknown): string | null {
28
+ return typeof value === "string" && value.trim() ? value.trim() : null;
29
+ }
30
+
31
+ function httpAddress(value: unknown): string | null {
32
+ const candidate = text(value);
33
+ return candidate && /^https?:\/\//i.test(candidate) ? candidate : null;
34
+ }
35
+
36
+ /** The preview of each Reference lineage, from its "preview" attachment. A lineage with none has no entry. */
37
+ export function referencePreviewsByLineage(attachments: ReferenceAttachmentRecord[] | undefined): Map<string, ReferencePreview> {
38
+ const previews = new Map<string, ReferencePreview>();
39
+ for (const attachment of attachments ?? []) {
40
+ if (attachment.role !== REFERENCE_PREVIEW_ROLE || !attachment.referenceLineageId) continue;
41
+ const metadata = record(attachment.metadata);
42
+ previews.set(attachment.referenceLineageId, {
43
+ imageUrl: httpAddress(attachment.sourceUri) ?? httpAddress(metadata.imageUrl),
44
+ description: text(metadata.description),
45
+ siteName: text(metadata.siteName),
46
+ title: text(metadata.title),
47
+ });
48
+ }
49
+ return previews;
50
+ }
51
+
52
+ /** The one-line dek: the source page's description, else a summary recorded on the Reference. */
53
+ export function referenceDek(reference: ReferenceRecord, preview: ReferencePreview | undefined): string | null {
54
+ if (preview?.description) return preview.description;
55
+ const metadata = record(reference.metadata);
56
+ for (const key of ["subtitle", "summary", "abstract", "description"]) {
57
+ const value = text(metadata[key]);
58
+ if (value) return value;
59
+ }
60
+ return null;
61
+ }
62
+
63
+ /** The source's host without "www.", or null when the Reference has no web address. */
64
+ export function referenceSourceHost(reference: ReferenceRecord): string | null {
65
+ const candidate = httpAddress(reference.sourceUri);
66
+ if (!candidate) return null;
67
+ try { return new URL(candidate).hostname.replace(/^www\./i, "") || null; } catch { return null; }
68
+ }
69
+
70
+ /** Short age for a card: "5m", "3h", "2d", "6w", "4mo". */
71
+ export function formatFeedAge(time: number | null, now: number): string | null {
72
+ if (time === null) return null;
73
+ const seconds = Math.max(0, Math.round((now - time) / 1000));
74
+ if (seconds < 60) return "now";
75
+ const minutes = Math.round(seconds / 60);
76
+ if (minutes < 60) return `${minutes}m`;
77
+ const hours = Math.round(minutes / 60);
78
+ if (hours < 24) return `${hours}h`;
79
+ const days = Math.round(hours / 24);
80
+ if (days < 14) return `${days}d`;
81
+ if (days < 60) return `${Math.round(days / 7)}w`;
82
+ return `${Math.round(days / 30)}mo`;
83
+ }
84
+
85
+ function words(text: string): string[] {
86
+ return text.toLowerCase().normalize("NFKD").replace(/[^\p{L}\p{N}]+/gu, " ").split(" ").filter((word) => word.length > 1);
87
+ }
88
+
89
+ /**
90
+ * Whether the dek tells the reader something the headline and picture do not. A dek that repeats the headline, or that is mostly
91
+ * the headline's own words, is dropped; so is the description of a GitHub repository, whose social-card picture already prints it.
92
+ */
93
+ export function dekAddsInformation(title: string, dek: string | null, imageUrl: string | null): boolean {
94
+ if (!dek) return false;
95
+ let imageHost = "";
96
+ try { imageHost = imageUrl ? new URL(imageUrl).hostname : ""; } catch { /* no host */ }
97
+ if (/(^|\.)opengraph\.githubassets\.com$/i.test(imageHost)) return false;
98
+ const titleWords = new Set(words(title));
99
+ const dekWords = words(dek);
100
+ if (!dekWords.length) return false;
101
+ const shared = dekWords.filter((word) => titleWords.has(word)).length;
102
+ const covered = titleWords.size ? [...titleWords].filter((word) => dekWords.includes(word)).length / titleWords.size : 0;
103
+ return shared / dekWords.length < 0.6 && covered < 0.8;
104
+ }
105
+
106
+ /** Pictures that are a text card, not a photograph: a repository social card, or any picture whose ratio is almost exactly 2:1 or the 1.91:1 Open Graph card (1200x630). Cropping cuts the words off. */
107
+ export function isCardStyleImage(url: string | null, naturalRatio: number | null): boolean {
108
+ let host = "";
109
+ try { host = url ? new URL(url).hostname : ""; } catch { /* no host */ }
110
+ if (/(^|\.)(opengraph\.githubassets\.com|repository-images\.githubusercontent\.com|github\.com)$/i.test(host)) return true;
111
+ return naturalRatio !== null && (Math.abs(naturalRatio - 2) < 0.04 || Math.abs(naturalRatio - 1200 / 630) < 0.04);
112
+ }
@@ -2,9 +2,10 @@
2
2
 
3
3
  import { generateClient } from "aws-amplify/data";
4
4
  import { getCurrentUser } from "aws-amplify/auth";
5
+ import { draftDecisionUpdate, draftView, type DraftRow, type DraftView } from "./review-drafts";
5
6
  import {
6
7
  answerUpdate, isDue, normalizeReviewRow, timeoutUpdate,
7
- type AnswerInput, type ReviewRequest,
8
+ type AnswerInput, type DraftDecision, type ReviewRequest,
8
9
  } from "./review-requests";
9
10
 
10
11
  /**
@@ -99,22 +100,71 @@ export async function markReviewRead(userKey: string, requestId: string, now: Da
99
100
  }
100
101
 
101
102
  const MAX_TITLE_LOOKUPS = 40;
103
+ /** The opening of a story, for a reviewer who has not opened it: the deck, then the first paragraphs of the body. */
104
+ const EXCERPT_CHARACTERS = 900;
105
+
106
+ export function storyExcerpt(deck: string | null | undefined, body: readonly (string | null)[] | null | undefined): string | null {
107
+ const text = [deck, ...(body ?? [])].map((part) => (part ?? "").trim()).filter(Boolean).join("\n\n");
108
+ if (!text) return null;
109
+ if (text.length <= EXCERPT_CHARACTERS) return text;
110
+ const cut = text.slice(0, EXCERPT_CHARACTERS);
111
+ return `${cut.slice(0, Math.max(cut.lastIndexOf(" "), EXCERPT_CHARACTERS - 80))}…`;
112
+ }
102
113
 
103
114
  /** Titles of the stories that review requests are about, by lineage id, and the ids of stories that no longer exist (no version of the lineage remains). A story that cannot be read simply has no entry (the card falls back to the id). */
104
- export async function loadStoryTitles(ids: string[]): Promise<{ titles: Record<string, string>; deleted: string[] }> {
115
+ export async function loadStoryTitles(ids: string[]): Promise<{ titles: Record<string, string>; deleted: string[]; excerpts?: Record<string, string> }> {
105
116
  const titles: Record<string, string> = {};
117
+ const excerpts: Record<string, string> = {};
106
118
  const deleted: string[] = [];
107
119
  await Promise.all([...new Set(ids)].slice(0, MAX_TITLE_LOOKUPS).map(async (id) => {
108
120
  const result = await run(
109
- `query StoryTitle($lineageId: ID!) { listItemsByLineageAndVersion(lineageId: $lineageId, limit: 50) { items { versionNumber headline title } } }`,
121
+ `query StoryTitle($lineageId: ID!) { listItemsByLineageAndVersion(lineageId: $lineageId, limit: 50) { items { versionNumber headline title deck body } } }`,
110
122
  { lineageId: id },
111
123
  );
112
124
  // Only a clean, empty answer means the story is gone; a failed lookup says nothing.
113
125
  if (!result.errors?.length && result.data?.listItemsByLineageAndVersion && !(result.data.listItemsByLineageAndVersion.items ?? []).filter(Boolean).length) deleted.push(id);
114
- const items = (result.data?.listItemsByLineageAndVersion?.items ?? []).filter(Boolean) as { versionNumber?: number; headline?: string; title?: string }[];
126
+ const items = (result.data?.listItemsByLineageAndVersion?.items ?? []).filter(Boolean) as { versionNumber?: number; headline?: string; title?: string; deck?: string | null; body?: (string | null)[] | null }[];
115
127
  const newest = items.sort((a, b) => (b.versionNumber ?? 0) - (a.versionNumber ?? 0))[0];
116
128
  const title = newest?.headline || newest?.title;
117
129
  if (title) titles[id] = title;
130
+ const excerpt = storyExcerpt(newest?.deck, newest?.body);
131
+ if (excerpt) excerpts[id] = excerpt;
132
+ }));
133
+ return { titles, deleted, excerpts };
134
+ }
135
+
136
+ const MAX_DRAFT_LOOKUPS = 60;
137
+ const DRAFT_FIELDS = "id kind title summary body state held evidence history override createdAt";
138
+
139
+ /** Records one draft's decision on the request while it stays open. Same condition as an answer: state = open. */
140
+ export async function saveDraftDecision(request: ReviewRequest, draftId: string, decision: DraftDecision): Promise<ReviewRequest> {
141
+ const result = await run(
142
+ `mutation Decide($input: UpdateReviewRequestInput!, $condition: ModelReviewRequestConditionInput) { updateReviewRequest(input: $input, condition: $condition) { ${FIELDS} } }`,
143
+ { input: draftDecisionUpdate(request, draftId, decision), condition: { state: { eq: "open" } } },
144
+ );
145
+ if (result.errors?.some((entry) => /conditional/i.test(`${entry.errorType ?? ""} ${entry.message ?? ""}`))) {
146
+ throw new Error("Someone else answered this, or it closed at its deadline. Refresh to see the result.");
147
+ }
148
+ if (result.errors?.length || !result.data?.updateReviewRequest) throw new Error("The draft was decided, but the request could not record it. Try again.");
149
+ return normalizeReviewRow(result.data.updateReviewRequest);
150
+ }
151
+
152
+ export type DraftLoad = { drafts: Record<string, DraftView>; missing: string[]; failed: string[] };
153
+
154
+ /**
155
+ * The Proposals that review requests are about, by id (editors and admins may read them). `missing` ids have no proposal (an idea kept
156
+ * only as JSON has no proposal to open); `failed` ids could not be read right now, which says nothing about whether they exist.
157
+ */
158
+ export async function loadDrafts(ids: string[], demo = false): Promise<DraftLoad> {
159
+ const drafts: Record<string, DraftView> = {};
160
+ const missing: string[] = [];
161
+ const failed: string[] = [];
162
+ await Promise.all([...new Set(ids)].slice(0, MAX_DRAFT_LOOKUPS).map(async (id) => {
163
+ const result = await run(`query Draft($id: ID!) { getProposal(id: $id) { ${DRAFT_FIELDS} } }`, { id });
164
+ const row = result.data?.getProposal as DraftRow | null | undefined;
165
+ if (row) drafts[id] = draftView(row, demo);
166
+ else if (result.errors?.length || !result.data) failed.push(id);
167
+ else missing.push(id);
118
168
  }));
119
- return { titles, deleted };
169
+ return { drafts, missing, failed };
120
170
  }