@agentproto/collect-cli 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,957 @@
1
+ import { parseArgs } from 'util';
2
+ import { lstat, realpath, mkdir, rm, open as open$1, readFile } from 'fs/promises';
3
+ import { dirname, resolve, join, basename, sep } from 'path';
4
+ import { fileURLToPath, pathToFileURL } from 'url';
5
+ import { readAll, CollectTask, CollectRunError, StoreLockedError, StoreVersionError, ConnectorDeclaration, listConnectors, createConnectorRegistry, canonicalUrl, itemIdFromUrl, textFingerprint, CollectItem, Observation, Pickup, Actor, seenKey, itemSeenKeys, stableStringify, recordSecrets, createCollector, Recipe, sha256Hex } from '@agentproto/collect';
6
+ import { initStore, StoreNotFoundError, StoreMigrationError, openStore, createHttpTransport, createApiTransport } from '@agentproto/collect/node';
7
+ import { parse as parse$1 } from 'yaml';
8
+ import { Writable, Readable } from 'stream';
9
+ import { pipeline } from 'stream/promises';
10
+ import { readFileSync } from 'fs';
11
+
12
+ /**
13
+ * @agentproto/collect-cli
14
+ * The `collect` binary: a command-line tool for collecting public posts and articles with provenance.
15
+ */
16
+
17
+ // src/io.ts
18
+ var UsageError = class extends Error {
19
+ code = "USAGE";
20
+ constructor(message) {
21
+ super(message);
22
+ this.name = "UsageError";
23
+ }
24
+ };
25
+ function out(io, text) {
26
+ io.stdout.write(text.endsWith("\n") ? text : `${text}
27
+ `);
28
+ }
29
+ function err(io, text) {
30
+ io.stderr.write(text.endsWith("\n") ? text : `${text}
31
+ `);
32
+ }
33
+ function outJson(io, value) {
34
+ out(io, JSON.stringify(value));
35
+ }
36
+ function table(rows) {
37
+ if (rows.length === 0) return "";
38
+ const widths = rows[0].map((_, i) => Math.max(...rows.map((r) => (r[i] ?? "").length)));
39
+ return rows.map((r) => r.map((c, i) => i === r.length - 1 ? c : c.padEnd(widths[i])).join(" ").trimEnd()).join("\n");
40
+ }
41
+ var COMMON_OPTIONS = {
42
+ json: { type: "boolean" },
43
+ help: { type: "boolean", short: "h" },
44
+ quiet: { type: "boolean", short: "q" }
45
+ };
46
+ function parse(argv, spec) {
47
+ try {
48
+ const { values, positionals } = parseArgs({ args: argv, options: { ...COMMON_OPTIONS, ...spec }, allowPositionals: true, strict: true });
49
+ return { values, positionals };
50
+ } catch (e) {
51
+ throw new UsageError(e instanceof Error ? e.message : String(e));
52
+ }
53
+ }
54
+ function positional(p, name, count = 1) {
55
+ if (p.length < count) throw new UsageError(`missing argument <${name}>`);
56
+ if (p.length > count) throw new UsageError(`unexpected argument "${p[count]}"`);
57
+ return p;
58
+ }
59
+ function intOption(name, value) {
60
+ if (value === void 0) return void 0;
61
+ if (!/^\d+$/.test(value) || Number(value) < 1) throw new UsageError(`--${name} must be a positive integer, got "${value}"`);
62
+ return Number(value);
63
+ }
64
+ function looksLikeConnector(v) {
65
+ if (!v || typeof v !== "object") return false;
66
+ const c = v;
67
+ return typeof c.plan === "function" && typeof c.fetch === "function" && typeof c.parse === "function";
68
+ }
69
+ function issuePath(path) {
70
+ return path.map((p, i) => typeof p === "number" ? `[${p}]` : i === 0 ? String(p) : `.${String(p)}`).join("") || "(root)";
71
+ }
72
+ function formatIssues(error) {
73
+ return error.issues.map((i) => ` ${issuePath(i.path)}: ${i.message}`).join("\n");
74
+ }
75
+ function validateRecipe(input, label) {
76
+ const parsed = Recipe.safeParse(input);
77
+ if (!parsed.success) throw new UsageError(`invalid recipe ${label}:
78
+ ${formatIssues(parsed.error)}`);
79
+ return parsed.data;
80
+ }
81
+ async function loadConnectors(paths, cwd) {
82
+ const found = /* @__PURE__ */ new Map();
83
+ const apiAuth = /* @__PURE__ */ new Map();
84
+ const merged = /* @__PURE__ */ new Map();
85
+ const add = (c, where) => {
86
+ const existing = found.get(c.id);
87
+ if (existing && existing !== c) throw new UsageError(`${where}: connector "${c.id}" is defined twice`);
88
+ found.set(c.id, c);
89
+ };
90
+ for (const p of paths) {
91
+ const file = resolve(cwd, p);
92
+ let mod;
93
+ try {
94
+ mod = await import(pathToFileURL(file).href);
95
+ } catch (e) {
96
+ throw new UsageError(`cannot load connector module ${p}: ${e instanceof Error ? e.message : String(e)}`);
97
+ }
98
+ const here = [];
99
+ for (const [name, value] of Object.entries(mod)) {
100
+ if (name === "apiAuth") continue;
101
+ for (const v of Array.isArray(value) ? value : [value]) {
102
+ if (!looksLikeConnector(v)) continue;
103
+ const { id, version, transports, access, capabilities, counters, pace } = v;
104
+ const declared = ConnectorDeclaration.safeParse({ id, version, transports, access, capabilities, counters, pace });
105
+ if (!declared.success) throw new UsageError(`connector module ${p}: export "${name}" is not a valid connector:
106
+ ${formatIssues(declared.error)}`);
107
+ let copy = merged.get(v);
108
+ if (!copy) merged.set(v, copy = Object.freeze({ ...v, ...declared.data }));
109
+ if (!here.includes(copy)) here.push(copy);
110
+ }
111
+ }
112
+ if (here.length === 0) throw new UsageError(`connector module ${p} exports no connector`);
113
+ for (const c of here) {
114
+ add(c, `connector module ${p}`);
115
+ if (mod.apiAuth && typeof mod.apiAuth === "object") apiAuth.set(c.id, mod.apiAuth);
116
+ }
117
+ }
118
+ for (const c of listConnectors()) if (!merged.has(c)) add(c, "registry");
119
+ return { registry: createConnectorRegistry([...found.values()]), apiAuth };
120
+ }
121
+ function envSecrets(env) {
122
+ return { get: async (name) => env[name] || void 0 };
123
+ }
124
+ function secretNameOf(c) {
125
+ return c.access.level === "key" ? c.access.secret : void 0;
126
+ }
127
+ function buildTransports(loaded, secrets, rateMs) {
128
+ const http = createHttpTransport(rateMs === void 0 ? {} : { minIntervalMs: rateMs });
129
+ return {
130
+ http,
131
+ api: (connector) => {
132
+ if (connector.access.level !== "key") return http;
133
+ const secret = connector.access.secret;
134
+ const auth = loaded.apiAuth.get(connector.id) ?? { type: "bearer", secret };
135
+ return createApiTransport({ http, secrets, auth: { ...auth, secret } });
136
+ }
137
+ };
138
+ }
139
+ async function loadRecipe(file, cwd) {
140
+ const abs = resolve(cwd, file);
141
+ let text;
142
+ try {
143
+ text = await readFile(abs, "utf8");
144
+ } catch {
145
+ throw new UsageError(`cannot read recipe ${file}`);
146
+ }
147
+ let doc;
148
+ try {
149
+ doc = parse$1(text);
150
+ } catch (e) {
151
+ throw new UsageError(`invalid YAML in ${file}: ${e instanceof Error ? e.message : String(e)}`);
152
+ }
153
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) throw new UsageError(`${file}: the recipe must be a mapping`);
154
+ const { connectors, ...rest } = doc;
155
+ if (connectors !== void 0 && (!Array.isArray(connectors) || connectors.some((c) => typeof c !== "string"))) {
156
+ throw new UsageError(`${file}: connectors: must be a list of module paths`);
157
+ }
158
+ const recipe = validateRecipe(rest, file);
159
+ return { recipe, connectors: (connectors ?? []).map((c) => resolve(dirname(abs), c)) };
160
+ }
161
+ function storePathOf(io, option) {
162
+ return resolve(io.cwd, option ?? io.env.COLLECT_STORE ?? "collect-store");
163
+ }
164
+
165
+ // src/commands/connectors.ts
166
+ var CONNECTOR_OPTION = { connector: { type: "string", multiple: true } };
167
+ async function runConnectors(argv, io) {
168
+ const { values, positionals } = parse(argv, CONNECTOR_OPTION);
169
+ positional(positionals, "none", 0);
170
+ const { registry } = await loadConnectors(values.connector ?? [], io.cwd);
171
+ const list = registry.list().map((c) => ({
172
+ id: c.id,
173
+ version: c.version,
174
+ transports: [...c.transports],
175
+ access: c.access,
176
+ capabilities: [...c.capabilities]
177
+ }));
178
+ if (values.json) {
179
+ outJson(io, list);
180
+ return 0;
181
+ }
182
+ if (list.length === 0) {
183
+ out(io, "no connectors registered (load one with --connector <module>)");
184
+ return 0;
185
+ }
186
+ const rows = [["id", "version", "transports", "access", "capabilities"]];
187
+ for (const c of list) {
188
+ const access = c.access.level === "key" ? `key (${c.access.secret})` : c.access.level === "session" ? `session (${c.access.site})` : "none";
189
+ rows.push([c.id, c.version, c.transports.join(","), access, c.capabilities.join(",")]);
190
+ }
191
+ out(io, table(rows));
192
+ return 0;
193
+ }
194
+
195
+ // src/commands/doctor.ts
196
+ async function runDoctor(argv, io) {
197
+ const { values, positionals } = parse(argv, { ...CONNECTOR_OPTION, source: { type: "string", multiple: true } });
198
+ if (positionals.length > 1) positional(positionals, "recipe", 1);
199
+ const modules = [...values.connector ?? []];
200
+ let wanted = values.source ?? [];
201
+ if (positionals[0]) {
202
+ const loaded = await loadRecipe(positionals[0], io.cwd);
203
+ modules.push(...loaded.connectors);
204
+ if (wanted.length === 0) wanted = [...new Set(loaded.recipe.sources.map((s) => s.connector))];
205
+ }
206
+ const { registry } = await loadConnectors(modules, io.cwd);
207
+ const ids = wanted.length > 0 ? wanted : registry.list().map((c) => c.id);
208
+ let unusable = 0;
209
+ const reports = ids.map((id) => {
210
+ const c = registry.get(id);
211
+ if (!c) {
212
+ unusable++;
213
+ return { id, registered: false, usable: false, problems: [`connector "${id}" is not registered`] };
214
+ }
215
+ const secret = secretNameOf(c);
216
+ const secretPresent = secret ? Boolean(io.env[secret]) : void 0;
217
+ const transports = {};
218
+ for (const t of c.transports) {
219
+ if (t === "http") transports[t] = { available: true };
220
+ else if (t === "api") transports[t] = secret ? { available: Boolean(secretPresent), note: secretPresent ? void 0 : `${secret} is not set` } : { available: false, note: "the connector declares no secret" };
221
+ else transports[t] = { available: false, note: "not available in this version" };
222
+ }
223
+ const problems = [];
224
+ if (secret && !secretPresent) problems.push(`secret ${secret} is not set`);
225
+ if (c.access.level === "session") problems.push(`needs a logged-in session on ${c.access.site} (browser transport not available in this version)`);
226
+ const usable = problems.length === 0 && Object.values(transports).some((t) => t.available);
227
+ if (!usable && problems.length === 0) problems.push("no usable transport");
228
+ if (!usable) unusable++;
229
+ return { id, registered: true, version: c.version, access: c.access, secret, secretPresent, transports, usable, problems };
230
+ });
231
+ if (values.json) outJson(io, { connectors: reports, ok: unusable === 0 });
232
+ else if (reports.length === 0) out(io, "no connectors to check");
233
+ else {
234
+ const rows = [["connector", "access", "secret", "transports", "usable"]];
235
+ for (const r of reports) {
236
+ if (!r.registered) {
237
+ rows.push([r.id, "-", "-", "-", "no (not registered)"]);
238
+ continue;
239
+ }
240
+ const t = Object.entries(r.transports).map(([n, a]) => `${n}:${a.available ? "yes" : `no${a.note ? ` (${a.note})` : ""}`}`).join(" ");
241
+ const secret = r.secret ? `${r.secret}: ${r.secretPresent ? "set" : "missing"}` : "-";
242
+ rows.push([r.id, r.access.level, secret, t, r.usable ? "yes" : "no"]);
243
+ }
244
+ out(io, table(rows));
245
+ for (const r of reports) for (const p of r.problems) out(io, `${r.id}: ${p}`);
246
+ }
247
+ return unusable > 0 ? 1 : 0;
248
+ }
249
+ function classify(e) {
250
+ const cause = e instanceof CollectRunError ? e.cause : e;
251
+ if (!(e instanceof CollectRunError) && cause instanceof Error && (cause.name === "ZodError" || cause instanceof SyntaxError)) {
252
+ return { code: 3, message: `store data is unreadable: ${cause.message.split("\n")[0]}` };
253
+ }
254
+ if (cause instanceof UsageError) return { code: 2, message: cause.message };
255
+ if (cause instanceof StoreLockedError) {
256
+ const h = cause.holder;
257
+ return { code: 3, message: `store is locked${h ? ` by pid ${h.pid} since ${h.at}` : ""}; wait for the other run to end` };
258
+ }
259
+ if (cause instanceof StoreNotFoundError) return { code: 3, message: `${cause.message}; create it with: collect init <path>` };
260
+ if (cause instanceof StoreVersionError || cause instanceof StoreMigrationError) return { code: 3, message: cause.message };
261
+ if (cause && typeof cause === "object" && "code" in cause && ["EACCES", "EPERM", "ENOENT", "EISDIR", "ENOTDIR"].includes(String(cause.code))) {
262
+ return { code: 3, message: `store unreadable: ${String(cause.message)}` };
263
+ }
264
+ return void 0;
265
+ }
266
+ async function open(path) {
267
+ return openStore(path);
268
+ }
269
+ function progress(io, json, quiet) {
270
+ return (event) => {
271
+ if (quiet) return;
272
+ if (json) return err(io, JSON.stringify(event));
273
+ const d = event.data ? ` ${Object.entries(event.data).map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`).join(" ")}` : "";
274
+ err(io, `[${event.type}]${d}`);
275
+ };
276
+ }
277
+ function reportExit(report, interrupted, unexpectedSkips) {
278
+ if (interrupted || unexpectedSkips > 0) return 1;
279
+ const bad = report.connectors.some((c) => c.status === "failed" || c.status === "skipped" || c.tasks.failed > 0);
280
+ return bad ? 1 : 0;
281
+ }
282
+ async function countUnexpectedSkips(store, runId) {
283
+ const latest = /* @__PURE__ */ new Map();
284
+ for await (const t of store.tasks(runId)) latest.set(`${t.connector}/${t.taskId}`, t);
285
+ let n = 0;
286
+ for (const t of latest.values()) {
287
+ if (t.status === "pending" || t.status === "started") n++;
288
+ else if (t.status === "skipped" && !/cap reached/.test(t.reason ?? "")) n++;
289
+ }
290
+ return n;
291
+ }
292
+ function renderReport(report) {
293
+ const rows = [["connector", "status", "tasks done/failed/skipped", "new", "obs", "dup"]];
294
+ for (const c of report.connectors) {
295
+ rows.push([c.connector, c.status, `${c.tasks.done}/${c.tasks.failed}/${c.tasks.skipped} of ${c.tasks.planned}`, String(c.newItems), String(c.observations), String(c.duplicates)]);
296
+ }
297
+ const lines = [`run ${report.runId}`, table(rows)];
298
+ for (const c of report.connectors) {
299
+ const why = [c.skippedReason, c.reason].filter(Boolean).join("; ");
300
+ if (why) lines.push(`${c.connector}: ${why}`);
301
+ const f = Object.entries(c.failures).map(([k, v]) => `${k}=${v}`).join(" ");
302
+ if (f) lines.push(`${c.connector}: failures ${f}`);
303
+ for (const e of c.escalations) lines.push(`${c.connector}: escalated ${e.from} -> ${e.to} (${e.count})`);
304
+ }
305
+ return lines.join("\n");
306
+ }
307
+ async function execute(io, opts) {
308
+ const store = await open(opts.storePath);
309
+ const secrets = recordSecrets(envSecrets(io.env));
310
+ io.addRedactor?.(secrets.redact);
311
+ const collector = createCollector({
312
+ store,
313
+ transports: buildTransports(opts.loaded, secrets, opts.rateMs),
314
+ secrets,
315
+ connectors: opts.loaded.registry
316
+ });
317
+ const report = await opts.start(collector, progress(io, opts.json, opts.quiet));
318
+ const interrupted = io.signal?.aborted === true;
319
+ if (opts.json) outJson(io, { ...report, interrupted });
320
+ else {
321
+ out(io, renderReport(report));
322
+ if (interrupted) out(io, `interrupted: continue with: collect resume ${report.runId}`);
323
+ }
324
+ return reportExit(report, interrupted, await countUnexpectedSkips(store, report.runId));
325
+ }
326
+
327
+ // src/commands/export.ts
328
+ var CSV_COLUMNS = [
329
+ "id",
330
+ "source",
331
+ "sourceInstance",
332
+ "kind",
333
+ "url",
334
+ "canonicalUrl",
335
+ "contentId",
336
+ "contentGroupId",
337
+ "title",
338
+ "text",
339
+ "textTruncated",
340
+ "language",
341
+ "wordCount",
342
+ "format",
343
+ "authorRef",
344
+ "submitterRef",
345
+ "publishedAt",
346
+ "postedAt",
347
+ "firstSeenAt",
348
+ "hasMedia",
349
+ "query",
350
+ "runId",
351
+ "subjects",
352
+ "tags",
353
+ "links",
354
+ "outboundLinks",
355
+ "parts",
356
+ "rawRefs",
357
+ "ext"
358
+ ];
359
+ function cell(value) {
360
+ if (value === void 0 || value === null) return "";
361
+ const text = typeof value === "object" ? JSON.stringify(value) : String(value);
362
+ return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
363
+ }
364
+ function csvRow(item) {
365
+ const r = item;
366
+ return CSV_COLUMNS.map((c) => cell(r[c])).join(",");
367
+ }
368
+ async function outputPath(io, out2, storePath) {
369
+ const wanted = resolve(io.cwd, out2);
370
+ let dir;
371
+ try {
372
+ dir = await realpath(dirname(wanted));
373
+ } catch {
374
+ throw new UsageError(`--out ${out2}: the directory does not exist`);
375
+ }
376
+ const real = join(dir, basename(wanted));
377
+ const store = await realpath(storePath);
378
+ if (real === store || real.startsWith(store + sep)) throw new UsageError(`--out ${out2} is inside the store directory; choose a path outside it`);
379
+ return real;
380
+ }
381
+ async function runExport(argv, io) {
382
+ const { values, positionals } = parse(argv, {
383
+ store: { type: "string" },
384
+ format: { type: "string" },
385
+ source: { type: "string" },
386
+ out: { type: "string" },
387
+ view: { type: "string" }
388
+ });
389
+ positional(positionals, "none", 0);
390
+ if (values.view !== void 0) {
391
+ if (values.view === "flat") {
392
+ err(io, "collect: --view flat is not available yet");
393
+ return 2;
394
+ }
395
+ throw new UsageError(`unknown view "${values.view}"`);
396
+ }
397
+ if (values.json && !values.out) throw new UsageError("export --json needs --out <file>: without it, items stream to stdout as JSONL");
398
+ const format = values.format ?? "jsonl";
399
+ if (format !== "jsonl" && format !== "csv") throw new UsageError(`--format must be jsonl or csv, got "${format}"`);
400
+ const storePath = storePathOf(io, values.store);
401
+ const store = await open(storePath);
402
+ let file;
403
+ let outPath;
404
+ if (values.out) {
405
+ outPath = await outputPath(io, values.out, storePath);
406
+ try {
407
+ file = await open$1(outPath, "wx");
408
+ } catch (e) {
409
+ if (e.code === "EEXIST") throw new UsageError(`--out ${values.out} already exists; it is never overwritten`);
410
+ throw e;
411
+ }
412
+ }
413
+ let count = 0;
414
+ const items = store.items(values.source);
415
+ async function* lines() {
416
+ if (format === "csv") yield `${CSV_COLUMNS.join(",")}
417
+ `;
418
+ for await (const item of items) {
419
+ count++;
420
+ yield `${format === "csv" ? csvRow(item) : JSON.stringify(item)}
421
+ `;
422
+ }
423
+ }
424
+ const sink = file ? file.createWriteStream() : new Writable({
425
+ write(chunk, _enc, cb) {
426
+ try {
427
+ const ok = io.stdout.write(chunk.toString("utf8"));
428
+ if (ok === false && io.stdout.once) io.stdout.once("drain", () => cb());
429
+ else cb();
430
+ } catch (e) {
431
+ cb(e);
432
+ }
433
+ }
434
+ });
435
+ try {
436
+ await pipeline(Readable.from(lines()), sink);
437
+ } catch (e) {
438
+ if (outPath) await rm(outPath, { force: true });
439
+ throw e;
440
+ }
441
+ const skipped = items.skipped;
442
+ if (skipped > 0) err(io, `warning: ${skipped} unreadable line(s) skipped; the export is incomplete`);
443
+ if (outPath && values.json) outJson(io, { out: outPath, format, items: count, skipped });
444
+ else if (outPath) err(io, `${count} item(s) written to ${values.out}`);
445
+ return skipped > 0 ? 1 : 0;
446
+ }
447
+ async function runInit(argv, io) {
448
+ const { values, positionals } = parse(argv, {});
449
+ const [path] = positional(positionals, "store");
450
+ const root = resolve(io.cwd, path);
451
+ const store = await initStore(root);
452
+ const schemaVersion = await store.schemaVersion();
453
+ if (values.json) outJson(io, { store: root, schemaVersion });
454
+ else out(io, `store ready at ${root} (schema version ${schemaVersion})`);
455
+ return 0;
456
+ }
457
+ var STORE_OPTION = { store: { type: "string" } };
458
+ async function runRuns(argv, io) {
459
+ const { values, positionals } = parse(argv, STORE_OPTION);
460
+ positional(positionals, "none", 0);
461
+ const store = await open(storePathOf(io, values.store));
462
+ const rows = [];
463
+ for (const id of (await store.listRuns()).sort()) {
464
+ const run = await store.getRun(id);
465
+ const report = await store.readReport(id);
466
+ rows.push({
467
+ runId: id,
468
+ name: run?.recipe.name,
469
+ createdAt: run?.createdAt,
470
+ state: report?.finishedAt ? "finished" : "unfinished",
471
+ connectors: (report?.connectors ?? []).map((c) => ({ connector: c.connector, status: c.status }))
472
+ });
473
+ }
474
+ if (values.json) outJson(io, rows);
475
+ else if (rows.length === 0) out(io, "no runs yet");
476
+ else {
477
+ out(io, table([["run", "name", "created", "state"], ...rows.map((r) => [r.runId, r.name ?? "", r.createdAt ?? "", r.state])]));
478
+ }
479
+ return 0;
480
+ }
481
+ async function runStatus(argv, io) {
482
+ const { values, positionals } = parse(argv, STORE_OPTION);
483
+ const [runId] = positional(positionals, "runId");
484
+ const store = await open(storePathOf(io, values.store));
485
+ const run = await store.getRun(runId);
486
+ if (!run) throw new UsageError(`unknown run ${runId}`);
487
+ const report = await store.readReport(runId);
488
+ const latest = /* @__PURE__ */ new Map();
489
+ for (const t of (await readAll(store.tasks(runId))).records) latest.set(`${t.connector}/${t.taskId}`, t);
490
+ const byStatus = {};
491
+ const failures = {};
492
+ for (const t of latest.values()) {
493
+ byStatus[t.status] = (byStatus[t.status] ?? 0) + 1;
494
+ if (t.status === "failed") failures[t.cause ?? "other"] = (failures[t.cause ?? "other"] ?? 0) + 1;
495
+ }
496
+ const state = report?.finishedAt ? "finished" : "unfinished";
497
+ if (values.json) {
498
+ outJson(io, { runId, name: run.recipe.name, createdAt: run.createdAt, state, tasks: byStatus, failures, report: report ?? null });
499
+ return 0;
500
+ }
501
+ out(io, `run ${runId}${run.recipe.name ? ` (${run.recipe.name})` : ""}: ${state}`);
502
+ out(io, `tasks: ${Object.entries(byStatus).map(([k, v]) => `${k}=${v}`).join(" ") || "none"}`);
503
+ if (Object.keys(failures).length) out(io, `failures: ${Object.entries(failures).map(([k, v]) => `${k}=${v}`).join(" ")}`);
504
+ if (report) {
505
+ out(io, table([["connector", "status", "new", "obs", "dup"], ...report.connectors.map((c) => [c.connector, c.status, String(c.newItems), String(c.observations), String(c.duplicates)])]));
506
+ }
507
+ if (state === "unfinished") out(io, `continue with: collect resume ${runId}`);
508
+ return 0;
509
+ }
510
+ async function ingestRaw(target, connector, entry, position, bytes, task, writtenActors, totals) {
511
+ const parsed = await connector.parse({
512
+ connector: connector.id,
513
+ task: CollectTask.parse(task),
514
+ raw: { ref: entry.ref, url: entry.url, ext: entry.ext, bytes, httpStatus: entry.httpStatus, fetchedAt: entry.fetchedAt, transport: entry.transport }
515
+ });
516
+ const keyOf = (kind, i) => sha256Hex(JSON.stringify([entry.runId ?? "", "reparse", position, entry.hash, kind, i]));
517
+ const items = [];
518
+ for (const p of parsed.items ?? []) {
519
+ const canonical = p.canonicalUrl ?? (p.url ? canonicalUrl(p.url) : void 0);
520
+ const id = p.id ?? (canonical ? await itemIdFromUrl(p.source, canonical) : void 0);
521
+ if (!id) throw new Error("an item needs an id or a url");
522
+ const contentId = p.contentId ?? (p.text ? await textFingerprint(p.text) : void 0);
523
+ const item = CollectItem.parse({
524
+ ...p,
525
+ id,
526
+ canonicalUrl: canonical,
527
+ contentId,
528
+ firstSeenAt: p.firstSeenAt ?? entry.fetchedAt,
529
+ runId: entry.runId,
530
+ rawRefs: [.../* @__PURE__ */ new Set([...p.rawRefs ?? [], entry.ref])]
531
+ });
532
+ if (connector.ext && item.ext !== void 0) connector.ext.parse(item.ext);
533
+ items.push(item);
534
+ }
535
+ const observations = [];
536
+ for (const [i, o] of (parsed.observations ?? []).entries()) {
537
+ observations.push(
538
+ Observation.parse({ measuredAt: entry.fetchedAt, transport: entry.transport, rawRef: entry.ref, ...o, runId: entry.runId, taskId: "reparse", recordKey: await keyOf("observation", i) })
539
+ );
540
+ }
541
+ const pickups = [];
542
+ for (const [i, p] of (parsed.pickups ?? []).entries()) {
543
+ pickups.push(
544
+ Pickup.parse({
545
+ firstSeenAt: entry.fetchedAt,
546
+ measuredAt: entry.fetchedAt,
547
+ ...p,
548
+ runId: entry.runId,
549
+ taskId: "reparse",
550
+ recordKey: await keyOf("pickup", i),
551
+ evidence: { rawRef: entry.ref, ...p.evidence }
552
+ })
553
+ );
554
+ }
555
+ const actors = (parsed.actors ?? []).map((a) => Actor.parse(a));
556
+ const idMap = /* @__PURE__ */ new Map();
557
+ const resolveId = async (id) => idMap.get(id) ?? await target.seenGet(seenKey("id", id)) ?? id;
558
+ const created = [];
559
+ for (const item of items) {
560
+ const idKey = seenKey("id", item.id);
561
+ let owner = await target.seenGet(idKey);
562
+ if (owner === void 0 && await target.seenHas(idKey)) owner = item.id;
563
+ let level = owner ? 1 : 0;
564
+ if (!owner && item.canonicalUrl) {
565
+ owner = await target.seenGet(seenKey("url", item.canonicalUrl));
566
+ if (owner) level = 2;
567
+ }
568
+ if (owner) {
569
+ idMap.set(item.id, owner);
570
+ if (level === 2) await target.seenAdd(idKey, owner);
571
+ totals.duplicates++;
572
+ continue;
573
+ }
574
+ await target.upsertItem(item);
575
+ for (const k of itemSeenKeys(item)) await target.seenAdd(k, item.id);
576
+ created.push(item);
577
+ totals.items++;
578
+ }
579
+ for (const item of created) {
580
+ if (!item.links) continue;
581
+ const links = { ...item.links };
582
+ let changed = false;
583
+ for (const name of ["target", "parent", "root", "quoted"]) {
584
+ const v = links[name];
585
+ if (v === void 0) continue;
586
+ const r = await resolveId(v);
587
+ if (r !== v) {
588
+ links[name] = r;
589
+ changed = true;
590
+ }
591
+ }
592
+ if (changed) await target.upsertItem({ ...item, links });
593
+ }
594
+ for (const o of observations) {
595
+ await target.appendObservation({ ...o, itemId: await resolveId(o.itemId) });
596
+ totals.observations++;
597
+ }
598
+ for (const a of actors) {
599
+ const k = stableStringify(a);
600
+ if (writtenActors.has(k)) continue;
601
+ writtenActors.add(k);
602
+ await target.appendActor(a);
603
+ totals.actors++;
604
+ }
605
+ for (const p of pickups) {
606
+ await target.appendPickup({ ...p, itemId: await resolveId(p.itemId), ...p.pickupItemId ? { pickupItemId: await resolveId(p.pickupItemId) } : {} });
607
+ totals.pickups++;
608
+ }
609
+ }
610
+ async function realTarget(path) {
611
+ const rest = [];
612
+ let cur = path;
613
+ for (; ; ) {
614
+ try {
615
+ return join(await realpath(cur), ...rest.reverse());
616
+ } catch (e) {
617
+ if (e.code !== "ENOENT") throw e;
618
+ const parent = dirname(cur);
619
+ if (parent === cur) throw e;
620
+ rest.push(basename(cur));
621
+ cur = parent;
622
+ }
623
+ }
624
+ }
625
+ var inside = (child, parent) => child === parent || child.startsWith(parent + sep);
626
+ async function originalTask(source, cache, entry) {
627
+ if (!entry.runId || !entry.taskId) return void 0;
628
+ let tasks = cache.get(entry.runId);
629
+ if (!tasks) {
630
+ tasks = /* @__PURE__ */ new Map();
631
+ for await (const t of source.tasks(entry.runId)) {
632
+ const p = t.payload;
633
+ if (p && typeof p.id === "string") tasks.set(t.taskId, { id: p.id, ...p.kind ? { kind: p.kind } : {}, params: p.params ?? {} });
634
+ }
635
+ cache.set(entry.runId, tasks);
636
+ }
637
+ return tasks.get(entry.taskId);
638
+ }
639
+ async function runReparse(argv, io) {
640
+ const { values, positionals } = parse(argv, { ...CONNECTOR_OPTION, store: { type: "string" }, into: { type: "string" } });
641
+ positional(positionals, "none", 0);
642
+ if (!values.into) throw new UsageError("reparse needs --into <new store path>: the source store is never rewritten in place");
643
+ const sourcePath = storePathOf(io, values.store);
644
+ const wanted = resolve(io.cwd, values.into);
645
+ const { registry } = await loadConnectors(values.connector ?? [], io.cwd);
646
+ const source = await open(sourcePath);
647
+ const exists = await lstat(wanted).then(
648
+ () => true,
649
+ (e) => {
650
+ if (e.code === "ENOENT") return false;
651
+ throw new UsageError(`--into ${values.into} cannot be used: ${e.message}`);
652
+ }
653
+ );
654
+ if (exists) throw new UsageError(`--into ${values.into} already exists; reparse writes a new store and never reuses a path`);
655
+ const target = await realTarget(wanted);
656
+ const realSource = await realpath(sourcePath);
657
+ if (inside(target, realSource) || inside(realSource, target)) {
658
+ throw new UsageError("--into and the source store must not contain each other (symlinks resolved)");
659
+ }
660
+ await mkdir(dirname(target), { recursive: true });
661
+ try {
662
+ await mkdir(target);
663
+ } catch (e) {
664
+ if (e.code === "EEXIST") throw new UsageError(`--into ${values.into} was taken by another process`);
665
+ throw e;
666
+ }
667
+ const totals = {
668
+ raws: 0,
669
+ parsed: 0,
670
+ failedRaws: 0,
671
+ legacyTaskFallbacks: 0,
672
+ skippedIndexLines: 0,
673
+ interrupted: false,
674
+ items: 0,
675
+ duplicates: 0,
676
+ observations: 0,
677
+ actors: 0,
678
+ pickups: 0,
679
+ problems: []
680
+ };
681
+ let sourceLock;
682
+ let targetLock;
683
+ try {
684
+ sourceLock = await source.acquireLock();
685
+ const out2 = await initStore(target);
686
+ targetLock = await out2.acquireLock();
687
+ const writtenActors = /* @__PURE__ */ new Set();
688
+ const taskCache = /* @__PURE__ */ new Map();
689
+ let position = 0;
690
+ const index = source.rawIndex();
691
+ for await (const entry of index) {
692
+ if (io.signal?.aborted) {
693
+ totals.interrupted = true;
694
+ break;
695
+ }
696
+ totals.raws++;
697
+ if (!values.quiet && (totals.raws === 1 || totals.raws % 25 === 0)) err(io, `[reparse] ${totals.raws} raw(s)`);
698
+ const bytes = await source.getRaw(entry.ref);
699
+ if (!bytes) {
700
+ totals.problems.push(`${entry.ref}: raw body is missing`);
701
+ position++;
702
+ continue;
703
+ }
704
+ await out2.putRaw({
705
+ connector: entry.connector,
706
+ ext: entry.ext,
707
+ bytes,
708
+ url: entry.url,
709
+ fetchedAt: entry.fetchedAt,
710
+ httpStatus: entry.httpStatus,
711
+ transport: entry.transport,
712
+ runId: entry.runId,
713
+ taskId: entry.taskId,
714
+ failure: entry.failure
715
+ });
716
+ if (entry.failure) {
717
+ totals.failedRaws++;
718
+ position++;
719
+ continue;
720
+ }
721
+ const connector = registry.get(entry.connector);
722
+ if (!connector) {
723
+ const msg = `connector "${entry.connector}" is not registered (load it with --connector <module>)`;
724
+ if (!totals.problems.includes(msg)) totals.problems.push(msg);
725
+ position++;
726
+ continue;
727
+ }
728
+ let task = await originalTask(source, taskCache, entry);
729
+ if (!task) {
730
+ totals.legacyTaskFallbacks++;
731
+ task = { id: `reparse:${entry.hash.slice(0, 12)}`, params: {} };
732
+ }
733
+ try {
734
+ await ingestRaw(out2, connector, entry, position, bytes, task, writtenActors, totals);
735
+ totals.parsed++;
736
+ } catch (e) {
737
+ totals.problems.push(`${entry.ref}: ${e instanceof Error ? e.message : String(e)}`);
738
+ }
739
+ position++;
740
+ }
741
+ totals.skippedIndexLines = index.skipped;
742
+ } catch (e) {
743
+ if (!targetLock) await rm(target, { recursive: true, force: true }).catch(() => void 0);
744
+ throw e;
745
+ } finally {
746
+ await targetLock?.release().catch(() => void 0);
747
+ await sourceLock?.release().catch(() => void 0);
748
+ }
749
+ if (values.json) outJson(io, { into: target, ...totals });
750
+ else {
751
+ out(io, `reparsed ${totals.parsed} of ${totals.raws} raw(s) into ${target}`);
752
+ out(io, `items=${totals.items} duplicates=${totals.duplicates} observations=${totals.observations} actors=${totals.actors} pickups=${totals.pickups} failedRaws=${totals.failedRaws}`);
753
+ if (totals.legacyTaskFallbacks) err(io, `warning: ${totals.legacyTaskFallbacks} raw(s) have no recorded task; parsed with a synthetic task, results may differ`);
754
+ if (totals.skippedIndexLines) err(io, `warning: ${totals.skippedIndexLines} unreadable line(s) in the raw index were skipped`);
755
+ if (totals.interrupted) err(io, "interrupted: the new store is incomplete");
756
+ for (const p of totals.problems) err(io, `problem: ${p}`);
757
+ }
758
+ const clean = totals.problems.length === 0 && totals.legacyTaskFallbacks === 0 && totals.skippedIndexLines === 0 && !totals.interrupted;
759
+ return clean ? 0 : 1;
760
+ }
761
+ var RUN_OPTIONS = {
762
+ ...CONNECTOR_OPTION,
763
+ store: { type: "string" },
764
+ "rate-ms": { type: "string" }
765
+ };
766
+ function rateOf(value) {
767
+ if (value === void 0) return void 0;
768
+ if (!/^\d+$/.test(value)) throw new UsageError(`--rate-ms must be a non-negative integer, got "${value}"`);
769
+ return Number(value);
770
+ }
771
+ async function runRun(argv, io) {
772
+ const { values, positionals } = parse(argv, {
773
+ ...RUN_OPTIONS,
774
+ source: { type: "string", multiple: true },
775
+ query: { type: "string", multiple: true },
776
+ subject: { type: "string" },
777
+ max: { type: "string" },
778
+ "dry-run": { type: "boolean" }
779
+ });
780
+ if (positionals.length > 1) positional(positionals, "recipe", 1);
781
+ const max = intOption("max", values.max);
782
+ const rateMs = rateOf(values["rate-ms"]);
783
+ const modules = [...values.connector ?? []];
784
+ let recipe;
785
+ if (positionals[0]) {
786
+ const loaded = await loadRecipe(positionals[0], io.cwd);
787
+ modules.push(...loaded.connectors);
788
+ recipe = loaded.recipe;
789
+ if (values.source?.length) {
790
+ const unknown = values.source.filter((s) => !recipe.sources.some((r) => r.connector === s));
791
+ if (unknown.length) throw new UsageError(`--source ${unknown.join(", ")} is not in the recipe`);
792
+ recipe = { ...recipe, sources: recipe.sources.filter((s) => values.source.includes(s.connector)) };
793
+ }
794
+ if (values.query?.length) {
795
+ if (!values.subject) throw new UsageError("--query needs --subject");
796
+ const queries = values.query.map((text) => ({ text, subject: values.subject }));
797
+ recipe = { ...recipe, sources: recipe.sources.map((s) => ({ ...s, queries })) };
798
+ }
799
+ } else {
800
+ if (!values.source?.length) throw new UsageError("give a recipe file, or --source <connector> for a trial run");
801
+ if (values.query?.length && !values.subject) throw new UsageError("--query needs --subject");
802
+ const queries = (values.query ?? []).map((text) => ({ text, subject: values.subject }));
803
+ recipe = validateRecipe({ name: "trial", sources: values.source.map((connector) => ({ connector, queries })) }, "built from the command line");
804
+ }
805
+ if (max !== void 0) recipe = { ...recipe, caps: { ...recipe.caps, total: max } };
806
+ recipe = validateRecipe(recipe, "after applying the command-line options");
807
+ const moduleFiles = [...new Set(modules.map((m) => resolve(io.cwd, m)))];
808
+ const loadedConnectors = await loadConnectors(moduleFiles, io.cwd);
809
+ if (values["dry-run"]) {
810
+ const tasks = [];
811
+ const seen = /* @__PURE__ */ new Set();
812
+ for (const id of new Set(recipe.sources.map((s) => s.connector))) {
813
+ const c = loadedConnectors.registry.get(id);
814
+ if (!c) throw new UsageError(`connector "${id}" is not registered (load it with --connector <module>)`);
815
+ const sources = recipe.sources.filter((s) => s.connector === id);
816
+ for (const t of c.plan(recipe, sources)) {
817
+ const task = CollectTask.parse(t);
818
+ if (seen.has(`${id}/${task.id}`)) continue;
819
+ seen.add(`${id}/${task.id}`);
820
+ tasks.push({ connector: id, id: task.id, ...task.kind ? { kind: task.kind } : {}, params: task.params });
821
+ }
822
+ }
823
+ if (values.json) outJson(io, { dryRun: true, tasks, sampling: recipe.sampling ?? null, lookahead: recipe.lookahead ?? null });
824
+ else {
825
+ out(io, `dry run: ${tasks.length} planned task${tasks.length === 1 ? "" : "s"}, nothing fetched or written`);
826
+ if (recipe.sampling) out(io, "sampling (bands, quotas, caps) applies to what the tasks return and is not simulated");
827
+ if (recipe.lookahead !== void 0) out(io, `lookahead: ${recipe.lookahead}`);
828
+ if (tasks.length) out(io, table(tasks.map((t) => [t.connector, t.id, t.kind ?? "", JSON.stringify(t.params)])));
829
+ }
830
+ return 0;
831
+ }
832
+ return execute(io, {
833
+ storePath: storePathOf(io, values.store),
834
+ json: Boolean(values.json),
835
+ quiet: Boolean(values.quiet),
836
+ loaded: loadedConnectors,
837
+ rateMs,
838
+ start: (collector, onEvent) => collector.run(recipe, { signal: io.signal, onEvent, connectorModules: moduleFiles })
839
+ });
840
+ }
841
+ async function runResume(argv, io) {
842
+ const { values, positionals } = parse(argv, RUN_OPTIONS);
843
+ const [runId] = positional(positionals, "runId");
844
+ const rateMs = rateOf(values["rate-ms"]);
845
+ const storePath = storePathOf(io, values.store);
846
+ const run = await (await open(storePath)).getRun(runId);
847
+ if (!run) throw new UsageError(`unknown run ${runId}`);
848
+ const modules = [.../* @__PURE__ */ new Set([...run.connectorModules ?? [], ...(values.connector ?? []).map((m) => resolve(io.cwd, m))])];
849
+ const loaded = await loadConnectors(modules, io.cwd);
850
+ return execute(io, {
851
+ storePath,
852
+ json: Boolean(values.json),
853
+ quiet: Boolean(values.quiet),
854
+ loaded,
855
+ rateMs,
856
+ start: (collector, onEvent) => collector.resume(runId, { signal: io.signal, onEvent })
857
+ });
858
+ }
859
+ function readVersion() {
860
+ try {
861
+ const here = dirname(fileURLToPath(import.meta.url));
862
+ const pkg = JSON.parse(readFileSync(resolve(here, "../package.json"), "utf8"));
863
+ return pkg.version ?? "0.0.0";
864
+ } catch {
865
+ return "0.0.0";
866
+ }
867
+ }
868
+ var VERSION = readVersion();
869
+
870
+ // src/main.ts
871
+ function defaultIo() {
872
+ return { stdout: process.stdout, stderr: process.stderr, env: process.env, cwd: process.cwd() };
873
+ }
874
+ var HELP = `collect: collect public posts and articles with provenance (v${VERSION})
875
+
876
+ Commands:
877
+ init <store> Create a store
878
+ connectors List the connectors that are registered or loaded
879
+ doctor [recipe.yaml] Check connectors: access level, secret (name only), transports
880
+ [--source id]... (default: every registered connector)
881
+ run [recipe.yaml] Run a recipe
882
+ [--source id]... [--query text]... [--subject label] [--max n]
883
+ [--dry-run] [--store path]
884
+ Without a recipe, --source (and --query with --subject) makes a trial run.
885
+ resume <runId> Continue an interrupted run (done tasks are not fetched again)
886
+ runs List the runs of a store
887
+ status <runId> Task states and report of one run
888
+ export Items as JSONL (default) or --format csv
889
+ [--source id] [--out file]
890
+ reparse --into <new store> Rebuild items, observations, actors and pickups from stored raws.
891
+ No network; the source store is never modified.
892
+
893
+ Options on every command:
894
+ --json machine output on stdout (progress stays on stderr)
895
+ --store path store to use (default: $COLLECT_STORE or ./collect-store)
896
+ --connector f load connector modules from a file (repeatable; also "connectors:" in a recipe)
897
+ -q, --quiet no progress on stderr
898
+ -h, --help this help
899
+
900
+ Exit codes: 0 success, 1 partial failure, 2 usage error, 3 store locked or unreadable.
901
+ `;
902
+ var COMMANDS = {
903
+ init: runInit,
904
+ connectors: runConnectors,
905
+ doctor: runDoctor,
906
+ run: runRun,
907
+ resume: runResume,
908
+ runs: runRuns,
909
+ status: runStatus,
910
+ export: runExport,
911
+ reparse: runReparse
912
+ };
913
+ function guarded(io) {
914
+ const redactors = [];
915
+ const scrub = (text) => redactors.reduce((t, r) => r(t), text);
916
+ const wrap = (s) => ({
917
+ write: (chunk) => s.write(redactors.length ? scrub(chunk) : chunk),
918
+ once: s.once ? s.once.bind(s) : void 0
919
+ });
920
+ return { ...io, stdout: wrap(io.stdout), stderr: wrap(io.stderr), addRedactor: (r) => void redactors.push(r) };
921
+ }
922
+ async function main(argv, io = defaultIo()) {
923
+ const [cmd, ...rest] = argv;
924
+ if (!cmd || cmd === "--help" || cmd === "-h" || cmd === "help") {
925
+ out(io, HELP);
926
+ return cmd ? 0 : 2;
927
+ }
928
+ if (cmd === "--version" || cmd === "-v") {
929
+ out(io, VERSION);
930
+ return 0;
931
+ }
932
+ const run = Object.hasOwn(COMMANDS, cmd) ? COMMANDS[cmd] : void 0;
933
+ if (!run) {
934
+ err(io, `collect: unknown command "${cmd}". Try --help.`);
935
+ return 2;
936
+ }
937
+ if (rest.includes("--help") || rest.includes("-h")) {
938
+ out(io, HELP);
939
+ return 0;
940
+ }
941
+ const safe = guarded(io);
942
+ try {
943
+ return await run(rest, safe);
944
+ } catch (e) {
945
+ const c = classify(e);
946
+ if (c) {
947
+ err(safe, `collect: ${c.message}`);
948
+ return c.code;
949
+ }
950
+ err(safe, `collect: ${e instanceof Error ? e.message : String(e)}`);
951
+ return 1;
952
+ }
953
+ }
954
+
955
+ export { defaultIo, main };
956
+ //# sourceMappingURL=index.mjs.map
957
+ //# sourceMappingURL=index.mjs.map