@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/index.d.ts CHANGED
@@ -1,6 +1,71 @@
1
1
  export { N as NodeFsAdapter, a as NodeFsAdapterOptions, O as OsIdentityAdapter, b as OsIdentityAdapterOptions } from './os-identity.adapter-CLBmnRoD.js';
2
- import '@agentproto/corpus';
2
+ import { Lens } from '@agentproto/corpus';
3
3
 
4
4
  declare const VERSION: string;
5
5
 
6
- export { VERSION };
6
+ /**
7
+ * Built-in lens catalog — lenses that ship with the `corpus` CLI and resolve by
8
+ * id in ANY workspace, no declaration required (`corpus distill <ws> --lens craft`).
9
+ *
10
+ * A {@link Lens} is a named projection over the source pool: its `prompt` is
11
+ * threaded to the distiller as the extraction instruction, its `kinds` constrain
12
+ * the emitted kinds, and its `aspect` is stamped on every produced entry as the
13
+ * `aspect:<value>` facet tag (the query key). See
14
+ * `@agentproto/corpus` `distill/lens.ts` + projects/guilde/docs/KNOWLEDGE-LENS-DESIGN.md.
15
+ *
16
+ * This is the CLI-side analog of the guild's built-in catalog
17
+ * (`apps/api` `services/knowledge-generate/lenses.ts`): a workspace can override
18
+ * any of these — or add its own — by dropping a `lenses/<id>.md` declaration in
19
+ * the workspace root (see {@link resolveLens}).
20
+ */
21
+
22
+ /**
23
+ * `craft` — extract TRANSFERABLE WRITING-CRAFT MOVES: how a piece is written
24
+ * (hook, structure, depth, voice, rhythm, ending), not what it is about. A `log`
25
+ * lens — craft moves accumulate across sources; there is no consolidated artifact
26
+ * to re-derive. Prompt validated in the studio (`/tmp/craft-lens.txt`), adapted
27
+ * to the distiller's `{kind,title,body,confidence,tags}` item shape.
28
+ */
29
+ declare const CRAFT_LENS: Lens;
30
+ /** Every built-in lens, keyed by id. */
31
+ declare const BUILTIN_LENSES: Readonly<Record<string, Lens>>;
32
+ /** The ids of every built-in lens — for `--lens` error messages. */
33
+ declare function builtinLensIds(): readonly string[];
34
+
35
+ /**
36
+ * Lens resolution for the `corpus distill --lens` flag.
37
+ *
38
+ * A lens can be reached three ways, in priority order:
39
+ * 1. `--lens <id>` → a workspace-declared `lenses/<id>.md` (overrides a
40
+ * built-in of the same id), else a {@link BUILTIN_LENSES built-in}.
41
+ * 2. `--lens-file <path>` → an ad-hoc lens declaration file, resolved by path
42
+ * (the escape hatch; same `.md` format as a workspace lens).
43
+ *
44
+ * A lens declaration is a markdown file: frontmatter carries `id` / `label` /
45
+ * `aspect` / `kinds` / `mode`, and the markdown BODY is the extraction prompt
46
+ * (a long prompt reads far better as prose than as a YAML block scalar). The
47
+ * `prompt` frontmatter key is accepted as a fallback when the body is empty.
48
+ * This mirrors how sources and entries are authored in this corpus system, and
49
+ * is the file-based analog of the guild's `guild.settings.knowledgeLenses`.
50
+ */
51
+
52
+ /** Thrown when a `--lens` / `--lens-file` cannot be resolved into a valid Lens. */
53
+ declare class LensError extends Error {
54
+ constructor(message: string);
55
+ }
56
+ /**
57
+ * Parse a lens declaration file's contents into a {@link Lens}. `fallbackId` is
58
+ * used when the frontmatter omits `id` (the workspace filename slug / `--lens`
59
+ * value). Throws {@link LensError} when no prompt can be found.
60
+ */
61
+ declare function parseLensDoc(raw: string, fallbackId: string): Lens;
62
+ /**
63
+ * Resolve `--lens <id>`: a workspace `lenses/<id>.md` (override) wins over a
64
+ * built-in of the same id. Throws {@link LensError} listing the built-ins when
65
+ * neither exists.
66
+ */
67
+ declare function resolveLens(id: string, workspaceRoot: string): Promise<Lens>;
68
+ /** Resolve `--lens-file <path>`: parse an ad-hoc lens declaration by path. */
69
+ declare function resolveLensFile(path: string): Promise<Lens>;
70
+
71
+ export { BUILTIN_LENSES, CRAFT_LENS, LensError, VERSION, builtinLensIds, parseLensDoc, resolveLens, resolveLensFile };
package/dist/index.mjs CHANGED
@@ -1,9 +1,12 @@
1
1
  import { readFileSync, existsSync } from 'fs';
2
- import path, { dirname, resolve } from 'path';
2
+ import path, { dirname, resolve, join, basename } from 'path';
3
3
  import { fileURLToPath } from 'url';
4
4
  import { randomBytes } from 'crypto';
5
5
  import { stat, readFile, mkdir, writeFile, rename, appendFile, readdir, rm } from 'fs/promises';
6
6
  import os from 'os';
7
+ import matter from 'gray-matter';
8
+ import { z } from 'zod';
9
+ import { isRefinedKind } from '@agentproto/corpus';
7
10
 
8
11
  /**
9
12
  * @agentproto/corpus-cli v0.1.0-alpha
@@ -178,6 +181,89 @@ function slugify(s) {
178
181
  return s.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").replace(/-{2,}/g, "-").slice(0, 64) || "anonymous";
179
182
  }
180
183
 
181
- export { NodeFsAdapter, OsIdentityAdapter, VERSION };
184
+ // src/lenses/builtin.ts
185
+ var CRAFT_LENS = {
186
+ id: "craft",
187
+ label: "Writing craft",
188
+ aspect: "craft",
189
+ mode: "log",
190
+ // The distiller emits {kind,title,body,...}; a craft move is a technique
191
+ // (pattern), a rule (principle), a shallow default it avoids (critique), or a
192
+ // specific instance (example). "summary" is dropped — a summary is topic
193
+ // content, not a transferable craft move.
194
+ kinds: ["pattern", "principle", "critique", "example"],
195
+ prompt: [
196
+ "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.",
197
+ "",
198
+ "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.",
199
+ "",
200
+ "For each move:",
201
+ '- kind: "pattern" for a technique, "principle" for a rule, "critique" for a shallow/generic default the move avoids, "example" for a specific instance.',
202
+ '- title: name the move crisply and imperatively (e.g. "Delay the thesis until after a concrete image").',
203
+ "- 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)."
204
+ ].join("\n")
205
+ };
206
+ var BUILTIN_LENSES = {
207
+ [CRAFT_LENS.id]: CRAFT_LENS
208
+ };
209
+ function builtinLensIds() {
210
+ return Object.keys(BUILTIN_LENSES);
211
+ }
212
+ var LensError = class extends Error {
213
+ constructor(message) {
214
+ super(message);
215
+ this.name = "LensError";
216
+ }
217
+ };
218
+ var LENS_FRONTMATTER = z.object({
219
+ id: z.string().optional().catch(void 0),
220
+ label: z.string().optional().catch(void 0),
221
+ aspect: z.string().optional().catch(void 0),
222
+ prompt: z.string().optional().catch(void 0),
223
+ mode: z.string().optional().catch(void 0),
224
+ kinds: z.array(z.string()).optional().catch(void 0),
225
+ synthesisPath: z.string().optional().catch(void 0)
226
+ }).loose();
227
+ function parseLensDoc(raw, fallbackId) {
228
+ const parsed = matter(raw);
229
+ const fm = LENS_FRONTMATTER.parse(parsed.data);
230
+ const prompt = (parsed.content.trim() || fm.prompt?.trim()) ?? "";
231
+ if (!prompt) {
232
+ throw new LensError(
233
+ `lens "${fm.id ?? fallbackId}" has no prompt \u2014 put the extraction instruction in the markdown body or a "prompt:" frontmatter key.`
234
+ );
235
+ }
236
+ const kinds = (fm.kinds ?? []).filter(isRefinedKind);
237
+ const mode = fm.mode === "synthesis" ? "synthesis" : "log";
238
+ return {
239
+ id: fm.id ?? fallbackId,
240
+ label: fm.label ?? fm.id ?? fallbackId,
241
+ prompt,
242
+ mode,
243
+ ...fm.aspect ? { aspect: fm.aspect } : {},
244
+ ...kinds.length > 0 ? { kinds } : {},
245
+ ...fm.synthesisPath ? { synthesisPath: fm.synthesisPath } : {}
246
+ };
247
+ }
248
+ async function resolveLens(id, workspaceRoot) {
249
+ const wsPath = join(workspaceRoot, "lenses", `${id}.md`);
250
+ if (existsSync(wsPath)) {
251
+ return parseLensDoc(await readFile(wsPath, "utf8"), id);
252
+ }
253
+ const builtin = BUILTIN_LENSES[id];
254
+ if (builtin) return builtin;
255
+ throw new LensError(
256
+ `unknown lens "${id}". Built-in: ${builtinLensIds().join(", ") || "(none)"}. Declare one at ${join("lenses", `${id}.md`)} in the workspace, or pass --lens-file <path>.`
257
+ );
258
+ }
259
+ async function resolveLensFile(path3) {
260
+ if (!existsSync(path3)) {
261
+ throw new LensError(`--lens-file not found: ${path3}`);
262
+ }
263
+ const fallbackId = basename(path3).replace(/\.[^.]+$/, "");
264
+ return parseLensDoc(await readFile(path3, "utf8"), fallbackId);
265
+ }
266
+
267
+ export { BUILTIN_LENSES, CRAFT_LENS, LensError, NodeFsAdapter, OsIdentityAdapter, VERSION, builtinLensIds, parseLensDoc, resolveLens, resolveLensFile };
182
268
  //# sourceMappingURL=index.mjs.map
183
269
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/version.ts","../src/ports/local-fs.adapter.ts","../src/ports/os-identity.adapter.ts"],"names":["path"],"mappings":";;;;;;;;;;;;AAYA,SAAS,WAAA,GAAsB;AAC7B,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAC,CAAA;AACnD,IAAA,MAAM,MAAM,IAAA,CAAK,KAAA;AAAA,MACf,YAAA,CAAa,OAAA,CAAQ,IAAA,EAAM,iBAAiB,GAAG,MAAM;AAAA,KACvD;AACA,IAAA,OAAO,IAAI,OAAA,IAAW,OAAA;AAAA,EACxB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,OAAA;AAAA,EACT;AACF;AAEO,IAAM,UAAkB,WAAA;ACexB,IAAM,gBAAN,MAAsC;AAAA,EAC1B,IAAA;AAAA,EAEjB,YAAY,IAAA,EAA4B;AACtC,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AAAA,EACnB;AAAA,EAEA,MAAM,OAAO,CAAA,EAA6B;AACxC,IAAA,IAAI;AACF,MAAA,MAAM,IAAA,CAAK,IAAA,CAAK,OAAA,CAAQ,CAAC,CAAC,CAAA;AAC1B,M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EAAW,CAAA,WAAA,EAAc,OAAA,CAAQ,IAAI,CAAC,CAAA,CAAA;AAAA,MACtC,YAAA,EAAc,OAAO,MAAA,CAAO;AAAA,QAC1B,CAAA,WAAA,EAAc,OAAA,CAAQ,IAAI,CAAC,CAAA,CAAA;AAAA,QAC3B,CAAA,gBAAA,EAAmB,OAAA,CAAQ,MAAM,CAAC,CAAA;AAAA,OACnC,CAAA;AAAA,MACD,WAAA,EAAa;AAAA,KACd,CAAA;AAAA,EACH;AAAA,EAEA,MAAM,OAAA,GAAmC;AACvC,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EACd;AACF;AAEA,SAAS,WAAA,GAAkC;AACzC,EAAA,IAAI;AACF,IAAA,OAAO,EAAA,CAAG,UAAS,CAAE,QAAA;AAAA,EACvB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAEA,SAAS,QAAQ,CAAA,EAAmB;AAClC,EAAA,OAAO,EACJ,WAAA,EAAY,CACZ,QAAQ,cAAA,EAAgB,GAAG,EAC3B,OAAA,CAAQ,UAAA,EAAY,EAAE,CAAA,CACtB,QAAQ,QAAA,EAAU,GAAG,EACrB,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,IAAK,WAAA;AACrB","file":"index.mjs","sourcesContent":["/**\n * CLI version — derived from the package's own package.json at runtime,\n * so it never drifts from the published version on a release bump.\n *\n * `import.meta.url` resolves to dist/cli.mjs in the published bundle and\n * to src/version.ts under tsx/vitest; in both, package.json sits one\n * directory up. A defensive fallback keeps --version from ever throwing.\n */\nimport { readFileSync } from \"node:fs\"\nimport { dirname, resolve } from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\n\nfunction readVersion(): string {\n try {\n const here = dirname(fileURLToPath(import.meta.url))\n const pkg = JSON.parse(\n readFileSync(resolve(here, \"../package.json\"), \"utf8\")\n ) as { version?: string }\n return pkg.version ?? \"0.0.0\"\n } catch {\n return \"0.0.0\"\n }\n}\n\nexport const VERSION: string = readVersion()\n","/**\n * NodeFsAdapter — `FsPort` implementation backed by node:fs.\n *\n * Atomic writes via temp + rename (the same posix pattern every\n * mature tool uses). Recursive `walk` skips hidden segments\n * (anything beginning with `.`). Advisory locks via lockfiles in\n * `.corpus-locks/` next to the target — single-process safe; for\n * multi-process the lockfile owner pid is recorded so callers can\n * see who holds the lock.\n */\n\nimport { randomBytes } from \"node:crypto\"\nimport {\n appendFile,\n mkdir,\n readFile,\n readdir,\n rename,\n rm,\n stat,\n writeFile,\n} from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { existsSync } from \"node:fs\"\nimport type {\n FsPort,\n FsLockHandle,\n FsStat,\n} from \"@agentproto/corpus\"\n\nexport interface NodeFsAdapterOptions {\n /**\n * Absolute path to the workspace root. All FsPort paths are\n * resolved relative to this — the kit never sees host filesystem\n * paths.\n */\n readonly root: string\n}\n\nexport class NodeFsAdapter implements FsPort {\n private readonly root: string\n\n constructor(opts: NodeFsAdapterOptions) {\n this.root = opts.root\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await stat(this.resolve(p))\n return true\n } catch {\n return false\n }\n }\n\n async readFile(p: string): Promise<string> {\n return await readFile(this.resolve(p), \"utf8\")\n }\n\n /**\n * Atomic write: write to `${target}.tmp-{nonce}`, fsync, rename.\n * Rename is atomic on the same filesystem. Creates parent dirs as\n * needed (most callers expect mkdir -p semantics).\n */\n async writeFile(p: string, content: string): Promise<void> {\n const target = this.resolve(p)\n await mkdir(path.dirname(target), { recursive: true })\n const tmp = `${target}.tmp-${randomBytes(8).toString(\"hex\")}`\n await writeFile(tmp, content, \"utf8\")\n await rename(tmp, target)\n }\n\n async appendFile(p: string, content: string): Promise<void> {\n const target = this.resolve(p)\n await mkdir(path.dirname(target), { recursive: true })\n await appendFile(target, content, \"utf8\")\n }\n\n async readdir(p: string): Promise<readonly string[]> {\n const target = this.resolve(p)\n const entries = await readdir(target)\n return entries\n }\n\n async walk(p: string): Promise<readonly string[]> {\n const out: string[] = []\n const start = this.resolve(p)\n const rootForRelative = start\n const visit = async (dir: string): Promise<void> => {\n let entries: string[] = []\n try {\n entries = await readdir(dir)\n } catch {\n return\n }\n for (const ent of entries) {\n // Skip hidden segments — matches the FsPort contract.\n if (ent.startsWith(\".\")) continue\n const full = path.join(dir, ent)\n const s = await stat(full)\n if (s.isDirectory()) {\n await visit(full)\n } else if (s.isFile()) {\n const rel = path.relative(rootForRelative, full).split(path.sep).join(\"/\")\n out.push(rel)\n }\n }\n }\n await visit(start)\n return out\n }\n\n async stat(p: string): Promise<FsStat | null> {\n try {\n const s = await stat(this.resolve(p))\n return {\n kind: s.isDirectory() ? \"directory\" : \"file\",\n bytes: s.isFile() ? s.size : undefined,\n modifiedAt: s.mtime,\n }\n } catch {\n return null\n }\n }\n\n /**\n * Advisory lock via a lockfile. Spins waiting for the lockfile to\n * disappear, then creates it with exclusive flag. Released by\n * deleting it. Single-process safe; multi-process semi-safe (the\n * write is best-effort exclusive — adequate for the corpus's\n * promote-entry transaction which is rare and short-lived).\n */\n async lock(p: string): Promise<FsLockHandle> {\n const target = this.resolve(p)\n const lockDir = path.join(path.dirname(target), \".corpus-locks\")\n await mkdir(lockDir, { recursive: true })\n const lockFile = path.join(lockDir, path.basename(target) + \".lock\")\n const myToken = `${process.pid}-${randomBytes(4).toString(\"hex\")}`\n\n // Spin until we acquire. Cheap polling is fine for corpus\n // workloads — transactions are < 1s.\n while (true) {\n if (!existsSync(lockFile)) {\n try {\n await writeFile(lockFile, myToken, { encoding: \"utf8\", flag: \"wx\" })\n // Race: verify our token is the one that landed.\n const written = await readFile(lockFile, \"utf8\").catch(() => \"\")\n if (written === myToken) break\n } catch {\n // Lost the race — fall through and retry.\n }\n }\n await new Promise((r) => setTimeout(r, 25))\n }\n return {\n release: async () => {\n try {\n await rm(lockFile, { force: true })\n } catch {\n // Lockfile already gone — no-op.\n }\n },\n }\n }\n\n // ── Helpers ────────────────────────────────────────────────────\n\n /**\n * Resolve a workspace-relative path to an absolute host path.\n * Refuses to climb out of the workspace root (defense against\n * `../../etc/passwd`-style abuse) — the corpus kit's paths must\n * stay inside the workspace.\n */\n private resolve(p: string): string {\n const normalized = path.posix.normalize(\"/\" + p.replace(/^\\/+/, \"\"))\n // Drop the leading \"/\" so path.join joins correctly under root.\n const rel = normalized.slice(1)\n if (rel.startsWith(\"..\")) {\n throw new Error(\n `NodeFsAdapter: path \"${p}\" escapes the workspace root \"${this.root}\"`\n )\n }\n return path.join(this.root, rel)\n }\n}\n","/**\n * OsIdentityAdapter — `IdentityPort` resolved from OS user + cwd.\n *\n * Local-topology identity model:\n * - principal = `ws://users/{os-user}`\n * - identityTree = [\n * `ws://users/{os-user}`,\n * `ws://workspaces/{workspace-dir-name}`,\n * ]\n *\n * Roles + guilds + orgs don't exist locally — single-user, single-\n * workspace machine. Scope-policy in the corpus adapter matches\n * against this minimal tree, so AIP-10 `appliesTo` entries scoped\n * narrower than `ws://users/...` or `ws://workspaces/...` are\n * invisible to the local user. That's the intended local-topology\n * semantics: you only see what's scoped to you or your workspace.\n */\n\nimport os from \"node:os\"\nimport path from \"node:path\"\nimport type {\n CallerIdentity,\n IdentityPort,\n} from \"@agentproto/corpus\"\n\nexport interface OsIdentityAdapterOptions {\n readonly workspaceRoot: string\n /** Override the OS user (useful for tests). Falls back to os.userInfo(). */\n readonly userOverride?: string\n}\n\nexport class OsIdentityAdapter implements IdentityPort {\n private readonly cached: CallerIdentity\n\n constructor(opts: OsIdentityAdapterOptions) {\n // Env vars win over os.userInfo() — matches Unix convention (env is\n // explicit intent, OS detection is fallback). Also keeps tests\n // deterministic across CI environments where the OS user differs.\n const user =\n opts.userOverride ??\n process.env.USER ??\n process.env.USERNAME ??\n safeGetUser() ??\n \"anonymous\"\n const wsName = path.basename(opts.workspaceRoot) || \"default\"\n this.cached = Object.freeze({\n principal: `ws://users/${slugify(user)}`,\n identityTree: Object.freeze([\n `ws://users/${slugify(user)}`,\n `ws://workspaces/${slugify(wsName)}`,\n ]),\n displayName: user,\n })\n }\n\n async resolve(): Promise<CallerIdentity> {\n return this.cached\n }\n}\n\nfunction safeGetUser(): string | undefined {\n try {\n return os.userInfo().username\n } catch {\n return undefined\n }\n}\n\nfunction slugify(s: string): string {\n return s\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .replace(/-{2,}/g, \"-\")\n .slice(0, 64) || \"anonymous\"\n}\n"]}
1
+ {"version":3,"sources":["../src/version.ts","../src/ports/local-fs.adapter.ts","../src/ports/os-identity.adapter.ts","../src/lenses/builtin.ts","../src/lenses/resolve.ts"],"names":["path","existsSync","readFile"],"mappings":";;;;;;;;;;;;;;;AAYA,SAAS,WAAA,GAAsB;AAC7B,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAC,CAAA;AACnD,IAAA,MAAM,MAAM,IAAA,CAAK,KAAA;AAAA,MACf,YAAA,CAAa,OAAA,CAAQ,IAAA,EAAM,iBAAiB,GAAG,MAAM;AAAA,KACvD;AACA,IAAA,OAAO,IAAI,OAAA,IAAW,OAAA;AAAA,EACxB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,OAAA;AAAA,EACT;AACF;AAEO,IAAM,UAAkB,WAAA;ACexB,IAAM,gBAAN,MAAsC;AAAA,EAC1B,IAAA;AAAA,EAEjB,YAAY,IAAA,EAA4B;AACtC,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AAAA,EACnB;AAAA,EAEA,MAAM,OAAO,CAAA,EAA6B;AACxC,IAAA,IAAI;AACF,MAAA,MAAM,IAAA,CAAK,IAAA,CAAK,OAAA,CAAQ,CAAC,CAAC,CAAA;AAC1B,MAAA,OAAO,IAAA;AAAA,IACT,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AAAA,EAEA,MAAM,SAAS,CAAA,EAA4B;AACzC,IAAA,OAAO,MAAM,QA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AAGA,eAAsB,gBAAgBF,KAAAA,EAA6B;AACjE,EAAA,IAAI,CAACC,UAAAA,CAAWD,KAAI,CAAA,EAAG;AACrB,IAAA,MAAM,IAAI,SAAA,CAAU,CAAA,uBAAA,EAA0BA,KAAI,CAAA,CAAE,CAAA;AAAA,EACtD;AACA,EAAA,MAAM,aAAa,QAAA,CAASA,KAAI,CAAA,CAAE,OAAA,CAAQ,YAAY,EAAE,CAAA;AACxD,EAAA,OAAO,aAAa,MAAME,QAAAA,CAASF,KAAAA,EAAM,MAAM,GAAG,UAAU,CAAA;AAC9D","file":"index.mjs","sourcesContent":["/**\n * CLI version — derived from the package's own package.json at runtime,\n * so it never drifts from the published version on a release bump.\n *\n * `import.meta.url` resolves to dist/cli.mjs in the published bundle and\n * to src/version.ts under tsx/vitest; in both, package.json sits one\n * directory up. A defensive fallback keeps --version from ever throwing.\n */\nimport { readFileSync } from \"node:fs\"\nimport { dirname, resolve } from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\n\nfunction readVersion(): string {\n try {\n const here = dirname(fileURLToPath(import.meta.url))\n const pkg = JSON.parse(\n readFileSync(resolve(here, \"../package.json\"), \"utf8\")\n ) as { version?: string }\n return pkg.version ?? \"0.0.0\"\n } catch {\n return \"0.0.0\"\n }\n}\n\nexport const VERSION: string = readVersion()\n","/**\n * NodeFsAdapter — `FsPort` implementation backed by node:fs.\n *\n * Atomic writes via temp + rename (the same posix pattern every\n * mature tool uses). Recursive `walk` skips hidden segments\n * (anything beginning with `.`). Advisory locks via lockfiles in\n * `.corpus-locks/` next to the target — single-process safe; for\n * multi-process the lockfile owner pid is recorded so callers can\n * see who holds the lock.\n */\n\nimport { randomBytes } from \"node:crypto\"\nimport {\n appendFile,\n mkdir,\n readFile,\n readdir,\n rename,\n rm,\n stat,\n writeFile,\n} from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { existsSync } from \"node:fs\"\nimport type {\n FsPort,\n FsLockHandle,\n FsStat,\n} from \"@agentproto/corpus\"\n\nexport interface NodeFsAdapterOptions {\n /**\n * Absolute path to the workspace root. All FsPort paths are\n * resolved relative to this — the kit never sees host filesystem\n * paths.\n */\n readonly root: string\n}\n\nexport class NodeFsAdapter implements FsPort {\n private readonly root: string\n\n constructor(opts: NodeFsAdapterOptions) {\n this.root = opts.root\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await stat(this.resolve(p))\n return true\n } catch {\n return false\n }\n }\n\n async readFile(p: string): Promise<string> {\n return await readFile(this.resolve(p), \"utf8\")\n }\n\n /**\n * Atomic write: write to `${target}.tmp-{nonce}`, fsync, rename.\n * Rename is atomic on the same filesystem. Creates parent dirs as\n * needed (most callers expect mkdir -p semantics).\n */\n async writeFile(p: string, content: string): Promise<void> {\n const target = this.resolve(p)\n await mkdir(path.dirname(target), { recursive: true })\n const tmp = `${target}.tmp-${randomBytes(8).toString(\"hex\")}`\n await writeFile(tmp, content, \"utf8\")\n await rename(tmp, target)\n }\n\n async appendFile(p: string, content: string): Promise<void> {\n const target = this.resolve(p)\n await mkdir(path.dirname(target), { recursive: true })\n await appendFile(target, content, \"utf8\")\n }\n\n async readdir(p: string): Promise<readonly string[]> {\n const target = this.resolve(p)\n const entries = await readdir(target)\n return entries\n }\n\n async walk(p: string): Promise<readonly string[]> {\n const out: string[] = []\n const start = this.resolve(p)\n const rootForRelative = start\n const visit = async (dir: string): Promise<void> => {\n let entries: string[] = []\n try {\n entries = await readdir(dir)\n } catch {\n return\n }\n for (const ent of entries) {\n // Skip hidden segments — matches the FsPort contract.\n if (ent.startsWith(\".\")) continue\n const full = path.join(dir, ent)\n const s = await stat(full)\n if (s.isDirectory()) {\n await visit(full)\n } else if (s.isFile()) {\n const rel = path.relative(rootForRelative, full).split(path.sep).join(\"/\")\n out.push(rel)\n }\n }\n }\n await visit(start)\n return out\n }\n\n async stat(p: string): Promise<FsStat | null> {\n try {\n const s = await stat(this.resolve(p))\n return {\n kind: s.isDirectory() ? \"directory\" : \"file\",\n bytes: s.isFile() ? s.size : undefined,\n modifiedAt: s.mtime,\n }\n } catch {\n return null\n }\n }\n\n /**\n * Advisory lock via a lockfile. Spins waiting for the lockfile to\n * disappear, then creates it with exclusive flag. Released by\n * deleting it. Single-process safe; multi-process semi-safe (the\n * write is best-effort exclusive — adequate for the corpus's\n * promote-entry transaction which is rare and short-lived).\n */\n async lock(p: string): Promise<FsLockHandle> {\n const target = this.resolve(p)\n const lockDir = path.join(path.dirname(target), \".corpus-locks\")\n await mkdir(lockDir, { recursive: true })\n const lockFile = path.join(lockDir, path.basename(target) + \".lock\")\n const myToken = `${process.pid}-${randomBytes(4).toString(\"hex\")}`\n\n // Spin until we acquire. Cheap polling is fine for corpus\n // workloads — transactions are < 1s.\n while (true) {\n if (!existsSync(lockFile)) {\n try {\n await writeFile(lockFile, myToken, { encoding: \"utf8\", flag: \"wx\" })\n // Race: verify our token is the one that landed.\n const written = await readFile(lockFile, \"utf8\").catch(() => \"\")\n if (written === myToken) break\n } catch {\n // Lost the race — fall through and retry.\n }\n }\n await new Promise((r) => setTimeout(r, 25))\n }\n return {\n release: async () => {\n try {\n await rm(lockFile, { force: true })\n } catch {\n // Lockfile already gone — no-op.\n }\n },\n }\n }\n\n // ── Helpers ────────────────────────────────────────────────────\n\n /**\n * Resolve a workspace-relative path to an absolute host path.\n * Refuses to climb out of the workspace root (defense against\n * `../../etc/passwd`-style abuse) — the corpus kit's paths must\n * stay inside the workspace.\n */\n private resolve(p: string): string {\n const normalized = path.posix.normalize(\"/\" + p.replace(/^\\/+/, \"\"))\n // Drop the leading \"/\" so path.join joins correctly under root.\n const rel = normalized.slice(1)\n if (rel.startsWith(\"..\")) {\n throw new Error(\n `NodeFsAdapter: path \"${p}\" escapes the workspace root \"${this.root}\"`\n )\n }\n return path.join(this.root, rel)\n }\n}\n","/**\n * OsIdentityAdapter — `IdentityPort` resolved from OS user + cwd.\n *\n * Local-topology identity model:\n * - principal = `ws://users/{os-user}`\n * - identityTree = [\n * `ws://users/{os-user}`,\n * `ws://workspaces/{workspace-dir-name}`,\n * ]\n *\n * Roles + guilds + orgs don't exist locally — single-user, single-\n * workspace machine. Scope-policy in the corpus adapter matches\n * against this minimal tree, so AIP-10 `appliesTo` entries scoped\n * narrower than `ws://users/...` or `ws://workspaces/...` are\n * invisible to the local user. That's the intended local-topology\n * semantics: you only see what's scoped to you or your workspace.\n */\n\nimport os from \"node:os\"\nimport path from \"node:path\"\nimport type {\n CallerIdentity,\n IdentityPort,\n} from \"@agentproto/corpus\"\n\nexport interface OsIdentityAdapterOptions {\n readonly workspaceRoot: string\n /** Override the OS user (useful for tests). Falls back to os.userInfo(). */\n readonly userOverride?: string\n}\n\nexport class OsIdentityAdapter implements IdentityPort {\n private readonly cached: CallerIdentity\n\n constructor(opts: OsIdentityAdapterOptions) {\n // Env vars win over os.userInfo() — matches Unix convention (env is\n // explicit intent, OS detection is fallback). Also keeps tests\n // deterministic across CI environments where the OS user differs.\n const user =\n opts.userOverride ??\n process.env.USER ??\n process.env.USERNAME ??\n safeGetUser() ??\n \"anonymous\"\n const wsName = path.basename(opts.workspaceRoot) || \"default\"\n this.cached = Object.freeze({\n principal: `ws://users/${slugify(user)}`,\n identityTree: Object.freeze([\n `ws://users/${slugify(user)}`,\n `ws://workspaces/${slugify(wsName)}`,\n ]),\n displayName: user,\n })\n }\n\n async resolve(): Promise<CallerIdentity> {\n return this.cached\n }\n}\n\nfunction safeGetUser(): string | undefined {\n try {\n return os.userInfo().username\n } catch {\n return undefined\n }\n}\n\nfunction slugify(s: string): string {\n return s\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .replace(/-{2,}/g, \"-\")\n .slice(0, 64) || \"anonymous\"\n}\n","/**\n * Built-in lens catalog — lenses that ship with the `corpus` CLI and resolve by\n * id in ANY workspace, no declaration required (`corpus distill <ws> --lens craft`).\n *\n * A {@link Lens} is a named projection over the source pool: its `prompt` is\n * threaded to the distiller as the extraction instruction, its `kinds` constrain\n * the emitted kinds, and its `aspect` is stamped on every produced entry as the\n * `aspect:<value>` facet tag (the query key). See\n * `@agentproto/corpus` `distill/lens.ts` + projects/guilde/docs/KNOWLEDGE-LENS-DESIGN.md.\n *\n * This is the CLI-side analog of the guild's built-in catalog\n * (`apps/api` `services/knowledge-generate/lenses.ts`): a workspace can override\n * any of these — or add its own — by dropping a `lenses/<id>.md` declaration in\n * the workspace root (see {@link resolveLens}).\n */\n\nimport type { Lens } from \"@agentproto/corpus\"\n\n/**\n * `craft` — extract TRANSFERABLE WRITING-CRAFT MOVES: how a piece is written\n * (hook, structure, depth, voice, rhythm, ending), not what it is about. A `log`\n * lens — craft moves accumulate across sources; there is no consolidated artifact\n * to re-derive. Prompt validated in the studio (`/tmp/craft-lens.txt`), adapted\n * to the distiller's `{kind,title,body,confidence,tags}` item shape.\n */\nexport const CRAFT_LENS: Lens = {\n id: \"craft\",\n label: \"Writing craft\",\n aspect: \"craft\",\n mode: \"log\",\n // The distiller emits {kind,title,body,...}; a craft move is a technique\n // (pattern), a rule (principle), a shallow default it avoids (critique), or a\n // specific instance (example). \"summary\" is dropped — a summary is topic\n // content, not a transferable craft move.\n kinds: [\"pattern\", \"principle\", \"critique\", \"example\"],\n prompt: [\n \"Extract TRANSFERABLE WRITING-CRAFT MOVES from the source — 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 — only the craft.\",\n \"\",\n \"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.\",\n \"\",\n \"For each move:\",\n '- kind: \"pattern\" for a technique, \"principle\" for a rule, \"critique\" for a shallow/generic default the move avoids, \"example\" for a specific instance.',\n '- title: name the move crisply and imperatively (e.g. \"Delay the thesis until after a concrete image\").',\n \"- 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).\",\n ].join(\"\\n\"),\n}\n\n/** Every built-in lens, keyed by id. */\nexport const BUILTIN_LENSES: Readonly<Record<string, Lens>> = {\n [CRAFT_LENS.id]: CRAFT_LENS,\n}\n\n/** The ids of every built-in lens — for `--lens` error messages. */\nexport function builtinLensIds(): readonly string[] {\n return Object.keys(BUILTIN_LENSES)\n}\n","/**\n * Lens resolution for the `corpus distill --lens` flag.\n *\n * A lens can be reached three ways, in priority order:\n * 1. `--lens <id>` → a workspace-declared `lenses/<id>.md` (overrides a\n * built-in of the same id), else a {@link BUILTIN_LENSES built-in}.\n * 2. `--lens-file <path>` → an ad-hoc lens declaration file, resolved by path\n * (the escape hatch; same `.md` format as a workspace lens).\n *\n * A lens declaration is a markdown file: frontmatter carries `id` / `label` /\n * `aspect` / `kinds` / `mode`, and the markdown BODY is the extraction prompt\n * (a long prompt reads far better as prose than as a YAML block scalar). The\n * `prompt` frontmatter key is accepted as a fallback when the body is empty.\n * This mirrors how sources and entries are authored in this corpus system, and\n * is the file-based analog of the guild's `guild.settings.knowledgeLenses`.\n */\n\nimport { existsSync } from \"node:fs\"\nimport { readFile } from \"node:fs/promises\"\nimport { basename, join } from \"node:path\"\nimport matter from \"gray-matter\"\nimport { z } from \"zod\"\nimport { isRefinedKind, type Lens, type LensMode, type RefinedKind } from \"@agentproto/corpus\"\nimport { BUILTIN_LENSES, builtinLensIds } from \"./builtin.js\"\n\n/** Thrown when a `--lens` / `--lens-file` cannot be resolved into a valid Lens. */\nexport class LensError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"LensError\"\n }\n}\n\n/** Lenient view of a lens declaration's frontmatter (each field degrades safely). */\nconst LENS_FRONTMATTER = z\n .object({\n id: z.string().optional().catch(undefined),\n label: z.string().optional().catch(undefined),\n aspect: z.string().optional().catch(undefined),\n prompt: z.string().optional().catch(undefined),\n mode: z.string().optional().catch(undefined),\n kinds: z.array(z.string()).optional().catch(undefined),\n synthesisPath: z.string().optional().catch(undefined),\n })\n .loose()\n\n/**\n * Parse a lens declaration file's contents into a {@link Lens}. `fallbackId` is\n * used when the frontmatter omits `id` (the workspace filename slug / `--lens`\n * value). Throws {@link LensError} when no prompt can be found.\n */\nexport function parseLensDoc(raw: string, fallbackId: string): Lens {\n const parsed = matter(raw)\n const fm = LENS_FRONTMATTER.parse(parsed.data)\n const prompt = (parsed.content.trim() || fm.prompt?.trim()) ?? \"\"\n if (!prompt) {\n throw new LensError(\n `lens \"${fm.id ?? fallbackId}\" has no prompt — put the extraction instruction in the markdown body or a \"prompt:\" frontmatter key.`\n )\n }\n const kinds: RefinedKind[] = (fm.kinds ?? []).filter(isRefinedKind)\n const mode: LensMode = fm.mode === \"synthesis\" ? \"synthesis\" : \"log\"\n return {\n id: fm.id ?? fallbackId,\n label: fm.label ?? fm.id ?? fallbackId,\n prompt,\n mode,\n ...(fm.aspect ? { aspect: fm.aspect } : {}),\n ...(kinds.length > 0 ? { kinds } : {}),\n ...(fm.synthesisPath ? { synthesisPath: fm.synthesisPath } : {}),\n }\n}\n\n/**\n * Resolve `--lens <id>`: a workspace `lenses/<id>.md` (override) wins over a\n * built-in of the same id. Throws {@link LensError} listing the built-ins when\n * neither exists.\n */\nexport async function resolveLens(id: string, workspaceRoot: string): Promise<Lens> {\n const wsPath = join(workspaceRoot, \"lenses\", `${id}.md`)\n if (existsSync(wsPath)) {\n return parseLensDoc(await readFile(wsPath, \"utf8\"), id)\n }\n const builtin = BUILTIN_LENSES[id]\n if (builtin) return builtin\n throw new LensError(\n `unknown lens \"${id}\". Built-in: ${builtinLensIds().join(\", \") || \"(none)\"}. ` +\n `Declare one at ${join(\"lenses\", `${id}.md`)} in the workspace, or pass --lens-file <path>.`\n )\n}\n\n/** Resolve `--lens-file <path>`: parse an ad-hoc lens declaration by path. */\nexport async function resolveLensFile(path: string): Promise<Lens> {\n if (!existsSync(path)) {\n throw new LensError(`--lens-file not found: ${path}`)\n }\n const fallbackId = basename(path).replace(/\\.[^.]+$/, \"\")\n return parseLensDoc(await readFile(path, \"utf8\"), fallbackId)\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  export { N as NodeFsAdapter, a as NodeFsAdapterOptions, O as OsIdentityAdapter, b as OsIdentityAdapterOptions } from '../os-identity.adapter-CLBmnRoD.js';
2
- import { FetcherPort, FetchedSource, DistillPort, DistillInput, DistilledItem, SinkPort, SinkItem, SinkPushResult } from '@agentproto/corpus';
2
+ import { FetcherPort, FetchedSource, PrSourcePort, PrQuery, PrDoc, DistillPort, DistillInput, DistilledItem, SinkPort, SinkItem, SinkPushResult } from '@agentproto/corpus';
3
3
  export { buildDistillPrompt, parseItems } from '@agentproto/corpus';
4
4
  import { z } from 'zod';
5
5
 
@@ -357,6 +357,45 @@ declare class HttpReadabilityFetcher implements FetcherPort {
357
357
  fetch(url: string): Promise<FetchedSource | null>;
358
358
  }
359
359
 
360
+ /**
361
+ * GhPrSourceAdapter — a PrSourcePort backed by the GitHub CLI (`gh`). This is
362
+ * how the local `corpus` runtime resolves a repo query to its pull requests:
363
+ * the SAME `gh` binary the rest of the repo already talks to GitHub through
364
+ * (see the daemon's `gh pr create` lane), reusing the user's existing `gh`
365
+ * auth — no new HTTP client, no token plumbing in the corpus layer.
366
+ *
367
+ * query → gh pr list --repo <repo> --json number … (enumerate)
368
+ * → gh pr view <n> --repo <repo> --json … (per-PR detail)
369
+ *
370
+ * Per-PR resilience lives HERE, not in the pure importer: a single PR that
371
+ * `gh pr view` cannot fetch (deleted, permission) is skipped with a stderr
372
+ * notice and simply not yielded, so one bad PR never aborts the batch. A
373
+ * failure to even *list* PRs (bad repo, `gh` unauthenticated) throws — that is
374
+ * a hard batch abort the importer surfaces.
375
+ *
376
+ * The `gh` invocation is injected as `run` so the adapter is unit-testable with
377
+ * a fake runner — no binary, no network. All `gh` JSON is parsed through zod;
378
+ * no `any` crosses the boundary.
379
+ */
380
+
381
+ /** Run a `gh` subcommand and resolve its stdout. Injectable for tests. */
382
+ type GhRunner = (args: readonly string[]) => Promise<string>;
383
+ interface GhPrSourceAdapterOptions {
384
+ /** Defaults to a `gh` subprocess runner. */
385
+ readonly run?: GhRunner;
386
+ /** Path to the `gh` binary (default: "gh" on PATH). */
387
+ readonly ghBin?: string;
388
+ }
389
+ declare class GhPrSourceAdapter implements PrSourcePort {
390
+ private readonly run;
391
+ constructor(opts?: GhPrSourceAdapterOptions);
392
+ listPullRequests(query: PrQuery): AsyncIterable<PrDoc>;
393
+ /** Resolve the query to a concrete, capped list of PR numbers. */
394
+ private resolveNumbers;
395
+ /** Fetch one PR's detail and shape it into a PrDoc, or null if empty. */
396
+ private viewPr;
397
+ }
398
+
360
399
  /**
361
400
  * Usage telemetry for the metered distill path — cost visibility + optional
362
401
  * Langfuse export. SDK-free (raw fetch to Langfuse's ingestion API), mirroring
@@ -570,4 +609,4 @@ declare class McpSink implements SinkPort {
570
609
  push(item: SinkItem): Promise<SinkPushResult>;
571
610
  }
572
611
 
573
- export { AnthropicDistiller, type AnthropicDistillerOptions, AssemblyAiStt, type AssemblyAiSttOptions, type AudioDownload, type AudioDownloader, type AudioSplitter, BrowserMcpFetcher, type BrowserMcpFetcherOptions, type BrowserMcpLike, CLI_ENGINES, ChunkedStt, type ChunkedSttOptions, CliAgentDistiller, type CliAgentDistillerOptions, type CliEngine, CompositeFetcher, type ConnectMcpHttpOptions, HttpReadabilityFetcher, type HttpReadabilityFetcherOptions, type McpClientLike, McpSink, type McpSinkConfig, OpenAiWhisperStt, type OpenAiWhisperSttOptions, ScrapeMcpFetcher, type ScrapeMcpFetcherOptions, type SttPort, ThrottleFetcher, type ThrottleFetcherOptions, type Transcript, YtDlpWhisperFetcher, type YtDlpWhisperFetcherOptions, connectMcpHttp };
612
+ export { AnthropicDistiller, type AnthropicDistillerOptions, AssemblyAiStt, type AssemblyAiSttOptions, type AudioDownload, type AudioDownloader, type AudioSplitter, BrowserMcpFetcher, type BrowserMcpFetcherOptions, type BrowserMcpLike, CLI_ENGINES, ChunkedStt, type ChunkedSttOptions, CliAgentDistiller, type CliAgentDistillerOptions, type CliEngine, CompositeFetcher, type ConnectMcpHttpOptions, GhPrSourceAdapter, type GhPrSourceAdapterOptions, type GhRunner, HttpReadabilityFetcher, type HttpReadabilityFetcherOptions, type McpClientLike, McpSink, type McpSinkConfig, OpenAiWhisperStt, type OpenAiWhisperSttOptions, ScrapeMcpFetcher, type ScrapeMcpFetcherOptions, type SttPort, ThrottleFetcher, type ThrottleFetcherOptions, type Transcript, YtDlpWhisperFetcher, type YtDlpWhisperFetcherOptions, connectMcpHttp };
@@ -761,6 +761,186 @@ function extractReadable(html) {
761
761
  function decodeEntities(s) {
762
762
  return s.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&nbsp;/g, " ").replace(/&#(\d+);/g, (_, n) => String.fromCharCode(Number(n)));
763
763
  }
764
+ var execFileAsync3 = promisify(execFile);
765
+ var GH_ACTOR = z.object({ login: z.string().optional(), name: z.string().optional() }).loose();
766
+ var GH_PR_LIST_ITEM = z.object({ number: z.number() }).loose();
767
+ var GH_PR_LIST = z.array(GH_PR_LIST_ITEM);
768
+ var GH_COMMENT = z.object({
769
+ author: GH_ACTOR.nullish(),
770
+ body: z.string().optional(),
771
+ path: z.string().optional(),
772
+ createdAt: z.string().optional(),
773
+ submittedAt: z.string().optional()
774
+ }).loose();
775
+ var GH_FILE = z.object({
776
+ path: z.string(),
777
+ additions: z.number().optional(),
778
+ deletions: z.number().optional()
779
+ }).loose();
780
+ var GH_PR_VIEW = z.object({
781
+ number: z.number(),
782
+ title: z.string().optional(),
783
+ body: z.string().optional(),
784
+ author: GH_ACTOR.nullish(),
785
+ url: z.string().optional(),
786
+ state: z.string().optional(),
787
+ mergedAt: z.string().nullish(),
788
+ reviews: z.array(GH_COMMENT).optional(),
789
+ comments: z.array(GH_COMMENT).optional(),
790
+ reviewRequests: z.array(GH_ACTOR).optional(),
791
+ additions: z.number().optional(),
792
+ deletions: z.number().optional(),
793
+ changedFiles: z.number().optional(),
794
+ files: z.array(GH_FILE).optional()
795
+ }).loose();
796
+ var VIEW_FIELDS = [
797
+ "number",
798
+ "title",
799
+ "body",
800
+ "author",
801
+ "url",
802
+ "state",
803
+ "mergedAt",
804
+ "reviews",
805
+ "comments",
806
+ "reviewRequests",
807
+ "additions",
808
+ "deletions",
809
+ "changedFiles",
810
+ "files"
811
+ ].join(",");
812
+ var GhPrSourceAdapter = class {
813
+ run;
814
+ constructor(opts = {}) {
815
+ this.run = opts.run ?? defaultGhRunner(opts.ghBin ?? "gh");
816
+ }
817
+ async *listPullRequests(query) {
818
+ const numbers = await this.resolveNumbers(query);
819
+ for (const n of numbers) {
820
+ let pr;
821
+ try {
822
+ pr = await this.viewPr(query, n);
823
+ } catch (e) {
824
+ process.stderr.write(
825
+ `corpus: skipping ${query.repo}#${n} \u2014 ${msg2(e)}
826
+ `
827
+ );
828
+ continue;
829
+ }
830
+ if (pr) yield pr;
831
+ }
832
+ }
833
+ /** Resolve the query to a concrete, capped list of PR numbers. */
834
+ async resolveNumbers(query) {
835
+ const cap = query.maxPRs ?? 1e3;
836
+ if (query.prNumbers && query.prNumbers.length > 0) {
837
+ return query.prNumbers.slice(0, cap);
838
+ }
839
+ const args = [
840
+ "pr",
841
+ "list",
842
+ "--repo",
843
+ query.repo,
844
+ "--state",
845
+ "all",
846
+ "--limit",
847
+ String(cap),
848
+ "--json",
849
+ "number"
850
+ ];
851
+ if (query.since) args.push("--search", `updated:>=${query.since}`);
852
+ const out = await this.run(args);
853
+ return GH_PR_LIST.parse(parseJson(out)).map((item) => item.number).sort((a, b) => a - b);
854
+ }
855
+ /** Fetch one PR's detail and shape it into a PrDoc, or null if empty. */
856
+ async viewPr(query, number) {
857
+ const out = await this.run([
858
+ "pr",
859
+ "view",
860
+ String(number),
861
+ "--repo",
862
+ query.repo,
863
+ "--json",
864
+ VIEW_FIELDS
865
+ ]);
866
+ const v = GH_PR_VIEW.parse(parseJson(out));
867
+ const reviewComments = toReviewComments([
868
+ ...v.reviews ?? [],
869
+ ...v.comments ?? []
870
+ ]);
871
+ const reviewers = uniqueLogins([
872
+ ...(v.reviews ?? []).map((r) => r.author),
873
+ ...v.reviewRequests ?? []
874
+ ]);
875
+ const doc = {
876
+ number: v.number,
877
+ title: v.title ?? "",
878
+ body: v.body ?? "",
879
+ ...actorLabel(v.author) ? { author: actorLabel(v.author) } : {},
880
+ ...v.url ? { url: v.url } : {},
881
+ ...v.state ? { state: v.state.toLowerCase() } : {},
882
+ ...v.mergedAt ? { mergedAt: v.mergedAt } : {},
883
+ ...reviewers.length > 0 ? { reviewers } : {},
884
+ ...reviewComments.length > 0 ? { reviewComments } : {},
885
+ ...query.includeDiffSummary ? { diffSummary: buildDiffSummary(v) } : {}
886
+ };
887
+ return doc;
888
+ }
889
+ };
890
+ function actorLabel(actor) {
891
+ const label = actor?.login ?? actor?.name;
892
+ return label && label.length > 0 ? label : void 0;
893
+ }
894
+ function toReviewComments(raw) {
895
+ const out = [];
896
+ for (const c of raw) {
897
+ const body = (c.body ?? "").trim();
898
+ if (!body) continue;
899
+ const author = actorLabel(c.author);
900
+ const at = c.submittedAt ?? c.createdAt;
901
+ out.push({
902
+ body,
903
+ ...author ? { author } : {},
904
+ ...c.path ? { path: c.path } : {},
905
+ ...at ? { at } : {}
906
+ });
907
+ }
908
+ return out;
909
+ }
910
+ function uniqueLogins(actors) {
911
+ const seen = /* @__PURE__ */ new Set();
912
+ for (const a of actors) {
913
+ const label = actorLabel(a);
914
+ if (label) seen.add(label);
915
+ }
916
+ return [...seen];
917
+ }
918
+ function buildDiffSummary(v) {
919
+ const lines = [];
920
+ for (const f of v.files ?? []) {
921
+ const add = f.additions ?? 0;
922
+ const del = f.deletions ?? 0;
923
+ lines.push(`${f.path} | +${add} -${del}`);
924
+ }
925
+ const totals = v.changedFiles !== void 0 ? `${v.changedFiles} files changed, +${v.additions ?? 0} -${v.deletions ?? 0}` : void 0;
926
+ return [...totals ? [totals] : [], ...lines].join("\n");
927
+ }
928
+ function parseJson(out) {
929
+ const trimmed = out.trim();
930
+ if (!trimmed) return [];
931
+ return JSON.parse(trimmed);
932
+ }
933
+ function msg2(e) {
934
+ return e instanceof Error ? e.message : String(e);
935
+ }
936
+ function defaultGhRunner(bin) {
937
+ return async (args) => {
938
+ const { stdout } = await execFileAsync3(bin, [...args], {
939
+ maxBuffer: 32 * 1024 * 1024
940
+ });
941
+ return stdout;
942
+ };
943
+ }
764
944
 
765
945
  // src/ports/anthropic-distiller.ts
766
946
  var ANTHROPIC_RESPONSE = z.object({
@@ -1084,10 +1264,10 @@ var SseMcpClient = class {
1084
1264
  try {
1085
1265
  const parsed = RPC_MESSAGE.safeParse(JSON.parse(payload));
1086
1266
  if (!parsed.success) return;
1087
- const msg3 = parsed.data;
1088
- if (typeof msg3.id === "number" && this.pending.has(msg3.id)) {
1089
- this.pending.get(msg3.id)(msg3);
1090
- this.pending.delete(msg3.id);
1267
+ const msg4 = parsed.data;
1268
+ if (typeof msg4.id === "number" && this.pending.has(msg4.id)) {
1269
+ this.pending.get(msg4.id)(msg4);
1270
+ this.pending.delete(msg4.id);
1091
1271
  }
1092
1272
  } catch {
1093
1273
  }
@@ -1154,7 +1334,7 @@ var McpSink = class {
1154
1334
  try {
1155
1335
  client = await this.ensure();
1156
1336
  } catch (e) {
1157
- return { uri: item.uri, ok: false, error: `connect: ${msg2(e)}` };
1337
+ return { uri: item.uri, ok: false, error: `connect: ${msg3(e)}` };
1158
1338
  }
1159
1339
  const args = template(this.config.args, item);
1160
1340
  const call = this.config.importedAlias ? { name: "mcp_imported_call", args: { alias: this.config.importedAlias, toolName: this.config.tool, args } } : { name: this.config.tool, args };
@@ -1163,7 +1343,7 @@ var McpSink = class {
1163
1343
  if (res.isError) return { uri: item.uri, ok: false, error: "tool returned isError" };
1164
1344
  return { uri: item.uri, ok: true };
1165
1345
  } catch (e) {
1166
- return { uri: item.uri, ok: false, error: msg2(e) };
1346
+ return { uri: item.uri, ok: false, error: msg3(e) };
1167
1347
  }
1168
1348
  }
1169
1349
  };
@@ -1207,10 +1387,10 @@ function stringify(v) {
1207
1387
  if (Array.isArray(v)) return v.join(", ");
1208
1388
  return v == null ? "" : String(v);
1209
1389
  }
1210
- function msg2(e) {
1390
+ function msg3(e) {
1211
1391
  return e instanceof Error ? e.message : String(e);
1212
1392
  }
1213
1393
 
1214
- export { AnthropicDistiller, AssemblyAiStt, BrowserMcpFetcher, CLI_ENGINES, ChunkedStt, CliAgentDistiller, CompositeFetcher, HttpReadabilityFetcher, McpSink, NodeFsAdapter, OpenAiWhisperStt, OsIdentityAdapter, ScrapeMcpFetcher, ThrottleFetcher, YtDlpWhisperFetcher, connectMcpHttp };
1394
+ export { AnthropicDistiller, AssemblyAiStt, BrowserMcpFetcher, CLI_ENGINES, ChunkedStt, CliAgentDistiller, CompositeFetcher, GhPrSourceAdapter, HttpReadabilityFetcher, McpSink, NodeFsAdapter, OpenAiWhisperStt, OsIdentityAdapter, ScrapeMcpFetcher, ThrottleFetcher, YtDlpWhisperFetcher, connectMcpHttp };
1215
1395
  //# sourceMappingURL=index.mjs.map
1216
1396
  //# sourceMappingURL=index.mjs.map