stanford-openarch 0.0.0-stage → 0.1.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/cli/check.js ADDED
@@ -0,0 +1,467 @@
1
+ // check.js — the conformance walk an aspiring member runs against its own
2
+ // adapter before applying: `openarch member check <base-url>`. Every check names
3
+ // the protocol section it comes from, says what it saw, and, when it fails, what
4
+ // to change. Pure function over the network: returns the report; the CLI
5
+ // renders it. The same walk is what the hub operator runs before registering a
6
+ // member, so "ready" means the same thing on both sides.
7
+
8
+ const TIMEOUT_MS = 45_000;
9
+ // an adapter's answer is read up to this many bytes, never without bound (ind-sec PR #3 review, nit)
10
+ const READ_MAX = 25 * 1024 * 1024;
11
+ async function readCappedBytes(res, max) {
12
+ const chunks = []; let n = 0;
13
+ for await (const c of res.body ?? []) { n += c.length; if (n > max) { try { await res.body.cancel(); } catch { /* dropped */ } throw new Error(`the answer is larger than ${max / 1024 / 1024} MB`); } chunks.push(c); }
14
+ return Buffer.concat(chunks.map((c) => Buffer.from(c)));
15
+ } // a federated member's search can fan out to a dozen archives; the walk reports the time it took
16
+ const TEXT_KINDS = new Set(["ocr", "born-digital", "transcript", "spreadsheet", "none"]);
17
+ const SLUG_RE = /^[a-z0-9][a-z0-9-]{1,40}$/;
18
+ const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
19
+ import { validateDeclarations, validateSharing, RIGHTS_BASIS } from "../server/lib/vocabulary.js";
20
+
21
+ async function call(base, path, { method = "GET", body, credential, query, headers: extra } = {}) {
22
+ const url = new URL(`${base}/openarch/v1${path}`);
23
+ for (const [k, v] of Object.entries(query ?? {})) if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
24
+ const headers = { Accept: "application/json", "X-OpenArch-Hub": "openarch-cli-check", "X-OpenArch-Key": "sha256:" + "0".repeat(64), "X-OpenArch-Partner": "openarch-cli", ...extra };
25
+ if (credential) headers.Authorization = `Bearer ${credential}`;
26
+ if (body !== undefined) headers["Content-Type"] = "application/json";
27
+ const t0 = Date.now();
28
+ try {
29
+ const res = await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(TIMEOUT_MS) });
30
+ const text = (await readCappedBytes(res, READ_MAX)).toString("utf8");
31
+ let json = null, parseError = null;
32
+ try { json = text ? JSON.parse(text) : null; } catch (e) { parseError = e.message; }
33
+ return { ok: true, status: res.status, json, text, parseError, ms: Date.now() - t0, contentType: res.headers.get("content-type") || "" };
34
+ } catch (e) {
35
+ const code = e?.cause?.code;
36
+ const why = e.name === "TimeoutError" ? `no answer in ${TIMEOUT_MS / 1000} s`
37
+ : code === "ENOTFOUND" || code === "EAI_AGAIN" ? `the name ${url.hostname} does not resolve (no DNS record yet?)`
38
+ : code === "ECONNREFUSED" ? `nothing is listening at ${url.host}`
39
+ : /CERT|SSL|TLS/i.test(code ?? "") ? `the https certificate was refused (${code})`
40
+ : code ? `${e.message} (${code})` : e.message;
41
+ return { ok: false, error: why, ms: Date.now() - t0 };
42
+ }
43
+ }
44
+
45
+ const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
46
+ const httpUrl = (u) => typeof u === "string" && /^https?:\/\/\S+$/i.test(u);
47
+ const squash = (t) => String(t ?? "").replace(/\s+/g, " ").trim();
48
+ /** The declared permalink pattern (https://…/{id}) as a whole-string regex, or null. */
49
+ const patternRe = (pattern) => (typeof pattern === "string" && pattern.includes("{id}")
50
+ ? new RegExp("^" + pattern.split("{id}").map((x) => x.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".+") + "$") : null);
51
+ /** A public address: https, and not this machine or a private network. */
52
+ export const isPublicHttps = (u) => {
53
+ let url; try { url = new URL(u); } catch { return false; }
54
+ if (url.protocol !== "https:") return false;
55
+ const h = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");
56
+ if (h === "localhost" || h.endsWith(".localhost") || h.endsWith(".local") || h.endsWith(".internal") || h === "::1" || h.startsWith("fc") || h.startsWith("fd") || h.startsWith("fe80")) return false;
57
+ const v4 = h.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
58
+ if (v4) { const [a, b] = [Number(v4[1]), Number(v4[2])]; if (a === 10 || a === 127 || a === 0 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127)) return false; }
59
+ return true;
60
+ };
61
+ // the reference member's identity and documents: an adapter still carrying them is the example, not an archive
62
+ const EXAMPLE_SIGNS = (m, firstId) => [
63
+ m?.member === "example" && 'member "example"',
64
+ /example (harbor )?archive/i.test(m?.name ?? "") && `name "${m.name}"`,
65
+ /@example\.(edu|com|org|net)$/i.test(m?.contact ?? "") && `contact ${m.contact}`,
66
+ m?.rights?.declared_by === "Example Archivist" && 'declarations by "Example Archivist"',
67
+ (m?.collections ?? []).some((c) => c?.id === "example/harbor-ledgers") && "the example's collection",
68
+ ["example/harbor-1904", "example/council-1911"].includes(firstId) && "the example's sample documents",
69
+ ].filter(Boolean);
70
+
71
+ /**
72
+ * @param {string} base the member's base URL (no /openarch/v1)
73
+ * @param {{credential?: string, query?: string, local?: boolean, onStep?: (step) => void}} opts
74
+ * local: a test on this machine. The walk is the same, but the verdict is
75
+ * "conforms (local test)", never "ready to apply": readiness needs the public
76
+ * https address the hub will use (§3).
77
+ * @returns {Promise<{base, member, sections: Array<{id, title, checks: Array<{id, status, title, detail, fix}>}>, passed, failed, warned, ready, conforms, local, ms}>}
78
+ */
79
+ export async function checkMember(base, { credential, query, onStep, local = false } = {}) {
80
+ base = String(base).replace(/\/+$/, "");
81
+ // ind-sec run-1 (credential-sent-to-unbound-file-url): the credential the hub
82
+ // alone presents never crosses the network in the clear, and never leaves the
83
+ // member's own origin
84
+ const baseUrl = (() => { try { return new URL(base); } catch { return null; } })();
85
+ const loopback = (u) => /^(localhost|127\.0\.0\.1|\[::1\])$/i.test(u.hostname);
86
+ if (credential && baseUrl && baseUrl.protocol === "http:" && !loopback(baseUrl)) {
87
+ throw new Error(`refusing to send the credential over plain http to ${baseUrl.host}: use https (http is fine only on this machine)`);
88
+ }
89
+ const t0 = Date.now();
90
+ const sections = [];
91
+ // In a local test the permalinks and file URLs name the public address, which may not be
92
+ // live yet: fetch the same path at the adapter under test, and say so.
93
+ let publicOrigin = null;
94
+ const localize = (u) => {
95
+ if (!local || !publicOrigin || !baseUrl) return { url: u, note: "" };
96
+ try { const x = new URL(u); if (x.origin !== publicOrigin) return { url: u, note: "" }; return { url: baseUrl.origin + x.pathname + x.search, note: ` (local test: fetched at ${baseUrl.host})` }; } catch { return { url: u, note: "" }; }
97
+ };
98
+ const served = []; // [where, permalink] — every permalink the adapter hands out, compared with its declared pattern
99
+ let section;
100
+ const begin = (id, title) => { section = { id, title, checks: [] }; sections.push(section); };
101
+ const add = (status, id, title, detail = "", fix = "") => { const c = { id, status, title, detail, fix }; section.checks.push(c); onStep?.(c); return c; };
102
+ const pass = (id, title, detail) => add("pass", id, title, detail);
103
+ const fail = (id, title, detail, fix) => add("fail", id, title, detail, fix);
104
+ const warn = (id, title, detail, fix) => add("warn", id, title, detail, fix);
105
+ const skip = (id, title, detail) => add("skip", id, title, detail);
106
+ let m = null, slug = null, gated = false;
107
+ const finish = () => {
108
+ const all = sections.flatMap((s) => s.checks);
109
+ const passed = all.filter((c) => c.status === "pass").length;
110
+ const failed = all.filter((c) => c.status === "fail").length;
111
+ const warned = all.filter((c) => c.status === "warn").length;
112
+ const skipped = all.filter((c) => c.status === "skip").length;
113
+ const conforms = failed === 0 && !gated && Boolean(m);
114
+ // ready only when the gate itself was proven: a credential given, and refused without it (P3 #26)
115
+ const gateProven = Boolean(credential) && all.some((c) => c.id === "A1" && c.status === "pass");
116
+ return { base, member: slug, name: m?.name ?? null, sections, passed, failed, warned, skipped, conforms, local, ready: conforms && !local && gateProven, gated, reached: Boolean(m), ms: Date.now() - t0 };
117
+ };
118
+
119
+ // ── §4.1 manifest ────────────────────────────────────────────────────────
120
+ begin("4.1", "Manifest");
121
+ const mres = await call(base, "/manifest");
122
+ const murl = `${base}/openarch/v1/manifest`;
123
+ // the base URL is the address before /openarch/v1; a base that already ends in it doubles the path
124
+ const baseHint = /\/openarch(\/v1)?$/i.test(base) ? ` Your base URL ends in ${base.match(/\/openarch(\/v1)?$/i)[0]}: give the address before it (${base.replace(/\/openarch(\/v1)?$/i, "")}).` : " The base URL is the address before /openarch/v1.";
125
+ if (!mres.ok) fail("M1", "reachable", `nothing answered at ${murl}: ${mres.error}`, /does not resolve/.test(mres.error) ? "Point the name's DNS at your server (an A or AAAA record), then run the check again." : `Is the adapter running at that address?${baseHint}`);
126
+ else if (mres.status === 404) fail("M1", "reachable", `HTTP 404 at ${murl}`, `No manifest at that path.${baseHint}`);
127
+ else if (mres.status === 401 || mres.status === 403) fail("M1", "reachable", `HTTP ${mres.status} at ${murl}`, "The manifest is public: answer it with no key, status 200 (only the other calls need the hub credential).");
128
+ else if (mres.status !== 200) fail("M1", "reachable", `HTTP ${mres.status} at ${murl}`, "The manifest answers 200 with JSON.");
129
+ else if (mres.parseError || !isObj(mres.json)) fail("M1", "reachable", `200 but not a JSON object (${mres.parseError || typeof mres.json})`, "Answer application/json, UTF-8.");
130
+ else { m = mres.json; pass("M1", "reachable", `200 in ${mres.ms} ms`); }
131
+
132
+ if (m) {
133
+ try { publicOrigin = new URL(String(m.permalinks?.pattern ?? "").replace("{id}", "x")).origin; } catch { publicOrigin = null; }
134
+ if (m.protocol === "0.1") pass("M2", "protocol", "0.1"); else fail("M2", "protocol", `protocol = ${JSON.stringify(m.protocol)}`, 'Set "protocol": "0.1".');
135
+ const idOk = typeof m.member === "string" && SLUG_RE.test(m.member);
136
+ slug = idOk ? m.member : null;
137
+ const idBits = [idOk ? m.member : `member slug ${JSON.stringify(m.member)} is not [a-z0-9-]{2,41}`, typeof m.name === "string" && m.name ? m.name : "name missing", typeof m.institution === "string" && m.institution ? m.institution : "institution missing", typeof m.contact === "string" && EMAIL_RE.test(m.contact) ? m.contact : "contact is not an email"];
138
+ const idBad = idBits.filter((b, i) => [!idOk, !m.name, !m.institution, !(typeof m.contact === "string" && EMAIL_RE.test(m.contact))][i]);
139
+ if (idBad.length === 0) pass("M3", "identity", idBits.join(" · ")); else fail("M3", "identity", idBad.join("; "), "member (lowercase slug), name, institution and a contact email are required.");
140
+ const caps = Array.isArray(m.capabilities) ? m.capabilities : [];
141
+ const missing = ["search", "documents", "citations"].filter((c) => !caps.includes(c));
142
+ if (missing.length === 0) pass("M4", "capabilities", caps.join(" ")); else fail("M4", "capabilities", `missing ${missing.join(", ")}`, "search, documents and citations are required; verify_quote is optional.");
143
+ const colls = Array.isArray(m.collections) ? m.collections : [];
144
+ const badIds = colls.filter((c) => !isObj(c) || typeof c.id !== "string" || !(slug && c.id.startsWith(`${slug}/`)));
145
+ const noTitle = colls.filter((c) => isObj(c) && !c.title);
146
+ const badCount = colls.filter((c) => isObj(c) && c.documents !== null && c.documents !== undefined && typeof c.documents !== "number");
147
+ if (colls.length === 0) fail("M5", "collections", "none", "List at least one collection: { id: \"<member>/<name>\", title, documents, terms }.");
148
+ else if (badIds.length || noTitle.length || badCount.length) fail("M5", "collections", [badIds.length && `${badIds.length} id(s) not prefixed ${slug}/`, noTitle.length && `${noTitle.length} without a title`, badCount.length && `${badCount.length} with a non-numeric document count`].filter(Boolean).join("; "), "Every collection id starts with your member slug; documents is a number or null.");
149
+ else pass("M5", "collections", `${colls.length} collection${colls.length === 1 ? "" : "s"}, ids prefixed ${slug}/`);
150
+ const terms = isObj(m.terms) ? m.terms : {};
151
+ const noTerms = colls.filter((c) => isObj(c) && (typeof c.terms !== "string" || !terms[c.terms]));
152
+ const thin = Object.entries(terms).filter(([, t]) => !isObj(t) || !t.label || !(t.url || t.reuse));
153
+ if (noTerms.length) fail("M6", "terms", `${noTerms.length} collection(s) name terms the manifest does not define`, "Every collection's terms id must be a key of manifest.terms.");
154
+ else if (thin.length) fail("M6", "terms", `${thin.length} terms entr${thin.length === 1 ? "y" : "ies"} without a label and a url or reuse`, "Each terms entry: { label, url, reuse }.");
155
+ else pass("M6", "terms", `${Object.keys(terms).length} terms entr${Object.keys(terms).length === 1 ? "y" : "ies"}; every collection names one`);
156
+ const lim = isObj(m.limits) ? m.limits : {};
157
+ if (typeof lim.search_results_max === "number" && typeof lim.document_bytes_max === "number") pass("M7", "limits", `search ${lim.search_results_max} · document ${lim.document_bytes_max.toLocaleString("en-US")} bytes`);
158
+ else fail("M7", "limits", "search_results_max / document_bytes_max missing", "State both limits as numbers so partners can plan.");
159
+ // the declarations (§4.1): rights, the permalink standard, the agreement
160
+ const v = validateDeclarations({ rights: m.rights, permalinks: m.permalinks, agreement: m.agreement }, { requireAgreement: false });
161
+ const rightsP = v.problems.filter((x) => x.startsWith("rights")), permP = v.problems.filter((x) => x.startsWith("permalinks"));
162
+ if (rightsP.length) fail("M8", "rights declared", rightsP[0] + (rightsP.length > 1 ? ` (+${rightsP.length - 1})` : ""), "Declare basis, grant, attribution and automated_access in the protocol's vocabulary (openarch member init asks).");
163
+ else pass("M8", "rights declared", `${m.rights.basis} · grants ${m.rights.grant} · credit ${m.rights.attribution} · automated ${m.rights.automated_access}${m.rights.license ? ` · ${m.rights.license}` : ""}`);
164
+ if (permP.length) fail("M9", "permalink standard", permP[0] + (permP.length > 1 ? ` (+${permP.length - 1})` : ""), "Give the https pattern with {id} and promise all three: minted once, old forms resolve, opens the document.");
165
+ else pass("M9", "permalink standard", `${m.permalinks.pattern} · minted once · old forms resolve · opens the document`);
166
+ const sh = validateSharing(m.sharing);
167
+ if (!m.sharing) warn("M11", "sharing grid", "not declared", "Sort what you hold into share (how far) and withhold (why): manifest.sharing — openarch member init asks, or your account on the hub.");
168
+ else if (!sh.ok) fail("M11", "sharing grid", sh.problems[0] + (sh.problems.length > 1 ? ` (+${sh.problems.length - 1})` : ""), "See protocol §4.1 for the kinds, modes and reasons.");
169
+ else {
170
+ const fileKinds = Object.entries(m.sharing.share).filter(([, mode]) => mode === "files").map(([k]) => k);
171
+ if (fileKinds.length && !(m.capabilities ?? []).includes("files")) fail("M11", "sharing grid", `shares ${fileKinds.join(", ")} as files but capabilities lacks "files"`, 'Declare the files capability and serve /documents/<id>/files, or share those kinds as "text".');
172
+ else pass("M11", "sharing grid", `shares ${Object.entries(m.sharing.share).map(([k, mo]) => `${k}:${mo}`).join(" ")}${Object.keys(m.sharing.withhold ?? {}).length ? ` · withholds ${Object.entries(m.sharing.withhold).map(([k, r]) => `${k} (${r})`).join(", ")}` : ""}`);
173
+ }
174
+ if (!m.agreement) warn("M10", "agreement", "not yet accepted", "Accept the membership agreement (openarch apply does) before the operator registers you.");
175
+ else { const va = validateDeclarations({ rights: m.rights, permalinks: m.permalinks, agreement: m.agreement }); const ap = va.problems.filter((x) => x.startsWith("agreement")); if (ap.length) fail("M10", "agreement", ap[0], "agreement: { version, accepted_by, accepted_on }"); else pass("M10", "agreement", `v${m.agreement.version} accepted by ${m.agreement.accepted_by} on ${m.agreement.accepted_on}`); }
176
+ }
177
+
178
+ // Nothing answered (or no manifest): every later call fails for the same reason, and its
179
+ // verdicts would be wrong ("open to any caller", "not declared"). Say it once and stop
180
+ // (walkthrough 2, 2026-11-26).
181
+ if (!m) {
182
+ begin("–", "The rest of the walk");
183
+ skip("W0", "not walked", "every remaining check needs the manifest (M1 above)");
184
+ begin("3", "Ready to apply");
185
+ if (local) skip("R2", "public https address", `local test at ${baseUrl?.host ?? base}`);
186
+ else if (isPublicHttps(base)) fail("R2", "public https address", `${baseUrl.host} is the right kind of address, but nothing answered there (M1)`, "Point the name's DNS at your server, start the adapter behind https (deploy/Caddyfile), and run the check again.");
187
+ else fail("R2", "public https address", `${baseUrl?.protocol === "https:" ? "" : "not https: "}${baseUrl?.host ?? base} is not an address the hub can reach`, "The hub calls members over https at a public address (§3, §7). Test on this machine with --local; check the public address before applying.");
188
+ return finish();
189
+ }
190
+
191
+ // ── §7 gate ──────────────────────────────────────────────────────────────
192
+ begin("7", "Credential gate");
193
+ const open = await call(base, "/search", { query: { q: "the", limit: 1 } });
194
+ if (credential) {
195
+ if (open.ok && open.status === 401) pass("A1", "refuses without the hub credential", "401");
196
+ else fail("A1", "refuses without the hub credential", open.ok ? `HTTP ${open.status} with no Authorization header` : open.error, "Every call but the manifest must require the hub credential (OPENARCH_HUB_CREDENTIAL in the adapter's .env): 401 otherwise.");
197
+ } else if (open.ok && open.status === 401) {
198
+ pass("A1", "refuses without the hub credential", "401 — pass --credential <your adapter's OPENARCH_HUB_CREDENTIAL> to run the gated checks");
199
+ } else {
200
+ warn("A1", "open to any caller", open.ok ? `HTTP ${open.status} with no credential` : open.error, "Fine while developing; set a hub credential before applying.");
201
+ }
202
+ gated = !credential && open.ok && open.status === 401;
203
+
204
+ // ── §4.2 search ──────────────────────────────────────────────────────────
205
+ begin("4.2", "Search");
206
+ const probe = query || (m?.collections?.[0]?.title || "").split(/\s+/).map((w) => w.replace(/[^\p{L}\p{N}]/gu, "")).find((w) => w.length >= 4)?.toLowerCase() || "the";
207
+ let firstId = null, firstLocal = null, firstPermalink = null;
208
+ if (gated) { skip("S1", "answers", "needs --credential"); }
209
+ else {
210
+ const s = await call(base, "/search", { credential, query: { q: probe, limit: 2 } });
211
+ if (!s.ok) fail("S1", "answers", s.error, "GET /openarch/v1/search?q=…&limit=… must answer JSON.");
212
+ else if (credential && (s.status === 401 || s.status === 403)) fail("S1", "answers", `HTTP ${s.status}: the adapter refused this credential`, "Pass the credential your adapter has set (OPENARCH_HUB_CREDENTIAL in its .env), or run the check in the member's directory, which reads it.");
213
+ else if (s.status !== 200 || !isObj(s.json)) fail("S1", "answers", `HTTP ${s.status}`, "A valid search answers 200 with { total, total_is_estimate, results, cursor }.");
214
+ else {
215
+ const b = s.json;
216
+ pass("S1", "answers", `"${probe}" → total ${typeof b.total === "number" ? b.total.toLocaleString("en-US") : JSON.stringify(b.total)}, ${Array.isArray(b.results) ? b.results.length : "?"} result(s) in ${s.ms} ms${b.partial ? ` · partial: ${(b.warnings || []).join("; ")}` : ""}`);
217
+ const problems = [];
218
+ if (typeof b.total !== "number") problems.push("total is not a number");
219
+ if (!Array.isArray(b.results)) problems.push("results is not an array");
220
+ if (!(b.cursor === null || typeof b.cursor === "string")) problems.push("cursor must be a string or null");
221
+ const collIds = new Set((m?.collections ?? []).map((c) => c.id));
222
+ const termIds = new Set(Object.keys(m?.terms ?? {}));
223
+ for (const [i, r] of (Array.isArray(b.results) ? b.results : []).entries()) {
224
+ if (!isObj(r)) { problems.push(`results[${i}] is not an object`); continue; }
225
+ if (typeof r.id !== "string" || !(slug && r.id.startsWith(`${slug}/`))) problems.push(`results[${i}].id ${JSON.stringify(r.id)} not prefixed ${slug}/`);
226
+ if (typeof r.title !== "string") problems.push(`results[${i}].title missing`);
227
+ if (!collIds.has(r.collection)) problems.push(`results[${i}].collection ${JSON.stringify(r.collection)} not in the manifest`);
228
+ if (!httpUrl(r.permalink)) problems.push(`results[${i}].permalink is not a URL`);
229
+ if (!termIds.has(r.terms)) problems.push(`results[${i}].terms ${JSON.stringify(r.terms)} not in manifest.terms`);
230
+ if (!(r.tokens === null || r.tokens === undefined || (typeof r.tokens === "number" && r.tokens > 0))) problems.push(`results[${i}].tokens must be a positive number or null, never 0`);
231
+ }
232
+ for (const r of Array.isArray(b.results) ? b.results : []) if (isObj(r) && typeof r.permalink === "string") served.push([`search result ${r.id}`, r.permalink]);
233
+ if (problems.length === 0) pass("S2", "result shape", "id · title · collection · permalink · terms · tokens all well-formed"); else fail("S2", "result shape", problems.slice(0, 3).join("; ") + (problems.length > 3 ? ` (+${problems.length - 3})` : ""), "See §4.2 for the result fields.");
234
+ if (typeof b.cursor === "string" && b.cursor) {
235
+ const next = await call(base, "/search", { credential, query: { q: probe, limit: 2, cursor: b.cursor } });
236
+ const ids1 = new Set((b.results ?? []).map((r) => r?.id));
237
+ const r2 = Array.isArray(next.json?.results) ? next.json.results : null;
238
+ if (!next.ok || next.status !== 200 || !r2) fail("S6", "next page", next.ok ? `HTTP ${next.status} for cursor ${JSON.stringify(b.cursor).slice(0, 40)}` : next.error, "?cursor=<the cursor you returned> must answer the next page (§4.2).");
239
+ else if (r2.some((r) => ids1.has(r?.id))) fail("S6", "next page", "the next page repeats a result from the first", "The cursor must continue where the page ended, not restart.");
240
+ else pass("S6", "next page", `cursor → ${r2.length} more result(s), none repeated`);
241
+ }
242
+ if (Array.isArray(b.results) && typeof b.total === "number" && b.total > b.results.length && b.cursor === null && !b.capped && !b.total_is_estimate) fail("S3", "honest counts", `total ${b.total} but ${b.results.length} results, no cursor, no capped flag`, "When more exist, return a cursor, or say capped: true / total_is_estimate: true.");
243
+ else pass("S3", "honest counts", b.cursor ? "cursor offered for the rest" : b.capped ? "capped disclosed" : "nothing withheld");
244
+ const r0 = Array.isArray(b.results) ? b.results.find((r) => isObj(r) && typeof r.id === "string") : null;
245
+ if (r0) { firstId = r0.id; firstLocal = slug && r0.id.startsWith(`${slug}/`) ? r0.id.slice(slug.length + 1) : r0.id; firstPermalink = r0.permalink; }
246
+ const c0 = m?.collections?.[0]?.id;
247
+ if (c0) {
248
+ const sc = await call(base, "/search", { credential, query: { q: probe, collection: c0, limit: 2 } });
249
+ if (sc.ok && sc.status === 200 && Array.isArray(sc.json?.results) && sc.json.results.every((r) => r.collection === c0)) pass("S4", "collection filter", `${c0}: ${sc.json.results.length} result(s), all in it`);
250
+ else fail("S4", "collection filter", sc.ok ? `HTTP ${sc.status}${sc.json?.results ? ", a result outside the collection" : ""}` : sc.error, "?collection=<id> must restrict results to that collection.");
251
+ }
252
+ }
253
+ const bad = await call(base, "/search", { credential });
254
+ if (bad.ok && bad.status === 400 && isObj(bad.json) && bad.json.error) pass("S5", "rejects a missing q", `400 ${bad.json.error}`); else fail("S5", "rejects a missing q", bad.ok ? `HTTP ${bad.status}` : bad.error, "A search without q answers 400 { error, message } (§4.9).");
255
+ }
256
+
257
+ // ── §4.3 documents ───────────────────────────────────────────────────────
258
+ begin("4.3", "Documents");
259
+ let text = "";
260
+ if (gated) skip("D1", "metadata", "needs --credential");
261
+ else if (!firstLocal) skip("D1", "metadata", "no search result to fetch");
262
+ else {
263
+ const d = await call(base, `/documents/${encodeURIComponent(firstLocal)}`, { credential, query: { text: "false" } });
264
+ if (!d.ok || d.status !== 200 || !isObj(d.json)) fail("D1", "metadata", d.ok ? `HTTP ${d.status}` : d.error, "GET /documents/<local id>?text=false answers 200 with the metadata fields.");
265
+ else {
266
+ const b = d.json, p = [];
267
+ if (b.id !== firstId) p.push(`id ${JSON.stringify(b.id)} ≠ ${firstId}`);
268
+ for (const k of ["title", "collection", "permalink", "terms"]) if (typeof b[k] !== "string") p.push(`${k} missing`);
269
+ if (typeof b.text === "string") p.push("text returned although text=false");
270
+ if (!(b.tokens === null || b.tokens === undefined || typeof b.tokens === "number")) p.push("tokens not a number or null");
271
+ if (typeof b.permalink === "string") served.push([`document ${firstId}`, b.permalink]);
272
+ if (p.length === 0) pass("D1", "metadata", `${firstId} · ${b.date ?? "no date"} · ${typeof b.tokens === "number" ? b.tokens.toLocaleString("en-US") + " tokens" : "tokens unknown"} · ${d.ms} ms`); else fail("D1", "metadata", p.join("; "), "See §4.3; ?text=false must cost nothing and return no text.");
273
+ }
274
+ const f = await call(base, `/documents/${encodeURIComponent(firstLocal)}`, { credential });
275
+ if (!f.ok || f.status !== 200 || !isObj(f.json)) fail("D2", "text", f.ok ? `HTTP ${f.status}` : f.error, "GET /documents/<local id> answers the metadata plus text, text_kind, pages_marked, tokens.");
276
+ else {
277
+ const b = f.json, p = [];
278
+ if (typeof b.text !== "string") p.push("text is not a string");
279
+ if (!TEXT_KINDS.has(b.text_kind)) p.push(`text_kind ${JSON.stringify(b.text_kind)} not one of ocr, born-digital, transcript, spreadsheet, none`);
280
+ if (b.text && typeof b.pages_marked !== "boolean") p.push("pages_marked must be a boolean when text is served");
281
+ if (b.text && !(typeof b.tokens === "number" && b.tokens > 0)) p.push("tokens must be a positive number when text is served");
282
+ if (b.text_kind === "spreadsheet" && !(isObj(b.sheet) && Array.isArray(b.sheet.names))) p.push("spreadsheet text needs sheet: { names, rendering }");
283
+ if (b.pages_marked === true && typeof b.text === "string" && !/\[\[page \d+\]\]/.test(b.text)) p.push("pages_marked is true but the text has no [[page N]] markers");
284
+ text = typeof b.text === "string" ? b.text : "";
285
+ if (p.length === 0) pass("D2", "text", `${text.length.toLocaleString("en-US")} chars · ${b.text_kind}${b.pages_marked ? " · pages marked" : ""} · ${f.ms} ms`); else fail("D2", "text", p.join("; "), "See §4.3.");
286
+ const fileKeys = Object.keys(b).filter((k) => /pdf|file_url|download|binary|base64/i.test(k));
287
+ const limit = typeof m?.limits?.document_bytes_max === "number" ? m.limits.document_bytes_max : Infinity;
288
+ if (fileKeys.length) fail("D3", "no file fields", `field(s) ${fileKeys.join(", ")}`, "The network serves text and a permalink to the original; no call returns a file (§2.3).");
289
+ else if (Buffer.byteLength(text) > limit) fail("D3", "no file fields", `text is ${Buffer.byteLength(text).toLocaleString("en-US")} bytes, over the manifest's document_bytes_max`, "Cap served text at your declared limit.");
290
+ else pass("D3", "no file fields", "the document carries text, not files (files go through §4.6); within document_bytes_max");
291
+ }
292
+ if ((m?.capabilities ?? []).includes("page_ranges")) {
293
+ if (!/\[\[page 1\]\]/.test(text)) skip("D6", "page ranges", "the sample document has no [[page 1]] marker to cut");
294
+ else {
295
+ const pr = await call(base, `/documents/${encodeURIComponent(firstLocal)}`, { credential, query: { pages: "1" } });
296
+ const t1 = typeof pr.json?.text === "string" ? pr.json.text : "";
297
+ if (!pr.ok || pr.status !== 200) fail("D6", "page ranges", pr.ok ? `HTTP ${pr.status} for ?pages=1` : pr.error, "With the page_ranges capability, ?pages=1 answers only page 1 (§4.3).");
298
+ else if (!/\[\[page 1\]\]/.test(t1) || /\[\[page 2\]\]/.test(t1) || !Array.isArray(pr.json.pages_returned)) fail("D6", "page ranges", "?pages=1 did not answer page 1 alone with pages_returned", "Return only the pages asked, each with its marker, plus pages_returned, pages_missing and pages_total (§4.3).");
299
+ else pass("D6", "page ranges", `?pages=1 → page 1 alone · pages_total ${pr.json.pages_total ?? "?"}`);
300
+ }
301
+ }
302
+ const nf = await call(base, "/documents/__openarch_no_such_document__", { credential, query: { text: "false" } });
303
+ if (nf.ok && nf.status === 404 && isObj(nf.json) && nf.json.error) pass("D4", "unknown id", `404 ${nf.json.error}`); else fail("D4", "unknown id", nf.ok ? `HTTP ${nf.status}` : nf.error, "An unknown id answers 404 { error, message } (§4.9).");
304
+ if (firstPermalink && httpUrl(firstPermalink)) {
305
+ try {
306
+ const lp = localize(firstPermalink);
307
+ // a redirect counts as resolving; it is never followed to wherever it points (nit)
308
+ const r = await fetch(lp.url, { method: "GET", redirect: "manual", signal: AbortSignal.timeout(TIMEOUT_MS), headers: { "User-Agent": "openarch-cli-check" } });
309
+ try { await r.body?.cancel(); } catch { /* not read */ }
310
+ if (r.status < 400) pass("D5", "permalink resolves", `${firstPermalink} → ${r.status}${lp.note}`); else warn("D5", "permalink resolves", `${firstPermalink} → ${r.status}${lp.note}`, "A permalink should open the document's page for a human reader.");
311
+ } catch (e) { warn("D5", "permalink resolves", `${firstPermalink}: ${e.message}`, "Could not reach it from here; check it opens in a browser."); }
312
+ }
313
+ }
314
+
315
+ // ── §4.4 citation ────────────────────────────────────────────────────────
316
+ begin("4.4", "Citation");
317
+ if (gated) skip("C1", "chicago", "needs --credential");
318
+ else if (!firstLocal) skip("C1", "chicago", "no document to cite");
319
+ else {
320
+ const c = await call(base, `/documents/${encodeURIComponent(firstLocal)}/citation`, { credential, query: { style: "chicago" } });
321
+ // §4.4: the citation names the holding archive (as the manifest names it) and the permalink
322
+ const names = (t) => !m?.name || squash(t).toLowerCase().includes(squash(m.name).toLowerCase());
323
+ if (typeof c.json?.permalink === "string") served.push(["chicago citation", c.json.permalink]);
324
+ if (!(c.ok && c.status === 200 && c.json?.style === "chicago" && typeof c.json?.citation === "string" && c.json.citation.length > 20 && httpUrl(c.json.permalink))) fail("C1", "chicago", c.ok ? `HTTP ${c.status}${c.json ? ` style=${JSON.stringify(c.json.style)}` : ""}` : c.error, "Answer { style, citation, permalink }; the citation names the holding archive and the permalink.");
325
+ else if (!names(c.json.citation)) fail("C1", "chicago", `does not name the holding archive ("${m.name}"): ${c.json.citation.slice(0, 90)}…`, "A citation names the archive that holds the document, as your manifest names it (§4.4).");
326
+ else if (!squash(c.json.citation).includes(c.json.permalink)) fail("C1", "chicago", "the citation does not carry its permalink", "Put the document's permalink in the citation text (§4.4).");
327
+ else pass("C1", "chicago", c.json.citation.length > 110 ? c.json.citation.slice(0, 110) + "…" : c.json.citation);
328
+ const others = await Promise.all(["apa", "mla", "bibtex"].map((s) => call(base, `/documents/${encodeURIComponent(firstLocal)}/citation`, { credential, query: { style: s } })));
329
+ const broken = others.map((r, i) => (!(r.ok && r.status === 200 && typeof r.json?.citation === "string") ? ["apa", "mla", "bibtex"][i] : null)).filter(Boolean);
330
+ const unnamed = others.map((r, i) => (r.ok && r.status === 200 && typeof r.json?.citation === "string" && !names(r.json.citation) ? ["apa", "mla", "bibtex"][i] : null)).filter(Boolean);
331
+ if (broken.length) fail("C2", "apa · mla · bibtex", `${broken.join(", ")} failed`, "All four styles are required.");
332
+ else if (unnamed.length) fail("C2", "apa · mla · bibtex", `${unnamed.join(", ")} do not name the holding archive ("${m.name}")`, "Every style names the archive that holds the document (§4.4).");
333
+ else pass("C2", "apa · mla · bibtex", "all answer and name the archive");
334
+ }
335
+
336
+ // ── §4.5 verify-quote ────────────────────────────────────────────────────
337
+ begin("4.5", "Quote verification");
338
+ const hasVerify = (m?.capabilities ?? []).includes("verify_quote");
339
+ if (!hasVerify) skip("V1", "capability", "not declared (optional)");
340
+ else if (gated) skip("V1", "real span", "needs --credential");
341
+ else if (!firstLocal || !text) skip("V1", "real span", "no text to draw a span from");
342
+ else {
343
+ let windows;
344
+ // eight consecutive plain words (letters and digits, no hyphenation or
345
+ // punctuation to argue about), from up to three places in the text
346
+ const ws = text.replace(/\[\[[^\]]*\]\]/g, " ").split(/\s+/);
347
+ const clean = (w) => /^[\p{L}\p{N}]{2,}$/u.test(w);
348
+ windows = [];
349
+ for (let i = 0; i + 8 <= ws.length && windows.length < 40; i++) if (ws.slice(i, i + 8).every(clean)) { windows.push(ws.slice(i, i + 8).join(" ")); i += 7; }
350
+ const picks = [windows[0], windows[Math.floor(windows.length / 2)], windows[windows.length - 1]].filter((x, i, a) => x && a.indexOf(x) === i);
351
+ let best = null;
352
+ if (picks.length === 0) skip("V1", "real span", "the text has no run of eight plain words to try");
353
+ else {
354
+ for (const span of picks) {
355
+ const v = await call(base, "/verify-quote", { credential, method: "POST", body: { id: firstId, quote: span } });
356
+ if (v.ok && v.status === 200 && v.json?.status === "anchored") { best = { v, span }; break; }
357
+ best = best ?? { v, span };
358
+ }
359
+ const v = best.v;
360
+ if (v.ok && v.status === 200 && v.json?.status === "anchored") pass("V1", "real span", `anchored (${v.json.confidence}) · method ${v.json.method ?? "unnamed"}${typeof v.json.offset === "number" ? ` · offset ${v.json.offset}` : ""}`);
361
+ else fail("V1", "real span", v.ok ? `HTTP ${v.status} status=${JSON.stringify(v.json?.status)} for “${best.span}”` : v.error, "A span copied from the document's own text must come back anchored.");
362
+ }
363
+ if (best?.v?.json?.status === "anchored") {
364
+ // one word of a real passage changed: the document's OCR differs from the quotation (§4.5).
365
+ // Sixteen words, the change near the end, so the matching runs before it sit together.
366
+ let long = null;
367
+ for (let i = 0; i + 16 <= ws.length && !long; i++) if (ws.slice(i, i + 16).every(clean)) long = ws.slice(i, i + 16);
368
+ const w = long ?? best.span.split(" ");
369
+ w[long ? 12 : Math.floor(w.length / 2)] = "zqxjvwk";
370
+ const near = await call(base, "/verify-quote", { credential, method: "POST", body: { id: firstId, quote: w.join(" ") } });
371
+ const nj = near.json;
372
+ if (!near.ok || near.status !== 200) fail("V4", "near miss", near.ok ? `HTTP ${near.status}` : near.error, "A quotation that differs from the text by one word answers 200 with a verdict.");
373
+ else if (nj?.status === "anchored") fail("V4", "near miss", "a changed word came back anchored", "A quotation with a word the document does not have is uncertain at most (§4.5).");
374
+ else if (nj?.status === "fabricated") warn("V4", "near miss", "a one-word difference came back fabricated", "Seven of eight words in place is uncertain, with matched_span showing the document's own passage (§4.5).");
375
+ else if (typeof nj?.matched_span !== "string") warn("V4", "near miss", "uncertain, without matched_span", "An uncertain verdict SHOULD carry matched_span, the passage as the document has it (§4.5).");
376
+ else if (!squash(text).includes(squash(nj.matched_span))) fail("V4", "near miss", `matched_span is not the document's own text: “${nj.matched_span.slice(0, 60)}”`, "matched_span is the passage exactly as the document has it, not the normalized text (§4.5).");
377
+ else pass("V4", "near miss", `uncertain · matched_span is the document's own passage`);
378
+ // two fragments of the text, in order, joined by an ellipsis
379
+ if (windows.length >= 3) {
380
+ const a = windows[0].split(" ").slice(0, 5).join(" "), z = windows[windows.length - 1].split(" ").slice(-5).join(" ");
381
+ const el = await call(base, "/verify-quote", { credential, method: "POST", body: { id: firstId, quote: `${a} … ${z}` } });
382
+ if (el.ok && el.status === 200 && el.json?.status === "anchored") pass("V5", "ellipsis", `anchored${Array.isArray(el.json.fragment_offsets) ? ` · fragments at ${el.json.fragment_offsets.join(", ")}` : ""}`);
383
+ else fail("V5", "ellipsis", el.ok ? `status=${JSON.stringify(el.json?.status)} for “${a} … ${z}”` : el.error, "A quotation with an ellipsis is anchored when every fragment is found in order (§4.5).");
384
+ }
385
+ }
386
+ const bogus = await call(base, "/verify-quote", { credential, method: "POST", body: { id: firstId, quote: "the committee unanimously resolved to abolish the tariff on imported marzipan next spring" } });
387
+ if (bogus.ok && bogus.status === 200 && ["fabricated", "uncertain"].includes(bogus.json?.status) && bogus.json.status !== "anchored") pass("V2", "invented span", `${bogus.json.status} (${bogus.json.confidence})`);
388
+ else fail("V2", "invented span", bogus.ok ? `status=${JSON.stringify(bogus.json?.status)}` : bogus.error, "An invented sentence must never come back anchored.");
389
+ const empty = await call(base, "/verify-quote", { credential, method: "POST", body: { id: firstId, quote: "" } });
390
+ if (empty.ok && empty.status === 400) pass("V3", "rejects an empty quote", "400"); else fail("V3", "rejects an empty quote", empty.ok ? `HTTP ${empty.status}` : empty.error, "An empty quote answers 400 { error, message } (§4.9).");
391
+ }
392
+
393
+ // ── §4.6–4.7 files ──────────────────────────────────────────────────────
394
+ begin("4.6", "Files");
395
+ const hasFiles = (m?.capabilities ?? []).includes("files");
396
+ if (!hasFiles) skip("F1", "capability", "not declared (optional)");
397
+ else if (gated) skip("F1", "listing", "needs --credential");
398
+ else if (!firstLocal) skip("F1", "listing", "no document to list");
399
+ else {
400
+ const fl = await call(base, `/documents/${encodeURIComponent(firstLocal)}/files`, { credential });
401
+ if (!fl.ok || fl.status !== 200 || !Array.isArray(fl.json?.files)) fail("F1", "listing", fl.ok ? `HTTP ${fl.status}` : fl.error, "GET /documents/<id>/files answers { id, files: [...] } (§4.6).");
402
+ else {
403
+ const files = fl.json.files, p = [];
404
+ const KINDS = new Set(["pdf", "image", "video", "audio", "spreadsheet", "email", "text", "dataset"]);
405
+ for (const [i, f] of files.entries()) { if (typeof f.file_id !== "string") p.push(`files[${i}].file_id missing`); if (!KINDS.has(f.kind)) p.push(`files[${i}].kind ${JSON.stringify(f.kind)} not a material kind`); if (!httpUrl(f.url)) p.push(`files[${i}].url is not a URL`); if (typeof f.media_type !== "string") p.push(`files[${i}].media_type missing`); }
406
+ const shared = new Set(Object.entries(m.sharing?.share ?? {}).filter(([, mo]) => mo === "files").map(([k]) => k));
407
+ const leak = files.filter((f) => !shared.has(f.kind)).map((f) => f.kind);
408
+ if (p.length) fail("F1", "listing", p.slice(0, 3).join("; "), "Each file: file_id, role, kind, media_type, bytes, url (§4.6).");
409
+ else pass("F1", "listing", `${files.length} file${files.length === 1 ? "" : "s"}${files.length ? ` · kinds ${[...new Set(files.map((f) => f.kind))].join(", ")}` : ""}`);
410
+ if (leak.length) fail("F2", "only shared kinds", `lists ${[...new Set(leak)].join(", ")}, not shared as files in the grid`, "The listing must not include a kind the grid does not share as files (the hub would drop it anyway).");
411
+ else pass("F2", "only shared kinds", "every listed file is a kind the grid shares as files");
412
+ const f0 = files[0];
413
+ if (f0) {
414
+ // the credential only to the member's own origin; a signed URL into the
415
+ // member's storage carries its own authorization (§4.7)
416
+ const lf = localize(f0.url);
417
+ const sameOrigin = (() => { try { return new URL(lf.url).origin === baseUrl?.origin; } catch { return false; } })();
418
+ const fb = await fetch(lf.url, { headers: credential && sameOrigin ? { Authorization: `Bearer ${credential}` } : {}, redirect: "manual", signal: AbortSignal.timeout(TIMEOUT_MS) }).catch((e) => ({ error: e.message }));
419
+ if (fb.error) fail("F3", "a file serves", `${f0.url}: ${fb.error}`, "GET /documents/<id>/files/<file_id> streams the bytes or redirects to a signed URL (§4.7). The file URL names the address the hub reaches you at.");
420
+ else if (fb.status === 200 || (fb.status >= 300 && fb.status < 400)) {
421
+ pass("F3", "a file serves", `${f0.file_id} → ${fb.status}${fb.status === 200 ? ` ${fb.headers.get("content-type")}` : " (redirect to the member's storage)"}${lf.note}`);
422
+ if (typeof f0.sha256 === "string" && fb.status === 200) {
423
+ const { createHash } = await import("node:crypto");
424
+ const got = createHash("sha256").update(await readCappedBytes(fb, READ_MAX)).digest("hex");
425
+ if (got === f0.sha256.toLowerCase()) pass("F4", "sha256", `${f0.file_id}: the bytes match the listed sha256`);
426
+ else fail("F4", "sha256", `${f0.file_id}: listed ${f0.sha256.slice(0, 12)}…, the bytes hash to ${got.slice(0, 12)}…`, "The listed sha256 must be the hash of the bytes served (§4.6).");
427
+ }
428
+ }
429
+ else fail("F3", "a file serves", `HTTP ${fb.status}`, "The file call must answer 200 with the bytes or 302 to a signed URL.");
430
+ }
431
+ }
432
+ }
433
+
434
+ // ── §3 ready to apply ────────────────────────────────────────────────────
435
+ // Conformance is the walk above. Ready means the hub can register THIS adapter as it
436
+ // stands: at a public https address, gated, your own archive, the declarations made.
437
+ // (The newcomer walkthrough of 2026-11-26: the untouched example, open to any caller on
438
+ // localhost, used to come back "Ready to apply".)
439
+ begin("3", "Ready to apply");
440
+ const status = (id) => sections.flatMap((x) => x.checks).find((c) => c.id === id)?.status;
441
+ if (m) {
442
+ const re = patternRe(m.permalinks?.pattern);
443
+ const off = re ? served.filter(([, u]) => !re.test(u)) : [];
444
+ if (!re) skip("R1", "permalinks follow the pattern", "no pattern with {id} declared (see M9)");
445
+ else if (served.length === 0) skip("R1", "permalinks follow the pattern", "no permalink served to compare");
446
+ else if (off.length) fail("R1", "permalinks follow the pattern", `${off[0][0]}: ${off[0][1]} does not match ${m.permalinks.pattern}`, "Serve the permalinks you declared: set the adapter's public base (PUBLIC_BASE), never the address you test it at (§4.1).");
447
+ else pass("R1", "permalinks follow the pattern", `${served.length} permalink(s) served, all ${m.permalinks.pattern}`);
448
+ }
449
+ if (local) skip("R2", "public https address", `local test at ${baseUrl?.host ?? base}: run the check again at your public https address before applying`);
450
+ else if (isPublicHttps(base)) pass("R2", "public https address", baseUrl.host);
451
+ else fail("R2", "public https address", `${baseUrl?.protocol === "https:" ? "" : "not https: "}${baseUrl?.host ?? base} is not an address the hub can reach`, "The hub calls members over https at a public address (§3, §7). Test on this machine with --local; check the public address before applying.");
452
+ if (gated) skip("R3", "gated by a credential", "refuses without one — pass --credential to finish the walk");
453
+ else if (credential && status("A1") === "pass") pass("R3", "gated by a credential", "refuses without it, answers with it");
454
+ else fail("R3", "gated by a credential", "open to any caller", "Set OPENARCH_HUB_CREDENTIAL in the adapter's .env (openarch member init writes a provisional one) and pass it with --credential. The hub's own credential replaces it at approval.");
455
+ const signs = m ? EXAMPLE_SIGNS(m, firstId) : [];
456
+ if (!m) skip("R4", "your own archive", "no manifest");
457
+ else if (signs.length) fail("R4", "your own archive", `still the example's: ${signs.join(", ")}`, "Put your archive's identity, collections and documents in place of the example's (openarch member init asks for them).");
458
+ else pass("R4", "your own archive", `${m.name} · ${m.member}`);
459
+ if (m) {
460
+ if (status("M10") === "pass") pass("R5", "agreement accepted", `v${m.agreement.version} by ${m.agreement.accepted_by}`);
461
+ else fail("R5", "agreement accepted", "not in the manifest", "Accept the membership agreement (openarch member init asks) so the manifest carries it.");
462
+ if (status("M11") === "pass") pass("R6", "sharing grid", "declared");
463
+ else fail("R6", "sharing grid", "not declared", "Sort what you hold into share and withhold (openarch member init asks).");
464
+ }
465
+
466
+ return finish();
467
+ }
package/cli/draft.js ADDED
@@ -0,0 +1,75 @@
1
+ // draft.js — find the quotations in a draft and the openarch document each one
2
+ // cites, for `openarch verify --from draft.md`. Pure: (text, member slugs) → items.
3
+ //
4
+ // A quotation is text in double quotes ("…" or “…”) or a Markdown block quote.
5
+ // Its citation is an openarch id — <member>/<local id>, bare, as openarch:<id>, or
6
+ // inside a hub permalink /d/<member>/<id> — in the same paragraph: the first one
7
+ // after the quotation (before the next quotation), else the last one before it.
8
+ // Only slugs of real members count as ids, so "and/or" is never a citation. Code
9
+ // (fenced or inline) is ignored. A short quotation with no id nearby is a scare
10
+ // quote, not a claim, and is left alone.
11
+
12
+ const MIN_WORDS_CITED = 2;
13
+ const MIN_WORDS_UNCITED = 4;
14
+
15
+ const words = (s) => s.split(/\s+/).filter(Boolean).length;
16
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
17
+
18
+ /** Replace code with spaces of the same length so offsets survive. */
19
+ function blankCode(text) {
20
+ const blank = (m) => m.replace(/[^\n]/g, " ");
21
+ return text.replace(/^(```|~~~)[^\n]*\n[\s\S]*?^\1[^\n]*$/gm, blank).replace(/`[^`\n]+`/g, blank);
22
+ }
23
+
24
+ function lineIndex(text) {
25
+ const starts = [0];
26
+ for (let i = 0; i < text.length; i++) if (text[i] === "\n") starts.push(i + 1);
27
+ return (off) => { let lo = 0, hi = starts.length - 1; while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= off) lo = mid; else hi = mid - 1; } return { line: lo + 1, col: off - starts[lo] + 1 }; };
28
+ }
29
+
30
+ /** Paragraph spans [start, end) — separated by blank lines. */
31
+ function paragraphs(text) {
32
+ const out = [];
33
+ const re = /\n[ \t]*\n/g;
34
+ let start = 0, m;
35
+ while ((m = re.exec(text))) { out.push([start, m.index]); start = m.index + m[0].length; }
36
+ out.push([start, text.length]);
37
+ return out;
38
+ }
39
+
40
+ export function extractQuotes(raw, memberSlugs = []) {
41
+ const text = blankCode(String(raw).replace(/\r\n?/g, "\n"));
42
+ const at = lineIndex(text);
43
+ const slugs = [...new Set(memberSlugs)].filter(Boolean).sort((a, b) => b.length - a.length);
44
+ const idRe = slugs.length ? new RegExp(`(?:/d/|openarch:|(?<![\\w/.:-]))(${slugs.map(escapeRe).join("|")})/([A-Za-z0-9](?:[A-Za-z0-9._:-]*[A-Za-z0-9])?)`, "g") : null;
45
+ const items = [];
46
+ let ignored = 0;
47
+
48
+ for (const [ps, pe] of paragraphs(text)) {
49
+ const para = text.slice(ps, pe);
50
+ const quotes = [];
51
+ // block quotes: a paragraph whose lines all start with ">" and that holds no inline quotation
52
+ const isBlock = para.trim() && para.split("\n").filter((l) => l.trim()).every((l) => /^\s*>/.test(l));
53
+ const inline = /“([^”]+?)”|"([^"]+?)"/g;
54
+ let m;
55
+ while ((m = inline.exec(para))) quotes.push({ start: m.index, end: m.index + m[0].length, quote: (m[1] ?? m[2]).replace(/\s*\n\s*>?\s*/g, " ").trim() });
56
+ if (isBlock && !quotes.length) {
57
+ const body = para.split("\n").map((l) => l.replace(/^\s*>\s?/, "")).join(" ");
58
+ const stripped = idRe ? body.replace(idRe, " ") : body;
59
+ const quote = stripped.replace(/\s*[—–-]{1,2}\s*$/, "").replace(/[(\[]\s*[)\]]/g, "").replace(/\s+/g, " ").trim();
60
+ quotes.push({ start: 0, end: para.length, quote, block: true });
61
+ }
62
+ const ids = [];
63
+ if (idRe) { idRe.lastIndex = 0; let im; while ((im = idRe.exec(para))) ids.push({ at: im.index, id: `${im[1]}/${im[2]}` }); }
64
+ quotes.forEach((q, i) => {
65
+ const nextStart = quotes[i + 1]?.start ?? para.length, prevEnd = quotes[i - 1]?.end ?? 0;
66
+ const id = q.block
67
+ ? ids[0]?.id ?? null
68
+ : (ids.find((x) => x.at >= q.end && x.at < nextStart) ?? ids.filter((x) => x.at < q.start && x.at >= prevEnd).pop())?.id ?? null;
69
+ const n = words(q.quote);
70
+ if (n < (id ? MIN_WORDS_CITED : MIN_WORDS_UNCITED)) { ignored++; return; }
71
+ items.push({ quote: q.quote, id, ...at(ps + q.start) });
72
+ });
73
+ }
74
+ return { items, ignored };
75
+ }