@anthusai/papyrus 2.0.0-next.2 → 2.0.0-next.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/amplify/data/resource.js +15 -0
  2. package/amplify/data/resource.ts +17 -0
  3. package/amplify/data/schema.js +20 -0
  4. package/amplify/data/schema.ts +22 -0
  5. package/amplify/functions/assignment-action/data-access.js +88 -0
  6. package/amplify/functions/assignment-action/data-access.ts +87 -0
  7. package/amplify/functions/content-actions/handler.py +22 -0
  8. package/amplify/functions/editorial-checks/handler.py +14 -0
  9. package/amplify/functions/editorial-checks/requirements.txt +1 -0
  10. package/amplify/functions/editorial-checks/resource.js +43 -0
  11. package/amplify/functions/editorial-checks/resource.ts +60 -0
  12. package/amplify/functions/editorial-checks/schema.js +92 -0
  13. package/amplify/functions/editorial-checks/schema.ts +94 -0
  14. package/amplify/functions/editorial-checks/wire.js +49 -0
  15. package/amplify/functions/editorial-checks/wire.ts +57 -0
  16. package/amplify/functions/model-attachment-upload/handler.ts +1 -0
  17. package/amplify/functions/monitoring-view/handler.py +11 -0
  18. package/amplify/functions/monitoring-view/resource.js +24 -0
  19. package/amplify/functions/monitoring-view/resource.ts +34 -0
  20. package/amplify/functions/monitoring-view/schema.js +16 -0
  21. package/amplify/functions/monitoring-view/schema.ts +18 -0
  22. package/amplify/functions/monitoring-view/wire.js +37 -0
  23. package/amplify/functions/monitoring-view/wire.ts +47 -0
  24. package/amplify/functions/public-forms/core.js +247 -0
  25. package/amplify/functions/public-forms/core.ts +310 -0
  26. package/amplify/functions/public-forms/handler.ts +41 -0
  27. package/amplify/functions/public-forms/origins.js +35 -0
  28. package/amplify/functions/public-forms/origins.ts +43 -0
  29. package/amplify/functions/public-forms/resource.js +9 -0
  30. package/amplify/functions/public-forms/resource.ts +10 -0
  31. package/amplify/functions/public-forms/wire.js +25 -0
  32. package/amplify/functions/public-forms/wire.ts +32 -0
  33. package/amplify/functions/shared/python-bundle.js +20 -14
  34. package/amplify/functions/shared/python-bundle.ts +25 -18
  35. package/amplify/publication/redirect-and-index.js +83 -0
  36. package/amplify/publication/redirect-rules.js +61 -0
  37. package/amplify/publication/redirect-rules.ts +79 -0
  38. package/amplify/publication/s3-projection.js +5 -1
  39. package/amplify/publication/s3-projection.ts +7 -1
  40. package/amplify/site-backend-config.ts +10 -0
  41. package/amplify/site-backend.js +31 -0
  42. package/amplify/site-backend.ts +38 -0
  43. package/app/api/newsroom/curation/context/route.ts +9 -0
  44. package/app/api/newsroom/curation/priming/route.ts +9 -0
  45. package/app/api/newsroom/curation/publication/route.ts +9 -0
  46. package/bin/papyrus-infra.mjs +20 -1
  47. package/components/editorial-checks-admin-panel.tsx +347 -0
  48. package/components/editorial-finding-card.tsx +162 -0
  49. package/components/editorial-findings-panel.tsx +91 -0
  50. package/components/editorial-preview-popover.tsx +103 -0
  51. package/components/markus-body-editor.tsx +213 -0
  52. package/components/markus-ir-preview.tsx +147 -6
  53. package/components/monitoring-overview-view.tsx +240 -0
  54. package/components/monitoring-panel.tsx +40 -0
  55. package/components/newsroom-article-editor.tsx +136 -11
  56. package/components/newsroom-board-view.tsx +6 -7
  57. package/components/newsroom-curation-bootstrap.tsx +45 -0
  58. package/components/newsroom-ops-shell.tsx +7 -3
  59. package/components/newsroom-organizer.css +74 -61
  60. package/components/newsroom-references-view.tsx +14 -14
  61. package/components/newsroom-theme-fonts/broadsheet-green.css +10 -0
  62. package/components/newsroom-theme-fonts/broadsheet-green.tsx +6 -0
  63. package/components/newsroom-theme-fonts/newspaper-gothic.css +9 -0
  64. package/components/newsroom-theme-fonts/newspaper-gothic.tsx +6 -0
  65. package/components/newsroom-theme-fonts/night-desk.css +10 -0
  66. package/components/newsroom-theme-fonts/night-desk.tsx +6 -0
  67. package/components/newsroom-theme-fonts/refined-newsprint.css +11 -0
  68. package/components/newsroom-theme-fonts/refined-newsprint.tsx +6 -0
  69. package/components/newsroom-theme.css +39 -0
  70. package/components/newsroom-theme.tsx +33 -0
  71. package/components/publication-cyclotron-panel.tsx +10 -10
  72. package/components/reference-add-entry.tsx +75 -0
  73. package/components/reference-curation-controls.tsx +30 -21
  74. package/components/reference-cyclotron-priming.tsx +4 -4
  75. package/components/reference-cyclotron-suggestion.tsx +1 -1
  76. package/components/reference-priming.tsx +14 -10
  77. package/components/reference-section-suggestion.tsx +1 -1
  78. package/components/topic-steering-workspace.tsx +27 -2
  79. package/components/use-editorial-checks.ts +133 -0
  80. package/lib/category-repository.ts +11 -9
  81. package/lib/curation-routes.ts +342 -0
  82. package/lib/editorial-checks-backend.ts +16 -0
  83. package/lib/editorial-checks-client.ts +194 -0
  84. package/lib/editorial-checks-demo.ts +147 -0
  85. package/lib/editorial-checks-settings.ts +27 -0
  86. package/lib/editorial-checks.ts +171 -0
  87. package/lib/editorial-preview.ts +228 -0
  88. package/lib/monitoring-client.ts +29 -0
  89. package/lib/monitoring-overview-fixture.ts +51 -0
  90. package/lib/monitoring-overview.ts +144 -0
  91. package/lib/newsroom-board.ts +27 -2
  92. package/lib/relevance-status.ts +2 -2
  93. package/lib/site-brand-tenant.ts +11 -6
  94. package/lib/site-brand.ts +23 -3
  95. package/package.json +47 -3
  96. package/routes.manifest.json +34 -1
  97. package/components/newsroom-fonts/playfair-display-700.ttf +0 -0
  98. package/components/newsroom-fonts/playfair-display-900.ttf +0 -0
  99. package/components/newsroom-fonts/playfair-display-OFL.txt +0 -93
  100. package/components/newsroom-fonts/plus-jakarta-sans-400.ttf +0 -0
  101. package/components/newsroom-fonts/plus-jakarta-sans-600.ttf +0 -0
  102. package/components/newsroom-fonts/plus-jakarta-sans-OFL.txt +0 -93
  103. package/components/newsroom-newsprint-board.css +0 -7
@@ -27,9 +27,14 @@ import { addInvalidationPathAlarm } from "./publication/invalidation-alarm";
27
27
  import { applyCognitoDomainPrefix, authConfigFromEnv, defineSiteAuth, siteAuthRedirectUrls } from "./auth/resource";
28
28
  import { PROSPECTUS_SIGN_IN_CALLBACK_PATH, addProspectusGoogleOnlyClient } from "./auth/prospectus-google-client";
29
29
  import { defineSiteData } from "./data/resource";
30
+ import { editorialChecks } from "./functions/editorial-checks/resource";
31
+ import { monitoringView } from "./functions/monitoring-view/resource";
32
+ import { wireMonitoringView } from "./functions/monitoring-view/wire";
33
+ import { wireEditorialChecks } from "./functions/editorial-checks/wire";
30
34
  import { resolvePlugins } from "./plugins/registry";
31
35
  import { wirePlugins } from "./plugins/wire";
32
36
  import { assignmentAction } from "./functions/assignment-action/resource";
37
+ import { scopeAssignmentDataAccess } from "./functions/assignment-action/data-access";
33
38
  import { categoryAction } from "./functions/category-action/resource";
34
39
  import { ConsoleChatResponderStack } from "./functions/console-chat-responder/resource";
35
40
  import { contentActions, setSiteFilesForContentActionsBundle } from "./functions/content-actions/resource";
@@ -37,6 +42,9 @@ import { knowledgeQuery } from "./functions/knowledge-query/resource";
37
42
  import { manageUserRole } from "./functions/manage-user-role/resource";
38
43
  import { modelAttachmentUpload } from "./functions/model-attachment-upload/resource";
39
44
  import { newsroomSummary } from "./functions/newsroom-summary/resource";
45
+ import { derivePublicFormOrigins } from "./functions/public-forms/origins";
46
+ import { publicForms } from "./functions/public-forms/resource";
47
+ import { wirePublicForms } from "./functions/public-forms/wire";
40
48
  import { procedureAction } from "./functions/procedure-action/resource";
41
49
  import { readerSettings } from "./functions/reader-settings/resource";
42
50
  import { emailSubmissionProcessor } from "./functions/email-submission-processor/resource";
@@ -109,12 +117,15 @@ export function defineSiteBackend(papyrusSite: PapyrusSite) {
109
117
  auth: defineSiteAuth(authConfig),
110
118
  categoryAction,
111
119
  contentActions,
120
+ editorialChecks,
112
121
  data: defineSiteData(pluginDefinitions),
113
122
  knowledgeQuery,
114
123
  manageUserRole,
124
+ monitoringView,
115
125
  modelAttachmentUpload,
116
126
  newsroomSummary,
117
127
  procedureAction,
128
+ publicForms,
118
129
  readerSettings,
119
130
  emailSubmissionProcessor,
120
131
  sesInboundReceive,
@@ -387,10 +398,25 @@ export function defineSiteBackend(papyrusSite: PapyrusSite) {
387
398
  }
388
399
  grantCorporaRead(backend.knowledgeQuery.resources.lambda as LambdaFunction);
389
400
  grantNewsroomReadWrite(backend.assignmentAction.resources.lambda as LambdaFunction);
401
+ scopeAssignmentDataAccess(
402
+ backend.assignmentAction.resources.lambda as LambdaFunction,
403
+ backend.data.resources.graphqlApi.arn,
404
+ );
390
405
  grantNewsroomReadWrite(backend.categoryAction.resources.lambda as LambdaFunction);
391
406
  grantNewsroomReadWrite(backend.newsroomSummary.resources.lambda as LambdaFunction);
392
407
  const contentActionsLambda = backend.contentActions.resources.lambda as LambdaFunction;
393
408
  grantNewsroomReadWriteDelete(contentActionsLambda);
409
+ if ((activeBrand?.corpusKey ?? "").trim() !== "") {
410
+ // A deploy creates the publication's canonical corpus from the brand when the backend has none.
411
+ contentActionsLambda.addEnvironment("PAPYRUS_PUBLICATION_CORPUS_KEY", (activeBrand?.corpusKey ?? "").trim());
412
+ contentActionsLambda.addEnvironment("PAPYRUS_PUBLICATION_NAME", (activeBrand?.publicationName ?? activeBrand?.corpusKey ?? "").trim());
413
+ }
414
+ // AppSync validates the token; pending intake additionally binds its actor
415
+ // and publication to this deployment's pool and existing API endpoint.
416
+ contentActionsLambda.addEnvironment(
417
+ "PAPYRUS_USER_POOL_ISSUER",
418
+ `https://cognito-idp.${Stack.of(contentActionsLambda).region}.amazonaws.com/${backend.auth.resources.userPool.userPoolId}`,
419
+ );
394
420
  contentActionsLambda.addEnvironment(
395
421
  "PAPYRUS_GRAPHQL_ENDPOINT",
396
422
  backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl,
@@ -685,8 +711,18 @@ export function defineSiteBackend(papyrusSite: PapyrusSite) {
685
711
  }),
686
712
  );
687
713
 
714
+ const publicFormsEndpoint = wirePublicForms(backend, {
715
+ allowedOrigins: derivePublicFormOrigins({
716
+ explicit: site.publicForms?.allowedOrigins,
717
+ hosts: [activeBrand?.readerDeployment?.domain, ...(publication?.distribution?.aliases ?? [])],
718
+ urls: [site.revalidateBaseUrl, ...siteAuthRedirectUrls(authConfig)],
719
+ }),
720
+ honeypotFields: site.publicForms?.honeypotFields,
721
+ });
722
+
688
723
  backend.addOutput({
689
724
  custom: {
725
+ publicForms: { endpoint: publicFormsEndpoint },
690
726
  prospectusSignIn: prospectusGoogleOnlyClient
691
727
  ? { clientId: prospectusGoogleOnlyClient.ref, callbackPath: PROSPECTUS_SIGN_IN_CALLBACK_PATH }
692
728
  : null,
@@ -721,6 +757,8 @@ export function defineSiteBackend(papyrusSite: PapyrusSite) {
721
757
  : null,
722
758
  },
723
759
  });
760
+ wireEditorialChecks(backend);
761
+ wireMonitoringView(backend);
724
762
  wirePlugins(backend, plugins, contentActionsLambda);
725
763
 
726
764
  return backend;
@@ -0,0 +1,9 @@
1
+ import type { NextRequest } from "next/server";
2
+ import { handleCurationRoute } from "../../../../../lib/curation-routes";
3
+
4
+ export const dynamic = "force-dynamic";
5
+ export const runtime = "nodejs";
6
+
7
+ export function GET(request: NextRequest) {
8
+ return handleCurationRoute(request, "context");
9
+ }
@@ -0,0 +1,9 @@
1
+ import type { NextRequest } from "next/server";
2
+ import { handleCurationRoute } from "../../../../../lib/curation-routes";
3
+
4
+ export const dynamic = "force-dynamic";
5
+ export const runtime = "nodejs";
6
+
7
+ export function POST(request: NextRequest) {
8
+ return handleCurationRoute(request, "priming");
9
+ }
@@ -0,0 +1,9 @@
1
+ import type { NextRequest } from "next/server";
2
+ import { handleCurationRoute } from "../../../../../lib/curation-routes";
3
+
4
+ export const dynamic = "force-dynamic";
5
+ export const runtime = "nodejs";
6
+
7
+ export function POST(request: NextRequest) {
8
+ return handleCurationRoute(request, "publication");
9
+ }
@@ -19,6 +19,7 @@ const USAGE = [
19
19
  " papyrus-infra synth --account-stack github-oidc [--out cdk.out] [--account A] [--region R]",
20
20
  " papyrus-infra print-buildspec --site infra/site.json --app cms-production|cms-staging|reader",
21
21
  " papyrus-infra deploy-edge --stack NAME --template FILE [--adoption-template FILE --adopt-resources FILE] [--parameter KEY=VALUE]... [--delete-function NAME] [--only-branch main] [--only-app-id ID] [--region R]",
22
+ " papyrus-infra compile-edge-function --static-dir web [--out FILE]",
22
23
  " papyrus-infra deploy --site infra/site.json [--only-branch main] [--only-app-id ID] [--out cdk.out] [--account A] [--region R]",
23
24
  ].join("\n");
24
25
 
@@ -36,11 +37,29 @@ const resolveEnvironmentOrExit = () => {
36
37
  }
37
38
  };
38
39
  const command = args[0];
39
- if (command !== "synth" && command !== "print-buildspec" && command !== "deploy" && command !== "deploy-edge") {
40
+ if (command !== "synth" && command !== "print-buildspec" && command !== "deploy" && command !== "deploy-edge" && command !== "compile-edge-function") {
40
41
  console.error(USAGE);
41
42
  process.exit(command ? 1 : 0);
42
43
  }
43
44
 
45
+ if (command === "compile-edge-function") {
46
+ // The viewer-request CloudFront Function with the site's projection.json rules compiled in: for an edge stack that is
47
+ // not deployed by the CMS backend, so that no site writes its own redirect function.
48
+ const staticDir = opt("static-dir");
49
+ if (!staticDir) {
50
+ console.error(USAGE);
51
+ process.exit(1);
52
+ }
53
+ const { compileRedirectFunctionSource, readEdgeConfig } = await import("../amplify/publication/redirect-rules.js");
54
+ const functionSource = fs.readFileSync(new URL("../amplify/publication/redirect-and-index.js", import.meta.url), "utf8");
55
+ const config = readEdgeConfig(staticDir);
56
+ const compiled = compileRedirectFunctionSource(functionSource, config.rules, { negotiateMarkdown: config.negotiateMarkdown });
57
+ const out = opt("out");
58
+ if (out) fs.writeFileSync(path.resolve(out), compiled);
59
+ else process.stdout.write(compiled);
60
+ process.exit(0);
61
+ }
62
+
44
63
  if (command === "deploy-edge") {
45
64
  const buildAppId = process.env.AWS_APP_ID;
46
65
  const buildBranch = process.env.AWS_BRANCH;
@@ -0,0 +1,347 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useState } from "react";
4
+ import { Button } from "./ui/button";
5
+ import { Input } from "./ui/input";
6
+ import { Spinner } from "./ui/spinner";
7
+ import { Textarea } from "./ui/textarea";
8
+ import { describeProbability, type EditorialCheckResult } from "../lib/editorial-checks";
9
+ import {
10
+ DEFAULT_EDITORIAL_SETTINGS,
11
+ deletePolicy,
12
+ draftQuestions,
13
+ importStarterPack,
14
+ listPolicies,
15
+ loadSettings,
16
+ recalibrate,
17
+ savePolicy,
18
+ saveSettings,
19
+ tryPolicy,
20
+ type EditorialPolicyRecord,
21
+ type EditorialSettings,
22
+ } from "../lib/editorial-checks-client";
23
+
24
+ const STARTER_PACKS = [
25
+ { name: "ai-writing-tells", label: "AI-writing tells" },
26
+ { name: "plain-language", label: "Federal Plain Language Guidelines" },
27
+ { name: "asd-ste100", label: "ASD-STE100 Simplified Technical English" },
28
+ ] as const;
29
+ const POLICY_KEY = /^[a-z0-9][a-z0-9._-]*$/;
30
+
31
+ type Draft = {
32
+ isNew: boolean;
33
+ record: EditorialPolicyRecord;
34
+ detectorsText: string;
35
+ violatesText: string;
36
+ compliesText: string;
37
+ };
38
+
39
+ function emptyPolicy(): EditorialPolicyRecord {
40
+ return {
41
+ id: "",
42
+ policyKey: "",
43
+ scope: "publication",
44
+ version: 1,
45
+ title: "",
46
+ guidance: "",
47
+ severity: "warn",
48
+ enabled: true,
49
+ detectors: [],
50
+ examples: null,
51
+ rewriteGuidance: null,
52
+ source: "custom",
53
+ };
54
+ }
55
+
56
+ function draftFrom(record: EditorialPolicyRecord, isNew: boolean): Draft {
57
+ return {
58
+ isNew,
59
+ record,
60
+ detectorsText: JSON.stringify(record.detectors, null, 2),
61
+ violatesText: (record.examples?.violates ?? []).join("\n"),
62
+ compliesText: (record.examples?.complies ?? []).join("\n"),
63
+ };
64
+ }
65
+
66
+ function lines(text: string): string[] {
67
+ return text.split("\n").map((line) => line.trim()).filter(Boolean);
68
+ }
69
+
70
+ /** The policy as Humanus sees it (its key is the policy id). Throws on invalid detector JSON. */
71
+ function humanusPolicy(draft: Draft): Record<string, unknown> {
72
+ const detectors = JSON.parse(draft.detectorsText || "[]") as unknown;
73
+ if (!Array.isArray(detectors)) throw new Error("Detectors must be a JSON list.");
74
+ const violates = lines(draft.violatesText);
75
+ const complies = lines(draft.compliesText);
76
+ return {
77
+ id: draft.record.policyKey || "draft",
78
+ version: draft.record.version,
79
+ title: draft.record.title || "Draft policy",
80
+ guidance: draft.record.guidance || "Draft policy.",
81
+ severity: draft.record.severity,
82
+ enabled: true,
83
+ detectors,
84
+ ...(violates.length || complies.length ? { examples: { violates, complies } } : {}),
85
+ ...(draft.record.rewriteGuidance ? { rewriteGuidance: draft.record.rewriteGuidance } : {}),
86
+ };
87
+ }
88
+
89
+ export function EditorialChecksAdminPanel() {
90
+ const [policies, setPolicies] = useState<EditorialPolicyRecord[] | null>(null);
91
+ const [settings, setSettings] = useState<EditorialSettings>(DEFAULT_EDITORIAL_SETTINGS);
92
+ const [settingsExist, setSettingsExist] = useState(false);
93
+ const [draft, setDraft] = useState<Draft | null>(null);
94
+ const [starterPack, setStarterPack] = useState<string>(STARTER_PACKS[0].name);
95
+ const [message, setMessage] = useState<string | null>(null);
96
+ const [working, setWorking] = useState<string | null>(null);
97
+ const [tryText, setTryText] = useState("");
98
+ const [tryResult, setTryResult] = useState<EditorialCheckResult | null>(null);
99
+
100
+ const refresh = useCallback(async () => {
101
+ try {
102
+ const [loadedPolicies, loadedSettings] = await Promise.all([listPolicies(), loadSettings()]);
103
+ setPolicies(loadedPolicies);
104
+ setSettings(loadedSettings.settings);
105
+ setSettingsExist(loadedSettings.exists);
106
+ } catch (error) {
107
+ setMessage(`Error: ${error instanceof Error ? error.message : "could not load editorial checks"}`);
108
+ }
109
+ }, []);
110
+
111
+ useEffect(() => {
112
+ void refresh();
113
+ }, [refresh]);
114
+
115
+ const run = async (label: string, action: () => Promise<string | void>) => {
116
+ setWorking(label);
117
+ setMessage(null);
118
+ try {
119
+ const outcome = await action();
120
+ if (outcome) setMessage(outcome);
121
+ } catch (error) {
122
+ setMessage(`Error: ${error instanceof Error ? error.message : String(error)}`);
123
+ } finally {
124
+ setWorking(null);
125
+ }
126
+ };
127
+
128
+ const patchDraft = (patch: Partial<EditorialPolicyRecord>) => setDraft((current) => (current ? { ...current, record: { ...current.record, ...patch } } : current));
129
+
130
+ const save = () =>
131
+ run("save", async () => {
132
+ if (!draft) return;
133
+ const key = draft.record.policyKey.trim();
134
+ if (!POLICY_KEY.test(key)) throw new Error("The key must be lowercase letters, digits, dots, hyphens or underscores.");
135
+ if (!draft.record.title.trim() || !draft.record.guidance.trim()) throw new Error("A policy needs a title and guidance.");
136
+ const policy = humanusPolicy(draft);
137
+ const record: EditorialPolicyRecord = {
138
+ ...draft.record,
139
+ id: draft.isNew ? `${draft.record.scope}#${key}` : draft.record.id,
140
+ policyKey: key,
141
+ version: draft.isNew ? 1 : draft.record.version + 1,
142
+ detectors: policy.detectors as unknown[],
143
+ examples: (policy.examples as EditorialPolicyRecord["examples"]) ?? null,
144
+ };
145
+ await savePolicy(record, draft.isNew);
146
+ setDraft(null);
147
+ await refresh();
148
+ return `Saved ${record.title} (version ${record.version}).`;
149
+ });
150
+
151
+ return (
152
+ <section aria-labelledby="newsroom-editorial-checks-title" data-news-desk-admin-panel="editorial-checks">
153
+ <h3 id="newsroom-editorial-checks-title">Editorial checks</h3>
154
+ <p>
155
+ Policies the article editor checks drafts against. Rules match words and patterns; judgment questions are answered by a decision model, sentence by sentence.
156
+ Findings are advice: editors can dismiss them, and publishing is never blocked.
157
+ </p>
158
+ <p aria-live="polite" role="status">
159
+ {working ? <><Spinner /> Working…</> : message}
160
+ </p>
161
+
162
+ <h4>Policies</h4>
163
+ <div className="flex flex-wrap gap-2">
164
+ <Button onClick={() => { setDraft(draftFrom(emptyPolicy(), true)); setTryResult(null); }} size="sm" type="button">New policy</Button>
165
+ <select aria-label="Starter pack" onChange={(event) => setStarterPack(event.target.value)} value={starterPack}>
166
+ {STARTER_PACKS.map((pack) => <option key={pack.name} value={pack.name}>{pack.label}</option>)}
167
+ </select>
168
+ <Button
169
+ disabled={working !== null}
170
+ onClick={() => run("import", async () => {
171
+ const outcome = await importStarterPack(starterPack);
172
+ await refresh();
173
+ const label = STARTER_PACKS.find((pack) => pack.name === starterPack)?.label ?? starterPack;
174
+ return `${label}: ${outcome.created} policies added, ${outcome.skipped} already present.`;
175
+ })}
176
+ size="sm"
177
+ type="button"
178
+ variant="outline"
179
+ >
180
+ Add starter pack
181
+ </Button>
182
+ <Button
183
+ disabled={working !== null}
184
+ onClick={() => run("recalibrate", async () => {
185
+ const outcome = await recalibrate();
186
+ await refresh();
187
+ const notes = outcome.detectors.filter((d) => d.note).map((d) => `${d.policyId}/${d.detectorId}: ${d.note}`);
188
+ return `Recalibrated ${outcome.updated} ${outcome.updated === 1 ? "policy" : "policies"} from editors' decisions.${notes.length ? ` ${notes.join("; ")}` : ""}`;
189
+ })}
190
+ size="sm"
191
+ type="button"
192
+ variant="outline"
193
+ >
194
+ Recalibrate from editors&apos; decisions
195
+ </Button>
196
+ </div>
197
+ {policies === null ? <p>Loading…</p> : policies.length === 0 ? <p>No policies yet. Add the starter pack or write one.</p> : (
198
+ <table data-editorial-policies>
199
+ <thead>
200
+ <tr><th scope="col">Policy</th><th scope="col">Applies to</th><th scope="col">Severity</th><th scope="col">Detectors</th><th scope="col">On</th><th scope="col"><span className="sr-only">Actions</span></th></tr>
201
+ </thead>
202
+ <tbody>
203
+ {policies.map((policy) => (
204
+ <tr data-editorial-policy-row={policy.id} key={policy.id}>
205
+ <td>{policy.title}<br /><small>{policy.policyKey} · v{policy.version}</small></td>
206
+ <td>{policy.scope === "publication" ? "Whole publication" : `Desk: ${policy.scope}`}</td>
207
+ <td>{policy.severity}</td>
208
+ <td>{policy.detectors.length === 0 ? "Guidance only" : policy.detectors.length}</td>
209
+ <td>
210
+ <input
211
+ aria-label={`${policy.title} enabled`}
212
+ checked={policy.enabled}
213
+ onChange={(event) => void run("toggle", async () => {
214
+ await savePolicy({ ...policy, enabled: event.target.checked, version: policy.version + 1 }, false);
215
+ await refresh();
216
+ })}
217
+ type="checkbox"
218
+ />
219
+ </td>
220
+ <td>
221
+ <button onClick={() => { setDraft(draftFrom(policy, false)); setTryResult(null); }} type="button">Edit</button>
222
+ </td>
223
+ </tr>
224
+ ))}
225
+ </tbody>
226
+ </table>
227
+ )}
228
+
229
+ {draft ? (
230
+ <form
231
+ className="space-y-2"
232
+ data-editorial-policy-form
233
+ onSubmit={(event) => { event.preventDefault(); void save(); }}
234
+ >
235
+ <h4>{draft.isNew ? "New policy" : `Edit ${draft.record.title}`}</h4>
236
+ <label>Key <Input disabled={!draft.isNew} onChange={(event) => patchDraft({ policyKey: event.target.value })} value={draft.record.policyKey} /></label>
237
+ <label>Title <Input onChange={(event) => patchDraft({ title: event.target.value })} value={draft.record.title} /></label>
238
+ <label>
239
+ Applies to (publication, or a desk key){" "}
240
+ <Input disabled={!draft.isNew} onChange={(event) => patchDraft({ scope: event.target.value.trim() || "publication" })} value={draft.record.scope} />
241
+ </label>
242
+ <label>
243
+ Severity{" "}
244
+ <select onChange={(event) => patchDraft({ severity: event.target.value as EditorialPolicyRecord["severity"] })} value={draft.record.severity}>
245
+ <option value="error">Must fix</option>
246
+ <option value="warn">Should fix</option>
247
+ <option value="info">Consider</option>
248
+ </select>
249
+ </label>
250
+ <label>Guidance (what the policy asks, in plain words) <Textarea onChange={(event) => patchDraft({ guidance: event.target.value })} rows={3} value={draft.record.guidance} /></label>
251
+ <label>How to fix it (for rewrite suggestions) <Textarea onChange={(event) => patchDraft({ rewriteGuidance: event.target.value || null })} rows={2} value={draft.record.rewriteGuidance ?? ""} /></label>
252
+ <label>Examples that break it (one per line) <Textarea onChange={(event) => setDraft({ ...draft, violatesText: event.target.value })} rows={3} value={draft.violatesText} /></label>
253
+ <label>Examples that follow it (one per line) <Textarea onChange={(event) => setDraft({ ...draft, compliesText: event.target.value })} rows={3} value={draft.compliesText} /></label>
254
+ <label>
255
+ Detectors (JSON; see <code>humanus schema policy-pack-v1</code>)
256
+ <Textarea className="font-mono text-xs" onChange={(event) => setDraft({ ...draft, detectorsText: event.target.value })} rows={10} value={draft.detectorsText} />
257
+ </label>
258
+ <div className="flex flex-wrap gap-2">
259
+ <Button
260
+ disabled={working !== null || !draft.record.title.trim() || !draft.record.guidance.trim()}
261
+ onClick={() => run("draft", async () => {
262
+ const drafted = await draftQuestions(draft.record.title, draft.record.guidance);
263
+ const existing = JSON.parse(draft.detectorsText || "[]") as unknown[];
264
+ setDraft({ ...draft, detectorsText: JSON.stringify([...existing, ...drafted.detectors], null, 2) });
265
+ return `Added ${drafted.detectors.length} drafted judgment question(s). Review them before saving. ${drafted.notes.join(" ")}`;
266
+ })}
267
+ type="button"
268
+ variant="outline"
269
+ >
270
+ Draft judgment questions
271
+ </Button>
272
+ <Button disabled={working !== null} type="submit">Save</Button>
273
+ {!draft.isNew ? (
274
+ <Button
275
+ onClick={() => run("delete", async () => {
276
+ await deletePolicy(draft.record.id);
277
+ setDraft(null);
278
+ await refresh();
279
+ return "Policy deleted.";
280
+ })}
281
+ type="button"
282
+ variant="outline"
283
+ >
284
+ Delete
285
+ </Button>
286
+ ) : null}
287
+ <Button onClick={() => setDraft(null)} type="button" variant="ghost">Cancel</Button>
288
+ </div>
289
+
290
+ <fieldset className="space-y-2" data-editorial-try>
291
+ <legend>Try it on sample text (nothing is saved)</legend>
292
+ <Textarea onChange={(event) => setTryText(event.target.value)} rows={4} value={tryText} />
293
+ <Button
294
+ disabled={working !== null || !tryText.trim()}
295
+ onClick={() => run("try", async () => {
296
+ setTryResult(await tryPolicy(humanusPolicy(draft), tryText));
297
+ })}
298
+ size="sm"
299
+ type="button"
300
+ variant="outline"
301
+ >
302
+ Try policy
303
+ </Button>
304
+ {tryResult ? (
305
+ tryResult.findings.length === 0 ? <p>No findings.</p> : (
306
+ <ul data-editorial-try-findings>
307
+ {tryResult.findings.map((finding) => (
308
+ <li key={finding.id}>
309
+ {finding.status === "review" ? "Unsure: " : ""}“{finding.excerpt || "whole text"}” {describeProbability(finding) ? `(${describeProbability(finding)})` : ""}
310
+ </li>
311
+ ))}
312
+ </ul>
313
+ )
314
+ ) : null}
315
+ </fieldset>
316
+ </form>
317
+ ) : null}
318
+
319
+ <h4>Settings</h4>
320
+ <form
321
+ className="space-y-2"
322
+ data-editorial-settings
323
+ onSubmit={(event) => {
324
+ event.preventDefault();
325
+ void run("settings", async () => {
326
+ await saveSettings(settings, settingsExist);
327
+ setSettingsExist(true);
328
+ return "Settings saved.";
329
+ });
330
+ }}
331
+ >
332
+ <label><input checked={settings.enabled} data-editorial-enabled onChange={(event) => setSettings({ ...settings, enabled: event.target.checked })} type="checkbox" /> Run editorial checks for this publication (turning this off stops checks and rewrites; policies are kept)</label>
333
+ <label><input checked={settings.lanes.rules} onChange={(event) => setSettings({ ...settings, lanes: { ...settings.lanes, rules: event.target.checked } })} type="checkbox" /> Rule checks</label>
334
+ <label><input checked={settings.lanes.classifier} onChange={(event) => setSettings({ ...settings, lanes: { ...settings.lanes, classifier: event.target.checked } })} type="checkbox" /> Judgment checks (decision model)</label>
335
+ <label><input checked={settings.checkWhileTyping} onChange={(event) => setSettings({ ...settings, checkWhileTyping: event.target.checked })} type="checkbox" /> Check while editors type (after a short pause)</label>
336
+ <label><input checked={settings.publishWarning} onChange={(event) => setSettings({ ...settings, publishWarning: event.target.checked })} type="checkbox" /> Warn before publishing with open findings</label>
337
+ <label>Decision model <Input onChange={(event) => setSettings({ ...settings, classifierModel: event.target.value })} value={settings.classifierModel} /></label>
338
+ <label>Rewrite model <Input onChange={(event) => setSettings({ ...settings, rewriteModel: event.target.value })} value={settings.rewriteModel} /></label>
339
+ <label>Time limit for judgment checks (seconds, under 28) <Input max={26} min={1} onChange={(event) => setSettings({ ...settings, deadlineSeconds: Number(event.target.value) })} type="number" value={settings.deadlineSeconds} /></label>
340
+ <label>Input-token budget per check <Input min={1} onChange={(event) => setSettings({ ...settings, maxInputTokens: Number(event.target.value) })} type="number" value={settings.maxInputTokens} /></label>
341
+ <label>Past decisions shown to each judgment question <Input max={32} min={0} onChange={(event) => setSettings({ ...settings, maxExamplesPerQuestion: Number(event.target.value) })} type="number" value={settings.maxExamplesPerQuestion} /></label>
342
+ <label>House guidance for rewrites <Textarea onChange={(event) => setSettings({ ...settings, guidance: event.target.value })} rows={3} value={settings.guidance} /></label>
343
+ <Button disabled={working !== null} type="submit">Save settings</Button>
344
+ </form>
345
+ </section>
346
+ );
347
+ }