@anthusai/papyrus 5.131.0-next.1 → 5.131.0-next.3

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.
@@ -6,24 +6,32 @@
6
6
  * guidelines door's operations; nothing here knows how a document is stored. Flat backgrounds and rounded shapes only, Lucide icons only, and every state is an
7
7
  * icon plus a word. Design: docs/plans/guidelines-as-data.md section 8.
8
8
  */
9
+ import type { ReactNode } from "react";
9
10
  import { useCallback, useEffect, useMemo, useState } from "react";
10
- import { CircleAlert, CircleCheck, FilePenLine, History, Info, Layers, Link as LinkIcon, ListChecks, Loader, Lock, PenLine, Plus, Save, Search, Trash2, Eye } from "lucide-react";
11
+ import {
12
+ BookOpen, Check, ChevronDown, ChevronUp, CircleAlert, CircleCheck, Eye, FilePenLine, FilePlus, FileText, FileX, History, Info, Layers, Link as LinkIcon, ListChecks, Loader, Lock, OctagonAlert, PenLine,
13
+ Plus, Search, Trash2, TriangleAlert, X,
14
+ } from "lucide-react";
11
15
  import { Button } from "./ui/button";
12
16
  import { listPolicies } from "../lib/editorial-checks-client";
13
17
  import { guidelinesDoor, listPublishedStories } from "../lib/guidelines/guidelines-door-client";
14
18
  import {
15
- CHOICE_FIELDS, EDITORS_READ_ONLY, FIELD_LABELS, LIST_FIELDS, LOCKABLE_FIELDS, NO_WRITING_WARNING, SITE_TAB, addExemplar, derivedChecks, describeChange, diffDocuments,
16
- documentFromForm, formFromDocument, isLocked, matchStories, reasonProblem, sourceWords, storyTitle, valueWords,
17
- type FieldSources, type GuidelineDocument, type GuidelinesDoor, type ListPublishedStories, type PublishedStory, type WritingForm,
19
+ FIELD_FILES, FILE_NAME, SEVERITIES, SEVERITY_HINTS, SEVERITY_WORDS, STATE_WORDS, addableFieldFiles, changedCount, checkKey, exemplarsBody, exemplarsOf, fieldFileNamed, filesFrom, folderNames,
20
+ foldersOf, isDecidable, lines, linesOf, lockedInFiles, lockedKeys, maxLengthOf, newFieldFile, newRuleFile, newRuleName, pathOf, restoreFolder, ruleFileChanges, severityOf, stateOf, textOf, withBody,
21
+ withMeta, withoutFolder, type FieldFile, type FileState, type Folder, type Scalar,
22
+ } from "../lib/guidelines/guideline-files";
23
+ import {
24
+ EDITORS_READ_ONLY, FIELD_LABELS, NO_WRITING_WARNING, SITE_TAB, derivedChecks, describeChange, diffDocuments, matchStories, reasonProblem, sourceWords, storyTitle, valueWords,
25
+ type FieldSources, type GuidelineDocument, type GuidelinesDoor, type ListPublishedStories, type PublishedStory,
18
26
  } from "../lib/guidelines/writing-guidelines-admin";
19
27
 
20
28
  export type GuidelineSection = { key: string; name: string };
21
29
  type Version = { itemId: string; versionNumber: number; isCurrent?: boolean; at?: string; by?: string; byKind?: string; reason?: string };
22
30
  type Loaded = { status: "loading" } | { status: "error"; message: string } | { status: "none"; guard: string }
23
- | { status: "ready"; document: GuidelineDocument; guard: string; versionNumber: number; updatedBy: string; updatedAt: string };
31
+ | { status: "ready"; document: GuidelineDocument; files: Record<string, string>; guard: string; versionNumber: number; updatedBy: string; updatedAt: string };
24
32
  type Note = { tone: "ok" | "error" | "info"; text: string };
25
33
  type Page = "edit" | "effective" | "history";
26
- type CheckRow = { id: string; title: string; enabled: boolean; source: string };
34
+ type CheckRow = { id: string; title: string; enabled: boolean; source: string; policyKey?: string };
27
35
 
28
36
  const FIELD = "w-full vs-tile bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-70";
29
37
  const PANEL = "vs-panel bg-muted/60 p-4";
@@ -45,7 +53,7 @@ function SourceTag({ field, words }: { field: string; words: string }) {
45
53
  );
46
54
  }
47
55
 
48
- export function WritingGuidelinesAdmin({ door = guidelinesDoor, listStories = listPublishedStories, listChecks, sections = [], isAdmin = false, checksHref = "/newsroom/administration/editorial-checks" }: {
56
+ export function WritingGuidelinesAdmin({ door = guidelinesDoor, listStories = listPublishedStories, listChecks = realChecks, sections = [], isAdmin = false, checksHref = "/newsroom/administration/editorial-checks" }: {
49
57
  door?: GuidelinesDoor; listStories?: ListPublishedStories; listChecks?: () => Promise<CheckRow[]>; sections?: GuidelineSection[]; isAdmin?: boolean; checksHref?: string;
50
58
  }) {
51
59
  const [tab, setTab] = useState<string>(SITE_TAB);
@@ -54,6 +62,7 @@ export function WritingGuidelinesAdmin({ door = guidelinesDoor, listStories = li
54
62
  const [own, setOwn] = useState<Loaded>({ status: "loading" });
55
63
  const [resolved, setResolved] = useState<{ document: GuidelineDocument; fieldSources: FieldSources } | null>(null);
56
64
  const [note, setNote] = useState<Note | null>(null);
65
+ const [checks, setChecks] = useState<CheckRow[] | null>(null);
57
66
  const section = tab === SITE_TAB ? null : tab;
58
67
  const sectionName = sections.find((item) => item.key === tab)?.name ?? tab;
59
68
 
@@ -62,7 +71,7 @@ export function WritingGuidelinesAdmin({ door = guidelinesDoor, listStories = li
62
71
  const answer = await door("guidelines_get", { kind: "writing", ...(sectionKey ? { section: sectionKey } : {}) });
63
72
  if (answer.ok) {
64
73
  const result = answer.result;
65
- return { status: "ready", document: result.document, guard: result.expectedCurrentVersionId, versionNumber: result.versionNumber, updatedBy: result.updatedBy ?? "", updatedAt: result.updatedAt ?? "" };
74
+ return { status: "ready", document: result.document, files: filesFrom(result.files), guard: result.expectedCurrentVersionId, versionNumber: result.versionNumber, updatedBy: result.updatedBy ?? "", updatedAt: result.updatedAt ?? "" };
66
75
  }
67
76
  if (answer.error.code === "not_found") return { status: "none", guard: "none" };
68
77
  return { status: "error", message: answer.error.message };
@@ -84,6 +93,8 @@ export function WritingGuidelinesAdmin({ door = guidelinesDoor, listStories = li
84
93
  useEffect(() => { setOwn({ status: "loading" }); void load(); }, [load]);
85
94
 
86
95
  const siteDocument = site.status === "ready" ? site.document : null;
96
+ const checksKey = own.status === "ready" ? own.versionNumber : 0;
97
+ useEffect(() => { let live = true; void listChecks().then((all) => { if (live) setChecks(derivedChecks(all, section)); }).catch(() => { if (live) setChecks([]); }); return () => { live = false; }; }, [listChecks, section, checksKey]);
87
98
 
88
99
  if (site.status === "loading") return <p className="flex items-center gap-2" data-writing-guidelines="loading" role="status"><Loader aria-hidden className="size-4 animate-spin" /> Loading the writing guidelines…</p>;
89
100
  if (site.status === "error") return <p className="flex items-center gap-2" data-writing-guidelines="error" role="alert"><CircleAlert aria-hidden className="size-4" /> <strong>Problem:</strong> {site.message}</p>;
@@ -116,56 +127,100 @@ export function WritingGuidelinesAdmin({ door = guidelinesDoor, listStories = li
116
127
  <StatusLine note={note} />
117
128
 
118
129
  {page === "edit" ? (
119
- <EditPage door={door} isAdmin={isAdmin} key={tab} listStories={listStories} loaded={own} onSaved={async (text) => { await load(); setNote({ tone: "ok", text }); }} section={section} setNote={setNote} siteDocument={siteDocument} sectionName={sectionName} />
130
+ <EditPage door={door} drawn={checks} isAdmin={isAdmin} key={tab} listStories={listStories} loaded={own} onSaved={async (text) => { await load(); setNote({ tone: "ok", text }); }} section={section} setNote={setNote} siteDocument={siteDocument} sectionName={sectionName} />
120
131
  ) : null}
121
132
  {page === "effective" && section ? <EffectivePage own={own} resolved={resolved} sectionName={sectionName} siteDocument={siteDocument} /> : null}
122
133
  {page === "history" ? <HistoryPage door={door} section={section} /> : null}
123
- <ChecksList checksHref={checksHref} listChecks={listChecks} section={section} versionKey={own.status === "ready" ? own.versionNumber : 0} />
134
+ <ChecksList checksHref={checksHref} rows={checks} />
124
135
  </section>
125
136
  );
126
137
  }
127
138
 
128
- // --- editing ----------------------------------------------------------------------------------------------------------------------------------------
139
+ // --- editing: the set of guideline files ------------------------------------------------------------------------------------------------------------
140
+
141
+ type Preview = { files: string[]; fields: string[]; checks: string[] };
142
+ type PlanStep = { action: string; policy: string };
143
+
144
+ const SEVERITY_ICON = { error: OctagonAlert, warn: TriangleAlert, guidance: BookOpen } as const;
145
+ const STATE_ICON = { unchanged: Check, changed: PenLine, added: FilePlus, removed: FileX } as const;
146
+ const CHANGE_WORDS = { added: "added", changed: "changed", removed: "removed" } as const;
129
147
 
130
- function TextArea({ label, hint, value, onChange, disabled, field, rows = 3, locked }: { label: string; hint?: string; value: string; onChange: (value: string) => void; disabled: boolean; field: string; rows?: number; locked?: boolean }) {
148
+ const PILL = "inline-flex items-center gap-1 vs-pill bg-secondary px-2.5 py-0.5 font-medium text-secondary-foreground";
149
+ function Pill({ children, ...rest }: { children: ReactNode; [attribute: `data-${string}`]: string | boolean | undefined }) { return <span className={PILL} {...rest}>{children}</span>; }
150
+
151
+ /** A box of one value per line that keeps what is typed (an empty line while typing) and follows the file when it is rejected or reset. */
152
+ function LineBox({ disabled, value, onLines }: { disabled: boolean; value: string[]; onLines: (lines: string[]) => void }) {
153
+ const [text, setText] = useState(value.join("\n"));
154
+ useEffect(() => { if (JSON.stringify(lines(text)) !== JSON.stringify(value)) setText(value.join("\n")); }, [value]); // eslint-disable-line react-hooks/exhaustive-deps
155
+ return <textarea className={FIELD} disabled={disabled} onChange={(event) => { setText(event.target.value); onLines(lines(event.target.value)); }} rows={3} value={text} />;
156
+ }
157
+
158
+ function Labelled({ label, hint, children, field }: { label: string; hint?: string; children: React.ReactNode; field: string }) {
131
159
  return (
132
160
  <label className="block space-y-1" data-field={field}>
133
- <span className="flex flex-wrap items-center gap-2 text-sm font-medium">{label}{locked ? <span className="inline-flex items-center gap-1 text-xs text-muted-foreground"><Lock aria-hidden className="size-3" /> Locked by site</span> : null}</span>
161
+ <span className="block text-sm font-medium">{label}</span>
134
162
  {hint ? <span className="block text-xs text-muted-foreground">{hint}</span> : null}
135
- <textarea className={FIELD} disabled={disabled} onChange={(event) => onChange(event.target.value)} rows={rows} value={value} />
163
+ {children}
136
164
  </label>
137
165
  );
138
166
  }
139
167
 
140
- function EditPage({ door, isAdmin, listStories, loaded, onSaved, section, sectionName, setNote, siteDocument }: {
141
- door: GuidelinesDoor; isAdmin: boolean; listStories: ListPublishedStories; loaded: Loaded; onSaved: (text: string) => Promise<void>; section: string | null; sectionName: string;
168
+ function problemsOf(details: Record<string, unknown> | undefined): Record<string, string[]> {
169
+ const found: Record<string, string[]> = {};
170
+ const list = Array.isArray(details?.problems) ? (details!.problems as Record<string, unknown>[]) : [];
171
+ for (const problem of list) {
172
+ const folder = typeof problem.guideline === "string" ? problem.guideline : "";
173
+ const key = typeof problem.key === "string" && problem.key ? `${problem.key} ` : "";
174
+ (found[folder] ??= []).push(`${key}${typeof problem.message === "string" ? problem.message : "has a problem"}`);
175
+ }
176
+ return found;
177
+ }
178
+
179
+ function EditPage({ door, drawn, isAdmin, listStories, loaded, onSaved, section, sectionName, setNote, siteDocument }: {
180
+ door: GuidelinesDoor; drawn: CheckRow[] | null; isAdmin: boolean; listStories: ListPublishedStories; loaded: Loaded; onSaved: (text: string) => Promise<void>; section: string | null; sectionName: string;
142
181
  setNote: (note: Note | null) => void; siteDocument: GuidelineDocument | null;
143
182
  }) {
144
- const base = loaded.status === "ready" ? loaded.document : null;
145
- const [form, setForm] = useState<WritingForm>(() => formFromDocument(base));
183
+ const saved = useMemo(() => (loaded.status === "ready" ? loaded.files : {}), [loaded]);
184
+ const [draft, setDraft] = useState<Record<string, string>>(saved);
185
+ const [open, setOpen] = useState<string[]>([]);
146
186
  const [reason, setReason] = useState("");
147
- const [preview, setPreview] = useState<string[] | null>(null);
187
+ const [preview, setPreview] = useState<Preview | null>(null);
188
+ const [problems, setProblems] = useState<Record<string, string[]>>({});
148
189
  const [busy, setBusy] = useState(false);
149
190
  const [stories, setStories] = useState<PublishedStory[] | null>(null);
150
191
  const [query, setQuery] = useState("");
192
+ const [adding, setAdding] = useState<string | null>(null);
151
193
  const versionKey = loaded.status === "ready" ? loaded.versionNumber : loaded.status;
152
- useEffect(() => { setForm(formFromDocument(base)); setReason(""); setPreview(null); }, [versionKey]); // eslint-disable-line react-hooks/exhaustive-deps
194
+ useEffect(() => { setDraft(saved); setReason(""); setPreview(null); setProblems({}); setAdding(null); }, [versionKey]); // eslint-disable-line react-hooks/exhaustive-deps
153
195
  useEffect(() => { if (isAdmin) void listStories().then(setStories).catch(() => setStories([])); }, [isAdmin, listStories]);
154
196
 
155
- const locked = (field: string) => section !== null && isLocked(siteDocument, field);
156
- const disabled = !isAdmin || busy;
157
- const scope = section ? "section" : "publication";
158
197
  const guard = loaded.status === "ready" || loaded.status === "none" ? loaded.guard : "none";
159
- const set = (patch: Partial<WritingForm>) => { setForm((current) => ({ ...current, ...patch })); setPreview(null); };
198
+ const lockedHere = useMemo(() => (section ? lockedKeys(siteDocument) : []), [section, siteDocument]);
199
+ const lockedForSections = useMemo(() => lockedInFiles(draft), [draft]);
200
+ const names = useMemo(() => folderNames(saved, draft), [saved, draft]);
201
+ const items = useMemo(() => foldersOf(draft), [draft]);
202
+ const changed = changedCount(saved, draft);
203
+ const disabled = !isAdmin || busy;
204
+
205
+ const edit = (next: Record<string, string>) => { setDraft(next); setPreview(null); setProblems({}); };
206
+ const update = (item: Folder, text: string) => edit({ ...draft, [pathOf(item.folder)]: text });
207
+ const toggle = (folder: string) => setOpen((current) => (current.includes(folder) ? current.filter((name) => name !== folder) : [...current, folder]));
208
+ const reject = (folder: string) => edit(restoreFolder(draft, saved, folder));
209
+ const remove = (folder: string) => { edit(withoutFolder(draft, folder)); setOpen((current) => current.filter((name) => name !== folder)); };
160
210
 
161
- const draft = () => documentFromForm(form, base, scope);
211
+ const request = () => ({ kind: "writing", ...(section ? { section } : {}), files: draft as Record<string, unknown> });
212
+ const refused = (error: { message: string; details: Record<string, unknown> }) => { setProblems(problemsOf(error.details)); setNote({ tone: "error", text: error.message }); };
162
213
 
163
214
  const showChanges = async () => {
164
215
  setBusy(true); setNote(null);
165
216
  try {
166
- const answer = await door("guidelines_diff", { kind: "writing", ...(section ? { section } : {}), document: draft() });
167
- if (!answer.ok) { setNote({ tone: "error", text: answer.error.message }); return; }
168
- setPreview(answer.result.changes.length ? answer.result.changes.map(describeChange) : []);
217
+ const answer = await door("guidelines_diff", request());
218
+ if (!answer.ok) { refused(answer.error); return; }
219
+ const result = answer.result as typeof answer.result & { policyPlan?: PlanStep[] };
220
+ setPreview({
221
+ files: (result.fileChanges ?? []).map((change) => `${change.path} ${CHANGE_WORDS[change.change]}`), fields: result.changes.map(describeChange),
222
+ checks: (result.policyPlan ?? []).filter((step) => step.action !== "unchanged" && step.action !== "skipped").map((step) => `Check ${step.policy}: ${step.action}`),
223
+ });
169
224
  } catch (error) { setNote({ tone: "error", text: error instanceof Error ? error.message : "Could not work out what would change." }); } finally { setBusy(false); }
170
225
  };
171
226
 
@@ -174,127 +229,99 @@ function EditPage({ door, isAdmin, listStories, loaded, onSaved, section, sectio
174
229
  if (problem) { setNote({ tone: "error", text: problem }); return; }
175
230
  setBusy(true); setNote(null);
176
231
  try {
177
- const answer = await door("guidelines_save", { kind: "writing", ...(section ? { section } : {}), document: draft(), reason: reason.trim(), expectedCurrentVersionId: guard });
232
+ const answer = await door("guidelines_save", { ...request(), reason: reason.trim(), expectedCurrentVersionId: guard });
178
233
  if (!answer.ok) {
179
- setNote({ tone: "error", text: answer.error.code === "stale_version" ? "Someone else changed the guidelines while you were editing. They have been reloaded; make your change again." : answer.error.message });
180
- if (answer.error.code === "stale_version") await onSaved("The latest guidelines are loaded.");
181
- return;
234
+ if (answer.error.code === "stale_version") { setNote({ tone: "error", text: "Someone else changed the guidelines while you were editing. They have been reloaded; make your change again." }); await onSaved("The latest guidelines are loaded."); return; }
235
+ refused(answer.error); return;
182
236
  }
183
237
  await onSaved(answer.result.unchanged ? "Nothing changed, so no new version was made." : `Saved as version ${answer.result.versionNumber}.`);
184
238
  } catch (error) { setNote({ tone: "error", text: error instanceof Error ? error.message : "The guidelines could not be saved." }); } finally { setBusy(false); }
185
239
  };
186
240
 
241
+ const addRule = () => {
242
+ const name = (adding ?? "").trim();
243
+ if (newRuleName(name, names) !== null) return;
244
+ edit({ ...draft, [pathOf(name)]: newRuleFile(name, section) });
245
+ setOpen((current) => [...current, name]); setAdding(null);
246
+ };
247
+ const addField = (field: FieldFile) => { edit({ ...draft, [pathOf(field.name)]: newFieldFile(field, section) }); setOpen((current) => [...current, field.name]); };
248
+
187
249
  if (loaded.status === "loading") return <p className="flex items-center gap-2" role="status"><Loader aria-hidden className="size-4 animate-spin" /> Loading…</p>;
188
250
  if (loaded.status === "error") return <p className="flex items-center gap-2" role="alert"><CircleAlert aria-hidden className="size-4" /> <strong>Problem:</strong> {loaded.message}</p>;
189
251
 
190
- const matches = stories ? matchStories(stories, query) : [];
252
+ const ruleProblem = adding === null ? null : newRuleName(adding, names);
253
+ const addable = addableFieldFiles(new Set(names), section, lockedHere);
254
+ const lockedMissing = FIELD_FILES.filter((field) => lockedHere.includes(field.key) && !names.includes(field.name));
191
255
  return (
192
256
  <div className="space-y-4" data-writing-guidelines-page-body="edit">
193
- {section ? <p className="flex items-start gap-2 text-sm" data-section-explainer><Info aria-hidden className="mt-0.5 size-4 shrink-0" /> <span>These are the additions for <strong>{sectionName}</strong>. They are laid over the site&apos;s guidelines: prose and word lists add to the site&apos;s, and a choice replaces the site&apos;s unless the site locks it. See the In effect page for the result.</span></p> : null}
194
- {loaded.status === "none" ? <p className="text-sm text-muted-foreground" data-no-document>{section ? "This section has no additions yet, so it follows the site's guidelines." : "Nothing is saved yet. The first save makes version 1."}</p> : null}
195
-
196
- <div className={`${PANEL} space-y-4`}>
197
- <h4 className="font-semibold">Voice and audience</h4>
198
- <label className="block space-y-1" data-field="voice">
199
- <span className="flex flex-wrap items-center gap-2 text-sm font-medium">Voice name{locked("voice") ? <span className="inline-flex items-center gap-1 text-xs text-muted-foreground"><Lock aria-hidden className="size-3" /> Locked by site</span> : null}</span>
200
- <input className={FIELD} disabled={disabled || locked("voice")} onChange={(event) => set({ voiceName: event.target.value })} placeholder={section ? asPlaceholder(siteDocument?.voice?.name) : ""} value={form.voiceName} />
201
- </label>
202
- {CHOICE_FIELDS.map((field) => (
203
- <TextArea disabled={disabled || locked(field.key)} field={field.key} hint={field.hint} key={field.key} label={field.label} locked={locked(field.key)} onChange={(value) => set({ [field.key]: value } as Partial<WritingForm>)} rows={2} value={form[field.key as "audience" | "editorialAim"]} />
204
- ))}
205
- </div>
206
-
207
- <div className={`${PANEL} space-y-4`}>
208
- <h4 className="font-semibold">How it sounds</h4>
209
- {LIST_FIELDS.map((field) => (
210
- <TextArea disabled={disabled} field={field.key} hint={field.hint} key={field.key} label={field.label} onChange={(value) => set({ lists: { ...form.lists, [field.key]: value } })} value={form.lists[field.key] ?? ""} />
211
- ))}
212
- <TextArea disabled={disabled} field="bodyMarkus" hint="Free guidance in Markus, for anything the fields above do not cover." label={FIELD_LABELS.bodyMarkus} onChange={(value) => set({ bodyMarkus: value })} rows={6} value={form.bodyMarkus} />
213
- </div>
214
-
215
- <div className={`${PANEL} space-y-4`}>
216
- <h4 className="font-semibold">Words</h4>
217
- <TextArea disabled={disabled} field="lexicon.prefer" hint="Words and phrases to use. One per line." label="Prefer" onChange={(value) => set({ prefer: value })} value={form.prefer} />
218
- <TextArea disabled={disabled} field="lexicon.avoid" hint="Words and phrases to avoid. One per line. A section can add to these, never remove one." label="Avoid" onChange={(value) => set({ avoid: value })} value={form.avoid} />
219
- <div className="space-y-2" data-field="glossary">
220
- <p className="flex flex-wrap items-center gap-2 text-sm font-medium">Glossary{locked("glossary") ? <span className="inline-flex items-center gap-1 text-xs text-muted-foreground"><Lock aria-hidden className="size-3" /> Locked by site</span> : null}</p>
221
- <p className="text-xs text-muted-foreground">Current names for products and things, and the old names to avoid (separated by commas).</p>
222
- {form.glossary.map((row, index) => (
223
- <div className="grid gap-2 sm:grid-cols-[1fr_1fr_1fr_auto]" data-glossary-row={index} key={index}>
224
- <input aria-label={`Term ${index + 1}`} className={FIELD} disabled={disabled || locked("glossary")} onChange={(event) => set({ glossary: form.glossary.map((item, at) => (at === index ? { ...item, term: event.target.value } : item)) })} placeholder="Term" value={row.term} />
225
- <input aria-label={`Use ${index + 1}`} className={FIELD} disabled={disabled || locked("glossary")} onChange={(event) => set({ glossary: form.glossary.map((item, at) => (at === index ? { ...item, use: event.target.value } : item)) })} placeholder="Use" value={row.use} />
226
- <input aria-label={`Avoid ${index + 1}`} className={FIELD} disabled={disabled || locked("glossary")} onChange={(event) => set({ glossary: form.glossary.map((item, at) => (at === index ? { ...item, avoid: event.target.value } : item)) })} placeholder="Avoid, separated by commas" value={row.avoid} />
227
- <Button aria-label={`Remove glossary term ${index + 1}`} disabled={disabled || locked("glossary")} onClick={() => set({ glossary: form.glossary.filter((_, at) => at !== index) })} size="icon" type="button" variant="ghost"><Trash2 aria-hidden /></Button>
228
- </div>
229
- ))}
230
- {isAdmin && !locked("glossary") ? <Button data-add-glossary onClick={() => set({ glossary: [...form.glossary, { term: "", use: "", avoid: "" }] })} size="sm" type="button" variant="secondary"><Plus aria-hidden /> Add a term</Button> : null}
231
- </div>
232
- </div>
257
+ {section ? <p className="flex items-start gap-2 text-sm" data-section-explainer><Info aria-hidden className="mt-0.5 size-4 shrink-0" /> <span>These are the files for <strong>{sectionName}</strong>. They are laid over the site&apos;s guidelines: prose and word lists add to the site&apos;s, and a choice replaces the site&apos;s unless the site locks it. See the In effect page for the result.</span></p> : null}
258
+ {loaded.status === "none" && Object.keys(draft).length === 0 ? <p className="text-sm text-muted-foreground" data-no-document>{section ? "This section has no files yet, so it follows the site's guidelines." : "Nothing is saved yet. The first save makes version 1."}</p> : null}
233
259
 
234
- <div className={`${PANEL} space-y-3`} data-field="exemplars">
235
- <h4 className="font-semibold">Voice examples</h4>
236
- <p className="text-xs text-muted-foreground">Published Stories that show the voice. Agents read these as examples. Pick them from the Stories this publication has published.</p>
237
- {form.exemplars.length === 0 ? <p className="text-sm text-muted-foreground">No examples picked yet.</p> : null}
260
+ <div className={`${PANEL} space-y-3`} data-guideline-files>
261
+ <h4 className="flex items-center gap-2 font-semibold"><FileText aria-hidden className="size-4" /> Guideline files</h4>
262
+ <p className="text-xs text-muted-foreground">Each file is one guideline: front matter, then the prose. A field file (tone, audience, lexicon...) is part of the house style. A rule file has a severity: an error or a warning derives an editorial check, guidance does not.</p>
263
+ {names.length === 0 ? <p className="text-sm text-muted-foreground">There are no files yet.</p> : null}
238
264
  <ul className="space-y-2">
239
- {form.exemplars.map((row, index) => (
240
- <li className="vs-tile bg-background p-3 space-y-2" data-exemplar={row.storyLineageId} key={row.storyLineageId}>
241
- <div className="flex items-center justify-between gap-2"><strong className="text-sm">{storyTitle(stories ?? [], row.storyLineageId)}</strong>
242
- {isAdmin ? <Button aria-label={`Remove example ${storyTitle(stories ?? [], row.storyLineageId)}`} onClick={() => set({ exemplars: form.exemplars.filter((_, at) => at !== index) })} size="icon" type="button" variant="ghost"><Trash2 aria-hidden /></Button> : null}</div>
243
- <input aria-label={`Why ${storyTitle(stories ?? [], row.storyLineageId)} is a good example`} className={FIELD} disabled={disabled} onChange={(event) => set({ exemplars: form.exemplars.map((item, at) => (at === index ? { ...item, note: event.target.value } : item)) })} placeholder="What it shows about the voice" value={row.note} />
244
- </li>
245
- ))}
265
+ {names.map((folder) => {
266
+ const state = stateOf(folder, saved, draft);
267
+ const item = items.find((entry) => entry.folder === folder) ?? foldersOf(saved).find((entry) => entry.folder === folder)!;
268
+ const field = fieldFileNamed(folder);
269
+ const locked = Boolean(field && lockedHere.includes(field.key));
270
+ const isOpen = open.includes(folder) && state !== "removed";
271
+ return <FileCard changeState={state} disabled={disabled || locked} drawn={drawn} editable={isAdmin && !locked} field={field} isOpen={isOpen} item={item} key={folder} locked={locked}
272
+ lockedForSections={Boolean(field && !section && lockedForSections.includes(field.key))} onReject={() => reject(folder)} onRemove={() => remove(folder)} onToggle={() => toggle(folder)}
273
+ onUpdate={(text) => update(item, text)} problems={problems[folder] ?? []} query={query} savedItem={foldersOf(saved).find((entry) => entry.folder === folder) ?? null}
274
+ setQuery={setQuery} siteValue={section && field ? valueWords(siteDocument?.[field.key]) : ""} stories={stories} />;
275
+ })}
246
276
  </ul>
277
+ {lockedMissing.length ? (
278
+ <ul className="space-y-1" data-locked-fields>
279
+ {lockedMissing.map((field) => <li className="flex items-center gap-2 vs-tile bg-background px-3 py-2 text-sm" data-locked-field={field.key} key={field.key}><Lock aria-hidden className="size-4" /> {field.label}: Locked by site, so this section cannot add it.</li>)}
280
+ </ul>
281
+ ) : null}
247
282
  {isAdmin ? (
248
- <div className="space-y-2" data-story-picker>
249
- <label className="flex items-center gap-2 text-sm font-medium"><Search aria-hidden className="size-4" /> Find a published Story
250
- <input className={FIELD} onChange={(event) => setQuery(event.target.value)} placeholder="Part of the title" value={query} />
251
- </label>
252
- {stories === null ? <p className="text-sm text-muted-foreground" role="status">Loading published Stories…</p> : matches.length === 0 ? <p className="text-sm text-muted-foreground">No published Story matches.</p> : (
253
- <ul className="space-y-1">{matches.map((story) => (
254
- <li className="flex items-center justify-between gap-2 vs-tile bg-background px-3 py-2 text-sm" data-story-option={story.lineageId} key={story.lineageId}>
255
- <span>{story.title}</span>
256
- <Button disabled={form.exemplars.some((row) => row.storyLineageId === story.lineageId)} onClick={() => set({ exemplars: addExemplar(form.exemplars, story) })} size="sm" type="button" variant="secondary"><Plus aria-hidden /> {form.exemplars.some((row) => row.storyLineageId === story.lineageId) ? "Picked" : "Use as example"}</Button>
257
- </li>))}</ul>
258
- )}
283
+ <div className="space-y-3" data-add-files>
284
+ <div className="space-y-2">
285
+ <div className="flex flex-wrap items-center gap-2">
286
+ <Button data-add-rule disabled={busy} onClick={() => setAdding(adding === null ? "" : null)} size="sm" type="button" variant="secondary"><FilePlus aria-hidden /> Add a rule file</Button>
287
+ </div>
288
+ {adding !== null ? (
289
+ <div className="space-y-1" data-new-rule>
290
+ <label className="block space-y-1"><span className="text-sm font-medium">Name of the rule (the folder it lives in)</span>
291
+ <input className={FIELD} data-new-rule-name onChange={(event) => setAdding(event.target.value)} placeholder="plain-claims" value={adding} /></label>
292
+ {adding.trim() && ruleProblem ? <p className="flex items-center gap-2 text-sm" data-new-rule-problem role="alert"><CircleAlert aria-hidden className="size-4" /> {ruleProblem}</p> : null}
293
+ <Button data-new-rule-add disabled={ruleProblem !== null} onClick={addRule} size="sm" type="button"><Plus aria-hidden /> Add the file</Button>
294
+ </div>
295
+ ) : null}
296
+ </div>
297
+ {addable.length ? (
298
+ <div className="space-y-1">
299
+ <p className="text-sm font-medium">Add a field file</p>
300
+ <div className="flex flex-wrap gap-2">
301
+ {addable.map((field) => <Button data-add-field-file={field.name} disabled={busy} key={field.name} onClick={() => addField(field)} size="sm" type="button" variant="secondary"><Plus aria-hidden /> {field.label}</Button>)}
302
+ </div>
303
+ </div>
304
+ ) : null}
259
305
  </div>
260
306
  ) : null}
261
307
  </div>
262
308
 
263
- {!section ? (
264
- <div className={`${PANEL} space-y-3`} data-field="locked">
265
- <h4 className="flex items-center gap-2 font-semibold"><Lock aria-hidden className="size-4" /> Fields sections cannot change</h4>
266
- <p className="text-xs text-muted-foreground">A locked field is the site&apos;s alone: a section tab shows it as &quot;Locked by site&quot; and cannot replace it.</p>
267
- <div className="flex flex-wrap gap-2">
268
- {LOCKABLE_FIELDS.map((field) => {
269
- const on = form.locked.includes(field.key);
270
- return (
271
- <Button aria-pressed={on} data-lock-field={field.key} disabled={disabled} key={field.key} onClick={() => set({ locked: on ? form.locked.filter((item) => item !== field.key) : [...form.locked, field.key] })} size="sm" type="button" variant={on ? "default" : "secondary"}>
272
- {on ? <Lock aria-hidden /> : <Layers aria-hidden />}{field.label}: {on ? "locked" : "open"}
273
- </Button>
274
- );
275
- })}
276
- </div>
277
- {Array.isArray(base?.constraints) && base!.constraints.length ? (
278
- <div data-binding-rules><h5 className="mt-2 text-sm font-medium">Binding rules</h5><p className="text-xs text-muted-foreground">Only an admin who is a person can change these, with the command line. They always apply to every section.</p>
279
- <ul className="mt-1 list-disc pl-5 text-sm">{base!.constraints.map((item: any) => <li key={item.id}>{item.text}</li>)}</ul></div>
280
- ) : null}
281
- </div>
282
- ) : null}
283
-
284
309
  {isAdmin ? (
285
310
  <div className={`${PANEL} space-y-3`} data-save-bar>
286
311
  <label className="block space-y-1"><span className="text-sm font-medium">Why are you changing the guidelines? (required)</span>
287
312
  <input className={FIELD} data-save-reason onChange={(event) => setReason(event.target.value)} placeholder="For example: tighten the tone after the style review" value={reason} />
288
313
  </label>
314
+ <p className="flex items-center gap-2 text-sm" data-change-count><PenLine aria-hidden className="size-4" /> {changed === 0 ? "No file has changed." : `${changed} ${changed === 1 ? "file has" : "files have"} changed.`}</p>
289
315
  {preview ? (
290
316
  <div data-change-preview>
291
- <p className="text-sm font-medium">{preview.length ? `Saving would change ${preview.length} ${preview.length === 1 ? "field" : "fields"}:` : "Nothing would change."}</p>
292
- <ul className="list-disc pl-5 text-sm">{preview.map((line) => <li key={line}>{line}</li>)}</ul>
317
+ <p className="text-sm font-medium">{preview.files.length + preview.fields.length + preview.checks.length ? "Saving would change:" : "Nothing would change."}</p>
318
+ <ul className="list-disc pl-5 text-sm">{[...preview.files, ...preview.fields, ...preview.checks].map((line) => <li key={line}>{line}</li>)}</ul>
293
319
  </div>
294
320
  ) : null}
295
321
  <div className="flex flex-wrap gap-2">
296
322
  <Button data-show-changes disabled={busy} onClick={() => void showChanges()} type="button" variant="secondary"><Eye aria-hidden /> Show what would change</Button>
297
- <Button data-save disabled={busy || reasonProblem(reason) !== null} onClick={() => void save()} type="button"><Save aria-hidden /> Save as a new version</Button>
323
+ <Button data-save disabled={busy || reasonProblem(reason) !== null} onClick={() => void save()} type="button"><Check aria-hidden /> Accept and save as a new version</Button>
324
+ <Button data-reject-all disabled={busy || changed === 0} onClick={() => edit(saved)} type="button" variant="secondary"><X aria-hidden /> Reject all changes</Button>
298
325
  </div>
299
326
  {reasonProblem(reason) ? <p className="flex items-center gap-2 text-sm text-muted-foreground" data-reason-needed><Info aria-hidden className="size-4" /> Saving is possible once you give a reason.</p> : null}
300
327
  </div>
@@ -303,7 +330,127 @@ function EditPage({ door, isAdmin, listStories, loaded, onSaved, section, sectio
303
330
  );
304
331
  }
305
332
 
306
- const asPlaceholder = (value: unknown): string => (typeof value === "string" && value ? `Site: ${value}` : "");
333
+ function checkLine(item: Folder, savedItem: Folder | null, drawn: CheckRow[] | null): string {
334
+ if (item.role === "field") return "Part of the house style: writers and agents read it.";
335
+ const severity = severityOf(item);
336
+ if (severity === "guidance") return "Guidance only: no check is derived.";
337
+ const judgement = isDecidable(item) ? "" : " It needs judgement: the check shows the guideline to the writer and the editor and finds nothing by itself.";
338
+ const row = drawn?.find((entry) => entry.policyKey === checkKey(item));
339
+ if (savedItem && severityOf(savedItem) === severity && row) return `Derived check: ${row.title} (${row.enabled ? "on" : "off"}).${judgement}`;
340
+ return `A check is derived when you save.${judgement}`;
341
+ }
342
+
343
+ function FileCard({ changeState, disabled, drawn, editable, field, isOpen, item, locked, lockedForSections, onReject, onRemove, onToggle, onUpdate, problems, query, savedItem, setQuery, siteValue, stories }: {
344
+ changeState: FileState; disabled: boolean; drawn: CheckRow[] | null; editable: boolean; field: FieldFile | undefined; isOpen: boolean; item: Folder; locked: boolean; lockedForSections: boolean;
345
+ onReject: () => void; onRemove: () => void; onToggle: () => void; onUpdate: (text: string) => void; problems: string[]; query: string; savedItem: Folder | null; setQuery: (query: string) => void;
346
+ siteValue: string; stories: PublishedStory[] | null;
347
+ }) {
348
+ const severity = severityOf(item), SeverityIcon = SEVERITY_ICON[severity], StateIcon = STATE_ICON[changeState];
349
+ const meta = (patch: Record<string, Scalar | Scalar[] | undefined>) => onUpdate(withMeta(item, patch));
350
+ const list = (key: string) => (
351
+ <Labelled field={key} hint="One per line." label={{ avoid: "Words and phrases to avoid", prefer: "Words and phrases to prefer", pattern: "Patterns to find (regular expressions)" }[key] ?? key}>
352
+ <LineBox disabled={disabled} onLines={(next) => meta({ [key]: next })} value={linesOf(item, key)} />
353
+ </Labelled>
354
+ );
355
+ return (
356
+ <li className="vs-tile bg-background p-3 space-y-2" data-file-state={changeState} data-guideline-file={item.folder}>
357
+ <div className="flex flex-wrap items-center justify-between gap-2">
358
+ <div className="space-y-1">
359
+ <strong className="text-sm">{field?.label ?? item.folder}</strong> <span className="text-xs text-muted-foreground">{item.folder}/{FILE_NAME}</span>
360
+ <div className="flex flex-wrap items-center gap-2 text-xs">
361
+ <Pill data-file-severity={severity}><SeverityIcon aria-hidden className="size-3" /> Severity: {SEVERITY_WORDS[severity]}</Pill>
362
+ <Pill data-file-role={item.role}><FileText aria-hidden className="size-3" /> {item.role === "field" ? "Field file" : "Rule file"}</Pill>
363
+ <Pill data-file-change={changeState}><StateIcon aria-hidden className="size-3" /> {STATE_WORDS[changeState]}</Pill>
364
+ {locked ? <Pill data-file-locked><Lock aria-hidden className="size-3" /> Locked by site</Pill> : null}
365
+ {lockedForSections ? <Pill data-file-locked-for-sections><Lock aria-hidden className="size-3" /> Locked: sections cannot change it</Pill> : null}
366
+ </div>
367
+ </div>
368
+ <div className="flex flex-wrap items-center gap-2">
369
+ {changeState !== "unchanged" && editable ? <Button aria-label={`Reject the ${changeState === "removed" ? "removal" : "changes"} to ${item.folder}`} data-reject-file onClick={onReject} size="sm" type="button" variant="secondary"><X aria-hidden /> Reject</Button> : null}
370
+ {editable && changeState !== "removed" ? <Button aria-label={`Remove ${item.folder}`} data-remove-file onClick={onRemove} size="sm" type="button" variant="ghost"><Trash2 aria-hidden /> Remove</Button> : null}
371
+ {changeState !== "removed" ? <Button aria-expanded={isOpen} aria-label={`${isOpen ? "Close" : "Open"} ${item.folder}`} data-toggle-file onClick={onToggle} size="sm" type="button" variant="secondary">{isOpen ? <ChevronUp aria-hidden /> : <ChevronDown aria-hidden />}{isOpen ? "Close" : "Open"}</Button> : null}
372
+ </div>
373
+ </div>
374
+ {changeState === "removed" ? <p className="flex items-center gap-2 text-sm" data-file-removed><FileX aria-hidden className="size-4" /> Removed. The file is deleted when you accept and save.</p> : <p className="text-sm text-muted-foreground" data-check-line>{checkLine(item, savedItem, drawn)}</p>}
375
+ {problems.map((problem) => <p className="flex items-start gap-2 text-sm" data-file-problem key={problem} role="alert"><CircleAlert aria-hidden className="mt-0.5 size-4 shrink-0" /> <span><strong>Problem:</strong> {problem}</span></p>)}
376
+ {isOpen ? (
377
+ <div className="space-y-3" data-file-editor>
378
+ {item.unreadable ? (
379
+ <>
380
+ <p className="flex items-start gap-2 text-sm" role="alert"><CircleAlert aria-hidden className="mt-0.5 size-4 shrink-0" /> <span><strong>Problem:</strong> The front matter cannot be read here: {item.unreadable} Correct the whole file below.</span></p>
381
+ <Labelled field="file" label="The whole file"><textarea className={`${FIELD} font-mono`} disabled={disabled} onChange={(event) => onUpdate(event.target.value)} rows={12} value={item.text} /></Labelled>
382
+ </>
383
+ ) : (
384
+ <>
385
+ <Labelled field="description" label="Description"><input className={FIELD} disabled={disabled} onChange={(event) => meta({ description: event.target.value })} value={textOf(item, "description")} /></Labelled>
386
+ {item.role === "rule" ? (
387
+ <div className="space-y-1" data-field="severity">
388
+ <p className="text-sm font-medium">Severity</p>
389
+ <div className="flex flex-wrap gap-2">
390
+ {SEVERITIES.map((choice) => { const Icon = SEVERITY_ICON[choice]; return (
391
+ <Button aria-pressed={severity === choice} data-severity={choice} disabled={disabled} key={choice} onClick={() => meta({ severity: choice })} size="sm" type="button" variant={severity === choice ? "default" : "secondary"}><Icon aria-hidden /> {SEVERITY_WORDS[choice]}{severity === choice ? <span className="sr-only"> (selected)</span> : null}</Button>
392
+ ); })}
393
+ </div>
394
+ <p className="text-xs text-muted-foreground">{SEVERITY_HINTS[severity]}</p>
395
+ </div>
396
+ ) : <p className="text-xs text-muted-foreground" data-field="severity">Severity: Guidance. A field file is always guidance.</p>}
397
+ {item.role === "rule" ? <>{list("avoid")}{list("prefer")}{list("pattern")}
398
+ <Labelled field="maxLength" hint="The most characters a text may have. Leave empty for no limit." label="Longest text">
399
+ <input className={FIELD} disabled={disabled} inputMode="numeric" onChange={(event) => { const typed = event.target.value.trim(); if (typed === "") meta({ maxLength: undefined }); else if (/^\d+$/.test(typed)) meta({ maxLength: Number(typed) }); }} value={maxLengthOf(item)} />
400
+ </Labelled></> : null}
401
+ {siteValue ? <p className="text-xs text-muted-foreground" data-site-value>Site: {siteValue}</p> : null}
402
+ {item.folder === "constraints" ? <p className="text-xs text-muted-foreground">Binding rules always apply to every section.</p> : null}
403
+ {item.folder === "exemplars" ? <ExemplarPicker body={item.body} disabled={disabled} editable={editable} onBody={(body) => onUpdate(withBody(item, body))} query={query} setQuery={setQuery} stories={stories} /> : null}
404
+ <Labelled field="body" hint={item.role === "field" ? { text: "The text itself.", bullets: "One sentence per line, each starting with '- '. A longer sentence continues on lines indented by two spaces.", json: "One fenced json block." }[field?.form ?? "text"] : "The prose of the guideline, in your own words."} label="Body">
405
+ <textarea className={`${FIELD} ${field?.form === "json" ? "font-mono" : ""}`} disabled={disabled} onChange={(event) => onUpdate(withBody(item, event.target.value))} rows={field?.form === "json" ? 8 : 6} value={item.body} />
406
+ </Labelled>
407
+ {item.extras.length ? <p className="text-xs text-muted-foreground">Also holds {item.extras.join(", ")}, kept as they are.</p> : null}
408
+ </>
409
+ )}
410
+ </div>
411
+ ) : null}
412
+ </li>
413
+ );
414
+ }
415
+
416
+ function ExemplarPicker({ body, disabled, editable, onBody, query, setQuery, stories }: {
417
+ body: string; disabled: boolean; editable: boolean; onBody: (body: string) => void; query: string; setQuery: (query: string) => void; stories: PublishedStory[] | null;
418
+ }) {
419
+ const rows = exemplarsOf(body);
420
+ if (rows === null) return <p className="text-xs text-muted-foreground" data-exemplars-unreadable>The examples are not a list yet, so Stories cannot be picked here. Write the list in the body.</p>;
421
+ const matches = stories ? matchStories(stories, query) : [];
422
+ const picked = (story: PublishedStory) => rows.some((row) => row.storyLineageId === story.lineageId);
423
+ return (
424
+ <div className="space-y-2" data-field="exemplars">
425
+ <p className="text-sm font-medium">Voice examples</p>
426
+ <p className="text-xs text-muted-foreground">Published Stories that show the voice. Agents read these as examples.</p>
427
+ {rows.length === 0 ? <p className="text-sm text-muted-foreground">No examples picked yet.</p> : null}
428
+ <ul className="space-y-2">
429
+ {rows.map((row, index) => (
430
+ <li className="vs-tile bg-muted/60 p-3 space-y-2" data-exemplar={row.storyLineageId} key={row.storyLineageId}>
431
+ <div className="flex items-center justify-between gap-2"><strong className="text-sm">{storyTitle(stories ?? [], row.storyLineageId)}</strong>
432
+ {editable ? <Button aria-label={`Remove example ${storyTitle(stories ?? [], row.storyLineageId)}`} onClick={() => onBody(exemplarsBody(rows.filter((_, at) => at !== index)))} size="icon" type="button" variant="ghost"><Trash2 aria-hidden /></Button> : null}</div>
433
+ <input aria-label={`Why ${storyTitle(stories ?? [], row.storyLineageId)} is a good example`} className={FIELD} disabled={disabled} onChange={(event) => onBody(exemplarsBody(rows.map((item, at) => (at === index ? { storyLineageId: item.storyLineageId, ...(event.target.value ? { note: event.target.value } : {}) } : item))))} placeholder="What it shows about the voice" value={row.note ?? ""} />
434
+ </li>
435
+ ))}
436
+ </ul>
437
+ {editable ? (
438
+ <div className="space-y-2" data-story-picker>
439
+ <label className="flex items-center gap-2 text-sm font-medium"><Search aria-hidden className="size-4" /> Find a published Story
440
+ <input className={FIELD} onChange={(event) => setQuery(event.target.value)} placeholder="Part of the title" value={query} />
441
+ </label>
442
+ {stories === null ? <p className="text-sm text-muted-foreground" role="status">Loading published Stories…</p> : matches.length === 0 ? <p className="text-sm text-muted-foreground">No published Story matches.</p> : (
443
+ <ul className="space-y-1">{matches.map((story) => (
444
+ <li className="flex items-center justify-between gap-2 vs-tile bg-muted/60 px-3 py-2 text-sm" data-story-option={story.lineageId} key={story.lineageId}>
445
+ <span>{story.title}</span>
446
+ <Button disabled={disabled || picked(story)} onClick={() => onBody(exemplarsBody([...rows, { storyLineageId: story.lineageId }]))} size="sm" type="button" variant="secondary"><Plus aria-hidden /> {picked(story) ? "Picked" : "Use as example"}</Button>
447
+ </li>))}</ul>
448
+ )}
449
+ </div>
450
+ ) : null}
451
+ </div>
452
+ );
453
+ }
307
454
 
308
455
  // --- what is in effect ------------------------------------------------------------------------------------------------------------------------------
309
456
 
@@ -350,7 +497,8 @@ function HistoryPage({ door, section }: { door: GuidelinesDoor; section: string
350
497
  const [older, newer] = [...picked].sort((a, b) => a - b);
351
498
  const [first, second] = await Promise.all([older, newer].map((version) => door("guidelines_get", { kind: "writing", ...(section ? { section } : {}), version })));
352
499
  if (!first.ok || !second.ok) { setProblem("One of those versions could not be read."); return; }
353
- setLines(diffDocuments(first.result.document, second.result.document).map(describeChange));
500
+ setLines([...diffDocuments(first.result.document, second.result.document).map(describeChange),
501
+ ...ruleFileChanges(filesFrom(first.result.files), filesFrom(second.result.files)).map((change) => `Rule file ${change.folder}: ${change.change}`)]);
354
502
  };
355
503
 
356
504
  if (problem) return <p className="flex items-center gap-2" role="alert"><CircleAlert aria-hidden className="size-4" /> <strong>Problem:</strong> {problem}</p>;
@@ -386,17 +534,15 @@ function HistoryPage({ door, section }: { door: GuidelinesDoor; section: string
386
534
  // --- the checks drawn from these guidelines ---------------------------------------------------------------------------------------------------------
387
535
 
388
536
  async function realChecks(): Promise<CheckRow[]> {
389
- return (await listPolicies()).map((policy) => ({ id: policy.id, title: policy.title, enabled: policy.enabled, source: policy.source }));
537
+ return (await listPolicies()).map((policy) => ({ id: policy.id, title: policy.title, enabled: policy.enabled, source: policy.source, policyKey: policy.policyKey }));
390
538
  }
391
539
 
392
- function ChecksList({ checksHref, listChecks = realChecks, section, versionKey }: { checksHref: string; listChecks?: () => Promise<CheckRow[]>; section: string | null; versionKey: number }) {
393
- const [rows, setRows] = useState<CheckRow[] | null>(null);
394
- useEffect(() => { let live = true; void listChecks().then((all) => { if (live) setRows(derivedChecks(all, section)); }).catch(() => { if (live) setRows([]); }); return () => { live = false; }; }, [listChecks, section, versionKey]);
540
+ function ChecksList({ checksHref, rows }: { checksHref: string; rows: CheckRow[] | null }) {
395
541
  const shown = useMemo(() => rows ?? [], [rows]);
396
542
  return (
397
543
  <div className={`${PANEL} space-y-2`} data-derived-checks>
398
544
  <h4 className="flex items-center gap-2 font-semibold"><ListChecks aria-hidden className="size-4" /> Checks drawn from these guidelines</h4>
399
- <p className="text-xs text-muted-foreground">Saving keeps these editorial checks in step with the guidelines. A check you write or edit yourself is never changed by a save.</p>
545
+ <p className="text-xs text-muted-foreground">Saving keeps these editorial checks in step with the guidelines: each error or warning rule file derives one. A check you write or edit yourself is never changed by a save.</p>
400
546
  {rows === null ? <p className="text-sm text-muted-foreground" role="status">Loading the checks…</p> : shown.length === 0 ? <p className="text-sm text-muted-foreground">No checks are drawn from these guidelines yet.</p> : (
401
547
  <ul className="space-y-1">{shown.map((row) => <li className="vs-tile bg-background px-3 py-2 text-sm" data-derived-check={row.id} key={row.id}>{row.title} <span className="text-muted-foreground">({row.enabled ? "on" : "off"})</span></li>)}</ul>
402
548
  )}