stanford-openarch 0.0.0 → 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.
@@ -0,0 +1,856 @@
1
+ #!/usr/bin/env node
2
+ // openarch — the command line for the network. Three people use it: a partner
3
+ // with a key (search, read, cite, verify), an aspiring member checking its
4
+ // adapter before it applies, and the hub's operator. One binary, one voice
5
+ // (cli/ui.js), JSON on request for scripts.
6
+ import { parseArgs } from "node:util";
7
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, chmodSync, rmSync, lstatSync, openSync, writeSync, fsyncSync, closeSync, renameSync } from "node:fs";
8
+ import { fileURLToPath } from "node:url";
9
+ import { dirname, join, resolve } from "node:path";
10
+ import { homedir } from "node:os";
11
+ import * as ui from "./ui.js";
12
+ import { checkMember } from "./check.js";
13
+ import { cmdQuote, cmdVerifyDraft, cmdPull, cmdMay } from "./research.js";
14
+ import { cmdMcp } from "./mcp.js";
15
+ import { refusal, writeReplacing } from "./safeFile.js";
16
+ import { RIGHTS_BASIS, REUSE_GRANT, ATTRIBUTION, AUTOMATED_ACCESS, PERMALINK_PROMISES, AGREEMENT_VERSION, PARTNER_TERMS_VERSION, MATERIAL_KINDS, SERVE_MODES, WITHHOLD_REASONS, validateDeclarations, validateSharing } from "../server/lib/vocabulary.js";
17
+
18
+ const HERE = dirname(fileURLToPath(import.meta.url));
19
+ const ROOT = resolve(HERE, "..");
20
+ const PKG = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
21
+ const DEFAULT_HUB = "https://openarch.stanford.edu";
22
+ // A CLI installed from a hub's /cli/ tarball talks to that hub unless told otherwise: the
23
+ // hub writes its own address into the package.json it serves (server/lib/memberPackage.js).
24
+ const INSTALLED_HUB = typeof PKG.openarch?.hub === "string" && /^https?:\/\//.test(PKG.openarch.hub) ? PKG.openarch.hub : null;
25
+ const CONFIG_DIR = process.env.OPENARCH_CONFIG_DIR || join(homedir(), ".config", "openarch");
26
+ const CONFIG_FILE = join(CONFIG_DIR, "config.json");
27
+
28
+ // ── arguments ──────────────────────────────────────────────────────────────
29
+
30
+ const OPTIONS = {
31
+ hub: { type: "string" }, key: { type: "string" }, json: { type: "boolean" }, "no-color": { type: "boolean" },
32
+ help: { type: "boolean", short: "h" }, version: { type: "boolean", short: "v" },
33
+ limit: { type: "string", short: "n" }, member: { type: "string", short: "m" }, collection: { type: "string", short: "c" }, cursor: { type: "string" },
34
+ style: { type: "string", short: "s" }, all: { type: "boolean" }, text: { type: "boolean", short: "t" }, out: { type: "string", short: "o" },
35
+ credential: { type: "string" }, query: { type: "string", short: "q" }, strict: { type: "boolean" }, local: { type: "boolean" }, public: { type: "boolean" },
36
+ answers: { type: "string" }, example: { type: "boolean" }, kit: { type: "string" }, "same-institution": { type: "boolean" },
37
+ kind: { type: "string" }, institution: { type: "string" }, name: { type: "string" }, email: { type: "string" }, purpose: { type: "string" }, "base-url": { type: "string" },
38
+ status: { type: "string" }, role: { type: "string" }, holder: { type: "string" }, label: { type: "string" }, slug: { type: "string" }, expires: { type: "string" }, yes: { type: "boolean", short: "y" },
39
+ basis: { type: "string" }, grant: { type: "string" }, attribution: { type: "string" }, automated: { type: "string" }, license: { type: "string" }, statement: { type: "string" }, permalink: { type: "string" }, "accept-as": { type: "string" }, archive: { type: "string" }, home: { type: "string" }, share: { type: "string" }, withhold: { type: "string" },
40
+ from: { type: "string", short: "f" }, find: { type: "boolean" }, meta: { type: "boolean" }, config: { type: "string" }, http: { type: "boolean" }, print: { type: "boolean" }, pages: { type: "string", short: "p" },
41
+ };
42
+
43
+ let args;
44
+ try { args = parseArgs({ options: OPTIONS, allowPositionals: true, strict: true }); }
45
+ catch (e) { ui.fail(e.message, "openarch --help lists the commands and flags."); process.exit(2); }
46
+ const { values: flags, positionals } = args;
47
+ if (flags["no-color"]) ui.setColor(false);
48
+ const JSON_OUT = Boolean(flags.json);
49
+
50
+ // ── config and the hub client ──────────────────────────────────────────────
51
+
52
+ function readConfig() {
53
+ try { return JSON.parse(readFileSync(CONFIG_FILE, "utf8")); } catch { return {}; }
54
+ }
55
+ function writeConfig(c) {
56
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
57
+ writeFileSync(CONFIG_FILE, JSON.stringify(c, null, 2) + "\n", { mode: 0o600 });
58
+ chmodSync(CONFIG_FILE, 0o600);
59
+ }
60
+ const cfg = readConfig();
61
+ const HUB = (flags.hub || process.env.OPENARCH_HUB || cfg.hub || INSTALLED_HUB || DEFAULT_HUB).replace(/\/+$/, "");
62
+ const HUB_SOURCE = flags.hub ? "--hub" : process.env.OPENARCH_HUB ? "OPENARCH_HUB" : cfg.hub ? "your login" : INSTALLED_HUB ? "where you installed openarch" : "the default";
63
+ // A stored key belongs to the hub it was stored for (ind-sec run-2 #24,
64
+ // cmdSearch:member-data-in-suggested-command): a --hub or OPENARCH_HUB that names
65
+ // another hub never carries it there; that hub takes --key or OPENARCH_API_KEY.
66
+ const sameHub = (a, b) => { try { const x = new URL(a), y = new URL(b); return x.origin === y.origin && x.pathname.replace(/\/+$/, "") === y.pathname.replace(/\/+$/, ""); } catch { return false; } };
67
+ const STORED_KEY = cfg.key && typeof cfg.hub === "string" && sameHub(cfg.hub, HUB) ? cfg.key : null;
68
+ const STORED_KEY_HUB = cfg.key && !STORED_KEY ? (typeof cfg.hub === "string" ? cfg.hub : "an unnamed hub") : null;
69
+ const KEY = flags.key || process.env.OPENARCH_API_KEY || STORED_KEY || null;
70
+ const KEY_SOURCE = flags.key ? "--key" : process.env.OPENARCH_API_KEY ? "OPENARCH_API_KEY" : STORED_KEY ? CONFIG_FILE : null;
71
+ const storedKeyElsewhere = () => (STORED_KEY_HUB ? ` The key stored on this machine is for ${ui.cleanLine(STORED_KEY_HUB)} and is never sent to another hub.` : "");
72
+
73
+ // Everything a hub relays (a member's titles, a partner's doc ids, an applicant's
74
+ // name) can reach this terminal: in human output a control character prints as
75
+ // U+FFFD, never as a terminal escape (ind-sec openarch run-1). --json keeps the
76
+ // answer as sent; JSON escapes its control characters.
77
+ const { cleanForTerminal } = ui;
78
+
79
+ class HubError extends Error { constructor(status, body, retryAfter) { super(body?.message || body?.error || `HTTP ${status}`); this.status = status; this.body = body; this.retryAfter = retryAfter; } }
80
+
81
+ async function hub(path, { method = "GET", body, query, key = KEY, auth = true } = {}) {
82
+ const url = new URL(`${HUB}/api/v1${path}`);
83
+ for (const [k, v] of Object.entries(query ?? {})) if (v !== undefined && v !== null && v !== "") url.searchParams.set(k, String(v));
84
+ const headers = { Accept: "application/json", "User-Agent": `openarch-cli/${PKG.version}` };
85
+ if (auth && key) {
86
+ if (ui.plainHttpRemote(HUB)) throw new HubError(0, { error: "plain_http", message: `Not sending your key to ${HUB}: it is plain http on another machine. A hub is reached over https (http only on this machine, for development).` });
87
+ headers.Authorization = `Bearer ${key}`;
88
+ }
89
+ if (body !== undefined) headers["Content-Type"] = "application/json";
90
+ let res;
91
+ // a bio run is a fresh search plus a model synthesis at the member: up to ~5 minutes
92
+ const waitMs = path.startsWith("/bio/") ? 360_000 : 60_000;
93
+ try { res = await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(waitMs) }); }
94
+ catch (e) { throw new HubError(0, { error: "unreachable", message: `Could not reach ${HUB}: ${e.name === "TimeoutError" ? `no answer in ${waitMs / 1000} s` : e.message}` }); }
95
+ const text = await res.text();
96
+ let parsed = null;
97
+ try { parsed = text ? JSON.parse(text) : null; } catch { parsed = { error: "bad_response", message: text.slice(0, 200) }; }
98
+ if (!JSON_OUT) parsed = cleanForTerminal(parsed);
99
+ if (!res.ok) throw new HubError(res.status, parsed, res.headers.get("retry-after"));
100
+ return parsed;
101
+ }
102
+
103
+ function explain(e) {
104
+ if (e instanceof ui.Interrupted) { process.exitCode = 130; return ui.fail("Stopped.", e.hint ?? ""); }
105
+ if (e instanceof ui.NotATerminal) return ui.fail(e.message, `Pass the value as a flag (openarch ${positionals.slice(0, positionals[0] === "member" ? 2 : 1).join(" ")} --help lists them) or run it in a terminal.${e.hint ? `\n ${e.hint}` : ""}`);
106
+ if (!(e instanceof HubError)) return ui.fail(e.message, e.hint ?? "");
107
+ const b = e.body ?? {};
108
+ switch (e.status) {
109
+ case 0: return ui.fail(b.message, `Hub: ${HUB}. Pass --hub <url> or set OPENARCH_HUB.`);
110
+ case 401: return ui.fail(KEY ? "The hub did not accept this key." : "This call needs a key.", KEY ? `${b.message || ""} Run openarch login to store a working key, or pass --key.`.trim() : `Run openarch login (or pass --key / set OPENARCH_API_KEY). No key yet? openarch apply.${storedKeyElsewhere()}`);
111
+ case 403: return ui.fail(b.message || "Your key lacks the right for this call.", b.error === "insufficient_role" ? "Operator commands need an oa_adm_ key." : "");
112
+ case 404: return ui.fail(b.message || `Not found (${b.error || 404}).`, b.error === "unknown_member" ? "openarch members lists the slugs." : "");
113
+ // an application the hub's pending caps refused is not a quota (ind-sec run-3 P2)
114
+ case 429: return ui.fail(b.message || "Over quota.", b.error === "too_many_pending" || b.error === "intake_full" ? "" : `Retry after ${e.retryAfter || "a while"}. openarch whoami shows today's usage.`);
115
+ case 501: return ui.fail(b.message || "Not supported by this member.");
116
+ case 503: return ui.fail(b.message || "A member did not answer.", "The hub is up; the member behind it is not. Try again shortly.");
117
+ default: return ui.fail(`${b.message || b.error || "Request failed"} (HTTP ${e.status})`);
118
+ }
119
+ }
120
+
121
+ const num = (v, d) => { const n = Number.parseInt(String(v ?? ""), 10); return Number.isFinite(n) && n > 0 ? n : d; };
122
+ const splitId = (id) => { const m = /^([a-z0-9][a-z0-9-]{1,40})\/(.+)$/.exec(String(id ?? "")); return m ? { member: m[1], local: m[2] } : null; };
123
+
124
+ // ── help ───────────────────────────────────────────────────────────────────
125
+
126
+ function help() {
127
+ const W = 48;
128
+ const cmd = (c, d) => c.length >= W - 1 ? ` ${ui.bold(c)}${d ? `\n ${" ".repeat(W)}${ui.dim(d)}` : ""}` : ` ${ui.bold(ui.pad(c, W))}${ui.dim(d)}`;
129
+ ui.out(ui.banner([`a network of university archives · protocol 0.1`, `hub ${HUB} (${HUB_SOURCE})${KEY ? "" : " · no key stored"}`]));
130
+ ui.blank();
131
+ ui.out(ui.label(" use the network"));
132
+ ui.out(cmd("members", "who is in the network"));
133
+ ui.out(cmd("member <slug>", "one member: collections, counts, terms"));
134
+ ui.out(cmd('search "<query>" [-m a,b] [-c id] [-n 25]', "search every member, or some, or one collection"));
135
+ ui.out(cmd("doc <member/id> [--text] [-p 3-5] [-o file]", "a document's metadata; --text its text; -p only those pages (and only their bytes)"));
136
+ ui.out(cmd("cite <member/id> [-s chicago|apa|mla|bibtex]", "a citation; --all prints every style"));
137
+ ui.out(cmd('verify <member/id> "<quote>"', "is this quotation in the document? anchored · uncertain · fabricated"));
138
+ ui.out(cmd('quote "<words>" [-m a,b]', "where is this quotation from? finds and verifies its source"));
139
+ ui.out(cmd("may <member/id | member> [use] [-c collection]", "may I quote, reproduce, mine, train, share, sell? read from the declarations"));
140
+ ui.out(cmd("verify --from draft.md [--find] [--strict]", "check every quotation in a draft against the document it cites"));
141
+ ui.out(cmd('pull "<query>" -o dir [-n 50] [--meta]', "a corpus on disk: documents.jsonl, citations.bib, checksums; resumable"));
142
+ ui.out(cmd("whoami", "your key, quotas, today's usage, recent calls"));
143
+ ui.out(cmd("login | logout", "store a key for this machine (~/.config/openarch, mode 600)"));
144
+ ui.out(cmd("apply", "request a partner key (the partner terms); an archive joins with member init … member apply"));
145
+ ui.out(cmd("protocol", "read the protocol"));
146
+ ui.blank();
147
+ ui.out(ui.label(" for agents"));
148
+ ui.out(cmd("mcp install claude|desktop|cursor|vscode", "wire openarch into an agent; the key stays in one file (--http for cursor or vscode sends it directly)"));
149
+ ui.out(cmd("mcp doctor", "hub, key, MCP handshake, tools, the bridge, which agents have it"));
150
+ ui.out(cmd("mcp serve", "the network's tools over stdio, for any MCP client"));
151
+ ui.blank();
152
+ ui.out(ui.label(" join as a member (openarch member --help: the whole path)"));
153
+ ui.out(cmd("member init [dir]", "from your catalog and files to a running adapter: asks, reads your columns, writes it all"));
154
+ ui.out(cmd("member check [--public]", "in your member's directory: the conformance walk, here or at its live address"));
155
+ ui.out(cmd("member apply", "send your application, declarations read from your live manifest (needs a Ready check)"));
156
+ ui.out(cmd("member status", "where your application stands; once approved, whether the hub reaches your adapter"));
157
+ ui.out(cmd("member credential set", "put the hub's credential (sent at approval) in your adapter's .env; it asks for it"));
158
+ ui.blank();
159
+ ui.out(ui.label(" operate the hub (oa_adm_ key)"));
160
+ ui.out(cmd("admin overview | requests", "the hub at a glance; the applications waiting"));
161
+ ui.out(cmd("admin approve <id> --institution <slug>", "approve an application (a member's: registers it, mints its hub credential and account key)"));
162
+ ui.out(cmd("admin deny <id>", "deny an application"));
163
+ ui.out(cmd("admin keys | keys issue | keys revoke <id>", ""));
164
+ ui.out(cmd("admin members | members add | members refresh <slug>", ""));
165
+ ui.out(cmd("admin institutions | institutions add | audit | calls", ""));
166
+ ui.blank();
167
+ ui.out(ui.dim(" flags --hub <url> --key <key> --json --no-color env OPENARCH_HUB OPENARCH_API_KEY"));
168
+ ui.out(ui.dim(" every command has its own help: openarch <command> --help"));
169
+ ui.blank();
170
+ }
171
+
172
+ // ── commands: use the network ──────────────────────────────────────────────
173
+
174
+ const docCount = (m) => (m.collections ?? []).reduce((n, c) => n + (Number(c.documents) || 0), 0);
175
+
176
+ async function cmdMembers() {
177
+ const sp = ui.spinner(`asking ${HUB}`);
178
+ const { members } = await hub("/members", { auth: false }).finally(() => sp.stop());
179
+ if (JSON_OUT) return ui.json(members);
180
+ if (!members.length) return ui.out(ui.dim(" No members yet."));
181
+ ui.blank();
182
+ ui.out(ui.table([
183
+ { key: "member", title: "member", format: (v) => ui.bold(v) },
184
+ { key: "name", title: "archive" },
185
+ { key: "institution", title: "institution" },
186
+ { key: "collections", title: "collections", align: "right", fixed: true, format: (v) => ui.fmtInt((v ?? []).length) },
187
+ { key: "documents", title: "documents", align: "right", fixed: true, format: (_v, r) => ui.fmtInt(docCount(r)) },
188
+ { key: "capabilities", title: "capabilities", format: (v) => (v ?? []).join(" ") },
189
+ ], members));
190
+ ui.blank();
191
+ ui.out(ui.dim(` ${members.length} member${members.length === 1 ? "" : "s"} · openarch member <slug> for one · hub ${HUB}`));
192
+ ui.blank();
193
+ }
194
+
195
+ async function cmdMember(slug) {
196
+ if (!slug) return ui.fail("Which member?", "openarch member <slug>; openarch members lists them.");
197
+ const sp = ui.spinner(`asking ${HUB} about ${slug}`);
198
+ const m = await hub(`/members/${encodeURIComponent(slug)}`, { auth: false }).finally(() => sp.stop());
199
+ if (JSON_OUT) return ui.json(m);
200
+ ui.blank();
201
+ ui.out(` ${ui.bold(m.name ?? m.member)} ${ui.dim(`· ${m.member}`)}`);
202
+ ui.out(ui.kv([["institution", m.institution], ["contact", m.contact], ["capabilities", (m.capabilities ?? []).join(" ")], ["documents", ui.fmtInt(docCount(m))], ["manifest read", m.manifest_at ? `${m.manifest_at} UTC` : null]]));
203
+ ui.blank();
204
+ ui.out(ui.table([
205
+ { key: "id", title: "collection", format: (v) => ui.bold(v) },
206
+ { key: "title", title: "title" },
207
+ { key: "documents", title: "documents", align: "right", fixed: true, format: ui.fmtInt },
208
+ { key: "terms", title: "terms" },
209
+ ], m.collections ?? []));
210
+ const terms = Object.entries(m.terms ?? {});
211
+ if (terms.length) {
212
+ ui.blank();
213
+ ui.out(ui.label(" terms"));
214
+ for (const [k, t] of terms) ui.out(` ${ui.bold(k)} ${t.label ?? ""}${t.reuse ? ui.dim(` · reuse: ${t.reuse}`) : ""}${t.verified === false ? ui.amber(" · unverified") : ""}${t.url ? `\n ${ui.dim(t.url)}` : ""}`);
215
+ }
216
+ ui.blank();
217
+ }
218
+
219
+ const CURSOR_TOKEN = /^[A-Za-z0-9_=-]{1,512}$/;
220
+ const SLUG = /^[a-z0-9][a-z0-9-]{0,40}$/;
221
+
222
+ async function cmdSearch(q) {
223
+ if (!q) return ui.fail("Search for what?", 'openarch search "menthol marketing" [-m indra] [-c indra/ucsf] [-n 25]');
224
+ const limit = num(flags.limit, 25);
225
+ const sp = ui.spinner(`searching ${flags.member ? flags.member : "every member"} for “${q}”`);
226
+ const r = await hub("/search", { query: { q, members: flags.member, collection: flags.collection, limit, cursor: flags.cursor } }).finally(() => sp.stop());
227
+ if (JSON_OUT) return ui.json(r);
228
+ ui.blank();
229
+ let shown = 0;
230
+ for (const g of r.members ?? []) {
231
+ if (g.error) { ui.out(` ${ui.bold(ui.cleanLine(g.member))} ${ui.red(ui.cleanLine(g.error))}${g.message ? ui.dim(` ${ui.cleanLine(g.message)}`) : ""}`); ui.blank(); continue; }
232
+ const head = `${ui.bold(ui.cleanLine(g.member))} ${ui.fmtInt(g.total)} match${g.total === 1 ? "" : "es"}${g.total_is_estimate ? ui.dim(" (estimate)") : ""}${g.capped ? ui.amber(" capped") : ""}${g.partial ? ui.amber(" partial") : ""}`;
233
+ ui.out(` ${head}`);
234
+ // a member's words stay on their own line: no line break or tab can start a fake one (#24)
235
+ if (g.capped_note) ui.out(ui.dim(` ${ui.cleanLine(g.capped_note)}`));
236
+ for (const w of g.warnings ?? []) ui.out(` ${ui.glyph.warn} ${ui.dim(ui.cleanLine(w))}`);
237
+ if ((g.results ?? []).length) {
238
+ ui.out(ui.table([
239
+ { key: "id", title: "id", format: (v) => ui.arch(v) },
240
+ { key: "date", title: "date", fixed: true, format: (v) => v ?? ui.dim("—") },
241
+ { key: "title", title: "title" },
242
+ { key: "tokens", title: "tokens", align: "right", fixed: true, format: (v, row) => (typeof v === "number" ? ui.fmtInt(v) : row.tokens_upper_bound ? ui.dim(`≤${ui.fmtInt(row.tokens_upper_bound)}`) : ui.dim("—")) },
243
+ { key: "collection", title: "collection", format: (v) => ui.dim(v) },
244
+ ], g.results));
245
+ shown += g.results.length;
246
+ }
247
+ // option values as --name=value and the query after "--": a member-sent value
248
+ // is never read as an option of its own (ind-sec run-1, round 2)
249
+ // and only a cursor shaped like a token is offered at all (#24): anything else stays in --json
250
+ if (g.cursor && CURSOR_TOKEN.test(String(g.cursor)) && SLUG.test(String(g.member))) ui.out(ui.dim(` more: openarch search --member=${ui.shq(g.member)}${flags.collection ? ` --collection=${ui.shq(flags.collection)}` : ""} --limit=${limit} --cursor=${ui.shq(g.cursor)} -- ${ui.shq(q)}`));
251
+ else if (g.cursor) ui.out(ui.dim(" more: this member's cursor is not a plain token, so no command is offered for it (--json shows it)"));
252
+ ui.blank();
253
+ }
254
+ if (!shown && !(r.members ?? []).some((g) => g.error)) ui.out(ui.dim(" Nothing matched."));
255
+ ui.out(ui.dim(` openarch doc <id> · openarch cite <id> · openarch verify <id> "<quote>" · openarch pull ${JSON.stringify(q)} -o corpus/`));
256
+ ui.blank();
257
+ }
258
+
259
+ async function cmdDoc(id) {
260
+ const p = splitId(id);
261
+ if (!p) return ui.fail("Which document?", "openarch doc <member>/<local id> [--text] [-p 3-5] [-o file] — ids look like indra/ffbw0103");
262
+ const wantText = Boolean(flags.text || flags.out || flags.pages);
263
+ const sp = ui.spinner(`${wantText ? "fetching" : "reading about"} ${id}`);
264
+ const d = await hub(`/documents/${encodeURIComponent(p.member)}/${encodeURIComponent(p.local)}`, { query: { text: wantText ? undefined : "false", pages: flags.pages } }).finally(() => sp.stop());
265
+ if (JSON_OUT) return ui.json(d);
266
+ if (flags.out) {
267
+ writeFileSync(flags.out, d.text ?? "");
268
+ ui.out(` ${ui.glyph.pass} wrote ${ui.fmtInt((d.text ?? "").length)} characters to ${flags.out}`);
269
+ }
270
+ ui.blank();
271
+ ui.out(` ${ui.bold(d.title ?? "Untitled")} ${ui.dim(`· ${d.id}`)}`);
272
+ ui.out(ui.kv([
273
+ ["date", d.date], ["authors", (d.authors ?? []).join("; ") || null], ["type", d.type], ["collection", d.collection],
274
+ ["pages", d.text_is_excerpt ? `${d.pages_returned.join(", ")} ${ui.dim(`of ${ui.fmtInt(d.pages_total)} · an excerpt${d.pages_missing?.length ? ` · not in the document: ${d.pages_missing.join(", ")}` : ""}`)}` : d.pages != null ? ui.fmtInt(d.pages) : null], ["tokens", d.text_is_excerpt ? `~${ui.fmtInt(d.excerpt_tokens_estimate)} in these pages${typeof d.tokens === "number" ? ui.dim(` · ${ui.fmtInt(d.tokens)} whole`) : ""}` : typeof d.tokens === "number" ? ui.fmtInt(d.tokens) : d.tokens_upper_bound ? ui.dim(`≤ ${ui.fmtInt(d.tokens_upper_bound)} (upper bound)`) : null],
275
+ ["terms", d.terms], ["permalink", d.permalink ? ui.underline(d.permalink) : null], ["source", d.source_url ? ui.underline(d.source_url) : null],
276
+ ...(wantText ? [["text", `${d.text_kind ?? "none"}${d.text_source ? ui.dim(` · ${d.text_source}`) : ""}${d.pages_marked ? ui.dim(" · [[page N]] markers") : ""}`]] : []),
277
+ ]));
278
+ if (wantText && !flags.out) {
279
+ ui.blank();
280
+ ui.out(ui.rule());
281
+ ui.out(d.text ?? ui.dim("(no text)"));
282
+ ui.out(ui.rule());
283
+ } else if (!wantText) {
284
+ ui.out(ui.dim(`\n --text prints the document's text (1 document of today's quota); -p 2-3 only those pages; -o file writes it.`));
285
+ }
286
+ ui.blank();
287
+ }
288
+
289
+ async function cmdCite(id) {
290
+ const p = splitId(id);
291
+ if (!p) return ui.fail("Cite which document?", "openarch cite <member>/<local id> [-s chicago|apa|mla|bibtex] [--all]");
292
+ const styles = flags.all ? ["chicago", "apa", "mla", "bibtex"] : [String(flags.style || "chicago").toLowerCase()];
293
+ const sp = ui.spinner(`citing ${id}`);
294
+ const out = [];
295
+ try { for (const s of styles) out.push(await hub(`/documents/${encodeURIComponent(p.member)}/${encodeURIComponent(p.local)}/citation`, { query: { style: s } })); }
296
+ finally { sp.stop(); }
297
+ if (JSON_OUT) return ui.json(flags.all ? out : out[0]);
298
+ ui.blank();
299
+ for (const c of out) { ui.out(` ${ui.label(c.style)}`); ui.out(c.citation.split("\n").map((l) => ` ${l}`).join("\n")); ui.blank(); }
300
+ }
301
+
302
+ async function cmdVerify(id, quote) {
303
+ const p = splitId(id);
304
+ if (!p || !quote) return ui.fail("Verify what, where?", 'openarch verify <member>/<local id> "the exact words"');
305
+ const sp = ui.spinner(`checking the quotation against ${id}`);
306
+ const v = await hub("/verify-quote", { method: "POST", body: { id, quote } }).finally(() => sp.stop());
307
+ if (JSON_OUT) return ui.json(v);
308
+ const g = v.status === "anchored" ? ui.green : v.status === "uncertain" ? ui.amber : ui.red;
309
+ ui.blank();
310
+ ui.out(` ${g(ui.bold(v.status))} ${ui.dim(`confidence ${v.confidence}${typeof v.offset === "number" ? ` · offset ${ui.fmtInt(v.offset)}` : ""} · ${v.method ?? "method unnamed"}`)}`);
311
+ if (v.matched_span) ui.out(` ${ui.dim("matched:")} ${v.matched_span}`);
312
+ if (v.note) ui.out(` ${ui.dim(v.note)}`);
313
+ if (v.permalink) ui.out(` ${ui.dim(v.permalink)}`);
314
+ ui.blank();
315
+ }
316
+
317
+ async function cmdWhoami() {
318
+ const sp = ui.spinner(`asking ${HUB} who you are`);
319
+ const w = await hub("/whoami").finally(() => sp.stop());
320
+ if (JSON_OUT) return ui.json(w);
321
+ ui.blank();
322
+ ui.out(` ${ui.bold(w.holder ?? "key holder")} ${ui.dim(`· ${w.role} key${w.label ? ` · ${w.label}` : ""}`)}`);
323
+ ui.out(ui.kv([["institution", w.institution], ["hub", HUB]]));
324
+ ui.blank();
325
+ const q = w.quotas ?? {}, u = w.used ?? {}, rem = w.remaining ?? {};
326
+ ui.out(ui.table([
327
+ { key: "quota", title: "quota" }, { key: "limit", title: "limit", align: "right", fixed: true }, { key: "used", title: "used", align: "right", fixed: true }, { key: "left", title: "left", align: "right", fixed: true },
328
+ ], [
329
+ { quota: "documents today", limit: ui.fmtInt(q.docsDay), used: ui.fmtInt(u.documents_today), left: ui.fmtInt(rem.documents_today) },
330
+ { quota: "bytes today", limit: ui.fmtBytes(q.bytesDay), used: ui.fmtBytes(u.bytes_today), left: ui.fmtBytes(rem.bytes_today) },
331
+ { quota: "searches this minute", limit: ui.fmtInt(q.searchMin), used: ui.fmtInt(u.searches_this_minute), left: ui.dim("—") },
332
+ { quota: "calls in flight", limit: ui.fmtInt(q.inflight), used: ui.dim("—"), left: ui.dim("—") },
333
+ ...(q.semanticPerMinute != null ? [
334
+ { quota: "semantic this minute", limit: ui.fmtInt(q.semanticPerMinute), used: ui.fmtInt(u.semantic_this_minute), left: ui.dim("—") },
335
+ { quota: "semantic today", limit: ui.fmtInt(q.semanticPerDay), used: ui.fmtInt(u.semantic_today), left: ui.fmtInt(rem.semantic_today) },
336
+ { quota: "semantic documents today", limit: ui.fmtInt(q.semanticDocsPerDay), used: ui.fmtInt(u.semantic_documents_today), left: ui.fmtInt(rem.semantic_documents_today) },
337
+ ] : []),
338
+ ]));
339
+ const calls = (w.recent_calls ?? []).slice(0, 10);
340
+ if (calls.length) {
341
+ ui.blank();
342
+ ui.out(ui.label(" recent calls"));
343
+ ui.out(ui.table([
344
+ { key: "at", title: "at (utc)", fixed: true }, { key: "member", title: "member" }, { key: "call", title: "call" }, { key: "doc_id", title: "document" }, { key: "bytes", title: "bytes", align: "right", fixed: true, format: ui.fmtBytes }, { key: "status", title: "status", align: "right", fixed: true },
345
+ ], calls));
346
+ }
347
+ ui.blank();
348
+ }
349
+
350
+ async function cmdLogin() {
351
+ ui.out(ui.banner(["store a key for this machine"]));
352
+ ui.blank();
353
+ const hubUrl = (await ui.ask("hub", { fallback: HUB })).replace(/\/+$/, "");
354
+ if (ui.plainHttpRemote(hubUrl)) return ui.fail(`${hubUrl} is plain http on another machine; a key goes only over https.`, "Give the hub's https address (http only for a hub on this machine).");
355
+ const key = await ui.ask("key (oa_…; not echoed)", { hidden: true });
356
+ if (!/^oa_(adm|mem|ro)_[0-9a-f]{40}$/.test(key)) return ui.fail("That does not look like an openarch key.", "Keys are oa_ro_ / oa_mem_ / oa_adm_ followed by 40 hex characters.");
357
+ const sp = ui.spinner(`checking the key with ${hubUrl}`);
358
+ let who;
359
+ try {
360
+ const res = await fetch(`${hubUrl}/api/v1/whoami`, { headers: { Authorization: `Bearer ${key}`, Accept: "application/json" }, signal: AbortSignal.timeout(30_000) });
361
+ who = res.ok ? cleanForTerminal(await res.json()) : null;
362
+ if (!res.ok) { sp.stop(); return ui.fail(`${hubUrl} did not accept the key (HTTP ${res.status}).`, "Nothing was saved."); }
363
+ } catch (e) { sp.stop(); return ui.fail(`Could not reach ${hubUrl}: ${e.message}`, "Nothing was saved."); }
364
+ sp.stop();
365
+ writeConfig({ ...cfg, hub: hubUrl, key });
366
+ ui.out(` ${ui.glyph.pass} saved for ${ui.bold(who.holder ?? "you")} ${ui.dim(`(${who.role} key, ${who.institution ?? "no institution"})`)} ${ui.dim(`→ ${CONFIG_FILE}`)}`);
367
+ ui.blank();
368
+ }
369
+
370
+ function cmdLogout() {
371
+ if (!existsSync(CONFIG_FILE)) return ui.out(ui.dim(" Nothing stored."));
372
+ rmSync(CONFIG_FILE);
373
+ ui.out(` ${ui.glyph.pass} removed ${CONFIG_FILE}`);
374
+ }
375
+
376
+ const today = () => new Date().toLocaleDateString("en-CA"); // YYYY-MM-DD, the signer's own date
377
+
378
+ /**
379
+ * The three declarations (protocol §4.1), asked in a terminal or taken from
380
+ * flags (--basis --grant --attribution --automated [--license] [--statement]
381
+ * --permalink --accept-as "Name"). Returns { rights, permalinks, agreement }.
382
+ */
383
+ async function askDeclarations({ who, presetSharing = null, presetPattern = null, preset = {}, record = () => {} } = {}) {
384
+ // preset: answers kept by an init that stopped part-way; record: each answer as it is given,
385
+ // so a Ctrl-C keeps it (walkthrough 3, finding 4)
386
+ const got = async (k, ask) => { const v = preset[k] !== undefined ? preset[k] : await ask(); record(k, v); return v; };
387
+ const basis = flags.basis || (await got("basis", () => ui.choose("Your rights in the materials — on what basis does your institution hold and serve them?", RIGHTS_BASIS)));
388
+ const grant = flags.grant || (await got("grant", () => ui.choose("What you grant others — what may a researcher, or an LLM agent, do with what you serve?", REUSE_GRANT)));
389
+ const license = flags.license || ((basis === "licensed" || grant === "open") ? await got("license", () => ui.ask("the license (an SPDX id or its name)")) : "");
390
+ const attribution = flags.attribution || (await got("attribution", () => ui.choose("Credit", ATTRIBUTION)));
391
+ const automated_access = flags.automated || (await got("automated_access", () => ui.choose("Automated access", AUTOMATED_ACCESS)));
392
+ const statement = flags.statement ?? (process.stdin.isTTY ? await got("statement", () => ui.ask("in your own words, if you like (served with every document; blank to skip)", { fallback: "" })) : "");
393
+ const pattern = presetPattern || flags.permalink || (await ui.ask("the pattern of your citable addresses, e.g. https://archive.example.edu/d/{id}"));
394
+ const promises = {};
395
+ for (const pr of PERMALINK_PROMISES) {
396
+ promises[pr.id] = flags["accept-as"] ? true : await got(`promise_${pr.id}`, () => ui.confirm(`${pr.label} — ${pr.note} Promise?`, true));
397
+ if (!promises[pr.id]) return ui.fail(`The permalink standard needs every promise; "${pr.label}" is part of membership.`, "See protocol §4.1 and the agreement §3.");
398
+ }
399
+ // the grid: --share pdf=text,image=files --withhold email=privileged, or one question per kind
400
+ const sharing = presetSharing ?? { share: {}, withhold: {} };
401
+ if (presetSharing) { /* init asked it for the kinds the catalog holds */ }
402
+ else if (flags.share || flags.withhold) {
403
+ for (const [k, v] of (flags.share || "").split(",").filter(Boolean).map((x) => x.split("="))) sharing.share[k] = v || "text";
404
+ for (const [k, v] of (flags.withhold || "").split(",").filter(Boolean).map((x) => x.split("="))) sharing.withhold[k] = v || "under-review";
405
+ } else {
406
+ ui.blank(); ui.out(` ${ui.bold("What you hold, and what you share.")} ${ui.dim("For each kind of material: not held, shared (how far), or withheld (why).")}`);
407
+ const CHOICES = [{ id: "none", label: "Not held", note: "this archive has none" }, ...SERVE_MODES.map((m) => ({ id: `share:${m.id}`, label: `Share — ${m.label}`, note: m.note })), ...WITHHOLD_REASONS.map((r) => ({ id: `withhold:${r.id}`, label: `Withhold — ${r.label}`, note: r.note }))];
408
+ for (const k of MATERIAL_KINDS) {
409
+ const c = await ui.choose(`${k.label} — ${k.note}`, CHOICES, { fallback: "none" });
410
+ if (c.startsWith("share:")) sharing.share[k.id] = c.slice(6); else if (c.startsWith("withhold:")) sharing.withhold[k.id] = c.slice(9);
411
+ }
412
+ }
413
+ const vs = validateSharing(sharing);
414
+ if (!vs.ok) return ui.fail("The sharing grid is not complete:", vs.problems.join("\n "));
415
+ let accepted_by = flags["accept-as"];
416
+ if (!accepted_by) {
417
+ ui.blank();
418
+ ui.out(` ${ui.bold(`The membership agreement, version ${AGREEMENT_VERSION}`)} ${ui.dim(`(${HUB}/agreement)`)}`);
419
+ for (const line of ["text as the floor; files only for the kinds your grid shares as files", "the declarations above, kept true", "what you serve is what you hold, unaltered — polluted or fabricated data means removal, and you indemnify openarch", "the permalink standard: minted once, old forms resolve, opens the document", "keys held by named people", "takedown answered within ten business days", "the hub's ledger of calls", "leave any time; permalinks outlive membership", "Stanford operates the hub"]) ui.out(` ${ui.dim("·")} ${line}`);
420
+ if (!(await ui.confirm("Accept, on behalf of your institution?", false))) return ui.fail("Membership needs the agreement.", "Read it at " + HUB + "/agreement and apply again.");
421
+ accepted_by = await ui.ask("your name, as the person accepting", { fallback: who || "" });
422
+ }
423
+ const d = {
424
+ rights: { basis, grant, attribution, automated_access, ...(license ? { license } : {}), ...(statement ? { statement } : {}), declared_by: accepted_by, declared_on: today() },
425
+ permalinks: { pattern, ...promises },
426
+ agreement: { version: AGREEMENT_VERSION, accepted_by, accepted_on: today() },
427
+ sharing,
428
+ };
429
+ const v = validateDeclarations(d);
430
+ if (!v.ok) return ui.fail("The declarations are not complete:", v.problems.join("\n "));
431
+ return d;
432
+ }
433
+
434
+ async function cmdApply() {
435
+ const kind = flags.kind || (await ui.ask("apply as — partner (use the network with a key) or member (connect an archive)", { fallback: "partner" }));
436
+ if (!["partner", "member"].includes(kind)) return ui.fail("kind must be partner or member");
437
+ const institution = flags.institution || (await ui.ask("institution"));
438
+ const name = flags.name || (await ui.ask("your name"));
439
+ const email = flags.email || (await ui.ask("your email"));
440
+ const purpose = flags.purpose || (await ui.ask(kind === "member" ? "the archive you would connect, in a sentence" : "what you will use it for, in a sentence"));
441
+ const archive_name = kind === "member" ? (flags.archive || (await ui.ask("the archive's name, as researchers know it"))) : undefined;
442
+ const home_url = kind === "member" ? (flags.home || (await ui.ask("the archive's public site", { fallback: "" }))) : undefined;
443
+ const base_url = kind === "member" ? (flags["base-url"] || (await ui.ask("your adapter's base URL", { fallback: "" }))) : undefined;
444
+ if (!institution || !name || !email) return ui.fail("institution, name and email are required.");
445
+ let declarations;
446
+ if (kind === "member") { declarations = await askDeclarations({ who: name }); if (!declarations) return; }
447
+ else {
448
+ let accepted_by = flags["accept-as"];
449
+ if (!accepted_by) {
450
+ ui.blank(); ui.out(` ${ui.bold(`The partner terms, version ${PARTNER_TERMS_VERSION}`)} ${ui.dim(`(${HUB}/partner-terms)`)}`);
451
+ for (const line of ["the key is yours, by name", "members' data comes as they serve it, without warranty from openarch", "use it within each member's terms; cite what you quote; verify quotations", "no re-hosting or bulk redistribution", "your calls are logged; you can read your own ledger", "either side can end it"]) ui.out(` ${ui.dim("·")} ${line}`);
452
+ if (!(await ui.confirm("Accept the partner terms?", false))) return ui.fail("A key needs the partner terms.", "Read them at " + HUB + "/partner-terms and apply again.");
453
+ accepted_by = await ui.ask("your name, as the person accepting", { fallback: name });
454
+ }
455
+ declarations = { partner_terms: { version: PARTNER_TERMS_VERSION, accepted_by, accepted_on: today() } };
456
+ }
457
+ const sp = ui.spinner(`sending to ${HUB}`);
458
+ const r = await hub("/access-requests", { method: "POST", auth: false, body: { kind, institution_name: institution, archive_name, contact_name: name, contact_email: email, purpose, home_url: home_url || undefined, base_url: base_url || undefined, declarations } }).finally(() => sp.stop());
459
+ if (JSON_OUT) return ui.json(r);
460
+ ui.blank();
461
+ ui.out(` ${ui.glyph.pass} received as request ${ui.bold(`#${r.id}`)} · ${r.status}`);
462
+ ui.out(` ${ui.dim(r.message)}`);
463
+ if (r.receipt_url && kind === "member") ui.out(` ${ui.bold("Your accepted agreement:")} ${ui.underline(r.receipt_url)} ${ui.dim("(add ?print=1 for Save as PDF)")}`);
464
+ if (kind === "member") ui.out(` ${ui.dim("An archive's adapter: openarch member init writes one, with these declarations in its manifest; openarch member check then walks it.")}`);
465
+ ui.blank();
466
+ }
467
+
468
+ function cmdProtocol() {
469
+ const p = join(ROOT, "protocol", "OPENARCH-PROTOCOL.md");
470
+ const md = readFileSync(p, "utf8");
471
+ if (JSON_OUT || !process.stdout.isTTY) return process.stdout.write(md);
472
+ let inCode = false;
473
+ for (const line of md.split("\n")) {
474
+ if (line.startsWith("```")) { inCode = !inCode; ui.out(ui.dim(line)); continue; }
475
+ if (inCode) ui.out(ui.dim(line));
476
+ else if (/^# /.test(line)) ui.out(ui.bold(line.replace(/^# /, "")));
477
+ else if (/^## /.test(line)) ui.out(`\n${ui.arch("§")} ${ui.bold(line.replace(/^## /, ""))}`);
478
+ else if (/^### /.test(line)) ui.out(ui.bold(line.replace(/^### /, "")));
479
+ else ui.out(line.replace(/`([^`]+)`/g, (_m, c) => ui.pale(c)));
480
+ }
481
+ }
482
+
483
+ // ── commands: join as a member ─────────────────────────────────────────────
484
+
485
+ /** In a member directory (openarch member init): its config and .env, for a check with no arguments. */
486
+ function memberHere() {
487
+ const cfgPath = resolve("openarch-member.json");
488
+ if (!existsSync(cfgPath)) return null;
489
+ let config; try { config = JSON.parse(readFileSync(cfgPath, "utf8")); } catch { return null; }
490
+ const env = {};
491
+ try { for (const l of readFileSync(resolve(".env"), "utf8").split("\n")) { const m = /^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*?)\s*$/.exec(l); if (m) env[m[1]] = m[2].replace(/^["']|["']$/g, ""); } } catch { /* no .env */ }
492
+ return { config, env };
493
+ }
494
+
495
+ /** The deploy files name the adapter's port too; say when they no longer match .env's PORT. */
496
+ function deployPortDrift(port) {
497
+ const out = [];
498
+ try { const m = /reverse_proxy\s+127\.0\.0\.1:(\d+)/.exec(readFileSync(resolve("deploy", "Caddyfile"), "utf8")); if (m && m[1] !== String(port)) out.push(`.env says PORT=${port}, but deploy/Caddyfile proxies to ${m[1]}: make them the same before going live.`); } catch { /* no Caddyfile */ }
499
+ try { const m = /-p 127\.0\.0\.1:\d+:(\d+)/.exec(readFileSync(resolve("deploy", "Dockerfile"), "utf8")); if (m && m[1] !== String(port)) out.push(`.env says PORT=${port}, but deploy/Dockerfile's run line maps ${m[1]}: change the -p mapping to match.`); } catch { /* no Dockerfile */ }
500
+ return out;
501
+ }
502
+
503
+ async function cmdMemberCheck(base) {
504
+ const here = !base ? memberHere() : null;
505
+ if (here) {
506
+ // run in the member's directory: the local adapter (npm start), or --public for the live address
507
+ base = flags.public ? here.config.public_base : `http://127.0.0.1:${here.env.PORT || 3101}`;
508
+ if (!flags.public && flags.local === undefined) flags.local = true;
509
+ if (!flags.credential && here.env.OPENARCH_HUB_CREDENTIAL) flags.credential = here.env.OPENARCH_HUB_CREDENTIAL;
510
+ }
511
+ if (!base) return ui.fail("Check which adapter?", "In your member's directory: openarch member check (this machine) or openarch member check --public (its live address). Elsewhere: openarch member check <base-url> [--credential …] [--local]");
512
+ // a bare host is https unless it is this machine (ind-sec run-1: a credential
513
+ // never crosses the network in the clear)
514
+ if (!/^https?:\/\//.test(base)) base = `${/^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(base) ? "http" : "https"}://${base}`;
515
+ const sp = ui.spinner(`walking ${base} through the protocol`);
516
+ let report;
517
+ try { report = await checkMember(base, { credential: flags.credential, query: flags.query, local: Boolean(flags.local), onStep: (c) => sp.update(`${c.id} ${c.title}`) }); }
518
+ catch (e) { sp.stop(); return ui.fail(e.message, "openarch member check https://<your adapter> --credential <its OPENARCH_HUB_CREDENTIAL>"); }
519
+ sp.stop();
520
+ if (JSON_OUT) { ui.json(report); process.exitCode = report.ready || (flags.local && report.conforms) ? 0 : 1; return; }
521
+ // the adapter's own words (its name, titles, citations, error text) reach this terminal
522
+ // through the details: control characters print as U+FFFD (P3 #25, ind-sec run-2)
523
+ report = cleanForTerminal(report);
524
+ ui.blank();
525
+ // ...and each on its own line: an adapter's line break can never print a check of its own
526
+ const L = ui.cleanLine;
527
+ ui.out(` ${ui.bold("openarch member check")} ${ui.dim(base)}${report.name ? ` ${ui.dim("·")} ${L(report.name)}` : ""}${flags.local ? ` ${ui.dim("· local test")}` : ""}`);
528
+ for (const s of report.sections) {
529
+ ui.blank();
530
+ ui.out(` ${ui.h2(`${s.id} ${L(s.title)}`)}`);
531
+ for (const c of s.checks) {
532
+ const g = ui.glyph[c.status];
533
+ ui.out(` ${g} ${ui.pad(L(c.title), 34)} ${c.status === "skip" ? ui.dim(L(c.detail)) : L(c.detail)}`);
534
+ if (c.fix && c.status !== "pass") ui.out(` ${ui.dim("→ " + L(c.fix))}`);
535
+ }
536
+ }
537
+ ui.blank();
538
+ ui.out(ui.rule(46));
539
+ const bits = [ui.green(`${report.passed} passed`), report.failed ? ui.red(`${report.failed} failed`) : null, report.warned ? ui.amber(`${report.warned} warning${report.warned === 1 ? "" : "s"}`) : null, report.skipped ? ui.dim(`${report.skipped} skipped`) : null].filter(Boolean);
540
+ ui.out(` ${bits.join(ui.dim(" · "))} ${ui.dim(`in ${ui.fmtMs(report.ms)}`)}`);
541
+ if (here) for (const w of deployPortDrift(here.env.PORT || "3101")) ui.out(` ${ui.amber("!")} ${ui.dim(w)}`);
542
+ if (report.gated) ui.out(` ${ui.dim("The adapter is gated (good). Re-run with --credential <the credential your adapter has set> to walk the gated calls.")}`);
543
+ else if (report.ready) ui.out(` ${ui.green("Ready to apply:")} openarch apply --kind member --base-url ${base}`);
544
+ else if (report.local && report.conforms) ui.out(` ${ui.green("Conforms (local test).")} ${ui.dim("Next: serve it at its public https address and run openarch member check there; that run says whether you are ready to apply.")}`);
545
+ else if (report.failed) ui.out(` ${ui.dim(`Fix the failures above and run the check again.${report.local ? "" : " Testing on this machine? Add --local."}`)}`);
546
+ ui.blank();
547
+ process.exitCode = (report.ready || (report.local && report.conforms)) && !(flags.strict && report.warned) ? 0 : 1;
548
+ }
549
+
550
+ async function cmdMemberInit(dir) {
551
+ const { memberInit } = await import("./init.js");
552
+ return memberInit({ dir, flags, ui, hub: HUB, version: PKG.version, root: ROOT, askDeclarations });
553
+ }
554
+
555
+ const APPLICATION_FILE = ".openarch-application.json";
556
+
557
+ /** openarch member apply: the declarations come from the live manifest, after a Ready check. */
558
+ async function cmdMemberApply() {
559
+ const here = memberHere();
560
+ if (!here) return ui.fail("Run it in your member's directory (where openarch member init wrote openarch-member.json).", "Elsewhere: openarch apply --kind member --base-url <your adapter>.");
561
+ // The receipt link is kept in this directory, which someone else may have supplied: a link
562
+ // at its name is refused before anything is sent, and the file is written through a new
563
+ // name and a rename, so a link swapped in later is replaced, never followed (ind-sec run-3 P2).
564
+ const appFile = resolve(APPLICATION_FILE);
565
+ const unsafe = refusal(appFile);
566
+ if (unsafe) return ui.fail(`${unsafe}, so nothing was sent and nothing was written.`, `apply keeps your receipt link in ${APPLICATION_FILE}: remove what is there, then run this again.`);
567
+ // --local: a development hub only, with the adapter on this machine (the real hub reaches
568
+ // members at a public https address, and refuses anything else)
569
+ if (flags.local && HUB === DEFAULT_HUB) return ui.fail("A local adapter cannot apply to the real hub.", "Serve it at its public https address and run openarch member apply there; --local is for a development hub (--hub).");
570
+ const base = (flags["base-url"] || (flags.local ? `http://127.0.0.1:${here.env.PORT || 3101}` : here.config.public_base)).replace(/\/+$/, "");
571
+ const sp = ui.spinner(`checking ${base} before applying`);
572
+ let report;
573
+ // .env's credential goes only to this member's own address or this machine, never to an address typed in (review nit)
574
+ const ownOrigin = (() => { try { const b = new URL(base), p = new URL(here.config.public_base); return b.origin === p.origin || /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/i.test(b.hostname); } catch { return false; } })();
575
+ try { report = await checkMember(base, { credential: flags.credential || (ownOrigin ? here.env.OPENARCH_HUB_CREDENTIAL : undefined), local: Boolean(flags.local) }); } finally { sp.stop(); }
576
+ if (!(flags.local ? report.conforms : report.ready)) {
577
+ const fails = cleanForTerminal(report.sections.flatMap((x) => x.checks).filter((c) => c.status === "fail"));
578
+ const unreachable = !flags.local && !report.reached;
579
+ ui.fail(`${base} is not ready to apply (${report.failed} check${report.failed === 1 ? "" : "s"} failed${report.gated ? ", gated calls not walked" : ""}).`,
580
+ fails.slice(0, 5).map((c) => `${c.id} ${ui.cleanLine(c.title)}: ${ui.cleanLine(c.detail)}`).join("\n ")
581
+ + `\n ${flags.local ? "openarch member check shows the whole walk." : "openarch member check --public shows the whole walk."}`
582
+ + (unreachable ? `\n Not live yet? Apply when ${base} answers. To rehearse against a development hub with the adapter on this machine: openarch member apply --local --hub <that hub>.` : ""));
583
+ return;
584
+ }
585
+ const m = (await fetch(`${base}/openarch/v1/manifest`, { signal: AbortSignal.timeout(30_000) }).then((r) => r.json()));
586
+ const shown = cleanForTerminal(m); // for this terminal; the application carries the manifest as sent
587
+ const name = flags.name || (await ui.ask("your name, as the person applying", { fallback: ui.cleanLine(m.agreement?.accepted_by || "") }));
588
+ const email = flags.email || (await ui.ask("your email", { fallback: ui.cleanLine(m.contact || "") }));
589
+ const purpose = flags.purpose || (await ui.ask("the archive, in a sentence (what it holds, for whom)"));
590
+ if (!name || !email || !purpose) return ui.fail("your name, email and a sentence about the archive are needed.");
591
+ const body = { kind: "member", institution_name: m.institution, archive_name: m.name, contact_name: name, contact_email: email, purpose, home_url: m.home || undefined, base_url: base, declarations: { rights: m.rights, permalinks: m.permalinks, agreement: m.agreement, sharing: m.sharing, member: m.member } };
592
+ // the real hub only on purpose: a test application must never go there by accident (walkthrough finding 23)
593
+ if (HUB === DEFAULT_HUB && !flags.yes) {
594
+ ui.blank(); ui.out(` ${ui.bold(`This sends ${ui.cleanLine(m.name)}'s application to ${HUB}.`)}`);
595
+ if (!(await ui.confirm("Send it?", false))) return ui.fail("Not sent.", "To try it against another hub: --hub <url>.");
596
+ }
597
+ const s = ui.spinner(`sending to ${HUB}`);
598
+ const r = await hub("/access-requests", { method: "POST", auth: false, body }).finally(() => s.stop());
599
+ const saved = { hub: HUB, id: r.id, receipt_url: r.receipt_url, status_url: r.status_url, member: m.member, base_url: base, sent_at: new Date().toISOString() };
600
+ writeReplacing(appFile, JSON.stringify(saved, null, 2) + "\n", 0o600);
601
+ if (JSON_OUT) return ui.json({ ...r, saved: APPLICATION_FILE });
602
+ ui.blank();
603
+ ui.out(` ${ui.glyph.pass} ${ui.bold(ui.cleanLine(shown.name))}: application ${ui.bold(`#${r.id}`)} received · ${ui.cleanLine(r.status)}`);
604
+ // the hub will call the address sent; the permalinks are what the adapter declares (walkthrough 2, 5 and 23)
605
+ const permalinkHost = (() => { try { return new URL(String(m.permalinks?.pattern ?? "").replace("{id}", "x")).host; } catch { return null; } })();
606
+ let baseHost = null; try { baseHost = new URL(base).host; } catch { /* checked above */ }
607
+ ui.out(ui.kv([["hub", HUB], ["adapter", `${base} ${ui.dim("(the address the hub will call)")}`], ["permalinks", ui.cleanLine(shown.permalinks?.pattern ?? "—")]]));
608
+ if (permalinkHost && baseHost && permalinkHost !== baseHost && flags.local) ui.out(` ${ui.amber("!")} ${ui.dim(`Your permalinks name ${permalinkHost}, which this local test does not serve; a real application needs ${permalinkHost} live.`)}`);
609
+ ui.out(ui.kv([["receipt", ui.cleanLine(r.receipt_url ?? "—")], ["next", "an operator reviews it; when approved you receive the hub's credential and an account key"], ["then", "openarch member credential set (it asks for the credential), restart the adapter"], ["meanwhile", "openarch member status"]]));
610
+ ui.out(` ${ui.dim(`Kept in ${APPLICATION_FILE} (it holds your receipt link; keep it private).`)}`);
611
+ ui.blank();
612
+ }
613
+
614
+ /** openarch member status: the application, and once approved, whether the hub reaches the adapter. */
615
+ async function cmdMemberStatus() {
616
+ let saved; try { saved = JSON.parse(readFileSync(APPLICATION_FILE, "utf8")); } catch { return ui.fail(`No ${APPLICATION_FILE} here.`, "Run it in your member's directory, after openarch member apply."); }
617
+ if (!saved.status_url) return ui.fail("This application was sent before status links existed.", `Ask the operator; your receipt: ${saved.receipt_url ?? "—"}`);
618
+ const r = await fetch(saved.status_url, { signal: AbortSignal.timeout(30_000) }).then(async (x) => ({ status: x.status, body: await x.json().catch(() => null) })).catch((e) => ({ status: 0, body: { message: e.message } }));
619
+ if (r.status !== 200) return ui.fail(`The hub did not answer the status (${r.status || r.body?.message}).`, saved.status_url);
620
+ const a = cleanForTerminal(r.body);
621
+ if (JSON_OUT) return ui.json(a);
622
+ ui.blank();
623
+ const verdict = a.status === "approved" ? ui.green("approved") : a.status === "denied" ? ui.red("denied") : a.status === "expired" ? ui.amber("expired") : ui.amber("pending review");
624
+ ui.out(` application #${a.id} · ${verdict} · received ${String(a.received_at).slice(0, 16)} UTC${a.decided_at ? ` · decided ${String(a.decided_at).slice(0, 16)} UTC` : ""}`);
625
+ if (a.member) {
626
+ const lc = a.member.last_call;
627
+ const reach = !lc ? ui.dim("the hub has not called your adapter yet") : lc.status === 401 ? ui.red(`the hub's last call was refused (401): set the hub's credential (openarch member credential set) and restart`) : lc.status < 400 ? ui.green(`the hub reached your adapter (${lc.call}, HTTP ${lc.status}, ${String(lc.at).slice(0, 16)} UTC)`) : ui.amber(`the hub's last call answered HTTP ${lc.status} (${lc.call}, ${String(lc.at).slice(0, 16)} UTC)`);
628
+ ui.out(` member ${ui.bold(a.member.slug)} · ${a.member.status} · manifest read ${a.member.manifest_read_at ? `${String(a.member.manifest_read_at).slice(0, 16)} UTC` : "never"}`);
629
+ ui.out(` ${reach}`);
630
+ } else if (a.status === "pending") ui.out(` ${ui.dim("An operator reviews every application; the approval brings your hub credential and account key.")}`);
631
+ else if (a.status === "expired") ui.out(` ${ui.dim("No operator decided it within 30 days. It is kept, with your accepted agreement; to be reviewed, apply again (openarch member apply).")}`);
632
+ ui.blank();
633
+ }
634
+
635
+ /**
636
+ * openarch member credential set: the hub's credential into .env (mode 600). It is read from a
637
+ * hidden prompt, or from stdin when piped, never from the command line, where it would stay in
638
+ * shell history and show in ps; only an oa_hub_ credential is accepted (the oa_mem_ account
639
+ * key is for openarch login); .env is replaced atomically, mode 600 from its first byte, never
640
+ * written through a symbolic link (ind-sec PR #3 review, S7–S9).
641
+ */
642
+ async function cmdMemberCredential(sub, value) {
643
+ if (sub !== "set") return ui.fail("openarch member credential set", "It asks for the credential the operator sent you (or reads it from a pipe).");
644
+ if (value) return ui.fail("Not on the command line: a credential typed there stays in your shell's history and shows in ps.", "Run openarch member credential set and paste it at the prompt, or pipe it in (openarch member credential set < file).");
645
+ if (!existsSync("openarch-member.json")) return ui.fail("Run it in your member's directory (where openarch-member.json is).");
646
+ let v;
647
+ if (process.stdin.isTTY) v = await ui.ask("the hub's credential, as the operator sent it (not shown)", { hidden: true });
648
+ else { const chunks = []; let n = 0; for await (const c of process.stdin) { chunks.push(c); n += c.length; if (n > 4096) break; } v = Buffer.concat(chunks).toString("utf8"); }
649
+ v = String(v ?? "").trim();
650
+ if (/^oa_mem_[0-9a-f]{40}$/.test(v)) return ui.fail("That is your account key (oa_mem_…), not the hub's credential.", "The account key is for openarch login and /account. The adapter takes the one that begins oa_hub_.");
651
+ if (!/^oa_hub_[0-9a-f]{40}$/.test(v)) return ui.fail("That is not a hub credential.", "It looks like oa_hub_ followed by 40 hex characters, as the operator sent it.");
652
+ const envPath = resolve(".env");
653
+ let text = "";
654
+ try {
655
+ if (lstatSync(envPath).isSymbolicLink()) return ui.fail(".env is a symbolic link.", "Replace it with a plain file, then run this again.");
656
+ text = readFileSync(envPath, "utf8");
657
+ } catch (e) { if (e.code !== "ENOENT") throw e; }
658
+ let placed = false;
659
+ const lines = text.split("\n").filter((l) => !/^OPENARCH_HUB_CREDENTIAL_SHA256=/.test(l)).flatMap((l) => {
660
+ if (!/^OPENARCH_HUB_CREDENTIAL=/.test(l)) return [l];
661
+ if (placed) return []; // every old credential line goes; the new one stands once
662
+ placed = true; return [`OPENARCH_HUB_CREDENTIAL=${v}`];
663
+ });
664
+ let out = lines.join("\n");
665
+ if (!placed) out = `${out.replace(/\n*$/, "\n")}OPENARCH_HUB_CREDENTIAL=${v}\n`;
666
+ if (!out.endsWith("\n")) out += "\n";
667
+ const tmp = `${envPath}.${process.pid}.tmp`;
668
+ const fd = openSync(tmp, "wx", 0o600);
669
+ try { writeSync(fd, out); fsyncSync(fd); } finally { closeSync(fd); }
670
+ renameSync(tmp, envPath);
671
+ ui.blank();
672
+ ui.out(` ${ui.glyph.pass} the hub's credential is in .env ${ui.dim("(mode 600; the provisional one is gone)")}`);
673
+ ui.out(ui.kv([["now", "restart the adapter (systemctl restart openarch-member, or npm start); on a server, copy .env there first"], ["then", "openarch member status — the hub's next call should answer 200"]]));
674
+ ui.blank();
675
+ }
676
+
677
+ // ── commands: operate the hub ──────────────────────────────────────────────
678
+
679
+ async function cmdAdmin(sub, a1, a2) {
680
+ const A = (p, o) => hub(`/admin${p}`, o);
681
+ // true once written: stdout.write's own answer is false whenever the pipe is full, and a
682
+ // long listing (more than about 16 KB) then printed its table after the JSON
683
+ const show = (v) => (JSON_OUT ? (ui.json(v), true) : false);
684
+ switch (sub) {
685
+ case "overview": { const o = await A("/overview"); if (show(o)) return; ui.blank(); ui.out(ui.kv(Object.entries(o).map(([k, v]) => [k.replace(/_/g, " "), typeof v === "object" ? JSON.stringify(v) : ui.fmtInt(v)]))); ui.blank(); return; }
686
+ case "requests": {
687
+ // every page (ind-sec run-3 P2: the hub pages its listing); a hub that does not page answers one
688
+ const requests = [];
689
+ for (let before; ;) {
690
+ const p = await A("/access-requests", { query: { status: flags.status || "pending", before } });
691
+ requests.push(...(p.requests ?? []));
692
+ if (!p.next_before || (before && !(p.next_before < before))) break;
693
+ before = p.next_before;
694
+ }
695
+ if (show(requests)) return; ui.blank(); if (!requests.length) return ui.out(ui.dim(` No ${flags.status || "pending"} requests.`)); ui.out(ui.table([{ key: "id", title: "id", align: "right", fixed: true }, { key: "created_at", title: "received (utc)", fixed: true }, { key: "kind", title: "kind" }, { key: "institution_name", title: "institution" }, { key: "contact_name", title: "contact" }, { key: "contact_email", title: "email" }, { key: "purpose", title: "purpose" }, { key: "base_url", title: "adapter" }], requests)); ui.blank(); ui.out(ui.dim(" openarch admin approve <id> --institution <slug> · openarch admin deny <id>")); ui.blank(); return; }
696
+ case "approve": { if (!a1) return ui.fail("Approve which request?", "openarch admin approve <id> --institution <slug> [--expires YYYY-MM-DD]"); let r; try { r = await A(`/access-requests/${a1}/approve`, { method: "POST", body: { institution: flags.institution, expires_at: flags.expires, slug: flags.slug, base_url: flags["base-url"], ...(flags["same-institution"] ? { confirm_shared_institution: true } : {}) } }); }
697
+ catch (e) { if (e.body?.error === "slug_required") return ui.fail(e.body.message, e.body.discovered ? `openarch admin approve ${a1} --institution ${flags.institution} --slug ${e.body.discovered}` : `openarch admin approve ${a1} --institution ${flags.institution} --slug <its short name>`); throw e; }
698
+ if (show(r)) return; ui.blank();
699
+ if (r.kind === "member") {
700
+ ui.out(` ${ui.glyph.pass} request #${r.request} approved · member ${ui.bold(r.member)} registered at ${r.base_url}${r.warning ? ` ${ui.amber(r.warning)}` : ""}`);
701
+ ui.out(` ${ui.dim("Send both to")} ${r.account_key.send_to} ${ui.dim(`(${r.account_key.holder}). Shown once.`)}`);
702
+ ui.out(ui.kv([["hub credential", r.hub_credential], [" for", "the adapter: openarch member credential set (it asks for it), then a restart"], ["account key", r.account_key.plaintext], [" for", "openarch login, and /account (the sharing board)"]]));
703
+ ui.blank(); return;
704
+ }
705
+ ui.out(` ${ui.glyph.pass} request #${r.request} approved · key #${r.key.id} for ${ui.bold(r.key.holder)} → send to ${r.key.send_to}`); ui.out(` ${ui.bold(r.key.plaintext)}`); ui.out(` ${ui.amber(r.note)}`); ui.blank(); return; }
706
+ case "deny": { if (!a1) return ui.fail("Deny which request?"); await A(`/access-requests/${a1}/deny`, { method: "POST", body: { reason: flags.purpose } }); return ui.out(` ${ui.glyph.pass} request #${a1} denied`); }
707
+ case "keys": {
708
+ if (a1 === "issue") { const need = ["role", "institution", "holder"].filter((k) => !flags[k]); if (need.length) return ui.fail(`Missing --${need.join(" --")}`, "openarch admin keys issue --role partner|member|admin --institution <slug> --holder \"Name\" [--label …] [--expires YYYY-MM-DD]"); const r = await A("/keys", { method: "POST", body: { role: flags.role, institution: flags.institution, holder: flags.holder, label: flags.label, expires_at: flags.expires } }); if (show(r)) return; ui.blank(); ui.out(` ${ui.glyph.pass} key #${r.key?.id ?? r.id} (${flags.role}) for ${ui.bold(flags.holder)}`); ui.out(` ${ui.bold(r.key?.plaintext ?? r.plaintext)}`); ui.out(` ${ui.amber("Shown once; only its hash is stored.")}`); ui.blank(); return; }
709
+ if (a1 === "revoke") { if (!a2) return ui.fail("Revoke which key id?"); await A(`/keys/${a2}/revoke`, { method: "POST" }); return ui.out(` ${ui.glyph.pass} key #${a2} revoked`); }
710
+ const { keys } = await A("/keys"); if (show(keys)) return; ui.blank(); ui.out(ui.table([{ key: "id", title: "id", align: "right", fixed: true }, { key: "key_prefix", title: "prefix" }, { key: "role", title: "role" }, { key: "holder", title: "holder" }, { key: "institution", title: "institution" }, { key: "status", title: "status", format: (v) => (v === "active" ? ui.green(v) : ui.red(v)) }, { key: "expires_at", title: "expires", fixed: true, format: (v) => (v ? v.slice(0, 10) : ui.dim("never")) }, { key: "last_used_at", title: "last used", fixed: true, format: (v) => (v ? v.slice(0, 16) : ui.dim("never")) }], keys)); ui.blank(); return;
711
+ }
712
+ case "members": {
713
+ if (a1 === "add") { const need = ["slug", "institution", "base-url"].filter((k) => !flags[k]); if (need.length) return ui.fail(`Missing --${need.join(" --")}`, 'openarch admin members add --slug indra --institution stanford --base-url https://… [--credential oa_hub_…]'); const r = await A("/members", { method: "POST", body: { slug: flags.slug, institution: flags.institution, base_url: flags["base-url"], hub_credential: flags.credential } }); if (show(r)) return; ui.out(` ${ui.glyph.pass} member ${ui.bold(flags.slug)} registered · ${r.manifest ? `${(r.manifest.collections ?? []).length} collections` : ui.amber(r.warning || "manifest not read")}`); return; }
714
+ if (a1 === "refresh") { if (!a2) return ui.fail("Refresh which member?"); const r = await A(`/members/${a2}/refresh`, { method: "POST" }); if (show(r)) return; ui.out(` ${ui.glyph.pass} ${a2}: manifest re-read · ${(r.manifest?.collections ?? []).length} collections`); return; }
715
+ if (a1 === "sharing") { if (!a2 || !(flags.share || flags.withhold)) return ui.fail("openarch admin members sharing <slug> --share pdf=text,image=files [--withhold email=privileged]"); const sharing = { share: Object.fromEntries((flags.share || "").split(",").filter(Boolean).map((x) => { const [k, v] = x.split("="); return [k, v || "text"]; })), withhold: Object.fromEntries((flags.withhold || "").split(",").filter(Boolean).map((x) => { const [k, v] = x.split("="); return [k, v || "under-review"]; })) }; const r = await A(`/members/${a2}/sharing`, { method: "POST", body: { sharing } }); if (show(r)) return; return ui.out(` ${ui.glyph.pass} ${a2}: sharing grid set`); }
716
+ if (a1 === "credential") { if (!a2 || !flags.credential) return ui.fail("openarch admin members credential <slug> --credential oa_hub_…"); await A(`/members/${a2}/credential`, { method: "POST", body: { hub_credential: flags.credential } }); return ui.out(` ${ui.glyph.pass} ${a2}: hub credential set`); }
717
+ const { members } = await A("/members"); if (show(members)) return; ui.blank(); ui.out(ui.table([{ key: "slug", title: "member", format: (v) => ui.bold(v) }, { key: "institution_name", title: "institution" }, { key: "base_url", title: "base url" }, { key: "status", title: "status", format: (v) => (v === "active" ? ui.green(v) : ui.red(v)) }, { key: "hub_credential", title: "credential", format: (v) => (v ? ui.green("set") : ui.amber("none")) }, { key: "manifest_at", title: "manifest read", fixed: true, format: (v) => (v ? v.slice(0, 16) : ui.dim("never")) }], members)); ui.blank(); return;
718
+ }
719
+ case "institutions": {
720
+ if (a1 === "add") { if (!flags.slug || !flags.name) return ui.fail("openarch admin institutions add --slug <slug> --name \"Name\""); const r = await A("/institutions", { method: "POST", body: { slug: flags.slug, name: flags.name, kind: flags.kind, contact_email: flags.email } }); if (show(r)) return; return ui.out(` ${ui.glyph.pass} institution ${ui.bold(flags.slug)} added`); }
721
+ const { institutions } = await A("/institutions"); if (show(institutions)) return; ui.blank(); ui.out(ui.table([{ key: "slug", title: "slug", format: (v) => ui.bold(v) }, { key: "name", title: "name" }, { key: "kind", title: "kind" }, { key: "status", title: "status" }, { key: "created_at", title: "since", fixed: true, format: (v) => (v ? v.slice(0, 10) : "") }], institutions)); ui.blank(); return;
722
+ }
723
+ case "audit": { const { audit } = await A("/audit", { query: { limit: num(flags.limit, 50) } }); if (show(audit)) return; ui.blank(); ui.out(ui.table([{ key: "at", title: "at (utc)", fixed: true }, { key: "actor", title: "actor" }, { key: "action", title: "action" }, { key: "detail", title: "detail", format: (v) => (typeof v === "string" ? v : JSON.stringify(v)) }], audit)); ui.blank(); return; }
724
+ case "calls": { const { calls } = await A("/calls", { query: { limit: num(flags.limit, 50) } }); if (show(calls)) return; ui.blank(); ui.out(ui.table([{ key: "at", title: "at (utc)", fixed: true }, { key: "holder", title: "partner" }, { key: "member_slug", title: "member" }, { key: "call", title: "call" }, { key: "doc_id", title: "document" }, { key: "bytes", title: "bytes", align: "right", fixed: true, format: ui.fmtBytes }, { key: "status", title: "status", align: "right", fixed: true }, { key: "ms", title: "ms", align: "right", fixed: true }], calls)); ui.blank(); return; }
725
+ default: return ui.fail(`Unknown admin command ${JSON.stringify(sub ?? "")}.`, "openarch admin overview | requests | approve | deny | keys | members | institutions | audit | calls");
726
+ }
727
+ }
728
+
729
+ // ── dispatch ───────────────────────────────────────────────────────────────
730
+
731
+ /** What the research and agent commands need from this file. */
732
+ const ctx = () => ({ hub, HUB, KEY, DEFAULT_HUB, ROOT, flags, JSON_OUT, num, version: PKG.version, keySource: KEY_SOURCE, storedKey: STORED_KEY, storedKeyHub: STORED_KEY_HUB });
733
+
734
+ // One screen per command, for `<command> --help`: what it does, every flag, and what comes next.
735
+ const COMMAND_HELP = {
736
+ member: `openarch member <command> connect your archive to the network
737
+ openarch member <slug> (with a member's short name: that member's collections)
738
+
739
+ The path, in order — each command has its own help (openarch member init --help):
740
+ member init [dir] asks about your archive, reads your catalog, writes the adapter
741
+ npm install && npm start in that directory: your archive answers on this machine
742
+ member check in that directory: the conformance walk, on this machine
743
+ (go live) deploy/ in that directory; see its README.md
744
+ member check --public the walk at your public https address: "Ready to apply"
745
+ member apply sends the application (declarations read from your adapter)
746
+ member status pending, approved; once approved, whether the hub reaches you
747
+ member credential set the hub's credential, sent to you at approval (it asks); then restart
748
+
749
+ Rehearsing against a development hub, with the adapter on this machine:
750
+ member apply --local --hub <that hub>
751
+
752
+ The guide: ${INSTALLED_HUB ?? DEFAULT_HUB}/cli/ (and members/kit/README.md in this package)`,
753
+ "member init": `openarch member init [dir]
754
+ From your catalog and files to a running adapter, with no code to write.
755
+
756
+ In a terminal it asks: the archive's name, institution, contact, short name and public
757
+ https address; your catalog file (CSV, TSV or JSONL — one row per document); which
758
+ column is which (it guesses; you confirm, with a preview); the declarations (rights,
759
+ grant, credit, automated access, the agreement) and, for each kind of material your
760
+ catalog holds, whether you share it and how far.
761
+
762
+ It writes [dir]/: openarch-member.json (everything it serves), index.js (three lines),
763
+ package.json, .env (a provisional hub credential, mode 600, never sent anywhere),
764
+ README.md and deploy/ (Dockerfile, systemd unit, Caddyfile). Then it loads your catalog
765
+ once and reports what it found, or each problem with its line.
766
+
767
+ --answers <file.json> the same answers as JSON, for a script (see members/kit/README.md)
768
+ --example the demonstration archive (member check names it as the example)
769
+ --kit <npm source> where the member kit comes from (default: this hub's tarball)
770
+
771
+ Next: cd [dir] && npm install && npm start, then openarch member check`,
772
+ "member check": `openarch member check [<base-url>] [--public] [--local] [--credential …] [-q <word>] [--strict]
773
+ The conformance walk: every protocol call, each failure named by section with its fix,
774
+ then "Ready to apply" — a public https address, gated by a credential, your own archive
775
+ (not the example), your permalinks as declared, the agreement and sharing grid declared.
776
+
777
+ In your member's directory it needs no arguments: it checks the adapter on this machine
778
+ (a local test, using .env's credential), or with --public the live public address.
779
+ Elsewhere, give the base URL: the address before /openarch/v1.
780
+
781
+ --local a test on this machine: "conforms", never "ready to apply"
782
+ --public in a member's directory: check the public address
783
+ --credential the credential your adapter checks (in a member's directory: from .env)
784
+ -q <word> a word your archive contains, for the search checks
785
+ --strict warnings fail too
786
+ --json the report as JSON (exit 0 only when ready, or conforms with --local)`,
787
+ "member apply": `openarch member apply [--name …] [--email …] [--purpose …] [--yes]
788
+ In your member's directory: checks your public address first and applies only when it is
789
+ Ready; the declarations are read from your live manifest, so you answer only who you are
790
+ and a sentence about the archive. Before sending to the real hub it asks you to confirm
791
+ (--yes skips). The receipt and status links are kept in .openarch-application.json.
792
+
793
+ --local apply the local adapter to a development hub (--hub); refused for the real hub
794
+ --base-url a different live address than openarch-member.json's public_base
795
+
796
+ Next: openarch member status · when approved: openarch member credential set (it asks for it)`,
797
+ "member status": `openarch member status
798
+ In your member's directory, after openarch member apply: pending, approved, denied or
799
+ expired (no decision within 30 days); once approved, your member's status and the hub's
800
+ last call to your adapter (a 401 means the adapter does not yet hold the hub's credential).`,
801
+ "member credential": `openarch member credential set
802
+ In your member's directory: asks for the credential the operator sent you at approval
803
+ (oa_hub_…, not shown as you paste it), or reads it from a pipe
804
+ (openarch member credential set < file), and puts it into .env (mode 600), replacing the
805
+ provisional one. Never on the command line: it would stay in your shell's history. Restart
806
+ the adapter (on a server, copy .env there first); openarch member status then shows the hub
807
+ reaching it.`,
808
+ apply: `openarch apply [--kind partner|member] [--institution …] [--name …] [--email …] [--purpose …]
809
+ A partner key request (the partner terms), or a member application from the declarations
810
+ asked here. A member with an adapter made by openarch member init uses openarch member apply
811
+ instead: it reads the declarations from your manifest and checks your address first.
812
+
813
+ --kind --institution --name --email --purpose --archive --home --base-url
814
+ --basis --grant --attribution --automated --license --statement --permalink
815
+ --share kind=mode,… --withhold kind=reason,… --accept-as "Name" (every question, as a flag)`,
816
+ };
817
+
818
+ async function main() {
819
+ const [cmd, a1, a2] = positionals;
820
+ if (flags.version) return ui.out(`openarch ${PKG.version} · protocol 0.1`);
821
+ // per-command help: `openarch member init --help`, `openarch help member apply`, `openarch apply -h`
822
+ if ((flags.help && cmd) || (cmd === "help" && positionals[1])) {
823
+ const words = (cmd === "help" ? positionals.slice(1) : positionals).filter((w) => !w.startsWith("-")).slice(0, 2);
824
+ const t = COMMAND_HELP[words.join(" ")] ?? COMMAND_HELP[words[0]];
825
+ if (t) { ui.blank(); for (const l of t.trim().split("\n")) ui.out(` ${l}`); ui.blank(); return; }
826
+ }
827
+ if (!cmd || flags.help || cmd === "help") return help();
828
+ switch (cmd) {
829
+ case "members": return cmdMembers();
830
+ case "member":
831
+ if (a1 === "check") return cmdMemberCheck(a2);
832
+ if (a1 === "init") return cmdMemberInit(a2);
833
+ if (a1 === "apply") return cmdMemberApply();
834
+ if (a1 === "status") return cmdMemberStatus();
835
+ if (a1 === "credential") return cmdMemberCredential(a2, positionals[3]);
836
+ if (!a1 || a1 === "help") { ui.blank(); for (const l of COMMAND_HELP.member.trim().split("\n")) ui.out(` ${l}`); ui.blank(); return; }
837
+ return cmdMember(a1);
838
+ case "search": return cmdSearch(positionals.slice(1).join(" "));
839
+ case "doc": case "document": return cmdDoc(a1);
840
+ case "cite": case "citation": return cmdCite(a1);
841
+ case "verify": return flags.from ? cmdVerifyDraft(ctx(), flags.from) : cmdVerify(a1, positionals.slice(2).join(" "));
842
+ case "quote": case "find": return cmdQuote(ctx(), positionals.slice(1).join(" "));
843
+ case "pull": return cmdPull(ctx(), positionals.slice(1).join(" "));
844
+ case "may": return cmdMay(ctx(), a1, a2);
845
+ case "mcp": return cmdMcp(ctx(), a1, a2);
846
+ case "whoami": return cmdWhoami();
847
+ case "login": return cmdLogin();
848
+ case "logout": return cmdLogout();
849
+ case "apply": return cmdApply();
850
+ case "protocol": return cmdProtocol();
851
+ case "admin": return cmdAdmin(a1, a2, positionals[3]);
852
+ default: return ui.fail(`Unknown command ${JSON.stringify(cmd)}.`, "openarch --help");
853
+ }
854
+ }
855
+
856
+ main().catch((e) => { explain(e); if (!process.exitCode) process.exitCode = 1; });