@agentproto/corpus-cli 0.4.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/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"]}
@@ -233,8 +233,23 @@
233
233
  "default": { "type": "string", "description": "Default model id passed to the agent." },
234
234
  "allowed": {
235
235
  "type": "array",
236
- "items": { "type": "string" },
237
- "description": "Model ids the host MAY route to."
236
+ "items": {
237
+ "oneOf": [
238
+ { "type": "string" },
239
+ {
240
+ "type": "object",
241
+ "additionalProperties": false,
242
+ "required": ["id"],
243
+ "description": "A model id annotated with who serves/bills it and how this adapter reaches it. A bare string (still legal) leaves provider unstated — the projector MUST NOT guess one.",
244
+ "properties": {
245
+ "id": { "type": "string", "description": "Model id, unchanged on the wire — this is annotation, not renaming." },
246
+ "provider": { "type": "string", "description": "ProviderPreset id (or direct provider, e.g. \"anthropic\") — who serves and bills this model. Omit when unstated." },
247
+ "mode": { "type": "string", "description": "This adapter's mode id that routes to `provider` (e.g. \"moonshot\"). Omit when the adapter routes on its own (e.g. a model-id prefix) or needs no mode switch." }
248
+ }
249
+ }
250
+ ]
251
+ },
252
+ "description": "Model ids the host MAY route to. Each entry is either a bare id (provider unstated, adapter default) or a { id, provider?, mode? } binding declaring who serves it and which adapter mode reaches it."
238
253
  },
239
254
  "env": {
240
255
  "type": "object",
@@ -269,6 +284,10 @@
269
284
  "description": "Stable id. The operator config references this id."
270
285
  },
271
286
  "description": { "type": "string" },
287
+ "kind": {
288
+ "enum": ["context"],
289
+ "description": "Which orthogonal session-config axis this mode expresses. Narrowed to the single value 'context' (what enters context) — the only concern with no ACP-protocol home. Route is derived from the model catalog (@route route-identity), not a manifest mode; posture comes from the harness's own ACP mode registry (SessionModeState.availableModes). Omitted ⇒ inferred from the id. The legacy 'posture'/'route' back-compat classification lives in the daemon's decomposeMode shim, not this manifest surface."
290
+ },
272
291
  "bin_args_prepend": {
273
292
  "type": "array",
274
293
  "items": { "type": "string" },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentproto/corpus-cli",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "@agentproto/corpus-cli — the `corpus` binary. Validate, lint, and operate an AIP-10 corpus workspace from the command line. Local-topology host for @agentproto/corpus — pair with a local backing engine (qdrant docker / gbrain) for a fully offline corpus runtime.",
5
5
  "keywords": [
6
6
  "agentproto",