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,114 @@
1
+ // pathCheck.js — which `openarch` does typing `openarch` run? (ind-sec, 2026-11-26)
2
+ // The public npm registry's "openarch" is someone else's program. A person who installed it
3
+ // (an old receipt page told members to install that bare name from npm) has a stranger's `openarch` on PATH, and a
4
+ // command typed with a key (`openarch login`, `openarch member check --credential …`) would
5
+ // hand that key to it. Agents are safe either way: `openarch mcp install` writes this
6
+ // program's absolute path, never the bare name. This lists every `openarch` on PATH and says
7
+ // which are this program, another copy of it, or something else.
8
+ //
9
+ // This program's npm package is "stanford-openarch" (2026-11-29; before, "openarch", the
10
+ // stranger's name, which let a name-based npm update replace it: ind-sec run-3 P2). Its command
11
+ // is still `openarch`.
12
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
13
+ import { delimiter, dirname, join, resolve, isAbsolute, posix } from "node:path";
14
+ import { createHash } from "node:crypto";
15
+ import { cleanLine, shq } from "./ui.js";
16
+
17
+ /** This program's npm package name (server/lib/memberPackage.js serves it under this name). */
18
+ export const PACKAGE_NAME = "stanford-openarch";
19
+
20
+ const FILE_MAX = 4 * 1024 * 1024, FILES_MAX = 400;
21
+ // a relative import: `from "./x.js"`, `import "./x.js"`, `import("./x.js")`
22
+ const RELATIVE_IMPORT = /(?:^|[\s;])(?:(?:from|import)\s+|import\s*\(\s*)["'](\.\.?\/[^"']+)["']/gm;
23
+
24
+ /**
25
+ * The code that typing `openarch` runs from a package: its entry point, cli/openarch.js, and
26
+ * every file that reaches by a relative import, recursively — one sha256 over each file's path
27
+ * in the package and its bytes. null when any of them is missing, unreadable, too large or
28
+ * outside the package. The package.json (which names the hub that served it) is not code and is
29
+ * not part of it; npm's dependencies (express, zod, the MCP SDK) are npm's to resolve, not ours.
30
+ * @param {string} root a package directory
31
+ */
32
+ export function codeDigest(root) {
33
+ const hashes = new Map(), queue = ["cli/openarch.js"];
34
+ while (queue.length) {
35
+ const rel = queue.shift();
36
+ if (hashes.has(rel)) continue;
37
+ if (hashes.size >= FILES_MAX) return null;
38
+ let body;
39
+ try { const p = join(root, rel), st = statSync(p); if (!st.isFile() || st.size > FILE_MAX) return null; body = readFileSync(p); } catch { return null; }
40
+ hashes.set(rel, createHash("sha256").update(body).digest("hex"));
41
+ if (!/\.m?js$/.test(rel)) continue;
42
+ for (const m of body.toString("utf8").matchAll(RELATIVE_IMPORT)) {
43
+ const next = posix.normalize(posix.join(posix.dirname(rel), m[1]));
44
+ if (next === ".." || next.startsWith("../")) return null;
45
+ if (!next.endsWith("package.json")) queue.push(next);
46
+ }
47
+ }
48
+ const h = createHash("sha256");
49
+ for (const rel of [...hashes.keys()].sort()) h.update(`${rel}\t${hashes.get(rel)}\n`);
50
+ return h.digest("hex");
51
+ }
52
+
53
+ /** The package directory an executable belongs to: the nearest package.json above its real path. */
54
+ function packageOf(file) {
55
+ let d = dirname(file);
56
+ for (let i = 0; i < 6 && d !== dirname(d); i++, d = dirname(d)) {
57
+ const p = join(d, "package.json");
58
+ if (existsSync(p)) { try { return { dir: d, pkg: JSON.parse(readFileSync(p, "utf8")) } } catch { return { dir: d, pkg: null }; } }
59
+ }
60
+ return { dir: null, pkg: null };
61
+ }
62
+
63
+ /** Another copy of this program: a package named stanford-openarch, whose `openarch` is its own
64
+ * cli/openarch.js, running exactly this program's code (codeDigest). Everything else a package
65
+ * shows is anyone's to write — its name, a package.json's openarch.hub, a protocol file, an
66
+ * entry point copied byte for byte beside a changed file it imports — so none of it alone makes
67
+ * a copy (PR #3 review, S11; ind-sec run-3 P2: the hub marker turned a forgery's fail into a warn). */
68
+ function isOurs(dir, pkg, real, selfDigest) {
69
+ if (!dir || !selfDigest || pkg?.name !== PACKAGE_NAME) return false;
70
+ let entry; try { entry = realpathSync(join(dir, "cli", "openarch.js")); } catch { return false; }
71
+ return entry === real && codeDigest(dir) === selfDigest;
72
+ }
73
+
74
+ /**
75
+ * Every `openarch` on PATH, in PATH order: { path, real, kind: "this" | "copy" | "other", name, version, description }.
76
+ * @param {string} selfRoot this program's package directory
77
+ */
78
+ export function openarchOnPath(selfRoot, env = process.env) {
79
+ const self = (() => { try { return realpathSync(join(selfRoot, "cli", "openarch.js")); } catch { return null; } })();
80
+ let selfDigest; // computed once, and only when PATH holds an openarch that is not this file
81
+ const digest = () => (selfDigest === undefined ? (selfDigest = self ? codeDigest(dirname(dirname(self))) : null) : selfDigest);
82
+ const names = process.platform === "win32" ? ["openarch.cmd", "openarch.exe", "openarch"] : ["openarch"];
83
+ const seen = new Set(), out = [];
84
+ // an empty PATH entry is the current directory, as the shell reads it (S10)
85
+ const entries = String(env.PATH ?? "").split(delimiter).map((d) => d || ".");
86
+ out.relativeEntries = entries.filter((d) => !isAbsolute(d));
87
+ for (const dir of entries) {
88
+ for (const n of names) {
89
+ const p = resolve(dir, n);
90
+ let real; try { if (!statSync(p).isFile()) continue; real = realpathSync(p); } catch { continue; }
91
+ if (seen.has(real)) continue;
92
+ seen.add(real);
93
+ const { dir: pkgDir, pkg } = packageOf(real);
94
+ const kind = real === self ? "this" : isOurs(pkgDir, pkg, real, digest()) ? "copy" : "other";
95
+ out.push({ path: p, real, kind, relative: !isAbsolute(dir), name: pkg?.name ?? null, version: pkg?.version ?? null, description: pkg?.description ?? null });
96
+ }
97
+ }
98
+ return out;
99
+ }
100
+
101
+ /** One doctor line: { status, detail, fix } for the list above. */
102
+ export function judgeOpenarchOnPath(found) {
103
+ if (!found.length) return { status: "warn", detail: `no openarch on PATH (this one ran by its full path)${found.relativeEntries?.length ? "; PATH also has relative entries" : ""}`, fix: "Typing openarch will not find it: add npm's global bin to PATH (npm prefix -g)." };
104
+ const first = found[0], others = found.filter((f) => f.kind === "other");
105
+ // a squatter's package.json reaches this terminal: through the filter, and quoted in a command (S12)
106
+ const label = (f) => cleanLine(`${f.path}${f.name ? ` (${String(f.name).slice(0, 60)}${f.version ? `@${String(f.version).slice(0, 20)}` : ""}${f.description ? `: ${String(f.description).slice(0, 80)}` : ""})` : ""}`);
107
+ const rm = (f) => `npm rm -g ${shq(/^(@[a-z0-9._-]+\/)?[a-z0-9._-]{1,214}$/.test(f.name ?? "") ? f.name : "openarch")}`;
108
+ const rel = found.filter((f) => f.relative);
109
+ if (first.kind === "other") return { status: "fail", detail: `typing openarch runs ${label(first)}, which is not this network's program`, fix: `Remove it (${rm(first)}) and install openarch from your hub's /cli/ page. If you used an openarch key with that command, tell the operator so the key is replaced.` };
110
+ if (rel.length || found.relativeEntries?.length) return { status: "warn", detail: rel.length ? `PATH has a relative entry (or ".") that holds ${label(rel[0])}` : `PATH has relative entries (${cleanLine(found.relativeEntries.slice(0, 3).map((d) => JSON.stringify(d)).join(", "))}): typing openarch in a folder that holds an openarch file would run that file`, fix: "Remove the relative entries (and any empty one, which means the current directory) from PATH." };
111
+ if (others.length) return { status: "warn", detail: `also on PATH: ${others.map(label).join("; ")}`, fix: `That is someone else's program named openarch; remove it (${rm(others[0])}) so it can never run in this one's place.` };
112
+ if (first.kind === "copy") return { status: "warn", detail: `typing openarch runs another copy: ${first.path}${first.version ? ` (${first.version})` : ""}`, fix: `Two copies of openarch are installed; keep one (npm ls -g ${PACKAGE_NAME}).` };
113
+ return { status: "pass", detail: `typing openarch runs this program (${first.path})` };
114
+ }
@@ -0,0 +1,248 @@
1
+ // research.js — the CLI's research commands: find a quotation's source, lint a
2
+ // draft's quotations against their documents, and pull a corpus to disk. Each is a
3
+ // thin loop over the Hub API; the hub routes, meters and records every call.
4
+ import { readFileSync, existsSync, mkdirSync, lstatSync } from "node:fs";
5
+ import { createHash } from "node:crypto";
6
+ import { join, resolve, relative } from "node:path";
7
+ import * as ui from "./ui.js";
8
+ import { extractQuotes } from "./draft.js";
9
+ import { refusal, appendOwn, writeReplacing, UnsafePath } from "./safeFile.js";
10
+
11
+ const sha256 = (s) => createHash("sha256").update(s).digest("hex");
12
+ const STATUS_GLYPH = { anchored: ui.glyph.pass, uncertain: ui.amber("~"), fabricated: ui.glyph.fail, unverifiable: ui.amber("?"), uncited: ui.dim("–") };
13
+ const paint = (status, s) => (status === "anchored" ? ui.green(s) : status === "uncertain" || status === "unverifiable" ? ui.amber(s) : status === "fabricated" ? ui.red(s) : ui.dim(s));
14
+ const clip = (s, n) => { s = String(s ?? "").replace(/\s+/g, " ").trim(); return s.length > n ? `${s.slice(0, n - 1)}…` : s; };
15
+ const membersFlag = (v) => (v ? String(v).split(",").map((s) => s.trim()).filter(Boolean) : undefined);
16
+
17
+ // ── openarch quote "<words>" ─────────────────────────────────────────────────
18
+
19
+ export async function cmdQuote(ctx, quote) {
20
+ const { hub, flags, JSON_OUT, num } = ctx;
21
+ if (!quote || quote.trim().length < 12) return ui.fail("Which quotation?", 'openarch quote "the exact words, a sentence or so" [-m indra,petra] [-n 5]');
22
+ const sp = ui.spinner(`looking for the quotation ${flags.member ? `in ${flags.member}` : "across the network"}`);
23
+ const r = await hub("/find-quote", { method: "POST", body: { quote, members: membersFlag(flags.member), limit: num(flags.limit, 5) } }).finally(() => sp.stop());
24
+ process.exitCode = r.best ? 0 : 1;
25
+ if (JSON_OUT) return ui.json(r);
26
+ ui.blank();
27
+ ui.out(` ${ui.dim("“")}${clip(quote, 110)}${ui.dim("”")}`);
28
+ ui.out(` ${ui.dim(`searched for: ${(r.probes ?? [r.words.join(" ")]).join(" · ")}`)}`);
29
+ ui.blank();
30
+ if (r.found.length) {
31
+ for (const f of r.found) {
32
+ ui.out(` ${STATUS_GLYPH[f.status]} ${paint(f.status, ui.pad(f.status, 10))} ${ui.arch(f.id)} ${ui.dim(`${f.date ?? ""}`)} ${clip(f.title, 70)}${f.status === "uncertain" ? ui.dim(` · ${f.confidence}`) : ""}`);
33
+ if (f.matched_span) ui.out(` ${ui.dim(f.status === "anchored" ? "matched:" : "the document reads:")} ${clip(f.matched_span, 110)}`);
34
+ if (f.permalink) ui.out(` ${ui.dim(f.permalink)}`);
35
+ }
36
+ } else ui.out(` ${ui.glyph.fail} ${ui.red("not found")} ${ui.dim("— no candidate document holds these words")}`);
37
+ ui.blank();
38
+ const down = r.members.filter((g) => g.error);
39
+ for (const g of down) ui.out(` ${ui.glyph.warn} ${ui.bold(g.member)} ${ui.dim(`${g.error}${g.message ? ` · ${clip(g.message, 80)}` : ""} — not searched`)}`);
40
+ if (r.best?.status === "uncertain") ui.out(ui.dim(" uncertain = the words are there with differences, usually the document's OCR; read the passage before quoting it."));
41
+ ui.out(ui.dim(` ${ui.fmtInt(r.checked)} candidate${r.checked === 1 ? "" : "s"} checked in ${r.members.length - down.length} member${r.members.length - down.length === 1 ? "" : "s"}${r.best ? ` · cite it: openarch cite -- ${ui.shq(r.best.id)}` : ""}`));
42
+ ui.blank();
43
+ }
44
+
45
+ // ── openarch verify --from draft.md ─────────────────────────────────────────
46
+
47
+ export async function cmdVerifyDraft(ctx, path) {
48
+ const { hub, flags, JSON_OUT } = ctx;
49
+ let src;
50
+ try { src = path === "-" ? readFileSync(0, "utf8") : readFileSync(path, "utf8"); }
51
+ catch (e) { return ui.fail(`Cannot read ${path}: ${e.code ?? e.message}`, "openarch verify --from draft.md (or - for stdin)"); }
52
+ const sp = ui.spinner(`reading ${path === "-" ? "stdin" : path}`);
53
+ try {
54
+ const { members } = await hub("/members", { auth: false });
55
+ const { items, ignored } = extractQuotes(src, members.map((m) => m.member));
56
+ const cited = items.filter((x) => x.id), uncited = items.filter((x) => !x.id);
57
+ const verdicts = [];
58
+ for (let i = 0; i < cited.length; i += 100) {
59
+ sp.update(`checking quotations ${i + 1}–${Math.min(i + 100, cited.length)} of ${cited.length}`);
60
+ const r = await hub("/verify-quotes", { method: "POST", body: { items: cited.slice(i, i + 100).map((x) => ({ id: x.id, quote: x.quote })) } });
61
+ verdicts.push(...r.items);
62
+ }
63
+ const rows = cited.map((x, i) => ({ ...x, status: verdicts[i].status, confidence: verdicts[i].confidence ?? null, reason: verdicts[i].reason ?? null, matched_span: verdicts[i].matched_span ?? null, method: verdicts[i].method ?? null }));
64
+ for (const [n, x] of uncited.entries()) {
65
+ const row = { ...x, status: "uncited" };
66
+ if (flags.find) {
67
+ sp.update(`locating uncited quotation ${n + 1} of ${uncited.length}`);
68
+ try { const f = await hub("/find-quote", { method: "POST", body: { quote: x.quote, limit: 3 } }); row.found = f.best ? { id: f.best.id, status: f.best.status, permalink: f.best.permalink } : f.found[0] ? { id: f.found[0].id, status: f.found[0].status } : null; }
69
+ catch (e) { row.found = { error: e.message }; }
70
+ }
71
+ rows.push(row);
72
+ }
73
+ rows.sort((a, b) => a.line - b.line || a.col - b.col);
74
+ sp.stop();
75
+ const count = (s) => rows.filter((r) => r.status === s).length;
76
+ const summary = { quotations: rows.length, anchored: count("anchored"), uncertain: count("uncertain"), fabricated: count("fabricated"), unverifiable: count("unverifiable"), uncited: count("uncited"), ignored };
77
+ const bad = summary.fabricated + (flags.strict ? summary.uncertain + summary.unverifiable + summary.uncited : 0);
78
+ process.exitCode = bad ? 1 : 0;
79
+ if (JSON_OUT) return ui.json({ file: path, summary, items: rows });
80
+ ui.blank();
81
+ ui.out(` ${ui.bold(path === "-" ? "stdin" : relative(process.cwd(), resolve(path)).startsWith("..") ? path : relative(process.cwd(), resolve(path)))} ${ui.dim(`· ${summary.quotations} quotation${summary.quotations === 1 ? "" : "s"} · ${cited.length} cited · ${uncited.length} uncited${ignored ? ` · ${ignored} short quote${ignored === 1 ? "" : "s"} left alone` : ""}`)}`);
82
+ ui.blank();
83
+ if (!rows.length) ui.out(ui.dim(" No quotations found. Quotations are text in double quotes or a > block quote, cited with a member/id."));
84
+ for (const r of rows) {
85
+ const where = ui.dim(ui.pad(`${r.line}:${r.col}`, 7));
86
+ const note = r.status === "unverifiable" ? ui.dim(r.reason ?? "") : r.status === "uncertain" ? ui.dim(String(r.confidence ?? "")) : r.found ? (r.found.id ? `${ui.dim("found in")} ${ui.arch(r.found.id)} ${paint(r.found.status, r.found.status)}` : ui.dim(r.found.error ? `find failed: ${r.found.error}` : "not found anywhere")) : "";
87
+ ui.out(` ${STATUS_GLYPH[r.status]} ${paint(r.status, ui.pad(r.status, 13))}${where}${r.id ? ui.arch(ui.pad(r.id, 26)) : ui.pad("", 26)} ${ui.dim("“")}${clip(r.quote, 60)}${ui.dim("”")} ${note}`);
88
+ if (r.status === "uncertain" && r.matched_span) ui.out(` ${ui.pad("", 22)}${ui.dim("the document reads:")} ${clip(r.matched_span, 90)}`);
89
+ }
90
+ ui.blank();
91
+ const bits = [ui.green(`${summary.anchored} anchored`), summary.uncertain ? ui.amber(`${summary.uncertain} uncertain`) : null, summary.fabricated ? ui.red(`${summary.fabricated} fabricated`) : null, summary.unverifiable ? ui.amber(`${summary.unverifiable} unverifiable`) : null, summary.uncited ? ui.dim(`${summary.uncited} uncited`) : null].filter(Boolean);
92
+ ui.out(ui.rule(46));
93
+ ui.out(` ${bits.join(ui.dim(" · "))}`);
94
+ if (summary.fabricated) ui.out(` ${ui.dim("A fabricated quotation is not in the document it cites. Fix the words, or the id: openarch quote \"…\" finds where they are.")}`);
95
+ else if (summary.uncited && !flags.find) ui.out(` ${ui.dim("--find looks for the uncited ones across the network.")}`);
96
+ ui.blank();
97
+ } finally { sp.stop(); }
98
+ }
99
+
100
+ // ── openarch pull "<query>" -o corpus/ ───────────────────────────────────────
101
+
102
+ export async function cmdPull(ctx, query) {
103
+ const { hub, HUB, flags, JSON_OUT, num, version } = ctx;
104
+ if (!query || !flags.out) return ui.fail("Pull what, where?", 'openarch pull "<query>" -o corpus/ [-m indra,petra] [-c collection] [-n 50] [--meta]');
105
+ const dir = resolve(flags.out);
106
+ const max = num(flags.limit, 50);
107
+ const docsFile = join(dir, "documents.jsonl"), bibFile = join(dir, "citations.bib"), manFile = join(dir, "manifest.json");
108
+ // A folder someone else supplied can hold links at these names (git and tar keep them), and
109
+ // pull appends a member's text to two of them: never through a link, never to a file that is
110
+ // not the user's own (ind-sec run-3 P2, cmdPull:work-dir-writes-follow-planted-symlinks).
111
+ // manifest.json.tmp is the name earlier versions wrote through; a link there is refused too.
112
+ const KEEP = "A corpus folder holds pull's own files: remove it, or pull into a new folder, then run this again.";
113
+ let dirWhy = null;
114
+ try { const st = lstatSync(dir); dirWhy = st.isSymbolicLink() ? `${dir} is a symbolic link` : st.isDirectory() ? null : `${dir} is not a folder`; }
115
+ catch (e) { if (e.code !== "ENOENT") throw e; }
116
+ if (dirWhy) return ui.fail(`${dirWhy}, so nothing was written.`, "pull writes into a real folder: give its own path, or a new folder.");
117
+ mkdirSync(dir, { recursive: true });
118
+ const unsafe = [docsFile, bibFile, manFile, `${manFile}.tmp`].map(refusal).find(Boolean);
119
+ if (unsafe) return ui.fail(`${unsafe}, so nothing was written.`, KEEP);
120
+ let prior = null;
121
+ if (existsSync(manFile)) {
122
+ try { prior = JSON.parse(readFileSync(manFile, "utf8")); } catch { return ui.fail(`${manFile} is not readable JSON.`, "Use a new folder, or remove it."); }
123
+ if (prior.query !== query || prior.hub !== HUB) return ui.fail(`${dir} holds a pull of ${JSON.stringify(prior.query)} from ${prior.hub}.`, "A folder is one corpus: pull into a new folder.");
124
+ }
125
+ const have = new Map();
126
+ if (existsSync(docsFile)) for (const line of readFileSync(docsFile, "utf8").split("\n")) { if (!line.trim()) continue; try { const d = JSON.parse(line); have.set(d.id, { id: d.id, sha256: d.sha256, bytes: d.bytes, tokens: d.tokens ?? null }); } catch { /* a torn last line from an interrupted run is skipped and refetched */ } }
127
+
128
+ const sp = ui.spinner(`searching for “${query}”`);
129
+ const started = Date.now();
130
+ let stopped = null, fetched = 0, bytes = 0, noText = 0;
131
+ const writeManifest = () => {
132
+ const index = [...have.values()];
133
+ const m = {
134
+ openarch_pull: 1, cli: version, hub: HUB, query, members: membersFlag(flags.member) ?? "all", collection: flags.collection ?? null, text: !flags.meta,
135
+ created_at: prior?.created_at ?? new Date(started).toISOString(), updated_at: new Date().toISOString(),
136
+ documents: index.length, bytes: index.reduce((n, d) => n + (d.bytes || 0), 0), stopped,
137
+ files: Object.fromEntries(["documents.jsonl", "citations.bib"].filter((f) => existsSync(join(dir, f))).map((f) => [f, sha256(readFileSync(join(dir, f)))])),
138
+ index, note: "Each document is reused under the terms it names (field `terms`); cite it with its permalink. Re-run the same command to resume or extend.",
139
+ };
140
+ writeReplacing(manFile, JSON.stringify(m, null, 2) + "\n", 0o666); // a random new name, then a rename: a link is replaced, never followed
141
+ return m;
142
+ };
143
+ const onSig = () => { stopped = "interrupted"; sp.stop(); writeManifest(); process.stderr.write(`\n stopped; ${have.size} documents kept in ${dir}. Run the same command to resume.\n`); process.exit(130); };
144
+ process.once("SIGINT", onSig);
145
+
146
+ try {
147
+ // 1. ids, from every member, page by page, until there are enough
148
+ const per = new Map();
149
+ const { members } = await hub("/search", { query: { q: query, members: flags.member, collection: flags.collection, limit: Math.min(max, 100) } });
150
+ const pending = [];
151
+ for (const g of members) { if (g.error) continue; per.set(g.member, (g.results ?? []).map((r) => r.id)); if (g.cursor) pending.push({ member: g.member, cursor: g.cursor }); }
152
+ const total = () => [...per.values()].reduce((n, a) => n + a.length, 0);
153
+ while (pending.length && total() < max + have.size) {
154
+ const p = pending.shift();
155
+ sp.update(`listing ${p.member} · ${total()} ids`);
156
+ const r = await hub("/search", { query: { q: query, members: p.member, collection: flags.collection, limit: 100, cursor: p.cursor } });
157
+ const g = r.members?.[0];
158
+ if (!g || g.error) continue;
159
+ per.get(p.member).push(...(g.results ?? []).map((x) => x.id));
160
+ if (g.cursor) pending.push({ member: p.member, cursor: g.cursor });
161
+ }
162
+ // round-robin across members, so one large archive does not take the whole budget
163
+ const queue = [], lists = [...per.values()].map((a) => a.filter((id) => !have.has(id)));
164
+ for (let i = 0; queue.length < max - Math.min(have.size, max) && lists.some((l) => i < l.length); i++) for (const l of lists) if (i < l.length && queue.length < max - Math.min(have.size, max)) queue.push(l[i]);
165
+ const unreachable = members.filter((g) => g.error).map((g) => `${g.member} (${g.error})`);
166
+
167
+ // 2. documents, a few at a time; each line is written as soon as it arrives
168
+ let next = 0;
169
+ // a link planted while the pull runs is refused by appendOwn, and every worker stops
170
+ const append = (file, text) => { try { appendOwn(file, text); } catch (e) { if (e instanceof UnsafePath) { stopped = "refused"; e.hint = KEEP; } throw e; } };
171
+ const worker = async () => {
172
+ while (next < queue.length && !stopped) {
173
+ const id = queue[next++];
174
+ const [member, ...rest] = id.split("/");
175
+ const local = rest.join("/");
176
+ sp.update(`${have.size + 1} · ${id}`);
177
+ let d;
178
+ try { d = await hub(`/documents/${encodeURIComponent(member)}/${encodeURIComponent(local)}`, { query: { text: flags.meta ? "false" : undefined } }); }
179
+ catch (e) { if (e.status === 429) { stopped = "quota"; return; } continue; }
180
+ const text = typeof d.text === "string" ? d.text : "";
181
+ const row = { id: d.id ?? id, member, title: d.title ?? null, date: d.date ?? null, authors: d.authors ?? [], type: d.type ?? null, collection: d.collection ?? null, permalink: d.permalink ?? null, source_url: d.source_url ?? null, terms: d.terms ?? null, tokens: d.tokens ?? null, pages: d.pages ?? null, text_kind: d.text_kind ?? null, text_source: d.text_source ?? null, sha256: text ? sha256(text) : null, bytes: Buffer.byteLength(text), fetched_at: new Date().toISOString(), ...(flags.meta ? {} : { text }) };
182
+ append(docsFile, JSON.stringify(row) + "\n");
183
+ have.set(row.id, { id: row.id, sha256: row.sha256, bytes: row.bytes, tokens: row.tokens });
184
+ fetched++; bytes += row.bytes; if (!flags.meta && !text) noText++;
185
+ let c = null;
186
+ try { c = await hub(`/documents/${encodeURIComponent(member)}/${encodeURIComponent(local)}/citation`, { query: { style: "bibtex" } }); } catch { /* a citation is a convenience; the document stands without it */ }
187
+ if (typeof c?.citation === "string" && c.citation) append(bibFile, c.citation.trim() + "\n\n"); // outside that catch: a refused write is not swallowed
188
+ }
189
+ };
190
+ await Promise.all(Array.from({ length: 3 }, worker));
191
+ sp.stop();
192
+ const m = writeManifest();
193
+ if (JSON_OUT) return ui.json({ ...m, index: undefined, fetched, no_text: noText, unreachable });
194
+ ui.blank();
195
+ ui.out(` ${ui.glyph.pass} ${ui.bold(dir)}`);
196
+ ui.out(ui.kv([
197
+ ["query", query], ["fetched now", `${ui.fmtInt(fetched)} document${fetched === 1 ? "" : "s"} · ${ui.fmtBytes(bytes)}${noText ? ui.dim(` · ${noText} without text (the member holds none for them)`) : ""}`],
198
+ ["in the corpus", `${ui.fmtInt(m.documents)} documents · ${ui.fmtBytes(m.bytes)}`],
199
+ ["files", "documents.jsonl · citations.bib · manifest.json (sha256 of each)"],
200
+ ...(unreachable.length ? [["not reached", unreachable.join(", ")]] : []),
201
+ ]));
202
+ if (stopped === "quota") ui.out(`\n ${ui.glyph.warn} ${ui.amber("Stopped at today's quota.")} ${ui.dim("Run the same command tomorrow to continue; nothing is fetched twice.")}`);
203
+ else if (queue.length === 0 && !fetched) ui.out(`\n ${ui.dim(have.size ? "Nothing new: every match is already in the corpus." : "Nothing matched.")}`);
204
+ ui.out(ui.dim(`\n next: openarch verify --from <your draft> · jq -r .title ${join(flags.out, "documents.jsonl")}`));
205
+ ui.blank();
206
+ } catch (e) { sp.stop(); if (have.size) writeManifest(); throw e; }
207
+ finally { process.removeListener("SIGINT", onSig); }
208
+ }
209
+
210
+ // ── openarch may <id|member> [use] ───────────────────────────────────────────
211
+
212
+ const VERDICT_LABEL = { yes: "yes", conditions: "yes, if", ask: "ask first", no: "no" };
213
+ const verdictPaint = (v, s = VERDICT_LABEL[v]) => (v === "yes" || v === "conditions" ? ui.green(s) : v === "ask" ? ui.amber(s) : ui.red(s));
214
+
215
+ export async function cmdMay(ctx, target, use) {
216
+ const { hub, flags, JSON_OUT } = ctx;
217
+ if (!target && !flags.collection) return ui.fail("May I use what?", "openarch may <member/id> [use] · openarch may <member> [-c member/collection] [use]\n uses: read quote quote-at-length reproduce-image teach text-mine train-model redistribute commercial");
218
+ const isId = Boolean(target) && target.includes("/");
219
+ const sp = ui.spinner(`reading the declarations for ${target ?? flags.collection}`);
220
+ const r = await hub("/may", { query: { id: isId ? target : undefined, member: !isId ? target : undefined, collection: flags.collection, use } }).finally(() => sp.stop());
221
+ if (use) process.exitCode = r.verdict === "yes" || r.verdict === "conditions" ? 0 : 1;
222
+ if (JSON_OUT) return ui.json(r);
223
+ ui.blank();
224
+ const what = r.id ?? r.collection ?? r.member;
225
+ const src = r.source_terms ? `${r.source_terms.label ?? r.source_terms.key} · ${r.source_terms.reuse ?? "?"}${r.source_terms.verified === false ? ui.amber(" · unverified") : ""}` : null;
226
+ ui.out(` ${ui.bold(what)}${src ? ` ${ui.dim(src)}` : ""}`);
227
+ if (r.rights) ui.out(` ${ui.dim(`member: ${r.rights.basis} · grants ${r.rights.grant} · credit ${r.rights.attribution} · automated ${r.rights.automated_access}`)}`);
228
+ ui.blank();
229
+ if (use) {
230
+ ui.out(` ${ui.bold(r.label)} ${verdictPaint(r.verdict, ui.bold(VERDICT_LABEL[r.verdict]))}`);
231
+ for (const c of r.conditions) ui.out(` ${ui.dim("·")} ${c}`);
232
+ ui.blank();
233
+ ui.out(ui.label(" because"));
234
+ for (const x of r.reasons) ui.out(` ${ui.pad(x.layer, 10)} ${verdictPaint(x.verdict, ui.pad(VERDICT_LABEL[x.verdict], 9))} ${ui.dim(x.says)}`);
235
+ if (r.note) { ui.blank(); ui.out(` ${ui.dim(r.note)}`); }
236
+ } else {
237
+ ui.out(ui.table([
238
+ { key: "label", title: "use" },
239
+ { key: "verdict", title: "may i?", format: (v) => verdictPaint(v) },
240
+ { key: "conditions", title: "conditions, or why not", format: (v, row) => ui.dim((row.verdict === "ask" || row.verdict === "no" ? row.reasons.filter((x) => x.verdict === row.verdict).map((x) => x.says)[0] ?? "" : (v ?? []).join("; ")).slice(0, 96)) },
241
+ ], r.uses));
242
+ }
243
+ ui.blank();
244
+ for (const c of r.caveats ?? []) ui.out(` ${ui.glyph.warn} ${ui.dim(c)}`);
245
+ ui.out(` ${ui.dim(r.disclaimer)}`);
246
+ if (!use) ui.out(ui.dim(` one use, with its reasons: openarch may ${target ?? ""}${flags.collection ? ` -c ${flags.collection}` : ""} quote-at-length`));
247
+ ui.blank();
248
+ }
@@ -0,0 +1,69 @@
1
+ // safeFile.js — the CLI's writes into a folder someone else may have supplied.
2
+ //
3
+ // A cloned repository, an unpacked archive or a shared drive can hold symbolic links at the
4
+ // names the CLI writes (git and tar keep links). writeFileSync and appendFileSync follow such
5
+ // a link and write wherever it points: a shell start-up file, ~/.ssh/authorized_keys. Run-2
6
+ // #7 closed that for mcp install; ind-sec run-3 P2 (cli/research.js:cmdPull:work-dir-writes-
7
+ // follow-planted-symlinks) found pull's corpus files, member init's answers file and member
8
+ // apply's application file still written through links. They are all written through here:
9
+ //
10
+ // refusal(path) why the CLI must not write at path, or null when it may:
11
+ // nothing there, or a regular file of the user's with one name
12
+ // appendOwn(path, text) append, never through a link (O_NOFOLLOW), and only to such
13
+ // a file, judged again on the open file (no race with a swap)
14
+ // writeReplacing(path, text) a new file beside it (O_EXCL, a random name), then a rename
15
+ // over path, which replaces a link instead of following it
16
+ import { lstatSync, fstatSync, openSync, writeSync, closeSync, renameSync, unlinkSync, constants } from "node:fs";
17
+ import { randomBytes } from "node:crypto";
18
+
19
+ /** A write the CLI refused; its message names the file and says nothing was written to it. */
20
+ export class UnsafePath extends Error {
21
+ constructor(why) { super(`${why}, so nothing was written to it`); this.name = "UnsafePath"; this.code = "OPENARCH_UNSAFE_PATH"; }
22
+ }
23
+
24
+ /** Why a file with these stats is not one the CLI may write to, or null. */
25
+ function judge(st) {
26
+ if (st.isSymbolicLink()) return "is a symbolic link";
27
+ if (!st.isFile()) return "is not a regular file";
28
+ const uid = typeof process.getuid === "function" ? process.getuid() : null;
29
+ if (uid !== null && st.uid !== uid) return "is not yours";
30
+ // a second name is a hard link: an append through it lands in the other file too
31
+ if (st.nlink > 1) return "has another name (a hard link)";
32
+ return null;
33
+ }
34
+
35
+ /** "<path> is a symbolic link" (or another reason), or null when the CLI may write there. */
36
+ export function refusal(path) {
37
+ let st;
38
+ try { st = lstatSync(path); } catch (e) { return e.code === "ENOENT" ? null : `${path} cannot be checked (${e.code ?? e.message})`; }
39
+ const why = judge(st);
40
+ return why ? `${path} ${why}` : null;
41
+ }
42
+
43
+ // O_NOFOLLOW refuses a link at the last name; O_NONBLOCK makes a planted FIFO fail to open
44
+ // rather than hang the command (regular files ignore it). Neither exists on Windows.
45
+ const APPEND = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
46
+
47
+ /** Append text to path, creating it (mode before umask) if absent; throws UnsafePath instead of writing through a link. */
48
+ export function appendOwn(path, text, mode = 0o666) {
49
+ let fd;
50
+ try { fd = openSync(path, APPEND, mode); }
51
+ catch (e) {
52
+ if (e.code === "ELOOP" || e.code === "EMLINK") throw new UnsafePath(`${path} is a symbolic link`);
53
+ if (e.code === "ENXIO") throw new UnsafePath(`${path} is not a regular file`);
54
+ throw e;
55
+ }
56
+ try {
57
+ const why = judge(fstatSync(fd));
58
+ if (why) throw new UnsafePath(`${path} ${why}`);
59
+ writeSync(fd, text);
60
+ } finally { closeSync(fd); }
61
+ }
62
+
63
+ /** Write text to dest through a new file beside it and a rename: a link at dest is replaced, never followed. */
64
+ export function writeReplacing(dest, text, mode = 0o600) {
65
+ const tmp = `${dest}.openarch-tmp-${process.pid}-${randomBytes(4).toString("hex")}`;
66
+ const fd = openSync(tmp, "wx", mode);
67
+ try { writeSync(fd, text); } finally { closeSync(fd); }
68
+ try { renameSync(tmp, dest); } catch (e) { try { unlinkSync(tmp); } catch { /* gone */ } throw e; }
69
+ }