@agentproto/corpus-cli 0.4.0 → 0.6.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/cli.mjs CHANGED
@@ -5,10 +5,10 @@ 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 matter2 from 'gray-matter';
10
+ import { buildDistillPrompt, parseItems, isRefinedKind, SyncRunner, resolveKnowledge, DistillIndex, DistillRunner, systemClock, WebImporter, ImporterRunner, CorpusEventEmitter, CorpusWorkspaceReader, CorpusLinter, CorpusValidator, ReadOnlyFs, normalizeLanguageTag, CodeImporter, PrReviewImporter, 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';
@@ -404,8 +404,8 @@ function resolveWorkspacePath(arg) {
404
404
  if (!arg) return process.cwd();
405
405
  return path.resolve(process.cwd(), arg);
406
406
  }
407
- function fail(msg5, code = 1) {
408
- process.stderr.write(`corpus: ${msg5}
407
+ function fail(msg8, code = 1) {
408
+ process.stderr.write(`corpus: ${msg8}
409
409
  `);
410
410
  return code;
411
411
  }
@@ -1868,7 +1868,7 @@ async function scanIngestedUrls(workspaceRoot) {
1868
1868
  if (!e.isFile() || !e.name.endsWith(".md")) continue;
1869
1869
  try {
1870
1870
  const raw = await readFile(join(e.parentPath, e.name), "utf-8");
1871
- const fm = SOURCE_URL_FRONTMATTER.parse(matter2(raw).data);
1871
+ const fm = SOURCE_URL_FRONTMATTER.parse(matter3(raw).data);
1872
1872
  const url = fm.metadata?.corpus?.originalUrl ?? fm.metadata?.corpus?.importerSourceUrl;
1873
1873
  if (url) seen.add(url);
1874
1874
  } catch {
@@ -2018,6 +2018,453 @@ function msg3(e) {
2018
2018
  return e instanceof Error ? e.message : String(e);
2019
2019
  }
2020
2020
  function parse3(args) {
2021
+ const out = {
2022
+ workspace: void 0,
2023
+ root: void 0,
2024
+ include: [],
2025
+ granularity: "file",
2026
+ max: void 0,
2027
+ tags: [],
2028
+ lang: void 0,
2029
+ importerId: "code",
2030
+ dryRun: false
2031
+ };
2032
+ for (let i = 0; i < args.length; i++) {
2033
+ const a = args[i];
2034
+ const next = () => args[++i];
2035
+ switch (a) {
2036
+ case "--root":
2037
+ out.root = next();
2038
+ break;
2039
+ case "--include": {
2040
+ const v = next();
2041
+ if (v) out.include.push(v);
2042
+ break;
2043
+ }
2044
+ case "--granularity": {
2045
+ const v = next();
2046
+ if (v === "file" || v === "module") out.granularity = v;
2047
+ break;
2048
+ }
2049
+ case "--max": {
2050
+ const v = next();
2051
+ if (v) out.max = Number(v);
2052
+ break;
2053
+ }
2054
+ case "--tags": {
2055
+ const v = next();
2056
+ if (v) out.tags.push(...v.split(",").map((s) => s.trim()).filter(Boolean));
2057
+ break;
2058
+ }
2059
+ case "--lang":
2060
+ out.lang = next();
2061
+ break;
2062
+ case "--importer-id":
2063
+ out.importerId = next() ?? "code";
2064
+ break;
2065
+ case "--dry-run":
2066
+ out.dryRun = true;
2067
+ break;
2068
+ default:
2069
+ if (!a.startsWith("-") && out.workspace === void 0) out.workspace = a;
2070
+ }
2071
+ }
2072
+ return out;
2073
+ }
2074
+ async function runImportCode(args) {
2075
+ const parsed = parse3(args);
2076
+ const target = resolveWorkspacePath(parsed.workspace);
2077
+ if (!parsed.root) {
2078
+ return fail("import-code requires --root <path> (workspace-relative source tree).", 2);
2079
+ }
2080
+ const fs = new NodeFsAdapter({ root: target });
2081
+ const importer = new CodeImporter({ fs });
2082
+ const importerTarget = {
2083
+ importerId: parsed.importerId,
2084
+ config: {
2085
+ rootPath: parsed.root,
2086
+ ...parsed.include.length ? { include: parsed.include } : {},
2087
+ granularity: parsed.granularity,
2088
+ ...parsed.max !== void 0 ? { maxFiles: parsed.max } : {},
2089
+ ...parsed.tags.length ? { tags: parsed.tags } : {},
2090
+ ...parsed.lang ? { language: parsed.lang } : {}
2091
+ }
2092
+ };
2093
+ const plan = ` workspace: ${target}
2094
+ root: ${parsed.root}
2095
+ include: ${parsed.include.length ? parsed.include.join(", ") : "**/*.ts (default)"}
2096
+ granularity: ${parsed.granularity}
2097
+ ` + (parsed.max !== void 0 ? ` max: ${parsed.max}
2098
+ ` : "");
2099
+ if (parsed.dryRun) {
2100
+ process.stdout.write(`import-code (dry run)
2101
+ ${plan}`);
2102
+ let count = 0;
2103
+ try {
2104
+ for await (const source of importer.enumerate(importerTarget)) {
2105
+ if (count < 20) process.stdout.write(` - ${source.slug} (${source.title})
2106
+ `);
2107
+ count++;
2108
+ }
2109
+ } catch (e) {
2110
+ return fail(`enumerate failed: ${msg4(e)}`, 1);
2111
+ }
2112
+ if (count > 20) process.stdout.write(` \u2026 +${count - 20} more
2113
+ `);
2114
+ process.stdout.write(` units: ${count}
2115
+ `);
2116
+ return 0;
2117
+ }
2118
+ process.stdout.write(`import-code
2119
+ ${plan}`);
2120
+ const runner = new ImporterRunner({
2121
+ // fs rooted AT the workspace → corpus paths are relative to it, so
2122
+ // workspacePath is "" (root), NOT the absolute target.
2123
+ fs,
2124
+ clock: systemClock,
2125
+ identity: new OsIdentityAdapter({ workspaceRoot: target }),
2126
+ workspacePath: ""
2127
+ });
2128
+ let report;
2129
+ try {
2130
+ report = await runner.run(importer, importerTarget);
2131
+ } catch (e) {
2132
+ return fail(`import failed: ${msg4(e)}`, 1);
2133
+ }
2134
+ process.stdout.write(
2135
+ `import-code \u2192 ${target}
2136
+ batch: ${report.batchId}
2137
+ archived: ${report.archivedSlugs.length}
2138
+ duplicates: ${report.duplicateSlugs.length}
2139
+ candidates: ${report.candidateIds.length}
2140
+ `
2141
+ );
2142
+ for (const w of report.warnings.slice(0, 20)) process.stdout.write(` ! ${w}
2143
+ `);
2144
+ process.stdout.write(
2145
+ `
2146
+ Notes-only: this archives code notes as knowledge sources. Symbol/caller/callee
2147
+ graph construction is the code-brain subsystem's job, not this importer.
2148
+ `
2149
+ );
2150
+ return 0;
2151
+ }
2152
+ function msg4(e) {
2153
+ return e instanceof Error ? e.message : String(e);
2154
+ }
2155
+ var execFileAsync4 = promisify(execFile);
2156
+ var GH_ACTOR = z.object({ login: z.string().optional(), name: z.string().optional() }).loose();
2157
+ var GH_PR_LIST_ITEM = z.object({ number: z.number() }).loose();
2158
+ var GH_PR_LIST = z.array(GH_PR_LIST_ITEM);
2159
+ var GH_COMMENT = z.object({
2160
+ author: GH_ACTOR.nullish(),
2161
+ body: z.string().optional(),
2162
+ path: z.string().optional(),
2163
+ createdAt: z.string().optional(),
2164
+ submittedAt: z.string().optional()
2165
+ }).loose();
2166
+ var GH_FILE = z.object({
2167
+ path: z.string(),
2168
+ additions: z.number().optional(),
2169
+ deletions: z.number().optional()
2170
+ }).loose();
2171
+ var GH_PR_VIEW = z.object({
2172
+ number: z.number(),
2173
+ title: z.string().optional(),
2174
+ body: z.string().optional(),
2175
+ author: GH_ACTOR.nullish(),
2176
+ url: z.string().optional(),
2177
+ state: z.string().optional(),
2178
+ mergedAt: z.string().nullish(),
2179
+ reviews: z.array(GH_COMMENT).optional(),
2180
+ comments: z.array(GH_COMMENT).optional(),
2181
+ reviewRequests: z.array(GH_ACTOR).optional(),
2182
+ additions: z.number().optional(),
2183
+ deletions: z.number().optional(),
2184
+ changedFiles: z.number().optional(),
2185
+ files: z.array(GH_FILE).optional()
2186
+ }).loose();
2187
+ var VIEW_FIELDS = [
2188
+ "number",
2189
+ "title",
2190
+ "body",
2191
+ "author",
2192
+ "url",
2193
+ "state",
2194
+ "mergedAt",
2195
+ "reviews",
2196
+ "comments",
2197
+ "reviewRequests",
2198
+ "additions",
2199
+ "deletions",
2200
+ "changedFiles",
2201
+ "files"
2202
+ ].join(",");
2203
+ var GhPrSourceAdapter = class {
2204
+ run;
2205
+ constructor(opts = {}) {
2206
+ this.run = opts.run ?? defaultGhRunner(opts.ghBin ?? "gh");
2207
+ }
2208
+ async *listPullRequests(query) {
2209
+ const numbers = await this.resolveNumbers(query);
2210
+ for (const n of numbers) {
2211
+ let pr;
2212
+ try {
2213
+ pr = await this.viewPr(query, n);
2214
+ } catch (e) {
2215
+ process.stderr.write(
2216
+ `corpus: skipping ${query.repo}#${n} \u2014 ${msg5(e)}
2217
+ `
2218
+ );
2219
+ continue;
2220
+ }
2221
+ if (pr) yield pr;
2222
+ }
2223
+ }
2224
+ /** Resolve the query to a concrete, capped list of PR numbers. */
2225
+ async resolveNumbers(query) {
2226
+ const cap = query.maxPRs ?? 1e3;
2227
+ if (query.prNumbers && query.prNumbers.length > 0) {
2228
+ return query.prNumbers.slice(0, cap);
2229
+ }
2230
+ const args = [
2231
+ "pr",
2232
+ "list",
2233
+ "--repo",
2234
+ query.repo,
2235
+ "--state",
2236
+ "all",
2237
+ "--limit",
2238
+ String(cap),
2239
+ "--json",
2240
+ "number"
2241
+ ];
2242
+ if (query.since) args.push("--search", `updated:>=${query.since}`);
2243
+ const out = await this.run(args);
2244
+ return GH_PR_LIST.parse(parseJson(out)).map((item) => item.number).sort((a, b) => a - b);
2245
+ }
2246
+ /** Fetch one PR's detail and shape it into a PrDoc, or null if empty. */
2247
+ async viewPr(query, number) {
2248
+ const out = await this.run([
2249
+ "pr",
2250
+ "view",
2251
+ String(number),
2252
+ "--repo",
2253
+ query.repo,
2254
+ "--json",
2255
+ VIEW_FIELDS
2256
+ ]);
2257
+ const v = GH_PR_VIEW.parse(parseJson(out));
2258
+ const reviewComments = toReviewComments([
2259
+ ...v.reviews ?? [],
2260
+ ...v.comments ?? []
2261
+ ]);
2262
+ const reviewers = uniqueLogins([
2263
+ ...(v.reviews ?? []).map((r) => r.author),
2264
+ ...v.reviewRequests ?? []
2265
+ ]);
2266
+ const doc = {
2267
+ number: v.number,
2268
+ title: v.title ?? "",
2269
+ body: v.body ?? "",
2270
+ ...actorLabel(v.author) ? { author: actorLabel(v.author) } : {},
2271
+ ...v.url ? { url: v.url } : {},
2272
+ ...v.state ? { state: v.state.toLowerCase() } : {},
2273
+ ...v.mergedAt ? { mergedAt: v.mergedAt } : {},
2274
+ ...reviewers.length > 0 ? { reviewers } : {},
2275
+ ...reviewComments.length > 0 ? { reviewComments } : {},
2276
+ ...query.includeDiffSummary ? { diffSummary: buildDiffSummary(v) } : {}
2277
+ };
2278
+ return doc;
2279
+ }
2280
+ };
2281
+ function actorLabel(actor) {
2282
+ const label = actor?.login ?? actor?.name;
2283
+ return label && label.length > 0 ? label : void 0;
2284
+ }
2285
+ function toReviewComments(raw) {
2286
+ const out = [];
2287
+ for (const c of raw) {
2288
+ const body = (c.body ?? "").trim();
2289
+ if (!body) continue;
2290
+ const author = actorLabel(c.author);
2291
+ const at = c.submittedAt ?? c.createdAt;
2292
+ out.push({
2293
+ body,
2294
+ ...author ? { author } : {},
2295
+ ...c.path ? { path: c.path } : {},
2296
+ ...at ? { at } : {}
2297
+ });
2298
+ }
2299
+ return out;
2300
+ }
2301
+ function uniqueLogins(actors) {
2302
+ const seen = /* @__PURE__ */ new Set();
2303
+ for (const a of actors) {
2304
+ const label = actorLabel(a);
2305
+ if (label) seen.add(label);
2306
+ }
2307
+ return [...seen];
2308
+ }
2309
+ function buildDiffSummary(v) {
2310
+ const lines = [];
2311
+ for (const f of v.files ?? []) {
2312
+ const add = f.additions ?? 0;
2313
+ const del = f.deletions ?? 0;
2314
+ lines.push(`${f.path} | +${add} -${del}`);
2315
+ }
2316
+ const totals = v.changedFiles !== void 0 ? `${v.changedFiles} files changed, +${v.additions ?? 0} -${v.deletions ?? 0}` : void 0;
2317
+ return [...totals ? [totals] : [], ...lines].join("\n");
2318
+ }
2319
+ function parseJson(out) {
2320
+ const trimmed = out.trim();
2321
+ if (!trimmed) return [];
2322
+ return JSON.parse(trimmed);
2323
+ }
2324
+ function msg5(e) {
2325
+ return e instanceof Error ? e.message : String(e);
2326
+ }
2327
+ function defaultGhRunner(bin) {
2328
+ return async (args) => {
2329
+ const { stdout } = await execFileAsync4(bin, [...args], {
2330
+ maxBuffer: 32 * 1024 * 1024
2331
+ });
2332
+ return stdout;
2333
+ };
2334
+ }
2335
+
2336
+ // src/commands/import-prs.ts
2337
+ function parse4(args) {
2338
+ const out = {
2339
+ workspace: void 0,
2340
+ repo: void 0,
2341
+ prNumbers: [],
2342
+ since: void 0,
2343
+ includeDiff: false,
2344
+ tags: [],
2345
+ lang: void 0,
2346
+ max: void 0,
2347
+ importerId: "pr-review",
2348
+ dryRun: false
2349
+ };
2350
+ for (let i = 0; i < args.length; i++) {
2351
+ const a = args[i];
2352
+ const next = () => args[++i];
2353
+ switch (a) {
2354
+ case "--repo":
2355
+ out.repo = next();
2356
+ break;
2357
+ case "--pr": {
2358
+ const v = next();
2359
+ if (v && Number.isFinite(Number(v))) out.prNumbers.push(Number(v));
2360
+ break;
2361
+ }
2362
+ case "--since":
2363
+ out.since = next();
2364
+ break;
2365
+ case "--include-diff":
2366
+ out.includeDiff = true;
2367
+ break;
2368
+ case "--tags": {
2369
+ const v = next();
2370
+ if (v) out.tags.push(...v.split(",").map((s) => s.trim()).filter(Boolean));
2371
+ break;
2372
+ }
2373
+ case "--lang":
2374
+ out.lang = next();
2375
+ break;
2376
+ case "--max": {
2377
+ const v = next();
2378
+ if (v) out.max = Number(v);
2379
+ break;
2380
+ }
2381
+ case "--importer-id":
2382
+ out.importerId = next() ?? "pr-review";
2383
+ break;
2384
+ case "--dry-run":
2385
+ out.dryRun = true;
2386
+ break;
2387
+ default:
2388
+ if (!a.startsWith("-") && out.workspace === void 0) out.workspace = a;
2389
+ }
2390
+ }
2391
+ return out;
2392
+ }
2393
+ async function runImportPrs(args) {
2394
+ const parsed = parse4(args);
2395
+ const target = resolveWorkspacePath(parsed.workspace);
2396
+ if (!parsed.repo) {
2397
+ return fail("import-prs requires --repo <owner/name> (e.g. --repo agentproto/ts).", 2);
2398
+ }
2399
+ const selection = parsed.prNumbers.length > 0 ? `PRs ${parsed.prNumbers.join(", ")}` : parsed.since ? `updated since ${parsed.since}` : "all PRs";
2400
+ const plan = ` workspace: ${target}
2401
+ repo: ${parsed.repo}
2402
+ select: ${selection}${parsed.max !== void 0 ? ` (--max ${parsed.max})` : ""}
2403
+ diff: ${parsed.includeDiff ? "included" : "omitted"}
2404
+ `;
2405
+ if (parsed.dryRun) {
2406
+ process.stdout.write(`import-prs (dry run)
2407
+ ${plan}`);
2408
+ for (const n of parsed.prNumbers.slice(0, 20)) {
2409
+ process.stdout.write(` - ${parsed.repo}#${n}
2410
+ `);
2411
+ }
2412
+ if (parsed.prNumbers.length > 20) {
2413
+ process.stdout.write(` \u2026 +${parsed.prNumbers.length - 20} more
2414
+ `);
2415
+ }
2416
+ return 0;
2417
+ }
2418
+ process.stdout.write(`import-prs
2419
+ ${plan}`);
2420
+ const importer = new PrReviewImporter({ source: new GhPrSourceAdapter() });
2421
+ const runner = new ImporterRunner({
2422
+ // The fs is rooted AT the workspace, so corpus paths are relative to it —
2423
+ // workspacePath is "" (root), NOT the absolute target.
2424
+ fs: new NodeFsAdapter({ root: target }),
2425
+ clock: systemClock,
2426
+ identity: new OsIdentityAdapter({ workspaceRoot: target }),
2427
+ workspacePath: ""
2428
+ });
2429
+ let report;
2430
+ try {
2431
+ report = await runner.run(importer, {
2432
+ importerId: parsed.importerId,
2433
+ config: {
2434
+ repo: parsed.repo,
2435
+ ...parsed.prNumbers.length > 0 ? { prNumbers: parsed.prNumbers } : {},
2436
+ ...parsed.since ? { since: parsed.since } : {},
2437
+ ...parsed.includeDiff ? { includeDiffSummary: true } : {},
2438
+ ...parsed.tags.length ? { tags: parsed.tags } : {},
2439
+ ...parsed.lang ? { language: parsed.lang } : {},
2440
+ ...parsed.max !== void 0 ? { maxPRs: parsed.max } : {}
2441
+ }
2442
+ });
2443
+ } catch (e) {
2444
+ return fail(`import failed: ${msg6(e)}`, 1);
2445
+ }
2446
+ process.stdout.write(
2447
+ `import-prs \u2192 ${target}
2448
+ batch: ${report.batchId}
2449
+ archived: ${report.archivedSlugs.length}
2450
+ duplicates: ${report.duplicateSlugs.length}
2451
+ candidates: ${report.candidateIds.length}
2452
+ `
2453
+ );
2454
+ for (const w of report.warnings.slice(0, 20)) process.stdout.write(` ! ${w}
2455
+ `);
2456
+ process.stdout.write(
2457
+ `
2458
+ Next: review candidates, then distill them \u2014 distillation turns the raw PR
2459
+ sources into refined knowledge.entry/v1 (pattern/critique/summary).
2460
+ `
2461
+ );
2462
+ return 0;
2463
+ }
2464
+ function msg6(e) {
2465
+ return e instanceof Error ? e.message : String(e);
2466
+ }
2467
+ function parse5(args) {
2021
2468
  const out = {
2022
2469
  topic: void 0,
2023
2470
  outputPath: void 0,
@@ -2192,7 +2639,7 @@ async function readExistingUrls(outFile) {
2192
2639
  }
2193
2640
  }
2194
2641
  async function runDiscover(args) {
2195
- const parsed = parse3(args);
2642
+ const parsed = parse5(args);
2196
2643
  if (!parsed.topic) {
2197
2644
  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);
2198
2645
  }
@@ -2571,6 +3018,91 @@ usage \u2014 ${records.length} metered call(s):
2571
3018
  };
2572
3019
  }
2573
3020
 
3021
+ // src/lenses/builtin.ts
3022
+ var CRAFT_LENS = {
3023
+ id: "craft",
3024
+ label: "Writing craft",
3025
+ aspect: "craft",
3026
+ mode: "log",
3027
+ // The distiller emits {kind,title,body,...}; a craft move is a technique
3028
+ // (pattern), a rule (principle), a shallow default it avoids (critique), or a
3029
+ // specific instance (example). "summary" is dropped — a summary is topic
3030
+ // content, not a transferable craft move.
3031
+ kinds: ["pattern", "principle", "critique", "example"],
3032
+ prompt: [
3033
+ "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.",
3034
+ "",
3035
+ "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.",
3036
+ "",
3037
+ "For each move:",
3038
+ '- kind: "pattern" for a technique, "principle" for a rule, "critique" for a shallow/generic default the move avoids, "example" for a specific instance.',
3039
+ '- title: name the move crisply and imperatively (e.g. "Delay the thesis until after a concrete image").',
3040
+ "- 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)."
3041
+ ].join("\n")
3042
+ };
3043
+ var BUILTIN_LENSES = {
3044
+ [CRAFT_LENS.id]: CRAFT_LENS
3045
+ };
3046
+ function builtinLensIds() {
3047
+ return Object.keys(BUILTIN_LENSES);
3048
+ }
3049
+
3050
+ // src/lenses/resolve.ts
3051
+ var LensError = class extends Error {
3052
+ constructor(message) {
3053
+ super(message);
3054
+ this.name = "LensError";
3055
+ }
3056
+ };
3057
+ var LENS_FRONTMATTER = z.object({
3058
+ id: z.string().optional().catch(void 0),
3059
+ label: z.string().optional().catch(void 0),
3060
+ aspect: z.string().optional().catch(void 0),
3061
+ prompt: z.string().optional().catch(void 0),
3062
+ mode: z.string().optional().catch(void 0),
3063
+ kinds: z.array(z.string()).optional().catch(void 0),
3064
+ synthesisPath: z.string().optional().catch(void 0)
3065
+ }).loose();
3066
+ function parseLensDoc(raw, fallbackId) {
3067
+ const parsed = matter3(raw);
3068
+ const fm = LENS_FRONTMATTER.parse(parsed.data);
3069
+ const prompt = (parsed.content.trim() || fm.prompt?.trim()) ?? "";
3070
+ if (!prompt) {
3071
+ throw new LensError(
3072
+ `lens "${fm.id ?? fallbackId}" has no prompt \u2014 put the extraction instruction in the markdown body or a "prompt:" frontmatter key.`
3073
+ );
3074
+ }
3075
+ const kinds = (fm.kinds ?? []).filter(isRefinedKind);
3076
+ const mode = fm.mode === "synthesis" ? "synthesis" : "log";
3077
+ return {
3078
+ id: fm.id ?? fallbackId,
3079
+ label: fm.label ?? fm.id ?? fallbackId,
3080
+ prompt,
3081
+ mode,
3082
+ ...fm.aspect ? { aspect: fm.aspect } : {},
3083
+ ...kinds.length > 0 ? { kinds } : {},
3084
+ ...fm.synthesisPath ? { synthesisPath: fm.synthesisPath } : {}
3085
+ };
3086
+ }
3087
+ async function resolveLens(id, workspaceRoot) {
3088
+ const wsPath = join(workspaceRoot, "lenses", `${id}.md`);
3089
+ if (existsSync(wsPath)) {
3090
+ return parseLensDoc(await readFile(wsPath, "utf8"), id);
3091
+ }
3092
+ const builtin = BUILTIN_LENSES[id];
3093
+ if (builtin) return builtin;
3094
+ throw new LensError(
3095
+ `unknown lens "${id}". Built-in: ${builtinLensIds().join(", ") || "(none)"}. Declare one at ${join("lenses", `${id}.md`)} in the workspace, or pass --lens-file <path>.`
3096
+ );
3097
+ }
3098
+ async function resolveLensFile(path6) {
3099
+ if (!existsSync(path6)) {
3100
+ throw new LensError(`--lens-file not found: ${path6}`);
3101
+ }
3102
+ const fallbackId = basename(path6).replace(/\.[^.]+$/, "");
3103
+ return parseLensDoc(await readFile(path6, "utf8"), fallbackId);
3104
+ }
3105
+
2574
3106
  // src/commands/distill.ts
2575
3107
  var SOURCE_FRONTMATTER = z.object({
2576
3108
  id: z.string().optional().catch(void 0),
@@ -2589,7 +3121,7 @@ var DEFAULT_ENGINE = "anthropic-api";
2589
3121
  async function readEntryLayout(target) {
2590
3122
  try {
2591
3123
  const raw = await readFile(join(target, "KNOWLEDGE.md"), "utf8");
2592
- const layout = matter2(raw).data?.metadata;
3124
+ const layout = matter3(raw).data?.metadata;
2593
3125
  const corpus = layout?.["corpus"];
2594
3126
  const v = corpus?.["entryLayout"];
2595
3127
  return v === "flat" || v === "dated" ? v : void 0;
@@ -2623,7 +3155,7 @@ var DISTILLER_ENGINES = {
2623
3155
  ])
2624
3156
  )
2625
3157
  };
2626
- function parse4(args) {
3158
+ function parse6(args) {
2627
3159
  const out = {
2628
3160
  workspace: void 0,
2629
3161
  sourceId: void 0,
@@ -2631,7 +3163,9 @@ function parse4(args) {
2631
3163
  throttleMs: 1e3,
2632
3164
  model: void 0,
2633
3165
  engine: DEFAULT_ENGINE,
2634
- lang: void 0
3166
+ lang: void 0,
3167
+ lens: void 0,
3168
+ lensFile: void 0
2635
3169
  };
2636
3170
  for (let i = 0; i < args.length; i++) {
2637
3171
  const a = args[i];
@@ -2661,6 +3195,12 @@ function parse4(args) {
2661
3195
  case "--lang":
2662
3196
  out.lang = next();
2663
3197
  break;
3198
+ case "--lens":
3199
+ out.lens = next();
3200
+ break;
3201
+ case "--lens-file":
3202
+ out.lensFile = next();
3203
+ break;
2664
3204
  default:
2665
3205
  if (!a.startsWith("-") && out.workspace === void 0) out.workspace = a;
2666
3206
  }
@@ -2680,14 +3220,16 @@ async function readSources(root) {
2680
3220
  if (!e.isFile() || !e.name.endsWith(".md")) continue;
2681
3221
  const path6 = join(e.parentPath, e.name);
2682
3222
  try {
2683
- const parsed = matter2(await readFile(path6, "utf-8"));
3223
+ const parsed = matter3(await readFile(path6, "utf-8"));
2684
3224
  const fm = SOURCE_FRONTMATTER.parse(parsed.data);
2685
3225
  if (!fm.id || !parsed.content.trim()) continue;
3226
+ const body = parsed.content.trim();
2686
3227
  out.push({
2687
3228
  path: path6,
2688
3229
  id: fm.id,
2689
3230
  title: fm.title ?? fm.id,
2690
- body: parsed.content.trim(),
3231
+ body,
3232
+ contentHash: "sha256:" + createHash("sha256").update(body).digest("hex"),
2691
3233
  ...fm.tags ? { tags: fm.tags } : {},
2692
3234
  ...fm.metadata?.corpus?.access ? { access: fm.metadata.corpus.access } : {},
2693
3235
  ...fm.metadata?.corpus?.domain ? { domain: fm.metadata.corpus.domain } : {}
@@ -2710,7 +3252,7 @@ async function scanDistilledSourceIds(root) {
2710
3252
  if (!e.isFile() || !e.name.endsWith(".md")) continue;
2711
3253
  try {
2712
3254
  const fm = ENTRY_SOURCES_FRONTMATTER.parse(
2713
- matter2(await readFile(join(e.parentPath, e.name), "utf-8")).data
3255
+ matter3(await readFile(join(e.parentPath, e.name), "utf-8")).data
2714
3256
  );
2715
3257
  if (fm.sources) for (const s of fm.sources) seen.add(s);
2716
3258
  } catch {
@@ -2719,29 +3261,77 @@ async function scanDistilledSourceIds(root) {
2719
3261
  return seen;
2720
3262
  }
2721
3263
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
2722
- async function runDistill(args) {
2723
- const parsed = parse4(args);
3264
+ function applyLens(src, lens) {
3265
+ return {
3266
+ ...src,
3267
+ instruction: lens.prompt,
3268
+ ...lens.kinds ? { kinds: lens.kinds } : {},
3269
+ aspect: lensAspect(lens)
3270
+ };
3271
+ }
3272
+ async function runDistill(args, deps = {}) {
3273
+ const parsed = parse6(args);
2724
3274
  const target = resolveWorkspacePath(parsed.workspace);
2725
- const engine = DISTILLER_ENGINES[parsed.engine];
2726
- if (!engine) {
2727
- return fail(
2728
- `unknown --engine "${parsed.engine}". Valid: ${Object.keys(DISTILLER_ENGINES).join(", ")}.`,
2729
- 2
2730
- );
3275
+ if (parsed.lens && parsed.lensFile) {
3276
+ return fail("--lens and --lens-file are mutually exclusive.", 2);
2731
3277
  }
2732
- const apiKey = process.env.ANTHROPIC_API_KEY;
2733
- if (engine.needsApiKey && !apiKey) {
2734
- return fail(`distill engine "${engine.id}" needs ANTHROPIC_API_KEY in the environment.`, 2);
3278
+ let lens;
3279
+ if (parsed.lens || parsed.lensFile) {
3280
+ try {
3281
+ lens = parsed.lensFile ? await resolveLensFile(parsed.lensFile) : await resolveLens(parsed.lens, target);
3282
+ } catch (e) {
3283
+ if (e instanceof LensError) return fail(e.message, 2);
3284
+ throw e;
3285
+ }
3286
+ }
3287
+ const usage = createUsageSink({ runName: basename(target) });
3288
+ let distiller;
3289
+ let engineLabel;
3290
+ if (deps.distiller) {
3291
+ distiller = deps.distiller;
3292
+ engineLabel = parsed.engine;
3293
+ } else {
3294
+ const engine = DISTILLER_ENGINES[parsed.engine];
3295
+ if (!engine) {
3296
+ return fail(
3297
+ `unknown --engine "${parsed.engine}". Valid: ${Object.keys(DISTILLER_ENGINES).join(", ")}.`,
3298
+ 2
3299
+ );
3300
+ }
3301
+ const apiKey = process.env.ANTHROPIC_API_KEY;
3302
+ if (engine.needsApiKey && !apiKey) {
3303
+ return fail(`distill engine "${engine.id}" needs ANTHROPIC_API_KEY in the environment.`, 2);
3304
+ }
3305
+ distiller = engine.create({
3306
+ ...apiKey ? { apiKey } : {},
3307
+ ...parsed.model ? { model: parsed.model } : {},
3308
+ onUsage: usage.record,
3309
+ ...parsed.lang ? { lang: parsed.lang } : {}
3310
+ });
3311
+ engineLabel = engine.id;
2735
3312
  }
3313
+ const fs = new NodeFsAdapter({ root: target });
2736
3314
  const all = await readSources(target);
2737
3315
  if (all.length === 0) return fail("no sources found under sources/ \u2014 run import-web first.", 2);
2738
- const done = await scanDistilledSourceIds(target);
2739
- const pool = parsed.sourceId ? all.filter((s) => s.id === parsed.sourceId) : all.filter((s) => !done.has(s.id));
3316
+ const index = new DistillIndex({ fs });
3317
+ let pool;
3318
+ if (parsed.sourceId) {
3319
+ pool = all.filter((s) => s.id === parsed.sourceId);
3320
+ } else if (lens) {
3321
+ pool = [];
3322
+ for (const s of all) {
3323
+ if (!await index.isDistilled(s.id, s.contentHash, lens.id)) pool.push(s);
3324
+ }
3325
+ } else {
3326
+ const done = await scanDistilledSourceIds(target);
3327
+ pool = all.filter((s) => !done.has(s.id));
3328
+ }
2740
3329
  const batch = parsed.max !== void 0 ? pool.slice(0, parsed.max) : pool;
2741
3330
  process.stdout.write(
2742
3331
  `distill \u2192 ${target}
2743
- engine: ${engine.id}
2744
- sources: ${all.length} total \xB7 ${all.length - pool.length} already distilled \xB7 ${pool.length} to do
3332
+ engine: ${engineLabel}
3333
+ ` + (lens ? ` lens: ${lens.id} (aspect:${lensAspect(lens)})
3334
+ ` : "") + ` sources: ${all.length} total \xB7 ${all.length - pool.length} already distilled \xB7 ${pool.length} to do
2745
3335
  this run: ${batch.length}${parsed.max !== void 0 ? ` (--max ${parsed.max})` : ""}
2746
3336
  `
2747
3337
  );
@@ -2749,30 +3339,37 @@ async function runDistill(args) {
2749
3339
  process.stdout.write(" nothing to do.\n");
2750
3340
  return 0;
2751
3341
  }
2752
- const usage = createUsageSink({ runName: basename(target) });
2753
3342
  const layout = await readEntryLayout(target);
2754
3343
  const runner = new DistillRunner({
2755
- fs: new NodeFsAdapter({ root: target }),
3344
+ fs,
2756
3345
  clock: systemClock,
2757
3346
  ...layout ? { layout } : {},
2758
- distiller: engine.create({
2759
- ...apiKey ? { apiKey } : {},
2760
- ...parsed.model ? { model: parsed.model } : {},
2761
- onUsage: usage.record,
2762
- ...parsed.lang ? { lang: parsed.lang } : {}
2763
- })
3347
+ distiller
2764
3348
  });
2765
3349
  let totalEntries = 0;
2766
3350
  for (let i = 0; i < batch.length; i++) {
2767
- const src = batch[i];
3351
+ const raw = batch[i];
3352
+ const src = lens ? applyLens(raw, lens) : raw;
2768
3353
  if (i > 0 && parsed.throttleMs > 0) await sleep(parsed.throttleMs);
2769
3354
  try {
2770
3355
  const report = await runner.run(src);
2771
3356
  totalEntries += report.entryPaths.length;
2772
- process.stdout.write(` \u2713 ${src.id} \u2192 ${report.entryPaths.length} entries
3357
+ if (lens) {
3358
+ await index.record({
3359
+ sourceId: raw.id,
3360
+ lensId: lens.id,
3361
+ title: raw.title,
3362
+ distilledAt: systemClock.now().toISOString(),
3363
+ engine: engineLabel,
3364
+ contentHash: raw.contentHash,
3365
+ entryCount: report.entryPaths.length,
3366
+ ...report.entryPaths.length ? { entryPaths: report.entryPaths } : {}
3367
+ });
3368
+ }
3369
+ process.stdout.write(` \u2713 ${raw.id} \u2192 ${report.entryPaths.length} entries
2773
3370
  `);
2774
3371
  } catch (e) {
2775
- process.stdout.write(` ! ${src.id} \u2014 ${e instanceof Error ? e.message : String(e)}
3372
+ process.stdout.write(` ! ${raw.id} \u2014 ${e instanceof Error ? e.message : String(e)}
2776
3373
  `);
2777
3374
  }
2778
3375
  }
@@ -3124,10 +3721,10 @@ var SseMcpClient = class {
3124
3721
  try {
3125
3722
  const parsed = RPC_MESSAGE.safeParse(JSON.parse(payload));
3126
3723
  if (!parsed.success) return;
3127
- const msg5 = parsed.data;
3128
- if (typeof msg5.id === "number" && this.pending.has(msg5.id)) {
3129
- this.pending.get(msg5.id)(msg5);
3130
- this.pending.delete(msg5.id);
3724
+ const msg8 = parsed.data;
3725
+ if (typeof msg8.id === "number" && this.pending.has(msg8.id)) {
3726
+ this.pending.get(msg8.id)(msg8);
3727
+ this.pending.delete(msg8.id);
3131
3728
  }
3132
3729
  } catch {
3133
3730
  }
@@ -3196,7 +3793,7 @@ var McpSink = class {
3196
3793
  try {
3197
3794
  client = await this.ensure();
3198
3795
  } catch (e) {
3199
- return { uri: item.uri, ok: false, error: `connect: ${msg4(e)}` };
3796
+ return { uri: item.uri, ok: false, error: `connect: ${msg7(e)}` };
3200
3797
  }
3201
3798
  const args = template(this.config.args, item);
3202
3799
  const call = this.config.importedAlias ? { name: "mcp_imported_call", args: { alias: this.config.importedAlias, toolName: this.config.tool, args } } : { name: this.config.tool, args };
@@ -3205,7 +3802,7 @@ var McpSink = class {
3205
3802
  if (res.isError) return { uri: item.uri, ok: false, error: "tool returned isError" };
3206
3803
  return { uri: item.uri, ok: true };
3207
3804
  } catch (e) {
3208
- return { uri: item.uri, ok: false, error: msg4(e) };
3805
+ return { uri: item.uri, ok: false, error: msg7(e) };
3209
3806
  }
3210
3807
  }
3211
3808
  };
@@ -3249,7 +3846,7 @@ function stringify(v) {
3249
3846
  if (Array.isArray(v)) return v.join(", ");
3250
3847
  return v == null ? "" : String(v);
3251
3848
  }
3252
- function msg4(e) {
3849
+ function msg7(e) {
3253
3850
  return e instanceof Error ? e.message : String(e);
3254
3851
  }
3255
3852
 
@@ -3376,10 +3973,31 @@ Commands:
3376
3973
  scrape MCP server (stealth + clean Markdown) for
3377
3974
  walled/JS pages, ahead of plain readability.
3378
3975
  --diarize: AssemblyAI speaker labels (interviews).
3976
+ import-code [path] --root <dir> [--include glob \u2026 --granularity file|module --max n --tags t --lang l --dry-run]
3977
+ Import a source tree as knowledge sources, one note
3978
+ per code unit (file or module). Notes-only: ZERO
3979
+ code indexing, no symbol/caller/callee graph \u2014
3980
+ that is the code-brain subsystem's job. --dry-run
3981
+ lists the units without writing.
3982
+ import-prs [path] --repo <owner/name> [--pr n ... | --since <iso>] [--include-diff --max n --tags t --lang l --dry-run]
3983
+ Import a repo's pull requests as sources via the
3984
+ user's gh CLI (description + review discussion +
3985
+ optional diff summary). Each PR \u2192 one AIP-10 source
3986
+ (authority: secondary), deduped by content_hash so
3987
+ re-runs skip unchanged PRs. --pr selects explicit PRs
3988
+ (repeatable); --since imports PRs updated since a
3989
+ date; --include-diff appends a diffstat summary.
3379
3990
  distill [path] [--source id --max n --throttle ms --model m --lang l --engine e]
3991
+ [--lens <id> | --lens-file <path>]
3380
3992
  Distill raw sources \u2192 refined entries
3381
3993
  (principle/pattern/\u2026) with sources:[id] provenance.
3382
3994
  Resumable: skips already-distilled sources.
3995
+ --lens reads every source THROUGH one aspect:
3996
+ its prompt drives extraction, its kinds constrain
3997
+ output, entries are tagged aspect:<value>, and the
3998
+ resume ledger keys by (source, lens). Resolves a
3999
+ workspace lenses/<id>.md (override) or a built-in
4000
+ (craft); --lens-file points at an ad-hoc lens doc.
3383
4001
  knowledge [path] --tags a,b [--kind k --access scope --max n]
3384
4002
  Preview what a skill's knowledge: binding resolves to
3385
4003
  \u2014 refined entries + their provenance (filesystem).
@@ -3428,6 +4046,10 @@ async function main(argv2) {
3428
4046
  return await runEventsTail(rest);
3429
4047
  case "import-web":
3430
4048
  return await runImportWeb(rest);
4049
+ case "import-code":
4050
+ return await runImportCode(rest);
4051
+ case "import-prs":
4052
+ return await runImportPrs(rest);
3431
4053
  case "discover":
3432
4054
  return await runDiscover(rest);
3433
4055
  case "distill":