@anthusai/papyrus 5.44.0 → 5.45.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.
@@ -0,0 +1,191 @@
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
+ }
@@ -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. 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;
112
+ }
package/package.json CHANGED
@@ -140,12 +140,16 @@
140
140
  "./components/reference-cyclotron-priming": "./components/reference-cyclotron-priming.tsx",
141
141
  "./components/reference-cyclotron-status": "./components/reference-cyclotron-status.tsx",
142
142
  "./components/reference-cyclotron-suggestion": "./components/reference-cyclotron-suggestion.tsx",
143
+ "./components/reference-feed": "./components/reference-feed.tsx",
143
144
  "./components/reference-live-agreement": "./components/reference-live-agreement.tsx",
144
145
  "./components/reference-priming": "./components/reference-priming.tsx",
145
146
  "./components/reference-relevance-review": "./components/reference-relevance-review.tsx",
146
147
  "./components/reference-review-card": "./components/reference-review-card.tsx",
147
148
  "./components/reference-section-suggestion": "./components/reference-section-suggestion.tsx",
148
149
  "./components/reference-source-preview": "./components/reference-source-preview.tsx",
150
+ "./components/references-page-loading": "./components/references-page-loading.tsx",
151
+ "./components/references-prefetch": "./components/references-prefetch.ts",
152
+ "./components/review-rating-grid": "./components/review-rating-grid.tsx",
149
153
  "./components/settings-page": "./components/settings-page.tsx",
150
154
  "./components/signup-entries-panel": "./components/signup-entries-panel.tsx",
151
155
  "./components/staging-banner": "./components/staging-banner.tsx",
@@ -240,8 +244,10 @@
240
244
  "./lib/layout-scenarios": "./lib/layout-scenarios.ts",
241
245
  "./lib/layout-types": "./lib/layout-types.ts",
242
246
  "./lib/layout-warnings": "./lib/layout-warnings.ts",
247
+ "./lib/local-preview-feed-fixture": "./lib/local-preview-feed-fixture.ts",
243
248
  "./lib/local-preview-section-fixtures": "./lib/local-preview-section-fixtures.ts",
244
249
  "./lib/local-preview-seed": "./lib/local-preview-seed.ts",
250
+ "./lib/local-preview-synthetic-rejects": "./lib/local-preview-synthetic-rejects.ts",
245
251
  "./lib/local-preview-tenant": "./lib/local-preview-tenant.ts",
246
252
  "./lib/local-preview": "./lib/local-preview.ts",
247
253
  "./lib/markus-body": "./lib/markus-body.ts",
@@ -252,6 +258,7 @@
252
258
  "./lib/monitoring-client": "./lib/monitoring-client.ts",
253
259
  "./lib/monitoring-overview-fixture": "./lib/monitoring-overview-fixture.ts",
254
260
  "./lib/monitoring-overview": "./lib/monitoring-overview.ts",
261
+ "./lib/monitoring-paging": "./lib/monitoring-paging.ts",
255
262
  "./lib/news-desk-session": "./lib/news-desk-session.ts",
256
263
  "./lib/newsletter-api": "./lib/newsletter-api.ts",
257
264
  "./lib/newsletter-client": "./lib/newsletter-client.ts",
@@ -314,7 +321,10 @@
314
321
  "./lib/reader-storage-url": "./lib/reader-storage-url.ts",
315
322
  "./lib/reader-subject": "./lib/reader-subject.ts",
316
323
  "./lib/reference-display": "./lib/reference-display.ts",
324
+ "./lib/reference-feed-cache": "./lib/reference-feed-cache.ts",
325
+ "./lib/reference-feed-ranking": "./lib/reference-feed-ranking.ts",
317
326
  "./lib/reference-policy": "./lib/reference-policy.ts",
327
+ "./lib/reference-preview": "./lib/reference-preview.ts",
318
328
  "./lib/reference-review-details": "./lib/reference-review-details.ts",
319
329
  "./lib/reference-review-request": "./lib/reference-review-request.ts",
320
330
  "./lib/reference-source-preview": "./lib/reference-source-preview.ts",
@@ -470,7 +480,7 @@
470
480
  "optional": true
471
481
  }
472
482
  },
473
- "version": "5.44.0",
483
+ "version": "5.45.0",
474
484
  "dependencies": {
475
485
  "@aws-amplify/adapter-nextjs": "^1.7.3",
476
486
  "@aws-crypto/sha256-js": "5.2.0",
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "5.44.0",
2
+ "version": "5.45.0",
3
3
  "routes": [
4
4
  {
5
5
  "file": "app/%5F_preview/[[...path]]/route.ts",