@anthusai/papyrus 1.4.0-next.4 → 1.4.0-next.6

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 (69) hide show
  1. package/amplify/data/resource.js +13 -3
  2. package/amplify/data/resource.ts +13 -3
  3. package/amplify/data/schema.js +10 -0
  4. package/amplify/data/schema.ts +10 -0
  5. package/amplify/functions/category-action/handler.ts +20 -19
  6. package/amplify/functions/console-chat-responder/src/main.rs +1 -1
  7. package/amplify/functions/content-actions/handler.py +23 -0
  8. package/amplify/functions/content-actions/requirements.txt +1 -1
  9. package/amplify/functions/content-actions/resource.js +1 -1
  10. package/amplify/functions/content-actions/resource.ts +1 -1
  11. package/amplify/functions/renditions/requirements.txt +1 -1
  12. package/amplify/functions/shared/reference-curation-metadata.ts +15 -0
  13. package/amplify/functions/shared/slack-events.ts +2 -2
  14. package/amplify/publication/renditions-function.js +1 -1
  15. package/amplify/publication/renditions-function.ts +1 -1
  16. package/app/api/local-preview/derive/route.ts +28 -0
  17. package/app/api/local-preview/media/route.ts +25 -0
  18. package/app/globals.css +28 -28
  19. package/app/layout.tsx +8 -5
  20. package/app/newsroom/[section]/[...selection]/page.tsx +0 -1
  21. package/app/newsroom/[section]/page.tsx +0 -1
  22. package/app/newsroom/insights/[threadId]/page.tsx +5 -16
  23. package/app/newsroom/insights/page.tsx +4 -12
  24. package/components/board-card-excerpts.tsx +45 -0
  25. package/components/markus-ir-preview.tsx +47 -2
  26. package/components/news-desk-page.tsx +0 -1
  27. package/components/news-desk-taxonomy-client.ts +25 -220
  28. package/components/newsroom-article-editor.tsx +135 -39
  29. package/components/newsroom-assignment-detail.tsx +35 -1
  30. package/components/newsroom-board-view.tsx +29 -7
  31. package/components/newsroom-newsprint-board.css +10 -2
  32. package/components/newsroom-ops-overview.tsx +27 -5
  33. package/components/newsroom-organizer-shell.tsx +25 -7
  34. package/components/newsroom-organizer.css +196 -4
  35. package/components/priming-proof-page.tsx +17 -8
  36. package/components/prospectus-account-chooser.tsx +98 -0
  37. package/components/story-reporting-trail-client.ts +91 -0
  38. package/components/story-reporting-trail.tsx +115 -0
  39. package/components/topic-steering-workspace.tsx +154 -671
  40. package/components/ui/sheet.tsx +1 -0
  41. package/components/wiki-concepts-view.tsx +153 -0
  42. package/components/wiki-index-client.ts +51 -0
  43. package/lib/content-actions-client.ts +3 -0
  44. package/lib/content-actions-demo.ts +55 -3
  45. package/lib/content-item-lifecycle.ts +4 -2
  46. package/lib/content-source-context.ts +9 -1
  47. package/lib/front-matter-fields.ts +42 -0
  48. package/lib/graphql-content-repository.ts +42 -7
  49. package/lib/local-preview-seed.ts +55 -2
  50. package/lib/local-preview-tenant.ts +27 -0
  51. package/lib/newsroom-articles.ts +2 -0
  52. package/lib/newsroom-board.ts +4 -0
  53. package/lib/newsroom-forum-routes.ts +2 -43
  54. package/lib/newsroom-index-filters.ts +3 -40
  55. package/lib/newsroom-media-backend.ts +5 -0
  56. package/lib/newsroom-nav.ts +1 -3
  57. package/lib/newsroom-organizer-nav.ts +5 -12
  58. package/lib/newsroom-section-routing.ts +1 -1
  59. package/lib/newsroom-sections.ts +12 -0
  60. package/lib/papyrus-web-locations.ts +3 -24
  61. package/lib/priming-proof-report.ts +1 -0
  62. package/lib/prospectus-tenant.ts +22 -0
  63. package/lib/semantic-graph.ts +5 -5
  64. package/lib/site-brand.ts +9 -0
  65. package/lib/story-reporting-trail.ts +106 -0
  66. package/lib/tenant-keys.ts +32 -0
  67. package/lib/wiki.ts +56 -0
  68. package/package.json +15 -1
  69. package/routes.manifest.json +23 -7
@@ -4,15 +4,24 @@ import {
4
4
  type PrimingProofReport,
5
5
  } from "../lib/priming-proof-report";
6
6
 
7
- function ProofMethod({ heldOutSize, teachingSource }: { heldOutSize: number | null; teachingSource: string | null }) {
7
+ function ProofMethod({ heldOutSize, teachingSource, design }: { heldOutSize: number | null; teachingSource: string | null; design: string | null }) {
8
8
  return (
9
9
  <section aria-labelledby="priming-proof-method" className="space-y-2 text-sm leading-relaxed">
10
10
  <h2 id="priming-proof-method" className="text-base font-semibold uppercase tracking-wide">How the number is made</h2>
11
- <p>
12
- Editors already decided which candidate sources belong in this publication. A fixed, balanced sample of those
13
- decisions{heldOutSize === null ? "" : ` (${heldOutSize} sources)`} is frozen as the held-out set and never used
14
- for teaching. A classifier that always gives the same answer agrees on half of it.
15
- </p>
11
+ {design === null ? (
12
+ <p>
13
+ Editors already decided which candidate sources belong in this publication. A fixed, balanced sample of those
14
+ decisions{heldOutSize === null ? "" : ` (${heldOutSize} sources)`} is frozen as the held-out set and never used
15
+ for teaching. A classifier that always gives the same answer agrees on half of it.
16
+ </p>
17
+ ) : (
18
+ <p>
19
+ Editors already decided which candidate sources belong in this publication
20
+ {heldOutSize === null ? "" : `, ${heldOutSize} of them`}. Design: {design}. No source is ever judged by a
21
+ classifier that was taught from that same source. The two outcomes are not equally common, so read agreement
22
+ beside precision and recall: a classifier that always gives the majority answer would still agree often.
23
+ </p>
24
+ )}
16
25
  <p>
17
26
  Editors teach the classifier with labels: their other reviews of candidate sources, and sources they paste,
18
27
  check after Papyrus extracts them, and mark publish or reject.
@@ -33,7 +42,7 @@ export function PrimingProofPage({ report }: { report: PrimingProofReport | null
33
42
  <h1 className="text-3xl font-bold">Does teaching the classifier work?</h1>
34
43
  <p className="text-muted-foreground">No approved proof run has been published for this publication yet.</p>
35
44
  </header>
36
- <ProofMethod heldOutSize={null} teachingSource={null} />
45
+ <ProofMethod heldOutSize={null} teachingSource={null} design={null} />
37
46
  </main>
38
47
  );
39
48
  }
@@ -84,7 +93,7 @@ export function PrimingProofPage({ report }: { report: PrimingProofReport | null
84
93
  </table>
85
94
  </div>
86
95
  </section>
87
- <ProofMethod heldOutSize={report.heldOut.size} teachingSource={report.priming.source} />
96
+ <ProofMethod heldOutSize={report.heldOut.size} teachingSource={report.priming.source} design={report.heldOut.design ?? null} />
88
97
  <p className="break-all text-xs text-muted-foreground">
89
98
  Held-out fingerprint {report.heldOut.fingerprint}
90
99
  {report.priming.fingerprint ? ` · labels fingerprint ${report.priming.fingerprint}` : ""}
@@ -0,0 +1,98 @@
1
+ "use client";
2
+
3
+ import { useEffect, useState } from "react";
4
+ import { Check } from "lucide-react";
5
+ import { isLocalPreviewEnabled } from "../lib/local-preview";
6
+ import { LOCAL_PREVIEW_TENANTS, getLocalPreviewTenantId, setLocalPreviewTenantId } from "../lib/local-preview-tenant";
7
+ import { loadProspectusAccountState, selectProspectusAccount, type ProspectusAccountState } from "../lib/prospectus-account-client";
8
+
9
+ function previewAccountState(): ProspectusAccountState {
10
+ return {
11
+ status: "signedIn",
12
+ publishingAccounts: LOCAL_PREVIEW_TENANTS.map(tenant => ({ accountId: tenant.accountId, name: tenant.name, role: tenant.role })),
13
+ selectedAccountId: getLocalPreviewTenantId(),
14
+ cyclotronLabAccess: true,
15
+ };
16
+ }
17
+
18
+ const ACCOUNT_STATE_EVENT = "papyrus:prospectus-account-state";
19
+
20
+ function summaryOf(state: ProspectusAccountState): string | null {
21
+ if (state.status !== "signedIn") return null;
22
+ const selected = state.publishingAccounts.find(account => account.accountId === state.selectedAccountId);
23
+ return selected ? `${selected.name ?? selected.accountId} · ${roleLabel(selected.role)}` : "Choose an account";
24
+ }
25
+
26
+ const roleLabel = (role: string) => role.replace(/_/g, " ");
27
+
28
+ /** The signed-in person's current publishing account as "Name · role", or null when the site has no Prospectus accounts. */
29
+ export function useProspectusAccountSummary(): string | null {
30
+ const [summary, setSummary] = useState<string | null>(null);
31
+ useEffect(() => {
32
+ let cancelled = false;
33
+ const returnPath = `${window.location.pathname}${window.location.search}`;
34
+ (isLocalPreviewEnabled() ? Promise.resolve(previewAccountState()) : loadProspectusAccountState(returnPath)).then(loaded => {
35
+ if (!cancelled) setSummary(summaryOf(loaded));
36
+ });
37
+ const onChange = (event: Event) => setSummary(summaryOf((event as CustomEvent<ProspectusAccountState>).detail));
38
+ window.addEventListener(ACCOUNT_STATE_EVENT, onChange);
39
+ return () => { cancelled = true; window.removeEventListener(ACCOUNT_STATE_EVENT, onChange); };
40
+ }, []);
41
+ return summary;
42
+ }
43
+
44
+ /**
45
+ * The publishing account the signed-in person is acting as. It appears only on sites that have Prospectus
46
+ * accounts configured; a site with its own user pool never shows it. Choosing an account records the choice
47
+ * in the sign-in session and reloads so every page reads the new account.
48
+ */
49
+ export function ProspectusAccountChooser() {
50
+ const [state, setState] = useState<ProspectusAccountState>({ status: "unavailable" });
51
+ const [error, setError] = useState<string | null>(null);
52
+ const [pending, setPending] = useState<string | null>(null);
53
+ useEffect(() => {
54
+ let cancelled = false;
55
+ const returnPath = `${window.location.pathname}${window.location.search}`;
56
+ (isLocalPreviewEnabled() ? Promise.resolve(previewAccountState()) : loadProspectusAccountState(returnPath))
57
+ .then(loaded => { if (!cancelled) setState(loaded); });
58
+ return () => { cancelled = true; };
59
+ }, []);
60
+ if (state.status === "unavailable") return null;
61
+ if (state.status === "signedOut") {
62
+ return <div className="organizer-account-chooser" data-prospectus-account-chooser="signed-out">
63
+ <a className="organizer-account-chooser-link" href={state.signInUrl}>Sign in with Prospectus</a>
64
+ </div>;
65
+ }
66
+ const choose = async (accountId: string) => {
67
+ if (accountId === state.selectedAccountId || pending) return;
68
+ setPending(accountId); setError(null);
69
+ if (isLocalPreviewEnabled()) {
70
+ setLocalPreviewTenantId(accountId);
71
+ window.location.reload();
72
+ return;
73
+ }
74
+ const result = await selectProspectusAccount(accountId);
75
+ setPending(null);
76
+ if ("error" in result) { setError(result.error); return; }
77
+ window.location.reload();
78
+ };
79
+ return <div className="organizer-account-chooser" data-prospectus-account-chooser="signed-in">
80
+ <p className="organizer-account-chooser-heading">Publishing account</p>
81
+ {state.publishingAccounts.length === 0
82
+ ? <p className="organizer-account-chooser-note">No publishing accounts yet.</p>
83
+ : <ul role="listbox" aria-label="Publishing account">
84
+ {state.publishingAccounts.map(account => {
85
+ const selected = account.accountId === state.selectedAccountId;
86
+ return <li key={account.accountId} role="presentation">
87
+ <button aria-selected={selected} data-selected={selected || undefined} disabled={pending !== null} onClick={() => { void choose(account.accountId); }} role="option" type="button">
88
+ <span><strong>{account.name ?? account.accountId}</strong><small>{roleLabel(account.role)}</small></span>
89
+ {selected ? <Check size={14} aria-label="Selected" /> : null}
90
+ </button>
91
+ </li>;
92
+ })}
93
+ </ul>}
94
+ {!state.selectedAccountId && state.publishingAccounts.length > 0 ? <p className="organizer-account-chooser-note">Choose the account you are working as.</p> : null}
95
+ {state.cyclotronLabAccess ? <p className="organizer-account-chooser-note" data-cyclotron-lab-access>Cyclotron lab access is on for you.</p> : null}
96
+ {error ? <p className="organizer-account-chooser-note" role="alert">{error}</p> : null}
97
+ </div>;
98
+ }
@@ -0,0 +1,91 @@
1
+ "use client";
2
+
3
+ import { generateClient } from "aws-amplify/data";
4
+ import type { Schema } from "../amplify/data/resource";
5
+ import { isLocalPreviewEnabled } from "../lib/local-preview";
6
+ import { createLocalPreviewReportingTrail } from "../lib/local-preview-seed";
7
+ import { EMPTY_STORY_REPORTING_TRAIL, type StoryReportingTrail, type TrailAssignment, type TrailAttachment, type TrailReference, type TrailThread, type TrailVersion } from "../lib/story-reporting-trail";
8
+ import { configureAmplifyClient } from "./amplify-client-provider";
9
+
10
+ type GraphqlResponse = { data?: Record<string, { items?: Record<string, unknown>[] | null; nextToken?: string | null } | null> | null; errors?: { message?: string }[] | null };
11
+ type GraphqlClient = { graphql: (options: Record<string, unknown>) => Promise<GraphqlResponse> };
12
+
13
+ const USER_POOL = "userPool";
14
+ const PAGE_LIMIT = 200;
15
+
16
+ async function listAll(client: GraphqlClient, field: string, selection: string, variableDeclarations: string, fieldArguments: string, variables: Record<string, unknown>): Promise<Record<string, unknown>[]> {
17
+ const rows: Record<string, unknown>[] = [];
18
+ let nextToken: string | null = null;
19
+ do {
20
+ const response: GraphqlResponse = await client.graphql({
21
+ query: `query ($limit: Int, $nextToken: String${variableDeclarations}) { ${field}(limit: $limit, nextToken: $nextToken${fieldArguments}) { items { ${selection} } nextToken } }`,
22
+ variables: { ...variables, limit: PAGE_LIMIT, nextToken },
23
+ authMode: USER_POOL,
24
+ });
25
+ if (response.errors?.length) throw new Error(response.errors.map(error => error.message ?? "GraphQL error").join("; "));
26
+ const connection = response.data?.[field];
27
+ rows.push(...((connection?.items ?? []).filter(Boolean) as Record<string, unknown>[]));
28
+ nextToken = connection?.nextToken ?? null;
29
+ } while (nextToken);
30
+ return rows;
31
+ }
32
+
33
+ const text = (value: unknown): string | null => typeof value === "string" ? value : null;
34
+
35
+ function parseMetadata(value: unknown): Record<string, unknown> {
36
+ if (typeof value === "string") {
37
+ try { const parsed = JSON.parse(value); return typeof parsed === "object" && parsed ? parsed as Record<string, unknown> : {}; } catch { return {}; }
38
+ }
39
+ return typeof value === "object" && value ? value as Record<string, unknown> : {};
40
+ }
41
+
42
+ async function getReference(client: GraphqlClient, referenceId: string): Promise<Record<string, unknown> | null> {
43
+ try {
44
+ const response = await client.graphql({ query: "query ($id: ID!) { getReference(id: $id) { id title sourceUri } }", variables: { id: referenceId }, authMode: USER_POOL });
45
+ return (response.data?.getReference as unknown as Record<string, unknown> | null) ?? null;
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+
51
+ /** Reads the whole reporting trail of one story from the backend; the local preview serves a snapshot instead. */
52
+ export async function loadStoryReportingTrail(lineageId: string, itemId: string): Promise<StoryReportingTrail> {
53
+ if (isLocalPreviewEnabled()) return createLocalPreviewReportingTrail(lineageId);
54
+ configureAmplifyClient();
55
+ const client = generateClient<Schema>() as unknown as GraphqlClient;
56
+ const [versionRows, assignmentRows, attachmentRows, relationRows] = await Promise.all([
57
+ listAll(client, "listItemsByLineageAndVersion", "id versionNumber versionState status stage headline title changeReason versionCreatedBy versionCreatedAt updatedAt", ", $lineageId: ID!", ", lineageId: $lineageId", { lineageId }).catch(() => []),
58
+ listAll(client, "listAssignmentsByItemLineageAndCreatedAt", "id title assignmentTypeKey status assigneeKey summary createdAt", ", $itemLineageId: ID!", ", itemLineageId: $itemLineageId", { itemLineageId: lineageId }).catch(() => []),
59
+ listAll(client, "listModelAttachmentsByOwnerRoleAndSortKey", "id role filename mediaType byteSize", ", $ownerId: ID!", ", ownerId: $ownerId", { ownerId: itemId }).catch(() => []),
60
+ listAll(client, "listSemanticRelations", "id predicate subjectKind subjectLineageId objectKind objectId objectLineageId metadata", ", $filter: ModelSemanticRelationFilterInput", ", filter: $filter", { filter: { or: [{ subjectLineageId: { eq: lineageId } }, { objectLineageId: { eq: lineageId } }] } }).catch(() => []),
61
+ ]);
62
+ const versions: TrailVersion[] = versionRows.map(row => ({
63
+ id: String(row.id), versionNumber: Number(row.versionNumber ?? 0), versionState: text(row.versionState), status: text(row.status), stage: text(row.stage),
64
+ headline: text(row.headline) ?? text(row.title), changeReason: text(row.changeReason), versionCreatedBy: text(row.versionCreatedBy), versionCreatedAt: text(row.versionCreatedAt), updatedAt: text(row.updatedAt),
65
+ })).sort((left, right) => right.versionNumber - left.versionNumber);
66
+ const assignments: TrailAssignment[] = await Promise.all(assignmentRows.map(async row => {
67
+ const eventRows = await listAll(client, "listAssignmentEventsByAssignmentAndCreatedAt", "id eventType fromStatus toStatus actorLabel note createdAt", ", $assignmentId: ID!", ", assignmentId: $assignmentId", { assignmentId: row.id }).catch(() => []);
68
+ return {
69
+ id: String(row.id), title: String(row.title ?? ""), assignmentTypeKey: String(row.assignmentTypeKey ?? ""), status: String(row.status ?? ""), assigneeKey: text(row.assigneeKey), summary: text(row.summary), createdAt: String(row.createdAt ?? ""),
70
+ events: eventRows.map(event => ({ id: String(event.id), eventType: String(event.eventType ?? ""), fromStatus: text(event.fromStatus), toStatus: text(event.toStatus), actorLabel: text(event.actorLabel), note: text(event.note), createdAt: String(event.createdAt ?? "") })),
71
+ };
72
+ }));
73
+ const anchorFilters = [{ primaryAnchorLineageId: { eq: lineageId } }, ...assignments.map(assignment => ({ primaryAnchorId: { eq: assignment.id } }))];
74
+ const threadRows = await listAll(client, "listMessageThreads", "id title threadKind summary", ", $filter: ModelMessageThreadFilterInput", ", filter: $filter", { filter: { or: anchorFilters } }).catch(() => []);
75
+ const threads: TrailThread[] = await Promise.all(threadRows.map(async row => {
76
+ const messageRows = await listAll(client, "listMessagesByThreadAndSequence", "id messageKind authorLabel summary content createdAt sequenceNumber", ", $threadId: ID!", ", threadId: $threadId", { threadId: row.id }).catch(() => []);
77
+ return { id: String(row.id), title: text(row.title), threadKind: text(row.threadKind), summary: text(row.summary), messages: messageRows.map(message => ({ id: String(message.id), sequenceNumber: typeof message.sequenceNumber === "number" ? message.sequenceNumber : null, messageKind: text(message.messageKind), authorLabel: text(message.authorLabel), summary: text(message.summary), content: text(message.content), createdAt: String(message.createdAt ?? "") })) };
78
+ }));
79
+ const referenceRelations = relationRows.filter(relation => relation.predicate === "uses_evidence" && relation.subjectLineageId === lineageId && relation.objectKind === "reference");
80
+ const references: TrailReference[] = await Promise.all(referenceRelations.map(async relation => {
81
+ const metadata = parseMetadata(relation.metadata);
82
+ const referenceRow = await getReference(client, String(relation.objectId));
83
+ return {
84
+ relationId: String(relation.id), predicate: String(relation.predicate ?? ""), referenceId: String(relation.objectId), referenceLineageId: text(relation.objectLineageId),
85
+ title: text(referenceRow?.title), sourceUri: text(referenceRow?.sourceUri),
86
+ role: metadata.role === "cited" ? "cited" as const : "consulted" as const, note: text(metadata.note), citationKey: text(metadata.citationKey), addedBy: text(metadata.addedBy), addedAt: text(metadata.addedAt),
87
+ };
88
+ }));
89
+ const attachments: TrailAttachment[] = attachmentRows.map(row => ({ id: String(row.id), role: text(row.role), filename: text(row.filename), mediaType: text(row.mediaType), byteSize: typeof row.byteSize === "number" ? row.byteSize : null }));
90
+ return { ...EMPTY_STORY_REPORTING_TRAIL, versions, assignments, threads, references, attachments };
91
+ }
@@ -0,0 +1,115 @@
1
+ "use client";
2
+
3
+ import Link from "next/link";
4
+ import { useEffect, useState } from "react";
5
+ import { getNewsroomNavHref } from "../lib/newsroom-nav";
6
+ import { storyMessageFeed, storyReportingTrailIsEmpty, type StoryReportingTrail, type TrailReference } from "../lib/story-reporting-trail";
7
+ import { loadStoryReportingTrail } from "./story-reporting-trail-client";
8
+
9
+ const timestampFormat = new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short" });
10
+
11
+ function formatTimestamp(value: string | null | undefined): string {
12
+ if (!value) return "";
13
+ const parsed = new Date(value);
14
+ return Number.isNaN(parsed.getTime()) ? value : timestampFormat.format(parsed);
15
+ }
16
+
17
+ function ReferenceSummary({ citedKeys, demo, focused, reference }: { citedKeys: readonly string[]; demo: boolean; focused: boolean; reference: TrailReference }) {
18
+ return <>
19
+ <div className="story-trail-row">
20
+ <strong>{reference.title ?? reference.referenceId}</strong>
21
+ <span className="story-trail-chip" data-story-trail-reference-role={reference.role}>{reference.role === "cited" ? "Cited" : "Consulted"}</span>
22
+ {reference.citationKey && citedKeys.includes(reference.citationKey) && <span className="story-trail-chip">In the text</span>}
23
+ </div>
24
+ <div className="story-trail-meta">{[reference.addedBy && `added by ${reference.addedBy}`, formatTimestamp(reference.addedAt), reference.citationKey && `citation key ${reference.citationKey}`].filter(Boolean).join(" · ")}</div>
25
+ {reference.note && <p data-story-trail-reference-summary={focused ? "focused" : undefined}>{reference.note}</p>}
26
+ {reference.sourceUri && <div className="story-trail-meta">{reference.sourceUri}</div>}
27
+ {reference.referenceLineageId && <Link href={getNewsroomNavHref(`/newsroom/references/${encodeURIComponent(reference.referenceLineageId)}`, demo)}>Open the full reference page</Link>}
28
+ </>;
29
+ }
30
+
31
+ function TrailSection({ count, children, title }: { count: number; children: React.ReactNode; title: string }) {
32
+ return <section className="story-trail-section" data-story-trail-section={title.toLowerCase()}>
33
+ <h3>{title} <small>{count}</small></h3>
34
+ {count ? children : <p className="story-trail-empty">None recorded.</p>}
35
+ </section>;
36
+ }
37
+
38
+ /**
39
+ * The messages and references of one story: draft versions, the assignments and agent events that did the work,
40
+ * notes and packets, the references behind it, and attached files. Container queries lay the sections out
41
+ * in one column in a narrow Board panel and side by side on a wide page.
42
+ */
43
+ export function StoryReportingTrailView({ citedKeys = [], demo = false, focusedReferenceId = null, itemId, lineageId, onOpenVersion, onShowReference, view = "messages" }: { citedKeys?: readonly string[]; demo?: boolean; focusedReferenceId?: string | null; itemId: string; lineageId: string | null | undefined; onOpenVersion?: (versionId: string) => void; onShowReference?: (referenceId: string) => void; view?: "messages" | "references" }) {
44
+ const [trail, setTrail] = useState<StoryReportingTrail | null>(null);
45
+ const [error, setError] = useState<string | null>(null);
46
+ useEffect(() => {
47
+ let cancelled = false;
48
+ setTrail(null); setError(null);
49
+ loadStoryReportingTrail(lineageId || itemId, itemId)
50
+ .then(loaded => { if (!cancelled) setTrail(loaded); })
51
+ .catch((reason: unknown) => { if (!cancelled) setError(reason instanceof Error ? reason.message : "Could not load the reporting trail."); });
52
+ return () => { cancelled = true; };
53
+ }, [itemId, lineageId]);
54
+ if (error) return <p role="alert" className="story-trail-empty">{error}</p>;
55
+ if (!trail) return <p className="story-trail-empty">Loading the reporting trail…</p>;
56
+ const messageFeed = storyMessageFeed(trail);
57
+ if (view === "references") return <div className="story-trail" data-story-trail data-story-trail-view="references">
58
+ <TrailSection count={trail.references.length} title="References">
59
+ <ul className="story-trail-list" data-story-references-list>
60
+ {trail.references.map(reference => <li data-story-reference-entry={reference.referenceId} data-story-reference-focused={reference.referenceId === focusedReferenceId ? "true" : undefined} key={reference.relationId} ref={reference.referenceId === focusedReferenceId ? node => node?.scrollIntoView({ block: "nearest" }) : undefined}>
61
+ <ReferenceSummary citedKeys={citedKeys} demo={demo} focused={reference.referenceId === focusedReferenceId} reference={reference} />
62
+ </li>)}
63
+ </ul>
64
+ </TrailSection>
65
+ </div>;
66
+ return <div className="story-trail" data-story-trail data-story-trail-view="messages">
67
+ {storyReportingTrailIsEmpty(trail) && <p className="story-trail-empty">No messages have been recorded for this story yet. Notes and packets, the work done on it, its draft versions and the references behind it appear here as agents and editors work on it.</p>}
68
+ <TrailSection count={messageFeed.length} title="Messages">
69
+ <ol className="story-trail-list" data-story-trail-feed>
70
+ {messageFeed.map(entry => entry.entryKind === "reference"
71
+ ? <li data-story-trail-feed-reference={entry.reference.referenceId} key={entry.id}>
72
+ <div className="story-trail-row"><span className="story-trail-chip">Reference found</span><span className="story-trail-meta">{formatTimestamp(entry.createdAt)}</span></div>
73
+ <ReferenceSummary citedKeys={citedKeys} demo={demo} focused={false} reference={entry.reference} />
74
+ {onShowReference && <button className="newsroom-article-link-button" data-story-trail-show-reference={entry.reference.referenceId} onClick={() => onShowReference(entry.reference.referenceId)} type="button">Show in the References list</button>}
75
+ </li>
76
+ : <li key={entry.id}>
77
+ <div className="story-trail-row"><strong>{entry.authorLabel ?? "Unknown author"}</strong>{entry.messageKind && <span className="story-trail-chip">{entry.messageKind.replace(/_/g, " ")}</span>}<span className="story-trail-meta">{formatTimestamp(entry.createdAt)}</span></div>
78
+ {entry.summary && <p><strong>{entry.summary}</strong></p>}
79
+ {entry.content && <details className="story-trail-message" open={messageFeed.length <= 3}><summary>Show the message</summary><pre>{entry.content}</pre></details>}
80
+ </li>)}
81
+ </ol>
82
+ </TrailSection>
83
+ <TrailSection count={trail.versions.length} title="Draft versions">
84
+ <ol className="story-trail-list">
85
+ {trail.versions.map((version, versionIndex) => <li key={version.id}>
86
+ <div className="story-trail-row"><strong>Version {version.versionNumber}</strong>{versionIndex === 0 && <span className="story-trail-chip">Latest</span>}<span className="story-trail-chip">{version.versionState ?? "draft"}</span>{version.stage && <span className="story-trail-chip">{version.stage}</span>}</div>
87
+ <div className="story-trail-meta">{[formatTimestamp(version.versionCreatedAt ?? version.updatedAt), version.versionCreatedBy, version.changeReason].filter(Boolean).join(" · ")}</div>
88
+ {onOpenVersion
89
+ ? <button className="newsroom-article-link-button" data-story-trail-open-version={version.versionNumber} onClick={() => onOpenVersion(version.id)} type="button">{versionIndex === 0 ? "Open the latest version" : "Open this older version (read-only)"}</button>
90
+ : <Link href={getNewsroomNavHref(`/newsroom/articles/${encodeURIComponent(version.id)}`, demo)}>{versionIndex === 0 ? "Open the latest version" : "Open this older version (read-only)"}</Link>}
91
+ </li>)}
92
+ </ol>
93
+ </TrailSection>
94
+ <TrailSection count={trail.assignments.length} title="Work">
95
+ <ol className="story-trail-list">
96
+ {trail.assignments.map(assignment => <li key={assignment.id}>
97
+ <div className="story-trail-row"><strong>{assignment.title}</strong> <span className="story-trail-chip">{assignment.status}</span></div>
98
+ <div className="story-trail-meta">{[assignment.assignmentTypeKey, assignment.assigneeKey, formatTimestamp(assignment.createdAt)].filter(Boolean).join(" · ")}</div>
99
+ {assignment.summary && <p>{assignment.summary}</p>}
100
+ {assignment.events.length > 0 && <ol className="story-trail-events">
101
+ {assignment.events.map(event => <li key={event.id}>
102
+ <span className="story-trail-meta">{formatTimestamp(event.createdAt)}</span> {event.eventType}{event.toStatus ? ` → ${event.toStatus}` : ""}{event.actorLabel ? ` by ${event.actorLabel}` : ""}{event.note ? `: ${event.note}` : ""}
103
+ </li>)}
104
+ </ol>}
105
+ <Link href={getNewsroomNavHref(`/newsroom/assignments/${encodeURIComponent(assignment.id)}`, demo)}>Open assignment</Link>
106
+ </li>)}
107
+ </ol>
108
+ </TrailSection>
109
+ <TrailSection count={trail.attachments.length} title="Files">
110
+ <ul className="story-trail-list">
111
+ {trail.attachments.map(attachment => <li key={attachment.id}><strong>{attachment.filename ?? attachment.id}</strong> <span className="story-trail-meta">{[attachment.role, attachment.mediaType].filter(Boolean).join(" · ")}</span></li>)}
112
+ </ul>
113
+ </TrailSection>
114
+ </div>;
115
+ }