@extantape/onephylogeny-cli 0.0.0-stage → 0.1.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,75 @@
1
+ Required Notice: Copyright 2026 EXTANT APE (https://github.com/ExtantApe)
2
+
3
+ # PolyForm Noncommercial License 1.0.0
4
+
5
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
6
+
7
+ ## Acceptance
8
+
9
+ In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
10
+
11
+ ## Copyright License
12
+
13
+ The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
14
+
15
+ ## Distribution License
16
+
17
+ The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
18
+
19
+ ## Notices
20
+
21
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
22
+
23
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
24
+
25
+ ## Changes and New Works License
26
+
27
+ The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
28
+
29
+ ## Patent License
30
+
31
+ The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
32
+
33
+ ## Noncommercial Purposes
34
+
35
+ Any noncommercial purpose is a permitted purpose.
36
+
37
+ ## Personal Uses
38
+
39
+ Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose.
40
+
41
+ ## Noncommercial Organizations
42
+
43
+ Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding.
44
+
45
+ ## Fair Use
46
+
47
+ You may have "fair use" rights for the software under the law. These terms do not limit them.
48
+
49
+ ## No Other Rights
50
+
51
+ These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
52
+
53
+ ## Patent Defense
54
+
55
+ If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
56
+
57
+ ## Violations
58
+
59
+ The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
60
+
61
+ ## No Liability
62
+
63
+ ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
64
+
65
+ ## Definitions
66
+
67
+ The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
68
+
69
+ **You** refers to the individual or entity agreeing to these terms.
70
+
71
+ **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
72
+
73
+ **Your licenses** are all the licenses granted to you for the software under these terms.
74
+
75
+ **Use** means anything you do with the software requiring one of your licenses.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @extantape/onephylogeny-cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ OnePhylogeny command line: run profiles, build panels, test samples and suggest outgroups.
4
+
5
+ See the [repository](https://github.com/ExtantApe/OnePhylogeny) for documentation.
package/dist/index.js ADDED
@@ -0,0 +1,714 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { execFile } from "child_process";
5
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readdirSync as readdirSync2, readFileSync as readFileSync2 } from "fs";
6
+ import { join as join2, resolve } from "path";
7
+ import { assessRead, auditGroups, checkPrimers, chimeraCandidates, compareWithGroups, comparisonMarkdown, parseVcf, readAbif, curationFromCsv, panelMethods, curationToCsv, parseCuration, parseFasta, parseProfile, reportMarkdown, sampleReport } from "@extantape/onephylogeny-core";
8
+ import { lookupPaper, NcbiClient, paced, publicListings, suggestOutgroups } from "@extantape/onephylogeny-acquire";
9
+ import { buildPanelFromRun, runHypothesis, testHypothesis, testHypothesisOnPanel, comparePanelVersions, panelVersionComparison, buildTree, EngineError, fetchAndAnchor, isCancelled, loadPanel, loadRunRecords, profilePaths, readCurationHistory, saveCuration, routeSample, runSample, testSample, traceArtifact, verifyDataset, writeDataset } from "@extantape/onephylogeny-engine";
10
+
11
+ // src/hypothesis.ts
12
+ import { HYPOTHESIS_VERDICTS } from "@extantape/onephylogeny-core";
13
+ var CLAIM_KINDS = ["sample-in-group", "groups-distinct", "panel-changed-call", "possibly-novel"];
14
+ var UsageError = class extends Error {
15
+ constructor(message) {
16
+ super(message);
17
+ this.name = "UsageError";
18
+ }
19
+ };
20
+ var need = (value, name, kind) => {
21
+ if (!value || value.startsWith("--")) throw new UsageError(`--claim ${kind} needs --${name}`);
22
+ return value;
23
+ };
24
+ function claimFromFlags(flag2, panelId) {
25
+ const kind = flag2("claim");
26
+ if (!kind || kind.startsWith("--")) throw new UsageError(`--claim is required: one of ${CLAIM_KINDS.join(", ")}`);
27
+ if (!CLAIM_KINDS.includes(kind)) throw new UsageError(`Unknown claim ${kind}. The claims are: ${CLAIM_KINDS.join(", ")}`);
28
+ const version = flag2("version");
29
+ const versionOf = (v) => {
30
+ if (!panelId) throw new UsageError("Naming a panel version needs a profile with panel settings");
31
+ return { id: panelId, version: v };
32
+ };
33
+ const panel = version ? { panel: versionOf(need(version, "version", kind)) } : {};
34
+ switch (kind) {
35
+ case "sample-in-group":
36
+ return { kind: "sample-in-group", sample: need(flag2("sample"), "sample", kind), group: need(flag2("group"), "group", kind), ...panel };
37
+ case "groups-distinct": {
38
+ const groups = need(flag2("groups"), "groups", kind).split(",").map((g) => g.trim()).filter(Boolean);
39
+ if (groups.length !== 2) throw new UsageError("--groups takes two groups, separated by a comma: --groups a,b");
40
+ return { kind: "groups-distinct", a: groups[0], b: groups[1], window: need(flag2("window"), "window", kind), ...panel };
41
+ }
42
+ case "panel-changed-call": {
43
+ const sample = flag2("record") ?? flag2("sample");
44
+ const group = flag2("group");
45
+ return { kind: "panel-changed-call", sample: need(sample, "record", kind), from: versionOf(need(flag2("a"), "a", kind)), to: versionOf(need(flag2("b"), "b", kind)), ...group ? { group } : {} };
46
+ }
47
+ case "possibly-novel":
48
+ return { kind: "possibly-novel", sample: need(flag2("sample"), "sample", kind), ...panel };
49
+ }
50
+ }
51
+ var short = (hash) => hash.replace(/^(sha256:)?([0-9a-f]{12})[0-9a-f]{52}$/, (_, p = "", h) => `${p}${h}\u2026`);
52
+ var where = (c) => [`${c.artifact.type} ${short(c.artifact.key)}`, ...c.path ? [c.path] : [], ...c.run ? [`run ${c.run}`] : []].join(", ");
53
+ var bullet = (lines) => lines.map((l) => ` - ${l}`);
54
+ var ORDER = [...HYPOTHESIS_VERDICTS];
55
+ function planText(plan) {
56
+ const s = plan.stated;
57
+ const lines = [`Claim: ${s.claimText}.`, ""];
58
+ if (!s.testable) {
59
+ lines.push(`Stated test: none. This can't be tested with the saved data: ${s.reason}.`);
60
+ if (s.uses.length) lines.push("", "It looked at:", ...bullet(s.uses.map((u) => `${u.rests} (${where(u)})`)));
61
+ } else {
62
+ lines.push("Stated test, before it runs:", ` Method: ${s.method.function}${s.method.calibrated === false ? " (uncalibrated)" : ""}.`, ` Rule: ${s.method.rule}.`, " Reads:", ...s.uses.map((u) => ` - ${u.rests} (${where(u)})`), " What each verdict will mean:");
63
+ for (const v of ORDER) if (s.outcomes?.[v]) lines.push(` - ${v}: ${s.outcomes[v]}.`);
64
+ lines.push(" Not refuted never means confirmed.");
65
+ }
66
+ if (plan.notes.length) lines.push("", "Notes from loading:", ...bullet(plan.notes));
67
+ return `${lines.join("\n")}
68
+ `;
69
+ }
70
+ function verdictText(outcome) {
71
+ const lines = [`Verdict: ${outcome.verdict}.`, ` ${outcome.explanation}`];
72
+ if (outcome.calibrated === false) lines.push(" The rule behind this verdict is uncalibrated.");
73
+ if (outcome.citations.length) lines.push("", "It rests on:", ...bullet(outcome.citations.map((c) => `${c.rests} (${where(c)})`)));
74
+ if (outcome.diagnostics?.length) lines.push("", "Problems found:", ...bullet(outcome.diagnostics.map((d) => d.message)));
75
+ if (outcome.caveats.length) lines.push("", "Caveats:", ...bullet(outcome.caveats));
76
+ if (outcome.notes.length) lines.push("", "Notes from loading:", ...bullet(outcome.notes));
77
+ return `${lines.join("\n")}
78
+ `;
79
+ }
80
+
81
+ // src/sanger.ts
82
+ import { alignToReference, joinReads } from "@extantape/onephylogeny-core";
83
+ var usable = (r) => r.assessment.status === "usable";
84
+ var why = (r) => `${r.file} ${r.assessment.status === "failed" ? "failed" : "is too short"}`;
85
+ function span(a) {
86
+ const start = a.aligned.search(/[^-]/);
87
+ let end = a.aligned.length - 1;
88
+ while (end > start && a.aligned[end] === "-") end--;
89
+ return { start, end };
90
+ }
91
+ function joinPair(forward, reverse, reference) {
92
+ const good = [forward, reverse].filter(usable);
93
+ if (!good.length) return { status: "refused", reason: `Neither read can be used: ${why(forward)} and ${why(reverse)}. A failed or too-short read is never used.` };
94
+ if (good.length === 1) {
95
+ const [kept, dropped] = usable(forward) ? [forward, reverse] : [reverse, forward];
96
+ return { status: "single", sequence: kept.assessment.sequence, used: [kept.file], notes: [`${why(dropped)}, so only ${kept.file} is used, alone and not joined.`] };
97
+ }
98
+ const seen = /* @__PURE__ */ new Map();
99
+ let next = "forward";
100
+ const join3 = joinReads(forward.assessment.sequence, reverse.assessment.sequence, reference, (seq, ref) => {
101
+ const a = alignToReference(seq, ref);
102
+ seen.set(next, a);
103
+ next = "reverse";
104
+ return a;
105
+ });
106
+ if (join3.status === "refused") return { status: "refused", reason: `Neither ${forward.file} nor ${reverse.file} aligns to the panel's reference. They may be from another gene or species.` };
107
+ if (join3.status === "single") {
108
+ const [kept, dropped] = seen.get("forward") ? [forward, reverse] : [reverse, forward];
109
+ return { status: "single", sequence: kept.assessment.sequence, used: [kept.file], notes: [`Only ${kept.file} aligns to the panel's reference, so ${dropped.file} is left out and ${kept.file} is used alone.`] };
110
+ }
111
+ const alignments = [...seen.values()];
112
+ const spans = alignments.map(span);
113
+ const lo = Math.min(...spans.map((s) => s.start));
114
+ const hi = Math.max(...spans.map((s) => s.end));
115
+ let sequence = "";
116
+ let deleted = 0;
117
+ let filled = 0;
118
+ for (let i = lo; i <= hi; i++) {
119
+ const c = join3.aligned[i];
120
+ if (c !== "-") sequence += c;
121
+ else if (spans.some((s) => i >= s.start && i <= s.end)) deleted++;
122
+ else {
123
+ sequence += "N";
124
+ filled++;
125
+ }
126
+ }
127
+ const notes2 = [...join3.notes];
128
+ if (filled) notes2.push(`The reads don't meet: ${filled} reference column${filled === 1 ? "" : "s"} between them ${filled === 1 ? "is" : "are"} written as N, so both keep their places.`);
129
+ if (deleted) notes2.push(`${deleted} reference column${deleted === 1 ? "" : "s"} where the reads have a gap (a deletion) ${deleted === 1 ? "is" : "are"} left out of the FASTA.`);
130
+ const inserted = alignments.reduce((n2, a) => n2 + a.insertions.reduce((m, x) => m + x.length, 0), 0);
131
+ if (inserted) notes2.push(`${inserted} base${inserted === 1 ? "" : "s"} with no column in the reference (insertions) ${inserted === 1 ? "is" : "are"} left out of the joined read. Use a read alone to keep them.`);
132
+ return {
133
+ status: "joined",
134
+ sequence,
135
+ span: { start: lo + 1, end: hi + 1 },
136
+ conflicts: join3.conflicts.map((c) => c + 1),
137
+ columns: join3.columns,
138
+ used: [forward.file, reverse.file],
139
+ notes: notes2
140
+ };
141
+ }
142
+
143
+ // src/snps.ts
144
+ function parseGroups(text) {
145
+ const body = text.replace(/^\uFEFF/, "").trim();
146
+ if (body.startsWith("{") || body.startsWith("[")) {
147
+ let data;
148
+ try {
149
+ data = JSON.parse(body);
150
+ } catch (e) {
151
+ throw new Error(`The groups file isn't valid JSON: ${e.message}`);
152
+ }
153
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error("The groups JSON must be one object mapping sample IDs to group IDs");
154
+ const out2 = {};
155
+ for (const [sample, group] of Object.entries(data)) {
156
+ if (typeof group !== "string" || !group.trim()) throw new Error(`Sample "${sample}" needs a group ID as text`);
157
+ out2[sample] = group.trim();
158
+ }
159
+ return out2;
160
+ }
161
+ const lines = body.split(/\r?\n/);
162
+ const cells = (line) => line.split(",").map((c) => c.trim().replace(/^"(.*)"$/, "$1").trim());
163
+ const head = cells(lines[0] ?? "").map((c) => c.toLowerCase());
164
+ const si = head.indexOf("sample");
165
+ const gi = head.indexOf("group");
166
+ if (si < 0 || gi < 0) throw new Error('The groups CSV needs a header row with a "sample" and a "group" column');
167
+ const out = {};
168
+ lines.slice(1).forEach((line, i) => {
169
+ if (!line.trim()) return;
170
+ const c = cells(line);
171
+ const sample = c[si];
172
+ const group = c[gi];
173
+ if (!sample || !group) throw new Error(`Line ${i + 2}: needs both a sample and a group`);
174
+ if (sample in out && out[sample] !== group) throw new Error(`Line ${i + 2}: ${sample} is already in group ${out[sample]}`);
175
+ out[sample] = group;
176
+ });
177
+ return out;
178
+ }
179
+ var fmt = (x) => x === null ? "none" : x.toFixed(3);
180
+ function snpsTable(vcf, result, minSharedSites) {
181
+ const lines = [];
182
+ lines.push(`VCF: ${vcf.samples.length} samples, ${vcf.sites.length} sites used.`);
183
+ for (const s of vcf.skipped) lines.push(`Skipped ${s.count} site${s.count === 1 ? "" : "s"}: ${s.reason}.`);
184
+ lines.push(`Compared ${result.compared} samples that have both SNPs and a group. Two samples count as neighbours only if they share at least ${minSharedSites} called sites.`);
185
+ lines.push(`Nearest SNP neighbours all in the same group: ${result.nearestSameGroup} of ${result.compared}. Tied between its own group and another: ${result.nearestTied}. No neighbour with enough shared sites: ${result.noNeighbour}.`);
186
+ lines.push("");
187
+ const rows = [
188
+ ["Group", "Samples", "Nearest in same group", "Tied", "Mean within", "Mean between"],
189
+ ...result.perGroup.map((g) => [g.group, String(g.samples), `${g.nearestSameGroup} of ${g.samples}`, String(g.nearestTied), fmt(g.meanWithin), fmt(g.meanBetween)])
190
+ ];
191
+ const widths = rows[0].map((_, i) => Math.max(...rows.map((r) => r[i].length)));
192
+ for (const r of rows) lines.push(r.map((c, i) => c.padEnd(widths[i])).join(" ").trimEnd());
193
+ lines.push("");
194
+ lines.push(`Grouped but not in the VCF: ${result.notInVcf.length ? result.notInVcf.join(", ") : "none"}`);
195
+ lines.push(`In the VCF but not grouped: ${result.notGrouped.length ? result.notGrouped.join(", ") : "none"}`);
196
+ lines.push("");
197
+ lines.push('Distances are the share of differing alleles over the sites both samples have called: 0 is identical, 1 is opposite homozygotes. "none" means no pair shared enough sites to measure.');
198
+ lines.push("These are descriptions, not probabilities. A sample whose nearest neighbour is in another group is not an error: maternal lines and nuclear relatedness can differ for real reasons.");
199
+ return `${lines.join("\n")}
200
+ `;
201
+ }
202
+
203
+ // src/sources.ts
204
+ import { LISTING_KINDS } from "@extantape/onephylogeny-acquire";
205
+ function chosenKinds(has2) {
206
+ const picked = LISTING_KINDS.filter((k) => has2(k));
207
+ return picked.length ? picked : [...LISTING_KINDS];
208
+ }
209
+ var ROWS = 20;
210
+ var n = (v) => v.toLocaleString("en-US");
211
+ var plural = (v, one, many = `${one}s`) => `${n(v)} ${v === 1 ? one : many}`;
212
+ function table(head, rows, numeric = []) {
213
+ const width = head.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length)));
214
+ const line = (cells) => cells.map((c, i) => numeric.includes(i) ? c.padStart(width[i]) : c.padEnd(width[i])).join(" ").trimEnd();
215
+ return [line(head), width.map((w) => "-".repeat(w)).join(" "), ...rows.map(line)].join("\n");
216
+ }
217
+ function counts(label, items) {
218
+ if (!items.length) return `${label}: none listed.`;
219
+ const shown = items.slice(0, ROWS);
220
+ const rest = items.slice(ROWS);
221
+ const more = rest.length ? `
222
+ \u2026and ${plural(rest.length, "more row")}, with ${plural(rest.reduce((s, c) => s + c.count, 0), "record")} between them (--json lists every one).` : "";
223
+ return `${table([label, "Records"], shown.map((c) => [c.name, n(c.count)]), [1])}${more}`;
224
+ }
225
+ var provenance = (p) => `Query: ${p.query}
226
+ Retrieved: ${p.retrieved} (${plural(p.requests.length, "request")})`;
227
+ var notes = (list) => list.length ? `
228
+
229
+ ${list.map((x) => `Note: ${x}`).join("\n")}` : "";
230
+ function failedHere(listing, service) {
231
+ const f = listing.failed.find((x) => x.service === service);
232
+ return f ? `Failed, so this count is unknown, not zero: ${f.message}` : null;
233
+ }
234
+ function section(title, body) {
235
+ return `## ${title}
236
+
237
+ ${body.trim()}
238
+ `;
239
+ }
240
+ function sra(l) {
241
+ const failed = failedHere(l, "NCBI SRA");
242
+ if (failed || !l.sra) return section("NCBI SRA runs", failed ?? "Not asked.");
243
+ const s = l.sra;
244
+ const cut = s.experiments.listed < s.experiments.total ? ` Only the first ${n(s.experiments.listed)} were read.` : "";
245
+ const head = `${plural(s.experiments.total, "experiment")} in SRA, ${plural(s.runs.length, "run")} listed.${cut} A listing only: no reads were downloaded.`;
246
+ if (!s.runs.length) return section("NCBI SRA runs", `${head}
247
+
248
+ ${provenance(s)}`);
249
+ const rows = s.runs.slice(0, ROWS).map((r) => [r.run, r.libraryStrategy ?? "", r.layout ?? "", r.platform ?? "", r.bases !== void 0 ? n(r.bases) : "not given", r.bioProject ?? "", r.bioSample ?? "", r.published ?? ""]);
250
+ const more = s.runs.length > ROWS ? `
251
+ \u2026and ${plural(s.runs.length - ROWS, "run")} more (--json lists every one).` : "";
252
+ return section("NCBI SRA runs", `${head}
253
+
254
+ ${table(["Run", "Strategy", "Layout", "Platform", "Bases", "BioProject", "BioSample", "Published"], rows, [4])}${more}
255
+
256
+ ${provenance(s)}`);
257
+ }
258
+ function genomes(l) {
259
+ const failed = failedHere(l, "NCBI Datasets");
260
+ if (failed || !l.genomes) return section("NCBI Datasets genomes", failed ?? "Not asked.");
261
+ const g = l.genomes;
262
+ const cut = g.genomes.length < g.total ? ` Only ${n(g.genomes.length)} were read.` : "";
263
+ const head = `${plural(g.total, "assembly", "assemblies")}.${cut} A listing only: nothing was downloaded.`;
264
+ if (!g.genomes.length) return section("NCBI Datasets genomes", `${head}
265
+
266
+ ${provenance(g)}`);
267
+ const rows = g.genomes.slice(0, ROWS).map((x) => [x.accession, x.database === "refseq" ? "RefSeq" : x.database === "genbank" ? "GenBank" : "unknown", x.assemblyLevel ?? "", x.length !== void 0 ? n(x.length) : "", x.released ?? "", x.mitogenome, x.pairedAccession ?? ""]);
268
+ const more = g.genomes.length > ROWS ? `
269
+ \u2026and ${plural(g.genomes.length - ROWS, "assembly", "assemblies")} more (--json lists every one).` : "";
270
+ const mito = g.genomes.some((x) => x.mitogenome === "not listed") ? `
271
+ Note: "not listed" doesn't mean the assembly has no mitogenome: check the paired accession too.` : "";
272
+ return section("NCBI Datasets genomes", `${head}
273
+
274
+ ${table(["Accession", "Database", "Level", "Length (bases)", "Released", "Mitogenome", "Paired with"], rows, [3])}${more}${mito ? `
275
+ ${mito}` : ""}
276
+
277
+ ${provenance(g)}`);
278
+ }
279
+ function coverage(l, service, c) {
280
+ const title = `${service} occurrence counts`;
281
+ const failed = failedHere(l, service);
282
+ if (failed || !c) return section(title, failed ?? "Not asked.");
283
+ const matched = `Matched: ${c.matched.name}${c.matched.rank ? `, ${c.matched.rank.toLowerCase()}` : ""}${c.matched.key ? ` (key ${c.matched.key})` : ""}${c.matched.matchType ? `, ${c.matched.matchType.toLowerCase()} match` : ""}.`;
284
+ const total = `${plural(c.total, "record")}${c.datasets !== void 0 ? ` from ${plural(c.datasets, "dataset")}` : ""}${c.noCountry ? `; ${n(c.noCountry)} with no country` : ""}. Counts only: no record and no coordinate was fetched.`;
285
+ const licences = c.licences === null ? "Licences: not indexed per record by this service." : counts("Licence", c.licences);
286
+ return section(title, `${matched}
287
+ ${total}
288
+
289
+ ${counts("Country", c.byCountry)}
290
+
291
+ ${counts("Basis of record", c.byBasisOfRecord)}
292
+
293
+ ${licences}${notes(c.notes)}
294
+
295
+ ${provenance(c)}`);
296
+ }
297
+ function bold(l) {
298
+ const failed = failedHere(l, "BOLD");
299
+ if (failed || !l.bold) return section("BOLD record counts", failed ?? "Not asked.");
300
+ const b = l.bold;
301
+ return section("BOLD record counts", `Matched: ${b.matched}. Counts only: no record and no coordinate was fetched.
302
+
303
+ ${counts("Country or ocean", b.byCountry)}
304
+
305
+ ${counts("Marker", b.byMarker)}${notes(b.notes)}
306
+
307
+ ${provenance(b)}`);
308
+ }
309
+ function sourcesText(l) {
310
+ const named = l.name && l.nameFrom === "ncbi-taxonomy" ? `GBIF, iDigBio and BOLD were asked about ${l.name}, NCBI Taxonomy's name for taxon ${l.taxon}.
311
+ ` : "";
312
+ const out = [
313
+ `# Public data for ${l.taxon}
314
+
315
+ Listings and counts of what public services hold. They aren't evidence about any sample, and no coordinates are fetched or shown. GBIF and iDigBio overlap (iDigBio publishes to GBIF), so don't add their counts together.
316
+ ${named}`
317
+ ];
318
+ if (l.asked.includes("sra")) out.push(sra(l));
319
+ if (l.asked.includes("genomes")) out.push(genomes(l));
320
+ if (l.asked.includes("occurrences")) out.push(coverage(l, "GBIF", l.gbif), coverage(l, "iDigBio", l.idigbio));
321
+ if (l.asked.includes("bold")) out.push(bold(l));
322
+ out.push(l.failed.length ? `## Failed
323
+
324
+ ${plural(l.failed.length, "service")} didn't answer, so ${l.failed.length === 1 ? "its counts are" : "their counts are"} unknown, not zero:
325
+ ${l.failed.map((f) => `- ${f.service}: ${f.message}`).join("\n")}
326
+ ` : "Every service asked answered.\n");
327
+ return out.join("\n");
328
+ }
329
+
330
+ // src/store.ts
331
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs";
332
+ import { dirname, join } from "path";
333
+ var nodeStore = (root) => ({
334
+ read: async (p) => readFileSync(join(root, p), "utf8"),
335
+ write: async (p, text) => {
336
+ const file = join(root, p);
337
+ mkdirSync(dirname(file), { recursive: true });
338
+ const temp = `${file}.${process.pid}.tmp`;
339
+ try {
340
+ writeFileSync(temp, text);
341
+ renameSync(temp, file);
342
+ } catch (error) {
343
+ try {
344
+ rmSync(temp, { force: true });
345
+ } catch {
346
+ }
347
+ throw error;
348
+ }
349
+ },
350
+ append: async (p, text) => {
351
+ const file = join(root, p);
352
+ mkdirSync(dirname(file), { recursive: true });
353
+ appendFileSync(file, text);
354
+ },
355
+ exists: async (p) => existsSync(join(root, p)),
356
+ folders: async (p) => {
357
+ const dir = join(root, p);
358
+ if (!existsSync(dir)) return [];
359
+ return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
360
+ }
361
+ });
362
+
363
+ // src/index.ts
364
+ var USAGE = `onephylogeny <command> --workspace DIR --profile ID [options]
365
+
366
+ doctor Check native tools
367
+ outgroups Suggest outgroups outward from the ingroup
368
+ fetch Download, anchor and gate records; write the sheet and log
369
+ panel Build and validate a panel from the latest run
370
+ test --fasta FILE Test local sequences against the panel
371
+ tree [--start N --end N] Build a tree from one window with IQ-TREE
372
+ curation export Print the curation sheet (CSV) for the latest run's records
373
+ curation import --file F [--apply --reason TEXT] [--by NAME]
374
+ Check a filled-in sheet and show what would change; --apply saves it, with the reason in the history
375
+ curation history [--record ID]
376
+ Every saved change, when, by whom and why
377
+ trace --type T --key K Show everything that produced an artifact
378
+ hypothesis --claim KIND [claim options] [--version V] [--plan-only] [--json]
379
+ Put a claim to the saved panels and results, read only. It prints the stated test first,
380
+ then one verdict (refuted, not refuted, untestable with this data, tool or data problem) with
381
+ what it rests on and its caveats. --plan-only stops after the stated test. Any verdict exits 0.
382
+ Claims: sample-in-group --sample S --group G | groups-distinct --groups G,H --window W |
383
+ panel-changed-call --a V --b V --record R [--group G] | possibly-novel --sample S.
384
+ With --dir PANEL instead of a profile, only that panel folder is read (no saved results)
385
+ compare --a V --b V [--markdown]
386
+ Compare two built panel versions: records, groups, settings, claims, as JSON. --markdown
387
+ prints it for reading, with each version's validation outcomes by window side by side
388
+ verify --dir DIR Check a built panel folder: file hashes, seal, and its examples rerun (no profile needed)
389
+ dataset --dir DIR Add examples and a manifest to a panel built before they existed (no profile needed)
390
+ lookup --title T [--authors A]
391
+ Propose DOI and PubMed links for a study from Crossref and Europe PMC (nothing is attached)
392
+ methods --dir DIR Methods text and citations for a built panel, from what it records
393
+ audit --dir DIR Check a built panel's groups against its sequences, window by window (flags only)
394
+ chimeras --dir DIR Records whose windows point to different groups: possible chimeras (flags only)
395
+ route --fasta FILE --panels DIR
396
+ Which panels under DIR apply to each sequence (no profile needed)
397
+ report --dir DIR --result FILE [--json]
398
+ A self-contained report for one saved result, as Markdown (no profile needed)
399
+ sanger --ab1 FILE [--min-quality N] [--min-length N] [--json]
400
+ Read a Sanger chromatogram: trim by quality, mask low bases as N, flag strong second peaks,
401
+ and print the kept read as FASTA (no profile needed)
402
+ sanger --ab1 FORWARD --reverse REVERSE --dir DIR [--json]
403
+ Join a forward and a reverse read on the panel's reference: good bases that disagree become N
404
+ and are listed (reference columns, counting from 1). One unusable read: the other is used alone
405
+ snps --vcf FILE --groups FILE [--min-shared N] [--json]
406
+ Compare SNP genotypes with groups: per group, how many samples' nearest SNP neighbour shares
407
+ their group, and mean distances within and between. GROUPS is CSV (sample,group) or a JSON
408
+ object. Default --min-shared 100. Descriptions, never probabilities (no profile needed)
409
+ sources --taxon NAME_OR_TAXID [--sra] [--genomes] [--occurrences] [--bold] [--json]
410
+ What public services list for a taxon: SRA runs, NCBI Datasets genomes, GBIF and iDigBio
411
+ occurrence counts, BOLD counts (default: all). Listings and counts only, never coordinates
412
+ or downloads. Needs the network. A service that fails is named, and the exit code is 1
413
+ (no profile needed)
414
+ primers --dir DIR --forward SEQ --reverse SEQ [--reference FASTA --offset N] [--max-mismatches N]
415
+ Which of a panel's windows a primer pair can cover. Give a longer reference and the marker's
416
+ offset in it when the primers sit outside the marker (no profile needed)
417
+
418
+ Options: --events (print JSON Lines events). Set NCBI_API_KEY to fetch faster.`;
419
+ var args = process.argv.slice(2);
420
+ var command = args[0];
421
+ var flag = (name) => {
422
+ const i = args.indexOf(`--${name}`);
423
+ return i >= 0 ? args[i + 1] : void 0;
424
+ };
425
+ var has = (name) => args.includes(`--${name}`);
426
+ var exec = (tool, a, cwd) => new Promise((res) => {
427
+ execFile(tool, a, { maxBuffer: 1 << 28, ...cwd ? { cwd } : {} }, (err, stdout, stderr) => {
428
+ const code = err ? typeof err.code === "number" ? err.code : 127 : 0;
429
+ res({ code, stdout: String(stdout), stderr: String(stderr || (err && !stderr ? err.message : "")) });
430
+ });
431
+ });
432
+ var tools = {
433
+ version: async (tool) => {
434
+ const r = await exec(tool, ["--version"]);
435
+ return r.code === 127 ? null : (r.stdout || r.stderr).split("\n").find((l) => l.trim())?.trim() ?? "unknown";
436
+ },
437
+ run: (tool, a, { cwd }) => {
438
+ mkdirSync2(cwd, { recursive: true });
439
+ return exec(tool, a, cwd);
440
+ }
441
+ };
442
+ async function main() {
443
+ if (!command || command === "help" || has("help")) return console.log(USAGE);
444
+ if (command === "doctor") {
445
+ console.log(JSON.stringify({ iqtree3: await tools.version("iqtree3"), note: "Fetching, anchoring, panels and sample tests need no native tools." }, null, 2));
446
+ return;
447
+ }
448
+ if (command === "lookup") {
449
+ const title = flag("title");
450
+ if (!title) throw new Error("--title is required");
451
+ const authors = flag("authors");
452
+ console.log(JSON.stringify(await lookupPaper(paced((url, init) => fetch(url, init)), { title, ...authors ? { authors } : {} }), null, 2));
453
+ return;
454
+ }
455
+ if (command === "sources") {
456
+ const taxon = flag("taxon");
457
+ if (!taxon || taxon.startsWith("--")) throw new Error("--taxon is required: an NCBI Taxonomy ID or a scientific name");
458
+ const http = (url, init) => fetch(url, init);
459
+ const client = new NcbiClient({ fetch: http, tool: "onephylogeny", ...process.env.NCBI_API_KEY ? { apiKey: process.env.NCBI_API_KEY } : {} });
460
+ const listing = await publicListings({ fetch: http, client }, taxon, { only: chosenKinds(has) });
461
+ process.stdout.write(has("json") ? `${JSON.stringify(listing, null, 2)}
462
+ ` : sourcesText(listing));
463
+ if (listing.failed.length) process.exitCode = 1;
464
+ return;
465
+ }
466
+ if (command === "methods") {
467
+ const dir = flag("dir");
468
+ if (!dir) throw new Error("--dir is required");
469
+ const m = panelMethods((await loadPanel(nodeStore(resolve(dir)), ".")).panel);
470
+ process.stdout.write(`${m.text}
471
+ ## Sources
472
+
473
+ ${m.citations.map((c) => `- ${c}`).join("\n")}
474
+ `);
475
+ return;
476
+ }
477
+ if (command === "chimeras") {
478
+ const dir = flag("dir");
479
+ if (!dir) throw new Error("--dir is required");
480
+ console.log(JSON.stringify(chimeraCandidates(await loadPanel(nodeStore(resolve(dir)), ".")), null, 2));
481
+ return;
482
+ }
483
+ if (command === "audit") {
484
+ const dir = flag("dir");
485
+ if (!dir) throw new Error("--dir is required");
486
+ console.log(JSON.stringify(auditGroups(await loadPanel(nodeStore(resolve(dir)), ".")), null, 2));
487
+ return;
488
+ }
489
+ if (command === "route") {
490
+ const file = flag("fasta");
491
+ const root2 = flag("panels");
492
+ if (!file || !root2) throw new Error("--fasta and --panels are required");
493
+ const found = [];
494
+ const walk = (dir, depth) => {
495
+ if (existsSync2(join2(dir, "panel.json"))) found.push(dir);
496
+ if (depth < 3) {
497
+ for (const e of readdirSync2(dir, { withFileTypes: true })) if (e.isDirectory()) walk(join2(dir, e.name), depth + 1);
498
+ }
499
+ };
500
+ walk(resolve(root2), 0);
501
+ const bundles = [];
502
+ const skipped = [];
503
+ for (const d of found) {
504
+ try {
505
+ bundles.push(await loadPanel(nodeStore(d), "."));
506
+ } catch (e) {
507
+ skipped.push({ folder: d, reason: e.message });
508
+ }
509
+ }
510
+ if (skipped.length) console.error(JSON.stringify({ skipped }, null, 2));
511
+ for (const e of parseFasta(readFileSync2(file, "utf8"))) console.log(JSON.stringify({ sample: e.id, suggestions: routeSample(e.sequence, bundles) }, null, 2));
512
+ return;
513
+ }
514
+ if (command === "sanger") {
515
+ const file = flag("ab1");
516
+ if (!file) throw new Error("--ab1 is required");
517
+ const reverseFile = flag("reverse");
518
+ const dir = flag("dir");
519
+ if (has("reverse") && (!reverseFile || reverseFile.startsWith("--"))) throw new Error("--reverse needs a file: the reverse read (.ab1)");
520
+ if (reverseFile && !dir) throw new Error("Joining two reads needs the panel's reference: add --dir with a built panel folder");
521
+ const num = (name) => flag(name) !== void 0 ? Number(flag(name)) : void 0;
522
+ const settings = { ...num("min-quality") !== void 0 ? { minQuality: num("min-quality") } : {}, ...num("min-length") !== void 0 ? { minLength: num("min-length") } : {} };
523
+ if (reverseFile) {
524
+ const reference = (await loadPanel(nodeStore(resolve(dir)), ".")).referenceSequence;
525
+ if (!reference) throw new Error("This panel carries no reference sequence, so the reads can't be joined. Build the panel again.");
526
+ const reads = [file, reverseFile].map((f) => {
527
+ const read2 = readAbif(new Uint8Array(readFileSync2(f)));
528
+ return { file: f, sampleName: read2.sampleName, instrument: read2.instrument, assessment: assessRead(read2, settings) };
529
+ });
530
+ const pair = joinPair(reads[0], reads[1], reference);
531
+ if (has("json")) {
532
+ console.log(JSON.stringify({ forward: { file, sampleName: reads[0].sampleName, instrument: reads[0].instrument, ...reads[0].assessment }, reverse: { file: reverseFile, sampleName: reads[1].sampleName, instrument: reads[1].instrument, ...reads[1].assessment }, ...pair }, null, 2));
533
+ if (pair.status === "refused") process.exitCode = 1;
534
+ return;
535
+ }
536
+ for (const [label, r] of [["Forward", reads[0]], ["Reverse", reads[1]]]) for (const n2 of r.assessment.notes) console.error(`${label} (${r.file}): ${n2}`);
537
+ if (pair.status === "refused") throw new Error(pair.reason);
538
+ for (const n2 of pair.notes) console.error(n2);
539
+ const fasta = (s) => s.match(/.{1,70}/g).join("\n");
540
+ if (pair.status === "single") {
541
+ const used = reads.find((r) => r.file === pair.used[0]);
542
+ process.stdout.write(`>${used.sampleName ?? used.file} status=${used.assessment.status} kept=${used.assessment.kept.start + 1}-${used.assessment.kept.end} alone
543
+ ${fasta(pair.sequence)}
544
+ `);
545
+ return;
546
+ }
547
+ console.error(`Reference columns ${pair.span.start} to ${pair.span.end}: ${pair.columns.both} with a good base from both reads, ${pair.columns.forwardOnly} from the forward only, ${pair.columns.reverseOnly} from the reverse only.`);
548
+ console.error(`Conflicts: ${pair.conflicts.length}${pair.conflicts.length ? ` (reference column${pair.conflicts.length === 1 ? "" : "s"} ${pair.conflicts.join(", ")}, counting from 1)` : ""}.`);
549
+ process.stdout.write(`>${reads[0].sampleName ?? file} joined columns=${pair.span.start}-${pair.span.end} conflicts=${pair.conflicts.length}
550
+ ${fasta(pair.sequence)}
551
+ `);
552
+ return;
553
+ }
554
+ const read = readAbif(new Uint8Array(readFileSync2(file)));
555
+ const a = assessRead(read, settings);
556
+ if (has("json")) return console.log(JSON.stringify({ sampleName: read.sampleName, instrument: read.instrument, ...a }, null, 2));
557
+ for (const n2 of a.notes) console.error(n2);
558
+ if (a.status === "failed") throw new Error(`${file}: the read failed, so there is no sequence to use`);
559
+ if (a.status === "short") console.error(`Not usable: too short. The kept bases are printed anyway, for inspection.`);
560
+ process.stdout.write(`>${read.sampleName ?? file} status=${a.status} kept=${a.kept.start + 1}-${a.kept.end}
561
+ ${a.sequence.match(/.{1,70}/g).join("\n")}
562
+ `);
563
+ return;
564
+ }
565
+ if (command === "snps") {
566
+ const vcfFile = flag("vcf");
567
+ const groupsFile = flag("groups");
568
+ if (!vcfFile || !groupsFile) throw new Error("--vcf and --groups are required");
569
+ const given = flag("min-shared");
570
+ const minShared = given === void 0 ? 100 : Number(given);
571
+ if (!Number.isInteger(minShared) || minShared < 1) throw new Error("--min-shared must be a whole number of sites, 1 or more");
572
+ const vcf = parseVcf(readFileSync2(vcfFile, "utf8"));
573
+ const groups = parseGroups(readFileSync2(groupsFile, "utf8"));
574
+ const result = compareWithGroups(vcf, groups, minShared);
575
+ if (has("json")) return console.log(JSON.stringify({ samples: vcf.samples.length, sites: vcf.sites.length, skipped: vcf.skipped, minSharedSites: minShared, ...result }, null, 2));
576
+ process.stdout.write(snpsTable(vcf, result, minShared));
577
+ return;
578
+ }
579
+ if (command === "primers") {
580
+ const dir = flag("dir");
581
+ const forward = flag("forward");
582
+ const reverse = flag("reverse");
583
+ if (!dir || !forward || !reverse) throw new Error("--dir, --forward and --reverse are required");
584
+ const bundle = await loadPanel(nodeStore(resolve(dir)), ".");
585
+ const given = flag("reference");
586
+ const reference = given ? parseFasta(readFileSync2(given, "utf8"))[0]?.sequence : bundle.referenceSequence;
587
+ if (!reference) throw new Error("This panel carries no reference sequence; give one with --reference");
588
+ if (given && flag("offset") === void 0) throw new Error("With --reference, give --offset: where the marker starts in it (0-based)");
589
+ const result = checkPrimers({ forward, reverse, reference, windows: bundle.panel.windows, markerOffset: given ? Number(flag("offset")) : 0, ...flag("max-mismatches") !== void 0 ? { maxMismatches: Number(flag("max-mismatches")) } : {} });
590
+ console.log(JSON.stringify(result, null, 2));
591
+ if (result.status === "refused") process.exitCode = 1;
592
+ return;
593
+ }
594
+ if (command === "report") {
595
+ const dir = flag("dir");
596
+ const file = flag("result");
597
+ if (!dir || !file) throw new Error("--dir and --result are required");
598
+ const { panel } = await loadPanel(nodeStore(resolve(dir)), ".");
599
+ const saved = JSON.parse(readFileSync2(file, "utf8"));
600
+ const result = "findings" in saved ? saved : saved.result;
601
+ if (!result) throw new Error(`This sample was refused, so there is no result to report: ${(saved.diagnostics ?? []).map((d) => d.message).join("; ")}`);
602
+ const report = sampleReport(panel, result);
603
+ process.stdout.write(has("json") ? `${JSON.stringify(report, null, 2)}
604
+ ` : reportMarkdown(report));
605
+ return;
606
+ }
607
+ if (command === "verify" || command === "dataset") {
608
+ const dir = flag("dir");
609
+ if (!dir) throw new Error("--dir is required");
610
+ const store2 = nodeStore(resolve(dir));
611
+ if (command === "dataset") {
612
+ const manifest = await writeDataset(store2, ".", await loadPanel(store2, "."), testSample);
613
+ console.log(JSON.stringify(manifest, null, 2));
614
+ return;
615
+ }
616
+ const r = await verifyDataset(store2, ".", loadPanel, testSample);
617
+ console.log(JSON.stringify({ verified: !r.diagnostics.some((d) => d.severity === "error"), ...r }, null, 2));
618
+ if (r.diagnostics.some((d) => d.severity === "error")) process.exitCode = 1;
619
+ return;
620
+ }
621
+ if (command === "hypothesis" && flag("dir")) {
622
+ const store2 = nodeStore(resolve(flag("dir")));
623
+ const panelId = await store2.exists("panel.json") ? JSON.parse(await store2.read("panel.json")).id : void 0;
624
+ const claim = claimFromFlags(flag, panelId);
625
+ const offline = { store: store2, ncbi: { fetch: () => Promise.reject(new Error("The hypothesis command never uses the network")) } };
626
+ return hypothesis(offline, await testHypothesisOnPanel(offline, ".", claim));
627
+ }
628
+ const root = resolve(flag("workspace") ?? ".");
629
+ const id = flag("profile");
630
+ if (!id) throw new Error("--profile is required");
631
+ const store = nodeStore(root);
632
+ const P = profilePaths(id);
633
+ const profile = parseProfile(await store.read(P.profile));
634
+ const controller = new AbortController();
635
+ process.on("SIGINT", () => controller.abort());
636
+ const ctx = {
637
+ store,
638
+ tools,
639
+ signal: controller.signal,
640
+ ncbi: { fetch: (url, init) => fetch(url, init), tool: "onephylogeny", ...process.env.NCBI_API_KEY ? { apiKey: process.env.NCBI_API_KEY } : {} },
641
+ onEvent: (e) => {
642
+ if (has("events")) console.log(JSON.stringify(e));
643
+ else if (e.level !== "debug") console.error(`[${e.step}] ${e.message}`);
644
+ }
645
+ };
646
+ if (command === "outgroups") {
647
+ const ladder = await suggestOutgroups(new NcbiClient(ctx.ncbi), profile.selection);
648
+ console.log(JSON.stringify(ladder, null, 2));
649
+ } else if (command === "fetch") {
650
+ const { run, outcomes } = await fetchAndAnchor(ctx, profile);
651
+ console.log(JSON.stringify({ run: run.id, status: run.status, records: outcomes.length, passed: outcomes.filter((o) => o.status === "passed").length, folder: join2(root, P.run(run.id)) }, null, 2));
652
+ } else if (command === "panel") {
653
+ const curation = parseCuration(await store.read(P.curation));
654
+ const { bundle, diagnostics, validation, unassigned } = await buildPanelFromRun(ctx, profile, curation);
655
+ console.log(JSON.stringify({ panel: bundle.panel.id, version: bundle.panel.version, checksum: bundle.panel.checksum, groups: bundle.panel.groups.map((g) => ({ id: g.id, records: g.evidence.length, coverage: g.coverage.map((c) => `${c.window}: ${c.records} records, ${c.blocks} sites${c.recordsNeeded ? `, needs ${c.recordsNeeded} more` : ""}`) })), pairs: bundle.panel.pairs.map((p) => `${p.a} / ${p.b} in ${p.window}: ${p.state === "not_evaluable" ? "not evaluable" : `${p.sites.length} sites`}`), claims: validation.claims.map((c) => ({ pair: `${c.a} / ${c.b}`, window: c.window, passed: c.passed, minColumns: c.minColumns, gates: c.gates.filter((g) => g.ran).map((g) => `${g.passed ? "pass" : "FAIL"} ${g.gate}: ${g.detail}`) })), scope: bundle.panel.validatedScope, unassigned, diagnostics, validation }, null, 2));
656
+ } else if (command === "test") {
657
+ const file = flag("fasta");
658
+ if (!file) throw new Error("--fasta is required");
659
+ if (!profile.panel) throw new Error("The profile has no panel settings");
660
+ for (const e of parseFasta(readFileSync2(file, "utf8"))) console.log(JSON.stringify(await runSample(ctx, profile, e.sequence, e.id), (k, v) => k === "aligned" || k === "run" && typeof v === "object" ? void 0 : v, 2));
661
+ } else if (command === "compare") {
662
+ const a = flag("a");
663
+ const b = flag("b");
664
+ if (!a || !b) throw new Error("--a and --b are required");
665
+ if (has("markdown")) process.stdout.write(comparisonMarkdown(await panelVersionComparison(store, profile, a, b)));
666
+ else console.log(JSON.stringify(await comparePanelVersions(store, profile, a, b), null, 2));
667
+ } else if (command === "curation") {
668
+ const records = await loadRunRecords(store, profile.id);
669
+ const curation = await store.exists(P.curation) ? parseCuration(await store.read(P.curation)) : { schemaVersion: 1, records: {} };
670
+ if (args[1] === "export") return void process.stdout.write(curationToCsv(curation, records));
671
+ if (args[1] === "history") return void console.log(JSON.stringify(await readCurationHistory(store, profile.id, flag("record")), null, 2));
672
+ if (args[1] !== "import") throw new Error("Use: curation export | import --file F [--apply --reason TEXT] | history [--record ID]");
673
+ const file = flag("file");
674
+ if (!file) throw new Error("--file is required");
675
+ const r = curationFromCsv(readFileSync2(file, "utf8"), curation, { knownRecords: records.map((x) => x.version || x.accession), groups: profile.panel?.groups.map((g) => g.id) ?? [] });
676
+ const errors = r.diagnostics.filter((d) => d.severity === "error");
677
+ const reason = flag("reason");
678
+ if (has("apply") && !reason) throw new Error("--apply needs --reason, so the history says why these changes were made");
679
+ const by = flag("by");
680
+ const applied = has("apply") && !errors.length && r.changes.length > 0;
681
+ if (applied) await saveCuration(store, profile.id, r.curation, { reason, ...by ? { by } : {} });
682
+ console.log(JSON.stringify({ applied, changed: r.changes.length, changes: r.changes, diagnostics: r.diagnostics }, null, 2));
683
+ if (errors.length) process.exitCode = 1;
684
+ } else if (command === "tree") {
685
+ const start = flag("start");
686
+ const end = flag("end");
687
+ const t = await buildTree(ctx, profile, { absoluteDir: root, ...start && end ? { window: { start: Number(start), end: Number(end) } } : {} });
688
+ console.log(JSON.stringify({ tool: t.tool, version: t.version, tips: t.tips.length, newick: t.newick.trim() }, null, 2));
689
+ } else if (command === "hypothesis") {
690
+ const claim = claimFromFlags(flag, profile.panel?.id);
691
+ await hypothesis(ctx, await testHypothesis(ctx, profile, claim));
692
+ } else if (command === "trace") {
693
+ const type = flag("type");
694
+ const key = flag("key");
695
+ if (!type || !key) throw new Error("--type and --key are required");
696
+ console.log(JSON.stringify(await traceArtifact(store, { type, key }), null, 2));
697
+ } else throw new Error(`Unknown command ${command}
698
+
699
+ ${USAGE}`);
700
+ }
701
+ async function hypothesis(ctx, plan) {
702
+ if (has("plan-only")) return void process.stdout.write(has("json") ? `${JSON.stringify({ plan }, null, 2)}
703
+ ` : planText(plan));
704
+ if (!has("json")) process.stdout.write(`${planText(plan)}
705
+ `);
706
+ const outcome = await runHypothesis(ctx, plan);
707
+ process.stdout.write(has("json") ? `${JSON.stringify({ plan, outcome }, null, 2)}
708
+ ` : verdictText(outcome));
709
+ }
710
+ main().catch((e) => {
711
+ console.error(e instanceof Error ? e.message : e);
712
+ if (e instanceof EngineError && e.action) console.error(`What to do: ${e.action}`);
713
+ process.exit(isCancelled(e) ? 130 : 1);
714
+ });
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@extantape/onephylogeny-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-alpha.8",
4
+ "description": "OnePhylogeny command line: run profiles, build panels, test samples and suggest outgroups.",
5
+ "keywords": [
6
+ "phylogenetics",
7
+ "reference-panel",
8
+ "genbank"
9
+ ],
10
+ "homepage": "https://github.com/ExtantApe/OnePhylogeny#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/ExtantApe/OnePhylogeny/issues"
13
+ },
14
+ "license": "PolyForm-Noncommercial-1.0.0",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/ExtantApe/OnePhylogeny.git",
18
+ "directory": "packages/cli"
19
+ },
20
+ "type": "module",
21
+ "sideEffects": false,
22
+ "exports": {
23
+ ".": "./dist/index.js"
24
+ },
25
+ "main": "./dist/index.js",
26
+ "files": [
27
+ "dist",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "engines": {
32
+ "node": ">=22"
33
+ },
34
+ "dependencies": {
35
+ "@extantape/onephylogeny-engine": "^0.1.0-alpha.8",
36
+ "@extantape/onephylogeny-core": "^0.1.0-alpha.8",
37
+ "@extantape/onephylogeny-acquire": "^0.1.0-alpha.8"
38
+ },
39
+ "bin": {
40
+ "onephylogeny": "./dist/index.js"
41
+ },
42
+ "devDependencies": {
43
+ "@types/node": "^24.19.2"
44
+ },
45
+ "scripts": {
46
+ "build": "tsup src/index.ts --format esm --clean --target es2022",
47
+ "typecheck": "tsc --noEmit",
48
+ "test": "vitest run --passWithNoTests"
49
+ }
6
50
  }