@agentproto/corpus 0.1.0-alpha.1 → 0.1.0-alpha.3

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.
@@ -0,0 +1,93 @@
1
+ import { z } from 'zod';
2
+ import matter from 'gray-matter';
3
+
4
+ /**
5
+ * @agentproto/corpus v0.1.0-alpha
6
+ * Composition of AIP-10/12/18/9/15/41 — autonomous knowledge-improvement kit.
7
+ */
8
+
9
+ var REFINED_KIND_SCHEMA = z.enum([
10
+ "principle",
11
+ "pattern",
12
+ "critique",
13
+ "summary",
14
+ "example"
15
+ ]);
16
+ function isRefinedKind(value) {
17
+ return REFINED_KIND_SCHEMA.safeParse(value).success;
18
+ }
19
+ var ENTRY_FRONTMATTER = z.object({
20
+ schema: z.string().optional().catch(void 0),
21
+ slug: z.string().optional().catch(void 0),
22
+ kind: z.string().optional().catch(void 0),
23
+ title: z.string().optional().catch(void 0),
24
+ sources: z.array(z.string()).optional().catch(void 0),
25
+ confidence: z.number().optional().catch(void 0),
26
+ tags: z.array(z.string()).optional().catch(void 0),
27
+ metadata: z.object({
28
+ corpus: z.object({
29
+ access: z.string().optional().catch(void 0),
30
+ status: z.string().optional().catch(void 0),
31
+ // Resolved provenance written at promote time — the origins this
32
+ // entry was distilled from, so a recall can cite the real source.
33
+ source_refs: z.array(
34
+ z.object({
35
+ id: z.string(),
36
+ url: z.string().optional().catch(void 0),
37
+ title: z.string().optional().catch(void 0),
38
+ authority: z.string().optional().catch(void 0),
39
+ language: z.string().optional().catch(void 0)
40
+ }).loose()
41
+ ).optional().catch(void 0)
42
+ }).loose().optional().catch(void 0)
43
+ }).loose().optional().catch(void 0)
44
+ }).loose();
45
+ async function resolveKnowledge(opts) {
46
+ const { fs, query, allowedAccess } = opts;
47
+ const wantTags = new Set((query.tags ?? []).map((t) => t.toLowerCase()));
48
+ const wantKinds = query.kinds ? new Set(query.kinds) : null;
49
+ let rels;
50
+ try {
51
+ rels = await fs.walk("entries");
52
+ } catch {
53
+ return [];
54
+ }
55
+ const hits = [];
56
+ for (const rel of rels) {
57
+ if (!rel.endsWith(".md")) continue;
58
+ const path = `entries/${rel}`;
59
+ let parsed;
60
+ try {
61
+ parsed = matter(await fs.readFile(path));
62
+ } catch {
63
+ continue;
64
+ }
65
+ const fm = ENTRY_FRONTMATTER.parse(parsed.data);
66
+ if (fm.schema !== "knowledge.entry/v1") continue;
67
+ if (fm.metadata?.corpus?.status === "archived") continue;
68
+ const kind = fm.kind ?? "";
69
+ if (wantKinds && !(isRefinedKind(kind) && wantKinds.has(kind))) continue;
70
+ const tags = fm.tags ?? [];
71
+ if (wantTags.size > 0 && !tags.some((t) => wantTags.has(t.toLowerCase()))) continue;
72
+ const access = fm.metadata?.corpus?.access;
73
+ if (allowedAccess && access && !allowedAccess.has(access)) continue;
74
+ hits.push({
75
+ slug: fm.slug ?? path,
76
+ kind,
77
+ title: fm.title ?? "",
78
+ body: parsed.content.trim(),
79
+ sources: fm.sources ?? [],
80
+ ...fm.metadata?.corpus?.source_refs ? { sourceRefs: fm.metadata.corpus.source_refs } : {},
81
+ confidence: fm.confidence ?? 0,
82
+ tags,
83
+ ...access ? { access } : {},
84
+ path
85
+ });
86
+ }
87
+ hits.sort((a, b) => b.confidence - a.confidence);
88
+ return query.maxResults !== void 0 ? hits.slice(0, query.maxResults) : hits;
89
+ }
90
+
91
+ export { REFINED_KIND_SCHEMA, isRefinedKind, resolveKnowledge };
92
+ //# sourceMappingURL=chunk-3P23OX5X.mjs.map
93
+ //# sourceMappingURL=chunk-3P23OX5X.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/distill/types.ts","../src/knowledge/resolve.ts"],"names":["z"],"mappings":";;;;;;;;AAgBO,IAAM,mBAAA,GAAsB,EAAE,IAAA,CAAK;AAAA,EACxC,WAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA,EACA,SAAA;AAAA,EACA;AACF,CAAC;AAKM,SAAS,cAAc,KAAA,EA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AAU,MAAA,EAAQ,WAAA,GACrB,EAAE,UAAA,EAAY,EAAA,CAAG,QAAA,CAAS,MAAA,CAAO,WAAA,EAAY,GAC7C,EAAC;AAAA,MACL,UAAA,EAAY,GAAG,UAAA,IAAc,CAAA;AAAA,MAC7B,IAAA;AAAA,MACA,GAAI,MAAA,GAAS,EAAE,MAAA,KAAW,EAAC;AAAA,MAC3B;AAAA,KACD,CAAA;AAAA,EACH;AAEA,EAAA,IAAA,CAAK,KAAK,CAAC,CAAA,EAAG,MAAM,CAAA,CAAE,UAAA,GAAa,EAAE,UAAU,CAAA;AAC/C,EAAA,OAAO,KAAA,CAAM,eAAe,MAAA,GAAY,IAAA,CAAK,MAAM,CAAA,EAAG,KAAA,CAAM,UAAU,CAAA,GAAI,IAAA;AAC5E","file":"chunk-3P23OX5X.mjs","sourcesContent":["/**\n * Distill — raw source → refined knowledge entries (the KNOWLEDGE layer).\n *\n * The \"simple mode\": no graph engine. A refined entry is just an AIP-10\n * `knowledge.entry/v1` markdown file whose `sources: [<id>]` frontmatter\n * IS the `derivedFrom` provenance edge. The filesystem refs ARE the graph;\n * a graph engine (mind-graph / gbrain) is an optional index added later.\n *\n * The kit owns the contract + the runner (what to write, where, with what\n * provenance). The LLM that actually extracts insights is an injected\n * `DistillPort` — host-supplied (Claude/OpenAI), so the kit stays pure.\n */\n\nimport { z } from \"zod\"\n\n/** Generic AIP-10 refined kinds — NOT domain-specific. */\nexport const REFINED_KIND_SCHEMA = z.enum([\n \"principle\",\n \"pattern\",\n \"critique\",\n \"summary\",\n \"example\",\n])\n\nexport type RefinedKind = z.infer<typeof REFINED_KIND_SCHEMA>\n\n/** Runtime guard — narrows an untyped value to RefinedKind without a cast. */\nexport function isRefinedKind(value: unknown): value is RefinedKind {\n return REFINED_KIND_SCHEMA.safeParse(value).success\n}\n\nexport interface DistilledItem {\n readonly kind: RefinedKind\n readonly title: string\n /** The refined insight, markdown. Self-contained, not a quote dump. */\n readonly body: string\n /** 0–1 model confidence. */\n readonly confidence?: number\n readonly tags?: readonly string[]\n}\n\nexport interface DistillInput {\n readonly title: string\n readonly body: string\n readonly tags?: readonly string[]\n /** Hint for the kinds worth extracting (e.g. only principles). */\n readonly kinds?: readonly RefinedKind[]\n}\n\n/**\n * The LLM boundary. Given a raw source, return refined items. Injected by\n * the host (corpus-cli `AnthropicDistiller`, a Guilde operator, …) so the\n * kit takes no model dependency.\n */\nexport interface DistillPort {\n distill(input: DistillInput): Promise<readonly DistilledItem[]>\n}\n","/**\n * resolveKnowledge — the `knowledge:` binding resolver (KNOWLEDGE→SKILL link).\n *\n * Filesystem-first: a skill's binding (`{ tags, kinds }`) is resolved against\n * the refined `entries/**​/*.md` on disk — no graph engine. Returns the\n * matching refined entries (with their `sources:` provenance), filtered by the\n * caller's access scope so an operator never sees knowledge above its clearance.\n *\n * A graph engine (mind-graph / gbrain) can later replace this scan with\n * traversal/activation behind the SAME signature — the binding contract is stable.\n */\n\nimport matter from \"gray-matter\"\nimport { z } from \"zod\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport { isRefinedKind, type RefinedKind } from \"../distill/types.js\"\n\n/**\n * Lenient zod view of an AIP-10 entry's frontmatter. Every field `.catch`es to\n * undefined so a malformed value degrades gracefully (the entry is still\n * parsed, the bad field is simply absent) — matching the previous defensive\n * hand-narrowing, but typed and cast-free.\n */\nconst ENTRY_FRONTMATTER = z\n .object({\n schema: z.string().optional().catch(undefined),\n slug: z.string().optional().catch(undefined),\n kind: z.string().optional().catch(undefined),\n title: z.string().optional().catch(undefined),\n sources: z.array(z.string()).optional().catch(undefined),\n confidence: z.number().optional().catch(undefined),\n tags: z.array(z.string()).optional().catch(undefined),\n metadata: z\n .object({\n corpus: z\n .object({\n access: z.string().optional().catch(undefined),\n status: z.string().optional().catch(undefined),\n // Resolved provenance written at promote time — the origins this\n // entry was distilled from, so a recall can cite the real source.\n source_refs: z\n .array(\n z\n .object({\n id: z.string(),\n url: z.string().optional().catch(undefined),\n title: z.string().optional().catch(undefined),\n authority: z.string().optional().catch(undefined),\n language: z.string().optional().catch(undefined),\n })\n .loose()\n )\n .optional()\n .catch(undefined),\n })\n .loose()\n .optional()\n .catch(undefined),\n })\n .loose()\n .optional()\n .catch(undefined),\n })\n .loose()\n\nexport interface CorpusEntryQuery {\n /** Match entries sharing ANY of these tags. Empty/absent = no tag filter. */\n readonly tags?: readonly string[]\n /** Restrict to these refined kinds. Empty/absent = all kinds. */\n readonly kinds?: readonly RefinedKind[]\n /** Cap results (highest-confidence first). */\n readonly maxResults?: number\n}\n\n/** A resolved origin an entry was distilled from (id + where to find it). */\nexport interface SourceRef {\n readonly id: string\n readonly url?: string\n readonly title?: string\n readonly authority?: string\n readonly language?: string\n}\n\nexport interface ResolvedEntry {\n readonly slug: string\n readonly kind: string\n readonly title: string\n readonly body: string\n /** Provenance — the raw source ids this entry was derived from. */\n readonly sources: readonly string[]\n /** Resolved provenance — id + url + title for each source, when available. */\n readonly sourceRefs?: readonly SourceRef[]\n readonly confidence: number\n readonly tags: readonly string[]\n readonly access?: string\n readonly path: string\n}\n\nexport interface ResolveKnowledgeOptions {\n readonly fs: FsPort\n readonly query: CorpusEntryQuery\n /**\n * Access scopes the caller (operator) is cleared for. An entry passes if it\n * has no access (public) or its access ∈ this set. Omit = no access filter.\n */\n readonly allowedAccess?: ReadonlySet<string>\n}\n\nexport async function resolveKnowledge(\n opts: ResolveKnowledgeOptions\n): Promise<readonly ResolvedEntry[]> {\n const { fs, query, allowedAccess } = opts\n const wantTags = new Set((query.tags ?? []).map(t => t.toLowerCase()))\n const wantKinds = query.kinds ? new Set(query.kinds) : null\n\n let rels: readonly string[]\n try {\n rels = await fs.walk(\"entries\")\n } catch {\n return []\n }\n\n const hits: ResolvedEntry[] = []\n for (const rel of rels) {\n if (!rel.endsWith(\".md\")) continue\n // `walk(\"entries\")` yields paths relative to the entries/ dir; readFile\n // resolves against the workspace root, so re-prefix.\n const path = `entries/${rel}`\n let parsed\n try {\n parsed = matter(await fs.readFile(path))\n } catch {\n continue\n }\n const fm = ENTRY_FRONTMATTER.parse(parsed.data)\n if (fm.schema !== \"knowledge.entry/v1\") continue\n\n // Tombstone: a guild disables a pack entry by shadowing it (same path) with\n // status \"archived\". Filtered here so the overlaid archived entry hides the\n // pack's. Absent/active = shown — only an explicit archive subtracts.\n if (fm.metadata?.corpus?.status === \"archived\") continue\n\n const kind = fm.kind ?? \"\"\n if (wantKinds && !(isRefinedKind(kind) && wantKinds.has(kind))) continue\n\n const tags = fm.tags ?? []\n if (wantTags.size > 0 && !tags.some(t => wantTags.has(t.toLowerCase()))) continue\n\n const access = fm.metadata?.corpus?.access\n if (allowedAccess && access && !allowedAccess.has(access)) continue\n\n hits.push({\n slug: fm.slug ?? path,\n kind,\n title: fm.title ?? \"\",\n body: parsed.content.trim(),\n sources: fm.sources ?? [],\n ...(fm.metadata?.corpus?.source_refs\n ? { sourceRefs: fm.metadata.corpus.source_refs }\n : {}),\n confidence: fm.confidence ?? 0,\n tags,\n ...(access ? { access } : {}),\n path,\n })\n }\n\n hits.sort((a, b) => b.confidence - a.confidence)\n return query.maxResults !== undefined ? hits.slice(0, query.maxResults) : hits\n}\n"]}
@@ -0,0 +1,60 @@
1
+ /**
2
+ * FsPort — filesystem boundary the corpus kit consumes.
3
+ *
4
+ * Structural interface, NOT a nominal one — any object exposing this
5
+ * shape satisfies it. Matches the existing Guilde `WorkspaceFsLike`
6
+ * convention (projects/guilde/packages/core/src/services/role-source/
7
+ * workspace.ts:38-47) so cloud and local topologies share the same
8
+ * minimal contract.
9
+ *
10
+ * Paths are relative to the workspace root (no leading slash). The
11
+ * concrete implementation (MastraFilesystem in cloud, local-fs in CLI,
12
+ * mcp-filesystem for hybrid topologies) does the resolution.
13
+ */
14
+ interface FsStat {
15
+ readonly kind: "file" | "directory";
16
+ readonly bytes?: number;
17
+ readonly modifiedAt?: Date;
18
+ }
19
+ interface FsPort {
20
+ /** True if a file or directory exists at `path`. */
21
+ exists(path: string): Promise<boolean>;
22
+ /** Read a file as UTF-8 text. Throws on missing path. */
23
+ readFile(path: string): Promise<string>;
24
+ /**
25
+ * Write a file atomically — caller assumes content is persisted on
26
+ * resolve. Implementations are expected to write to a temp file +
27
+ * rename so partial writes never become visible.
28
+ */
29
+ writeFile(path: string, content: string): Promise<void>;
30
+ /**
31
+ * Append to a file. MUST be atomic against concurrent appends to the
32
+ * same path — used by the event emitter for _log.md. If the file
33
+ * does not exist, create it.
34
+ */
35
+ appendFile(path: string, content: string): Promise<void>;
36
+ /**
37
+ * List immediate children of a directory. Returns names only (NOT
38
+ * full paths). Throws if `path` is not a directory.
39
+ */
40
+ readdir(path: string): Promise<readonly string[]>;
41
+ /**
42
+ * Recursive directory listing — returns workspace-relative paths of
43
+ * every file under `path`. Skips directories starting with `.`.
44
+ */
45
+ walk(path: string): Promise<readonly string[]>;
46
+ /** File metadata. Returns null if the path doesn't exist. */
47
+ stat(path: string): Promise<FsStat | null>;
48
+ /**
49
+ * Acquire a cross-process advisory lock on `path`. Used by the
50
+ * writer for atomic multi-file transactions (entry write + _index
51
+ * regen + _log append). Implementations MAY no-op for single-process
52
+ * topologies (local CLI), but cloud hosts MUST enforce real locking.
53
+ */
54
+ lock(path: string): Promise<FsLockHandle>;
55
+ }
56
+ interface FsLockHandle {
57
+ release(): Promise<void>;
58
+ }
59
+
60
+ export type { FsPort as F, FsStat as a, FsLockHandle as b };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
- import { FsPort, ClockPort, IdentityPort, FetcherPort, FsStat, FsLockHandle, EvalRubricPort, EvalContextPort, EvaluatorPort } from './ports/index.js';
1
+ import { ClockPort, IdentityPort, FetcherPort, EvalRubricPort, EvalContextPort, EvaluatorPort } from './ports/index.js';
2
2
  export { CallerIdentity, EvalInputPort, EvalResultPort, FetchedSource, FetchedSourceKind, systemClock } from './ports/index.js';
3
+ import { F as FsPort, a as FsStat, b as FsLockHandle } from './fs.port-BHzctsoT.js';
3
4
  import { z } from 'zod';
5
+ import { R as ReportModelPort } from './model-CtAaBJn4.js';
4
6
  import { Registry } from '@agentproto/registry';
5
7
 
6
8
  /**
@@ -971,6 +973,26 @@ declare function parseItems(text: string): DistilledItem[];
971
973
 
972
974
  declare function scanDistilledSourceIds(fs: FsPort): Promise<Set<string>>;
973
975
 
976
+ /**
977
+ * modelDistiller — a {@link DistillPort} backed by any structural model port
978
+ * (`complete({prompt}) → {result}`). This is the seam that unifies distill with
979
+ * the report writer: both are `buildPrompt → model.complete → parse`, so the
980
+ * SAME executor (an API ModelPort, or `makeAgentCliModel(runtime)` over ANY
981
+ * AIP-45 agent CLI — Hermes, claude-code, opencode, codex …) drives both.
982
+ *
983
+ * Owns only the distill-specific glue (the shared prompt + tolerant parse); the
984
+ * model supplies the transport. Pure — no HTTP, no child process. The CLI's
985
+ * `--engine <id>` selection and the HTTP `AnthropicDistiller` are now two
986
+ * instances of the same shape.
987
+ */
988
+
989
+ interface ModelDistillerOptions {
990
+ /** Max distilled items requested per source. Default 8. */
991
+ maxItems?: number;
992
+ }
993
+ /** Wrap a structural model port as a DistillPort (prompt → complete → parse). */
994
+ declare function modelDistiller(model: ReportModelPort, opts?: ModelDistillerOptions): DistillPort;
995
+
974
996
  /**
975
997
  * Distill registry — the catalog of distill kinds.
976
998
  *
@@ -2890,4 +2912,4 @@ declare class PlaybookEvaluator {
2890
2912
  declare const SPEC_NAME: "agentcorpus/v1";
2891
2913
  declare const SPEC_VERSION: "0.1.0-alpha";
2892
2914
 
2893
- export { ANY_REF, type AccessCaller, type AccessClassification, type AccessContext, type AccessDecision, type AccessModesMap, type ActivateResult, type AggregateOptions, type AggregateResult, type AipSchemaBundle, type AipSchemaKey, type ArchiveResult, type AttachmentAsset, type AttachmentDeclaration, type Attestation, type AttestationKind, type AutoPromoteConfig, type AutoPromoteRequirements, type AxisDefinition, type AxisRegistry, type BatchReport, type BuildOverlayOptions, type CalibrationOptions, type CandidateForGate, type CandidateRow, type CandidateStatus, CandidatesSidecar, type CandidatesSidecarOptions, type Capability, type CapabilityCaller, type CapabilityDecision, type CapabilityRule, type ChunkerOptions, ClaudeDistiller, type ClaudeDistillerOptions, ClockPort, type ConversationDoc, ConversationImporter, type ConversationImporterOptions, type ConversationSourcePort, type ConversationThreadRef, type ConversationTurn, type ConversationWindowSource, type CorpusAccessSpec, type CorpusEntryQuery, type CorpusEvent, CorpusEventEmitter, type CorpusEventEmitterOptions, type CorpusEventKind, type CorpusImporter, CorpusIndexer, type CorpusIndexerOptions, CorpusLinter, type CorpusLinterOptions, type CorpusPreset, type CorpusPresetBootstrapContext, CorpusPromoter, CorpusValidator, type CorpusValidatorOptions, CorpusVersionConflictError, CorpusWorkspaceReader, type CorpusWorkspaceReaderOptions, type CorpusWorkspaceSnapshot, CorpusWorkspaceWriter, type CorpusWorkspaceWriterOptions, type CustomLintRunner, DEFAULT_TRANSITIONS, type Dimensions, type DistillBinding, type DistillDescriptor, type DistillInput, type DistillPort, type DistillRegistry, type DistillReport, type DistillRunReport, DistillRunner, type DistillRunnerOptions, type DistillScope, type DistillSource, type DistillTarget, type DistilledItem, EMPTY_SELECTOR, type EntryLayout, type EvalCase, EvalContextPort, EvalRubricPort, EvaluatorPort, FetcherPort, type FileKind, FsLockHandle, FsPort, FsStat, type GateFailure, type GateResult, IdentityPort, IllegalPlaybookTransitionError, IllegalTransitionError, type ImportedSource, ImporterRunner, type ImporterRunnerOptions, type ImporterTarget, type IndexReport, type KbListLike, type KbMigrationConfig, KbMigrationImporter, type KbSourceLike, type LanguageFilter, type LayerMode, type LayerProvider, type LayerRef, type LayerShadow, type LintIssue, type LintReport, LocalFilesImporter, type LocalFilesImporterOptions, type MarkdownDoc, type MatchAttachmentsOptions, type MatchOptions, MemFs, OperatorOverlayResolver, OverlayFs, type OverlayFsOptions, type ParsedFile, type Playbook, type PlaybookBatchOptions, type PlaybookBatchResult, type PlaybookCorpusMeta, PlaybookEvaluator, type PlaybookEvaluatorOptions, type PlaybookKind, PlaybookLifecycle, type PlaybookLifecycleOptions, PlaybookNotFoundError, type PlaybookQuery, PlaybookRegistry, type PlaybookRegistryOptions, type PlaybookStatus, type PlaybookTarget, type PlaybookTargetKind, type PromoteContext, type PromoteOptions, PromoteRejectedError, type PromoteResult, type PushChunksInput, REFINED_KIND_SCHEMA, ReadOnlyFs, type RefinedKind, type RenderedOverlays, type ResolutionContext, type ResolveContext, type ResolveKnowledgeOptions, type ResolveLanguageFilterInput, type ResolveResult, type ResolvedEntry, type ResolvedOverlay, type ReviewerCalibration, type ReviewerScore, ReviewerTrackRecord, type ReviewerTrackRecordOptions, SPEC_NAME, SPEC_VERSION, type Selector, type SelectorTerm, SidecarDuplicateError, SidecarNotFoundError, type SinkItem, type SinkPort, type SinkPushResult, type SlugifyOptions, type SourceRef, type StackEntry, type StackRefPartition, type StackResolution, StackResolver, type StackSkip, type SyncReport, SyncRunner, type SyncRunnerOptions, type TrackRecordEntry, type TransitionCheck, type ValidationIssue, type ValidationResult, WELL_KNOWN_AXES, WHITEOUT_SUFFIX, WebImporter, type WebImporterOptions, type WriterChunk, type WriterPort, aggregateReviewerScores, appendAttestation, assertTransition, buildDistillPrompt, buildOverlayFromStack, canTransition, capabilityAxis, chunkText, compileLegacyPlaybookBinding, computeReviewerCalibration, createAxisRegistry, createDistillRegistry, enumerateWindowRefs, evaluateAccess, evaluateCapability, evaluateGate, extractAutoPromoteConfig, flattenPackRefs, identityAxis, isEmptySelector, isEntrySlug, isRefinedKind, isSourceSlug, makeAttestation, matchAttachmentRefs, matchAttachments, matchesLanguageFilter, matchesSelector, normalizeLanguageTag, parseItems, parseSelectorFrontmatter, parseWindowRef, partitionStackRefs, pearsonCorrelation, positionAxis, prefixedRefNormalizer, readAccessModes, readAccessSpec, readAttestations, readEntryLanguage, readOperatorLocale, readWorkspaceDefaultLanguage, renderOverlays, resolveKnowledge, resolveLanguageFilter, roleAxis, runDistill, scanDistilledSourceIds, slugify, transitionGraphFromCollection, uniqueSlug, windowRef, windowSlug };
2915
+ export { ANY_REF, type AccessCaller, type AccessClassification, type AccessContext, type AccessDecision, type AccessModesMap, type ActivateResult, type AggregateOptions, type AggregateResult, type AipSchemaBundle, type AipSchemaKey, type ArchiveResult, type AttachmentAsset, type AttachmentDeclaration, type Attestation, type AttestationKind, type AutoPromoteConfig, type AutoPromoteRequirements, type AxisDefinition, type AxisRegistry, type BatchReport, type BuildOverlayOptions, type CalibrationOptions, type CandidateForGate, type CandidateRow, type CandidateStatus, CandidatesSidecar, type CandidatesSidecarOptions, type Capability, type CapabilityCaller, type CapabilityDecision, type CapabilityRule, type ChunkerOptions, ClaudeDistiller, type ClaudeDistillerOptions, ClockPort, type ConversationDoc, ConversationImporter, type ConversationImporterOptions, type ConversationSourcePort, type ConversationThreadRef, type ConversationTurn, type ConversationWindowSource, type CorpusAccessSpec, type CorpusEntryQuery, type CorpusEvent, CorpusEventEmitter, type CorpusEventEmitterOptions, type CorpusEventKind, type CorpusImporter, CorpusIndexer, type CorpusIndexerOptions, CorpusLinter, type CorpusLinterOptions, type CorpusPreset, type CorpusPresetBootstrapContext, CorpusPromoter, CorpusValidator, type CorpusValidatorOptions, CorpusVersionConflictError, CorpusWorkspaceReader, type CorpusWorkspaceReaderOptions, type CorpusWorkspaceSnapshot, CorpusWorkspaceWriter, type CorpusWorkspaceWriterOptions, type CustomLintRunner, DEFAULT_TRANSITIONS, type Dimensions, type DistillBinding, type DistillDescriptor, type DistillInput, type DistillPort, type DistillRegistry, type DistillReport, type DistillRunReport, DistillRunner, type DistillRunnerOptions, type DistillScope, type DistillSource, type DistillTarget, type DistilledItem, EMPTY_SELECTOR, type EntryLayout, type EvalCase, EvalContextPort, EvalRubricPort, EvaluatorPort, FetcherPort, type FileKind, FsLockHandle, FsPort, FsStat, type GateFailure, type GateResult, IdentityPort, IllegalPlaybookTransitionError, IllegalTransitionError, type ImportedSource, ImporterRunner, type ImporterRunnerOptions, type ImporterTarget, type IndexReport, type KbListLike, type KbMigrationConfig, KbMigrationImporter, type KbSourceLike, type LanguageFilter, type LayerMode, type LayerProvider, type LayerRef, type LayerShadow, type LintIssue, type LintReport, LocalFilesImporter, type LocalFilesImporterOptions, type MarkdownDoc, type MatchAttachmentsOptions, type MatchOptions, MemFs, type ModelDistillerOptions, OperatorOverlayResolver, OverlayFs, type OverlayFsOptions, type ParsedFile, type Playbook, type PlaybookBatchOptions, type PlaybookBatchResult, type PlaybookCorpusMeta, PlaybookEvaluator, type PlaybookEvaluatorOptions, type PlaybookKind, PlaybookLifecycle, type PlaybookLifecycleOptions, PlaybookNotFoundError, type PlaybookQuery, PlaybookRegistry, type PlaybookRegistryOptions, type PlaybookStatus, type PlaybookTarget, type PlaybookTargetKind, type PromoteContext, type PromoteOptions, PromoteRejectedError, type PromoteResult, type PushChunksInput, REFINED_KIND_SCHEMA, ReadOnlyFs, type RefinedKind, type RenderedOverlays, type ResolutionContext, type ResolveContext, type ResolveKnowledgeOptions, type ResolveLanguageFilterInput, type ResolveResult, type ResolvedEntry, type ResolvedOverlay, type ReviewerCalibration, type ReviewerScore, ReviewerTrackRecord, type ReviewerTrackRecordOptions, SPEC_NAME, SPEC_VERSION, type Selector, type SelectorTerm, SidecarDuplicateError, SidecarNotFoundError, type SinkItem, type SinkPort, type SinkPushResult, type SlugifyOptions, type SourceRef, type StackEntry, type StackRefPartition, type StackResolution, StackResolver, type StackSkip, type SyncReport, SyncRunner, type SyncRunnerOptions, type TrackRecordEntry, type TransitionCheck, type ValidationIssue, type ValidationResult, WELL_KNOWN_AXES, WHITEOUT_SUFFIX, WebImporter, type WebImporterOptions, type WriterChunk, type WriterPort, aggregateReviewerScores, appendAttestation, assertTransition, buildDistillPrompt, buildOverlayFromStack, canTransition, capabilityAxis, chunkText, compileLegacyPlaybookBinding, computeReviewerCalibration, createAxisRegistry, createDistillRegistry, enumerateWindowRefs, evaluateAccess, evaluateCapability, evaluateGate, extractAutoPromoteConfig, flattenPackRefs, identityAxis, isEmptySelector, isEntrySlug, isRefinedKind, isSourceSlug, makeAttestation, matchAttachmentRefs, matchAttachments, matchesLanguageFilter, matchesSelector, modelDistiller, normalizeLanguageTag, parseItems, parseSelectorFrontmatter, parseWindowRef, partitionStackRefs, pearsonCorrelation, positionAxis, prefixedRefNormalizer, readAccessModes, readAccessSpec, readAttestations, readEntryLanguage, readOperatorLocale, readWorkspaceDefaultLanguage, renderOverlays, resolveKnowledge, resolveLanguageFilter, roleAxis, runDistill, scanDistilledSourceIds, slugify, transitionGraphFromCollection, uniqueSlug, windowRef, windowSlug };
package/dist/index.mjs CHANGED
@@ -1,4 +1,6 @@
1
1
  export { systemClock } from './chunk-KYX2DTEH.mjs';
2
+ import { REFINED_KIND_SCHEMA, resolveKnowledge } from './chunk-3P23OX5X.mjs';
3
+ export { REFINED_KIND_SCHEMA, isRefinedKind, resolveKnowledge } from './chunk-3P23OX5X.mjs';
2
4
  import { CandidatesSidecar } from './chunk-UPX26MYH.mjs';
3
5
  export { CandidatesSidecar, SidecarDuplicateError, SidecarNotFoundError } from './chunk-UPX26MYH.mjs';
4
6
  import matter from 'gray-matter';
@@ -1054,16 +1056,6 @@ function sanitizeTag(raw) {
1054
1056
  const t = raw.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").replace(/-{2,}/g, "-");
1055
1057
  return /^[a-z][a-z0-9-]*$/.test(t) ? t : null;
1056
1058
  }
1057
- var REFINED_KIND_SCHEMA = z.enum([
1058
- "principle",
1059
- "pattern",
1060
- "critique",
1061
- "summary",
1062
- "example"
1063
- ]);
1064
- function isRefinedKind(value) {
1065
- return REFINED_KIND_SCHEMA.safeParse(value).success;
1066
- }
1067
1059
  var DISTILLED_ITEM = z.object({
1068
1060
  kind: REFINED_KIND_SCHEMA,
1069
1061
  title: z.string(),
@@ -1141,6 +1133,19 @@ async function scanDistilledSourceIds(fs) {
1141
1133
  return ids;
1142
1134
  }
1143
1135
 
1136
+ // src/distill/model-distiller.ts
1137
+ function modelDistiller(model, opts = {}) {
1138
+ const maxItems = opts.maxItems ?? 8;
1139
+ return {
1140
+ async distill(input) {
1141
+ const prompt = buildDistillPrompt(input, maxItems);
1142
+ const { result } = await model.complete({ prompt });
1143
+ const text = typeof result === "string" ? result : JSON.stringify(result);
1144
+ return parseItems(text);
1145
+ }
1146
+ };
1147
+ }
1148
+
1144
1149
  // src/distill/registry.ts
1145
1150
  function createDistillRegistry() {
1146
1151
  const descriptors = /* @__PURE__ */ new Map();
@@ -1282,77 +1287,6 @@ async function enumerateWindowRefs(source, distilled) {
1282
1287
  }
1283
1288
  return refs;
1284
1289
  }
1285
- var ENTRY_FRONTMATTER = z.object({
1286
- schema: z.string().optional().catch(void 0),
1287
- slug: z.string().optional().catch(void 0),
1288
- kind: z.string().optional().catch(void 0),
1289
- title: z.string().optional().catch(void 0),
1290
- sources: z.array(z.string()).optional().catch(void 0),
1291
- confidence: z.number().optional().catch(void 0),
1292
- tags: z.array(z.string()).optional().catch(void 0),
1293
- metadata: z.object({
1294
- corpus: z.object({
1295
- access: z.string().optional().catch(void 0),
1296
- status: z.string().optional().catch(void 0),
1297
- // Resolved provenance written at promote time — the origins this
1298
- // entry was distilled from, so a recall can cite the real source.
1299
- source_refs: z.array(
1300
- z.object({
1301
- id: z.string(),
1302
- url: z.string().optional().catch(void 0),
1303
- title: z.string().optional().catch(void 0),
1304
- authority: z.string().optional().catch(void 0),
1305
- language: z.string().optional().catch(void 0)
1306
- }).loose()
1307
- ).optional().catch(void 0)
1308
- }).loose().optional().catch(void 0)
1309
- }).loose().optional().catch(void 0)
1310
- }).loose();
1311
- async function resolveKnowledge(opts) {
1312
- const { fs, query, allowedAccess } = opts;
1313
- const wantTags = new Set((query.tags ?? []).map((t) => t.toLowerCase()));
1314
- const wantKinds = query.kinds ? new Set(query.kinds) : null;
1315
- let rels;
1316
- try {
1317
- rels = await fs.walk("entries");
1318
- } catch {
1319
- return [];
1320
- }
1321
- const hits = [];
1322
- for (const rel of rels) {
1323
- if (!rel.endsWith(".md")) continue;
1324
- const path = `entries/${rel}`;
1325
- let parsed;
1326
- try {
1327
- parsed = matter(await fs.readFile(path));
1328
- } catch {
1329
- continue;
1330
- }
1331
- const fm = ENTRY_FRONTMATTER.parse(parsed.data);
1332
- if (fm.schema !== "knowledge.entry/v1") continue;
1333
- if (fm.metadata?.corpus?.status === "archived") continue;
1334
- const kind = fm.kind ?? "";
1335
- if (wantKinds && !(isRefinedKind(kind) && wantKinds.has(kind))) continue;
1336
- const tags = fm.tags ?? [];
1337
- if (wantTags.size > 0 && !tags.some((t) => wantTags.has(t.toLowerCase()))) continue;
1338
- const access = fm.metadata?.corpus?.access;
1339
- if (allowedAccess && access && !allowedAccess.has(access)) continue;
1340
- hits.push({
1341
- slug: fm.slug ?? path,
1342
- kind,
1343
- title: fm.title ?? "",
1344
- body: parsed.content.trim(),
1345
- sources: fm.sources ?? [],
1346
- ...fm.metadata?.corpus?.source_refs ? { sourceRefs: fm.metadata.corpus.source_refs } : {},
1347
- confidence: fm.confidence ?? 0,
1348
- tags,
1349
- ...access ? { access } : {},
1350
- path
1351
- });
1352
- }
1353
- hits.sort((a, b) => b.confidence - a.confidence);
1354
- return query.maxResults !== void 0 ? hits.slice(0, query.maxResults) : hits;
1355
- }
1356
1290
 
1357
1291
  // src/knowledge/overlay-fs.ts
1358
1292
  var WHITEOUT_SUFFIX = ".whiteout";
@@ -3375,6 +3309,6 @@ function joinPath5(a, b) {
3375
3309
  var SPEC_NAME = "agentcorpus/v1";
3376
3310
  var SPEC_VERSION = "0.1.0-alpha";
3377
3311
 
3378
- export { ANY_REF, ClaudeDistiller, ConversationImporter, CorpusEventEmitter, CorpusIndexer, CorpusLinter, CorpusPromoter, CorpusValidator, CorpusVersionConflictError, CorpusWorkspaceReader, CorpusWorkspaceWriter, DEFAULT_TRANSITIONS, DistillRunner, EMPTY_SELECTOR, IllegalPlaybookTransitionError, IllegalTransitionError, ImporterRunner, KbMigrationImporter, LocalFilesImporter, MemFs, OperatorOverlayResolver, OverlayFs, PlaybookEvaluator, PlaybookLifecycle, PlaybookNotFoundError, PlaybookRegistry, PromoteRejectedError, REFINED_KIND_SCHEMA, ReadOnlyFs, ReviewerTrackRecord, SPEC_NAME, SPEC_VERSION, StackResolver, SyncRunner, WELL_KNOWN_AXES, WHITEOUT_SUFFIX, WebImporter, aggregateReviewerScores, appendAttestation, assertTransition, buildDistillPrompt, buildOverlayFromStack, canTransition, capabilityAxis, chunkText, compileLegacyPlaybookBinding, computeReviewerCalibration, createAxisRegistry, createDistillRegistry, enumerateWindowRefs, evaluateAccess, evaluateCapability, evaluateGate, extractAutoPromoteConfig, flattenPackRefs, identityAxis, isEmptySelector, isEntrySlug, isRefinedKind, isSourceSlug, makeAttestation, matchAttachmentRefs, matchAttachments, matchesLanguageFilter, matchesSelector, normalizeLanguageTag, parseItems, parseSelectorFrontmatter, parseWindowRef, partitionStackRefs, pearsonCorrelation, positionAxis, prefixedRefNormalizer, readAccessModes, readAccessSpec, readAttestations, readEntryLanguage, readOperatorLocale, readWorkspaceDefaultLanguage, renderOverlays, resolveKnowledge, resolveLanguageFilter, roleAxis, runDistill, scanDistilledSourceIds, slugify, transitionGraphFromCollection, uniqueSlug, windowRef, windowSlug };
3312
+ export { ANY_REF, ClaudeDistiller, ConversationImporter, CorpusEventEmitter, CorpusIndexer, CorpusLinter, CorpusPromoter, CorpusValidator, CorpusVersionConflictError, CorpusWorkspaceReader, CorpusWorkspaceWriter, DEFAULT_TRANSITIONS, DistillRunner, EMPTY_SELECTOR, IllegalPlaybookTransitionError, IllegalTransitionError, ImporterRunner, KbMigrationImporter, LocalFilesImporter, MemFs, OperatorOverlayResolver, OverlayFs, PlaybookEvaluator, PlaybookLifecycle, PlaybookNotFoundError, PlaybookRegistry, PromoteRejectedError, ReadOnlyFs, ReviewerTrackRecord, SPEC_NAME, SPEC_VERSION, StackResolver, SyncRunner, WELL_KNOWN_AXES, WHITEOUT_SUFFIX, WebImporter, aggregateReviewerScores, appendAttestation, assertTransition, buildDistillPrompt, buildOverlayFromStack, canTransition, capabilityAxis, chunkText, compileLegacyPlaybookBinding, computeReviewerCalibration, createAxisRegistry, createDistillRegistry, enumerateWindowRefs, evaluateAccess, evaluateCapability, evaluateGate, extractAutoPromoteConfig, flattenPackRefs, identityAxis, isEmptySelector, isEntrySlug, isSourceSlug, makeAttestation, matchAttachmentRefs, matchAttachments, matchesLanguageFilter, matchesSelector, modelDistiller, normalizeLanguageTag, parseItems, parseSelectorFrontmatter, parseWindowRef, partitionStackRefs, pearsonCorrelation, positionAxis, prefixedRefNormalizer, readAccessModes, readAccessSpec, readAttestations, readEntryLanguage, readOperatorLocale, readWorkspaceDefaultLanguage, renderOverlays, resolveLanguageFilter, roleAxis, runDistill, scanDistilledSourceIds, slugify, transitionGraphFromCollection, uniqueSlug, windowRef, windowSlug };
3379
3313
  //# sourceMappingURL=index.mjs.map
3380
3314
  //# sourceMappingURL=index.mjs.map