@anthusai/papyrus 5.131.0-next.2 → 5.131.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.
- package/amplify/functions/automation-view/wire.js +4 -1
- package/amplify/functions/automation-view/wire.ts +4 -1
- package/amplify/functions/image-service/schema.js +10 -0
- package/amplify/functions/image-service/schema.ts +10 -0
- package/amplify/functions/image-service/wire.js +9 -0
- package/amplify/functions/image-service/wire.ts +9 -0
- package/components/announcement-lines.css +26 -0
- package/components/announcement-lines.tsx +157 -0
- package/components/announcement-marks.tsx +36 -0
- package/components/announcements-panel.tsx +10 -34
- package/components/newsroom-article-editor.tsx +4 -0
- package/components/newsroom-organizer.css +1 -1
- package/components/today-view.tsx +45 -0
- package/components/writing-guidelines-admin-panel.tsx +272 -126
- package/lib/announcement-lines.ts +95 -0
- package/lib/announcements-demo.ts +96 -0
- package/lib/announcements-door-client.ts +21 -0
- package/lib/announcements-fixture.ts +1 -19
- package/lib/announcements-model.ts +0 -21
- package/lib/content-actions-demo.ts +2 -0
- package/lib/guidelines/guideline-files.ts +257 -0
- package/lib/guidelines/writing-guidelines-admin.ts +3 -67
- package/lib/images/operations.generated.ts +210 -0
- package/lib/newsroom-articles.ts +5 -0
- package/lib/today-fixture.ts +7 -0
- package/lib/today-overview.ts +40 -0
- package/package.json +7 -2
- package/routes.manifest.json +1 -1
- package/lib/announcements-data.ts +0 -21
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the Story drawer and the Announcements list read (PPY-e4ae3a): one line for each Delivery, in words and marks. The words and the name of each mark (a Lucide icon) are said
|
|
3
|
+
* once, by the backend (`src/papyrus_content/announcements/lines.py`), so the console, `papyrus announcements` and the agents' tools show the same sentence. This module holds the
|
|
4
|
+
* shapes of the answer, the door that asks for it, and the few plain labels the page adds (a channel's name, a kind's name).
|
|
5
|
+
*/
|
|
6
|
+
import type { ImageEnvelope, ImageOperations } from "./images/operations.generated";
|
|
7
|
+
|
|
8
|
+
export type Marked = { words: string; mark: string };
|
|
9
|
+
|
|
10
|
+
/** A Delivery's review: `approval` is none, soft or hard (the words say what that means). Null for a Delivery that will not go. */
|
|
11
|
+
export type ReviewLine = Marked & { approval: "none" | "soft" | "hard" | string };
|
|
12
|
+
|
|
13
|
+
/** What needs a person's eye: Overdue (due, with no attempt), Outcome unknown (an attempt with no answer yet, until Caducus settles it), or a failed check. */
|
|
14
|
+
export type AttentionLine = Marked & { kind: "overdue" | "outcome_unknown" | "check_failed"; since?: string };
|
|
15
|
+
|
|
16
|
+
export type AttemptLine = Marked & { number: number; at?: string | null; outcome: "started" | "sent" | "refused" | "unknown"; code?: string | null };
|
|
17
|
+
|
|
18
|
+
export type DeliveryLine = Marked & {
|
|
19
|
+
id: string;
|
|
20
|
+
announcementId: string;
|
|
21
|
+
channel: string;
|
|
22
|
+
accountId: string;
|
|
23
|
+
generation?: number;
|
|
24
|
+
state: string;
|
|
25
|
+
approval?: ReviewLine | null;
|
|
26
|
+
releaseAt?: string | null;
|
|
27
|
+
lockAt?: string | null;
|
|
28
|
+
dueAt?: string | null;
|
|
29
|
+
waitingFor?: string | null;
|
|
30
|
+
nextAttemptAt?: string | null;
|
|
31
|
+
blockedReason?: string | null;
|
|
32
|
+
attempts: number;
|
|
33
|
+
lastAttempt?: AttemptLine | null;
|
|
34
|
+
resultUrl?: string | null;
|
|
35
|
+
attention: AttentionLine[];
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** The one open review flag of an Announcement whose draft was blocked: shown once, however many channels are blocked. */
|
|
39
|
+
export type ReviewFlagLine = Marked & { id: string; reason: string; ask?: string | null; raisedAt?: string | null };
|
|
40
|
+
|
|
41
|
+
export type AnnouncementEntry = {
|
|
42
|
+
id: string;
|
|
43
|
+
kind: string;
|
|
44
|
+
state: string;
|
|
45
|
+
releaseAt: string;
|
|
46
|
+
trigger?: string | null;
|
|
47
|
+
createdBy?: string | null;
|
|
48
|
+
versionLookedAt?: number | null;
|
|
49
|
+
reviewFlag?: ReviewFlagLine | null;
|
|
50
|
+
deliveries: DeliveryLine[];
|
|
51
|
+
/** In the list: the Stories the Announcement is about. */
|
|
52
|
+
stories?: { lineageId: string; title: string; versionLookedAt?: number | null }[];
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export type AnnouncementsWhere = { story: string; announcements: AnnouncementEntry[] };
|
|
56
|
+
export type AnnouncementsRecent = { announcements: AnnouncementEntry[]; overdue: DeliveryLine[]; next: string | null };
|
|
57
|
+
|
|
58
|
+
type DoorOperation = "announcements_where" | "announcements_recent";
|
|
59
|
+
type DoorResult = { announcements_where: AnnouncementsWhere; announcements_recent: AnnouncementsRecent };
|
|
60
|
+
|
|
61
|
+
/** The announcements door: reads only. The console's own sends GraphQL (`lib/announcements-door-client.ts`); the demo answers from seeded data. */
|
|
62
|
+
export type AnnouncementsDoor = <Name extends DoorOperation>(op: Name, input: ImageOperations[Name]["input"]) => Promise<ImageEnvelope<DoorResult[Name]>>;
|
|
63
|
+
|
|
64
|
+
/** The answer, or the plain sentence of why there is none. */
|
|
65
|
+
export async function readDoor<Name extends DoorOperation>(door: AnnouncementsDoor, op: Name, input: ImageOperations[Name]["input"]): Promise<DoorResult[Name]> {
|
|
66
|
+
let envelope: ImageEnvelope<DoorResult[Name]>;
|
|
67
|
+
try {
|
|
68
|
+
envelope = await door(op, input);
|
|
69
|
+
} catch (error) {
|
|
70
|
+
throw new Error(error instanceof Error && error.message ? error.message : "The announcements service did not answer. It may not be on this site yet.");
|
|
71
|
+
}
|
|
72
|
+
if (!envelope.ok) throw new Error(envelope.error.message || "The announcements service did not answer.");
|
|
73
|
+
return envelope.result;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A channel's name for a person: X, Email, and any other channel with a capital. */
|
|
77
|
+
export function channelName(channel: string): string {
|
|
78
|
+
return channel === "x" ? "X" : channel.charAt(0).toUpperCase() + channel.slice(1);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const KIND_NAMES: Record<string, string> = { story_published: "Story published", roundup: "Roundup", correction: "Correction" };
|
|
82
|
+
|
|
83
|
+
export function kindName(kind: string): string {
|
|
84
|
+
return KIND_NAMES[kind] ?? (kind.replace(/_/g, " ").replace(/^./, (letter) => letter.toUpperCase()));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** What a Delivery is waiting for, in words, when it names a time. Empty when it waits for nothing. */
|
|
88
|
+
export function waitingWords(line: DeliveryLine, when: (iso: string) => string): string {
|
|
89
|
+
if (line.waitingFor && line.nextAttemptAt) return `Waiting for the ${line.waitingFor} until ${when(line.nextAttemptAt)}`;
|
|
90
|
+
if (line.state === "drafted" || line.state === "ready") {
|
|
91
|
+
if (line.lockAt && line.lockAt !== line.releaseAt) return `Goes ${when(line.releaseAt ?? line.lockAt)}, locks ${when(line.lockAt)}`;
|
|
92
|
+
if (line.releaseAt) return `Goes ${when(line.releaseAt)}`;
|
|
93
|
+
}
|
|
94
|
+
return "";
|
|
95
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { AnnouncementEntry, AnnouncementsDoor, AnnouncementsRecent, AnnouncementsWhere, DeliveryLine } from "./announcement-lines";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Seeded announcements for `?demo=1` and the local preview: clearly fake Stories and accounts, no real address, and no channel that sends. Times are relative to now, so the
|
|
5
|
+
* Overdue line is always overdue and the Delivery that is not due is always ahead. The words and marks are the ones the backend says (`lines.py`, `approval_words.py`).
|
|
6
|
+
* X stays off: nothing here is, or could be, sent.
|
|
7
|
+
*/
|
|
8
|
+
const HOUR = 3_600_000;
|
|
9
|
+
const at = (hours: number, now: number) => new Date(now + hours * HOUR).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
10
|
+
|
|
11
|
+
const REVIEW = {
|
|
12
|
+
none: { words: "Released automatically by publication policy", mark: "bot", approval: "none" },
|
|
13
|
+
soft: { words: "Goes at its lock time unless a person stops it (publication policy)", mark: "hourglass", approval: "soft" },
|
|
14
|
+
hard: { words: "Waits for a person to release it (override: kind roundup)", mark: "hand", approval: "hard" },
|
|
15
|
+
person: { words: "Released by a person (Preview editor)", mark: "user-check", approval: "hard" },
|
|
16
|
+
} as const;
|
|
17
|
+
|
|
18
|
+
function line(announcementId: string, channel: string, accountId: string, fields: Partial<DeliveryLine> & Pick<DeliveryLine, "state" | "words" | "mark">): DeliveryLine {
|
|
19
|
+
return {
|
|
20
|
+
id: `${announcementId}#${channel}#${accountId}#g1`, announcementId, channel, accountId, generation: 1, approval: null, releaseAt: null, lockAt: null, dueAt: null, waitingFor: null,
|
|
21
|
+
nextAttemptAt: null, blockedReason: null, attempts: 0, lastAttempt: null, resultUrl: null, attention: [], ...fields,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The two published Stories of the local preview (lib/local-preview-seed.ts), as the preview titles them. */
|
|
26
|
+
const HARBOR = { lineageId: "preview-item-lineage-published-0", title: "Published: harbor safety review", versionLookedAt: 1 };
|
|
27
|
+
const LIGHTHOUSE = { lineageId: "preview-item-lineage-published-1", title: "Published: the lighthouse keepers' archive", versionLookedAt: 1 };
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Every demo Announcement. The harbor Story was posted, was corrected (the correction's attempt has no answer yet), and is in a roundup that waits for a person. The lighthouse Story
|
|
31
|
+
* is in that roundup too, has an overdue Delivery and has a blocked draft with its one review flag.
|
|
32
|
+
*/
|
|
33
|
+
export function demoAnnouncements(now: number = Date.now()): AnnouncementEntry[] {
|
|
34
|
+
const posted = "announcement-demo-posted", stuck = "announcement-demo-stuck", unsure = "announcement-demo-correction", roundup = "announcement-demo-roundup";
|
|
35
|
+
return [
|
|
36
|
+
{
|
|
37
|
+
id: roundup, kind: "roundup", state: "planned", releaseAt: at(20, now), createdBy: "announce", trigger: "weekly roundup", versionLookedAt: null, reviewFlag: null, stories: [HARBOR, LIGHTHOUSE],
|
|
38
|
+
deliveries: [line(roundup, "email", "site-one", { state: "drafted", words: "Draft", mark: "pencil-line", approval: REVIEW.hard, releaseAt: at(20, now), lockAt: at(20, now), dueAt: at(20, now) })],
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
id: unsure, kind: "correction", state: "released", releaseAt: at(-1, now), createdBy: "announce", trigger: "story corrected", versionLookedAt: 2, reviewFlag: null, stories: [HARBOR],
|
|
42
|
+
deliveries: [line(unsure, "x", "handle-demo", {
|
|
43
|
+
state: "sending", words: "Sending", mark: "send", approval: REVIEW.none, releaseAt: at(-1, now), lockAt: at(-1, now), attempts: 1,
|
|
44
|
+
lastAttempt: { number: 1, at: at(-0.5, now), outcome: "started", words: "Outcome unknown", mark: "?" },
|
|
45
|
+
attention: [{ kind: "outcome_unknown", words: "Outcome unknown", mark: "circle-help", since: at(-0.5, now) }],
|
|
46
|
+
})],
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
id: stuck, kind: "story_published", state: "released", releaseAt: at(-3, now), createdBy: "announce", trigger: "story published", versionLookedAt: 1,
|
|
50
|
+
reviewFlag: { id: "blocked-draft-demo", words: "Review requested: a draft was blocked", mark: "flag", reason: "A draft was blocked: the checks on its words failed: the post is over 280 characters.", ask: "email site-one: the words did not pass their checks, so nothing will be sent. Look at the draft and decide what should go out.", raisedAt: at(-2.5, now) },
|
|
51
|
+
stories: [LIGHTHOUSE],
|
|
52
|
+
deliveries: [
|
|
53
|
+
line(stuck, "email", "site-one", {
|
|
54
|
+
state: "blocked", words: "Blocked: check failed", mark: "ban", approval: REVIEW.soft, blockedReason: "check failed", releaseAt: at(-3, now), lockAt: at(-3, now),
|
|
55
|
+
attention: [{ kind: "check_failed", words: "The checks on its words failed", mark: "shield-alert", since: at(-2.5, now) }],
|
|
56
|
+
}),
|
|
57
|
+
line(stuck, "x", "handle-demo", {
|
|
58
|
+
state: "ready", words: "Ready", mark: "calendar-check", approval: REVIEW.none, releaseAt: at(-3, now), lockAt: at(-3, now), dueAt: at(-3, now),
|
|
59
|
+
attention: [{ kind: "overdue", words: "Overdue", mark: "clock-alert", since: at(-3, now) }],
|
|
60
|
+
}),
|
|
61
|
+
],
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
id: posted, kind: "story_published", state: "released", releaseAt: at(-30, now), createdBy: "announce", trigger: "story published", versionLookedAt: 1, reviewFlag: null, stories: [HARBOR],
|
|
65
|
+
deliveries: [
|
|
66
|
+
line(posted, "email", "site-one", {
|
|
67
|
+
state: "sent", words: "Sent", mark: "circle-check", approval: REVIEW.person, releaseAt: at(-30, now), lockAt: at(-30, now), attempts: 1,
|
|
68
|
+
lastAttempt: { number: 1, at: at(-29.9, now), outcome: "sent", words: "Sent", mark: "✓" },
|
|
69
|
+
}),
|
|
70
|
+
line(posted, "x", "handle-demo", { state: "dry_run", words: "Dry run: not sent", mark: "flask-conical", releaseAt: at(-30, now), lockAt: at(-30, now) }),
|
|
71
|
+
],
|
|
72
|
+
},
|
|
73
|
+
];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The Announcements a demo Story is about, as the drawer reads them (the Story's titles are the list's). */
|
|
77
|
+
function whereDemo(lineageId: string, now: number): AnnouncementsWhere {
|
|
78
|
+
const announcements = demoAnnouncements(now)
|
|
79
|
+
.filter((entry) => entry.stories?.some((story) => story.lineageId === lineageId))
|
|
80
|
+
.map(({ stories: _stories, ...entry }) => entry);
|
|
81
|
+
return { story: lineageId, announcements };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function recentDemo(now: number): AnnouncementsRecent {
|
|
85
|
+
const announcements = demoAnnouncements(now);
|
|
86
|
+
return { announcements, overdue: announcements.flatMap((entry) => entry.deliveries.filter((delivery) => delivery.attention.some((item) => item.kind === "overdue"))), next: null };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function createDemoAnnouncementsDoor(now: () => number = Date.now): AnnouncementsDoor {
|
|
90
|
+
return (async (op: string, input: { story?: string }) => {
|
|
91
|
+
const base = { ok: true as const, op, publication: "demo", warnings: [] };
|
|
92
|
+
if (op === "announcements_where") return { ...base, result: whereDemo(String(input.story ?? ""), now()) };
|
|
93
|
+
if (op === "announcements_recent") return { ...base, result: recentDemo(now()) };
|
|
94
|
+
return { ok: false as const, op, error: { code: "unknown_operation", message: `The demo has no ${op}.`, retryable: false, details: {} } };
|
|
95
|
+
}) as unknown as AnnouncementsDoor;
|
|
96
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The newsroom's front end for the announcements door: `announcementsRead`, which only reads (the Story drawer's lines and the Announcements list). The door takes who is asking
|
|
5
|
+
* from the signed-in session; the browser only says which operation and its input. What changes an announcement stays on the command line and in the agents' tools.
|
|
6
|
+
*/
|
|
7
|
+
import { generateClient } from "aws-amplify/data";
|
|
8
|
+
import { configureAmplifyClient } from "../components/amplify-client-provider";
|
|
9
|
+
import { callImageOperation } from "./images/operations.generated";
|
|
10
|
+
import type { AnnouncementsDoor } from "./announcement-lines";
|
|
11
|
+
|
|
12
|
+
const GRAPHQL_READ = `query AnnouncementsRead($op: String!, $input: AWSJSON) { announcementsRead(op: $op, input: $input) }`;
|
|
13
|
+
|
|
14
|
+
export const announcementsDoor: AnnouncementsDoor = ((op, input) => callImageOperation(op, input, async ({ op: name, input: body }) => {
|
|
15
|
+
configureAmplifyClient();
|
|
16
|
+
const client = generateClient({ authMode: "userPool" });
|
|
17
|
+
const response = (await client.graphql({ query: GRAPHQL_READ, variables: { op: name, input: JSON.stringify(body ?? {}) } })) as { data?: Record<string, unknown>; errors?: { message?: string }[] };
|
|
18
|
+
if (response.errors?.length) throw new Error("The announcements service did not answer. It may not be on this site yet.");
|
|
19
|
+
const raw = response.data?.announcementsRead;
|
|
20
|
+
return typeof raw === "string" ? JSON.parse(raw) : raw;
|
|
21
|
+
})) as AnnouncementsDoor;
|
|
@@ -1,27 +1,9 @@
|
|
|
1
1
|
import type { AnnouncementsApi } from "./announcements-client";
|
|
2
|
-
import type {
|
|
3
|
-
import type { AnnouncementsSource } from "./announcements-data";
|
|
2
|
+
import type { AnnouncementSettings, XStatus } from "./announcements-model";
|
|
4
3
|
|
|
5
4
|
/** Demo data for `?demo=1` and the local preview only. Nothing here is read by a signed-in site. */
|
|
6
5
|
const DEMO_REDIRECT_HANDLE = "mom_test";
|
|
7
6
|
|
|
8
|
-
const DEMO_ROWS: AnnouncementRow[] = [
|
|
9
|
-
{
|
|
10
|
-
id: "a1", storyTitle: "The machines that audit other machines", state: "dry_run", at: "2026-11-13T09:01:00Z",
|
|
11
|
-
text: "New on Machines on Machines: how automated auditors check other automated systems, and where they fall short.", link: "https://machines.example/articles/auditors?utm_source=x&utm_medium=social&utm_campaign=announcement", weightedLength: 126,
|
|
12
|
-
},
|
|
13
|
-
{
|
|
14
|
-
id: "a2", storyTitle: "Why the hardware shortage is a software story", state: "blocked", blockedReason: "Paused", at: "2026-11-13T10:30:00Z",
|
|
15
|
-
text: "A shortage of chips is changing how software gets written. Our latest on what teams are doing about it.", link: "https://machines.example/articles/shortage?utm_source=x&utm_medium=social&utm_campaign=announcement", weightedLength: 119,
|
|
16
|
-
},
|
|
17
|
-
{
|
|
18
|
-
id: "a3", storyTitle: "Reading a model's mind, one neuron at a time", state: "posted", at: "2026-11-12T14:00:00Z", postUrl: "https://x.example/mom_test/status/1", costUsd: 0.2,
|
|
19
|
-
text: "Interpretability researchers can now trace a single answer back to its parts. What that does and does not tell us.", link: "https://machines.example/articles/neurons?utm_source=x&utm_medium=social&utm_campaign=announcement", weightedLength: 133,
|
|
20
|
-
},
|
|
21
|
-
];
|
|
22
|
-
|
|
23
|
-
export const demoAnnouncementsSource: AnnouncementsSource = { list: async () => DEMO_ROWS };
|
|
24
|
-
|
|
25
7
|
export function createFixtureApi(initial?: { connected?: boolean }): AnnouncementsApi {
|
|
26
8
|
let settings: AnnouncementSettings = {
|
|
27
9
|
mode: "off",
|
|
@@ -29,21 +29,6 @@ export type XUsage = { postsThisCycle: string | null; postCap: string | null; ca
|
|
|
29
29
|
|
|
30
30
|
export type AnnouncementFailure = { ok: false; error: string; message?: string };
|
|
31
31
|
|
|
32
|
-
/** One announcement as the announcement backend (PPY-9f4d66) lists it. Only what this page shows. */
|
|
33
|
-
export type AnnouncementRow = {
|
|
34
|
-
id: string;
|
|
35
|
-
storyTitle: string;
|
|
36
|
-
state: "dry_run" | "ready" | "posting" | "posted" | "failed" | "blocked" | "withdrawn";
|
|
37
|
-
blockedReason?: string | null;
|
|
38
|
-
text: string;
|
|
39
|
-
link: string;
|
|
40
|
-
weightedLength: number;
|
|
41
|
-
at: string;
|
|
42
|
-
postUrl?: string | null;
|
|
43
|
-
costUsd?: number | null;
|
|
44
|
-
error?: string | null;
|
|
45
|
-
};
|
|
46
|
-
|
|
47
32
|
/** The three-star decision (PPY-0e8d66): nothing below it is public or announced. The function holds the same number. */
|
|
48
33
|
export const QUALITY_FLOOR_STARS = 3;
|
|
49
34
|
export const STAR_CHOICES = [3, 4, 5] as const;
|
|
@@ -133,12 +118,6 @@ export function failureText(failure: AnnouncementFailure): string {
|
|
|
133
118
|
return "Announcements are not available on this site yet.";
|
|
134
119
|
}
|
|
135
120
|
|
|
136
|
-
export function stateWords(state: AnnouncementRow["state"]): string {
|
|
137
|
-
return {
|
|
138
|
-
dry_run: "Dry run: not sent", ready: "Ready", posting: "Posting", posted: "Posted", failed: "Failed", blocked: "Blocked", withdrawn: "Withdrawn",
|
|
139
|
-
}[state];
|
|
140
|
-
}
|
|
141
|
-
|
|
142
121
|
/** The ratings the sort of the list keys to; the key of the saved section ids is stable even when a title changes. */
|
|
143
122
|
export function toggled<T>(list: readonly T[], value: T): T[] {
|
|
144
123
|
return list.includes(value) ? list.filter((entry) => entry !== value) : [...list, value];
|
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
type DemoArticleRecord,
|
|
24
24
|
} from "./newsroom-demo-articles";
|
|
25
25
|
import { createLocalPreviewEditableArticle, lineageForPreviewVersion, localPreviewScheduleFields, recordLocalPreviewDesk, recordLocalPreviewVersion, setLocalPreviewSchedule } from "./local-preview-seed";
|
|
26
|
+
import { createDemoAnnouncementsDoor } from "./announcements-demo";
|
|
26
27
|
import { scheduleFromFields } from "./story-schedule";
|
|
27
28
|
import { LOCAL_PREVIEW_TIME_ZONE } from "./schedule-zone";
|
|
28
29
|
import { sourceLineOffset, type ArticlesBackend, type EditableArticle, type NewsroomArticleRow } from "./newsroom-articles";
|
|
@@ -324,5 +325,6 @@ export function createDemoArticlesBackend(): ArticlesBackend {
|
|
|
324
325
|
starRating: record.starRating ?? null,
|
|
325
326
|
};
|
|
326
327
|
},
|
|
328
|
+
announcementsDoor: createDemoAnnouncementsDoor(),
|
|
327
329
|
};
|
|
328
330
|
}
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Guideline files in the console (PPY-b0c478): the writing guidelines are a set of files, `<name>/GUIDELINE.md`, each with flat front matter and a prose body
|
|
3
|
+
* (`src/papyrus_content/guidelines/files.py`, `field_files.py`). This module reads a set into the folders the editor shows, makes the text of a changed file, and
|
|
4
|
+
* names what each file does (its severity, the check it derives). It never decides whether a set is valid: the guidelines door refuses a set with problems and
|
|
5
|
+
* names each one by file and key (`guidelines_diff` and `guidelines_save`), and the editor shows those.
|
|
6
|
+
*/
|
|
7
|
+
import type { GuidelineDocument } from "./writing-guidelines-admin";
|
|
8
|
+
|
|
9
|
+
export const FILE_NAME = "GUIDELINE.md";
|
|
10
|
+
export const TYPE = "papyrus:Guideline";
|
|
11
|
+
export const SEVERITIES = ["error", "warn", "guidance"] as const;
|
|
12
|
+
export type Severity = (typeof SEVERITIES)[number];
|
|
13
|
+
export const LIST_KEYS = ["avoid", "prefer", "pattern"] as const;
|
|
14
|
+
export const KEY_ORDER = ["id", "type", "name", "description", "kind", "scope", "severity", "language", "avoid", "prefer", "pattern", "maxLength"] as const;
|
|
15
|
+
export const SEVERITY_WORDS: Record<Severity, string> = { error: "Error", warn: "Warning", guidance: "Guidance" };
|
|
16
|
+
export const SEVERITY_HINTS: Record<Severity, string> = {
|
|
17
|
+
error: "A writer must fix it. It derives an editorial check that blocks.",
|
|
18
|
+
warn: "A writer should look at it. It derives an editorial check that warns.",
|
|
19
|
+
guidance: "Read by writers and agents. It derives no check.",
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export type Scalar = string | number | boolean | null;
|
|
23
|
+
export type Meta = Record<string, Scalar | Scalar[]>;
|
|
24
|
+
export type FieldForm = "text" | "bullets" | "json";
|
|
25
|
+
export type FieldFile = { key: string; name: string; label: string; form: FieldForm; template: string };
|
|
26
|
+
|
|
27
|
+
const kebab = (key: string) => key.replace(/(?<!^)(?=[A-Z])/g, "-").toLowerCase();
|
|
28
|
+
const field = (key: string, label: string, form: FieldForm, template = ""): FieldFile => ({ key, name: kebab(key), label, form, template });
|
|
29
|
+
const OBJECT = "{}", LIST = "[]";
|
|
30
|
+
|
|
31
|
+
/** Every field file the writing guidelines know (the fixed names of `field_files.FORMS`), with what a new one starts with. */
|
|
32
|
+
export const FIELD_FILES: FieldFile[] = [
|
|
33
|
+
field("voice", "Voice", "json", '{\n "name": ""\n}'), field("audience", "Audience", "text"), field("headline", "Headline", "json", OBJECT), field("editorialAim", "Editorial aim", "text"),
|
|
34
|
+
field("register", "Register", "text"), field("tone", "Tone", "bullets"), field("sentenceStyle", "Sentence style", "bullets"), field("voicePatterns", "Voice patterns", "bullets"),
|
|
35
|
+
field("structure", "Structure", "bullets"), field("evidenceRules", "Evidence rules", "bullets"), field("bodyMarkus", "Guidance in your own words", "text"),
|
|
36
|
+
field("lexicon", "Words to prefer and avoid", "json", '{\n "prefer": [],\n "avoid": []\n}'), field("glossary", "Glossary", "json", LIST), field("exemplars", "Voice examples", "json", LIST),
|
|
37
|
+
field("constraints", "Binding rules", "json", LIST), field("publicationKey", "Publication key", "text"), field("judge", "Judge", "json", OBJECT), field("checks", "Checks", "json", OBJECT),
|
|
38
|
+
field("density", "Density", "json", OBJECT), field("rules", "Rules", "json", OBJECT), field("compare", "Compare", "json", OBJECT), field("referenceSamples", "Reference samples", "json", LIST),
|
|
39
|
+
field("locked", "Fields a section may not replace", "bullets"),
|
|
40
|
+
];
|
|
41
|
+
const BY_NAME = new Map(FIELD_FILES.map((item) => [item.name, item]));
|
|
42
|
+
export const fieldFileNamed = (name: string): FieldFile | undefined => BY_NAME.get(name);
|
|
43
|
+
|
|
44
|
+
/** A section's set holds additions only: these belong to the publication (or to a language overlay) and are never offered on a section tab. */
|
|
45
|
+
const PUBLICATION_OR_LANGUAGE_ONLY = new Set(["locked", "constraints", "publicationKey", "judge", "checks", "density", "rules", "compare", "referenceSamples", "register"]);
|
|
46
|
+
/** The field files a person can still add here (`register` is a language overlay's field, so it is never offered). */
|
|
47
|
+
export const addableFieldFiles = (present: Set<string>, section: string | null, lockedKeys: string[]): FieldFile[] =>
|
|
48
|
+
FIELD_FILES.filter((item) => !present.has(item.name) && item.key !== "register" && !(section !== null && (PUBLICATION_OR_LANGUAGE_ONLY.has(item.key) || lockedKeys.includes(item.key))));
|
|
49
|
+
|
|
50
|
+
// --- front matter ----------------------------------------------------------------------------------------------------------------------------------
|
|
51
|
+
|
|
52
|
+
/** The flat front matter subset of `front_matter.py`: `key: value` lines; text plain or quoted, a number, true, false, null, or a flat list inline or as `- item` lines. */
|
|
53
|
+
function scalar(raw: string): Scalar {
|
|
54
|
+
const text = raw.replace(/\s#.*$/, "").trim();
|
|
55
|
+
if (text === "" || text === "~" || /^null$/i.test(text)) return null;
|
|
56
|
+
if (/^true$/i.test(text)) return true;
|
|
57
|
+
if (/^false$/i.test(text)) return false;
|
|
58
|
+
if (/^-?\d+$/.test(text)) return Number(text);
|
|
59
|
+
if (/^-?\d+\.\d+$/.test(text)) return Number(text);
|
|
60
|
+
if (text.startsWith('"')) { const parsed = JSON.parse(text); if (typeof parsed !== "string") throw new Error("a quoted text is not valid"); return parsed; }
|
|
61
|
+
if (text.startsWith("'")) { if (!text.endsWith("'") || text.length < 2) throw new Error("a single-quoted text is not closed"); return text.slice(1, -1).replace(/''/g, "'"); }
|
|
62
|
+
return text;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function splitFlow(inner: string): string[] {
|
|
66
|
+
const items: string[] = []; let current = "", quote = "";
|
|
67
|
+
for (let index = 0; index < inner.length; index += 1) {
|
|
68
|
+
const char = inner[index];
|
|
69
|
+
if (quote) { current += char; if (char === "\\" && quote === '"') { current += inner[index += 1] ?? ""; } else if (char === quote) quote = ""; }
|
|
70
|
+
else if (char === '"' || char === "'") { quote = char; current += char; }
|
|
71
|
+
else if (char === ",") { items.push(current); current = ""; }
|
|
72
|
+
else current += char;
|
|
73
|
+
}
|
|
74
|
+
if (current.trim() || items.length) items.push(current);
|
|
75
|
+
return items.filter((item, at) => item.trim() !== "" || at < items.length - 1);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function parseFrontMatter(lines: string): Meta {
|
|
79
|
+
const meta: Meta = {};
|
|
80
|
+
const rows = lines.replace(/\r\n/g, "\n").split("\n");
|
|
81
|
+
for (let index = 0; index < rows.length; index += 1) {
|
|
82
|
+
const row = rows[index];
|
|
83
|
+
if (!row.trim() || row.trimStart().startsWith("#")) continue;
|
|
84
|
+
const found = /^([A-Za-z][A-Za-z0-9_-]*):(?:[ \t]+(.*))?$/.exec(row);
|
|
85
|
+
if (!found) throw new Error(`a line is not 'key: value': ${row.trim().slice(0, 60)}`);
|
|
86
|
+
const [, key, rest = ""] = found;
|
|
87
|
+
if (key in meta) throw new Error(`the key ${key} is there twice`);
|
|
88
|
+
const value = rest.trim();
|
|
89
|
+
if (value === "" || value.startsWith("#")) {
|
|
90
|
+
const items: Scalar[] = [];
|
|
91
|
+
while (index + 1 < rows.length && (!rows[index + 1].trim() || /^[ \t]*-([ \t]|$)/.test(rows[index + 1]))) {
|
|
92
|
+
index += 1;
|
|
93
|
+
if (rows[index].trim()) items.push(scalar(rows[index].trim().slice(1)));
|
|
94
|
+
}
|
|
95
|
+
meta[key] = items.length ? items : null;
|
|
96
|
+
} else if (value.startsWith("[")) {
|
|
97
|
+
const body = value.replace(/\s#.*$/, "").trim();
|
|
98
|
+
if (!body.endsWith("]")) throw new Error("a list is not closed");
|
|
99
|
+
meta[key] = splitFlow(body.slice(1, -1)).map(scalar);
|
|
100
|
+
} else if (value.startsWith("{")) throw new Error(`${key} is nested; the front matter is flat`);
|
|
101
|
+
else meta[key] = scalar(value);
|
|
102
|
+
}
|
|
103
|
+
return meta;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const dumpScalar = (value: Scalar): string => (typeof value === "string" ? JSON.stringify(value) : value === null ? "null" : String(value));
|
|
107
|
+
|
|
108
|
+
/** The front matter lines of a flat mapping, the way `front_matter.dumps` writes them: texts always double-quoted, lists inline. */
|
|
109
|
+
export function dumpFrontMatter(meta: Meta): string {
|
|
110
|
+
return Object.entries(meta).map(([key, value]) => `${key}: ${Array.isArray(value) ? `[${value.map(dumpScalar).join(", ")}]` : dumpScalar(value)}`).join("\n") + "\n";
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export const fileText = (meta: Meta, body: string): string => `---\n${dumpFrontMatter(meta)}---\n${body}`;
|
|
114
|
+
|
|
115
|
+
const FRONT = /^---[ \t]*\n([\s\S]*?)\n---[ \t]*(?:\n|$)([\s\S]*)$/;
|
|
116
|
+
|
|
117
|
+
// --- a set as folders ------------------------------------------------------------------------------------------------------------------------------
|
|
118
|
+
|
|
119
|
+
export type Folder = {
|
|
120
|
+
folder: string;
|
|
121
|
+
/** "field": a fixed name, one field of the house style. "rule": any other name, a guideline with a severity. */
|
|
122
|
+
role: "field" | "rule";
|
|
123
|
+
text: string;
|
|
124
|
+
meta: Meta;
|
|
125
|
+
body: string;
|
|
126
|
+
/** The files beside GUIDELINE.md (supporting files): kept as they are, and removed with the folder. */
|
|
127
|
+
extras: string[];
|
|
128
|
+
/** Why the front matter cannot be read here; the door names what is wrong with the file when it is saved. */
|
|
129
|
+
unreadable: string | null;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
export const pathOf = (folder: string): string => `${folder}/${FILE_NAME}`;
|
|
133
|
+
const folderOf = (path: string): string => path.split("/")[0];
|
|
134
|
+
|
|
135
|
+
export function foldersOf(files: Record<string, string>): Folder[] {
|
|
136
|
+
const names = [...new Set(Object.keys(files).filter((path) => path.includes("/")).map(folderOf))].sort();
|
|
137
|
+
return names.map((folder) => {
|
|
138
|
+
const text = files[pathOf(folder)] ?? "";
|
|
139
|
+
const extras = Object.keys(files).filter((path) => folderOf(path) === folder && path !== pathOf(folder)).sort();
|
|
140
|
+
const found = FRONT.exec(text.replace(/\r\n/g, "\n"));
|
|
141
|
+
let meta: Meta = {}, body = "", unreadable: string | null = null;
|
|
142
|
+
if (!found) unreadable = text ? "It does not open with a front matter block between two --- lines." : `It has no ${FILE_NAME}.`;
|
|
143
|
+
else { try { meta = parseFrontMatter(found[1]); body = found[2]; } catch (error) { unreadable = error instanceof Error ? error.message : "The front matter cannot be read."; } }
|
|
144
|
+
return { folder, role: BY_NAME.has(folder) ? "field" : "rule", text, meta, body, extras, unreadable };
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export const severityOf = (item: Folder): Severity => (SEVERITIES as readonly string[]).includes(item.meta.severity as string) ? (item.meta.severity as Severity) : "guidance";
|
|
149
|
+
export const textOf = (item: Folder, key: string): string => (typeof item.meta[key] === "string" ? (item.meta[key] as string) : "");
|
|
150
|
+
export const linesOf = (item: Folder, key: string): string[] => (Array.isArray(item.meta[key]) ? (item.meta[key] as Scalar[]).map(String) : []);
|
|
151
|
+
export const maxLengthOf = (item: Folder): string => (item.meta.maxLength == null ? "" : String(item.meta.maxLength));
|
|
152
|
+
export const lines = (text: string): string[] => text.split("\n").map((line) => line.trim()).filter(Boolean);
|
|
153
|
+
|
|
154
|
+
/** What a rule file can decide with no model: a listed word, a pattern, a length. Prose alone needs judgement. */
|
|
155
|
+
export const isDecidable = (item: Folder): boolean => linesOf(item, "avoid").length + linesOf(item, "pattern").length > 0 || item.meta.maxLength != null;
|
|
156
|
+
/** What derives a check (`derived_policies.rule_policy`): an `error` or `warn` rule file, named `guideline-<name>`. */
|
|
157
|
+
export const derivesCheck = (item: Folder): boolean => item.role === "rule" && severityOf(item) !== "guidance";
|
|
158
|
+
export const checkKey = (item: Folder): string => `guideline-${item.folder}`;
|
|
159
|
+
|
|
160
|
+
/** The text of a file after one front matter key is set. A key given no value is dropped. Key order is kept; a new key goes where the file form puts it. */
|
|
161
|
+
export function withMeta(item: Folder, patch: Record<string, Scalar | Scalar[] | undefined>): string {
|
|
162
|
+
const meta: Meta = { ...item.meta };
|
|
163
|
+
for (const [key, value] of Object.entries(patch)) { if (value === undefined || (Array.isArray(value) && value.length === 0)) delete meta[key]; else meta[key] = value; }
|
|
164
|
+
const known = KEY_ORDER.filter((key) => key in meta), rest = Object.keys(meta).filter((key) => !(KEY_ORDER as readonly string[]).includes(key));
|
|
165
|
+
return fileText(Object.fromEntries([...known, ...rest].map((key) => [key, meta[key]])), item.body);
|
|
166
|
+
}
|
|
167
|
+
export const withBody = (item: Folder, body: string): string => (item.unreadable ? item.text : fileText(item.meta, body));
|
|
168
|
+
|
|
169
|
+
// --- adding a file ---------------------------------------------------------------------------------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
export const lineageScope = (section: string | null): string => (section ? `section/${section.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "topic"}` : "publication");
|
|
172
|
+
const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
173
|
+
/** A random version 4 UUID from `getRandomValues`, which a page served over plain http (a LAN preview) still has; `randomUUID` needs a secure origin. */
|
|
174
|
+
export function newId(): string {
|
|
175
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
176
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
177
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
178
|
+
return `urn:uuid:${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function newRuleName(name: string, existing: string[]): string | null {
|
|
182
|
+
const word = name.trim();
|
|
183
|
+
if (!word) return "Give the rule a name.";
|
|
184
|
+
if (!NAME.test(word)) return "A name is lowercase words joined by hyphens, such as plain-claims.";
|
|
185
|
+
if (BY_NAME.has(word)) return `${word} is the name of a field file. Add it as a field file, or choose another name.`;
|
|
186
|
+
if (existing.includes(word)) return `There is already a file named ${word}.`;
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export function newRuleFile(name: string, section: string | null): string {
|
|
191
|
+
return fileText({ id: newId(), type: TYPE, name, description: "", kind: "writing", scope: lineageScope(section), severity: "guidance" }, "");
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function newFieldFile(item: FieldFile, section: string | null): string {
|
|
195
|
+
const body = item.form === "json" ? `\`\`\`json\n${item.template}\n\`\`\`\n` : item.form === "bullets" ? "- \n" : "\n";
|
|
196
|
+
return fileText({ id: newId(), type: TYPE, name: item.name, description: `${item.label} in the writing guidelines.`, kind: "writing", scope: lineageScope(section), severity: "guidance" }, body);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// --- what changed since the saved set --------------------------------------------------------------------------------------------------------------
|
|
200
|
+
|
|
201
|
+
export type FileState = "unchanged" | "changed" | "added" | "removed";
|
|
202
|
+
export const STATE_WORDS: Record<FileState, string> = { unchanged: "Unchanged", changed: "Changed", added: "Added", removed: "Removed" };
|
|
203
|
+
|
|
204
|
+
export function stateOf(folder: string, saved: Record<string, string>, draft: Record<string, string>): FileState {
|
|
205
|
+
const was = Object.keys(saved).filter((path) => folderOf(path) === folder), now = Object.keys(draft).filter((path) => folderOf(path) === folder);
|
|
206
|
+
if (!was.length) return now.length ? "added" : "unchanged";
|
|
207
|
+
if (!now.length) return "removed";
|
|
208
|
+
return was.length === now.length && was.every((path) => saved[path] === draft[path]) ? "unchanged" : "changed";
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Every folder of either set, in name order, with whether it changed. A removed folder is listed so it can be put back. */
|
|
212
|
+
export function folderNames(saved: Record<string, string>, draft: Record<string, string>): string[] {
|
|
213
|
+
return [...new Set([...Object.keys(saved), ...Object.keys(draft)].filter((path) => path.includes("/")).map(folderOf))].sort();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export const withoutFolder = (files: Record<string, string>, folder: string): Record<string, string> => Object.fromEntries(Object.entries(files).filter(([path]) => folderOf(path) !== folder));
|
|
217
|
+
/** The set with one folder as `from` has it (put back as saved), or without it when `from` has none. */
|
|
218
|
+
export const restoreFolder = (draft: Record<string, string>, saved: Record<string, string>, folder: string): Record<string, string> =>
|
|
219
|
+
({ ...withoutFolder(draft, folder), ...Object.fromEntries(Object.entries(saved).filter(([path]) => folderOf(path) === folder)) });
|
|
220
|
+
export const changedCount = (saved: Record<string, string>, draft: Record<string, string>): number => folderNames(saved, draft).filter((folder) => stateOf(folder, saved, draft) !== "unchanged").length;
|
|
221
|
+
|
|
222
|
+
/** The set the door answered with, as text by path (a value that is not text is left out, so a malformed answer shows as an empty set, never a crash). */
|
|
223
|
+
export const filesFrom = (value: Record<string, unknown> | undefined): Record<string, string> =>
|
|
224
|
+
Object.fromEntries(Object.entries(value ?? {}).filter((entry): entry is [string, string] => typeof entry[1] === "string"));
|
|
225
|
+
|
|
226
|
+
/** The fields locked by the site, read from the site's document view. */
|
|
227
|
+
export const lockedKeys = (siteDocument: GuidelineDocument | null): string[] => (Array.isArray(siteDocument?.locked) ? siteDocument!.locked.filter((item: unknown) => typeof item === "string") : []);
|
|
228
|
+
|
|
229
|
+
// --- the Story picker's example list ---------------------------------------------------------------------------------------------------------------
|
|
230
|
+
|
|
231
|
+
const JSON_BLOCK = /^```json\n([\s\S]*)\n```\n?$/;
|
|
232
|
+
export type Exemplar = { storyLineageId: string; note?: string };
|
|
233
|
+
|
|
234
|
+
/** The voice examples a `exemplars` file body holds, or null when the body is not the fenced list. */
|
|
235
|
+
export function exemplarsOf(body: string): Exemplar[] | null {
|
|
236
|
+
const found = JSON_BLOCK.exec(body.replace(/\r\n/g, "\n"));
|
|
237
|
+
if (!found) return null;
|
|
238
|
+
try { const value = JSON.parse(found[1]); return Array.isArray(value) ? value : null; } catch { return null; }
|
|
239
|
+
}
|
|
240
|
+
export const exemplarsBody = (items: Exemplar[]): string => `\`\`\`json\n${JSON.stringify(items, null, 2)}\n\`\`\`\n`;
|
|
241
|
+
|
|
242
|
+
/** The items of a bullets body (`- item` lines; a longer sentence continues on lines indented by two spaces). */
|
|
243
|
+
export const bulletsOf = (body: string): string[] => body.replace(/\r\n/g, "\n").split("\n").filter((line) => line.startsWith("- ")).map((line) => line.slice(2).trim()).filter(Boolean);
|
|
244
|
+
|
|
245
|
+
/** The fields the site locks, read from the site's own `locked` file (the Site tab edits it, so it shows what the draft says). */
|
|
246
|
+
export const lockedInFiles = (files: Record<string, string>): string[] => {
|
|
247
|
+
const found = foldersOf(files).find((item) => item.folder === "locked");
|
|
248
|
+
return found && !found.unreadable ? bulletsOf(found.body) : [];
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
/** What differs between two versions in the rule files (the field files are compared as the document they make). */
|
|
252
|
+
export function ruleFileChanges(older: Record<string, string>, newer: Record<string, string>): { folder: string; change: "added" | "changed" | "removed" }[] {
|
|
253
|
+
return folderNames(older, newer).filter((folder) => !BY_NAME.has(folder)).flatMap((folder) => {
|
|
254
|
+
const state = stateOf(folder, older, newer);
|
|
255
|
+
return state === "unchanged" ? [] : [{ folder, change: state }];
|
|
256
|
+
});
|
|
257
|
+
}
|