@agentproto/corpus-cli 0.3.0 → 0.5.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/LICENSE +202 -21
- package/README.md +2 -0
- package/dist/cli.mjs +412 -62
- package/dist/cli.mjs.map +1 -1
- package/dist/index.d.ts +67 -2
- package/dist/index.mjs +88 -2
- package/dist/index.mjs.map +1 -1
- package/dist/specs/resources/aip-45/draft/AGENT-CLI.schema.json +26 -2
- package/package.json +5 -5
package/dist/cli.mjs
CHANGED
|
@@ -5,14 +5,14 @@ import { createRequire } from 'module';
|
|
|
5
5
|
import path, { dirname, resolve, basename, join, extname } from 'path';
|
|
6
6
|
import { fileURLToPath, pathToFileURL } from 'url';
|
|
7
7
|
import { z } from 'zod';
|
|
8
|
-
import { randomBytes, randomUUID } from 'crypto';
|
|
8
|
+
import { randomBytes, randomUUID, createHash } from 'crypto';
|
|
9
9
|
import { readFileSync, existsSync } from 'fs';
|
|
10
|
-
import { buildDistillPrompt, parseItems, isRefinedKind, SyncRunner, resolveKnowledge, DistillRunner, systemClock, WebImporter, ImporterRunner, CorpusEventEmitter, CorpusWorkspaceReader, CorpusLinter, CorpusValidator, ReadOnlyFs, normalizeLanguageTag } from '@agentproto/corpus';
|
|
11
|
-
import
|
|
10
|
+
import { buildDistillPrompt, parseItems, isRefinedKind, SyncRunner, resolveKnowledge, DistillIndex, DistillRunner, systemClock, WebImporter, ImporterRunner, CorpusEventEmitter, CorpusWorkspaceReader, CorpusLinter, CorpusValidator, ReadOnlyFs, normalizeLanguageTag, lensAspect } from '@agentproto/corpus';
|
|
11
|
+
import matter3 from 'gray-matter';
|
|
12
12
|
import { execFile } from 'child_process';
|
|
13
13
|
import { promisify } from 'util';
|
|
14
14
|
import { parseClaudeJsonOutput, spawnWithStdin } from '@agentproto/cli-exec';
|
|
15
|
-
import { stitchReport, buildPacks, reportConfigSchema } from '@agentproto/corpus/report';
|
|
15
|
+
import { stitchReport, buildPacks, lintReportConfig, reportConfigSchema } from '@agentproto/corpus/report';
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
18
|
* @agentproto/corpus-cli v0.1.0-alpha
|
|
@@ -104,9 +104,9 @@ function resolvePackageJson(packageName) {
|
|
|
104
104
|
}
|
|
105
105
|
return null;
|
|
106
106
|
}
|
|
107
|
-
async function readJsonIfExists(
|
|
107
|
+
async function readJsonIfExists(path6) {
|
|
108
108
|
try {
|
|
109
|
-
const raw = await readFile(
|
|
109
|
+
const raw = await readFile(path6, "utf8");
|
|
110
110
|
return JSON.parse(raw);
|
|
111
111
|
} catch (err) {
|
|
112
112
|
if (err.code === "ENOENT") return void 0;
|
|
@@ -115,9 +115,9 @@ async function readJsonIfExists(path5) {
|
|
|
115
115
|
}
|
|
116
116
|
async function readConfiguredPresetPackages() {
|
|
117
117
|
const base = process.env["AGENTPROTO_HOME"] ?? join(homedir(), ".agentproto");
|
|
118
|
-
const
|
|
118
|
+
const path6 = join(base, "config.json");
|
|
119
119
|
try {
|
|
120
|
-
const raw = await readFile(
|
|
120
|
+
const raw = await readFile(path6, "utf8");
|
|
121
121
|
const parsed = JSON.parse(raw);
|
|
122
122
|
const list = parsed.corpusPresetPackages;
|
|
123
123
|
if (Array.isArray(list) && list.length > 0) return list;
|
|
@@ -631,6 +631,160 @@ async function runLint(args) {
|
|
|
631
631
|
);
|
|
632
632
|
return report.errorCount > 0 ? 1 : 0;
|
|
633
633
|
}
|
|
634
|
+
var FLAG_PATTERNS = [
|
|
635
|
+
/does not match/i,
|
|
636
|
+
/content is about/i,
|
|
637
|
+
/no substantive content/i,
|
|
638
|
+
/content mismatch/i,
|
|
639
|
+
/appears to be a (?:newsletter|navigation|login|error) page/i,
|
|
640
|
+
/stated title/i,
|
|
641
|
+
/placeholder page/i,
|
|
642
|
+
/cookie consent/i,
|
|
643
|
+
/page could not be/i
|
|
644
|
+
];
|
|
645
|
+
function parse(args) {
|
|
646
|
+
const out = {
|
|
647
|
+
workspace: void 0,
|
|
648
|
+
facets: [],
|
|
649
|
+
thin: 8,
|
|
650
|
+
apply: false,
|
|
651
|
+
contaminated: false
|
|
652
|
+
};
|
|
653
|
+
for (let i = 0; i < args.length; i++) {
|
|
654
|
+
const a = args[i];
|
|
655
|
+
const next = () => args[++i];
|
|
656
|
+
switch (a) {
|
|
657
|
+
case "--facets": {
|
|
658
|
+
const v = next();
|
|
659
|
+
if (v) out.facets = v.split(",").map((s) => s.trim()).filter(Boolean);
|
|
660
|
+
break;
|
|
661
|
+
}
|
|
662
|
+
case "--thin": {
|
|
663
|
+
const v = next();
|
|
664
|
+
if (v) out.thin = Number(v);
|
|
665
|
+
break;
|
|
666
|
+
}
|
|
667
|
+
case "--apply":
|
|
668
|
+
out.apply = true;
|
|
669
|
+
break;
|
|
670
|
+
case "--contaminated":
|
|
671
|
+
out.contaminated = true;
|
|
672
|
+
break;
|
|
673
|
+
default:
|
|
674
|
+
if (!a.startsWith("-") && out.workspace === void 0) out.workspace = a;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
return out;
|
|
678
|
+
}
|
|
679
|
+
function firstFlag(haystack) {
|
|
680
|
+
for (const re of FLAG_PATTERNS) {
|
|
681
|
+
const m = haystack.match(re);
|
|
682
|
+
if (m) return m[0];
|
|
683
|
+
}
|
|
684
|
+
return void 0;
|
|
685
|
+
}
|
|
686
|
+
function entryStatus(entry) {
|
|
687
|
+
const corpus = entry.frontmatter.metadata?.corpus;
|
|
688
|
+
return corpus?.status ?? "active";
|
|
689
|
+
}
|
|
690
|
+
function tagsOf(entry) {
|
|
691
|
+
const tags = entry.frontmatter.tags;
|
|
692
|
+
return Array.isArray(tags) ? tags.map(String) : [];
|
|
693
|
+
}
|
|
694
|
+
function sourcesOf(entry) {
|
|
695
|
+
const sources = entry.frontmatter.sources;
|
|
696
|
+
return Array.isArray(sources) ? sources.map(String) : [];
|
|
697
|
+
}
|
|
698
|
+
async function runVerify(args) {
|
|
699
|
+
const parsed = parse(args);
|
|
700
|
+
if (parsed.facets.length === 0) {
|
|
701
|
+
return fail(
|
|
702
|
+
"verify requires --facets a,b,c. Usage: corpus verify <workspace> --facets landscape,daemons,... [--thin 8] [--apply] [--contaminated]",
|
|
703
|
+
2
|
|
704
|
+
);
|
|
705
|
+
}
|
|
706
|
+
const target = resolveWorkspacePath(parsed.workspace);
|
|
707
|
+
const fs = new NodeFsAdapter({ root: target });
|
|
708
|
+
if (!await fs.exists("entries")) {
|
|
709
|
+
return fail(`verify: no entries/ under ${target}`, 1);
|
|
710
|
+
}
|
|
711
|
+
const snapshot = await new CorpusWorkspaceReader({ fs }).read("");
|
|
712
|
+
const entries = snapshot.entries.filter((e) => entryStatus(e) === "active");
|
|
713
|
+
const perFacet = /* @__PURE__ */ new Map();
|
|
714
|
+
for (const facet of parsed.facets) perFacet.set(facet, 0);
|
|
715
|
+
for (const entry of entries) {
|
|
716
|
+
for (const tag of tagsOf(entry)) {
|
|
717
|
+
if (perFacet.has(tag)) perFacet.set(tag, (perFacet.get(tag) ?? 0) + 1);
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
process.stdout.write(`== coverage (${entries.length} entries) ==
|
|
721
|
+
`);
|
|
722
|
+
const thin = [];
|
|
723
|
+
for (const facet of parsed.facets) {
|
|
724
|
+
const n = perFacet.get(facet) ?? 0;
|
|
725
|
+
if (n < parsed.thin) thin.push(facet);
|
|
726
|
+
const mark = n < parsed.thin ? " THIN \u26A0" : "";
|
|
727
|
+
process.stdout.write(` ${facet.padEnd(16)} ${String(n).padStart(4)}${mark}
|
|
728
|
+
`);
|
|
729
|
+
}
|
|
730
|
+
const flagged = [];
|
|
731
|
+
for (const entry of entries) {
|
|
732
|
+
const title = String(entry.frontmatter.title ?? "");
|
|
733
|
+
const why = firstFlag(`${title}
|
|
734
|
+
${entry.body}`);
|
|
735
|
+
if (why) flagged.push({ entry, why });
|
|
736
|
+
}
|
|
737
|
+
process.stdout.write(`
|
|
738
|
+
== self-flagged entries (${flagged.length}) ==
|
|
739
|
+
`);
|
|
740
|
+
const poisonedSources = /* @__PURE__ */ new Set();
|
|
741
|
+
for (const { entry, why } of flagged) {
|
|
742
|
+
process.stdout.write(` ${entry.path} [${why}]
|
|
743
|
+
`);
|
|
744
|
+
for (const s of sourcesOf(entry)) poisonedSources.add(s);
|
|
745
|
+
}
|
|
746
|
+
const flaggedPaths = new Set(flagged.map((f) => f.entry.path));
|
|
747
|
+
const contaminated = [];
|
|
748
|
+
if (parsed.contaminated && poisonedSources.size > 0) {
|
|
749
|
+
for (const entry of entries) {
|
|
750
|
+
if (flaggedPaths.has(entry.path)) continue;
|
|
751
|
+
if (sourcesOf(entry).some((s) => poisonedSources.has(s))) {
|
|
752
|
+
contaminated.push(entry);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
process.stdout.write(
|
|
756
|
+
`
|
|
757
|
+
== contaminated siblings (${contaminated.length}) from ${poisonedSources.size} poisoned source(s) ==
|
|
758
|
+
`
|
|
759
|
+
);
|
|
760
|
+
for (const entry of contaminated) {
|
|
761
|
+
process.stdout.write(` ${entry.path}
|
|
762
|
+
`);
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
if (parsed.apply) {
|
|
766
|
+
const toMove = [...flagged.map((f) => f.entry), ...contaminated];
|
|
767
|
+
for (const entry of toMove) {
|
|
768
|
+
const rel = path.relative("entries", entry.path);
|
|
769
|
+
const dest = path.join(target, "demoted", rel);
|
|
770
|
+
await mkdir(path.dirname(dest), { recursive: true });
|
|
771
|
+
await rename(path.join(target, entry.path), dest);
|
|
772
|
+
}
|
|
773
|
+
process.stdout.write(`
|
|
774
|
+
moved ${toMove.length} entries \u2192 demoted/
|
|
775
|
+
`);
|
|
776
|
+
} else if (flagged.length > 0) {
|
|
777
|
+
process.stdout.write(
|
|
778
|
+
"\n(re-run with --apply to quarantine; --contaminated to also demote siblings)\n"
|
|
779
|
+
);
|
|
780
|
+
}
|
|
781
|
+
if (thin.length > 0) {
|
|
782
|
+
process.stdout.write(`
|
|
783
|
+
thin facets \u2192 loop back to \u2461 DISCOVER: ${thin.join(", ")}
|
|
784
|
+
`);
|
|
785
|
+
}
|
|
786
|
+
return 0;
|
|
787
|
+
}
|
|
634
788
|
var OsIdentityAdapter = class {
|
|
635
789
|
cached;
|
|
636
790
|
constructor(opts) {
|
|
@@ -1297,18 +1451,18 @@ var AssemblyAiStt = class {
|
|
|
1297
1451
|
...job.language_code ? { language: job.language_code } : {}
|
|
1298
1452
|
};
|
|
1299
1453
|
}
|
|
1300
|
-
async post(
|
|
1301
|
-
const r = await fetch(`${this.baseUrl}${
|
|
1454
|
+
async post(path6, body) {
|
|
1455
|
+
const r = await fetch(`${this.baseUrl}${path6}`, {
|
|
1302
1456
|
method: "POST",
|
|
1303
1457
|
headers: { authorization: this.apiKey, "content-type": "application/json" },
|
|
1304
1458
|
body: JSON.stringify(body)
|
|
1305
1459
|
});
|
|
1306
|
-
if (!r.ok) throw new Error(`AssemblyAI POST ${
|
|
1460
|
+
if (!r.ok) throw new Error(`AssemblyAI POST ${path6} ${r.status}: ${(await r.text()).slice(0, 200)}`);
|
|
1307
1461
|
return AAI_TRANSCRIPT.parse(await r.json());
|
|
1308
1462
|
}
|
|
1309
|
-
async get(
|
|
1310
|
-
const r = await fetch(`${this.baseUrl}${
|
|
1311
|
-
if (!r.ok) throw new Error(`AssemblyAI GET ${
|
|
1463
|
+
async get(path6) {
|
|
1464
|
+
const r = await fetch(`${this.baseUrl}${path6}`, { headers: { authorization: this.apiKey } });
|
|
1465
|
+
if (!r.ok) throw new Error(`AssemblyAI GET ${path6} ${r.status}: ${(await r.text()).slice(0, 200)}`);
|
|
1312
1466
|
return AAI_TRANSCRIPT.parse(await r.json());
|
|
1313
1467
|
}
|
|
1314
1468
|
};
|
|
@@ -1593,7 +1747,7 @@ var SOURCE_URL_FRONTMATTER = z.object({
|
|
|
1593
1747
|
}).loose().optional().catch(void 0)
|
|
1594
1748
|
}).loose().optional().catch(void 0)
|
|
1595
1749
|
}).loose();
|
|
1596
|
-
function
|
|
1750
|
+
function parse2(args) {
|
|
1597
1751
|
const out = {
|
|
1598
1752
|
workspace: void 0,
|
|
1599
1753
|
urlsFile: void 0,
|
|
@@ -1714,7 +1868,7 @@ async function scanIngestedUrls(workspaceRoot) {
|
|
|
1714
1868
|
if (!e.isFile() || !e.name.endsWith(".md")) continue;
|
|
1715
1869
|
try {
|
|
1716
1870
|
const raw = await readFile(join(e.parentPath, e.name), "utf-8");
|
|
1717
|
-
const fm = SOURCE_URL_FRONTMATTER.parse(
|
|
1871
|
+
const fm = SOURCE_URL_FRONTMATTER.parse(matter3(raw).data);
|
|
1718
1872
|
const url = fm.metadata?.corpus?.originalUrl ?? fm.metadata?.corpus?.importerSourceUrl;
|
|
1719
1873
|
if (url) seen.add(url);
|
|
1720
1874
|
} catch {
|
|
@@ -1723,7 +1877,7 @@ async function scanIngestedUrls(workspaceRoot) {
|
|
|
1723
1877
|
return seen;
|
|
1724
1878
|
}
|
|
1725
1879
|
async function runImportWeb(args) {
|
|
1726
|
-
const parsed =
|
|
1880
|
+
const parsed = parse2(args);
|
|
1727
1881
|
const target = resolveWorkspacePath(parsed.workspace);
|
|
1728
1882
|
const urls = await readUrls(parsed);
|
|
1729
1883
|
if (urls.length === 0) {
|
|
@@ -1863,7 +2017,7 @@ knowledge engine (RAG) via the WriterPort. Import only stages the sources.
|
|
|
1863
2017
|
function msg3(e) {
|
|
1864
2018
|
return e instanceof Error ? e.message : String(e);
|
|
1865
2019
|
}
|
|
1866
|
-
function
|
|
2020
|
+
function parse3(args) {
|
|
1867
2021
|
const out = {
|
|
1868
2022
|
topic: void 0,
|
|
1869
2023
|
outputPath: void 0,
|
|
@@ -1871,7 +2025,8 @@ function parse2(args) {
|
|
|
1871
2025
|
channels: /* @__PURE__ */ new Set(["web"]),
|
|
1872
2026
|
lang: void 0,
|
|
1873
2027
|
tags: [],
|
|
1874
|
-
doImport: false
|
|
2028
|
+
doImport: false,
|
|
2029
|
+
fresh: false
|
|
1875
2030
|
};
|
|
1876
2031
|
for (let i = 0; i < args.length; i++) {
|
|
1877
2032
|
const a = args[i];
|
|
@@ -1898,6 +2053,9 @@ function parse2(args) {
|
|
|
1898
2053
|
case "--import":
|
|
1899
2054
|
out.doImport = true;
|
|
1900
2055
|
break;
|
|
2056
|
+
case "--fresh":
|
|
2057
|
+
out.fresh = true;
|
|
2058
|
+
break;
|
|
1901
2059
|
default:
|
|
1902
2060
|
if (!a.startsWith("-")) {
|
|
1903
2061
|
if (out.topic === void 0) out.topic = a;
|
|
@@ -2025,10 +2183,18 @@ async function discoverSocial(_topic, _lang, _max) {
|
|
|
2025
2183
|
process.stdout.write(" social channel needs a Bureau session \u2014 skipped.\n");
|
|
2026
2184
|
return [];
|
|
2027
2185
|
}
|
|
2186
|
+
async function readExistingUrls(outFile) {
|
|
2187
|
+
try {
|
|
2188
|
+
const prior = await readFile(outFile, "utf-8");
|
|
2189
|
+
return prior.split("\n").map((l) => l.trim()).filter(Boolean);
|
|
2190
|
+
} catch {
|
|
2191
|
+
return [];
|
|
2192
|
+
}
|
|
2193
|
+
}
|
|
2028
2194
|
async function runDiscover(args) {
|
|
2029
|
-
const parsed =
|
|
2195
|
+
const parsed = parse3(args);
|
|
2030
2196
|
if (!parsed.topic) {
|
|
2031
|
-
return fail("discover requires a <topic> argument. Usage: corpus discover <topic> [path] [--max N] [--channels web,youtube,social] [--lang fr] [--tags t] [--import]", 2);
|
|
2197
|
+
return fail("discover requires a <topic> argument. Usage: corpus discover <topic> [path] [--max N] [--channels web,youtube,social] [--lang fr] [--tags t] [--import] [--fresh]", 2);
|
|
2032
2198
|
}
|
|
2033
2199
|
const outputPath = parsed.outputPath ? resolveWorkspacePath(parsed.outputPath) : process.cwd();
|
|
2034
2200
|
process.stdout.write(`discover "${parsed.topic}"
|
|
@@ -2071,10 +2237,22 @@ async function runDiscover(args) {
|
|
|
2071
2237
|
}
|
|
2072
2238
|
await mkdir(outputPath, { recursive: true });
|
|
2073
2239
|
const outFile = join(outputPath, "urls.discovered.txt");
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2240
|
+
const existing = parsed.fresh ? [] : await readExistingUrls(outFile);
|
|
2241
|
+
const merged = [...existing];
|
|
2242
|
+
const known = new Set(existing);
|
|
2243
|
+
for (const url of allUrls) {
|
|
2244
|
+
if (!known.has(url)) {
|
|
2245
|
+
known.add(url);
|
|
2246
|
+
merged.push(url);
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
const added = merged.length - existing.length;
|
|
2250
|
+
await writeFile(outFile, merged.join("\n") + "\n", "utf-8");
|
|
2251
|
+
process.stdout.write(
|
|
2252
|
+
`
|
|
2253
|
+
written \u2192 ${outFile} (${merged.length} URLs` + (parsed.fresh ? ", --fresh overwrite" : `, ${added} new, ${existing.length} kept from previous runs`) + `)
|
|
2254
|
+
`
|
|
2255
|
+
);
|
|
2078
2256
|
if (parsed.doImport) {
|
|
2079
2257
|
process.stdout.write("\n --import: chaining import-web\u2026\n");
|
|
2080
2258
|
const importArgs = [
|
|
@@ -2393,6 +2571,91 @@ usage \u2014 ${records.length} metered call(s):
|
|
|
2393
2571
|
};
|
|
2394
2572
|
}
|
|
2395
2573
|
|
|
2574
|
+
// src/lenses/builtin.ts
|
|
2575
|
+
var CRAFT_LENS = {
|
|
2576
|
+
id: "craft",
|
|
2577
|
+
label: "Writing craft",
|
|
2578
|
+
aspect: "craft",
|
|
2579
|
+
mode: "log",
|
|
2580
|
+
// The distiller emits {kind,title,body,...}; a craft move is a technique
|
|
2581
|
+
// (pattern), a rule (principle), a shallow default it avoids (critique), or a
|
|
2582
|
+
// specific instance (example). "summary" is dropped — a summary is topic
|
|
2583
|
+
// content, not a transferable craft move.
|
|
2584
|
+
kinds: ["pattern", "principle", "critique", "example"],
|
|
2585
|
+
prompt: [
|
|
2586
|
+
"Extract TRANSFERABLE WRITING-CRAFT MOVES from the source \u2014 reusable techniques a writer could apply to ANY topic. Study HOW the piece is written; IGNORE what it is about. Do NOT extract facts, claims, or lessons about the subject matter \u2014 only the craft.",
|
|
2587
|
+
"",
|
|
2588
|
+
"Focus on: how the first line hooks; structure and transitions; how depth is manufactured (specificity, tension, the earned turn, surprising-but-true facts); how voice and edge are earned without cringe; sentence rhythm and variation; how it ends. Prioritise the moves that separate memorable writing from generic filler.",
|
|
2589
|
+
"",
|
|
2590
|
+
"For each move:",
|
|
2591
|
+
'- kind: "pattern" for a technique, "principle" for a rule, "critique" for a shallow/generic default the move avoids, "example" for a specific instance.',
|
|
2592
|
+
'- title: name the move crisply and imperatively (e.g. "Delay the thesis until after a concrete image").',
|
|
2593
|
+
"- body: state the reusable technique in 1-2 topic-agnostic sentences; name the generic / AI-default it beats; and include a <=30-word verbatim snippet from the source where the move happens (omit the quote only when the move is purely structural)."
|
|
2594
|
+
].join("\n")
|
|
2595
|
+
};
|
|
2596
|
+
var BUILTIN_LENSES = {
|
|
2597
|
+
[CRAFT_LENS.id]: CRAFT_LENS
|
|
2598
|
+
};
|
|
2599
|
+
function builtinLensIds() {
|
|
2600
|
+
return Object.keys(BUILTIN_LENSES);
|
|
2601
|
+
}
|
|
2602
|
+
|
|
2603
|
+
// src/lenses/resolve.ts
|
|
2604
|
+
var LensError = class extends Error {
|
|
2605
|
+
constructor(message) {
|
|
2606
|
+
super(message);
|
|
2607
|
+
this.name = "LensError";
|
|
2608
|
+
}
|
|
2609
|
+
};
|
|
2610
|
+
var LENS_FRONTMATTER = z.object({
|
|
2611
|
+
id: z.string().optional().catch(void 0),
|
|
2612
|
+
label: z.string().optional().catch(void 0),
|
|
2613
|
+
aspect: z.string().optional().catch(void 0),
|
|
2614
|
+
prompt: z.string().optional().catch(void 0),
|
|
2615
|
+
mode: z.string().optional().catch(void 0),
|
|
2616
|
+
kinds: z.array(z.string()).optional().catch(void 0),
|
|
2617
|
+
synthesisPath: z.string().optional().catch(void 0)
|
|
2618
|
+
}).loose();
|
|
2619
|
+
function parseLensDoc(raw, fallbackId) {
|
|
2620
|
+
const parsed = matter3(raw);
|
|
2621
|
+
const fm = LENS_FRONTMATTER.parse(parsed.data);
|
|
2622
|
+
const prompt = (parsed.content.trim() || fm.prompt?.trim()) ?? "";
|
|
2623
|
+
if (!prompt) {
|
|
2624
|
+
throw new LensError(
|
|
2625
|
+
`lens "${fm.id ?? fallbackId}" has no prompt \u2014 put the extraction instruction in the markdown body or a "prompt:" frontmatter key.`
|
|
2626
|
+
);
|
|
2627
|
+
}
|
|
2628
|
+
const kinds = (fm.kinds ?? []).filter(isRefinedKind);
|
|
2629
|
+
const mode = fm.mode === "synthesis" ? "synthesis" : "log";
|
|
2630
|
+
return {
|
|
2631
|
+
id: fm.id ?? fallbackId,
|
|
2632
|
+
label: fm.label ?? fm.id ?? fallbackId,
|
|
2633
|
+
prompt,
|
|
2634
|
+
mode,
|
|
2635
|
+
...fm.aspect ? { aspect: fm.aspect } : {},
|
|
2636
|
+
...kinds.length > 0 ? { kinds } : {},
|
|
2637
|
+
...fm.synthesisPath ? { synthesisPath: fm.synthesisPath } : {}
|
|
2638
|
+
};
|
|
2639
|
+
}
|
|
2640
|
+
async function resolveLens(id, workspaceRoot) {
|
|
2641
|
+
const wsPath = join(workspaceRoot, "lenses", `${id}.md`);
|
|
2642
|
+
if (existsSync(wsPath)) {
|
|
2643
|
+
return parseLensDoc(await readFile(wsPath, "utf8"), id);
|
|
2644
|
+
}
|
|
2645
|
+
const builtin = BUILTIN_LENSES[id];
|
|
2646
|
+
if (builtin) return builtin;
|
|
2647
|
+
throw new LensError(
|
|
2648
|
+
`unknown lens "${id}". Built-in: ${builtinLensIds().join(", ") || "(none)"}. Declare one at ${join("lenses", `${id}.md`)} in the workspace, or pass --lens-file <path>.`
|
|
2649
|
+
);
|
|
2650
|
+
}
|
|
2651
|
+
async function resolveLensFile(path6) {
|
|
2652
|
+
if (!existsSync(path6)) {
|
|
2653
|
+
throw new LensError(`--lens-file not found: ${path6}`);
|
|
2654
|
+
}
|
|
2655
|
+
const fallbackId = basename(path6).replace(/\.[^.]+$/, "");
|
|
2656
|
+
return parseLensDoc(await readFile(path6, "utf8"), fallbackId);
|
|
2657
|
+
}
|
|
2658
|
+
|
|
2396
2659
|
// src/commands/distill.ts
|
|
2397
2660
|
var SOURCE_FRONTMATTER = z.object({
|
|
2398
2661
|
id: z.string().optional().catch(void 0),
|
|
@@ -2411,7 +2674,7 @@ var DEFAULT_ENGINE = "anthropic-api";
|
|
|
2411
2674
|
async function readEntryLayout(target) {
|
|
2412
2675
|
try {
|
|
2413
2676
|
const raw = await readFile(join(target, "KNOWLEDGE.md"), "utf8");
|
|
2414
|
-
const layout =
|
|
2677
|
+
const layout = matter3(raw).data?.metadata;
|
|
2415
2678
|
const corpus = layout?.["corpus"];
|
|
2416
2679
|
const v = corpus?.["entryLayout"];
|
|
2417
2680
|
return v === "flat" || v === "dated" ? v : void 0;
|
|
@@ -2445,7 +2708,7 @@ var DISTILLER_ENGINES = {
|
|
|
2445
2708
|
])
|
|
2446
2709
|
)
|
|
2447
2710
|
};
|
|
2448
|
-
function
|
|
2711
|
+
function parse4(args) {
|
|
2449
2712
|
const out = {
|
|
2450
2713
|
workspace: void 0,
|
|
2451
2714
|
sourceId: void 0,
|
|
@@ -2453,7 +2716,9 @@ function parse3(args) {
|
|
|
2453
2716
|
throttleMs: 1e3,
|
|
2454
2717
|
model: void 0,
|
|
2455
2718
|
engine: DEFAULT_ENGINE,
|
|
2456
|
-
lang: void 0
|
|
2719
|
+
lang: void 0,
|
|
2720
|
+
lens: void 0,
|
|
2721
|
+
lensFile: void 0
|
|
2457
2722
|
};
|
|
2458
2723
|
for (let i = 0; i < args.length; i++) {
|
|
2459
2724
|
const a = args[i];
|
|
@@ -2483,6 +2748,12 @@ function parse3(args) {
|
|
|
2483
2748
|
case "--lang":
|
|
2484
2749
|
out.lang = next();
|
|
2485
2750
|
break;
|
|
2751
|
+
case "--lens":
|
|
2752
|
+
out.lens = next();
|
|
2753
|
+
break;
|
|
2754
|
+
case "--lens-file":
|
|
2755
|
+
out.lensFile = next();
|
|
2756
|
+
break;
|
|
2486
2757
|
default:
|
|
2487
2758
|
if (!a.startsWith("-") && out.workspace === void 0) out.workspace = a;
|
|
2488
2759
|
}
|
|
@@ -2500,16 +2771,18 @@ async function readSources(root) {
|
|
|
2500
2771
|
const out = [];
|
|
2501
2772
|
for (const e of entries) {
|
|
2502
2773
|
if (!e.isFile() || !e.name.endsWith(".md")) continue;
|
|
2503
|
-
const
|
|
2774
|
+
const path6 = join(e.parentPath, e.name);
|
|
2504
2775
|
try {
|
|
2505
|
-
const parsed =
|
|
2776
|
+
const parsed = matter3(await readFile(path6, "utf-8"));
|
|
2506
2777
|
const fm = SOURCE_FRONTMATTER.parse(parsed.data);
|
|
2507
2778
|
if (!fm.id || !parsed.content.trim()) continue;
|
|
2779
|
+
const body = parsed.content.trim();
|
|
2508
2780
|
out.push({
|
|
2509
|
-
path:
|
|
2781
|
+
path: path6,
|
|
2510
2782
|
id: fm.id,
|
|
2511
2783
|
title: fm.title ?? fm.id,
|
|
2512
|
-
body
|
|
2784
|
+
body,
|
|
2785
|
+
contentHash: "sha256:" + createHash("sha256").update(body).digest("hex"),
|
|
2513
2786
|
...fm.tags ? { tags: fm.tags } : {},
|
|
2514
2787
|
...fm.metadata?.corpus?.access ? { access: fm.metadata.corpus.access } : {},
|
|
2515
2788
|
...fm.metadata?.corpus?.domain ? { domain: fm.metadata.corpus.domain } : {}
|
|
@@ -2532,7 +2805,7 @@ async function scanDistilledSourceIds(root) {
|
|
|
2532
2805
|
if (!e.isFile() || !e.name.endsWith(".md")) continue;
|
|
2533
2806
|
try {
|
|
2534
2807
|
const fm = ENTRY_SOURCES_FRONTMATTER.parse(
|
|
2535
|
-
|
|
2808
|
+
matter3(await readFile(join(e.parentPath, e.name), "utf-8")).data
|
|
2536
2809
|
);
|
|
2537
2810
|
if (fm.sources) for (const s of fm.sources) seen.add(s);
|
|
2538
2811
|
} catch {
|
|
@@ -2541,29 +2814,77 @@ async function scanDistilledSourceIds(root) {
|
|
|
2541
2814
|
return seen;
|
|
2542
2815
|
}
|
|
2543
2816
|
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2544
|
-
|
|
2545
|
-
|
|
2817
|
+
function applyLens(src, lens) {
|
|
2818
|
+
return {
|
|
2819
|
+
...src,
|
|
2820
|
+
instruction: lens.prompt,
|
|
2821
|
+
...lens.kinds ? { kinds: lens.kinds } : {},
|
|
2822
|
+
aspect: lensAspect(lens)
|
|
2823
|
+
};
|
|
2824
|
+
}
|
|
2825
|
+
async function runDistill(args, deps = {}) {
|
|
2826
|
+
const parsed = parse4(args);
|
|
2546
2827
|
const target = resolveWorkspacePath(parsed.workspace);
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
return fail(
|
|
2550
|
-
`unknown --engine "${parsed.engine}". Valid: ${Object.keys(DISTILLER_ENGINES).join(", ")}.`,
|
|
2551
|
-
2
|
|
2552
|
-
);
|
|
2828
|
+
if (parsed.lens && parsed.lensFile) {
|
|
2829
|
+
return fail("--lens and --lens-file are mutually exclusive.", 2);
|
|
2553
2830
|
}
|
|
2554
|
-
|
|
2555
|
-
if (
|
|
2556
|
-
|
|
2831
|
+
let lens;
|
|
2832
|
+
if (parsed.lens || parsed.lensFile) {
|
|
2833
|
+
try {
|
|
2834
|
+
lens = parsed.lensFile ? await resolveLensFile(parsed.lensFile) : await resolveLens(parsed.lens, target);
|
|
2835
|
+
} catch (e) {
|
|
2836
|
+
if (e instanceof LensError) return fail(e.message, 2);
|
|
2837
|
+
throw e;
|
|
2838
|
+
}
|
|
2557
2839
|
}
|
|
2840
|
+
const usage = createUsageSink({ runName: basename(target) });
|
|
2841
|
+
let distiller;
|
|
2842
|
+
let engineLabel;
|
|
2843
|
+
if (deps.distiller) {
|
|
2844
|
+
distiller = deps.distiller;
|
|
2845
|
+
engineLabel = parsed.engine;
|
|
2846
|
+
} else {
|
|
2847
|
+
const engine = DISTILLER_ENGINES[parsed.engine];
|
|
2848
|
+
if (!engine) {
|
|
2849
|
+
return fail(
|
|
2850
|
+
`unknown --engine "${parsed.engine}". Valid: ${Object.keys(DISTILLER_ENGINES).join(", ")}.`,
|
|
2851
|
+
2
|
|
2852
|
+
);
|
|
2853
|
+
}
|
|
2854
|
+
const apiKey = process.env.ANTHROPIC_API_KEY;
|
|
2855
|
+
if (engine.needsApiKey && !apiKey) {
|
|
2856
|
+
return fail(`distill engine "${engine.id}" needs ANTHROPIC_API_KEY in the environment.`, 2);
|
|
2857
|
+
}
|
|
2858
|
+
distiller = engine.create({
|
|
2859
|
+
...apiKey ? { apiKey } : {},
|
|
2860
|
+
...parsed.model ? { model: parsed.model } : {},
|
|
2861
|
+
onUsage: usage.record,
|
|
2862
|
+
...parsed.lang ? { lang: parsed.lang } : {}
|
|
2863
|
+
});
|
|
2864
|
+
engineLabel = engine.id;
|
|
2865
|
+
}
|
|
2866
|
+
const fs = new NodeFsAdapter({ root: target });
|
|
2558
2867
|
const all = await readSources(target);
|
|
2559
2868
|
if (all.length === 0) return fail("no sources found under sources/ \u2014 run import-web first.", 2);
|
|
2560
|
-
const
|
|
2561
|
-
|
|
2869
|
+
const index = new DistillIndex({ fs });
|
|
2870
|
+
let pool;
|
|
2871
|
+
if (parsed.sourceId) {
|
|
2872
|
+
pool = all.filter((s) => s.id === parsed.sourceId);
|
|
2873
|
+
} else if (lens) {
|
|
2874
|
+
pool = [];
|
|
2875
|
+
for (const s of all) {
|
|
2876
|
+
if (!await index.isDistilled(s.id, s.contentHash, lens.id)) pool.push(s);
|
|
2877
|
+
}
|
|
2878
|
+
} else {
|
|
2879
|
+
const done = await scanDistilledSourceIds(target);
|
|
2880
|
+
pool = all.filter((s) => !done.has(s.id));
|
|
2881
|
+
}
|
|
2562
2882
|
const batch = parsed.max !== void 0 ? pool.slice(0, parsed.max) : pool;
|
|
2563
2883
|
process.stdout.write(
|
|
2564
2884
|
`distill \u2192 ${target}
|
|
2565
|
-
engine: ${
|
|
2566
|
-
|
|
2885
|
+
engine: ${engineLabel}
|
|
2886
|
+
` + (lens ? ` lens: ${lens.id} (aspect:${lensAspect(lens)})
|
|
2887
|
+
` : "") + ` sources: ${all.length} total \xB7 ${all.length - pool.length} already distilled \xB7 ${pool.length} to do
|
|
2567
2888
|
this run: ${batch.length}${parsed.max !== void 0 ? ` (--max ${parsed.max})` : ""}
|
|
2568
2889
|
`
|
|
2569
2890
|
);
|
|
@@ -2571,30 +2892,37 @@ async function runDistill(args) {
|
|
|
2571
2892
|
process.stdout.write(" nothing to do.\n");
|
|
2572
2893
|
return 0;
|
|
2573
2894
|
}
|
|
2574
|
-
const usage = createUsageSink({ runName: basename(target) });
|
|
2575
2895
|
const layout = await readEntryLayout(target);
|
|
2576
2896
|
const runner = new DistillRunner({
|
|
2577
|
-
fs
|
|
2897
|
+
fs,
|
|
2578
2898
|
clock: systemClock,
|
|
2579
2899
|
...layout ? { layout } : {},
|
|
2580
|
-
distiller
|
|
2581
|
-
...apiKey ? { apiKey } : {},
|
|
2582
|
-
...parsed.model ? { model: parsed.model } : {},
|
|
2583
|
-
onUsage: usage.record,
|
|
2584
|
-
...parsed.lang ? { lang: parsed.lang } : {}
|
|
2585
|
-
})
|
|
2900
|
+
distiller
|
|
2586
2901
|
});
|
|
2587
2902
|
let totalEntries = 0;
|
|
2588
2903
|
for (let i = 0; i < batch.length; i++) {
|
|
2589
|
-
const
|
|
2904
|
+
const raw = batch[i];
|
|
2905
|
+
const src = lens ? applyLens(raw, lens) : raw;
|
|
2590
2906
|
if (i > 0 && parsed.throttleMs > 0) await sleep(parsed.throttleMs);
|
|
2591
2907
|
try {
|
|
2592
2908
|
const report = await runner.run(src);
|
|
2593
2909
|
totalEntries += report.entryPaths.length;
|
|
2594
|
-
|
|
2910
|
+
if (lens) {
|
|
2911
|
+
await index.record({
|
|
2912
|
+
sourceId: raw.id,
|
|
2913
|
+
lensId: lens.id,
|
|
2914
|
+
title: raw.title,
|
|
2915
|
+
distilledAt: systemClock.now().toISOString(),
|
|
2916
|
+
engine: engineLabel,
|
|
2917
|
+
contentHash: raw.contentHash,
|
|
2918
|
+
entryCount: report.entryPaths.length,
|
|
2919
|
+
...report.entryPaths.length ? { entryPaths: report.entryPaths } : {}
|
|
2920
|
+
});
|
|
2921
|
+
}
|
|
2922
|
+
process.stdout.write(` \u2713 ${raw.id} \u2192 ${report.entryPaths.length} entries
|
|
2595
2923
|
`);
|
|
2596
2924
|
} catch (e) {
|
|
2597
|
-
process.stdout.write(` ! ${
|
|
2925
|
+
process.stdout.write(` ! ${raw.id} \u2014 ${e instanceof Error ? e.message : String(e)}
|
|
2598
2926
|
`);
|
|
2599
2927
|
}
|
|
2600
2928
|
}
|
|
@@ -2681,7 +3009,12 @@ async function runReport(args) {
|
|
|
2681
3009
|
}
|
|
2682
3010
|
function loadReportConfig(configPath) {
|
|
2683
3011
|
const raw = readFileSync(path.resolve(process.cwd(), configPath), "utf8");
|
|
2684
|
-
|
|
3012
|
+
const parsed = JSON.parse(raw);
|
|
3013
|
+
for (const warning of lintReportConfig(parsed)) {
|
|
3014
|
+
process.stderr.write(`corpus report: ${warning}
|
|
3015
|
+
`);
|
|
3016
|
+
}
|
|
3017
|
+
return reportConfigSchema.parse(parsed);
|
|
2685
3018
|
}
|
|
2686
3019
|
async function runReportPacks(args) {
|
|
2687
3020
|
let dataset;
|
|
@@ -3162,12 +3495,20 @@ Commands:
|
|
|
3162
3495
|
(--preset seeds a full vertical; --list shows them)
|
|
3163
3496
|
validate [path] JSON Schema check across every AIP file
|
|
3164
3497
|
lint [path] Run lints declared in KNOWLEDGE.md
|
|
3498
|
+
verify [path] --facets a,b,... [--thin 8] [--apply] [--contaminated]
|
|
3499
|
+
SOP \u2464b: coverage per facet tag +
|
|
3500
|
+
quarantine of self-flagged bad scrapes.
|
|
3501
|
+
--apply moves flagged entries to
|
|
3502
|
+
demoted/ (reversible); --contaminated
|
|
3503
|
+
(with --apply) also demotes siblings
|
|
3504
|
+
sharing a poisoned source.
|
|
3165
3505
|
events:emit <kind> --payload <json> [path]
|
|
3166
3506
|
Append an event to _log.md
|
|
3167
3507
|
events:tail [path] Print _log.md
|
|
3168
|
-
discover <topic> [path] [--max N --channels web,youtube,social --lang l --tags t --import]
|
|
3508
|
+
discover <topic> [path] [--max N --channels web,youtube,social --lang l --tags t --import --fresh]
|
|
3169
3509
|
Fan out across channels (web search + YouTube +
|
|
3170
|
-
social), dedup,
|
|
3510
|
+
social), dedup, merge into urls.discovered.txt
|
|
3511
|
+
(union with previous runs; --fresh overwrites).
|
|
3171
3512
|
Web: auto-picks first available key (SERPER /
|
|
3172
3513
|
EXA / TAVILY / GOOGLE_SEARCH). YouTube: yt-dlp
|
|
3173
3514
|
flat-playlist. --import chains import-web.
|
|
@@ -3186,9 +3527,16 @@ Commands:
|
|
|
3186
3527
|
walled/JS pages, ahead of plain readability.
|
|
3187
3528
|
--diarize: AssemblyAI speaker labels (interviews).
|
|
3188
3529
|
distill [path] [--source id --max n --throttle ms --model m --lang l --engine e]
|
|
3530
|
+
[--lens <id> | --lens-file <path>]
|
|
3189
3531
|
Distill raw sources \u2192 refined entries
|
|
3190
3532
|
(principle/pattern/\u2026) with sources:[id] provenance.
|
|
3191
3533
|
Resumable: skips already-distilled sources.
|
|
3534
|
+
--lens reads every source THROUGH one aspect:
|
|
3535
|
+
its prompt drives extraction, its kinds constrain
|
|
3536
|
+
output, entries are tagged aspect:<value>, and the
|
|
3537
|
+
resume ledger keys by (source, lens). Resolves a
|
|
3538
|
+
workspace lenses/<id>.md (override) or a built-in
|
|
3539
|
+
(craft); --lens-file points at an ad-hoc lens doc.
|
|
3192
3540
|
knowledge [path] --tags a,b [--kind k --access scope --max n]
|
|
3193
3541
|
Preview what a skill's knowledge: binding resolves to
|
|
3194
3542
|
\u2014 refined entries + their provenance (filesystem).
|
|
@@ -3229,6 +3577,8 @@ async function main(argv2) {
|
|
|
3229
3577
|
return await runValidate(rest);
|
|
3230
3578
|
case "lint":
|
|
3231
3579
|
return await runLint(rest);
|
|
3580
|
+
case "verify":
|
|
3581
|
+
return await runVerify(rest);
|
|
3232
3582
|
case "events:emit":
|
|
3233
3583
|
return await runEventsEmit(rest);
|
|
3234
3584
|
case "events:tail":
|