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

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/util/slug.ts","../src/util/language.ts","../src/lifecycle/attestations.ts","../src/access/policy.ts","../src/access/capability.ts","../src/access/language.ts","../src/events/emitter.ts","../src/workspace/reader.ts","../src/workspace/writer.ts","../src/importers/runner.ts","../src/importers/local-files.ts","../src/importers/kb-migration.ts","../src/importers/web.ts","../src/importers/conversation.ts","../src/distill/runner.ts","../src/distill/types.ts","../src/distill/prompt.ts","../src/distill/scan.ts","../src/distill/registry.ts","../src/distill/run.ts","../src/distill/claude-distiller.ts","../src/distill/windows.ts","../src/knowledge/resolve.ts","../src/knowledge/overlay-fs.ts","../src/knowledge/mem-fs.ts","../src/util/shadow-sample.ts","../src/stack/resolver.ts","../src/stack/mount.ts","../src/sink/runner.ts","../src/calibration/aggregate.ts","../src/calibration/track-record.ts","../src/calibration/correlation.ts","../src/validate/validator.ts","../src/validate/linter.ts","../src/lifecycle/candidate.ts","../src/lifecycle/gate.ts","../src/lifecycle/promote.ts","../src/index/chunker.ts","../src/index/indexer.ts","../src/binding/axes.ts","../src/binding/selector.ts","../src/binding/parse.ts","../src/binding/legacy.ts","../src/binding/attachment.ts","../src/playbooks/registry.ts","../src/playbooks/resolver.ts","../src/playbooks/lifecycle.ts","../src/playbooks/evaluator.ts","../src/index.ts"],"names":["createHash","matter","joinPath","sha256","parseConfig","z","acc","yamlParse","yamlStringify","CandidatesSidecar","allOf","readStatus","sampleShadow","assertTransition"],"mappings":";;;;;;;;;;;;;;;;;AAaA,IAAM,WAAA,GAAc,sBAAA;AACpB,IAAM,UAAA,GAAa,2BAAA;AAiBZ,SAAS,OAAA,CAAQ,KAAA,EAAe,IAAA,GAAuB,EAAC,EAAW;AACxE,EAAA,MAAM,MAAA,GAAS,KAAK,MAAA,IAAU,EAAA;A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,CAAA;AAC7C;;;ACxRO,IAAM,SAAA,GAAY;AAClB,IAAM,YAAA,GAAe","file":"index.mjs","sourcesContent":["/**\n * AIP-10 slug helpers — the single source of truth for turning arbitrary\n * text or paths into schema-valid slugs. Replaces the three drifted\n * `makeSlug` copies (web / local-files / distill importers) and the two\n * `uniqueSlug` copies, so a rule change lands once instead of in four\n * places.\n *\n * Two AIP-10 slug shapes:\n * - **source** id `^[a-z0-9][a-z0-9-]*$` — a leading digit is allowed.\n * - **entry / role / tag** id `^[a-z][a-z0-9-]*[a-z0-9]$` — must start\n * with a letter and end alphanumeric. Pass `leadingLetter: true`.\n */\n\nconst SOURCE_SLUG = /^[a-z0-9][a-z0-9-]*$/\nconst ENTRY_SLUG = /^[a-z][a-z0-9-]*[a-z0-9]$/\n\nexport interface SlugifyOptions {\n /** Max length before the trailing-dash trim. Default 96. */\n readonly maxLen?: number\n /** Returned when the slugified result is empty / degenerate. Default \"item\". */\n readonly fallback?: string\n /**\n * Guarantee the AIP-10 *entry* shape: a leading letter (prefix `e-` when\n * the slug would otherwise start with a digit) and length ≥ 2.\n */\n readonly leadingLetter?: boolean\n /** Strip a leading `http(s)://` first — for slugging a URL fallback. */\n readonly stripScheme?: boolean\n}\n\n/** Slugify arbitrary text into an AIP-10-valid id. */\nexport function slugify(input: string, opts: SlugifyOptions = {}): string {\n const maxLen = opts.maxLen ?? 96\n const fallback = opts.fallback ?? \"item\"\n let s = input\n .toLowerCase()\n .normalize(\"NFD\")\n .replace(/[̀-ͯ]/g, \"\") // strip combining diacritics\n if (opts.stripScheme) s = s.replace(/^https?:\\/\\//, \"\")\n s = s\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/-{2,}/g, \"-\")\n .slice(0, maxLen)\n .replace(/^-+|-+$/g, \"\") // trim AFTER slicing, so a cut mid-dash can't leave one\n if (opts.leadingLetter && s && !/^[a-z]/.test(s)) {\n s = `e-${s}`.slice(0, maxLen).replace(/-+$/g, \"\")\n }\n return s.length >= 2 ? s : fallback\n}\n\n/**\n * Disambiguate a slug against a set of already-used ones by appending\n * `-2`, `-3`, … The suffix is numeric, so an entry-shaped base stays\n * entry-valid (ends alphanumeric).\n */\nexport function uniqueSlug(base: string, seen: Set<string>, maxLen = 96): string {\n let slug = base\n let n = 2\n while (seen.has(slug)) {\n slug = `${base}-${n++}`.slice(0, maxLen).replace(/-+$/g, \"\")\n }\n seen.add(slug)\n return slug\n}\n\n/** True when `s` is a valid AIP-10 source id (leading digit allowed). */\nexport function isSourceSlug(s: string): boolean {\n return SOURCE_SLUG.test(s) && s.length >= 2 && s.length <= 96\n}\n\n/** True when `s` is a valid AIP-10 entry/role/tag id (leading letter). */\nexport function isEntrySlug(s: string): boolean {\n return ENTRY_SLUG.test(s) && s.length >= 2 && s.length <= 96\n}\n","/**\n * Language-tag normalization — the single source of truth for coercing a\n * raw language value into the AIP-10 source shape `^[a-z]{2}(-[A-Z]{2})?$`.\n *\n * Two upstreams feed it, which is why this used to be two drifted copies:\n * - **STT** (Whisper verbose_json) emits a full English NAME (\"english\",\n * \"french\").\n * - **readability / browser** fetchers read `<html lang>` VERBATIM, in any\n * case and separator (\"en-us\", \"EN\", \"pt_BR\", \"zh-Hant-TW\").\n *\n * One function handles both: map a known name → code, else parse a BCP-47\n * tag — lowercase the 2-letter primary, uppercase a genuine 2-letter region,\n * and discard scripts / extensions / 3-letter primaries (which the AIP-10\n * source schema doesn't allow) rather than emit something that fails\n * validation. Returns `undefined` for anything unparseable so the field is\n * omitted, never written invalid.\n */\n\nconst NAME_TO_CODE: Readonly<Record<string, string>> = {\n english: \"en\", french: \"fr\", spanish: \"es\", german: \"de\", italian: \"it\",\n portuguese: \"pt\", dutch: \"nl\", russian: \"ru\", japanese: \"ja\", korean: \"ko\",\n chinese: \"zh\", arabic: \"ar\", hindi: \"hi\", turkish: \"tr\", polish: \"pl\",\n swedish: \"sv\", norwegian: \"no\", danish: \"da\", finnish: \"fi\", greek: \"el\",\n hebrew: \"he\", thai: \"th\", vietnamese: \"vi\", indonesian: \"id\", ukrainian: \"uk\",\n}\n\nexport function normalizeLanguageTag(raw: string | undefined): string | undefined {\n if (!raw) return undefined\n const v = raw.trim().toLowerCase()\n if (!v) return undefined\n const named = NAME_TO_CODE[v]\n if (named) return named\n // BCP-47: subtags split on \"-\" or \"_\" (POSIX locales like pt_BR appear in\n // <html lang>). Require a 2-letter primary; append only a 2-letter region.\n const parts = v.split(/[-_]/)\n const primary = parts[0]\n if (!primary || !/^[a-z]{2}$/.test(primary)) return undefined\n const region = parts.slice(1).find(p => /^[a-z]{2}$/.test(p))\n return region ? `${primary}-${region.toUpperCase()}` : primary\n}\n","/**\n * Attestation helpers — append + read the per-transition audit chain\n * stored under `metadata.corpus.attestations[]`.\n *\n * Pure. The lifecycle workflows (promote, playbook activate/archive,\n * playbook evaluator) call `appendAttestation` immediately before\n * writing the file. Tooling that displays the chain (curator UI,\n * `corpus events:trace <slug>`) calls `readAttestations`.\n */\n\nimport type { Attestation } from \"../types.js\"\n\n/**\n * Append an attestation to a frontmatter object's\n * `metadata.corpus.attestations[]`. Returns a NEW frontmatter\n * object — mutation-free so callers can chain transformations.\n *\n * If `metadata.corpus.attestations` doesn't exist, it's created. If\n * the new attestation is byte-identical to the last entry (same kind\n * + identity + at), it's a no-op (idempotent against\n * lifecycle workflow retries).\n */\nexport function appendAttestation(\n frontmatter: Readonly<Record<string, unknown>>,\n attestation: Attestation\n): Record<string, unknown> {\n const metaIn = (frontmatter.metadata as Record<string, unknown> | undefined) ?? {}\n const corpusIn =\n (metaIn.corpus as Record<string, unknown> | undefined) ?? {}\n const existing =\n (corpusIn.attestations as Attestation[] | undefined) ?? []\n const last = existing[existing.length - 1]\n if (\n last &&\n last.kind === attestation.kind &&\n last.identity === attestation.identity &&\n last.at === attestation.at\n ) {\n // Idempotent — don't duplicate on lifecycle retry.\n return { ...frontmatter }\n }\n return {\n ...frontmatter,\n metadata: {\n ...metaIn,\n corpus: {\n ...corpusIn,\n attestations: [...existing, attestation],\n },\n },\n }\n}\n\n/**\n * Read the attestation chain off a frontmatter object. Returns `[]`\n * if the entry has none (e.g. legacy entries written before the\n * attestation chain shipped).\n */\nexport function readAttestations(\n frontmatter: Readonly<Record<string, unknown>>\n): readonly Attestation[] {\n const meta = frontmatter.metadata as { corpus?: { attestations?: unknown } } | undefined\n const list = meta?.corpus?.attestations\n if (!Array.isArray(list)) return []\n return Object.freeze(list as Attestation[])\n}\n\n/**\n * Convenience: build an attestation from current clock + identity.\n * Lifecycle code typically calls this then immediately\n * `appendAttestation`.\n */\nexport function makeAttestation(input: {\n readonly kind: Attestation[\"kind\"]\n readonly identity: string\n readonly at: string\n readonly model?: string\n readonly promptHash?: string\n readonly note?: string\n}): Attestation {\n return Object.freeze({\n kind: input.kind,\n identity: input.identity,\n at: input.at,\n ...(input.model ? { model: input.model } : {}),\n ...(input.promptHash ? { promptHash: input.promptHash } : {}),\n ...(input.note ? { note: input.note } : {}),\n })\n}\n","/**\n * Access policy — pure logic that decides whether a caller can see a\n * piece of corpus content based on its `metadata.corpus.access` spec.\n *\n * Inputs:\n * spec — what the entry/source declares (classification + allowed refs)\n * caller — identityTree (resolved by IdentityPort)\n *\n * Output:\n * permitted: boolean\n * reason: human-readable\n * redact: bytes-redaction hint for getSource() (some classifications\n * let the caller see metadata but not body bytes)\n *\n * Default policy by classification:\n *\n * public — anyone can see (and read bytes)\n * internal — same-guild only (default for unmarked entries)\n * restricted — explicit allowedRoles / allowedOperators / allowedUsers\n * ONLY; classification fallback is deny\n * secret — same as restricted PLUS bytes are redacted for\n * callers below the bar (they see frontmatter, not body)\n *\n * Engines/UIs filter silently — no \"you have N results but can't see\n * them\" leakage to the caller below.\n */\n\nexport type AccessClassification =\n | \"public\"\n | \"internal\"\n | \"restricted\"\n | \"secret\"\n\nexport interface CorpusAccessSpec {\n readonly classification?: AccessClassification\n readonly allowedRoles?: readonly string[]\n readonly allowedOperators?: readonly string[]\n readonly allowedUsers?: readonly string[]\n readonly allowedGuilds?: readonly string[]\n readonly allowedOrgs?: readonly string[]\n /** Free-form host extension. */\n readonly metadata?: Readonly<Record<string, unknown>>\n}\n\nexport interface AccessCaller {\n /** identityTree most-specific → least-specific. */\n readonly identityTree: readonly string[]\n}\n\n/**\n * Per-evaluation context the adapter passes alongside the caller.\n * Distinct from the spec (entry-side) and the caller (subject-side);\n * this carries the *workspace-side* facts that classification rules\n * need but that the entry doesn't repeat per-row.\n */\nexport interface AccessContext {\n /**\n * Guild slug that owns the workspace this entry lives in (e.g.\n * \"acme-marketing\"). When set, the `internal` classification\n * requires the caller's identityTree to include\n * `ws://guilds/<homeGuild>` — i.e. an entry tagged internal is\n * visible only to that guild, not to anyone-in-any-guild.\n *\n * When omitted, `internal` falls back to \"fail-closed\" rather than\n * the old \"any-guild\" semantics, on the principle that an\n * unidentifiable workspace shouldn't leak its content.\n */\n readonly homeGuild?: string\n}\n\nexport interface AccessDecision {\n readonly permitted: boolean\n readonly reason: string\n /** For getSource — true means body bytes MUST be redacted. */\n readonly redactBytes: boolean\n}\n\nconst DEFAULT_CLASSIFICATION: AccessClassification = \"internal\"\n\n/**\n * Evaluate access for a caller against an access spec. Returns a\n * decision the caller (engine adapter, tool) uses to filter / redact.\n *\n * Missing `access` block in frontmatter = treat as `classification:\n * internal`, no explicit allow lists. Same-guild matches via the\n * identityTree.\n */\nexport function evaluateAccess(\n spec: CorpusAccessSpec | undefined,\n caller: AccessCaller,\n context: AccessContext = {}\n): AccessDecision {\n const classification = spec?.classification ?? DEFAULT_CLASSIFICATION\n\n // Explicit allow lists win across all classifications.\n if (spec) {\n if (matchesAllowed(\"roles\", spec.allowedRoles, caller))\n return permit(`allowedRoles match`, classification)\n if (matchesAllowed(\"operators\", spec.allowedOperators, caller))\n return permit(`allowedOperators match`, classification)\n if (matchesAllowed(\"users\", spec.allowedUsers, caller))\n return permit(`allowedUsers match`, classification)\n if (matchesAllowed(\"guilds\", spec.allowedGuilds, caller))\n return permit(`allowedGuilds match`, classification)\n if (matchesAllowed(\"orgs\", spec.allowedOrgs, caller))\n return permit(`allowedOrgs match`, classification)\n }\n\n switch (classification) {\n case \"public\":\n return {\n permitted: true,\n reason: \"classification=public\",\n redactBytes: false,\n }\n case \"internal\": {\n // Internal = scoped to the workspace's home guild. The host\n // (corpus-host) is expected to supply `context.homeGuild`; when\n // it does, the caller must hold that guild in their identity\n // tree. When omitted, fail-closed — an unidentifiable workspace\n // shouldn't leak via the broadest classification.\n if (!context.homeGuild) {\n return {\n permitted: false,\n reason:\n \"classification=internal but no homeGuild context — fail-closed\",\n redactBytes: false,\n }\n }\n const expected = `ws://guilds/${context.homeGuild}`\n const inHomeGuild = caller.identityTree.includes(expected)\n return {\n permitted: inHomeGuild,\n reason: inHomeGuild\n ? `classification=internal + caller in ${expected}`\n : `classification=internal but caller not in ${expected}`,\n redactBytes: false,\n }\n }\n case \"restricted\":\n return {\n permitted: false,\n reason:\n \"classification=restricted — caller not in any allowed list (roles/operators/users/guilds/orgs)\",\n redactBytes: false,\n }\n case \"secret\":\n return {\n permitted: false,\n reason:\n \"classification=secret — caller not in any allowed list; bytes redacted\",\n redactBytes: true,\n }\n default: {\n // Forward-compat — unknown classification fails closed.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const _exhaustive: never = classification\n return {\n permitted: false,\n reason: `unknown classification \"${String(classification)}\" — fail-closed`,\n redactBytes: true,\n }\n }\n }\n}\n\nfunction permit(\n reason: string,\n classification: AccessClassification\n): AccessDecision {\n // Even when explicitly allowed, secret content still has redactBytes\n // depend on classification — callers might want to expose\n // frontmatter only. For now, explicit allow = full access.\n return {\n permitted: true,\n reason: `${reason} (classification=${classification})`,\n redactBytes: false,\n }\n}\n\nfunction matchesAllowed(\n kind: \"roles\" | \"operators\" | \"users\" | \"guilds\" | \"orgs\",\n list: readonly string[] | undefined,\n caller: AccessCaller\n): boolean {\n if (!list || list.length === 0) return false\n const prefix = `ws://${kind}/`\n for (const ref of list) {\n // Tolerate both bare slugs and full ws:// refs in the allow list.\n const expanded = ref.startsWith(\"ws://\") ? ref : prefix + ref\n if (caller.identityTree.includes(expanded)) return true\n // Glob: \"ws://roles/*\" matches any role in the caller's tree.\n if (expanded === `${prefix}*`) {\n if (caller.identityTree.some((r) => r.startsWith(prefix))) return true\n }\n }\n return false\n}\n\n/**\n * Extract the access spec from a frontmatter object's\n * `metadata.corpus.access`. Returns undefined when the entry has\n * none — caller treats it as `internal` (the default).\n */\nexport function readAccessSpec(\n frontmatter: Readonly<Record<string, unknown>>\n): CorpusAccessSpec | undefined {\n const meta = frontmatter.metadata as { corpus?: { access?: unknown } } | undefined\n const access = meta?.corpus?.access\n if (!access || typeof access !== \"object\") return undefined\n return access as CorpusAccessSpec\n}\n","/**\n * Capability — uniform tool-boundary enforcement.\n *\n * Every corpus tool declares a required `Capability`. The host\n * (Guilde corpus.bundle / corpus-cli) calls `evaluateCapability` at\n * dispatch time. Capabilities are configured per-workspace under\n * `KNOWLEDGE.md.metadata.corpus.accessModes`.\n *\n * Pure logic. Audit + actual rejection happen in the host.\n */\n\nexport type Capability =\n | \"read\"\n | \"cite\"\n | \"flag-learning\"\n | \"curate\"\n | \"promote\"\n | \"activate-playbook\"\n | \"admin-reindex\"\n | \"bypass-default-filters\"\n\nexport interface CapabilityRule {\n readonly allowedRoles: readonly string[]\n /** Optional rate-limit hint — enforcement lives in the host. */\n readonly rateLimit?: {\n readonly perOperator?: number\n readonly window?: string\n }\n /** Requires curator approval before the action commits. */\n readonly requireApproval?: boolean\n /** Audit-log the call (default false). */\n readonly audit?: boolean\n}\n\nexport type AccessModesMap = Readonly<\n Partial<Record<Capability, CapabilityRule>>\n>\n\nexport interface CapabilityCaller {\n /** identityTree most-specific → least-specific. */\n readonly identityTree: readonly string[]\n}\n\nexport interface CapabilityDecision {\n readonly permitted: boolean\n readonly reason: string\n /** Rate-limit hint to enforce, if defined. */\n readonly rateLimit?: CapabilityRule[\"rateLimit\"]\n /** True if the tool MUST collect approval before committing. */\n readonly requireApproval: boolean\n /** True if the host should write an audit entry on completion. */\n readonly audit: boolean\n}\n\n/**\n * Sensible defaults applied when KNOWLEDGE.md doesn't declare a rule\n * for a given capability. Match the v1 plan's accessModes shape:\n *\n * read | cite | flag-learning → allowedRoles: [\"*\"] (anyone)\n * curate | promote → allowedRoles: [\"corpus-curator\", \"admin\"]\n * activate-playbook → same + requireApproval: true\n * admin-reindex → allowedRoles: [\"admin\"]\n * bypass-default-filters → curator/admin + audit: true\n */\nconst DEFAULT_RULES: Record<Capability, CapabilityRule> = Object.freeze({\n \"read\": { allowedRoles: [\"*\"] },\n \"cite\": { allowedRoles: [\"*\"] },\n \"flag-learning\": {\n allowedRoles: [\"*\"],\n rateLimit: { perOperator: 20, window: \"24h\" },\n },\n \"curate\": { allowedRoles: [\"corpus-curator\", \"admin\"] },\n \"promote\": { allowedRoles: [\"corpus-curator\", \"admin\"] },\n \"activate-playbook\": {\n allowedRoles: [\"corpus-curator\", \"admin\"],\n requireApproval: true,\n },\n \"admin-reindex\": { allowedRoles: [\"admin\"] },\n \"bypass-default-filters\": {\n allowedRoles: [\"corpus-curator\", \"admin\"],\n audit: true,\n },\n})\n\nexport function evaluateCapability(\n capability: Capability,\n accessModes: AccessModesMap | undefined,\n caller: CapabilityCaller\n): CapabilityDecision {\n const rule = accessModes?.[capability] ?? DEFAULT_RULES[capability]\n if (!rule) {\n return {\n permitted: false,\n reason: `unknown capability \"${capability}\"`,\n requireApproval: false,\n audit: true,\n }\n }\n const permitted = matchesRoles(rule.allowedRoles, caller.identityTree)\n return {\n permitted,\n reason: permitted\n ? `caller identity matches allowedRoles for \"${capability}\"`\n : `caller identity does NOT match allowedRoles for \"${capability}\"`,\n rateLimit: rule.rateLimit,\n requireApproval: !!rule.requireApproval,\n audit: !!rule.audit,\n }\n}\n\nfunction matchesRoles(\n allowed: readonly string[],\n identityTree: readonly string[]\n): boolean {\n if (allowed.includes(\"*\")) return true\n for (const role of allowed) {\n // Accept both bare slugs and full ws:// refs in the rule.\n const expanded = role.startsWith(\"ws://\") ? role : `ws://roles/${role}`\n if (identityTree.includes(expanded)) return true\n }\n return false\n}\n\n/**\n * Read accessModes from a parsed KNOWLEDGE.md workspace\n * frontmatter. Returns undefined if not declared — caller uses\n * DEFAULT_RULES.\n */\nexport function readAccessModes(\n workspaceFrontmatter: Readonly<Record<string, unknown>>\n): AccessModesMap | undefined {\n const meta = workspaceFrontmatter.metadata as\n | { corpus?: { accessModes?: unknown } }\n | undefined\n const am = meta?.corpus?.accessModes\n if (!am || typeof am !== \"object\") return undefined\n return am as AccessModesMap\n}\n","/**\n * Language filtering — pure helpers for BCP-47 locale matching.\n *\n * Where language lives:\n * - AIP-10 source: native top-level `language` field (already in spec).\n * - AIP-10 entry: under `metadata.corpus.language` until the AIP-10\n * spec hoists `language` to first-class on entries.\n * - Workspace default: `KNOWLEDGE.md.metadata.corpus.languages.default`.\n * - Operator locale: `OPERATOR.md.metadata.corpus.locale`.\n *\n * Default filter: an entry surfaces to an operator if its language\n * matches the operator's locale OR matches the workspace default\n * (typically en-US so generic principles aren't locale-gated). Empty\n * `language` on the entry = treat as the workspace default (it's\n * almost always the corpus's home language).\n *\n * Locale matching is loose (`en` matches `en-US` / `en-GB`) so we\n * don't drown the user in misses on regional variants.\n */\n\nexport interface ResolveLanguageFilterInput {\n /** BCP-47 locale the caller is operating in. */\n readonly callerLocale?: string\n /**\n * Default language declared in `KNOWLEDGE.md.metadata.corpus.languages.default`.\n * Used as the implicit language for entries that don't declare one.\n */\n readonly workspaceDefaultLanguage?: string\n}\n\nexport interface LanguageFilter {\n /**\n * The set of language codes that surface. Used by middleware to\n * filter hits silently. Empty set = no language filter (everyone\n * sees everything; happens when neither caller nor workspace\n * declares a language).\n */\n readonly allowedLanguages: ReadonlySet<string>\n /**\n * Whether entries with no declared language should pass through.\n * True when the workspace declares a default — those entries\n * inherit it.\n */\n readonly allowUnspecified: boolean\n}\n\nexport function resolveLanguageFilter(\n input: ResolveLanguageFilterInput\n): LanguageFilter {\n const set = new Set<string>()\n if (input.callerLocale) addExpansions(set, input.callerLocale)\n if (input.workspaceDefaultLanguage)\n addExpansions(set, input.workspaceDefaultLanguage)\n return Object.freeze({\n allowedLanguages: set,\n // If a workspace default exists, entries without an explicit\n // language inherit it → pass-through. If neither caller nor\n // workspace declares one, the filter is effectively off (everyone\n // surfaces; the helper isn't called for cross-language scoping).\n allowUnspecified:\n set.size === 0 ? true : input.workspaceDefaultLanguage != null,\n })\n}\n\nexport function matchesLanguageFilter(\n entryLanguage: string | undefined,\n filter: LanguageFilter\n): boolean {\n if (filter.allowedLanguages.size === 0) return true // no filter\n if (!entryLanguage) return filter.allowUnspecified\n // Exact + loose (en-US matches en) — try both directions for\n // tolerance.\n const lower = entryLanguage.toLowerCase()\n if (filter.allowedLanguages.has(lower)) return true\n const baseLang = lower.split(\"-\")[0]\n if (baseLang && filter.allowedLanguages.has(baseLang)) return true\n // Caller had \"en\", entry has \"en-US\" → also accept.\n for (const allowed of filter.allowedLanguages) {\n if (lower.startsWith(allowed + \"-\")) return true\n }\n return false\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\nfunction addExpansions(set: Set<string>, locale: string): void {\n const lower = locale.toLowerCase()\n set.add(lower)\n const base = lower.split(\"-\")[0]\n if (base) set.add(base)\n}\n\n/**\n * Convenience: read the operator's locale from frontmatter.\n * Falls back to undefined when not declared.\n */\nexport function readOperatorLocale(\n operatorFrontmatter: Readonly<Record<string, unknown>>\n): string | undefined {\n const meta = operatorFrontmatter.metadata as\n | { corpus?: { locale?: unknown } }\n | undefined\n const l = meta?.corpus?.locale\n return typeof l === \"string\" ? l : undefined\n}\n\n/**\n * Read the workspace's default language from KNOWLEDGE.md.\n */\nexport function readWorkspaceDefaultLanguage(\n workspaceFrontmatter: Readonly<Record<string, unknown>>\n): string | undefined {\n const meta = workspaceFrontmatter.metadata as\n | { corpus?: { languages?: { default?: unknown } } }\n | undefined\n const def = meta?.corpus?.languages?.default\n return typeof def === \"string\" ? def : undefined\n}\n\n/**\n * Read an entry / source's language. Sources expose it at top level\n * (AIP-10 spec); entries put it under `metadata.corpus.language`\n * until the corresponding AIP-10 amendment lands.\n */\nexport function readEntryLanguage(\n frontmatter: Readonly<Record<string, unknown>>\n): string | undefined {\n const top = frontmatter.language\n if (typeof top === \"string\") return top\n const meta = frontmatter.metadata as\n | { corpus?: { language?: unknown } }\n | undefined\n const corp = meta?.corpus?.language\n return typeof corp === \"string\" ? corp : undefined\n}\n","/**\n * CorpusEventEmitter — append-only writer for `_log.md`.\n *\n * The corpus' audit trail. Every state transition (candidate\n * discovered/analyzed/approved/rejected, entry promoted/deprecated,\n * playbook activated/archived, gap opened/resolved) appends one line\n * here.\n *\n * Line format (NDJSON-ish, but inside a markdown file for AIP-10\n * conformance — _log.md is the canonical AIP-10 log doctype):\n *\n * - {ISO} {kind} by {actor} payload={JSON}\n *\n * Concrete:\n *\n * - 2026-05-22T14:30:00.000Z corpus.entry.promoted by ws://operators/corpus-curator payload={\"slug\":\"contrarian-short-form-hooks\",\"kind\":\"pattern\"}\n *\n * Why line-per-event (not blocks): every host needs to grep / tail /\n * stream the log without a markdown parser. Inside an .md file =\n * AIP-10 conformant; line-format = ops-friendly.\n *\n * Atomicity: relies on FsPort.appendFile being atomic against\n * concurrent appends. Hosts MUST honor that — cloud topology uses\n * append APIs (S3 Express, GCS), local topology uses POSIX append\n * (atomic up to PIPE_BUF).\n */\n\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type { ClockPort } from \"../ports/clock.port.js\"\nimport type { IdentityPort } from \"../ports/identity.port.js\"\nimport type {\n CorpusEvent,\n CorpusEventKind,\n} from \"../types.js\"\n\nexport interface CorpusEventEmitterOptions {\n readonly fs: FsPort\n readonly clock: ClockPort\n readonly identity: IdentityPort\n /**\n * Workspace root the emitter targets — `_log.md` is written\n * relative to this. Hosts that mount multiple corpora pass one\n * emitter per workspace root.\n */\n readonly workspaceRoot: string\n}\n\nexport class CorpusEventEmitter {\n constructor(private readonly opts: CorpusEventEmitterOptions) {}\n\n /**\n * Emit one event. Returns the event as written (including the\n * ISO timestamp and actor resolved at emit time). The .md log file\n * is created on first append if missing.\n */\n async emit(\n kind: CorpusEventKind,\n payload: Readonly<Record<string, unknown>>\n ): Promise<CorpusEvent> {\n const identity = await this.opts.identity.resolve()\n const event: CorpusEvent = {\n kind,\n at: this.opts.clock.now().toISOString(),\n actor: identity.principal,\n payload,\n }\n const logPath = joinPath(this.opts.workspaceRoot, \"_log.md\")\n const line = formatLine(event) + \"\\n\"\n\n // Initialize the log file with an AIP-10 conformant header on\n // first write, so a fresh corpus' _log.md is also a valid\n // markdown doc (not just a JSON-lines stream).\n if (!(await this.opts.fs.exists(logPath))) {\n await this.opts.fs.writeFile(\n logPath,\n \"# Corpus activity log\\n\\n\" +\n \"Append-only AIP-10 log of corpus state transitions. Each line:\\n\" +\n \"`- <iso> <kind> by <actor> payload=<json>`\\n\\n\"\n )\n }\n await this.opts.fs.appendFile(logPath, line)\n return event\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────\n\nfunction formatLine(event: CorpusEvent): string {\n // Compact JSON keeps lines greppable. Sort keys for deterministic\n // diffs across emitters running on the same workspace.\n const payload = JSON.stringify(event.payload, [...Object.keys(event.payload).sort()])\n return `- ${event.at} ${event.kind} by ${event.actor} payload=${payload}`\n}\n\nfunction joinPath(a: string, b: string): string {\n if (!a) return b\n return a.endsWith(\"/\") ? a + b : a + \"/\" + b\n}\n","/**\n * CorpusWorkspaceReader — scan + parse a corpus workspace via FsPort.\n *\n * Pure path-discipline + YAML parsing — no schema validation here. The\n * reader's job is to surface every .md file in the workspace and\n * classify it by location. Schema validation happens in\n * `validate/validator.ts` so callers can run both in parallel and get\n * crisp error categorization.\n *\n * Pure: no `node:fs`, no `node:path`. All paths are joined manually\n * with \"/\" so the kit runs on Node, Bun, Deno, and browser-side\n * editors (e.g. curator UI lint preview).\n */\n\nimport matter from \"gray-matter\"\nimport { createHash } from \"node:crypto\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type {\n CorpusWorkspaceSnapshot,\n FileKind,\n ParsedFile,\n} from \"../types.js\"\n\nexport interface CorpusWorkspaceReaderOptions {\n readonly fs: FsPort\n}\n\nexport class CorpusWorkspaceReader {\n constructor(private readonly opts: CorpusWorkspaceReaderOptions) {}\n\n /**\n * Scan the workspace rooted at `root` and return a typed snapshot.\n * `root` is workspace-relative (the host resolves to a backing\n * storage); commonly \"\" for the workspace root itself.\n */\n async read(root: string): Promise<CorpusWorkspaceSnapshot> {\n const files = await this.opts.fs.walk(root)\n const mdFiles = files.filter((p) => p.endsWith(\".md\"))\n\n const buckets: Record<FileKind, ParsedFile[]> = {\n \"knowledge-workspace\": [],\n \"knowledge-source\": [],\n \"knowledge-entry\": [],\n \"collection-schema\": [],\n \"collection-item\": [],\n \"playbook\": [],\n \"operator\": [],\n \"workflow\": [],\n \"routine\": [],\n \"unknown\": [],\n }\n\n for (const path of mdFiles) {\n const content = await this.opts.fs.readFile(path)\n const parsed = matter(content)\n const file: ParsedFile = {\n // Workspace-relative path. The walk returns paths anchored at\n // the host's storage root (which already includes `root` for\n // non-empty workspaces — see GuildWorkspaceFsAdapter.walk),\n // so we strip `root` here to match the documented contract\n // (\"paths returned are workspace-relative\"). Without this,\n // call sites that re-join `workspacePath + file.path` (the\n // playbook lifecycle, the evaluator, the promoter's CAS write)\n // double-prefix the path and the next read/CAS misses,\n // surfacing as CorpusVersionConflictError.\n path: stripRoot(path, root),\n kind: classify(path, root),\n frontmatter: (parsed.data ?? {}) as Readonly<Record<string, unknown>>,\n body: parsed.content,\n versionToken: sha256(content),\n }\n buckets[file.kind].push(file)\n }\n\n return {\n root,\n workspace: buckets[\"knowledge-workspace\"][0] ?? null,\n sources: freeze(buckets[\"knowledge-source\"]),\n entries: freeze(buckets[\"knowledge-entry\"]),\n collections: freeze(buckets[\"collection-schema\"]),\n collectionItems: freeze(buckets[\"collection-item\"]),\n playbooks: freeze(buckets[\"playbook\"]),\n operators: freeze(buckets[\"operator\"]),\n workflows: freeze(buckets[\"workflow\"]),\n routines: freeze(buckets[\"routine\"]),\n unknown: freeze(buckets[\"unknown\"]),\n }\n }\n}\n\n// ── Classification ─────────────────────────────────────────────────────\n\n/**\n * Classify a workspace-relative path by AIP convention.\n *\n * Important: the reader does NOT consult frontmatter to decide. Location\n * is authoritative — a file at `entries/principles/foo.md` is always\n * \"knowledge-entry\" even if its frontmatter is wrong. The validator\n * later surfaces the mismatch as a structured error.\n */\nfunction classify(path: string, root: string): FileKind {\n const rel = stripRoot(path, root)\n const segs = rel.split(\"/\").filter(Boolean)\n const fname = segs[segs.length - 1] ?? \"\"\n\n if (segs.length === 1 && fname === \"KNOWLEDGE.md\") return \"knowledge-workspace\"\n\n const top = segs[0]\n switch (top) {\n case \"sources\":\n return \"knowledge-source\"\n case \"entries\":\n return \"knowledge-entry\"\n case \"collections\":\n if (fname === \"COLLECTION.md\") return \"collection-schema\"\n if (fname === \"ITEM.md\" || /^[a-z0-9][a-z0-9-]*\\.md$/.test(fname))\n return \"collection-item\"\n return \"unknown\"\n case \"playbooks\":\n if (fname === \"PLAYBOOK.md\") return \"playbook\"\n return \"unknown\"\n case \"operators\":\n if (fname === \"OPERATOR.md\") return \"operator\"\n return \"unknown\"\n case \"workflows\":\n if (fname === \"WORKFLOW.md\") return \"workflow\"\n return \"unknown\"\n case \"routines\":\n if (fname === \"ROUTINE.md\") return \"routine\"\n return \"unknown\"\n default:\n return \"unknown\"\n }\n}\n\nfunction stripRoot(path: string, root: string): string {\n if (!root) return path\n const prefix = root.endsWith(\"/\") ? root : root + \"/\"\n return path.startsWith(prefix) ? path.slice(prefix.length) : path\n}\n\nfunction sha256(content: string): string {\n return \"sha256:\" + createHash(\"sha256\").update(content).digest(\"hex\")\n}\n\nfunction freeze<T>(arr: T[]): readonly T[] {\n return Object.freeze([...arr])\n}\n","/**\n * CorpusWorkspaceWriter — atomic file writes with versionToken\n * optimistic-concurrency guard.\n *\n * Every write goes through `writeFile(path, content, expected?)`:\n * - If `expected` is provided, the writer reads the current file's\n * content hash and refuses to write if it doesn't match → throws\n * CorpusVersionConflictError. Caller retries with the fresh\n * versionToken.\n * - If `expected` is null, the writer requires the file to NOT\n * exist (create-only).\n * - If `expected` is undefined, the writer overwrites unconditionally\n * (use sparingly — bypasses the concurrency-correctness story).\n *\n * Multi-file transactions (e.g. promote entry + update _index.md +\n * append _log.md) use FsPort.lock on a sentinel path so concurrent\n * promoters serialize cleanly.\n *\n * The writer is the ONLY component allowed to call FsPort.writeFile\n * for workspace content. The reader/validator/linter never write.\n * The event emitter writes only _log.md via append.\n */\n\nimport { createHash } from \"node:crypto\"\nimport matter from \"gray-matter\"\nimport type { FsPort, FsLockHandle } from \"../ports/fs.port.js\"\n\nexport class CorpusVersionConflictError extends Error {\n constructor(\n readonly path: string,\n readonly expected: string,\n readonly actual: string\n ) {\n super(\n `CorpusVersionConflictError: ${path} versionToken mismatch — expected ${expected}, found ${actual}. Re-read the file and retry with the fresh token.`\n )\n this.name = \"CorpusVersionConflictError\"\n }\n}\n\nexport interface CorpusWorkspaceWriterOptions {\n readonly fs: FsPort\n}\n\n/**\n * Frontmatter + body source pair, used by helpers like `writeEntry`\n * that need to serialize the .md back from structured data.\n */\nexport interface MarkdownDoc {\n readonly frontmatter: Readonly<Record<string, unknown>>\n readonly body: string\n}\n\nexport class CorpusWorkspaceWriter {\n constructor(private readonly opts: CorpusWorkspaceWriterOptions) {}\n\n /**\n * Compute the versionToken for raw file content. Exposed so the\n * caller can stage a write and pass the same hash function used\n * inside the writer.\n */\n static versionTokenOf(content: string): string {\n return \"sha256:\" + createHash(\"sha256\").update(content).digest(\"hex\")\n }\n\n /**\n * Atomic write with optimistic concurrency check.\n *\n * - expected === undefined → unconditional overwrite (use sparingly)\n * - expected === null → create-only (refuses if exists)\n * - expected === string → CAS check (refuses if current hash differs)\n *\n * Returns the new versionToken on success.\n */\n async writeFile(\n path: string,\n content: string,\n expected?: string | null\n ): Promise<string> {\n if (expected === null) {\n if (await this.opts.fs.exists(path)) {\n throw new CorpusVersionConflictError(path, \"<must-not-exist>\", \"<exists>\")\n }\n } else if (typeof expected === \"string\") {\n const existing = await this.opts.fs.exists(path)\n if (!existing) {\n throw new CorpusVersionConflictError(path, expected, \"<missing>\")\n }\n const current = await this.opts.fs.readFile(path)\n const actual = CorpusWorkspaceWriter.versionTokenOf(current)\n if (actual !== expected) {\n throw new CorpusVersionConflictError(path, expected, actual)\n }\n }\n await this.opts.fs.writeFile(path, content)\n return CorpusWorkspaceWriter.versionTokenOf(content)\n }\n\n /**\n * Serialize a markdown doc (frontmatter + body) and write atomically.\n * Frontmatter keys are stringified in a stable order so version\n * tokens are deterministic across emitter rebuilds.\n */\n async writeMarkdown(\n path: string,\n doc: MarkdownDoc,\n expected?: string | null\n ): Promise<string> {\n const content = serializeMarkdown(doc)\n return this.writeFile(path, content, expected)\n }\n\n /**\n * Run `fn` while holding a workspace-scoped lock. Used for\n * multi-file transactions (promote entry + update _index.md + log\n * append). The lock path is host-specific; we default to\n * `_log.md` because it's the file every transaction touches.\n *\n * `lockPath` is workspace-relative.\n */\n async transaction<T>(\n lockPath: string,\n fn: () => Promise<T>\n ): Promise<T> {\n let handle: FsLockHandle | null = null\n try {\n handle = await this.opts.fs.lock(lockPath)\n return await fn()\n } finally {\n if (handle) await handle.release()\n }\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────\n\n/**\n * Serialize a MarkdownDoc back to `--- frontmatter --- body` form.\n * gray-matter's `stringify` does this; we wrap it for the deterministic\n * key-order convention.\n */\nfunction serializeMarkdown(doc: MarkdownDoc): string {\n // gray-matter.stringify takes (content, data) — body first, then\n // frontmatter object.\n return matter.stringify(doc.body.startsWith(\"\\n\") ? doc.body : \"\\n\" + doc.body, doc.frontmatter)\n}\n","/**\n * ImporterRunner — drives a CorpusImporter to actually land files\n * + candidate rows in the workspace.\n *\n * Importers themselves are pure source-of-data — they yield\n * `ImportedSource`. The runner is where I/O lives: archives sources\n * to `sources/<importerId>/<batchId>/`, appends `_candidates.yaml`\n * rows, dedups against existing sources by `content_hash`, emits a\n * `corpus.candidate.discovered` event per imported source.\n *\n * Same fs+writer+emitter pattern as the rest of the corpus lifecycle.\n */\n\nimport matter from \"gray-matter\"\nimport { CorpusEventEmitter } from \"../events/emitter.js\"\nimport { CorpusWorkspaceReader } from \"../workspace/reader.js\"\nimport { CorpusWorkspaceWriter } from \"../workspace/writer.js\"\nimport { CandidatesSidecar } from \"../workspace/sidecar.js\"\nimport { isSourceSlug } from \"../util/slug.js\"\nimport type { ClockPort } from \"../ports/clock.port.js\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type { IdentityPort } from \"../ports/identity.port.js\"\nimport type { CandidateRow } from \"../workspace/sidecar.js\"\nimport type {\n BatchReport,\n CorpusImporter,\n ImportedSource,\n ImporterRunnerOptions,\n ImporterTarget,\n} from \"./types.js\"\n\nconst SIDECAR_PATH = \"collections/corpus-candidate/_candidates.yaml\"\n\nexport class ImporterRunner {\n constructor(\n private readonly opts: {\n readonly fs: FsPort\n readonly clock: ClockPort\n readonly identity: IdentityPort\n readonly workspacePath: string\n readonly runner?: ImporterRunnerOptions\n }\n ) {}\n\n /**\n * Run a single importer batch end-to-end.\n *\n * 1. Pre-load existing source content_hashes for dedup.\n * 2. For each source the importer yields:\n * a. Skip if hash already exists in the workspace.\n * b. Otherwise write AIP-10 source frontmatter + body to\n * `sources/<importerId>/<batchId>/<slug>.md`.\n * c. Append candidate row to `_candidates.yaml`.\n * 3. Emit `corpus.candidate.discovered` per archived source.\n *\n * Atomic per-source (each source archived + candidate written\n * inside one writer.transaction).\n */\n async run(\n importer: CorpusImporter,\n target: ImporterTarget\n ): Promise<BatchReport> {\n const fs = this.opts.fs\n const writer = new CorpusWorkspaceWriter({ fs })\n const reader = new CorpusWorkspaceReader({ fs })\n const sidecar = new CandidatesSidecar({\n fs,\n path: joinPath(this.opts.workspacePath, SIDECAR_PATH),\n })\n const emitter = new CorpusEventEmitter({\n fs,\n clock: this.opts.clock,\n identity: this.opts.identity,\n workspaceRoot: this.opts.workspacePath,\n })\n\n const batchId = target.batchId ?? this.opts.clock.now().toISOString().slice(0, 10)\n const archiveDirSegment = `sources/${target.importerId}/${batchId}`\n\n // Pre-load existing content_hashes for dedup. O(n) one-shot scan.\n const snapshot = await reader.read(this.opts.workspacePath)\n const existingHashes = new Set<string>()\n for (const file of snapshot.sources) {\n const h = file.frontmatter.content_hash\n if (typeof h === \"string\") existingHashes.add(h)\n }\n\n const archivedSlugs: string[] = []\n const duplicateSlugs: string[] = []\n const candidateIds: string[] = []\n const warnings: string[] = []\n\n for await (const source of importer.enumerate(target)) {\n if (!isSourceSlug(source.slug)) {\n warnings.push(`source skipped — invalid slug \"${source.slug}\"`)\n continue\n }\n if (existingHashes.has(source.contentHash)) {\n duplicateSlugs.push(source.slug)\n continue\n }\n existingHashes.add(source.contentHash) // dedup within batch too\n\n const sourcePath = joinPath(\n this.opts.workspacePath,\n `${archiveDirSegment}/${source.slug}.md`\n )\n const sourceContent = serializeSource(source, archiveDirSegment, this.opts.clock)\n // Create-only — if the slug somehow collides with an existing file,\n // surface it as a warning and skip.\n try {\n await writer.writeFile(sourcePath, sourceContent, null)\n } catch (err) {\n warnings.push(\n `source \"${source.slug}\" — slug collision in ${archiveDirSegment} (${\n err instanceof Error ? err.message : \"unknown\"\n }); skipped`\n )\n continue\n }\n archivedSlugs.push(source.slug)\n\n // Append candidate row. Use the importer's optional toCandidate\n // mapper if provided; otherwise default to corpusKind=example.\n const toCandidate =\n this.opts.runner?.toCandidate ?? defaultToCandidate\n const sourceId = source.slug\n const row = toCandidate(source, sourceId)\n try {\n await sidecar.append(row)\n candidateIds.push(row.id)\n } catch (err) {\n warnings.push(\n `candidate \"${row.id}\" — sidecar append failed (${\n err instanceof Error ? err.message : \"unknown\"\n })`\n )\n }\n\n // Audit event per archived source.\n await emitter\n .emit(\"corpus.candidate.discovered\", {\n id: row.id,\n importerId: target.importerId,\n batchId,\n contentHash: source.contentHash,\n provenanceKind: `imported-from-${target.importerId}`,\n })\n .catch(() => undefined)\n }\n\n return Object.freeze({\n importerId: target.importerId,\n batchId,\n archivedSlugs: Object.freeze(archivedSlugs),\n duplicateSlugs: Object.freeze(duplicateSlugs),\n candidateIds: Object.freeze(candidateIds),\n warnings: Object.freeze(warnings),\n })\n }\n}\n\n// ── Defaults + helpers ─────────────────────────────────────────────\n\nfunction defaultToCandidate(\n s: ImportedSource,\n sourceId: string\n): CandidateRow {\n return {\n id: sourceId,\n status: \"discovered\",\n corpusKind: \"example\",\n sourcePath: undefined, // filled in by archiver via path mapping\n sourceUrl: s.originalUrl,\n contentHash: s.contentHash,\n title: s.title,\n summary: undefined,\n discoveredAt: new Date().toISOString(),\n discoveredBy: \"ws://operators/importer-runner\",\n provenanceKind: \"imported\",\n }\n}\n\nfunction serializeSource(\n source: ImportedSource,\n archiveDirSegment: string,\n clock: ClockPort\n): string {\n const fm: Record<string, unknown> = {\n schema: \"knowledge.source/v1\",\n id: source.slug,\n path: `${archiveDirSegment}/${source.slug}.md`,\n title: source.title,\n captured_at: clock.now().toISOString(),\n content_hash: source.contentHash,\n authority: source.authority ?? \"secondary\",\n }\n if (source.language) fm.language = source.language\n if (source.tags && source.tags.length > 0) fm.tags = source.tags\n if (source.originalUrl || source.corpusMetadata) {\n fm.metadata = {\n corpus: {\n ...(source.originalUrl ? { originalUrl: source.originalUrl } : {}),\n ...(source.corpusMetadata ?? {}),\n },\n }\n }\n return matter.stringify(\n source.body.startsWith(\"\\n\") ? source.body : \"\\n\" + source.body,\n fm\n )\n}\n\nfunction joinPath(a: string, b: string): string {\n if (!a) return b\n return a.endsWith(\"/\") ? a + b : a + \"/\" + b\n}\n","/**\n * LocalFilesImporter — reads .md files from a configured FsPort path\n * and yields them as ImportedSource. Reference implementation that\n * proves the importer surface end-to-end without external SDKs.\n *\n * Config (target.config):\n * - rootPath: string — workspace-relative path to scan\n * - extensions?: string[] — defaults to [\".md\"]\n * - maxFiles?: number — defaults to 1000\n * - tags?: string[] — applied to every imported source\n * - language?: string — applied to every source (BCP-47)\n *\n * Pure kit code — consumes FsPort, no node:fs / no network.\n *\n * Slug derivation: filename without extension, lowercased + slug-safed.\n * Content hash: sha256 of UTF-8 body bytes.\n */\n\nimport { createHash } from \"node:crypto\"\nimport { slugify } from \"../util/slug.js\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type {\n CorpusImporter,\n ImportedSource,\n ImporterTarget,\n} from \"./types.js\"\n\nexport interface LocalFilesImporterOptions {\n readonly fs: FsPort\n}\n\ninterface LocalFilesConfig {\n readonly rootPath: string\n readonly extensions?: readonly string[]\n readonly maxFiles?: number\n readonly tags?: readonly string[]\n readonly language?: string\n}\n\nexport class LocalFilesImporter implements CorpusImporter {\n readonly id = \"local-files\"\n readonly label = \"Local Files\"\n\n constructor(private readonly opts: LocalFilesImporterOptions) {}\n\n async *enumerate(target: ImporterTarget): AsyncIterable<ImportedSource> {\n const config = parseConfig(target.config)\n const exts = new Set(config.extensions ?? [\".md\"])\n const maxFiles = config.maxFiles ?? 1000\n const paths = await this.opts.fs.walk(config.rootPath)\n let yielded = 0\n for (const p of paths) {\n if (yielded >= maxFiles) break\n const ext = pickExt(p)\n if (!exts.has(ext)) continue\n const body = await this.opts.fs.readFile(p)\n const slug = makeSlug(p, config.rootPath)\n const contentHash = sha256(body)\n const title = readTitleFromBody(body, slug)\n yield {\n slug,\n title,\n contentHash,\n body,\n authority: \"secondary\",\n ...(config.language ? { language: config.language } : {}),\n ...(config.tags && config.tags.length > 0 ? { tags: config.tags } : {}),\n corpusMetadata: {\n importerSourcePath: p,\n importerRoot: config.rootPath,\n },\n }\n yielded++\n }\n }\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\nfunction parseConfig(raw: Readonly<Record<string, unknown>>): LocalFilesConfig {\n if (typeof raw.rootPath !== \"string\") {\n throw new Error(\n `LocalFilesImporter: config.rootPath is required (string)`\n )\n }\n const cfg: LocalFilesConfig = {\n rootPath: raw.rootPath,\n extensions: Array.isArray(raw.extensions)\n ? (raw.extensions as unknown[]).filter(\n (x): x is string => typeof x === \"string\"\n )\n : undefined,\n maxFiles: typeof raw.maxFiles === \"number\" ? raw.maxFiles : undefined,\n tags: Array.isArray(raw.tags)\n ? (raw.tags as unknown[]).filter(\n (x): x is string => typeof x === \"string\"\n )\n : undefined,\n language: typeof raw.language === \"string\" ? raw.language : undefined,\n }\n return cfg\n}\n\nfunction pickExt(path: string): string {\n const i = path.lastIndexOf(\".\")\n if (i < 0) return \"\"\n return path.slice(i).toLowerCase()\n}\n\nfunction makeSlug(path: string, rootPath: string): string {\n // Slug from the root-relative path, extension stripped. Source ids may\n // start with a digit, so no leading-letter constraint here.\n const rel = path.startsWith(rootPath) ? path.slice(rootPath.length) : path\n const stripped = rel.replace(/^\\/+/, \"\").replace(/\\.[^.]+$/, \"\")\n return slugify(stripped, { fallback: \"source\" })\n}\n\nfunction readTitleFromBody(body: string, fallback: string): string {\n // First markdown H1 line, or the filename slug.\n const m = body.match(/^\\s*#\\s+(.+)$/m)\n if (m && m[1]) return m[1].trim().slice(0, 200)\n return fallback\n}\n\nfunction sha256(content: string): string {\n return \"sha256:\" + createHash(\"sha256\").update(content).digest(\"hex\")\n}\n","/**\n * KbMigrationImporter — turn an existing knowledge base into a\n * stream of `ImportedSource` for the runner.\n *\n * Use case: a guild already has a populated qdrant/gbrain KB row\n * with N documents. Day-1 corpus onboarding shouldn't be \"abandon\n * your knowledge and start over\" — this importer reads the source\n * KB via its IKnowledgeProvider, materializes each source as an\n * importable, and the runner archives them into `sources/` +\n * appends candidates. The source KB stays intact (read-only).\n *\n * The minimal IKnowledgeProvider-like shape we consume — keeps the\n * kit decoupled from @agstudio/integration-knowledge.\n *\n * Each migrated source carries `provenanceKind: imported-from-kb`\n * and `sourceKbId` in `metadata.corpus` so curators can trace which\n * KB row each item came from.\n */\n\nimport { createHash } from \"node:crypto\"\nimport type {\n CorpusImporter,\n ImportedSource,\n ImporterTarget,\n} from \"./types.js\"\n\n/**\n * Structural shape — any IKnowledgeProvider satisfies it. We don't\n * import IKnowledgeProvider directly to keep the kit dep-free.\n */\nexport interface KbListLike {\n listSources(): Promise<readonly KbSourceLike[]>\n}\n\nexport interface KbSourceLike {\n readonly id: string\n readonly kind: string\n readonly uri: string\n readonly title?: string\n readonly bytes: number\n readonly metadata: Readonly<Record<string, unknown>>\n}\n\nexport interface KbMigrationConfig {\n /** Stable id of the source KB (used in provenance + archive path). */\n readonly sourceKbId: string\n /** Live provider instance from the source KB. */\n readonly provider: KbListLike\n /**\n * Optional fetcher for the body of each source. The migration\n * importer enumerates source METADATA from listSources(); to\n * archive the actual content, the host must supply a way to fetch\n * the body. If omitted, sources are imported with an empty body +\n * a note pointing back to the source KB.\n */\n readonly fetchBody?: (sourceId: string) => Promise<string>\n /** Optional max sources to import this batch. */\n readonly maxSources?: number\n}\n\nexport class KbMigrationImporter implements CorpusImporter {\n readonly id = \"kb-migration\"\n readonly label = \"Migrate from existing KB\"\n\n async *enumerate(target: ImporterTarget): AsyncIterable<ImportedSource> {\n const config = parseKbMigrationConfig(target.config)\n const sources = await config.provider.listSources()\n const max = config.maxSources ?? sources.length\n let yielded = 0\n for (const s of sources) {\n if (yielded >= max) break\n const body = config.fetchBody\n ? await config.fetchBody(s.id)\n : `(Migrated from KB ${config.sourceKbId}, source id=${s.id}. Body fetcher not configured — archive contains metadata only.)`\n const slug = slugifyKbSource(s.id, config.sourceKbId)\n yield {\n slug,\n title: s.title ?? s.id,\n contentHash: hashKbSource(s, body),\n body,\n originalUrl: typeof s.uri === \"string\" ? s.uri : undefined,\n authority: \"secondary\",\n corpusMetadata: {\n provenanceKind: \"imported-from-kb\",\n sourceKbId: config.sourceKbId,\n sourceKbSourceId: s.id,\n sourceKbBytes: s.bytes,\n sourceKbKind: s.kind,\n // Carry the original KB's metadata through verbatim so\n // curators can see what was lost in translation.\n sourceKbMetadata: s.metadata,\n },\n }\n yielded++\n }\n }\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\nfunction parseKbMigrationConfig(\n raw: Readonly<Record<string, unknown>>\n): KbMigrationConfig {\n const sourceKbId = raw.sourceKbId\n const provider = raw.provider\n if (typeof sourceKbId !== \"string\") {\n throw new Error(\"KbMigrationImporter: config.sourceKbId required (string)\")\n }\n if (!provider || typeof provider !== \"object\" || typeof (provider as KbListLike).listSources !== \"function\") {\n throw new Error(\n \"KbMigrationImporter: config.provider required (must implement listSources)\"\n )\n }\n return {\n sourceKbId,\n provider: provider as KbListLike,\n fetchBody:\n typeof raw.fetchBody === \"function\"\n ? (raw.fetchBody as (id: string) => Promise<string>)\n : undefined,\n maxSources:\n typeof raw.maxSources === \"number\" ? raw.maxSources : undefined,\n }\n}\n\nfunction slugifyKbSource(id: string, kbId: string): string {\n // Prefix with kbId so two KBs migrating sources with overlapping\n // ids don't collide in `sources/<importer>/<batch>/`.\n const combined = `${kbId}-${id}`\n const slug = combined\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .replace(/-{2,}/g, \"-\")\n .slice(0, 96)\n return slug || \"migrated-source\"\n}\n\nfunction hashKbSource(s: KbSourceLike, body: string): string {\n // Stable hash so the dedup gate works across reruns of the same\n // KB. Uses node:crypto for parity with reader.ts; Bun/Deno also\n // ship node:crypto in their stdlib.\n return (\n \"sha256:\" +\n createHash(\"sha256\")\n .update(`${s.id}|${s.bytes}|${body}`)\n .digest(\"hex\")\n )\n}\n","/**\n * WebImporter — turns a list of URLs into corpus sources by reducing\n * each to text through an injected FetcherPort. The importer is pure:\n * it slugs, hashes, and shapes ImportedSource; the FetcherPort supplies\n * the environment-bound \"URL → { title, text }\" capability (YouTube\n * captions, article readability, or — at a fatter tier — transcription).\n *\n * Config (target.config):\n * - urls: string[] — required. The source URLs to import.\n * - maxUrls?: number — defaults to 1000.\n * - tags?: string[] — applied to every imported source.\n * - language?: string — fallback BCP-47 when the fetcher omits one.\n *\n * A URL the fetcher returns `null` for (e.g. a caption-less video on a\n * non-transcribing tier) is skipped — the runner records it as a\n * warning rather than aborting the batch.\n *\n * Pure kit code — consumes FetcherPort, no node:fs / no network of its\n * own. Slug: derived from title, else the URL. Hash: sha256 of the text.\n */\n\nimport { createHash } from \"node:crypto\"\nimport { slugify, uniqueSlug } from \"../util/slug.js\"\nimport { normalizeLanguageTag } from \"../util/language.js\"\nimport type { FetcherPort, FetchedSource } from \"../ports/fetcher.port.js\"\nimport type {\n CorpusImporter,\n ImportedSource,\n ImporterTarget,\n} from \"./types.js\"\n\nexport interface WebImporterOptions {\n readonly fetcher: FetcherPort\n}\n\ninterface WebConfig {\n readonly urls: readonly string[]\n readonly maxUrls?: number\n readonly tags?: readonly string[]\n readonly language?: string\n}\n\nexport class WebImporter implements CorpusImporter {\n readonly id = \"web\"\n readonly label = \"Web (URLs)\"\n\n constructor(private readonly opts: WebImporterOptions) {}\n\n async *enumerate(target: ImporterTarget): AsyncIterable<ImportedSource> {\n const config = parseConfig(target.config)\n const maxUrls = config.maxUrls ?? 1000\n const seenSlugs = new Set<string>()\n let yielded = 0\n\n for (const url of config.urls) {\n if (yielded >= maxUrls) break\n\n // A fetcher signals \"couldn't reduce this URL\" with null. A *thrown*\n // error (transient network failure, browser-MCP disconnect, timeout)\n // must NOT abort the whole batch — the throw would propagate out of\n // this generator and kill every remaining URL. Treat it as a per-URL\n // skip; the importer is resumable, so a re-run retries it.\n let fetched: FetchedSource | null\n try {\n fetched = await this.opts.fetcher.fetch(url)\n } catch {\n continue\n }\n // null = the fetcher couldn't reduce this URL to text; skip it.\n // The runner surfaces skipped URLs as warnings on the batch.\n if (!fetched || !fetched.text.trim()) continue\n\n const slug = uniqueSlug(\n slugify(fetched.title, { fallback: \"\" }) ||\n slugify(url, { stripScheme: true, fallback: \"source\" }),\n seenSlugs\n )\n const language = normalizeLanguageTag(fetched.language ?? config.language)\n\n yield {\n slug,\n title: fetched.title.slice(0, 200) || slug,\n contentHash: sha256(fetched.text),\n body: fetched.text,\n originalUrl: url,\n authority: \"secondary\",\n ...(language ? { language } : {}),\n ...(config.tags && config.tags.length > 0\n ? { tags: config.tags }\n : {}),\n corpusMetadata: {\n importerSourceUrl: url,\n fetchKind: fetched.kind,\n ...(fetched.via ? { fetchedVia: fetched.via } : {}),\n },\n }\n yielded++\n }\n }\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\nfunction parseConfig(raw: Readonly<Record<string, unknown>>): WebConfig {\n const rawUrls = raw.urls\n if (!Array.isArray(rawUrls) || rawUrls.length === 0) {\n throw new Error(\"WebImporter: config.urls is required (non-empty string[])\")\n }\n const urls = rawUrls.filter(\n (x): x is string => typeof x === \"string\" && x.length > 0\n )\n if (urls.length === 0) {\n throw new Error(\"WebImporter: config.urls contained no usable strings\")\n }\n const rawTags = raw.tags\n return {\n urls,\n maxUrls: typeof raw.maxUrls === \"number\" ? raw.maxUrls : undefined,\n tags: Array.isArray(rawTags)\n ? rawTags.filter((x): x is string => typeof x === \"string\")\n : undefined,\n language: typeof raw.language === \"string\" ? raw.language : undefined,\n }\n}\n\nfunction sha256(content: string): string {\n return \"sha256:\" + createHash(\"sha256\").update(content).digest(\"hex\")\n}\n","/**\n * ConversationImporter — turns conversations into corpus sources by rendering\n * each to a transcript through an injected ConversationSourcePort. The importer\n * is pure: it slugs, hashes, and shapes ImportedSource; the port supplies the\n * environment-bound \"ref → turns\" capability (a Mastra thread store, a chat DB).\n *\n * This is the seam for conversation→knowledge distill — the resulting sources\n * feed DistillRunner exactly like web sources do (the pipeline is provenance-\n * agnostic). Chat is append-only, so a single immutable slug per conversation\n * would collide once new turns arrive; the host handles this by WINDOWING —\n * giving each ConversationDoc a window-unique id (e.g. `<thread>-<date>`), so\n * each window distills once and a daily run only sees fresh windows.\n *\n * Config (target.config):\n * - refs: string[] — required. Refs to resolve.\n * - tags?: string[] — applied to every source.\n * - language?: string — fallback BCP-47.\n * - authority?: \"primary\"|\"secondary\"|\"rumour\" — default \"secondary\".\n * - maxRefs?: number — defaults to 1000.\n *\n * Pure kit code — consumes ConversationSourcePort, no chat-store dependency.\n * Slug: derived from the doc id. Hash: sha256 of the rendered transcript, so\n * an unchanged window re-import dedups in ImporterRunner.\n */\n\nimport { createHash } from \"node:crypto\"\nimport { slugify, uniqueSlug } from \"../util/slug.js\"\nimport { normalizeLanguageTag } from \"../util/language.js\"\nimport type {\n ConversationDoc,\n ConversationSourcePort,\n ConversationTurn,\n} from \"../ports/conversation-source.port.js\"\nimport type {\n CorpusImporter,\n ImportedSource,\n ImporterTarget,\n} from \"./types.js\"\n\ntype Authority = \"primary\" | \"secondary\" | \"rumour\"\n\nexport interface ConversationImporterOptions {\n readonly source: ConversationSourcePort\n}\n\ninterface ConversationConfig {\n readonly refs: readonly string[]\n readonly tags?: readonly string[]\n readonly language?: string\n readonly authority?: Authority\n readonly maxRefs?: number\n}\n\nexport class ConversationImporter implements CorpusImporter {\n readonly id = \"conversation\"\n readonly label = \"Conversation\"\n\n constructor(private readonly opts: ConversationImporterOptions) {}\n\n async *enumerate(target: ImporterTarget): AsyncIterable<ImportedSource> {\n const config = parseConfig(target.config)\n const maxRefs = config.maxRefs ?? 1000\n const seenSlugs = new Set<string>()\n let yielded = 0\n\n for (const ref of config.refs) {\n if (yielded >= maxRefs) break\n\n // A port signals \"couldn't resolve this ref\" with null. A *thrown* error\n // (store unreachable, auth) must NOT abort the whole batch — the throw\n // would propagate out of this generator and kill every remaining ref.\n // Treat it as a per-ref skip; the importer is resumable, so a re-run\n // retries it.\n let doc: ConversationDoc | null\n try {\n doc = await this.opts.source.fetchConversation(ref)\n } catch {\n continue\n }\n if (!doc || doc.turns.length === 0) continue\n\n const body = renderTranscript(doc.turns)\n if (!body) continue // every turn was empty — nothing to distill\n\n const slug = uniqueSlug(\n slugify(doc.id, { fallback: \"\" }) ||\n slugify(doc.title ?? \"conversation\", { fallback: \"conversation\" }),\n seenSlugs\n )\n const language = normalizeLanguageTag(doc.language ?? config.language)\n const stamps = doc.turns\n .map(t => t.at)\n .filter((a): a is string => typeof a === \"string\" && a.length > 0)\n .sort()\n\n yield {\n slug,\n title: (doc.title ?? `Conversation ${doc.id}`).slice(0, 200),\n contentHash: sha256(body),\n body,\n authority: config.authority ?? \"secondary\",\n ...(language ? { language } : {}),\n ...(config.tags && config.tags.length > 0 ? { tags: config.tags } : {}),\n corpusMetadata: {\n conversationRef: ref,\n conversationId: doc.id,\n sourceKind: \"conversation\",\n turnCount: countTurns(doc.turns),\n ...(stamps.length\n ? { firstTurnAt: stamps[0], lastTurnAt: stamps[stamps.length - 1] }\n : {}),\n },\n }\n yielded++\n }\n }\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\nfunction parseConfig(\n raw: Readonly<Record<string, unknown>>\n): ConversationConfig {\n const rawRefs = raw.refs\n if (!Array.isArray(rawRefs) || rawRefs.length === 0) {\n throw new Error(\n \"ConversationImporter: config.refs is required (non-empty string[])\"\n )\n }\n const refs = rawRefs.filter(\n (x): x is string => typeof x === \"string\" && x.length > 0\n )\n if (refs.length === 0) {\n throw new Error(\n \"ConversationImporter: config.refs contained no usable strings\"\n )\n }\n const rawTags = raw.tags\n return {\n refs,\n maxRefs: typeof raw.maxRefs === \"number\" ? raw.maxRefs : undefined,\n tags: Array.isArray(rawTags)\n ? rawTags.filter((x): x is string => typeof x === \"string\")\n : undefined,\n language: typeof raw.language === \"string\" ? raw.language : undefined,\n authority: isAuthority(raw.authority) ? raw.authority : undefined,\n }\n}\n\nfunction isAuthority(v: unknown): v is Authority {\n return v === \"primary\" || v === \"secondary\" || v === \"rumour\"\n}\n\n/** Render turns to a plain transcript — `Role: text`, blank-line separated.\n * Empty-text turns are dropped so the distiller sees only substance. */\nfunction renderTranscript(turns: readonly ConversationTurn[]): string {\n const blocks: string[] = []\n for (const turn of turns) {\n const text = turn.text.trim()\n if (!text) continue\n blocks.push(`${labelRole(turn.role)}: ${text}`)\n }\n return blocks.join(\"\\n\\n\")\n}\n\nfunction countTurns(turns: readonly ConversationTurn[]): number {\n let n = 0\n for (const t of turns) if (t.text.trim()) n++\n return n\n}\n\nfunction labelRole(role: string): string {\n const r = role.trim()\n if (!r) return \"Speaker\"\n return r.charAt(0).toUpperCase() + r.slice(1)\n}\n\nfunction sha256(content: string): string {\n return \"sha256:\" + createHash(\"sha256\").update(content).digest(\"hex\")\n}\n","/**\n * DistillRunner — turn one raw source into refined AIP-10 entries.\n *\n * Reads nothing itself beyond what it's handed; writes each distilled item\n * as `entries/<kind-plural>/<year>/<slug>.md` (layout: \"dated\", default) or\n * `entries/<kind-plural>/<slug>.md` (layout: \"flat\") with `sources: [<sourceId>]`\n * (the provenance edge) and inherited `access`. Pure: consumes FsPort +\n * ClockPort + an injected DistillPort. The filesystem refs are the graph.\n */\n\nimport matter from \"gray-matter\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type { ClockPort } from \"../ports/clock.port.js\"\nimport { slugify, uniqueSlug } from \"../util/slug.js\"\nimport type { DistillPort, DistilledItem, RefinedKind } from \"./types.js\"\n\n/** Entry slugs must start with a letter; cap at 80 and fall back to \"entry\". */\nconst ENTRY_SLUG_OPTS = { leadingLetter: true, fallback: \"entry\", maxLen: 80 } as const\n\nconst KIND_DIR: Record<RefinedKind, string> = {\n principle: \"principles\",\n pattern: \"patterns\",\n critique: \"critiques\",\n summary: \"summaries\",\n example: \"examples\",\n}\n\nexport interface DistillSource {\n /** The raw source's AIP-10 id (becomes the `sources:` provenance ref). */\n readonly id: string\n readonly title: string\n readonly body: string\n readonly tags?: readonly string[]\n /** Access scope inherited by every entry distilled from this source. */\n readonly access?: string\n readonly domain?: string\n}\n\nexport interface DistillRunReport {\n readonly sourceId: string\n readonly entryPaths: readonly string[]\n readonly skipped: readonly string[] // slugs skipped (already exist)\n}\n\n/** Where distilled entries land under `entries/<kind>/`. */\nexport type EntryLayout = \"dated\" | \"flat\"\n\nexport interface DistillRunnerOptions {\n readonly fs: FsPort\n readonly clock: ClockPort\n readonly distiller: DistillPort\n /**\n * Entry path layout. \"dated\" (default) → `entries/<kind>/<year>/<slug>.md`\n * (scales to large corpora over time); \"flat\" → `entries/<kind>/<slug>.md`.\n */\n readonly layout?: EntryLayout\n}\n\nexport class DistillRunner {\n constructor(private readonly opts: DistillRunnerOptions) {}\n\n async run(source: DistillSource): Promise<DistillRunReport> {\n const items = await this.opts.distiller.distill({\n title: source.title,\n body: source.body,\n ...(source.tags ? { tags: source.tags } : {}),\n })\n\n const year = this.opts.clock.now().getUTCFullYear()\n const flat = this.opts.layout === \"flat\"\n const seen = new Set<string>()\n const entryPaths: string[] = []\n const skipped: string[] = []\n\n for (const item of items) {\n if (!item.title.trim() || !item.body.trim()) continue\n const slug = uniqueSlug(slugify(item.title, ENTRY_SLUG_OPTS), seen, 80)\n const dir = KIND_DIR[item.kind]\n const path = flat\n ? `entries/${dir}/${slug}.md`\n : `entries/${dir}/${year}/${slug}.md`\n\n if (await this.opts.fs.exists(path)) {\n skipped.push(slug)\n continue\n }\n await this.opts.fs.writeFile(path, serializeEntry(item, slug, source, this.opts.clock))\n entryPaths.push(path)\n }\n return { sourceId: source.id, entryPaths, skipped }\n }\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\nfunction serializeEntry(\n item: DistilledItem,\n slug: string,\n source: DistillSource,\n clock: ClockPort\n): string {\n const now = clock.now().toISOString()\n const fm: Record<string, unknown> = {\n schema: \"knowledge.entry/v1\",\n slug,\n kind: item.kind,\n title: item.title,\n updated_at: now,\n sources: [source.id], // ← derivedFrom / provenance edge\n confidence: typeof item.confidence === \"number\" ? item.confidence : 0.7,\n tags: dedupeTags(item.tags, source.tags),\n metadata: {\n corpus: {\n status: \"active\",\n ...(source.domain ? { domain: source.domain } : {}),\n // access inherited from the source — propagates up the chain so a\n // refined insight is never more visible than its evidence.\n ...(source.access ? { access: source.access } : {}),\n promotionMode: \"auto-distill\",\n promotedAt: now,\n },\n },\n }\n const body = item.body.trim()\n return matter.stringify(body.startsWith(\"\\n\") ? body : \"\\n\" + body, fm)\n}\n\nfunction dedupeTags(\n a: readonly string[] | undefined,\n b: readonly string[] | undefined\n): string[] {\n const out = new Set<string>()\n for (const raw of [...(a ?? []), ...(b ?? [])]) {\n const t = sanitizeTag(raw)\n if (t) out.add(t)\n }\n return [...out]\n}\n\n/** AIP-10 tag pattern is ^[a-z][a-z0-9-]*$ — lowercase, strip accents,\n * kebab-ize, drop anything that can't start with a letter. */\nfunction sanitizeTag(raw: string): string | null {\n const t = raw\n .toLowerCase()\n .normalize(\"NFD\")\n .replace(/[̀-ͯ]/g, \"\")\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .replace(/-{2,}/g, \"-\")\n return /^[a-z][a-z0-9-]*$/.test(t) ? t : null\n}\n\n","/**\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 * Shared distill prompt + parse — the model-agnostic core of distillation.\n *\n * Every DistillPort backend (an HTTP Messages-API distiller, a CLI-agent\n * distiller, an in-app model adapter) asks the same thing and reads the same\n * shape back, so the prompt and the tolerant JSON parse live here once. A\n * backend owns only the transport (HTTP vs. child process vs. SDK) and how it\n * extracts the model's text.\n */\n\nimport { z } from \"zod\"\nimport {\n REFINED_KIND_SCHEMA,\n type DistillInput,\n type DistilledItem,\n} from \"./types.js\"\n\n/** A single distilled item as the model is asked to emit it. */\nconst DISTILLED_ITEM = z\n .object({\n kind: REFINED_KIND_SCHEMA,\n title: z.string(),\n body: z.string(),\n confidence: z.number().optional(),\n tags: z.array(z.string()).optional(),\n })\n .loose()\n\n/** Build the distillation prompt for one source, capped at `maxItems`. */\nexport function buildDistillPrompt(\n input: DistillInput,\n maxItems: number\n): string {\n return `You distill a raw source (a video transcript or article) into REFINED, reusable knowledge for an AI operator. Extract the durable insights — not a summary of the video, but the transferable lessons.\n\nReturn a JSON array (max ${maxItems} items). Each item:\n{ \"kind\": one of \"principle\" | \"pattern\" | \"critique\" | \"summary\" | \"example\",\n \"title\": short imperative/declarative title,\n \"body\": 2-5 sentences, SELF-CONTAINED (no \"the speaker says\"), the actual insight,\n \"confidence\": 0-1, \"tags\": [short topic tags] }\n\nGuidance:\n- \"principle\": a durable rule of thumb. \"pattern\": a repeatable technique/sequence.\n \"critique\": a common mistake / anti-pattern. \"summary\": a compact overview.\n \"example\": a concrete worked instance worth remembering.\n- Drop filler, calls-to-action, tangents. Keep only what an operator could ACT on later.\n- Write every title and body in ENGLISH, even when the source is in another language. Translate the insight; do not copy the source language.\n\nSOURCE TITLE: ${input.title}\n${input.tags?.length ? `TAGS: ${input.tags.join(\", \")}\\n` : \"\"}SOURCE BODY:\n${input.body.slice(0, 24000)}\n\nReturn ONLY the JSON array, no prose.`\n}\n\n/** Tolerant parse: grab the first `[...]` block (allows ```json fences / prose). */\nexport function parseItems(text: string): DistilledItem[] {\n const start = text.indexOf(\"[\")\n const end = text.lastIndexOf(\"]\")\n if (start < 0 || end <= start) return []\n let raw: unknown\n try {\n raw = JSON.parse(text.slice(start, end + 1))\n } catch {\n return []\n }\n if (!Array.isArray(raw)) return []\n const out: DistilledItem[] = []\n for (const r of raw) {\n const item = DISTILLED_ITEM.safeParse(r)\n if (!item.success) continue\n const { kind, title, body, confidence, tags } = item.data\n out.push({\n kind,\n title,\n body,\n ...(typeof confidence === \"number\" ? { confidence } : {}),\n ...(tags ? { tags } : {}),\n })\n }\n return out\n}\n","/**\n * scanDistilledSourceIds — which raw source ids already have ≥1 refined entry\n * derived from them, found by reading the `sources:` provenance backlink on\n * every `entries/**​/*.md`. Lets an incremental distill skip sources already\n * done, so a daily re-run is idempotent (no duplicate entries, no wasted spend).\n *\n * Tolerant of both `walk` conventions a host's FsPort may use — paths relative\n * to the walked dir (MemFs) or anchored at the workspace root (a workspace\n * adapter) — by normalizing each back under `entries/` before reading.\n */\n\nimport matter from \"gray-matter\"\nimport { z } from \"zod\"\nimport type { FsPort } from \"../ports/fs.port.js\"\n\nconst ENTRY_SOURCES = z\n .object({ sources: z.array(z.string()).optional().catch(undefined) })\n .loose()\n\nexport async function scanDistilledSourceIds(\n fs: FsPort\n): Promise<Set<string>> {\n const ids = new Set<string>()\n let rels: readonly string[]\n try {\n rels = await fs.walk(\"entries\")\n } catch {\n return ids\n }\n for (const rel of rels) {\n if (!rel.endsWith(\".md\")) continue\n const path = rel.startsWith(\"entries/\") ? rel : `entries/${rel}`\n try {\n const fm = ENTRY_SOURCES.parse(matter(await fs.readFile(path)).data)\n if (fm.sources) for (const s of fm.sources) ids.add(s)\n } catch {\n // unreadable / no frontmatter — skip\n }\n }\n return ids\n}\n","/**\n * Distill registry — the catalog of distill kinds.\n *\n * Distill is four swappable slots: SOURCE (raw material) → IMPORTER (how to\n * render it) → DISTILLER (the LLM) → TARGET (where entries land). A\n * `DistillDescriptor` binds all four for one kind (\"conversation\", \"web\", …);\n * the registry holds them by id so the cron/worker can dispatch polymorphically\n * — adding a kind is registering a descriptor, with zero pipeline changes.\n *\n * Lightweight on purpose (mirrors the AIP-35 filesystem-provider registry):\n * descriptors are code-registered, so there is no `resolveConfig` / secrets /\n * UI-fields surface the way user-connected engine descriptors carry. Vendor-\n * neutral — the kit owns the contract + the generic runner; the per-kind\n * bindings live in each app's core package.\n */\n\nimport type { CorpusImporter, ImportedSource } from \"../importers/types.js\"\nimport type { ClockPort } from \"../ports/clock.port.js\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type { DistillPort } from \"./types.js\"\n\n/**\n * Who a distill runs for. `id` is the durable handle carried on the queued job\n * (`resolveScope` rehydrates it in the worker); `userId` feeds the job's owner.\n * Kinds extend this with their own scope fields (a guild id, a workspace id, …).\n */\nexport interface DistillScope {\n readonly id: string\n readonly userId: string\n readonly [key: string]: unknown\n}\n\n/** Where distilled entries land — the corpus filesystem for a scope. */\nexport interface DistillTarget {\n readonly fs: FsPort\n readonly clock: ClockPort\n /** Optional corpus root within the fs (defaults to the fs root, \"\"). */\n readonly root?: string\n}\n\n/**\n * SOURCE + IMPORTER bound to one scope. Co-constructed so both share a single\n * (cache-bearing) source instance where relevant (e.g. a windowed conversation\n * source loads each thread once). The binding owns the importer-native config\n * AND the provenance mapping, so `runDistill` stays importer-agnostic — a\n * conversation kind keys on `{refs}`/`conversationId`, a web kind on\n * `{urls}`/`originalUrl`, with no per-kind code in the runner.\n */\nexport interface DistillBinding {\n /** The kit importer for this kind (ConversationImporter, WebImporter, …). */\n readonly importer: CorpusImporter\n /**\n * Build the importer's NATIVE config for the fresh (not-yet-distilled)\n * material, or `null` when nothing new is left to import. The config is\n * passed straight to `importer.enumerate({ config })`, so its shape is the\n * importer's own (`{refs}`, `{urls}`, …). Filter against `distilled` (the set\n * of provenance ids already backing ≥1 entry) so a re-run only sees fresh work.\n */\n prepare(\n distilled: ReadonlySet<string>\n ): Promise<Readonly<Record<string, unknown>> | null>\n /**\n * Stable provenance id for an imported source — becomes the entry's\n * `sources:` backlink and the dedup key matched against `distilled`. MUST\n * agree with the ids `prepare` filters on (e.g. the window slug, the URL).\n */\n provenanceId(imported: ImportedSource): string\n}\n\n/**\n * One catalog entry: a distill kind, with its four slots bound to a scope.\n * Generic over the scope shape so each kind keeps its own typed scope while the\n * registry stores them uniformly.\n */\nexport interface DistillDescriptor<S extends DistillScope = DistillScope> {\n /** Stable kind id — \"conversation\" | \"web\" | … */\n readonly id: string\n /** Queue type the cron submits and the worker handles, e.g. \"distill:conversation\". */\n readonly jobType: string\n /** Human-readable label (diagnostics / surfaces). */\n readonly label: string\n /** Tags applied to every source distilled by this kind (e.g. [\"personal\"]). */\n readonly tags?: readonly string[]\n\n /**\n * SOURCE + IMPORTER slots, bound to the scope. Receives the resolved TARGET\n * so an importer that reads the corpus filesystem (e.g. refine-its-own-sources)\n * can bind against it without resolving the target a second time.\n */\n bind(scope: S, target: DistillTarget): DistillBinding\n /** DISTILLER slot: the LLM boundary for this scope. */\n distiller(scope: S): DistillPort\n /** TARGET slot: where entries land for this scope. */\n target(scope: S): Promise<DistillTarget>\n\n /**\n * Consent gate. Checked at fan-out (bulk filter) AND re-checked in the worker\n * (authoritative — it can flip between enqueue and execution). Absent ⇒ no gate.\n */\n consent?(scope: S): Promise<boolean>\n /** Who to run for. Implementations should stream/paginate at scale. */\n scopes(): Promise<readonly S[]>\n /** Rehydrate a scope from its `id` — the worker holds only the id post-enqueue. */\n resolveScope(scopeId: string): Promise<S>\n}\n\nexport interface DistillRegistry {\n /** Register a kind. Throws on duplicate id. */\n register<S extends DistillScope>(descriptor: DistillDescriptor<S>): void\n has(id: string): boolean\n /** Resolve by id. Throws when the id was never registered. */\n resolve(id: string): DistillDescriptor\n /** All registered descriptors (for the cron fan-out + worker handler map). */\n list(): DistillDescriptor[]\n}\n\nexport function createDistillRegistry(): DistillRegistry {\n const descriptors = new Map<string, DistillDescriptor>()\n\n return {\n register(descriptor) {\n if (descriptors.has(descriptor.id)) {\n throw new Error(`Distill descriptor \"${descriptor.id}\" is already registered`)\n }\n descriptors.set(descriptor.id, descriptor)\n },\n has(id) {\n return descriptors.has(id)\n },\n resolve(id) {\n const descriptor = descriptors.get(id)\n if (!descriptor) {\n throw new Error(\n `Distill descriptor \"${id}\" is not registered. Registered: ${[...descriptors.keys()].join(\", \") || \"(none)\"}`\n )\n }\n return descriptor\n },\n list() {\n return [...descriptors.values()]\n },\n }\n}\n","/**\n * runDistill — the generic distill pass for one (descriptor × scope).\n *\n * The kind-agnostic generalization of the conversation pipeline: resolve the\n * scope's TARGET, scan which provenance ids are already distilled, ask the\n * binding (SOURCE + IMPORTER) for the fresh refs, import each, and run the\n * DISTILLER over it — writing refined AIP-10 entries via `DistillRunner`.\n * No per-kind branches: every variation rides on the descriptor's slots.\n *\n * Idempotent: a unit whose provenance id already backs an entry is skipped by\n * the binding's `prepare`, and `DistillRunner` additionally skips any entry\n * slug that already exists — so a daily re-run only adds fresh material.\n */\n\nimport { DistillRunner, type DistillSource } from \"./runner.js\"\nimport { scanDistilledSourceIds } from \"./scan.js\"\nimport type { DistillDescriptor, DistillScope } from \"./registry.js\"\n\nexport interface DistillReport {\n readonly descriptorId: string\n readonly scopeId: string\n /** Sources the importer yielded this run. */\n unitsConsidered: number\n /** Units that produced ≥1 new entry. */\n unitsDistilled: number\n entriesWritten: number\n /** Entry slugs skipped because an identical title already existed. */\n skipped: number\n}\n\nexport async function runDistill<S extends DistillScope>(\n descriptor: DistillDescriptor<S>,\n scope: S\n): Promise<DistillReport> {\n const report: DistillReport = {\n descriptorId: descriptor.id,\n scopeId: scope.id,\n unitsConsidered: 0,\n unitsDistilled: 0,\n entriesWritten: 0,\n skipped: 0,\n }\n\n const target = await descriptor.target(scope)\n const distilled = await scanDistilledSourceIds(target.fs)\n const binding = descriptor.bind(scope, target)\n const config = await binding.prepare(distilled)\n // null ⇒ the binding found nothing fresh to import this run.\n if (!config) return report\n\n const runner = new DistillRunner({\n fs: target.fs,\n clock: target.clock,\n distiller: descriptor.distiller(scope),\n })\n\n for await (const imported of binding.importer.enumerate({\n importerId: descriptor.id,\n config,\n })) {\n report.unitsConsidered++\n // Provenance id is binding-defined (window slug, URL, …) so the skip-scan\n // matches it on the next run — not the slugified entry slug.\n const source: DistillSource = {\n id: binding.provenanceId(imported),\n title: imported.title,\n body: imported.body,\n ...(imported.tags ? { tags: imported.tags } : {}),\n }\n try {\n const r = await runner.run(source)\n if (r.entryPaths.length > 0) report.unitsDistilled++\n report.entriesWritten += r.entryPaths.length\n report.skipped += r.skipped.length\n } catch {\n // One unit failing (rate cap, transient) must not abort the rest — it\n // stays undistilled and is retried next run.\n }\n }\n return report\n}\n","/**\n * ClaudeDistiller — a `DistillPort` backed by Claude over the Messages API.\n * Reuses the kit's shared prompt + tolerant parse (`buildDistillPrompt` /\n * `parseItems`), owning only the HTTP transport. SDK-free (raw fetch) so the\n * job takes no client-lib dependency.\n *\n * Vendor-neutral: the only host coupling is an injected `apiKey` / `model` /\n * `baseUrl` — no app names, no env-name assumptions. Distillation is bulk +\n * background, so a mid-tier model is the sensible default; the caller gates\n * the spend (consent + incremental windows).\n */\n\nimport { z } from \"zod\"\nimport { buildDistillPrompt, parseItems } from \"./prompt.js\"\nimport type { DistillInput, DistilledItem, DistillPort } from \"./types.js\"\n\n/** The Messages API response shape we read (just the text content blocks). */\nconst ANTHROPIC_RESPONSE = z\n .object({\n content: z\n .array(\n z.object({ type: z.string(), text: z.string().optional() }).loose()\n )\n .optional(),\n })\n .loose()\n\nexport interface ClaudeDistillerOptions {\n readonly apiKey: string\n /** Defaults to a mid-tier model — distillation is bulk + background. */\n readonly model?: string\n readonly baseUrl?: string\n /** Max refined items to extract per source. */\n readonly maxItems?: number\n}\n\nexport class ClaudeDistiller implements DistillPort {\n private readonly apiKey: string\n private readonly model: string\n private readonly baseUrl: string\n private readonly maxItems: number\n\n constructor(opts: ClaudeDistillerOptions) {\n this.apiKey = opts.apiKey\n this.model = opts.model ?? \"claude-sonnet-4-6\"\n this.baseUrl = (opts.baseUrl ?? \"https://api.anthropic.com/v1\").replace(\n /\\/+$/,\n \"\"\n )\n this.maxItems = opts.maxItems ?? 8\n }\n\n async distill(input: DistillInput): Promise<readonly DistilledItem[]> {\n const prompt = buildDistillPrompt(input, this.maxItems)\n const res = await fetch(`${this.baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"x-api-key\": this.apiKey,\n \"anthropic-version\": \"2023-06-01\",\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n model: this.model,\n max_tokens: 4096,\n messages: [{ role: \"user\", content: prompt }],\n }),\n })\n if (!res.ok) {\n throw new Error(\n `Claude distill ${res.status}: ${(await res.text()).slice(0, 200)}`\n )\n }\n const parsed = ANTHROPIC_RESPONSE.safeParse(await res.json())\n const text = parsed.success\n ? ((parsed.data.content ?? []).find(c => c.type === \"text\")?.text ?? \"\")\n : \"\"\n return parseItems(text)\n }\n}\n","/**\n * Conversation windowing — pure helpers + the windowed-source contract.\n *\n * Chat is append-only, so a single immutable slug per conversation would\n * collide once new turns arrive. The fix is WINDOWING: each (thread,\n * completed-UTC-day) slice is the unit that distils exactly once (a closed day\n * is immutable). These helpers compose / parse the window ref the importer\n * resolves and the provenance slug the distilled-scan dedups on.\n *\n * No transport, no chat-store, no model dependency — just string algebra over\n * `(threadId, day)` plus a structural source contract. A fake satisfying\n * `ConversationWindowSource` is all a test needs.\n */\n\nimport type { ConversationSourcePort } from \"../ports/conversation-source.port.js\"\n\nconst WINDOW_SEP = \"::\"\n\n/** Compose the importer ref for one (thread, day) window. */\nexport function windowRef(threadId: string, day: string): string {\n return `${threadId}${WINDOW_SEP}${day}`\n}\n\n/** Parse a window ref back to its parts, or null when malformed. */\nexport function parseWindowRef(\n ref: string\n): { threadId: string; day: string } | null {\n const i = ref.indexOf(WINDOW_SEP)\n if (i < 0) return null\n const threadId = ref.slice(0, i)\n const day = ref.slice(i + WINDOW_SEP.length)\n return threadId && day ? { threadId, day } : null\n}\n\n/** Slug base a window resolves to — also the `sources:` provenance id, so the\n * distilled-scan can dedup windows across runs with no slug drift. */\nexport function windowSlug(threadId: string, day: string): string {\n return `${threadId}-${day}`\n}\n\n/** A thread the source owns — minimal shape the enumeration needs. */\nexport interface ConversationThreadRef {\n readonly id: string\n readonly threadId?: string\n}\n\n/**\n * The windowed source the distill pipeline drives: a `ConversationSourcePort`\n * that can also enumerate its threads and each thread's completed-day windows.\n * A fake satisfying this is all a test needs (no DB, no chat store).\n */\nexport interface ConversationWindowSource extends ConversationSourcePort {\n listThreads(): Promise<ConversationThreadRef[]>\n listWindows(threadId: string): Promise<string[]>\n}\n\n/**\n * Enumerate the window refs worth distilling for a windowed source: every\n * (thread, completed-day) window whose provenance slug isn't already distilled.\n * Generic over any `ConversationWindowSource`, so a binding never re-implements\n * the thread→window→skip loop.\n */\nexport async function enumerateWindowRefs(\n source: ConversationWindowSource,\n distilled: ReadonlySet<string>\n): Promise<string[]> {\n const refs: string[] = []\n for (const thread of await source.listThreads()) {\n const threadId = thread.threadId ?? thread.id\n if (!threadId) continue\n for (const day of await source.listWindows(threadId)) {\n if (distilled.has(windowSlug(threadId, day))) continue\n refs.push(windowRef(threadId, day))\n }\n }\n return refs\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","/**\n * OverlayFs — stacks FsPorts so a writable layer shadows read-only ones.\n *\n * This is the customization engine for the SKILL→KNOWLEDGE→SOURCES spine:\n * a guild's editable corpus (its system workspace) sits ON TOP of one or\n * more read-only knowledge packs (shared, shipped). Layers are ordered\n * highest-precedence first.\n *\n * overlay = new OverlayFs([guildFs, packFs]) // guild wins\n *\n * Resolution is by RELATIVE PATH:\n * - reads (readFile/stat/exists) return the first layer that has the path\n * - walk/readdir UNION across layers, deduped — so an entry the guild\n * re-authors at the same path appears ONCE, with the guild's content\n * - a path only in the pack passes through unchanged (the floor)\n * - a path only in the guild is additive (extend)\n * - writes/appends/locks always target the top (writable) layer; the\n * packs stay pristine for every other guild\n *\n * This keeps `resolveKnowledge` untouched: it walks `entries/**` over the\n * overlay and never sees a pack entry that the guild has shadowed.\n */\n\nimport type { FsPort, FsLockHandle, FsStat } from \"../ports/fs.port.js\"\n\n/**\n * Sibling-path marker that removes (whiteouts) a lower layer's entry. To\n * drop `entries/foo.md`, a higher layer authors `entries/foo.md.whiteout`.\n * A marker file (not a frontmatter flag) keeps overlay resolution a pure\n * path operation — listing a directory never reads entry bodies.\n */\nexport const WHITEOUT_SUFFIX = \".whiteout\"\n\nconst isMarker = (p: string): boolean => p.endsWith(WHITEOUT_SUFFIX)\nconst baseOf = (markerPath: string): string =>\n markerPath.slice(0, -WHITEOUT_SUFFIX.length)\n\nexport interface OverlayFsOptions {\n /**\n * Honor `.whiteout` markers so a higher layer can REMOVE (not just\n * shadow) a lower entry. OFF by default: with whiteout disabled the\n * overlay is pure union + shadow, byte-for-byte the original behavior.\n */\n readonly whiteout?: boolean\n /**\n * Index of the writable layer (writes / appends / locks target it).\n * Defaults to 0. Set this when a read-only CONSTRAINT floor is pinned\n * ABOVE the writable layer: read precedence (layer order) and the write\n * target are then independent — the floor wins reads, the guild layer\n * still takes writes.\n */\n readonly writableLayer?: number\n}\n\nexport class OverlayFs implements FsPort {\n /** Layers ordered highest-precedence first. */\n private readonly layers: readonly FsPort[]\n private readonly whiteout: boolean\n private readonly writableIndex: number\n\n constructor(layers: readonly FsPort[], options: OverlayFsOptions = {}) {\n if (layers.length === 0) {\n throw new Error(\"OverlayFs requires at least one layer\")\n }\n this.layers = layers\n this.whiteout = options.whiteout ?? false\n const w = options.writableLayer ?? 0\n if (w < 0 || w >= layers.length) {\n throw new Error(\n `OverlayFs: writableLayer ${w} out of range [0, ${layers.length - 1}]`\n )\n }\n this.writableIndex = w\n }\n\n /**\n * Top-down resolution for a single path: the first layer that declares\n * either the real entry OR its whiteout marker decides. Within one\n * layer a real entry wins over a stale marker. Returns null when no\n * layer declares the path, and `{ removed: true }` when the winning\n * layer tombstones it.\n */\n private async resolvePath(\n path: string\n ): Promise<{ layer: FsPort } | { removed: true } | null> {\n const marker = path + WHITEOUT_SUFFIX\n for (const layer of this.layers) {\n if (await layer.exists(path)) return { layer }\n if (await layer.exists(marker)) return { removed: true }\n }\n return null\n }\n\n async exists(path: string): Promise<boolean> {\n if (!this.whiteout) {\n for (const layer of this.layers) {\n if (await layer.exists(path)) return true\n }\n return false\n }\n if (isMarker(path)) return false // markers are not visible entries\n const r = await this.resolvePath(path)\n return r !== null && !(\"removed\" in r)\n }\n\n async readFile(path: string): Promise<string> {\n if (this.whiteout && !isMarker(path)) {\n const r = await this.resolvePath(path)\n if (r && \"layer\" in r) return await r.layer.readFile(path)\n // Tombstoned or genuinely missing — surface a plain not-found.\n return await this.layers[0]!.readFile(path)\n }\n for (const layer of this.layers) {\n if (await layer.exists(path)) return await layer.readFile(path)\n }\n // Match a plain fs: throw on a genuinely missing path.\n return await this.layers[0]!.readFile(path)\n }\n\n async stat(path: string): Promise<FsStat | null> {\n if (this.whiteout && !isMarker(path)) {\n const r = await this.resolvePath(path)\n if (r && \"layer\" in r) return await r.layer.stat(path)\n return null\n }\n if (this.whiteout && isMarker(path)) return null\n for (const layer of this.layers) {\n const s = await layer.stat(path)\n if (s) return s\n }\n return null\n }\n\n async readdir(path: string): Promise<readonly string[]> {\n if (!this.whiteout) {\n const seen = new Set<string>()\n for (const layer of this.layers) {\n let names: readonly string[]\n try {\n names = await layer.readdir(path)\n } catch {\n continue // layer lacks this dir — skip\n }\n for (const n of names) seen.add(n)\n }\n return [...seen]\n }\n return this.unionWhiteoutAware((layer) => layer.readdir(path))\n }\n\n async walk(path: string): Promise<readonly string[]> {\n if (!this.whiteout) {\n const seen = new Set<string>()\n for (const layer of this.layers) {\n const rels = await layer.walk(path) // NodeFsAdapter returns [] if missing\n for (const rel of rels) seen.add(rel)\n }\n return [...seen]\n }\n return this.unionWhiteoutAware((layer) => layer.walk(path))\n }\n\n /**\n * Union the entries each layer reports for a path (basenames for\n * readdir, relative paths for walk), resolving whiteouts top-down: the\n * first layer (highest precedence) that declares an entry or its marker\n * wins. Real entries win over markers within the same layer; marker\n * files are stripped from the result.\n */\n private async unionWhiteoutAware(\n list: (layer: FsPort) => Promise<readonly string[]>\n ): Promise<readonly string[]> {\n const decided = new Map<string, \"present\" | \"removed\">()\n for (const layer of this.layers) {\n let entries: readonly string[]\n try {\n entries = await list(layer)\n } catch {\n continue // layer lacks this dir — skip\n }\n const reals = entries.filter((e) => !isMarker(e))\n const markerBases = entries.filter(isMarker).map(baseOf)\n // Real entries first so a real entry wins over a same-layer marker.\n for (const r of reals) if (!decided.has(r)) decided.set(r, \"present\")\n for (const b of markerBases) if (!decided.has(b)) decided.set(b, \"removed\")\n }\n const out: string[] = []\n for (const [name, state] of decided) {\n if (state === \"present\") out.push(name)\n }\n return out\n }\n\n // ── mutations target the writable layer only ────────────────────────\n\n async writeFile(path: string, content: string): Promise<void> {\n return await this.layers[this.writableIndex]!.writeFile(path, content)\n }\n\n async appendFile(path: string, content: string): Promise<void> {\n return await this.layers[this.writableIndex]!.appendFile(path, content)\n }\n\n async lock(path: string): Promise<FsLockHandle> {\n return await this.layers[this.writableIndex]!.lock(path)\n }\n}\n\n/**\n * ReadOnlyFs — wraps an FsPort and rejects every mutation. Use to seal a\n * knowledge pack so a misconfigured host can never write into the shared,\n * shipped corpus (the guild's edits belong in its own overlay layer).\n */\nexport class ReadOnlyFs implements FsPort {\n constructor(private readonly inner: FsPort) {}\n\n exists(path: string): Promise<boolean> {\n return this.inner.exists(path)\n }\n readFile(path: string): Promise<string> {\n return this.inner.readFile(path)\n }\n stat(path: string): Promise<FsStat | null> {\n return this.inner.stat(path)\n }\n readdir(path: string): Promise<readonly string[]> {\n return this.inner.readdir(path)\n }\n walk(path: string): Promise<readonly string[]> {\n return this.inner.walk(path)\n }\n\n async writeFile(path: string, _content: string): Promise<void> {\n throw new Error(`ReadOnlyFs: refusing to write \"${path}\" — packs are immutable`)\n }\n async appendFile(path: string, _content: string): Promise<void> {\n throw new Error(`ReadOnlyFs: refusing to append \"${path}\" — packs are immutable`)\n }\n async lock(path: string): Promise<FsLockHandle> {\n throw new Error(`ReadOnlyFs: refusing to lock \"${path}\" — packs are immutable`)\n }\n}\n","/**\n * MemFs — an in-memory FsPort over a flat `path → content` map.\n *\n * Paths are workspace-relative (no leading slash), exactly like the disk\n * adapters; `walk(dir)` returns paths relative to the walked directory, so it\n * composes with `resolveKnowledge` (which re-prefixes) and with `OverlayFs`\n * unchanged.\n *\n * Primary use: a knowledge PACK whose entries are inlined into the JS bundle\n * at build time (see `@guilde/knowledge-packs`). Reading from an in-memory map\n * means packs ride inside `dist` — no runtime `fs`, no path resolution, no\n * loose data files for the deploy to drop. Wrap in `ReadOnlyFs` for packs.\n */\n\nimport type { FsPort, FsStat, FsLockHandle } from \"../ports/fs.port.js\"\n\nexport class MemFs implements FsPort {\n private readonly files: Record<string, string>\n\n constructor(files: Record<string, string>) {\n // Copy so a caller's shared/frozen map can't be mutated through this fs.\n this.files = { ...files }\n }\n\n async exists(path: string): Promise<boolean> {\n return path in this.files\n }\n\n async readFile(path: string): Promise<string> {\n const content = this.files[path]\n if (content === undefined) throw new Error(`MemFs: ENOENT ${path}`)\n return content\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n this.files[path] = content\n }\n\n async appendFile(path: string, content: string): Promise<void> {\n this.files[path] = (this.files[path] ?? \"\") + content\n }\n\n async readdir(path: string): Promise<readonly string[]> {\n const prefix = path.endsWith(\"/\") ? path : `${path}/`\n const names = new Set<string>()\n for (const key of Object.keys(this.files)) {\n if (key.startsWith(prefix)) names.add(key.slice(prefix.length).split(\"/\")[0]!)\n }\n return [...names]\n }\n\n async walk(path: string): Promise<readonly string[]> {\n const prefix = path.endsWith(\"/\") ? path : `${path}/`\n return Object.keys(this.files)\n .filter(key => key.startsWith(prefix))\n .map(key => key.slice(prefix.length))\n }\n\n async stat(path: string): Promise<FsStat | null> {\n const content = this.files[path]\n return content === undefined ? null : { kind: \"file\", bytes: content.length }\n }\n\n async lock(): Promise<FsLockHandle> {\n return { release: async () => {} }\n }\n}\n","/**\n * Deterministic shadow-traffic sampling.\n *\n * A stable token (e.g. a conversation id) is hashed with a per-arm salt\n * into a 0..1 bucket, so the SAME token always lands the same arm — an\n * eval batch partitioned by that token is reproducible, and a shadow\n * layer rolls out to a fixed fraction of traffic rather than flickering\n * per request.\n *\n * Used by both the playbook overlay resolver and the knowledge-stack\n * resolver so % rollout behaves identically across the two.\n */\n\nimport { createHash } from \"node:crypto\"\n\nexport const DEFAULT_SHADOW_TRAFFIC_PCT = 0.1\n\n/** Deterministic bucket in [0, 1) from a token + salt. */\nexport function deterministicBucket(token: string, salt: string): number {\n const h = createHash(\"sha256\").update(`${token}|${salt}`).digest()\n // First 4 bytes as a uint32 → [0, 1).\n return h.readUInt32BE(0) / 0x1_0000_0000\n}\n\n/**\n * True iff this token is sampled into a shadow arm of width `pct`. No\n * token (e.g. a one-shot tool call) → never sampled: shadow arms only\n * fire on traffic with stable identity.\n */\nexport function sampleShadow(\n token: string | undefined,\n salt: string,\n pct: number = DEFAULT_SHADOW_TRAFFIC_PCT\n): boolean {\n if (!token) return false\n if (pct <= 0) return false\n if (pct >= 1) return true\n return deterministicBucket(token, salt) < pct\n}\n","/**\n * StackResolver — given a `ResolutionContext` and a registry of\n * `LayerProvider`s, produce the band-ordered list of layers an operator's\n * recall is resolved against.\n *\n * The generalization of `OperatorOverlayResolver` (playbooks): same\n * ctx → registry → priority-sort → ordered-list shape, same deterministic\n * shadow sampling for % rollout. Pure — no I/O. The host turns the emitted\n * refs into mounted FsPorts (see `buildOverlayFromStack`).\n */\n\nimport type { Registry } from \"@agentproto/registry\"\nimport { sampleShadow } from \"../util/shadow-sample.js\"\nimport type {\n LayerProvider,\n ResolutionContext,\n StackEntry,\n StackResolution,\n StackSkip,\n} from \"./types.js\"\n\nexport class StackResolver<TSubject = unknown> {\n constructor(\n private readonly registry: Registry<LayerProvider<TSubject>>\n ) {}\n\n async resolve(\n ctx: ResolutionContext<TSubject>\n ): Promise<StackResolution> {\n // Lower band = higher precedence. Stable order for equal bands is the\n // registry's insertion order (AIP-43 Maps preserve it).\n const providers = [...this.registry.list()].sort((a, b) => a.band - b.band)\n\n const entries: StackEntry[] = []\n const skipped: StackSkip[] = []\n\n for (const p of providers) {\n let shadowSampled = false\n if (p.shadow) {\n shadowSampled = sampleShadow(ctx.conversationId, p.id, p.shadow.pct)\n if (!shadowSampled) {\n skipped.push({\n providerId: p.id,\n dimension: p.dimension,\n reason: \"shadow-not-sampled\",\n })\n continue\n }\n }\n\n const refs = await p.resolve(ctx)\n if (refs.length === 0) {\n skipped.push({\n providerId: p.id,\n dimension: p.dimension,\n reason: \"empty\",\n })\n continue\n }\n\n entries.push({\n providerId: p.id,\n band: p.band,\n mode: p.mode,\n dimension: p.dimension,\n refs,\n shadowSampled,\n })\n }\n\n return Object.freeze({\n entries: Object.freeze(entries),\n skipped: Object.freeze(skipped),\n })\n }\n}\n","/**\n * Turn a resolved knowledge stack into a mounted `OverlayFs`, and the\n * helpers that flatten it.\n *\n * Mount order encodes the AIP-10 plane-precedence invariant:\n *\n * [ ...constraint layers (read-only floor, band-ordered) ] ← top\n * [ guild writable layer ] ← writes here\n * [ ...lens layers (band-ordered) ] ← floor packs\n *\n * Constraints are hoisted ABOVE the guild layer so neither a guild edit\n * nor a `.whiteout` can shadow or remove them (they sit higher, and\n * top-down resolution + whiteout-only-suppresses-lower make them a true\n * floor). Writes still target the guild layer via `writableLayer`, so the\n * read floor and the write target stay independent.\n */\n\nimport { OverlayFs, ReadOnlyFs } from \"../knowledge/overlay-fs.js\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type { LayerRef, StackResolution } from \"./types.js\"\n\nexport interface BuildOverlayOptions {\n /** The guild's own editable corpus — the single writable layer. */\n readonly guildFs: FsPort\n /** The resolved stack (band-ordered entries). */\n readonly stack: StackResolution\n /** Resolve a layer ref to an FsPort, or null if it has no mountable source. */\n readonly loadFs: (ref: LayerRef) => FsPort | null\n}\n\n/**\n * Build the mounted overlay for a resolved stack. Returns `guildFs`\n * unchanged when no layer resolves to a mountable source (so the\n * single-layer fast path is preserved).\n */\nexport function buildOverlayFromStack(opts: BuildOverlayOptions): FsPort {\n const { guildFs, stack, loadFs } = opts\n\n const constraintFs: FsPort[] = []\n const lensFs: FsPort[] = []\n for (const entry of stack.entries) {\n const target = entry.mode === \"constraint\" ? constraintFs : lensFs\n for (const ref of entry.refs) {\n const fs = loadFs(ref)\n if (fs) target.push(entry.mode === \"constraint\" ? new ReadOnlyFs(fs) : fs)\n }\n }\n\n if (constraintFs.length === 0 && lensFs.length === 0) return guildFs\n\n const layers = [...constraintFs, guildFs, ...lensFs]\n return new OverlayFs(layers, {\n whiteout: true,\n writableLayer: constraintFs.length, // index of guildFs\n })\n}\n\n/**\n * Flatten a resolved stack to a de-duplicated, band-ordered list of pack\n * refs (kind `pack` or unspecified). This reproduces the legacy\n * `resolveOperatorPacks` output shape (operator packs before role packs,\n * each id once) so the pack-id contract stays stable.\n */\nexport function flattenPackRefs(stack: StackResolution): string[] {\n const out: string[] = []\n for (const entry of stack.entries) {\n for (const ref of entry.refs) {\n if (ref.kind && ref.kind !== \"pack\") continue\n if (!out.includes(ref.ref)) out.push(ref.ref)\n }\n }\n return out\n}\n\n/** Pack refs split by composition mode, each list deduped + band-ordered. */\nexport interface StackRefPartition {\n /** Lens packs — mount UNDER the writable layer (the guild shadows them). */\n readonly lens: readonly string[]\n /** Constraint packs — mount ABOVE the writable layer (a non-shadowable floor). */\n readonly constraint: readonly string[]\n}\n\n/**\n * Partition a resolved stack's pack refs by mode. The host mounts `lens`\n * below the guild layer and `constraint` above it (read-only), so a\n * compliance/legal floor cannot be shadowed or tombstoned. With no\n * constraint layers resolved, `lens` equals `flattenPackRefs` — the legacy\n * pack-id contract.\n */\nexport function partitionStackRefs(stack: StackResolution): StackRefPartition {\n const lens: string[] = []\n const constraint: string[] = []\n for (const entry of stack.entries) {\n const target = entry.mode === \"constraint\" ? constraint : lens\n for (const ref of entry.refs) {\n if (ref.kind && ref.kind !== \"pack\") continue\n if (!target.includes(ref.ref)) target.push(ref.ref)\n }\n }\n return { lens, constraint }\n}\n","/**\n * SyncRunner — push refined corpus entries to a SinkPort. Agnostic: it scans\n * `entries/` (via resolveKnowledge), shapes each as a SinkItem, and pushes\n * through the injected sink. The sink (and its host binding) is config, not\n * code here. Sources stay local (raw archive); only refined knowledge syncs.\n */\n\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport { resolveKnowledge, type CorpusEntryQuery } from \"../knowledge/resolve.js\"\nimport type { SinkPort, SinkItem, SinkPushResult } from \"./types.js\"\n\nexport interface SyncRunnerOptions {\n readonly fs: FsPort\n readonly sink: SinkPort\n /** Which entries to sync (tags/kinds). Empty = all refined entries. */\n readonly select?: CorpusEntryQuery\n /** URI scheme for the item address. Default `corpus`. */\n readonly uriScheme?: string\n /** Pace between pushes (ms). Default 0. */\n readonly throttleMs?: number\n readonly sleep?: (ms: number) => Promise<void>\n}\n\nexport interface SyncReport {\n readonly pushed: number\n readonly skipped: number\n readonly failed: number\n readonly results: readonly SinkPushResult[]\n}\n\nexport class SyncRunner {\n constructor(private readonly opts: SyncRunnerOptions) {}\n\n async run(): Promise<SyncReport> {\n const scheme = this.opts.uriScheme ?? \"corpus\"\n const throttle = this.opts.throttleMs ?? 0\n const sleep = this.opts.sleep ?? ((ms: number) => new Promise(r => setTimeout(r, ms)))\n\n const entries = await resolveKnowledge({\n fs: this.opts.fs,\n query: this.opts.select ?? {},\n })\n\n const results: SinkPushResult[] = []\n let pushed = 0\n let skipped = 0\n let failed = 0\n\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i]!\n if (i > 0 && throttle > 0) await sleep(throttle)\n const item: SinkItem = {\n slug: e.slug,\n kind: e.kind,\n title: e.title,\n body: e.body,\n sources: e.sources,\n tags: e.tags,\n confidence: e.confidence,\n ...(e.access ? { access: e.access } : {}),\n uri: `${scheme}://${e.slug}`,\n }\n let res: SinkPushResult\n try {\n res = await this.opts.sink.push(item)\n } catch (err) {\n res = { uri: item.uri, ok: false, error: err instanceof Error ? err.message : String(err) }\n }\n results.push(res)\n if (res.skipped) skipped++\n else if (res.ok) pushed++\n else failed++\n }\n return { pushed, skipped, failed, results }\n }\n}\n","/**\n * Multi-reviewer score aggregation.\n *\n * High-stakes corpus entries (those flagged by curator policy as\n * needing N-reviewer review) get scored by multiple reviewers — the\n * single-reviewer path is fine for the bulk of the queue, but the\n * top quality tier deserves redundancy.\n *\n * Aggregation policy:\n * - **Median** is the default — robust to a single outlier reviewer.\n * - **Weighted-median** uses reviewer track-record weights so a\n * well-calibrated reviewer's score counts for more than a fresh /\n * under-calibrated one.\n *\n * Disagreement detection: when the spread between the highest and\n * lowest review exceeds a threshold, the aggregate carries a\n * `disagreement: true` flag — the curator's queue can route those\n * entries to human adjudication rather than auto-trust the median.\n *\n * Pure — no I/O. Inputs come from the lifecycle workflow; outputs\n * feed the gate evaluator.\n */\n\nexport interface ReviewerScore {\n /** AIP-23-style identity. */\n readonly reviewerIdentity: string\n /** 0..5 (matches metadata.corpus.qualityScore convention). */\n readonly score: number\n /**\n * Optional confidence weight from the reviewer's track record\n * (correlation with downstream utility/lift). Defaults to 1.0\n * for unknown reviewers. See `correlation.ts`.\n */\n readonly weight?: number\n readonly at: string\n readonly note?: string\n}\n\nexport interface AggregateOptions {\n /** Spread threshold above which `disagreement` is flagged. Default: 1.5. */\n readonly disagreementThreshold?: number\n /** When true, use weighted-median; else plain median. */\n readonly weighted?: boolean\n}\n\nexport interface AggregateResult {\n /** Aggregate qualityScore (0..5). */\n readonly aggregate: number\n /** Highest vs lowest review difference. */\n readonly spread: number\n /** True when spread > disagreementThreshold. */\n readonly disagreement: boolean\n /** Number of reviewers that contributed. */\n readonly sampleSize: number\n /** Per-reviewer breakdown for the curator UI. */\n readonly breakdown: readonly {\n readonly reviewerIdentity: string\n readonly score: number\n readonly weight: number\n }[]\n}\n\nconst DEFAULT_DISAGREEMENT_THRESHOLD = 1.5\n\n/**\n * Aggregate N reviewer scores into one final score + a disagreement\n * flag. Empty input → aggregate=0, disagreement=false (caller decides\n * whether that's an error).\n */\nexport function aggregateReviewerScores(\n reviews: readonly ReviewerScore[],\n opts: AggregateOptions = {}\n): AggregateResult {\n if (reviews.length === 0) {\n return Object.freeze({\n aggregate: 0,\n spread: 0,\n disagreement: false,\n sampleSize: 0,\n breakdown: Object.freeze([]),\n })\n }\n const threshold = opts.disagreementThreshold ?? DEFAULT_DISAGREEMENT_THRESHOLD\n const weighted = opts.weighted !== false // default true\n\n const breakdown = reviews.map((r) => ({\n reviewerIdentity: r.reviewerIdentity,\n score: r.score,\n weight: typeof r.weight === \"number\" && r.weight > 0 ? r.weight : 1,\n }))\n const scores = breakdown.map((b) => b.score)\n const min = Math.min(...scores)\n const max = Math.max(...scores)\n const spread = max - min\n\n const aggregate = weighted\n ? weightedMedian(breakdown)\n : plainMedian(scores)\n\n return Object.freeze({\n aggregate,\n spread,\n disagreement: spread > threshold,\n sampleSize: reviews.length,\n breakdown: Object.freeze(breakdown),\n })\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\nfunction plainMedian(values: readonly number[]): number {\n const sorted = [...values].sort((a, b) => a - b)\n const mid = Math.floor(sorted.length / 2)\n if (sorted.length % 2 === 0) {\n return (sorted[mid - 1]! + sorted[mid]!) / 2\n }\n return sorted[mid]!\n}\n\n/**\n * Weighted median: order by score, cumulate weights, pick the score\n * at which the cumulative weight first crosses half the total weight.\n * Robust to outliers AND to the well-calibrated reviewers getting\n * more say than the under-calibrated ones.\n */\nfunction weightedMedian(\n items: readonly { score: number; weight: number }[]\n): number {\n const sorted = [...items].sort((a, b) => a.score - b.score)\n const totalWeight = sorted.reduce((acc, it) => acc + it.weight, 0)\n if (totalWeight === 0) return plainMedian(items.map((i) => i.score))\n const half = totalWeight / 2\n let acc = 0\n for (let i = 0; i < sorted.length; i++) {\n acc += sorted[i]!.weight\n if (acc >= half) {\n // When acc lands exactly on half + the next item also has\n // identical cumulative weight, the median is the average of the\n // two adjacent scores (matches the symmetric definition).\n if (acc === half && i + 1 < sorted.length) {\n return (sorted[i]!.score + sorted[i + 1]!.score) / 2\n }\n return sorted[i]!.score\n }\n }\n return sorted[sorted.length - 1]!.score\n}\n","/**\n * Reviewer track record — per-reviewer history of (score → observed\n * outcome) used to compute calibration weights.\n *\n * Stored at `corpus/_calibration/reviewer-track-record.yaml`:\n *\n * reviewers:\n * \"ws://operators/quality-reviewer\":\n * - { entrySlug, qualityScore, observedUtility?, observedLift?, at }\n * \"ws://operators/junior-reviewer\":\n * - ...\n *\n * Append-only — every review pass adds rows. The calibration routine\n * reads the configured window (typically 90 days), correlates the\n * reviewer's scores against observed retrieval-quality outcomes, and\n * derives a weight in [0, 1] that feeds the multi-reviewer aggregator\n * (see `aggregate.ts`).\n */\n\nimport { parse as yamlParse, stringify as yamlStringify } from \"yaml\"\nimport type { FsPort } from \"../ports/fs.port.js\"\n\nexport interface TrackRecordEntry {\n readonly entrySlug: string\n /** Reviewer-assigned 0..5 quality score at review time. */\n readonly qualityScore: number\n /** Retrieval utility (0..1 — fraction of hits actually cited). */\n readonly observedUtility?: number\n /** Retrieval lift (>1 = boost vs baseline, <1 = drag). */\n readonly observedLift?: number\n readonly at: string\n}\n\ninterface TrackRecordShape {\n reviewers: Record<string, readonly TrackRecordEntry[]>\n}\n\nconst DEFAULT_PATH = \"_calibration/reviewer-track-record.yaml\"\n\nexport interface ReviewerTrackRecordOptions {\n readonly fs: FsPort\n /** Workspace-relative path. Defaults to `_calibration/reviewer-track-record.yaml`. */\n readonly path?: string\n}\n\nexport class ReviewerTrackRecord {\n private readonly path: string\n\n constructor(private readonly opts: ReviewerTrackRecordOptions) {\n this.path = opts.path ?? DEFAULT_PATH\n }\n\n /** Load the full record. Empty when the file doesn't exist yet. */\n async load(): Promise<Readonly<Record<string, readonly TrackRecordEntry[]>>> {\n if (!(await this.opts.fs.exists(this.path))) return {}\n const content = await this.opts.fs.readFile(this.path)\n if (!content.trim()) return {}\n const parsed = yamlParse(content) as Partial<TrackRecordShape> | null\n if (!parsed || typeof parsed.reviewers !== \"object\") return {}\n return Object.freeze(parsed.reviewers as Record<string, readonly TrackRecordEntry[]>)\n }\n\n /** Append one entry under a reviewer's identity. */\n async append(\n reviewerIdentity: string,\n entry: TrackRecordEntry\n ): Promise<void> {\n const existing = await this.load()\n const current = existing[reviewerIdentity] ?? []\n const next: TrackRecordShape = {\n reviewers: {\n ...existing,\n [reviewerIdentity]: [...current, entry],\n },\n }\n const content = yamlStringify(next)\n await this.opts.fs.writeFile(this.path, content)\n }\n\n /**\n * Read all entries for a reviewer in the last N days. Used by the\n * calibration routine to compute correlation on a rolling window.\n */\n async window(\n reviewerIdentity: string,\n days: number,\n now: Date\n ): Promise<readonly TrackRecordEntry[]> {\n const all = await this.load()\n const slice = all[reviewerIdentity] ?? []\n const cutoffMs = now.getTime() - days * 86_400_000\n return slice.filter((e) => Date.parse(e.at) >= cutoffMs)\n }\n\n /** Reviewer identities present in the record. */\n async listReviewers(): Promise<readonly string[]> {\n const all = await this.load()\n return Object.keys(all)\n }\n}\n","/**\n * Calibration — correlate a reviewer's qualityScore against the\n * downstream retrieval-quality outcomes (utility + lift). Reviewers\n * whose scores don't predict outcomes are miscalibrated; their\n * weight drops in the multi-reviewer aggregator until they re-train.\n *\n * Math: Pearson correlation coefficient on two parallel arrays.\n * Returns NaN-safe r in [-1, 1]. Threshold for \"calibrated\" is host\n * policy; the helper just reports.\n *\n * Pure — no I/O. Inputs come from `ReviewerTrackRecord.window`,\n * outputs feed the calibration routine + multi-reviewer aggregator.\n */\n\nimport type { TrackRecordEntry } from \"./track-record.js\"\n\nexport interface ReviewerCalibration {\n readonly reviewerIdentity: string\n readonly sampleSize: number\n /**\n * Pearson r in [-1, 1]. Higher = reviewer's qualityScore predicts\n * downstream outcomes better. Negative = reviewer is inversely\n * correlated (worse than random). NaN when sampleSize < 2 or all\n * scores are identical (no variance).\n */\n readonly correlationUtility: number\n readonly correlationLift: number\n /** Whether this reviewer meets the calibrated threshold. */\n readonly isCalibrated: boolean\n /** Suggested weight for the multi-reviewer aggregator (0..1). */\n readonly suggestedWeight: number\n /** Reason flag — useful for curator UI tooltips. */\n readonly status:\n | \"calibrated\"\n | \"miscalibrated\"\n | \"insufficient-sample\"\n | \"no-variance\"\n}\n\nexport interface CalibrationOptions {\n /** Minimum sample size to compute calibration. Defaults to 10. */\n readonly minSampleSize?: number\n /** Pearson r threshold above which a reviewer is \"calibrated\". Defaults to 0.4. */\n readonly calibratedThreshold?: number\n}\n\nconst DEFAULT_MIN_SAMPLE = 10\nconst DEFAULT_CALIBRATED_THRESHOLD = 0.4\n\n/**\n * Pearson correlation coefficient on two parallel numeric arrays.\n *\n * r = cov(X, Y) / (σ_X · σ_Y)\n *\n * Returns NaN when:\n * - either array is < 2 elements\n * - either array has zero variance (all values identical)\n *\n * NaN is the explicit \"I can't compute this\" signal — callers\n * decide whether NaN means \"default to neutral weight\" or \"flag for\n * human review\".\n */\nexport function pearsonCorrelation(\n xs: readonly number[],\n ys: readonly number[]\n): number {\n if (xs.length !== ys.length) {\n throw new Error(\n `pearsonCorrelation: array length mismatch (xs=${xs.length}, ys=${ys.length})`\n )\n }\n const n = xs.length\n if (n < 2) return Number.NaN\n\n let sumX = 0\n let sumY = 0\n for (let i = 0; i < n; i++) {\n sumX += xs[i]!\n sumY += ys[i]!\n }\n const meanX = sumX / n\n const meanY = sumY / n\n\n let cov = 0\n let varX = 0\n let varY = 0\n for (let i = 0; i < n; i++) {\n const dx = xs[i]! - meanX\n const dy = ys[i]! - meanY\n cov += dx * dy\n varX += dx * dx\n varY += dy * dy\n }\n if (varX === 0 || varY === 0) return Number.NaN\n return cov / Math.sqrt(varX * varY)\n}\n\n/**\n * Compute a single reviewer's calibration from their track-record\n * window. Returns a ReviewerCalibration summary.\n *\n * Strategy: average the utility-correlation and lift-correlation\n * (when both are available). If only one outcome was recorded\n * across the window (rare), use that one alone.\n */\nexport function computeReviewerCalibration(\n reviewerIdentity: string,\n entries: readonly TrackRecordEntry[],\n opts: CalibrationOptions = {}\n): ReviewerCalibration {\n const minSample = opts.minSampleSize ?? DEFAULT_MIN_SAMPLE\n const threshold = opts.calibratedThreshold ?? DEFAULT_CALIBRATED_THRESHOLD\n\n const utilityRows = entries.filter(\n (e) => typeof e.observedUtility === \"number\"\n )\n const liftRows = entries.filter((e) => typeof e.observedLift === \"number\")\n\n if (\n Math.max(utilityRows.length, liftRows.length) < minSample\n ) {\n return Object.freeze({\n reviewerIdentity,\n sampleSize: Math.max(utilityRows.length, liftRows.length),\n correlationUtility: Number.NaN,\n correlationLift: Number.NaN,\n isCalibrated: false,\n suggestedWeight: 1, // neutral — no penalty for insufficient data\n status: \"insufficient-sample\" as const,\n })\n }\n\n const corrUtil =\n utilityRows.length >= minSample\n ? pearsonCorrelation(\n utilityRows.map((e) => e.qualityScore),\n utilityRows.map((e) => e.observedUtility!)\n )\n : Number.NaN\n const corrLift =\n liftRows.length >= minSample\n ? pearsonCorrelation(\n liftRows.map((e) => e.qualityScore),\n liftRows.map((e) => e.observedLift!)\n )\n : Number.NaN\n\n // Compose a single calibration signal: average of available\n // correlations. NaN handling: if both are NaN, the reviewer's\n // scores have no variance in the window (one-note scoring), so\n // flag and de-weight.\n const available = [corrUtil, corrLift].filter((x) => !Number.isNaN(x))\n if (available.length === 0) {\n return Object.freeze({\n reviewerIdentity,\n sampleSize: entries.length,\n correlationUtility: corrUtil,\n correlationLift: corrLift,\n isCalibrated: false,\n suggestedWeight: 0.3, // de-weight but not zero\n status: \"no-variance\" as const,\n })\n }\n const composite = available.reduce((a, b) => a + b, 0) / available.length\n\n // Weight derivation: linearly map [threshold, 1] → [0.7, 1.0] for\n // calibrated, [-1, threshold] → [0, 0.7] for miscalibrated.\n // Negative correlation is worst-case = weight 0.\n let weight: number\n let isCalibrated: boolean\n if (composite >= threshold) {\n isCalibrated = true\n weight = 0.7 + 0.3 * ((composite - threshold) / (1 - threshold))\n } else {\n isCalibrated = false\n weight = Math.max(\n 0,\n 0.7 * ((composite + 1) / (threshold + 1))\n )\n }\n\n return Object.freeze({\n reviewerIdentity,\n sampleSize: entries.length,\n correlationUtility: corrUtil,\n correlationLift: corrLift,\n isCalibrated,\n suggestedWeight: Math.max(0, Math.min(1, weight)),\n status: isCalibrated ? \"calibrated\" : \"miscalibrated\",\n })\n}\n","/**\n * CorpusValidator — validate a workspace snapshot against the AIP JSON\n * Schemas (the spec source-of-truth at\n * projects/agentproto/agentproto/specs/resources/aip-XX/draft/).\n *\n * The validator is constructed once with an AJV instance pre-loaded\n * with every referenced schema, then run against a `ParsedFile` or a\n * whole `CorpusWorkspaceSnapshot`. Schema loading is delegated to a\n * factory function so the kit doesn't carry the spec JSON inside — the\n * host (cloud adapter or local CLI) supplies the schemas at boot.\n *\n * Why AJV not zod: the AgentProto zod schemas at @agentproto/(aip)/schema\n * are partially generated stubs today (z.any() oneOf branches in\n * knowledge/collection/playbook). AJV against the canonical JSON\n * Schemas is the authoritative path until the zod stubs are\n * regenerated from the JSON Schemas. The corpus kit is the place that\n * exercises both, so this discipline matters.\n */\n\nimport type { ValidateFunction } from \"ajv/dist/2020.js\"\nimport Ajv2020 from \"ajv/dist/2020.js\"\nimport addFormats from \"ajv-formats\"\nimport type {\n CorpusWorkspaceSnapshot,\n FileKind,\n ParsedFile,\n ValidationIssue,\n ValidationResult,\n} from \"../types.js\"\n\n/**\n * Map from FileKind → JSON Schema key. The schema bundle the host\n * supplies must include these keys.\n */\nexport type AipSchemaKey =\n | \"knowledge\" // AIP-10 — entries, sources, workspace (oneOf inside)\n | \"collection\" // AIP-18 — both COLLECTION.md (schema) and ITEM.md (item)\n | \"playbook\" // AIP-12\n | \"operator\" // AIP-9\n | \"workflow\" // AIP-15\n | \"routine\" // AIP-41\n\nexport interface AipSchemaBundle {\n /** Schemas keyed by AIP doctype. Values are JSON Schema documents. */\n readonly schemas: Readonly<Record<AipSchemaKey, unknown>>\n /**\n * External schemas to register with AJV before compilation (so\n * `$ref` cross-document references resolve). The known cross-refs\n * today are AIP-16 IO and AIP-17 RUNNER.\n */\n readonly externals?: ReadonlyArray<unknown>\n}\n\nconst FILE_KIND_TO_SCHEMA: Partial<Record<FileKind, AipSchemaKey>> = {\n \"knowledge-workspace\": \"knowledge\",\n \"knowledge-source\": \"knowledge\",\n \"knowledge-entry\": \"knowledge\",\n \"collection-schema\": \"collection\",\n \"collection-item\": \"collection\",\n \"playbook\": \"playbook\",\n \"operator\": \"operator\",\n \"workflow\": \"workflow\",\n \"routine\": \"routine\",\n}\n\nexport interface CorpusValidatorOptions {\n readonly bundle: AipSchemaBundle\n}\n\nexport class CorpusValidator {\n private readonly validators: Readonly<Record<AipSchemaKey, ValidateFunction>>\n\n constructor(opts: CorpusValidatorOptions) {\n const ajv = new Ajv2020({\n strict: false,\n allErrors: true,\n allowUnionTypes: true,\n })\n addFormats(ajv)\n\n // Register externals first so refs from doctype schemas resolve.\n for (const ext of opts.bundle.externals ?? []) {\n const id = (ext as { $id?: string }).$id\n if (id && !ajv.getSchema(id)) ajv.addSchema(ext as object)\n }\n\n const validators: Record<AipSchemaKey, ValidateFunction> = {} as Record<\n AipSchemaKey,\n ValidateFunction\n >\n for (const key of Object.keys(opts.bundle.schemas) as AipSchemaKey[]) {\n validators[key] = ajv.compile(opts.bundle.schemas[key] as object)\n }\n this.validators = validators\n }\n\n /**\n * Validate a single parsed file. Returns issues + a valid flag.\n * Unknown FileKind (\"unknown\" bucket) is reported as a single info\n * issue — the file exists but doesn't fit AIP conventions.\n */\n validateFile(file: ParsedFile): ValidationResult {\n if (file.kind === \"unknown\") {\n return {\n valid: false,\n issues: [\n {\n path: file.path,\n instancePath: \"/\",\n message:\n \"file location does not match any AIP convention; expected under sources/, entries/, collections/, playbooks/, operators/, workflows/, or routines/\",\n severity: \"info\",\n },\n ],\n }\n }\n\n const schemaKey = FILE_KIND_TO_SCHEMA[file.kind]\n if (!schemaKey) {\n // Defensive — shouldn't happen, but never throw on classification drift.\n return {\n valid: true,\n issues: [],\n }\n }\n\n const validator = this.validators[schemaKey]\n const ok = validator(file.frontmatter)\n if (ok) return { valid: true, issues: [] }\n\n const issues: ValidationIssue[] = (validator.errors ?? []).map((e) => ({\n path: file.path,\n instancePath: e.instancePath || \"/\",\n message: `${e.message}${\n e.params && Object.keys(e.params).length > 0\n ? ` (${JSON.stringify(e.params)})`\n : \"\"\n }`,\n severity: \"error\" as const,\n }))\n return { valid: false, issues }\n }\n\n /**\n * Validate every file in a workspace snapshot. Returns a flat list\n * of issues across all files plus a `valid` flag that's true only\n * if zero error-severity issues exist.\n */\n validateWorkspace(snapshot: CorpusWorkspaceSnapshot): ValidationResult {\n const all: ValidationIssue[] = []\n const buckets: ReadonlyArray<readonly ParsedFile[]> = [\n snapshot.workspace ? [snapshot.workspace] : [],\n snapshot.sources,\n snapshot.entries,\n snapshot.collections,\n snapshot.collectionItems,\n snapshot.playbooks,\n snapshot.operators,\n snapshot.workflows,\n snapshot.routines,\n snapshot.unknown,\n ]\n for (const bucket of buckets) {\n for (const file of bucket) {\n all.push(...this.validateFile(file).issues)\n }\n }\n return {\n valid: all.every((i) => i.severity !== \"error\"),\n issues: Object.freeze(all),\n }\n }\n}\n","/**\n * CorpusLinter — implements the AIP-10 lint kinds declared in\n * KNOWLEDGE.md.lints[]. Five canonical kinds + `custom` delegation\n * hook for hosts that ship their own checks.\n *\n * Lint kinds (per AIP-10 spec):\n * - require-source — entries of kinds X MUST have ≥1 source ref\n * - min-confidence — entries of kinds X SHOULD have confidence ≥ N\n * - max-age — entries of kinds X with updated_at older than N days\n * - broken-ref — sources/links/supersedes references that don't resolve\n * - orphan — entries that no other entry references (incoming = 0)\n * - custom — delegated to host-supplied callbacks keyed by lint id\n *\n * The linter assumes the workspace has already passed schema validation.\n * Running lint on invalid workspace yields garbage. Callers should run\n * the validator first; the writer pipeline enforces this.\n */\n\nimport type {\n CorpusWorkspaceSnapshot,\n LintIssue,\n LintReport,\n ParsedFile,\n} from \"../types.js\"\nimport type { ClockPort } from \"../ports/clock.port.js\"\n\ninterface LintDeclaration {\n readonly id: string\n readonly kind:\n | \"require-source\"\n | \"min-confidence\"\n | \"max-age\"\n | \"broken-ref\"\n | \"orphan\"\n | \"custom\"\n readonly appliesTo: string\n readonly severity: \"error\" | \"warn\" | \"info\"\n readonly params?: Readonly<Record<string, unknown>>\n}\n\nexport type CustomLintRunner = (\n decl: LintDeclaration,\n snapshot: CorpusWorkspaceSnapshot\n) => readonly LintIssue[]\n\nexport interface CorpusLinterOptions {\n readonly clock: ClockPort\n /** Per-id implementations for `kind: custom` lints. */\n readonly customRunners?: Readonly<Record<string, CustomLintRunner>>\n}\n\nexport class CorpusLinter {\n constructor(private readonly opts: CorpusLinterOptions) {}\n\n lint(snapshot: CorpusWorkspaceSnapshot): LintReport {\n const decls = extractLintDeclarations(snapshot)\n const issues: LintIssue[] = []\n\n for (const decl of decls) {\n switch (decl.kind) {\n case \"require-source\":\n issues.push(...this.lintRequireSource(decl, snapshot))\n break\n case \"min-confidence\":\n issues.push(...this.lintMinConfidence(decl, snapshot))\n break\n case \"max-age\":\n issues.push(...this.lintMaxAge(decl, snapshot))\n break\n case \"broken-ref\":\n issues.push(...this.lintBrokenRef(decl, snapshot))\n break\n case \"orphan\":\n issues.push(...this.lintOrphan(decl, snapshot))\n break\n case \"custom\": {\n const runner = this.opts.customRunners?.[decl.id]\n if (runner) issues.push(...runner(decl, snapshot))\n break\n }\n }\n }\n\n return reportFrom(issues)\n }\n\n // ── Lint implementations ────────────────────────────────────────────\n\n private lintRequireSource(\n decl: LintDeclaration,\n snapshot: CorpusWorkspaceSnapshot\n ): LintIssue[] {\n const out: LintIssue[] = []\n for (const entry of snapshot.entries) {\n if (!matchesAppliesTo(entry, decl.appliesTo)) continue\n const sources = (entry.frontmatter.sources ?? []) as readonly unknown[]\n if (sources.length === 0) {\n out.push({\n lintId: decl.id,\n path: entry.path,\n message: `entry has no sources[] (kind=${entry.frontmatter.kind ?? \"?\"})`,\n severity: decl.severity,\n })\n }\n }\n return out\n }\n\n private lintMinConfidence(\n decl: LintDeclaration,\n snapshot: CorpusWorkspaceSnapshot\n ): LintIssue[] {\n const min = numberParam(decl, \"min\", 0.5)\n const out: LintIssue[] = []\n for (const entry of snapshot.entries) {\n if (!matchesAppliesTo(entry, decl.appliesTo)) continue\n const c = entry.frontmatter.confidence\n if (typeof c === \"number\" && c < min) {\n out.push({\n lintId: decl.id,\n path: entry.path,\n message: `confidence ${c} < min ${min}`,\n severity: decl.severity,\n })\n }\n }\n return out\n }\n\n private lintMaxAge(\n decl: LintDeclaration,\n snapshot: CorpusWorkspaceSnapshot\n ): LintIssue[] {\n const days = numberParam(decl, \"days\", 365)\n const cutoffMs = this.opts.clock.nowMs() - days * 86_400_000\n const out: LintIssue[] = []\n for (const entry of snapshot.entries) {\n if (!matchesAppliesTo(entry, decl.appliesTo)) continue\n const updated = entry.frontmatter.updated_at\n if (typeof updated !== \"string\") continue\n const t = Date.parse(updated)\n if (Number.isNaN(t)) continue\n if (t < cutoffMs) {\n out.push({\n lintId: decl.id,\n path: entry.path,\n message: `updated_at ${updated} older than ${days}d`,\n severity: decl.severity,\n })\n }\n }\n return out\n }\n\n private lintBrokenRef(\n decl: LintDeclaration,\n snapshot: CorpusWorkspaceSnapshot\n ): LintIssue[] {\n const sourceIds = new Set<string>()\n for (const s of snapshot.sources) {\n const id = s.frontmatter.id\n if (typeof id === \"string\") sourceIds.add(id)\n }\n const entrySlugs = new Set<string>()\n for (const e of snapshot.entries) {\n const slug = e.frontmatter.slug\n if (typeof slug === \"string\") entrySlugs.add(slug)\n }\n\n const out: LintIssue[] = []\n for (const entry of snapshot.entries) {\n if (!matchesAppliesTo(entry, decl.appliesTo)) continue\n // sources[] — must resolve in source registry\n const sources = (entry.frontmatter.sources ?? []) as readonly unknown[]\n for (const s of sources) {\n if (typeof s === \"string\" && !sourceIds.has(s)) {\n out.push({\n lintId: decl.id,\n path: entry.path,\n message: `unresolved source ref: ${s}`,\n severity: decl.severity,\n })\n }\n }\n // supersedes / contradicts / links — must resolve in entry slug set\n for (const field of [\"supersedes\", \"contradicts\", \"links\"] as const) {\n const refs = (entry.frontmatter[field] ?? []) as readonly unknown[]\n for (const r of refs) {\n if (typeof r === \"string\" && !entrySlugs.has(r)) {\n out.push({\n lintId: decl.id,\n path: entry.path,\n message: `unresolved ${field} ref: ${r}`,\n severity: decl.severity,\n })\n }\n }\n }\n }\n return out\n }\n\n private lintOrphan(\n decl: LintDeclaration,\n snapshot: CorpusWorkspaceSnapshot\n ): LintIssue[] {\n // Build the incoming-reference set across all entries\n const incoming = new Set<string>()\n for (const e of snapshot.entries) {\n for (const field of [\"supersedes\", \"contradicts\", \"links\"] as const) {\n const refs = (e.frontmatter[field] ?? []) as readonly unknown[]\n for (const r of refs) {\n if (typeof r === \"string\") incoming.add(r)\n }\n }\n }\n\n const out: LintIssue[] = []\n for (const entry of snapshot.entries) {\n if (!matchesAppliesTo(entry, decl.appliesTo)) continue\n const slug = entry.frontmatter.slug\n if (typeof slug !== \"string\") continue\n if (!incoming.has(slug)) {\n out.push({\n lintId: decl.id,\n path: entry.path,\n message: `entry has no incoming references (orphan)`,\n severity: decl.severity,\n })\n }\n }\n return out\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────\n\nfunction extractLintDeclarations(\n snapshot: CorpusWorkspaceSnapshot\n): readonly LintDeclaration[] {\n if (!snapshot.workspace) return []\n const raw = (snapshot.workspace.frontmatter.lints ?? []) as readonly unknown[]\n const decls: LintDeclaration[] = []\n for (const r of raw) {\n if (!isLintDeclaration(r)) continue\n decls.push(r)\n }\n return decls\n}\n\nfunction isLintDeclaration(x: unknown): x is LintDeclaration {\n if (typeof x !== \"object\" || x === null) return false\n const o = x as Record<string, unknown>\n return (\n typeof o.id === \"string\" &&\n typeof o.kind === \"string\" &&\n typeof o.appliesTo === \"string\" &&\n typeof o.severity === \"string\"\n )\n}\n\nfunction matchesAppliesTo(entry: ParsedFile, appliesTo: string): boolean {\n if (appliesTo === \"*\") return true\n // Compare the AIP-10 `kind` field (lowercase) against the lint's\n // appliesTo PascalCase entity type. We compare case-insensitively\n // because entities are declared as e.g. \"Principle\" in KNOWLEDGE.md\n // but entries set `kind: principle`.\n const kind = entry.frontmatter.kind\n if (typeof kind !== \"string\") return false\n return appliesTo.toLowerCase() === kind.toLowerCase()\n}\n\nfunction numberParam(\n decl: LintDeclaration,\n key: string,\n fallback: number\n): number {\n const params = decl.params ?? {}\n const v = (params as Record<string, unknown>)[key]\n return typeof v === \"number\" ? v : fallback\n}\n\nfunction reportFrom(issues: LintIssue[]): LintReport {\n let errorCount = 0\n let warnCount = 0\n let infoCount = 0\n for (const i of issues) {\n if (i.severity === \"error\") errorCount++\n else if (i.severity === \"warn\") warnCount++\n else infoCount++\n }\n return {\n issues: Object.freeze([...issues]),\n errorCount,\n warnCount,\n infoCount,\n }\n}\n","/**\n * Candidate state machine.\n *\n * AIP-18 collection COLLECTION.md declares the `statuses[]` array\n * with explicit `transitionsTo`. This module enforces those\n * transitions at the corpus-kit boundary so callers can never\n * silently land an item in an illegal state.\n *\n * The corpus' canonical candidate collection (per the plan) has:\n *\n * discovered → analyzed | rejected\n * analyzed → approved | rejected | needs-work\n * needs-work → analyzed | rejected\n * approved = terminal\n * rejected = terminal\n *\n * This module is pure (no I/O). The lifecycle workflow caller pairs\n * it with the writer + emitter to durably enact each transition.\n */\n\nexport type CandidateStatus =\n | \"discovered\"\n | \"analyzed\"\n | \"needs-work\"\n | \"approved\"\n | \"rejected\"\n\n/**\n * Default transition graph mirroring the corpus-candidate AIP-18\n * collection shape shipped in the marketing preset. Hosts that load a\n * custom collection schema may override via\n * `transitionGraphFromCollection()`.\n */\nexport const DEFAULT_TRANSITIONS: Readonly<\n Record<CandidateStatus, readonly CandidateStatus[]>\n> = Object.freeze({\n discovered: [\"analyzed\", \"rejected\"],\n analyzed: [\"approved\", \"rejected\", \"needs-work\"],\n \"needs-work\": [\"analyzed\", \"rejected\"],\n approved: [],\n rejected: [],\n})\n\nexport interface TransitionCheck {\n readonly allowed: boolean\n readonly reason?: string\n}\n\n/**\n * Check whether a candidate can transition from `from` to `to`.\n */\nexport function canTransition(\n from: CandidateStatus,\n to: CandidateStatus,\n graph: Readonly<\n Record<CandidateStatus, readonly CandidateStatus[]>\n > = DEFAULT_TRANSITIONS\n): TransitionCheck {\n if (from === to) {\n return { allowed: false, reason: \"same-status (no-op)\" }\n }\n const allowedTargets = graph[from] ?? []\n if (allowedTargets.length === 0) {\n return {\n allowed: false,\n reason: `\"${from}\" is terminal — no outgoing transitions`,\n }\n }\n if (!allowedTargets.includes(to)) {\n return {\n allowed: false,\n reason: `\"${from}\" cannot transition to \"${to}\". Allowed: ${allowedTargets.join(\", \")}`,\n }\n }\n return { allowed: true }\n}\n\n/**\n * Build a transition graph from a parsed COLLECTION.md frontmatter.\n * Hosts call this once at boot to align the candidate state machine\n * with whatever collection schema the workspace ships.\n *\n * Falls back to DEFAULT_TRANSITIONS if the frontmatter doesn't carry\n * a recognizable `statuses[]` array — the caller is encouraged to\n * pass the parsed frontmatter directly rather than re-flattening.\n */\nexport function transitionGraphFromCollection(\n fm: Readonly<Record<string, unknown>>\n): Readonly<Record<string, readonly string[]>> {\n const statuses = (fm.statuses ?? []) as readonly unknown[]\n const graph: Record<string, string[]> = {}\n for (const s of statuses) {\n if (typeof s !== \"object\" || s === null) continue\n const o = s as { id?: unknown; transitionsTo?: unknown; terminal?: unknown }\n if (typeof o.id !== \"string\") continue\n if (o.terminal === true) {\n graph[o.id] = []\n continue\n }\n if (Array.isArray(o.transitionsTo)) {\n graph[o.id] = (o.transitionsTo as unknown[]).filter(\n (x): x is string => typeof x === \"string\"\n )\n }\n }\n return Object.keys(graph).length > 0 ? Object.freeze(graph) : DEFAULT_TRANSITIONS\n}\n\nexport class IllegalTransitionError extends Error {\n constructor(\n readonly from: CandidateStatus,\n readonly to: CandidateStatus,\n readonly reason: string\n ) {\n super(\n `IllegalTransitionError: ${from} → ${to} is not allowed (${reason})`\n )\n this.name = \"IllegalTransitionError\"\n }\n}\n\n/**\n * Validate a transition and throw if disallowed. Convenience wrapper\n * around canTransition for callers that want fail-fast semantics.\n */\nexport function assertTransition(\n from: CandidateStatus,\n to: CandidateStatus,\n graph?: Readonly<Record<CandidateStatus, readonly CandidateStatus[]>>\n): void {\n const check = canTransition(from, to, graph)\n if (!check.allowed) {\n throw new IllegalTransitionError(from, to, check.reason ?? \"no reason\")\n }\n}\n","/**\n * Auto-promote gate — evaluates a candidate against\n * `KNOWLEDGE.md.metadata.corpus.autoPromote.requires`.\n *\n * The plan's auto-promote requirements (from the workspace manifest\n * example) typically include:\n *\n * qualityScore: { min: 4.2 }\n * riskScore: { max: 1.5 }\n * hasArchiveHash: true\n * requiredFields: [why_it_works, transferable_pattern, use_when, avoid_when]\n * notRestricted: true\n *\n * This gate returns a structured GateResult with pass/fail + the\n * specific rules that failed, so the caller can either auto-promote\n * (all pass) or route to human review (corpus-review collection)\n * with the failure reasons attached.\n *\n * Pure — no I/O.\n */\n\nimport type { CorpusWorkspaceSnapshot } from \"../types.js\"\n\nexport interface AutoPromoteRequirements {\n readonly qualityScore?: { min?: number; max?: number }\n readonly riskScore?: { min?: number; max?: number }\n readonly hasArchiveHash?: boolean\n readonly requiredFields?: readonly string[]\n readonly notRestricted?: boolean\n}\n\nexport interface AutoPromoteConfig {\n readonly enabled: boolean\n readonly requires?: AutoPromoteRequirements\n}\n\nexport interface CandidateForGate {\n /** Parsed candidate frontmatter (analyzed state) + body. */\n readonly frontmatter: Readonly<Record<string, unknown>>\n readonly body: string\n /** Optional analysis output — fields the analyst produced. */\n readonly analysis?: Readonly<Record<string, unknown>>\n}\n\nexport interface GateFailure {\n readonly rule: string\n readonly message: string\n}\n\nexport interface GateResult {\n readonly passed: boolean\n readonly failures: readonly GateFailure[]\n /** True when the workspace itself has auto-promote disabled. */\n readonly disabled: boolean\n}\n\n/**\n * Read the auto-promote config from a workspace snapshot. Returns\n * a \"disabled\" config if the workspace doesn't declare one — the\n * gate will short-circuit to \"always require human review\".\n */\nexport function extractAutoPromoteConfig(\n snapshot: CorpusWorkspaceSnapshot\n): AutoPromoteConfig {\n const ws = snapshot.workspace\n if (!ws) return { enabled: false }\n const corpus = (ws.frontmatter.metadata as { corpus?: unknown })\n ?.corpus as { autoPromote?: AutoPromoteConfig } | undefined\n if (!corpus?.autoPromote) return { enabled: false }\n return corpus.autoPromote\n}\n\n/**\n * Evaluate a candidate against the workspace's auto-promote config.\n * Returns `passed: true` only when every declared requirement holds.\n */\nexport function evaluateGate(\n candidate: CandidateForGate,\n config: AutoPromoteConfig\n): GateResult {\n if (!config.enabled) {\n return { passed: false, failures: [], disabled: true }\n }\n const requires = config.requires ?? {}\n const failures: GateFailure[] = []\n\n // Look at both candidate-level metadata.corpus.* (for promoted-from-analyzed\n // shape) and the candidate's flat fields (for AIP-18 collection items\n // whose fields live at the top level of frontmatter).\n const flat = candidate.frontmatter\n const corpusMeta =\n (flat.metadata as { corpus?: Record<string, unknown> })?.corpus ?? {}\n // Prefer corpus-namespaced fields when present (analyzed → promoted\n // path), falling back to flat ITEM.md fields (AIP-18 raw shape).\n const get = (key: string): unknown => {\n if (corpusMeta[key] !== undefined) return corpusMeta[key]\n if (flat[key] !== undefined) return flat[key]\n return undefined\n }\n\n // qualityScore\n if (requires.qualityScore) {\n const q = get(\"qualityScore\")\n if (typeof q !== \"number\") {\n failures.push({\n rule: \"qualityScore\",\n message: \"qualityScore is missing (required by autoPromote)\",\n })\n } else {\n if (requires.qualityScore.min !== undefined && q < requires.qualityScore.min) {\n failures.push({\n rule: \"qualityScore\",\n message: `qualityScore ${q} < min ${requires.qualityScore.min}`,\n })\n }\n if (requires.qualityScore.max !== undefined && q > requires.qualityScore.max) {\n failures.push({\n rule: \"qualityScore\",\n message: `qualityScore ${q} > max ${requires.qualityScore.max}`,\n })\n }\n }\n }\n\n // riskScore\n if (requires.riskScore) {\n const r = get(\"riskScore\")\n if (typeof r !== \"number\") {\n failures.push({\n rule: \"riskScore\",\n message: \"riskScore is missing (required by autoPromote)\",\n })\n } else {\n if (requires.riskScore.min !== undefined && r < requires.riskScore.min) {\n failures.push({\n rule: \"riskScore\",\n message: `riskScore ${r} < min ${requires.riskScore.min}`,\n })\n }\n if (requires.riskScore.max !== undefined && r > requires.riskScore.max) {\n failures.push({\n rule: \"riskScore\",\n message: `riskScore ${r} > max ${requires.riskScore.max}`,\n })\n }\n }\n }\n\n // hasArchiveHash — the candidate must point at a source whose\n // content_hash exists. We look at the candidate's `contentHash`\n // field (the AIP-18 ITEM convention) for a quick check.\n if (requires.hasArchiveHash) {\n const h = get(\"contentHash\") ?? get(\"content_hash\")\n if (typeof h !== \"string\" || !/^(sha256|sha512|blake3):/.test(h)) {\n failures.push({\n rule: \"hasArchiveHash\",\n message: \"candidate has no archive-grade content_hash\",\n })\n }\n }\n\n // requiredFields — every named field must be present and non-empty\n // in the analysis output (typically the body of the ITEM.md or the\n // candidate's `analysis` block).\n if (requires.requiredFields && requires.requiredFields.length > 0) {\n const analysis = candidate.analysis ?? {}\n const body = candidate.body\n for (const field of requires.requiredFields) {\n const inAnalysis =\n (analysis as Record<string, unknown>)[field]\n const inBody = body.includes(`## ${humanize(field)}`) ||\n body.includes(`## ${field}`)\n if (\n (typeof inAnalysis !== \"string\" || inAnalysis.trim().length === 0) &&\n !inBody\n ) {\n failures.push({\n rule: \"requiredFields\",\n message: `candidate is missing required field \"${field}\" (not in analysis.${field} nor in body section \"## ${humanize(field)}\")`,\n })\n }\n }\n }\n\n // notRestricted — candidate's metadata.corpus.access.classification\n // must not be \"restricted\" or \"secret\".\n if (requires.notRestricted) {\n const access =\n (corpusMeta as { access?: { classification?: string } }).access\n const cls = access?.classification\n if (cls === \"restricted\" || cls === \"secret\") {\n failures.push({\n rule: \"notRestricted\",\n message: `candidate access.classification is \"${cls}\" — fails notRestricted gate`,\n })\n }\n }\n\n return {\n passed: failures.length === 0,\n failures: Object.freeze(failures),\n disabled: false,\n }\n}\n\n/** snake_case + camelCase → \"Snake case\" / \"Camel case\" for body matching. */\nfunction humanize(field: string): string {\n const spaced = field\n .replace(/_/g, \" \")\n .replace(/([a-z])([A-Z])/g, \"$1 $2\")\n .toLowerCase()\n return spaced.charAt(0).toUpperCase() + spaced.slice(1)\n}\n","/**\n * Promote workflow — turn an analyzed candidate into a published\n * AIP-10 entry. The fan-out the plan describes:\n *\n * 1. Validate the promotion request (gate check, slug uniqueness)\n * 2. Acquire workspace lock (atomicity across the multi-file write)\n * 3. Write the entry file (AIP-10 conformant frontmatter + body)\n * 4. Update _index.md (faceted catalog regen)\n * 5. Sync to backing engine via CorpusIndexer\n * 6. Append corpus.entry.promoted event to _log.md\n * 7. Take the candidate row out of the sidecar (or update the\n * AIP-18 ITEM.md if it was materialized already)\n *\n * Idempotent on candidate.id — re-running promote for the same id\n * reuses the existing entry path rather than duplicating. The\n * workspace lock guards against concurrent promoters.\n *\n * Pure-ish: the workflow itself is logic + orchestration; every I/O\n * effect goes through the injected reader/writer/emitter/indexer.\n */\n\nimport type { CorpusWorkspaceSnapshot } from \"../types.js\"\nimport type { ClockPort } from \"../ports/clock.port.js\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport { CorpusWorkspaceReader } from \"../workspace/reader.js\"\nimport {\n CorpusWorkspaceWriter,\n type MarkdownDoc,\n} from \"../workspace/writer.js\"\nimport { CorpusEventEmitter } from \"../events/emitter.js\"\nimport { CorpusIndexer } from \"../index/indexer.js\"\nimport { evaluateGate, extractAutoPromoteConfig } from \"./gate.js\"\nimport { appendAttestation, makeAttestation } from \"./attestations.js\"\nimport type { IdentityPort } from \"../ports/identity.port.js\"\n\nexport interface PromoteOptions {\n /** Workspace root inside FsPort (typically \"\"). */\n readonly workspacePath: string\n /** Slug of the entry to create (or update, if it already exists). */\n readonly entrySlug: string\n /** AIP-10 entry kind (principle | pattern | …). */\n readonly entryKind: string\n /** Path of the entry within the workspace, e.g. entries/patterns/2026/foo.md */\n readonly entryPath: string\n /** AIP-10 entry frontmatter to publish. */\n readonly frontmatter: Readonly<Record<string, unknown>>\n /** Entry body (markdown after frontmatter). */\n readonly body: string\n /**\n * Optional candidate id to consume from a sidecar. When provided,\n * the workflow removes the row from `collections/<name>/_candidates.yaml`\n * on success (caller specifies the collection via `candidateSidecar`).\n */\n readonly candidateId?: string\n readonly candidateSidecarPath?: string\n /**\n * Bypass the auto-promote gate. Used when a curator manually\n * approves a candidate that failed the gate (corpus-review path).\n * The emitted event still records the bypass.\n */\n readonly bypassGate?: boolean\n}\n\nexport interface PromoteResult {\n readonly entryPath: string\n readonly entryVersionToken: string\n readonly chunkCount: number\n readonly gatePassed: boolean\n readonly bypassed: boolean\n}\n\nexport interface PromoteContext {\n readonly fs: FsPort\n readonly clock: ClockPort\n readonly identity: IdentityPort\n readonly indexer: CorpusIndexer\n}\n\nexport class PromoteRejectedError extends Error {\n constructor(\n readonly entrySlug: string,\n readonly failures: ReadonlyArray<{ rule: string; message: string }>\n ) {\n super(\n `PromoteRejectedError: ${entrySlug} failed auto-promote gate — ${failures\n .map((f) => `[${f.rule}] ${f.message}`)\n .join(\" / \")}`\n )\n this.name = \"PromoteRejectedError\"\n }\n}\n\n/**\n * Workspace-scoped promoter. Construct once per workspace + per\n * actor (identity is captured by the injected IdentityPort).\n */\nexport class CorpusPromoter {\n constructor(private readonly ctx: PromoteContext) {}\n\n async promote(opts: PromoteOptions): Promise<PromoteResult> {\n const reader = new CorpusWorkspaceReader({ fs: this.ctx.fs })\n const writer = new CorpusWorkspaceWriter({ fs: this.ctx.fs })\n const emitter = new CorpusEventEmitter({\n fs: this.ctx.fs,\n clock: this.ctx.clock,\n identity: this.ctx.identity,\n workspaceRoot: opts.workspacePath,\n })\n\n // Acquire workspace transaction lock (multi-file write).\n const lockPath = joinPath(opts.workspacePath, \"_log.md\")\n return await writer.transaction(lockPath, async () => {\n const snapshot = await reader.read(opts.workspacePath)\n\n // Gate check unless explicitly bypassed.\n let gatePassed = false\n let bypassed = false\n if (opts.bypassGate) {\n bypassed = true\n } else {\n const config = extractAutoPromoteConfig(snapshot)\n const result = evaluateGate(\n {\n frontmatter: opts.frontmatter,\n body: opts.body,\n },\n config\n )\n gatePassed = result.passed\n if (!result.passed && !result.disabled) {\n throw new PromoteRejectedError(opts.entrySlug, result.failures)\n }\n // If auto-promote is disabled, treat as bypassed (caller is in\n // charge of routing through corpus-review).\n if (result.disabled) bypassed = true\n }\n\n // Resolve existing entry vs new. Idempotency on candidate.id:\n // if the same slug already exists, we overwrite (re-promotion\n // path); if a different slug at this path exists, that's a bug.\n const existing = snapshot.entries.find(\n (e) => e.frontmatter.slug === opts.entrySlug\n )\n const targetPath = existing?.path ?? opts.entryPath\n const expectedToken = existing?.versionToken ?? null\n\n // Append a `promoted` attestation before writing. The chain is\n // append-only — readers get the full history of who promoted\n // when, what gate state, whether bypassed.\n const identity = await this.ctx.identity.resolve()\n const attestedFm = appendAttestation(\n opts.frontmatter,\n makeAttestation({\n kind: \"promoted\",\n identity: identity.principal,\n at: this.ctx.clock.now().toISOString(),\n note: bypassed\n ? `bypassed=true${gatePassed ? \"\" : \" (gate not consulted)\"}`\n : `gatePassed=${gatePassed}`,\n })\n )\n\n // Write entry atomically (CAS for re-promotion).\n const doc: MarkdownDoc = {\n frontmatter: attestedFm,\n body: opts.body,\n }\n const entryAbsPath = joinPath(opts.workspacePath, targetPath)\n const entryVersionToken = await writer.writeMarkdown(\n entryAbsPath,\n doc,\n expectedToken\n )\n\n // Re-snapshot so the indexer sees the freshly-written entry.\n const freshSnapshot = await reader.read(opts.workspacePath)\n const indexResult = await this.ctx.indexer.syncEntry(\n freshSnapshot,\n opts.entrySlug\n )\n\n // Regenerate _index.md (host-maintained faceted catalog).\n await regenIndexFile({\n fs: this.ctx.fs,\n workspacePath: opts.workspacePath,\n snapshot: freshSnapshot,\n clock: this.ctx.clock,\n })\n\n // Consume the sidecar row, if any.\n if (opts.candidateId && opts.candidateSidecarPath) {\n const { CandidatesSidecar } = await import(\"../workspace/sidecar.js\")\n const sidecar = new CandidatesSidecar({\n fs: this.ctx.fs,\n path: joinPath(opts.workspacePath, opts.candidateSidecarPath),\n })\n // Tolerate already-removed rows (re-promotion path).\n try {\n await sidecar.take(opts.candidateId)\n } catch {\n // not-found means it was already taken\n }\n }\n\n // Append the audit event.\n await emitter.emit(\"corpus.entry.promoted\", {\n slug: opts.entrySlug,\n kind: opts.entryKind,\n entryPath: targetPath,\n candidateId: opts.candidateId,\n bypassed,\n gatePassed,\n chunkCount: indexResult.chunkCount,\n })\n\n return {\n entryPath: targetPath,\n entryVersionToken,\n chunkCount: indexResult.chunkCount,\n gatePassed,\n bypassed,\n }\n })\n }\n}\n\n// ── _index.md regeneration ─────────────────────────────────────────\n\ninterface RegenInput {\n readonly fs: FsPort\n readonly workspacePath: string\n readonly snapshot: CorpusWorkspaceSnapshot\n readonly clock: ClockPort\n}\n\n/**\n * Generate a minimal faceted catalog: entries grouped by kind, with\n * quality + recency hints. Richer regen (additional facets, retrieval\n * boost panel) can layer on later; this version is enough to prove\n * the regen runs on every promotion.\n */\nasync function regenIndexFile(input: RegenInput): Promise<void> {\n const lines: string[] = []\n lines.push(\"# Corpus index\")\n lines.push(\"\")\n lines.push(\n `Generated ${input.clock.now().toISOString()} — ${input.snapshot.entries.length} entries.`\n )\n lines.push(\"\")\n\n // Group entries by kind for the at-a-glance facet.\n type Entry = (typeof input.snapshot.entries)[number]\n const byKind = new Map<string, Entry[]>()\n for (const entry of input.snapshot.entries) {\n const k = String(entry.frontmatter.kind ?? \"unknown\")\n const bucket = byKind.get(k) ?? []\n bucket.push(entry)\n byKind.set(k, bucket)\n }\n\n for (const [kind, entries] of [...byKind].sort(([a], [b]) =>\n a.localeCompare(b)\n )) {\n lines.push(`## ${kind} (${entries.length})`)\n lines.push(\"\")\n for (const e of entries.sort((a: Entry, b: Entry) =>\n String(a.frontmatter.slug).localeCompare(String(b.frontmatter.slug))\n )) {\n const slug = e.frontmatter.slug\n const title = e.frontmatter.title ?? slug\n const corpus = (e.frontmatter.metadata as { corpus?: { qualityScore?: number; status?: string } })\n ?.corpus\n const q = corpus?.qualityScore\n const s = corpus?.status ?? \"active\"\n const meta: string[] = []\n if (s !== \"active\") meta.push(`status=${s}`)\n if (typeof q === \"number\") meta.push(`q=${q.toFixed(1)}`)\n const suffix = meta.length > 0 ? ` _(${meta.join(\", \")})_` : \"\"\n lines.push(`- [[${slug}]] — ${title}${suffix}`)\n }\n lines.push(\"\")\n }\n\n const content = lines.join(\"\\n\")\n await input.fs.writeFile(\n joinPath(input.workspacePath, \"_index.md\"),\n content\n )\n}\n\nfunction joinPath(a: string, b: string): string {\n if (!a) return b\n return a.endsWith(\"/\") ? a + b : a + \"/\" + b\n}\n","/**\n * Chunking strategy for corpus entries.\n *\n * Split an entry body into chunks that fit the backing engine's\n * `maxChunkBytes` capability. Naive but predictable — overlap window\n * keeps semantic continuity across boundaries; smarter sentence /\n * semantic chunking can land later behind the same call.\n *\n * Matches the qdrant adapter's CHUNK_TARGET_CHARS / CHUNK_OVERLAP_CHARS\n * numerology so corpus + qdrant agree on chunk shape end-to-end.\n */\n\nexport interface ChunkerOptions {\n /** Soft target per chunk (characters). Default 1500 ≈ 375 tokens. */\n readonly targetChars?: number\n /** Overlap window between adjacent chunks. Default 150. */\n readonly overlapChars?: number\n /** Hard ceiling — backing engine's maxChunkBytes (Buffer-byte). */\n readonly maxBytes?: number\n}\n\nconst DEFAULT_TARGET = 1500\nconst DEFAULT_OVERLAP = 150\nconst DEFAULT_MAX_BYTES = 64 * 1024\n\nexport function chunkText(text: string, opts: ChunkerOptions = {}): string[] {\n const target = opts.targetChars ?? DEFAULT_TARGET\n const overlap = opts.overlapChars ?? DEFAULT_OVERLAP\n const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES\n if (overlap >= target) {\n throw new Error(\"chunkText: overlap must be < target\")\n }\n\n const trimmed = text.trim()\n if (trimmed.length === 0) return []\n if (byteLength(trimmed) <= maxBytes && trimmed.length <= target) {\n return [trimmed]\n }\n\n const chunks: string[] = []\n let cursor = 0\n while (cursor < trimmed.length) {\n let end = Math.min(cursor + target, trimmed.length)\n let slice = trimmed.slice(cursor, end)\n // If the slice exceeds the hard byte ceiling, bisect by char\n // until it fits. Pessimistic but correct for multibyte runs.\n while (byteLength(slice) > maxBytes && slice.length > 1) {\n end = cursor + Math.floor((end - cursor) * 0.9)\n slice = trimmed.slice(cursor, end)\n }\n chunks.push(slice)\n if (end >= trimmed.length) break\n cursor = end - overlap\n if (cursor < 0) cursor = 0\n }\n return chunks\n}\n\nfunction byteLength(s: string): number {\n // TextEncoder is built-in across Node ≥18, Bun, browsers.\n return new TextEncoder().encode(s).length\n}\n","/**\n * CorpusIndexer — coordinator that ships active entries into the\n * backing engine via WriterPort.\n *\n * The kit doesn't know about IKnowledgeProvider — agstudio's\n * CorpusInternalWriter satisfies WriterPort and bridges to the\n * actual engine (qdrant / gbrain). Local topology supplies its own\n * WriterPort (e.g. dockered qdrant).\n *\n * Three public methods:\n * - reindex(snapshot) full sync: pushes every active entry\n * - syncEntry(snapshot, slug) delta: re-push a single entry\n * - removeEntry(slug) delta: drop a deprecated/archived entry\n *\n * Policy: only entries with `metadata.corpus.status === \"active\"`\n * (or unset, treated as active) are shipped. Deprecated/archived\n * entries are removed from the backing engine.\n */\n\nimport { chunkText, type ChunkerOptions } from \"./chunker.js\"\nimport type { WriterPort } from \"../ports/writer.port.js\"\nimport type {\n CorpusWorkspaceSnapshot,\n ParsedFile,\n} from \"../types.js\"\n\nexport interface CorpusIndexerOptions {\n readonly writer: WriterPort\n /** Optional chunker tuning. Defaults match the backing engine's caps. */\n readonly chunker?: ChunkerOptions\n}\n\nexport interface IndexReport {\n readonly pushed: number // entries shipped\n readonly removed: number // entries dropped\n readonly skipped: number // entries skipped (non-active)\n readonly chunkCount: number // total chunks pushed across entries\n}\n\nexport class CorpusIndexer {\n constructor(private readonly opts: CorpusIndexerOptions) {}\n\n /**\n * Re-sync every active entry. Used at boot (cold-install) and by\n * the admin `corpus reindex` command for drift recovery.\n */\n async reindex(snapshot: CorpusWorkspaceSnapshot): Promise<IndexReport> {\n let pushed = 0\n let removed = 0\n let skipped = 0\n let chunkCount = 0\n\n for (const entry of snapshot.entries) {\n const status = readStatus(entry)\n if (status === \"active\") {\n const n = await this.pushEntry(entry)\n pushed++\n chunkCount += n\n } else if (status === \"deprecated\" || status === \"archived\") {\n const slug = entry.frontmatter.slug\n if (typeof slug === \"string\") {\n const r = await this.opts.writer.removeEntry(slug)\n removed += r.removed > 0 ? 1 : 0\n }\n } else {\n skipped++\n }\n }\n return { pushed, removed, skipped, chunkCount }\n }\n\n /**\n * Re-sync a single entry by slug. The lifecycle's `promote`\n * workflow calls this immediately after writing the entry file.\n */\n async syncEntry(\n snapshot: CorpusWorkspaceSnapshot,\n slug: string\n ): Promise<{ chunkCount: number }> {\n const entry = snapshot.entries.find((e) => e.frontmatter.slug === slug)\n if (!entry) {\n // Missing slug = deprecated/erased; drop from backing engine.\n await this.opts.writer.removeEntry(slug)\n return { chunkCount: 0 }\n }\n const status = readStatus(entry)\n if (status !== \"active\") {\n await this.opts.writer.removeEntry(slug)\n return { chunkCount: 0 }\n }\n // Always remove-then-push for syncEntry — backing engine doesn't\n // have an \"upsert by entrySlug\" op. This keeps the chunk set\n // consistent with the current entry body.\n await this.opts.writer.removeEntry(slug)\n const n = await this.pushEntry(entry)\n return { chunkCount: n }\n }\n\n /** Drop one entry from the backing engine (deprecation, GDPR erase). */\n async removeEntry(slug: string): Promise<void> {\n await this.opts.writer.removeEntry(slug)\n }\n\n // ── Internal ─────────────────────────────────────────────────────\n\n private async pushEntry(entry: ParsedFile): Promise<number> {\n const slug = entry.frontmatter.slug\n if (typeof slug !== \"string\") return 0\n const chunks = chunkText(entry.body, this.opts.chunker).map((text) => ({\n text,\n }))\n const corpus = readCorpusMetadata(entry)\n await this.opts.writer.pushChunks({\n entrySlug: slug,\n entryPath: entry.path,\n title: typeof entry.frontmatter.title === \"string\"\n ? entry.frontmatter.title\n : undefined,\n chunks,\n // Forward the corpus-namespaced metadata so the engine adapter\n // can hydrate hits without re-reading the file.\n entryMetadata: {\n kind: entry.frontmatter.kind,\n sources: entry.frontmatter.sources,\n confidence: entry.frontmatter.confidence,\n tags: entry.frontmatter.tags,\n ...corpus,\n },\n })\n return chunks.length\n }\n}\n\nfunction readStatus(entry: ParsedFile): string {\n const corpus = (entry.frontmatter.metadata as { corpus?: { status?: unknown } })\n ?.corpus\n const s = corpus?.status\n return typeof s === \"string\" ? s : \"active\"\n}\n\nfunction readCorpusMetadata(\n entry: ParsedFile\n): Readonly<Record<string, unknown>> {\n const corpus = (entry.frontmatter.metadata as { corpus?: unknown })?.corpus\n return (corpus as Readonly<Record<string, unknown>>) ?? {}\n}\n","/**\n * Attachment-binding axes — the dimensions a selector can target.\n *\n * An axis is a named dimension of the consuming subject (an operator,\n * usually): its identity slug, the AIP-47 role it fulfils, the\n * host-assigned position label, the capabilities it carries. Assets\n * (playbook overlays, knowledge packs, skills) declare a `Selector`\n * over these axes; the host supplies `Dimensions` for the subject and\n * one matcher evaluates `selector ⊨ dimensions`.\n *\n * This package ships only the AIP-concept axes. Hosts register extra\n * axes (org units, regions, compliance regimes, …) on their own\n * registry — nothing here knows about any host's org model.\n */\n\nimport { createRegistry, type Registry } from \"@agentproto/registry\"\n\nexport interface AxisDefinition {\n /** Axis id — the key used in `selector:` frontmatter and in Dimensions. */\n readonly id: string\n /** AIP that owns the axis's value vocabulary, when one does. */\n readonly aip?: number\n /** Doc line for catalog/UI surfaces. */\n readonly description?: string\n /**\n * Authoring-time ref check. Returns an error message, or null when\n * the ref is acceptable. Hosts inject catalog-aware validators here\n * (e.g. \"role ref must be a known catalog slug\").\n */\n readonly validateRef?: (ref: string) => string | null\n /**\n * Canonicalize a ref before matching — absorbs the AIP-12 ref shapes\n * (`operator/<slug>`, `ws://operators/<slug>`, globs → `\"*\"`).\n */\n readonly normalizeRef?: (ref: string) => string\n}\n\n/** Matches any present value on the axis. */\nexport const ANY_REF = \"*\"\n\n/**\n * Ref-shape normalizer for an axis addressed as `<singular>/<slug>` or\n * `ws://<plural>/<slug>` — the shapes AIP-12 targets historically used.\n * Globs (`<singular>/*`, `ws://<plural>/*`) collapse to `ANY_REF`.\n */\nexport function prefixedRefNormalizer(\n singular: string,\n plural: string\n): (ref: string) => string {\n const bare = `${singular}/`\n const ws = `ws://${plural}/`\n return (ref) => {\n const stripped = ref.startsWith(bare)\n ? ref.slice(bare.length)\n : ref.startsWith(ws)\n ? ref.slice(ws.length)\n : ref\n return stripped === \"*\" ? ANY_REF : stripped\n }\n}\n\nconst SLUG_RE = /^[a-z][a-z0-9-]*[a-z0-9]$/\n\nfunction slugValidator(ref: string): string | null {\n if (ref === ANY_REF) return null\n return SLUG_RE.test(ref)\n ? null\n : `not a slug (lowercase, digits, dashes): \"${ref}\"`\n}\n\n/** The operator's own slug — AIP-9 identity. */\nexport const identityAxis: AxisDefinition = {\n id: \"identity\",\n aip: 9,\n description: \"The subject's own slug — targets one specific operator.\",\n normalizeRef: prefixedRefNormalizer(\"operator\", \"operators\"),\n validateRef: slugValidator,\n}\n\n/** The AIP-47 catalog role (job) the operator fulfils. */\nexport const roleAxis: AxisDefinition = {\n id: \"role\",\n aip: 47,\n description:\n \"The AIP-47 catalog role (job) the subject fulfils — targets every operator in the role.\",\n normalizeRef: prefixedRefNormalizer(\"role\", \"roles\"),\n validateRef: slugValidator,\n}\n\n/** The host-assigned, user-settable seat label (slugified). */\nexport const positionAxis: AxisDefinition = {\n id: \"position\",\n aip: 6,\n description:\n \"The host-assigned seat label (slugified) — targets the one operator holding the seat. See AIP-47 §Role vs Position vs Access role.\",\n normalizeRef: prefixedRefNormalizer(\"position\", \"positions\"),\n validateRef: slugValidator,\n}\n\n/** A capability slug the subject carries. */\nexport const capabilityAxis: AxisDefinition = {\n id: \"capability\",\n aip: 9,\n description: \"A capability slug the subject carries.\",\n normalizeRef: prefixedRefNormalizer(\"capability\", \"capabilities\"),\n validateRef: slugValidator,\n}\n\nexport const WELL_KNOWN_AXES: readonly AxisDefinition[] = Object.freeze([\n identityAxis,\n roleAxis,\n positionAxis,\n capabilityAxis,\n])\n\nexport type AxisRegistry = Registry<AxisDefinition>\n\n/**\n * Axis registry seeded with the well-known AIP axes. Hosts pass their\n * extra axes; ids must not collide with the well-known set.\n */\nexport function createAxisRegistry(\n extra: readonly AxisDefinition[] = []\n): AxisRegistry {\n const registry = createRegistry<AxisDefinition>({\n family: \"binding-axis\",\n keyBy: (axis) => axis.id,\n })\n for (const axis of WELL_KNOWN_AXES) registry.register(axis)\n for (const axis of extra) registry.register(axis)\n return registry\n}\n","/**\n * Selector ⊨ Dimensions — the one matcher every attachment kind uses.\n *\n * A `Selector` is a small boolean expression over axis terms; the host\n * supplies the subject's `Dimensions` (axis → value(s)) and the matcher\n * decides whether the asset attaches. Scope (org / guild / workspace\n * reach) is NOT expressed here — reach is decided by which corpus\n * workspaces the host aggregates before matching ever runs.\n */\n\nimport { ANY_REF, type AxisDefinition, type AxisRegistry } from \"./axes.js\"\n\nexport interface SelectorTerm {\n readonly axis: string\n /** Refs the term accepts — OR within the list. `\"*\"` = any present value. */\n readonly anyOf: readonly string[]\n}\n\nexport interface Selector {\n /** Every term must match (AND). */\n readonly allOf?: readonly SelectorTerm[]\n /** At least one term must match (OR). */\n readonly anyOf?: readonly SelectorTerm[]\n}\n\n/**\n * The subject's axis values. A missing key means the subject has no\n * value on that axis — terms against it fail (never match-all).\n */\nexport type Dimensions = Readonly<\n Record<string, string | readonly string[] | undefined>\n>\n\nexport interface MatchOptions {\n /** Axis registry supplying per-axis `normalizeRef`. Optional — without it refs match verbatim. */\n readonly axes?: AxisRegistry\n}\n\nexport const EMPTY_SELECTOR: Selector = Object.freeze({})\n\n/** True when the selector has no terms at all. */\nexport function isEmptySelector(selector: Selector): boolean {\n return !selector.allOf?.length && !selector.anyOf?.length\n}\n\n/**\n * Evaluate `selector ⊨ dimensions`.\n *\n * - An EMPTY selector matches NOTHING — an asset that wants everyone\n * in scope says so with an explicit `{ axis, anyOf: [\"*\"] }` term.\n * (Parity with the legacy empty-`targets` behavior.)\n * - A term fails when the dimension is absent.\n * - A term matches when its normalized refs intersect the dimension's\n * values, or when it carries `\"*\"` and the dimension is present.\n */\nexport function matchesSelector(\n selector: Selector,\n dimensions: Dimensions,\n options: MatchOptions = {}\n): boolean {\n if (isEmptySelector(selector)) return false\n const { allOf, anyOf } = selector\n if (allOf?.length) {\n for (const term of allOf) {\n if (!termMatches(term, dimensions, options)) return false\n }\n }\n if (anyOf?.length) {\n return anyOf.some((term) => termMatches(term, dimensions, options))\n }\n return true\n}\n\nfunction termMatches(\n term: SelectorTerm,\n dimensions: Dimensions,\n options: MatchOptions\n): boolean {\n const raw = dimensions[term.axis]\n if (raw === undefined) return false\n const values = typeof raw === \"string\" ? [raw] : raw\n if (values.length === 0) return false\n const axis = options.axes?.get(term.axis)\n for (const ref of term.anyOf) {\n const normalized = normalizeRef(ref, axis)\n if (normalized === ANY_REF) return true\n if (values.includes(normalized)) return true\n }\n return false\n}\n\nfunction normalizeRef(ref: string, axis: AxisDefinition | undefined): string {\n return axis?.normalizeRef ? axis.normalizeRef(ref) : ref\n}\n","/**\n * `selector:` frontmatter → Selector.\n *\n * Authoring shape (AIP-12 §selector):\n *\n * selector:\n * role: sales-rep # one ref\n * capability: [demo, forecast] # OR within the list\n *\n * Keys are axis ids; multiple keys AND together. The advanced\n * `allOf:`/`anyOf:` long form is accepted verbatim for selectors that\n * need OR across axes.\n *\n * Parsing never throws — malformed input returns null and the caller\n * falls back to the legacy `targets` compile. A selector that silently\n * dropped a malformed term could attach an overlay to the wrong\n * operators; null keeps the file on its legacy binding instead.\n */\n\nimport type { Selector, SelectorTerm } from \"./selector.js\"\n\nexport function parseSelectorFrontmatter(raw: unknown): Selector | null {\n if (!isPlainObject(raw)) return null\n\n // Long form: explicit allOf / anyOf term lists.\n if (\"allOf\" in raw || \"anyOf\" in raw) {\n const allOf = readTermList(raw.allOf)\n const anyOf = readTermList(raw.anyOf)\n if (allOf === null || anyOf === null) return null\n if (!allOf.length && !anyOf.length) return null\n return Object.freeze({\n ...(allOf.length ? { allOf } : {}),\n ...(anyOf.length ? { anyOf } : {}),\n })\n }\n\n // Short form: axis → ref | ref[].\n const allOf: SelectorTerm[] = []\n for (const [axis, value] of Object.entries(raw)) {\n const refs = readRefs(value)\n if (refs === null) return null\n allOf.push(Object.freeze({ axis, anyOf: refs }))\n }\n if (!allOf.length) return null\n return Object.freeze({ allOf: Object.freeze(allOf) })\n}\n\nfunction readTermList(raw: unknown): readonly SelectorTerm[] | null {\n if (raw === undefined) return []\n if (!Array.isArray(raw)) return null\n const out: SelectorTerm[] = []\n for (const entry of raw as readonly unknown[]) {\n if (!isPlainObject(entry)) return null\n const axis = entry.axis\n if (typeof axis !== \"string\" || !axis.length) return null\n const refs = readRefs(entry.anyOf)\n if (refs === null || !refs.length) return null\n out.push(Object.freeze({ axis, anyOf: refs }))\n }\n return Object.freeze(out)\n}\n\nfunction readRefs(value: unknown): readonly string[] | null {\n if (typeof value === \"string\") {\n return value.length ? Object.freeze([value]) : null\n }\n if (Array.isArray(value)) {\n const refs = value as readonly unknown[]\n if (!refs.length) return null\n if (!refs.every((r): r is string => typeof r === \"string\" && r.length > 0))\n return null\n return Object.freeze([...refs])\n }\n return null\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v)\n}\n","/**\n * Legacy `targets[]` / `binds_operator` → Selector compile.\n *\n * Permanent, not transitional: PLAYBOOK.md files authored before\n * `selector:` live in real corpus workspaces and keep working forever.\n *\n * The legacy format is axis-AMBIGUOUS: a `kind: \"operator\"` ref (and\n * `binds_operator`) historically held either an operator slug OR a\n * role slug — the old matcher tried both. The compile preserves that\n * exactly by putting each such ref in BOTH the identity and the role\n * bucket of an `anyOf` selector. `kind: \"role\" | \"skill\" | \"runtime\"`\n * refs compile to their own axes (a host that supplies no `skill`\n * dimension keeps today's no-match behavior for skill targets).\n */\n\nimport {\n capabilityAxis,\n identityAxis,\n positionAxis,\n roleAxis,\n prefixedRefNormalizer,\n} from \"./axes.js\"\nimport type { Selector, SelectorTerm } from \"./selector.js\"\n\ninterface LegacyTarget {\n readonly kind: string\n readonly ref: string\n}\n\nconst normalizeOperatorRef = identityAxis.normalizeRef!\nconst normalizeRoleRef = roleAxis.normalizeRef!\nconst normalizeSkillRef = prefixedRefNormalizer(\"skill\", \"skills\")\nconst normalizeRuntimeRef = prefixedRefNormalizer(\"runtime\", \"runtimes\")\n\nexport function compileLegacyPlaybookBinding(\n targets: readonly LegacyTarget[],\n bindsOperator?: string\n): Selector {\n const identity = new Set<string>()\n const role = new Set<string>()\n const skill = new Set<string>()\n const runtime = new Set<string>()\n\n if (bindsOperator) {\n identity.add(normalizeOperatorRef(bindsOperator))\n role.add(normalizeRoleRef(bindsOperator))\n }\n for (const target of targets) {\n switch (target.kind) {\n case \"operator\":\n identity.add(normalizeOperatorRef(target.ref))\n role.add(normalizeRoleRef(target.ref))\n break\n case \"role\":\n role.add(normalizeRoleRef(target.ref))\n break\n case \"skill\":\n skill.add(normalizeSkillRef(target.ref))\n break\n case \"runtime\":\n runtime.add(normalizeRuntimeRef(target.ref))\n break\n default:\n break\n }\n }\n\n const anyOf: SelectorTerm[] = []\n pushTerm(anyOf, identityAxis.id, identity)\n pushTerm(anyOf, roleAxis.id, role)\n pushTerm(anyOf, \"skill\", skill)\n pushTerm(anyOf, \"runtime\", runtime)\n if (!anyOf.length) return Object.freeze({})\n return Object.freeze({ anyOf: Object.freeze(anyOf) })\n}\n\nfunction pushTerm(out: SelectorTerm[], axis: string, refs: Set<string>): void {\n if (!refs.size) return\n out.push(Object.freeze({ axis, anyOf: Object.freeze([...refs]) }))\n}\n\n// Re-exported so hosts assembling Dimensions use the same axis ids the\n// compile emits.\nexport { identityAxis, roleAxis, positionAxis, capabilityAxis }\n","/**\n * Attachment declarations — \"this asset attaches to subjects matching\n * this selector\", evaluated by the one matcher.\n *\n * A host keeps a flat list of declarations (a knowledge pack attaches to\n * a set of roles, a skill attaches to one position, …) and asks which\n * ones a given subject's `Dimensions` satisfy. This replaces the older\n * shape where bindings were grafted onto the subject (e.g. mutating a\n * role handle at boot): the declaration is data, matching is a pure\n * function, nothing is mutated.\n *\n * Asset-kind-agnostic and vendor-neutral — the `kind` is the host's\n * (`\"pack\" | \"skill\" | …`); the selector axes are AIP concepts. `band` /\n * `mode` are optional layering hints a host's mount step may honor; the\n * matcher itself ignores them.\n */\n\nimport type { LayerMode } from \"../stack/types.js\"\nimport { matchesSelector, type Dimensions, type Selector } from \"./selector.js\"\nimport type { AxisRegistry } from \"./axes.js\"\n\n/** What a declaration attaches — an opaque, host-typed ref under a kind. */\nexport interface AttachmentAsset<Kind extends string = string> {\n readonly kind: Kind\n readonly ref: string\n}\n\n/** An asset + the selector deciding which subjects it attaches to. */\nexport interface AttachmentDeclaration<Kind extends string = string> {\n readonly asset: AttachmentAsset<Kind>\n /** Subjects whose `Dimensions` satisfy this attach the asset. */\n readonly selector: Selector\n /** Optional precedence hint for the host's mount step (see AIP-10 bands). */\n readonly band?: number\n /** Optional composition hint — `lens` vs `constraint`. */\n readonly mode?: LayerMode\n}\n\nexport interface MatchAttachmentsOptions {\n /** Axis registry supplying per-axis `normalizeRef` for the matcher. */\n readonly axes?: AxisRegistry\n}\n\n/**\n * The subset of `declarations` whose selector matches `dimensions`. Order\n * is preserved; de-duplication of resulting refs is the caller's call\n * (the same asset may attach via several declarations).\n */\nexport function matchAttachments<Kind extends string>(\n declarations: readonly AttachmentDeclaration<Kind>[],\n dimensions: Dimensions,\n options: MatchAttachmentsOptions = {}\n): AttachmentDeclaration<Kind>[] {\n return declarations.filter((d) =>\n matchesSelector(d.selector, dimensions, { axes: options.axes })\n )\n}\n\n/**\n * Matched asset refs for one kind, de-duplicated, first-seen order — the\n * flat shape most mount steps want.\n */\nexport function matchAttachmentRefs<Kind extends string>(\n declarations: readonly AttachmentDeclaration<Kind>[],\n kind: Kind,\n dimensions: Dimensions,\n options: MatchAttachmentsOptions = {}\n): string[] {\n const seen = new Set<string>()\n for (const d of matchAttachments(declarations, dimensions, options)) {\n if (d.asset.kind === kind) seen.add(d.asset.ref)\n }\n return [...seen]\n}\n","/**\n * PlaybookRegistry — load + index every AIP-12 PLAYBOOK.md in the\n * workspace's `playbooks/` directory.\n *\n * The registry is a thin read layer over a `CorpusWorkspaceSnapshot`:\n * - parses raw frontmatter into the typed `Playbook` shape,\n * - exposes O(1) lookups by slug,\n * - filters by status / kind / target operator on listBy().\n *\n * No FsPort dependency — the snapshot already carries the parsed\n * files. The lifecycle layer is the one that writes; this registry\n * is pure read.\n */\n\nimport {\n compileLegacyPlaybookBinding,\n createAxisRegistry,\n matchesSelector,\n parseSelectorFrontmatter,\n} from \"../binding/index.js\"\nimport type { CorpusWorkspaceSnapshot, ParsedFile } from \"../types.js\"\nimport type {\n Playbook,\n PlaybookCorpusMeta,\n PlaybookKind,\n PlaybookQuery,\n PlaybookStatus,\n PlaybookTarget,\n} from \"./types.js\"\n\nexport interface PlaybookRegistryOptions {\n readonly snapshot: CorpusWorkspaceSnapshot\n}\n\nexport class PlaybookRegistry {\n private readonly bySlug: ReadonlyMap<string, Playbook>\n private readonly all: readonly Playbook[]\n\n constructor(opts: PlaybookRegistryOptions) {\n const parsed: Playbook[] = []\n for (const file of opts.snapshot.playbooks) {\n const playbook = parsePlaybook(file)\n if (playbook) parsed.push(playbook)\n }\n parsed.sort((a, b) => b.priority - a.priority)\n this.all = Object.freeze(parsed)\n const map = new Map<string, Playbook>()\n for (const p of parsed) map.set(p.slug, p)\n this.bySlug = map\n }\n\n list(): readonly Playbook[] {\n return this.all\n }\n\n bySlugOrNull(slug: string): Playbook | null {\n return this.bySlug.get(slug) ?? null\n }\n\n listBy(query: PlaybookQuery = {}): readonly Playbook[] {\n return this.all.filter((p) => matches(p, query))\n }\n}\n\n// ── Parsing ─────────────────────────────────────────────────────────\n\nfunction parsePlaybook(file: ParsedFile): Playbook | null {\n const fm = file.frontmatter\n const slug = typeof fm.slug === \"string\" ? fm.slug : null\n const title = typeof fm.title === \"string\" ? fm.title : null\n if (!slug || !title) return null\n\n const status = readStatus(fm)\n const kind: PlaybookKind = fm.kind === \"block-replacement\"\n ? \"block-replacement\"\n : \"overlay\"\n const priority = typeof fm.priority === \"number\" ? fm.priority : 100\n const bindsOperator =\n typeof fm.binds_operator === \"string\" ? fm.binds_operator : undefined\n const targets = readTargets(fm)\n const supersedes = readStringArray(fm.supersedes)\n const corpus = readCorpusMeta(fm)\n // Explicit `selector:` wins; malformed or absent falls back to the\n // legacy compile so an old or broken file keeps its targets binding.\n const explicitSelector = parseSelectorFrontmatter(fm.selector)\n const selector =\n explicitSelector ?? compileLegacyPlaybookBinding(targets, bindsOperator)\n const selectorSource = explicitSelector ? \"selector\" : \"legacy\"\n\n return Object.freeze({\n path: file.path,\n slug,\n title,\n status,\n kind,\n priority,\n targets,\n bindsOperator,\n selector,\n selectorSource,\n supersedes,\n body: file.body,\n corpus,\n versionToken: file.versionToken,\n file,\n })\n}\n\nfunction readStatus(fm: Readonly<Record<string, unknown>>): PlaybookStatus {\n const s = fm.status\n if (s === \"active\" || s === \"shadow\" || s === \"archived\") return s\n return \"shadow\"\n}\n\nfunction readTargets(\n fm: Readonly<Record<string, unknown>>\n): readonly PlaybookTarget[] {\n const raw = fm.targets\n if (!Array.isArray(raw)) return []\n const out: PlaybookTarget[] = []\n for (const t of raw as readonly unknown[]) {\n if (typeof t !== \"object\" || t === null) continue\n const o = t as { kind?: unknown; ref?: unknown }\n if (\n typeof o.ref !== \"string\" ||\n (o.kind !== \"operator\" &&\n o.kind !== \"role\" &&\n o.kind !== \"skill\" &&\n o.kind !== \"runtime\")\n )\n continue\n out.push({ kind: o.kind, ref: o.ref })\n }\n return Object.freeze(out)\n}\n\nfunction readStringArray(v: unknown): readonly string[] {\n if (!Array.isArray(v)) return []\n return Object.freeze(\n (v as readonly unknown[]).filter((x): x is string => typeof x === \"string\")\n )\n}\n\nfunction readCorpusMeta(\n fm: Readonly<Record<string, unknown>>\n): PlaybookCorpusMeta {\n const meta = (fm.metadata as { corpus?: unknown })?.corpus\n if (!meta || typeof meta !== \"object\") return {}\n return Object.freeze(meta as PlaybookCorpusMeta)\n}\n\n// ── Query matching ─────────────────────────────────────────────────\n\nconst AXES = createAxisRegistry()\n\nfunction matches(p: Playbook, q: PlaybookQuery): boolean {\n if (q.status !== undefined) {\n const wanted = Array.isArray(q.status) ? q.status : [q.status]\n if (!wanted.includes(p.status)) return false\n }\n if (q.kind !== undefined && p.kind !== q.kind) return false\n if (q.dimensions !== undefined) {\n return matchesSelector(p.selector, q.dimensions, { axes: AXES })\n }\n if (q.forOperatorSlug !== undefined) {\n // Legacy sugar: the caller's slugs are axis-ambiguous handles, so\n // try them on both axes — exactly the old either-axis behavior.\n const slugs = Array.isArray(q.forOperatorSlug)\n ? q.forOperatorSlug\n : [q.forOperatorSlug]\n return matchesSelector(\n p.selector,\n { identity: slugs, role: slugs },\n { axes: AXES }\n )\n }\n if (q.operatorRef !== undefined) {\n return p.targets.some(\n (t) => t.kind === \"operator\" && t.ref === q.operatorRef\n )\n }\n return true\n}\n","/**\n * OperatorOverlayResolver — given an operator + conversation context,\n * returns the playbook overlays to splice into the operator's prompt.\n *\n * Decision rules:\n * 1. `active` playbooks targeting the operator are ALWAYS included.\n * 2. `shadow` playbooks fire on a deterministic-hash subset of\n * conversations (`shadowTrafficPct`, default 0.10) — same\n * conversation always lands the same arm so an eval batch is\n * reproducible.\n * 3. `archived` playbooks are never included (per the AIP-12\n * lifecycle terminal state).\n * 4. Multiple active playbooks for the same operator stack by\n * `priority` (higher first). `kind: block-replacement` overrides\n * the operator's default block for the named trait;\n * `kind: overlay` appends to the prompt.\n *\n * Pure — no I/O. Consumes a `PlaybookRegistry` (read-only) + the\n * resolution context. Lifecycle writes go through the lifecycle\n * module.\n */\n\nimport type { Dimensions } from \"../binding/index.js\"\nimport type {\n Playbook,\n PlaybookStatus,\n} from \"./types.js\"\nimport type { PlaybookRegistry } from \"./registry.js\"\nimport {\n DEFAULT_SHADOW_TRAFFIC_PCT,\n sampleShadow as sampleShadowToken,\n} from \"../util/shadow-sample.js\"\n\nexport interface ResolveContext {\n /**\n * Slug of the operator the overlays apply to. Matches against\n * `binds_operator` AND `targets[].ref` (with operator/* glob).\n */\n readonly operatorSlug: string\n /**\n * The role (job) slug the operator fulfils, when distinct from its\n * identity slug. Overlays bind by role — \"the recruiting SOP for any\n * recruiter\" — so a playbook targeting this role matches every operator\n * fulfilling it, not just one. Matched in addition to `operatorSlug`.\n *\n * @deprecated Supply `dimensions` instead — it carries role, position,\n * capability, and any host-registered axis in one typed map.\n */\n readonly roleSlug?: string\n /**\n * Typed subject dimensions (axis → value(s)) evaluated against each\n * playbook's selector. When present, wins over the\n * `operatorSlug`/`roleSlug` slug-pair matching.\n */\n readonly dimensions?: Dimensions\n /**\n * Conversation id (or another stable bucketing token). Used to\n * deterministically place a conversation into shadow-traffic\n * buckets, so the same conversation consistently sees (or doesn't\n * see) a given shadow overlay.\n */\n readonly conversationId?: string\n}\n\nexport interface ResolvedOverlay {\n readonly playbookSlug: string\n readonly status: PlaybookStatus\n readonly kind: Playbook[\"kind\"]\n readonly priority: number\n /** The overlay body. */\n readonly body: string\n /** Audit attribution. */\n readonly playbookPath: string\n /** True iff this overlay came from a shadow playbook + was sampled in. */\n readonly shadowSampled: boolean\n}\n\nexport interface ResolveResult {\n readonly operatorSlug: string\n readonly overlays: readonly ResolvedOverlay[]\n}\n\nexport class OperatorOverlayResolver {\n constructor(private readonly registry: PlaybookRegistry) {}\n\n resolve(ctx: ResolveContext): ResolveResult {\n const slugs = ctx.roleSlug\n ? [ctx.operatorSlug, ctx.roleSlug]\n : [ctx.operatorSlug]\n const candidates = this.registry.listBy({\n ...(ctx.dimensions\n ? { dimensions: ctx.dimensions }\n : { forOperatorSlug: slugs }),\n status: [\"active\", \"shadow\"],\n })\n\n const overlays: ResolvedOverlay[] = []\n for (const p of candidates) {\n if (p.status === \"archived\") continue\n const shadowSampled =\n p.status === \"shadow\"\n ? sampleShadow(ctx, p)\n : false\n if (p.status === \"shadow\" && !shadowSampled) continue\n overlays.push({\n playbookSlug: p.slug,\n status: p.status,\n kind: p.kind,\n priority: p.priority,\n body: p.body,\n playbookPath: p.path,\n shadowSampled,\n })\n }\n\n // Registry already sorts by priority desc; preserve that.\n return Object.freeze({\n operatorSlug: ctx.operatorSlug,\n overlays: Object.freeze(overlays),\n })\n }\n}\n\n// ── Shadow-traffic sampling ────────────────────────────────────────\n\n/**\n * Deterministic 0..1 bucket from a stable token (conversation id).\n * Same conversation always lands the same bucket — so an eval batch\n * partitioned by conversation id is reproducible.\n *\n * If no conversationId is supplied (e.g. one-shot tool call), we fall\n * back to the default of NOT sampling — shadow overlays only fire on\n * traffic with stable identity.\n */\nfunction sampleShadow(ctx: ResolveContext, p: Playbook): boolean {\n const pct = typeof p.corpus.shadowTrafficPct === \"number\"\n ? p.corpus.shadowTrafficPct\n : DEFAULT_SHADOW_TRAFFIC_PCT\n return sampleShadowToken(ctx.conversationId, p.slug, pct)\n}\n\n/**\n * Render-ready combination of overlays for a prompt. Returns the\n * concatenated overlay bodies (priority-ordered, separated by\n * `\\n\\n---\\n\\n`). `block-replacement` overlays are listed in the\n * `replacements` field separately — the host's prompt assembler\n * decides how to merge those into the operator's named blocks.\n */\nexport interface RenderedOverlays {\n readonly appendBlock: string\n readonly replacements: ReadonlyArray<{\n readonly playbookSlug: string\n readonly body: string\n }>\n}\n\nexport function renderOverlays(result: ResolveResult): RenderedOverlays {\n const overlays = result.overlays.filter((o) => o.kind === \"overlay\")\n const replacements = result.overlays\n .filter((o) => o.kind === \"block-replacement\")\n .map((o) => ({ playbookSlug: o.playbookSlug, body: o.body }))\n return Object.freeze({\n appendBlock: overlays.map((o) => o.body.trim()).join(\"\\n\\n---\\n\\n\"),\n replacements: Object.freeze(replacements),\n })\n}\n","/**\n * PlaybookLifecycle — activate / archive / supersede AIP-12\n * playbooks, atomically.\n *\n * State machine (per the AIP-12 spec):\n * shadow → active | archived\n * active → archived\n * archived = terminal\n *\n * activate(slug):\n * 1. Read current playbook (CAS via versionToken).\n * 2. For each slug in playbook.supersedes that's currently active:\n * transition that slug to `archived` first.\n * 3. Update the target playbook's status → \"active\", clear\n * shadowMetrics.lastEvaluatedAt to mark the activation moment.\n * 4. Atomic file write (CAS).\n * 5. Emit `playbook.activated` event.\n *\n * archive(slug, reason):\n * 1. CAS read.\n * 2. Set status → \"archived\", metadata.corpus.archiveReason = reason.\n * 3. Atomic write.\n * 4. Emit `playbook.archived`.\n *\n * Multi-file transaction guarded by FsPort.lock so a concurrent\n * activate can't half-supersede.\n */\n\nimport matter from \"gray-matter\"\nimport type { ClockPort } from \"../ports/clock.port.js\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type { IdentityPort } from \"../ports/identity.port.js\"\nimport { CorpusEventEmitter } from \"../events/emitter.js\"\nimport { CorpusWorkspaceReader } from \"../workspace/reader.js\"\nimport { CorpusWorkspaceWriter } from \"../workspace/writer.js\"\nimport { appendAttestation, makeAttestation } from \"../lifecycle/attestations.js\"\nimport type { Attestation } from \"../types.js\"\nimport { PlaybookRegistry } from \"./registry.js\"\nimport type { Playbook, PlaybookStatus } from \"./types.js\"\n\nexport class PlaybookNotFoundError extends Error {\n constructor(readonly slug: string) {\n super(`PlaybookNotFoundError: no playbook found with slug \"${slug}\"`)\n this.name = \"PlaybookNotFoundError\"\n }\n}\n\nexport class IllegalPlaybookTransitionError extends Error {\n constructor(\n readonly slug: string,\n readonly from: PlaybookStatus,\n readonly to: PlaybookStatus\n ) {\n super(\n `IllegalPlaybookTransitionError: ${slug}: ${from} → ${to} is not allowed`\n )\n this.name = \"IllegalPlaybookTransitionError\"\n }\n}\n\nexport interface PlaybookLifecycleOptions {\n readonly fs: FsPort\n readonly clock: ClockPort\n readonly identity: IdentityPort\n readonly workspacePath: string\n}\n\nexport interface ActivateResult {\n readonly slug: string\n readonly previousStatus: PlaybookStatus\n readonly versionToken: string\n readonly supersededSlugs: readonly string[]\n}\n\nexport interface ArchiveResult {\n readonly slug: string\n readonly previousStatus: PlaybookStatus\n readonly versionToken: string\n}\n\nexport class PlaybookLifecycle {\n constructor(private readonly opts: PlaybookLifecycleOptions) {}\n\n /**\n * Transition `slug` from shadow → active. Cascades through\n * `supersedes[]`: any currently-active playbook listed there is\n * archived (with `archiveReason: superseded-by-<slug>`) in the\n * same lock-guarded transaction.\n */\n async activate(slug: string): Promise<ActivateResult> {\n const writer = new CorpusWorkspaceWriter({ fs: this.opts.fs })\n const lockPath = joinPath(this.opts.workspacePath, \"_log.md\")\n return await writer.transaction(lockPath, async () => {\n const playbook = await this.loadOne(slug)\n assertTransition(playbook.status, \"active\", slug)\n\n // Supersede chain: archive previous active versions BEFORE\n // we flip this one. If any supersede write fails, the lock\n // protects us from a half-activated state — but the AIP-10\n // log will show the partial sequence so a recovery routine\n // can detect inconsistency.\n const supersededSlugs: string[] = []\n const reg = await this.loadRegistry()\n const identity = await this.opts.identity.resolve()\n for (const supersededSlug of playbook.supersedes) {\n const prev = reg.bySlugOrNull(supersededSlug)\n if (!prev || prev.status !== \"active\") continue\n const att = this.attestation(\n \"archived\",\n identity.principal,\n `superseded-by-${slug}`\n )\n await this.writeWith(prev, (fm) =>\n appendAttestation(\n patchStatus(fm, \"archived\", {\n archiveReason: `superseded-by-${slug}`,\n archivedAt: att.at,\n }),\n att\n )\n )\n await this.emitter().emit(\"playbook.archived\", {\n slug: prev.slug,\n archiveReason: `superseded-by-${slug}`,\n })\n supersededSlugs.push(prev.slug)\n }\n\n const activateAtt = this.attestation(\n \"activated\",\n identity.principal,\n `from=${playbook.status}`\n )\n const newToken = await this.writeWith(playbook, (fm) =>\n appendAttestation(\n patchStatus(fm, \"active\", { activatedAt: activateAtt.at }),\n activateAtt\n )\n )\n await this.emitter().emit(\"playbook.activated\", {\n slug,\n previousStatus: playbook.status,\n supersededSlugs,\n })\n\n return {\n slug,\n previousStatus: playbook.status,\n versionToken: newToken,\n supersededSlugs: Object.freeze(supersededSlugs),\n }\n })\n }\n\n /**\n * Transition `slug` → archived. Skip-no-op if already archived.\n */\n async archive(slug: string, reason: string): Promise<ArchiveResult> {\n const writer = new CorpusWorkspaceWriter({ fs: this.opts.fs })\n const lockPath = joinPath(this.opts.workspacePath, \"_log.md\")\n return await writer.transaction(lockPath, async () => {\n const playbook = await this.loadOne(slug)\n if (playbook.status === \"archived\") {\n return {\n slug,\n previousStatus: \"archived\" as const,\n versionToken: playbook.versionToken,\n }\n }\n assertTransition(playbook.status, \"archived\", slug)\n const identity = await this.opts.identity.resolve()\n const att = this.attestation(\"archived\", identity.principal, reason)\n const newToken = await this.writeWith(playbook, (fm) =>\n appendAttestation(\n patchStatus(fm, \"archived\", {\n archiveReason: reason,\n archivedAt: att.at,\n }),\n att\n )\n )\n await this.emitter().emit(\"playbook.archived\", {\n slug,\n previousStatus: playbook.status,\n archiveReason: reason,\n })\n return {\n slug,\n previousStatus: playbook.status,\n versionToken: newToken,\n }\n })\n }\n\n // ── Internal ─────────────────────────────────────────────────────\n\n private async loadOne(slug: string): Promise<Playbook> {\n const reg = await this.loadRegistry()\n const p = reg.bySlugOrNull(slug)\n if (!p) throw new PlaybookNotFoundError(slug)\n return p\n }\n\n private async loadRegistry(): Promise<PlaybookRegistry> {\n const reader = new CorpusWorkspaceReader({ fs: this.opts.fs })\n const snapshot = await reader.read(this.opts.workspacePath)\n return new PlaybookRegistry({ snapshot })\n }\n\n private async writeWith(\n playbook: Playbook,\n patch: (fm: Record<string, unknown>) => Record<string, unknown>\n ): Promise<string> {\n const writer = new CorpusWorkspaceWriter({ fs: this.opts.fs })\n // Rebuild the file content from the parsed frontmatter +\n // original body. We use the parsed-frontmatter shape (not the\n // raw original .md) so the patch is applied to typed data.\n const nextFm = patch({ ...playbook.file.frontmatter })\n const nextContent = matter.stringify(\n playbook.body.startsWith(\"\\n\") ? playbook.body : \"\\n\" + playbook.body,\n nextFm\n )\n return await writer.writeFile(\n joinPath(this.opts.workspacePath, playbook.path),\n nextContent,\n playbook.versionToken\n )\n }\n\n /** Build a transition attestation from current clock + given identity. */\n private attestation(\n kind: Attestation[\"kind\"],\n identity: string,\n note?: string\n ): Attestation {\n return makeAttestation({\n kind,\n identity,\n at: this.opts.clock.now().toISOString(),\n ...(note ? { note } : {}),\n })\n }\n\n private emitter(): CorpusEventEmitter {\n return new CorpusEventEmitter({\n fs: this.opts.fs,\n clock: this.opts.clock,\n identity: this.opts.identity,\n workspaceRoot: this.opts.workspacePath,\n })\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────\n\nfunction assertTransition(\n from: PlaybookStatus,\n to: PlaybookStatus,\n slug: string\n): void {\n const allowed: Record<PlaybookStatus, readonly PlaybookStatus[]> = {\n shadow: [\"active\", \"archived\"],\n active: [\"archived\"],\n archived: [],\n }\n if (!allowed[from].includes(to)) {\n throw new IllegalPlaybookTransitionError(slug, from, to)\n }\n}\n\nfunction patchStatus(\n fm: Record<string, unknown>,\n newStatus: PlaybookStatus,\n extraCorpusMeta: Record<string, unknown>\n): Record<string, unknown> {\n const metaIn = (fm.metadata as Record<string, unknown> | undefined) ?? {}\n const corpusIn =\n (metaIn.corpus as Record<string, unknown> | undefined) ?? {}\n return {\n ...fm,\n status: newStatus,\n metadata: {\n ...metaIn,\n corpus: {\n ...corpusIn,\n ...extraCorpusMeta,\n },\n },\n }\n}\n\nfunction joinPath(a: string, b: string): string {\n if (!a) return b\n return a.endsWith(\"/\") ? a + b : a + \"/\" + b\n}\n","/**\n * PlaybookEvaluator — runs shadow vs baseline eval batches on AIP-12\n * playbooks, records winRateVsBaseline + sample size, decides\n * promotion readiness against `metadata.corpus.autoPromote`.\n *\n * Inputs (per eval-case the host hands us):\n * - prompt: the test prompt\n * - shadow.response: agent output WITH the playbook overlay applied\n * - baseline.response: agent output WITHOUT the overlay\n * - rubric: how to score both arms\n *\n * Output:\n * - winRateVsBaseline = fraction of cases where shadow.score >= baseline.score\n * - sampleSize = n\n * - readyForActivation = winRate >= threshold && n >= minSampleSize\n *\n * The evaluator does NOT itself activate the playbook — it writes\n * shadowMetrics back to the PLAYBOOK.md (via the writer) and lets\n * the curator's `activate` workflow decide. That keeps the\n * audit chain clean: evaluator measures, curator decides.\n *\n * Pure logic. Backing IEvaluator + writer/emitter come in as ports.\n */\n\nimport matter from \"gray-matter\"\nimport type {\n EvalContextPort,\n EvalRubricPort,\n EvaluatorPort,\n} from \"../ports/evaluator.port.js\"\nimport type { ClockPort } from \"../ports/clock.port.js\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type { IdentityPort } from \"../ports/identity.port.js\"\nimport { CorpusEventEmitter } from \"../events/emitter.js\"\nimport { CorpusWorkspaceReader } from \"../workspace/reader.js\"\nimport { CorpusWorkspaceWriter } from \"../workspace/writer.js\"\nimport {\n appendAttestation,\n makeAttestation,\n} from \"../lifecycle/attestations.js\"\nimport { PlaybookNotFoundError } from \"./lifecycle.js\"\nimport { PlaybookRegistry } from \"./registry.js\"\nimport type { Playbook } from \"./types.js\"\n\nexport interface EvalCase {\n /** Optional stable id — used in event payloads + per-case audit. */\n readonly id?: string\n readonly prompt: string\n /** Agent output WITH the playbook overlay applied. */\n readonly shadowResponse: string\n /** Agent output WITHOUT the overlay (baseline). */\n readonly baselineResponse: string\n}\n\nexport interface PlaybookBatchOptions {\n readonly rubric: EvalRubricPort\n readonly cases: readonly EvalCase[]\n /** Forwarded to evaluator + recorded in event payloads. */\n readonly contextOverrides?: Partial<EvalContextPort>\n}\n\nexport interface PlaybookBatchResult {\n readonly playbookSlug: string\n readonly sampleSize: number\n readonly winRateVsBaseline: number\n readonly shadowAvgScore: number\n readonly baselineAvgScore: number\n readonly readyForActivation: boolean\n /** Per-case details — useful for the curator UI. */\n readonly perCase: readonly {\n readonly id?: string\n readonly shadowScore: number\n readonly baselineScore: number\n readonly winnerArm: \"shadow\" | \"baseline\" | \"tie\"\n }[]\n}\n\nexport interface PlaybookEvaluatorOptions {\n readonly fs: FsPort\n readonly clock: ClockPort\n readonly identity: IdentityPort\n readonly workspacePath: string\n readonly evaluator: EvaluatorPort\n}\n\nexport class PlaybookEvaluator {\n constructor(private readonly opts: PlaybookEvaluatorOptions) {}\n\n /**\n * Run an eval batch against a single playbook. For each case:\n * 1. Score shadow.response against rubric → shadowScore\n * 2. Score baseline.response against rubric → baselineScore\n * 3. shadow \"wins\" if shadowScore >= baselineScore\n * Aggregate: winRateVsBaseline = wins / n.\n *\n * On completion: writes shadowMetrics back to the PLAYBOOK.md (CAS),\n * emits a `corpus.playbook.evaluated` event (held outside the formal\n * AIP-41 taxonomy until the spec adopts it).\n */\n async runBatch(\n playbookSlug: string,\n batch: PlaybookBatchOptions\n ): Promise<PlaybookBatchResult> {\n const playbook = await this.loadPlaybook(playbookSlug)\n const perCase: PlaybookBatchResult[\"perCase\"][number][] = []\n let wins = 0\n let shadowSum = 0\n let baselineSum = 0\n\n for (const c of batch.cases) {\n const shadowResult = await this.opts.evaluator.evaluate({\n rubric: batch.rubric,\n prompt: c.prompt,\n response: c.shadowResponse,\n context: {\n ...(batch.contextOverrides ?? {}),\n arm: \"shadow\",\n appliedPlaybooks: [playbookSlug],\n },\n })\n const baselineResult = await this.opts.evaluator.evaluate({\n rubric: batch.rubric,\n prompt: c.prompt,\n response: c.baselineResponse,\n context: {\n ...(batch.contextOverrides ?? {}),\n arm: \"baseline\",\n appliedPlaybooks: [],\n },\n })\n const winnerArm: \"shadow\" | \"baseline\" | \"tie\" =\n shadowResult.score > baselineResult.score\n ? \"shadow\"\n : shadowResult.score < baselineResult.score\n ? \"baseline\"\n : \"tie\"\n // Tie counts as a NON-win — playbook has to strictly beat baseline.\n if (winnerArm === \"shadow\") wins++\n shadowSum += shadowResult.score\n baselineSum += baselineResult.score\n perCase.push({\n id: c.id,\n shadowScore: shadowResult.score,\n baselineScore: baselineResult.score,\n winnerArm,\n })\n }\n\n const sampleSize = batch.cases.length\n const winRate = sampleSize > 0 ? wins / sampleSize : 0\n const auto = (playbook.corpus.autoPromote ?? {}) as {\n enabled?: boolean\n metric?: string\n threshold?: { gte?: number; lte?: number }\n minSampleSize?: number\n }\n const gteOK =\n typeof auto.threshold?.gte === \"number\"\n ? winRate >= auto.threshold.gte\n : false\n const sizeOK =\n typeof auto.minSampleSize === \"number\"\n ? sampleSize >= auto.minSampleSize\n : sampleSize > 0\n const readyForActivation = !!auto.enabled && gteOK && sizeOK\n\n // Persist shadowMetrics back to PLAYBOOK.md (CAS).\n await this.persistMetrics(playbook, {\n sampleSize,\n winRateVsBaseline: winRate,\n lastEvaluatedAt: this.opts.clock.now().toISOString(),\n })\n\n // Emit a custom event — the formal AIP-41 event taxonomy doesn't\n // yet include a typed name like `playbook.shadow.evaluated`, so we\n // route through the lower-level CorpusWorkspaceWriter / FsPort\n // directly here. The host can tail _log.md and pick this up.\n // (Same `_log.md` format as the standard emitter.)\n await this.appendCustomEvent(\"playbook.shadow.evaluated\", {\n slug: playbook.slug,\n sampleSize,\n winRateVsBaseline: winRate,\n readyForActivation,\n })\n\n return Object.freeze({\n playbookSlug: playbook.slug,\n sampleSize,\n winRateVsBaseline: winRate,\n shadowAvgScore: sampleSize > 0 ? shadowSum / sampleSize : 0,\n baselineAvgScore: sampleSize > 0 ? baselineSum / sampleSize : 0,\n readyForActivation,\n perCase: Object.freeze(perCase),\n })\n }\n\n // ── Internal ─────────────────────────────────────────────────────\n\n private async loadPlaybook(slug: string): Promise<Playbook> {\n const reader = new CorpusWorkspaceReader({ fs: this.opts.fs })\n const snapshot = await reader.read(this.opts.workspacePath)\n const reg = new PlaybookRegistry({ snapshot })\n const p = reg.bySlugOrNull(slug)\n if (!p) throw new PlaybookNotFoundError(slug)\n return p\n }\n\n private async persistMetrics(\n playbook: Playbook,\n metrics: {\n sampleSize: number\n winRateVsBaseline: number\n lastEvaluatedAt: string\n }\n ): Promise<void> {\n const writer = new CorpusWorkspaceWriter({ fs: this.opts.fs })\n const identity = await this.opts.identity.resolve()\n let fm = { ...playbook.file.frontmatter } as Record<string, unknown>\n const metaIn = (fm.metadata as Record<string, unknown> | undefined) ?? {}\n const corpusIn =\n (metaIn.corpus as Record<string, unknown> | undefined) ?? {}\n fm.metadata = {\n ...metaIn,\n corpus: {\n ...corpusIn,\n shadowMetrics: metrics,\n },\n }\n // Append the `evaluated` attestation so the chain records who/when.\n fm = appendAttestation(\n fm,\n makeAttestation({\n kind: \"evaluated\",\n identity: identity.principal,\n at: metrics.lastEvaluatedAt,\n note: `n=${metrics.sampleSize} winRate=${metrics.winRateVsBaseline.toFixed(3)}`,\n })\n )\n const content = matter.stringify(\n playbook.body.startsWith(\"\\n\") ? playbook.body : \"\\n\" + playbook.body,\n fm\n )\n await writer.writeFile(\n joinPath(this.opts.workspacePath, playbook.path),\n content,\n playbook.versionToken\n )\n }\n\n private async appendCustomEvent(\n customKind: string,\n payload: Readonly<Record<string, unknown>>\n ): Promise<void> {\n // Use the canonical emitter shape so _log.md stays homogeneous,\n // but pass through the kit's typed CorpusEventEmitter for the\n // formal kinds. For custom kinds, we hand-craft a line so the\n // file format stays one-event-per-line.\n const identity = await this.opts.identity.resolve()\n const line = `- ${this.opts.clock.now().toISOString()} ${customKind} by ${identity.principal} payload=${JSON.stringify(payload, [...Object.keys(payload).sort()])}\\n`\n const logPath = joinPath(this.opts.workspacePath, \"_log.md\")\n // Initialize the log file with the AIP-10 header on first write\n // (same shape as CorpusEventEmitter).\n if (!(await this.opts.fs.exists(logPath))) {\n // Construct a fresh emitter to write the header for parity.\n const emitter = new CorpusEventEmitter({\n fs: this.opts.fs,\n clock: this.opts.clock,\n identity: this.opts.identity,\n workspaceRoot: this.opts.workspacePath,\n })\n // Cheapest way to materialize the header: emit one canonical\n // event (the host might prefer to just call `appendFile`\n // directly; keeping the header parity is the important bit).\n void emitter\n await this.opts.fs.writeFile(\n logPath,\n \"# Corpus activity log\\n\\nAppend-only AIP-10 log of corpus state transitions. Each line:\\n`- <iso> <kind> by <actor> payload=<json>`\\n\\n\"\n )\n }\n await this.opts.fs.appendFile(logPath, line)\n }\n}\n\nfunction joinPath(a: string, b: string): string {\n if (!a) return b\n return a.endsWith(\"/\") ? a + b : a + \"/\" + b\n}\n","/**\n * @agentproto/corpus — composition of AIP-10/12/18/9/15/41.\n *\n * Spec: https://agentproto.sh/docs/corpus\n */\n\nexport const SPEC_NAME = \"agentcorpus/v1\" as const\nexport const SPEC_VERSION = \"0.1.0-alpha\" as const\n\n// Shared slug + language utilities (single source of truth)\nexport {\n slugify,\n uniqueSlug,\n isSourceSlug,\n isEntrySlug,\n type SlugifyOptions,\n} from \"./util/slug.js\"\nexport { normalizeLanguageTag } from \"./util/language.js\"\n\n// Types\nexport type {\n FileKind,\n ParsedFile,\n CorpusWorkspaceSnapshot,\n ValidationIssue,\n ValidationResult,\n LintIssue,\n LintReport,\n CorpusEventKind,\n CorpusEvent,\n CorpusPreset,\n CorpusPresetBootstrapContext,\n Attestation,\n AttestationKind,\n} from \"./types.js\"\n\n// Access — attestations + access policy + capability levels\nexport {\n appendAttestation,\n readAttestations,\n makeAttestation,\n} from \"./lifecycle/attestations.js\"\nexport {\n evaluateAccess,\n readAccessSpec,\n} from \"./access/policy.js\"\nexport type {\n AccessClassification,\n AccessCaller,\n AccessContext,\n AccessDecision,\n CorpusAccessSpec,\n} from \"./access/policy.js\"\nexport {\n evaluateCapability,\n readAccessModes,\n} from \"./access/capability.js\"\nexport type {\n AccessModesMap,\n Capability,\n CapabilityCaller,\n CapabilityDecision,\n CapabilityRule,\n} from \"./access/capability.js\"\n\n// i18n / language filter\nexport {\n resolveLanguageFilter,\n matchesLanguageFilter,\n readOperatorLocale,\n readWorkspaceDefaultLanguage,\n readEntryLanguage,\n} from \"./access/language.js\"\nexport type {\n LanguageFilter,\n ResolveLanguageFilterInput,\n} from \"./access/language.js\"\n\n// Importers\nexport { ImporterRunner } from \"./importers/runner.js\"\nexport { LocalFilesImporter } from \"./importers/local-files.js\"\nexport { KbMigrationImporter } from \"./importers/kb-migration.js\"\nexport { WebImporter } from \"./importers/web.js\"\nexport { ConversationImporter } from \"./importers/conversation.js\"\nexport type {\n CorpusImporter,\n ImporterTarget,\n ImportedSource,\n BatchReport,\n ImporterRunnerOptions,\n} from \"./importers/types.js\"\nexport type { LocalFilesImporterOptions } from \"./importers/local-files.js\"\nexport type { WebImporterOptions } from \"./importers/web.js\"\nexport type { ConversationImporterOptions } from \"./importers/conversation.js\"\n\n// Distill — raw source → refined entries (KNOWLEDGE layer)\nexport { DistillRunner } from \"./distill/runner.js\"\nexport type {\n DistillRunnerOptions,\n DistillSource,\n DistillRunReport,\n EntryLayout,\n} from \"./distill/runner.js\"\nexport type {\n DistillPort,\n DistillInput,\n DistilledItem,\n RefinedKind,\n} from \"./distill/types.js\"\nexport { REFINED_KIND_SCHEMA, isRefinedKind } from \"./distill/types.js\"\nexport { buildDistillPrompt, parseItems } from \"./distill/prompt.js\"\nexport { scanDistilledSourceIds } from \"./distill/scan.js\"\n\n// Distill registry — the catalog of distill kinds (4 swappable slots per\n// descriptor) + the generic per-(descriptor × scope) runner.\nexport { createDistillRegistry } from \"./distill/registry.js\"\nexport type {\n DistillRegistry,\n DistillDescriptor,\n DistillBinding,\n DistillScope,\n DistillTarget,\n} from \"./distill/registry.js\"\nexport { runDistill } from \"./distill/run.js\"\nexport type { DistillReport } from \"./distill/run.js\"\n\n// ClaudeDistiller — a DistillPort over the Messages API (host-injected key).\nexport { ClaudeDistiller } from \"./distill/claude-distiller.js\"\nexport type { ClaudeDistillerOptions } from \"./distill/claude-distiller.js\"\n\n// Conversation windowing — pure (thread, day) helpers + the windowed-source\n// contract the conversation kind binds against.\nexport {\n windowRef,\n parseWindowRef,\n windowSlug,\n enumerateWindowRefs,\n} from \"./distill/windows.js\"\nexport type {\n ConversationWindowSource,\n ConversationThreadRef,\n} from \"./distill/windows.js\"\n\n// Knowledge resolver — the `knowledge:` binding (KNOWLEDGE → SKILL link)\nexport { resolveKnowledge } from \"./knowledge/resolve.js\"\nexport type {\n CorpusEntryQuery,\n ResolvedEntry,\n SourceRef,\n ResolveKnowledgeOptions,\n} from \"./knowledge/resolve.js\"\n\n// Overlay — guild edits shadow read-only packs (the customization engine)\nexport {\n OverlayFs,\n ReadOnlyFs,\n WHITEOUT_SUFFIX,\n type OverlayFsOptions,\n} from \"./knowledge/overlay-fs.js\"\n\n// In-memory FsPort — backs build-time-inlined knowledge packs (no runtime fs)\nexport { MemFs } from \"./knowledge/mem-fs.js\"\n\n// Knowledge stack — composable layer resolution (register one provider per\n// dimension; resolver emits a band-ordered stack; mount helper overlays it)\nexport {\n StackResolver,\n buildOverlayFromStack,\n flattenPackRefs,\n partitionStackRefs,\n type BuildOverlayOptions,\n type StackRefPartition,\n type LayerMode,\n type LayerRef,\n type LayerProvider,\n type LayerShadow,\n type ResolutionContext,\n type StackEntry,\n type StackResolution,\n type StackSkip,\n} from \"./stack/index.js\"\n\n// Sink — agnostic outbound (corpus → external store via a config/MCP sink)\nexport { SyncRunner } from \"./sink/runner.js\"\nexport type { SyncRunnerOptions, SyncReport } from \"./sink/runner.js\"\nexport type { SinkPort, SinkItem, SinkPushResult } from \"./sink/types.js\"\nexport type {\n KbMigrationConfig,\n KbListLike,\n KbSourceLike,\n} from \"./importers/kb-migration.js\"\n\n// Calibration — reviewer track record + multi-reviewer aggregator\nexport { aggregateReviewerScores } from \"./calibration/aggregate.js\"\nexport type {\n AggregateOptions,\n AggregateResult,\n ReviewerScore,\n} from \"./calibration/aggregate.js\"\nexport { ReviewerTrackRecord } from \"./calibration/track-record.js\"\nexport type {\n ReviewerTrackRecordOptions,\n TrackRecordEntry,\n} from \"./calibration/track-record.js\"\nexport {\n pearsonCorrelation,\n computeReviewerCalibration,\n} from \"./calibration/correlation.js\"\nexport type {\n CalibrationOptions,\n ReviewerCalibration,\n} from \"./calibration/correlation.js\"\n\n// Re-export the most commonly consumed ports from the main barrel so\n// the agstudio side (corpus engine adapter) doesn't need the subpath.\n// Full port surface lives under `@agentproto/corpus/ports`.\nexport type {\n FsPort,\n FsStat,\n FsLockHandle,\n} from \"./ports/fs.port.js\"\nexport type { ClockPort } from \"./ports/clock.port.js\"\nexport type { IdentityPort, CallerIdentity } from \"./ports/identity.port.js\"\nexport type {\n FetcherPort,\n FetchedSource,\n FetchedSourceKind,\n} from \"./ports/fetcher.port.js\"\nexport type {\n ConversationSourcePort,\n ConversationDoc,\n ConversationTurn,\n} from \"./ports/conversation-source.port.js\"\nexport { systemClock } from \"./ports/clock.port.js\"\n\n// Workspace\nexport { CorpusWorkspaceReader } from \"./workspace/reader.js\"\nexport {\n CorpusWorkspaceWriter,\n CorpusVersionConflictError,\n} from \"./workspace/writer.js\"\nexport type {\n CorpusWorkspaceReaderOptions,\n} from \"./workspace/reader.js\"\nexport type {\n CorpusWorkspaceWriterOptions,\n MarkdownDoc,\n} from \"./workspace/writer.js\"\n\n// Validate\nexport { CorpusValidator } from \"./validate/validator.js\"\nexport type {\n CorpusValidatorOptions,\n AipSchemaKey,\n AipSchemaBundle,\n} from \"./validate/validator.js\"\nexport { CorpusLinter } from \"./validate/linter.js\"\nexport type {\n CorpusLinterOptions,\n CustomLintRunner,\n} from \"./validate/linter.js\"\n\n// Events\nexport { CorpusEventEmitter } from \"./events/emitter.js\"\nexport type {\n CorpusEventEmitterOptions,\n} from \"./events/emitter.js\"\n\n// Sidecar\nexport {\n CandidatesSidecar,\n SidecarDuplicateError,\n SidecarNotFoundError,\n} from \"./workspace/sidecar.js\"\nexport type {\n CandidateRow,\n CandidatesSidecarOptions,\n} from \"./workspace/sidecar.js\"\n\n// Lifecycle\nexport {\n DEFAULT_TRANSITIONS,\n canTransition,\n assertTransition,\n transitionGraphFromCollection,\n IllegalTransitionError,\n} from \"./lifecycle/candidate.js\"\nexport type {\n CandidateStatus,\n TransitionCheck,\n} from \"./lifecycle/candidate.js\"\nexport {\n evaluateGate,\n extractAutoPromoteConfig,\n} from \"./lifecycle/gate.js\"\nexport type {\n AutoPromoteConfig,\n AutoPromoteRequirements,\n CandidateForGate,\n GateFailure,\n GateResult,\n} from \"./lifecycle/gate.js\"\nexport { CorpusPromoter, PromoteRejectedError } from \"./lifecycle/promote.js\"\nexport type {\n PromoteOptions,\n PromoteResult,\n PromoteContext,\n} from \"./lifecycle/promote.js\"\n\n// Index\nexport { CorpusIndexer } from \"./index/indexer.js\"\nexport type {\n CorpusIndexerOptions,\n IndexReport,\n} from \"./index/indexer.js\"\nexport { chunkText } from \"./index/chunker.js\"\nexport type { ChunkerOptions } from \"./index/chunker.js\"\n\n// Writer port — the kit's seam into a backing engine\nexport type {\n WriterPort,\n WriterChunk,\n PushChunksInput,\n} from \"./ports/writer.port.js\"\n\n// Evaluator port — the kit's seam into a backing evaluator engine.\n// @agstudio/integration-evaluator's IEvaluator satisfies it structurally.\nexport type {\n EvaluatorPort,\n EvalInputPort,\n EvalResultPort,\n EvalRubricPort,\n EvalContextPort,\n} from \"./ports/evaluator.port.js\"\n\n// Attachment binding plane — Dimensions × Selectors × one matcher\nexport {\n ANY_REF,\n WELL_KNOWN_AXES,\n createAxisRegistry,\n identityAxis,\n roleAxis,\n positionAxis,\n capabilityAxis,\n prefixedRefNormalizer,\n EMPTY_SELECTOR,\n isEmptySelector,\n matchesSelector,\n parseSelectorFrontmatter,\n compileLegacyPlaybookBinding,\n matchAttachments,\n matchAttachmentRefs,\n} from \"./binding/index.js\"\nexport type {\n AxisDefinition,\n AxisRegistry,\n Dimensions,\n MatchOptions,\n Selector,\n SelectorTerm,\n AttachmentAsset,\n AttachmentDeclaration,\n MatchAttachmentsOptions,\n} from \"./binding/index.js\"\n\n// Playbooks (AIP-12)\nexport { PlaybookRegistry } from \"./playbooks/registry.js\"\nexport type { PlaybookRegistryOptions } from \"./playbooks/registry.js\"\nexport {\n OperatorOverlayResolver,\n renderOverlays,\n} from \"./playbooks/resolver.js\"\nexport type {\n ResolveContext,\n ResolveResult,\n ResolvedOverlay,\n RenderedOverlays,\n} from \"./playbooks/resolver.js\"\nexport {\n PlaybookLifecycle,\n PlaybookNotFoundError,\n IllegalPlaybookTransitionError,\n} from \"./playbooks/lifecycle.js\"\nexport type {\n PlaybookLifecycleOptions,\n ActivateResult,\n ArchiveResult,\n} from \"./playbooks/lifecycle.js\"\nexport type {\n Playbook,\n PlaybookCorpusMeta,\n PlaybookKind,\n PlaybookQuery,\n PlaybookStatus,\n PlaybookTarget,\n PlaybookTargetKind,\n} from \"./playbooks/types.js\"\nexport { PlaybookEvaluator } from \"./playbooks/evaluator.js\"\nexport type {\n EvalCase,\n PlaybookBatchOptions,\n PlaybookBatchResult,\n PlaybookEvaluatorOptions,\n} from \"./playbooks/evaluator.js\"\n\n"]}
1
+ {"version":3,"sources":["../src/util/slug.ts","../src/util/language.ts","../src/lifecycle/attestations.ts","../src/access/policy.ts","../src/access/capability.ts","../src/access/language.ts","../src/events/emitter.ts","../src/workspace/reader.ts","../src/workspace/writer.ts","../src/importers/runner.ts","../src/importers/local-files.ts","../src/importers/kb-migration.ts","../src/importers/web.ts","../src/importers/conversation.ts","../src/distill/runner.ts","../src/distill/prompt.ts","../src/distill/scan.ts","../src/distill/registry.ts","../src/distill/run.ts","../src/distill/claude-distiller.ts","../src/distill/windows.ts","../src/knowledge/overlay-fs.ts","../src/knowledge/mem-fs.ts","../src/util/shadow-sample.ts","../src/stack/resolver.ts","../src/stack/mount.ts","../src/sink/runner.ts","../src/calibration/aggregate.ts","../src/calibration/track-record.ts","../src/calibration/correlation.ts","../src/validate/validator.ts","../src/validate/linter.ts","../src/lifecycle/candidate.ts","../src/lifecycle/gate.ts","../src/lifecycle/promote.ts","../src/index/chunker.ts","../src/index/indexer.ts","../src/binding/axes.ts","../src/binding/selector.ts","../src/binding/parse.ts","../src/binding/legacy.ts","../src/binding/attachment.ts","../src/playbooks/registry.ts","../src/playbooks/resolver.ts","../src/playbooks/lifecycle.ts","../src/playbooks/evaluator.ts","../src/index.ts"],"names":["createHash","matter","joinPath","sha256","parseConfig","z","acc","yamlParse","yamlStringify","CandidatesSidecar","allOf","readStatus","sampleShadow","assertTransition"],"mappings":";;;;;;;;;;;;;;;;;;;AAaA,IAAM,WAAA,GAAc,sBAAA;AACpB,IAAM,UAAA,GAAa,2BAAA;AAiBZ,SAAS,OAAA,CAAQ,KAAA,EAAe,IAAA,GAAuB,EAAC,EAAW;AACxE,EAAA,MAAM,MAAA,GAAS,KAAK,MAAA,IAAU,EAAA;AAC9B,EAAA,MAAM,QAAA,GAAW,KAAK,QAAA,IAAY,MAAA;AAClC,EAAA,IAAI,CAAA,GAAI,MACL,WAAA,EAAY,CACZ,UAAU,KAAK,CAAA,CACf,OAAA,CAAQ,QAAA,EAAU,EAAE,CAAA;AACvB,EAAA,IAAI,KAAK,WAAA,EAAa,CAAA,GAAI,CAAA,CAAE,OAAA,CAAQ,gBAAgB,EAAE,CAAA;AACtD,EAAA,CAAA,GAAI,CAAA,CACD,OAAA,CAAQ,aAAA,EAAe,GAAG,EAC1B,OAAA,CAAQ,QAAA,EAAU,GAAG,CAAA,CACrB,MAAM,CAAA,EAAG,MAAM,CAAA,CACf,OAAA,CAAQ,YAAY,EAAE,CAAA;AACzB,EAAA,IAAI,KAAK,aAAA,IAAiB,CAAA,IAAK,CAAC,QAAA,CAAS,IAAA,CAAK,CAAC,CAAA,EAAG;AAChD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,GAAI,IAAI,GAAA,GAAM,CAAA;AAC7C;;;ACxRO,IAAM,SAAA,GAAY;AAClB,IAAM,YAAA,GAAe","file":"index.mjs","sourcesContent":["/**\n * AIP-10 slug helpers — the single source of truth for turning arbitrary\n * text or paths into schema-valid slugs. Replaces the three drifted\n * `makeSlug` copies (web / local-files / distill importers) and the two\n * `uniqueSlug` copies, so a rule change lands once instead of in four\n * places.\n *\n * Two AIP-10 slug shapes:\n * - **source** id `^[a-z0-9][a-z0-9-]*$` — a leading digit is allowed.\n * - **entry / role / tag** id `^[a-z][a-z0-9-]*[a-z0-9]$` — must start\n * with a letter and end alphanumeric. Pass `leadingLetter: true`.\n */\n\nconst SOURCE_SLUG = /^[a-z0-9][a-z0-9-]*$/\nconst ENTRY_SLUG = /^[a-z][a-z0-9-]*[a-z0-9]$/\n\nexport interface SlugifyOptions {\n /** Max length before the trailing-dash trim. Default 96. */\n readonly maxLen?: number\n /** Returned when the slugified result is empty / degenerate. Default \"item\". */\n readonly fallback?: string\n /**\n * Guarantee the AIP-10 *entry* shape: a leading letter (prefix `e-` when\n * the slug would otherwise start with a digit) and length ≥ 2.\n */\n readonly leadingLetter?: boolean\n /** Strip a leading `http(s)://` first — for slugging a URL fallback. */\n readonly stripScheme?: boolean\n}\n\n/** Slugify arbitrary text into an AIP-10-valid id. */\nexport function slugify(input: string, opts: SlugifyOptions = {}): string {\n const maxLen = opts.maxLen ?? 96\n const fallback = opts.fallback ?? \"item\"\n let s = input\n .toLowerCase()\n .normalize(\"NFD\")\n .replace(/[̀-ͯ]/g, \"\") // strip combining diacritics\n if (opts.stripScheme) s = s.replace(/^https?:\\/\\//, \"\")\n s = s\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/-{2,}/g, \"-\")\n .slice(0, maxLen)\n .replace(/^-+|-+$/g, \"\") // trim AFTER slicing, so a cut mid-dash can't leave one\n if (opts.leadingLetter && s && !/^[a-z]/.test(s)) {\n s = `e-${s}`.slice(0, maxLen).replace(/-+$/g, \"\")\n }\n return s.length >= 2 ? s : fallback\n}\n\n/**\n * Disambiguate a slug against a set of already-used ones by appending\n * `-2`, `-3`, … The suffix is numeric, so an entry-shaped base stays\n * entry-valid (ends alphanumeric).\n */\nexport function uniqueSlug(base: string, seen: Set<string>, maxLen = 96): string {\n let slug = base\n let n = 2\n while (seen.has(slug)) {\n slug = `${base}-${n++}`.slice(0, maxLen).replace(/-+$/g, \"\")\n }\n seen.add(slug)\n return slug\n}\n\n/** True when `s` is a valid AIP-10 source id (leading digit allowed). */\nexport function isSourceSlug(s: string): boolean {\n return SOURCE_SLUG.test(s) && s.length >= 2 && s.length <= 96\n}\n\n/** True when `s` is a valid AIP-10 entry/role/tag id (leading letter). */\nexport function isEntrySlug(s: string): boolean {\n return ENTRY_SLUG.test(s) && s.length >= 2 && s.length <= 96\n}\n","/**\n * Language-tag normalization — the single source of truth for coercing a\n * raw language value into the AIP-10 source shape `^[a-z]{2}(-[A-Z]{2})?$`.\n *\n * Two upstreams feed it, which is why this used to be two drifted copies:\n * - **STT** (Whisper verbose_json) emits a full English NAME (\"english\",\n * \"french\").\n * - **readability / browser** fetchers read `<html lang>` VERBATIM, in any\n * case and separator (\"en-us\", \"EN\", \"pt_BR\", \"zh-Hant-TW\").\n *\n * One function handles both: map a known name → code, else parse a BCP-47\n * tag — lowercase the 2-letter primary, uppercase a genuine 2-letter region,\n * and discard scripts / extensions / 3-letter primaries (which the AIP-10\n * source schema doesn't allow) rather than emit something that fails\n * validation. Returns `undefined` for anything unparseable so the field is\n * omitted, never written invalid.\n */\n\nconst NAME_TO_CODE: Readonly<Record<string, string>> = {\n english: \"en\", french: \"fr\", spanish: \"es\", german: \"de\", italian: \"it\",\n portuguese: \"pt\", dutch: \"nl\", russian: \"ru\", japanese: \"ja\", korean: \"ko\",\n chinese: \"zh\", arabic: \"ar\", hindi: \"hi\", turkish: \"tr\", polish: \"pl\",\n swedish: \"sv\", norwegian: \"no\", danish: \"da\", finnish: \"fi\", greek: \"el\",\n hebrew: \"he\", thai: \"th\", vietnamese: \"vi\", indonesian: \"id\", ukrainian: \"uk\",\n}\n\nexport function normalizeLanguageTag(raw: string | undefined): string | undefined {\n if (!raw) return undefined\n const v = raw.trim().toLowerCase()\n if (!v) return undefined\n const named = NAME_TO_CODE[v]\n if (named) return named\n // BCP-47: subtags split on \"-\" or \"_\" (POSIX locales like pt_BR appear in\n // <html lang>). Require a 2-letter primary; append only a 2-letter region.\n const parts = v.split(/[-_]/)\n const primary = parts[0]\n if (!primary || !/^[a-z]{2}$/.test(primary)) return undefined\n const region = parts.slice(1).find(p => /^[a-z]{2}$/.test(p))\n return region ? `${primary}-${region.toUpperCase()}` : primary\n}\n","/**\n * Attestation helpers — append + read the per-transition audit chain\n * stored under `metadata.corpus.attestations[]`.\n *\n * Pure. The lifecycle workflows (promote, playbook activate/archive,\n * playbook evaluator) call `appendAttestation` immediately before\n * writing the file. Tooling that displays the chain (curator UI,\n * `corpus events:trace <slug>`) calls `readAttestations`.\n */\n\nimport type { Attestation } from \"../types.js\"\n\n/**\n * Append an attestation to a frontmatter object's\n * `metadata.corpus.attestations[]`. Returns a NEW frontmatter\n * object — mutation-free so callers can chain transformations.\n *\n * If `metadata.corpus.attestations` doesn't exist, it's created. If\n * the new attestation is byte-identical to the last entry (same kind\n * + identity + at), it's a no-op (idempotent against\n * lifecycle workflow retries).\n */\nexport function appendAttestation(\n frontmatter: Readonly<Record<string, unknown>>,\n attestation: Attestation\n): Record<string, unknown> {\n const metaIn = (frontmatter.metadata as Record<string, unknown> | undefined) ?? {}\n const corpusIn =\n (metaIn.corpus as Record<string, unknown> | undefined) ?? {}\n const existing =\n (corpusIn.attestations as Attestation[] | undefined) ?? []\n const last = existing[existing.length - 1]\n if (\n last &&\n last.kind === attestation.kind &&\n last.identity === attestation.identity &&\n last.at === attestation.at\n ) {\n // Idempotent — don't duplicate on lifecycle retry.\n return { ...frontmatter }\n }\n return {\n ...frontmatter,\n metadata: {\n ...metaIn,\n corpus: {\n ...corpusIn,\n attestations: [...existing, attestation],\n },\n },\n }\n}\n\n/**\n * Read the attestation chain off a frontmatter object. Returns `[]`\n * if the entry has none (e.g. legacy entries written before the\n * attestation chain shipped).\n */\nexport function readAttestations(\n frontmatter: Readonly<Record<string, unknown>>\n): readonly Attestation[] {\n const meta = frontmatter.metadata as { corpus?: { attestations?: unknown } } | undefined\n const list = meta?.corpus?.attestations\n if (!Array.isArray(list)) return []\n return Object.freeze(list as Attestation[])\n}\n\n/**\n * Convenience: build an attestation from current clock + identity.\n * Lifecycle code typically calls this then immediately\n * `appendAttestation`.\n */\nexport function makeAttestation(input: {\n readonly kind: Attestation[\"kind\"]\n readonly identity: string\n readonly at: string\n readonly model?: string\n readonly promptHash?: string\n readonly note?: string\n}): Attestation {\n return Object.freeze({\n kind: input.kind,\n identity: input.identity,\n at: input.at,\n ...(input.model ? { model: input.model } : {}),\n ...(input.promptHash ? { promptHash: input.promptHash } : {}),\n ...(input.note ? { note: input.note } : {}),\n })\n}\n","/**\n * Access policy — pure logic that decides whether a caller can see a\n * piece of corpus content based on its `metadata.corpus.access` spec.\n *\n * Inputs:\n * spec — what the entry/source declares (classification + allowed refs)\n * caller — identityTree (resolved by IdentityPort)\n *\n * Output:\n * permitted: boolean\n * reason: human-readable\n * redact: bytes-redaction hint for getSource() (some classifications\n * let the caller see metadata but not body bytes)\n *\n * Default policy by classification:\n *\n * public — anyone can see (and read bytes)\n * internal — same-guild only (default for unmarked entries)\n * restricted — explicit allowedRoles / allowedOperators / allowedUsers\n * ONLY; classification fallback is deny\n * secret — same as restricted PLUS bytes are redacted for\n * callers below the bar (they see frontmatter, not body)\n *\n * Engines/UIs filter silently — no \"you have N results but can't see\n * them\" leakage to the caller below.\n */\n\nexport type AccessClassification =\n | \"public\"\n | \"internal\"\n | \"restricted\"\n | \"secret\"\n\nexport interface CorpusAccessSpec {\n readonly classification?: AccessClassification\n readonly allowedRoles?: readonly string[]\n readonly allowedOperators?: readonly string[]\n readonly allowedUsers?: readonly string[]\n readonly allowedGuilds?: readonly string[]\n readonly allowedOrgs?: readonly string[]\n /** Free-form host extension. */\n readonly metadata?: Readonly<Record<string, unknown>>\n}\n\nexport interface AccessCaller {\n /** identityTree most-specific → least-specific. */\n readonly identityTree: readonly string[]\n}\n\n/**\n * Per-evaluation context the adapter passes alongside the caller.\n * Distinct from the spec (entry-side) and the caller (subject-side);\n * this carries the *workspace-side* facts that classification rules\n * need but that the entry doesn't repeat per-row.\n */\nexport interface AccessContext {\n /**\n * Guild slug that owns the workspace this entry lives in (e.g.\n * \"acme-marketing\"). When set, the `internal` classification\n * requires the caller's identityTree to include\n * `ws://guilds/<homeGuild>` — i.e. an entry tagged internal is\n * visible only to that guild, not to anyone-in-any-guild.\n *\n * When omitted, `internal` falls back to \"fail-closed\" rather than\n * the old \"any-guild\" semantics, on the principle that an\n * unidentifiable workspace shouldn't leak its content.\n */\n readonly homeGuild?: string\n}\n\nexport interface AccessDecision {\n readonly permitted: boolean\n readonly reason: string\n /** For getSource — true means body bytes MUST be redacted. */\n readonly redactBytes: boolean\n}\n\nconst DEFAULT_CLASSIFICATION: AccessClassification = \"internal\"\n\n/**\n * Evaluate access for a caller against an access spec. Returns a\n * decision the caller (engine adapter, tool) uses to filter / redact.\n *\n * Missing `access` block in frontmatter = treat as `classification:\n * internal`, no explicit allow lists. Same-guild matches via the\n * identityTree.\n */\nexport function evaluateAccess(\n spec: CorpusAccessSpec | undefined,\n caller: AccessCaller,\n context: AccessContext = {}\n): AccessDecision {\n const classification = spec?.classification ?? DEFAULT_CLASSIFICATION\n\n // Explicit allow lists win across all classifications.\n if (spec) {\n if (matchesAllowed(\"roles\", spec.allowedRoles, caller))\n return permit(`allowedRoles match`, classification)\n if (matchesAllowed(\"operators\", spec.allowedOperators, caller))\n return permit(`allowedOperators match`, classification)\n if (matchesAllowed(\"users\", spec.allowedUsers, caller))\n return permit(`allowedUsers match`, classification)\n if (matchesAllowed(\"guilds\", spec.allowedGuilds, caller))\n return permit(`allowedGuilds match`, classification)\n if (matchesAllowed(\"orgs\", spec.allowedOrgs, caller))\n return permit(`allowedOrgs match`, classification)\n }\n\n switch (classification) {\n case \"public\":\n return {\n permitted: true,\n reason: \"classification=public\",\n redactBytes: false,\n }\n case \"internal\": {\n // Internal = scoped to the workspace's home guild. The host\n // (corpus-host) is expected to supply `context.homeGuild`; when\n // it does, the caller must hold that guild in their identity\n // tree. When omitted, fail-closed — an unidentifiable workspace\n // shouldn't leak via the broadest classification.\n if (!context.homeGuild) {\n return {\n permitted: false,\n reason:\n \"classification=internal but no homeGuild context — fail-closed\",\n redactBytes: false,\n }\n }\n const expected = `ws://guilds/${context.homeGuild}`\n const inHomeGuild = caller.identityTree.includes(expected)\n return {\n permitted: inHomeGuild,\n reason: inHomeGuild\n ? `classification=internal + caller in ${expected}`\n : `classification=internal but caller not in ${expected}`,\n redactBytes: false,\n }\n }\n case \"restricted\":\n return {\n permitted: false,\n reason:\n \"classification=restricted — caller not in any allowed list (roles/operators/users/guilds/orgs)\",\n redactBytes: false,\n }\n case \"secret\":\n return {\n permitted: false,\n reason:\n \"classification=secret — caller not in any allowed list; bytes redacted\",\n redactBytes: true,\n }\n default: {\n // Forward-compat — unknown classification fails closed.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const _exhaustive: never = classification\n return {\n permitted: false,\n reason: `unknown classification \"${String(classification)}\" — fail-closed`,\n redactBytes: true,\n }\n }\n }\n}\n\nfunction permit(\n reason: string,\n classification: AccessClassification\n): AccessDecision {\n // Even when explicitly allowed, secret content still has redactBytes\n // depend on classification — callers might want to expose\n // frontmatter only. For now, explicit allow = full access.\n return {\n permitted: true,\n reason: `${reason} (classification=${classification})`,\n redactBytes: false,\n }\n}\n\nfunction matchesAllowed(\n kind: \"roles\" | \"operators\" | \"users\" | \"guilds\" | \"orgs\",\n list: readonly string[] | undefined,\n caller: AccessCaller\n): boolean {\n if (!list || list.length === 0) return false\n const prefix = `ws://${kind}/`\n for (const ref of list) {\n // Tolerate both bare slugs and full ws:// refs in the allow list.\n const expanded = ref.startsWith(\"ws://\") ? ref : prefix + ref\n if (caller.identityTree.includes(expanded)) return true\n // Glob: \"ws://roles/*\" matches any role in the caller's tree.\n if (expanded === `${prefix}*`) {\n if (caller.identityTree.some((r) => r.startsWith(prefix))) return true\n }\n }\n return false\n}\n\n/**\n * Extract the access spec from a frontmatter object's\n * `metadata.corpus.access`. Returns undefined when the entry has\n * none — caller treats it as `internal` (the default).\n */\nexport function readAccessSpec(\n frontmatter: Readonly<Record<string, unknown>>\n): CorpusAccessSpec | undefined {\n const meta = frontmatter.metadata as { corpus?: { access?: unknown } } | undefined\n const access = meta?.corpus?.access\n if (!access || typeof access !== \"object\") return undefined\n return access as CorpusAccessSpec\n}\n","/**\n * Capability — uniform tool-boundary enforcement.\n *\n * Every corpus tool declares a required `Capability`. The host\n * (Guilde corpus.bundle / corpus-cli) calls `evaluateCapability` at\n * dispatch time. Capabilities are configured per-workspace under\n * `KNOWLEDGE.md.metadata.corpus.accessModes`.\n *\n * Pure logic. Audit + actual rejection happen in the host.\n */\n\nexport type Capability =\n | \"read\"\n | \"cite\"\n | \"flag-learning\"\n | \"curate\"\n | \"promote\"\n | \"activate-playbook\"\n | \"admin-reindex\"\n | \"bypass-default-filters\"\n\nexport interface CapabilityRule {\n readonly allowedRoles: readonly string[]\n /** Optional rate-limit hint — enforcement lives in the host. */\n readonly rateLimit?: {\n readonly perOperator?: number\n readonly window?: string\n }\n /** Requires curator approval before the action commits. */\n readonly requireApproval?: boolean\n /** Audit-log the call (default false). */\n readonly audit?: boolean\n}\n\nexport type AccessModesMap = Readonly<\n Partial<Record<Capability, CapabilityRule>>\n>\n\nexport interface CapabilityCaller {\n /** identityTree most-specific → least-specific. */\n readonly identityTree: readonly string[]\n}\n\nexport interface CapabilityDecision {\n readonly permitted: boolean\n readonly reason: string\n /** Rate-limit hint to enforce, if defined. */\n readonly rateLimit?: CapabilityRule[\"rateLimit\"]\n /** True if the tool MUST collect approval before committing. */\n readonly requireApproval: boolean\n /** True if the host should write an audit entry on completion. */\n readonly audit: boolean\n}\n\n/**\n * Sensible defaults applied when KNOWLEDGE.md doesn't declare a rule\n * for a given capability. Match the v1 plan's accessModes shape:\n *\n * read | cite | flag-learning → allowedRoles: [\"*\"] (anyone)\n * curate | promote → allowedRoles: [\"corpus-curator\", \"admin\"]\n * activate-playbook → same + requireApproval: true\n * admin-reindex → allowedRoles: [\"admin\"]\n * bypass-default-filters → curator/admin + audit: true\n */\nconst DEFAULT_RULES: Record<Capability, CapabilityRule> = Object.freeze({\n \"read\": { allowedRoles: [\"*\"] },\n \"cite\": { allowedRoles: [\"*\"] },\n \"flag-learning\": {\n allowedRoles: [\"*\"],\n rateLimit: { perOperator: 20, window: \"24h\" },\n },\n \"curate\": { allowedRoles: [\"corpus-curator\", \"admin\"] },\n \"promote\": { allowedRoles: [\"corpus-curator\", \"admin\"] },\n \"activate-playbook\": {\n allowedRoles: [\"corpus-curator\", \"admin\"],\n requireApproval: true,\n },\n \"admin-reindex\": { allowedRoles: [\"admin\"] },\n \"bypass-default-filters\": {\n allowedRoles: [\"corpus-curator\", \"admin\"],\n audit: true,\n },\n})\n\nexport function evaluateCapability(\n capability: Capability,\n accessModes: AccessModesMap | undefined,\n caller: CapabilityCaller\n): CapabilityDecision {\n const rule = accessModes?.[capability] ?? DEFAULT_RULES[capability]\n if (!rule) {\n return {\n permitted: false,\n reason: `unknown capability \"${capability}\"`,\n requireApproval: false,\n audit: true,\n }\n }\n const permitted = matchesRoles(rule.allowedRoles, caller.identityTree)\n return {\n permitted,\n reason: permitted\n ? `caller identity matches allowedRoles for \"${capability}\"`\n : `caller identity does NOT match allowedRoles for \"${capability}\"`,\n rateLimit: rule.rateLimit,\n requireApproval: !!rule.requireApproval,\n audit: !!rule.audit,\n }\n}\n\nfunction matchesRoles(\n allowed: readonly string[],\n identityTree: readonly string[]\n): boolean {\n if (allowed.includes(\"*\")) return true\n for (const role of allowed) {\n // Accept both bare slugs and full ws:// refs in the rule.\n const expanded = role.startsWith(\"ws://\") ? role : `ws://roles/${role}`\n if (identityTree.includes(expanded)) return true\n }\n return false\n}\n\n/**\n * Read accessModes from a parsed KNOWLEDGE.md workspace\n * frontmatter. Returns undefined if not declared — caller uses\n * DEFAULT_RULES.\n */\nexport function readAccessModes(\n workspaceFrontmatter: Readonly<Record<string, unknown>>\n): AccessModesMap | undefined {\n const meta = workspaceFrontmatter.metadata as\n | { corpus?: { accessModes?: unknown } }\n | undefined\n const am = meta?.corpus?.accessModes\n if (!am || typeof am !== \"object\") return undefined\n return am as AccessModesMap\n}\n","/**\n * Language filtering — pure helpers for BCP-47 locale matching.\n *\n * Where language lives:\n * - AIP-10 source: native top-level `language` field (already in spec).\n * - AIP-10 entry: under `metadata.corpus.language` until the AIP-10\n * spec hoists `language` to first-class on entries.\n * - Workspace default: `KNOWLEDGE.md.metadata.corpus.languages.default`.\n * - Operator locale: `OPERATOR.md.metadata.corpus.locale`.\n *\n * Default filter: an entry surfaces to an operator if its language\n * matches the operator's locale OR matches the workspace default\n * (typically en-US so generic principles aren't locale-gated). Empty\n * `language` on the entry = treat as the workspace default (it's\n * almost always the corpus's home language).\n *\n * Locale matching is loose (`en` matches `en-US` / `en-GB`) so we\n * don't drown the user in misses on regional variants.\n */\n\nexport interface ResolveLanguageFilterInput {\n /** BCP-47 locale the caller is operating in. */\n readonly callerLocale?: string\n /**\n * Default language declared in `KNOWLEDGE.md.metadata.corpus.languages.default`.\n * Used as the implicit language for entries that don't declare one.\n */\n readonly workspaceDefaultLanguage?: string\n}\n\nexport interface LanguageFilter {\n /**\n * The set of language codes that surface. Used by middleware to\n * filter hits silently. Empty set = no language filter (everyone\n * sees everything; happens when neither caller nor workspace\n * declares a language).\n */\n readonly allowedLanguages: ReadonlySet<string>\n /**\n * Whether entries with no declared language should pass through.\n * True when the workspace declares a default — those entries\n * inherit it.\n */\n readonly allowUnspecified: boolean\n}\n\nexport function resolveLanguageFilter(\n input: ResolveLanguageFilterInput\n): LanguageFilter {\n const set = new Set<string>()\n if (input.callerLocale) addExpansions(set, input.callerLocale)\n if (input.workspaceDefaultLanguage)\n addExpansions(set, input.workspaceDefaultLanguage)\n return Object.freeze({\n allowedLanguages: set,\n // If a workspace default exists, entries without an explicit\n // language inherit it → pass-through. If neither caller nor\n // workspace declares one, the filter is effectively off (everyone\n // surfaces; the helper isn't called for cross-language scoping).\n allowUnspecified:\n set.size === 0 ? true : input.workspaceDefaultLanguage != null,\n })\n}\n\nexport function matchesLanguageFilter(\n entryLanguage: string | undefined,\n filter: LanguageFilter\n): boolean {\n if (filter.allowedLanguages.size === 0) return true // no filter\n if (!entryLanguage) return filter.allowUnspecified\n // Exact + loose (en-US matches en) — try both directions for\n // tolerance.\n const lower = entryLanguage.toLowerCase()\n if (filter.allowedLanguages.has(lower)) return true\n const baseLang = lower.split(\"-\")[0]\n if (baseLang && filter.allowedLanguages.has(baseLang)) return true\n // Caller had \"en\", entry has \"en-US\" → also accept.\n for (const allowed of filter.allowedLanguages) {\n if (lower.startsWith(allowed + \"-\")) return true\n }\n return false\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\nfunction addExpansions(set: Set<string>, locale: string): void {\n const lower = locale.toLowerCase()\n set.add(lower)\n const base = lower.split(\"-\")[0]\n if (base) set.add(base)\n}\n\n/**\n * Convenience: read the operator's locale from frontmatter.\n * Falls back to undefined when not declared.\n */\nexport function readOperatorLocale(\n operatorFrontmatter: Readonly<Record<string, unknown>>\n): string | undefined {\n const meta = operatorFrontmatter.metadata as\n | { corpus?: { locale?: unknown } }\n | undefined\n const l = meta?.corpus?.locale\n return typeof l === \"string\" ? l : undefined\n}\n\n/**\n * Read the workspace's default language from KNOWLEDGE.md.\n */\nexport function readWorkspaceDefaultLanguage(\n workspaceFrontmatter: Readonly<Record<string, unknown>>\n): string | undefined {\n const meta = workspaceFrontmatter.metadata as\n | { corpus?: { languages?: { default?: unknown } } }\n | undefined\n const def = meta?.corpus?.languages?.default\n return typeof def === \"string\" ? def : undefined\n}\n\n/**\n * Read an entry / source's language. Sources expose it at top level\n * (AIP-10 spec); entries put it under `metadata.corpus.language`\n * until the corresponding AIP-10 amendment lands.\n */\nexport function readEntryLanguage(\n frontmatter: Readonly<Record<string, unknown>>\n): string | undefined {\n const top = frontmatter.language\n if (typeof top === \"string\") return top\n const meta = frontmatter.metadata as\n | { corpus?: { language?: unknown } }\n | undefined\n const corp = meta?.corpus?.language\n return typeof corp === \"string\" ? corp : undefined\n}\n","/**\n * CorpusEventEmitter — append-only writer for `_log.md`.\n *\n * The corpus' audit trail. Every state transition (candidate\n * discovered/analyzed/approved/rejected, entry promoted/deprecated,\n * playbook activated/archived, gap opened/resolved) appends one line\n * here.\n *\n * Line format (NDJSON-ish, but inside a markdown file for AIP-10\n * conformance — _log.md is the canonical AIP-10 log doctype):\n *\n * - {ISO} {kind} by {actor} payload={JSON}\n *\n * Concrete:\n *\n * - 2026-05-22T14:30:00.000Z corpus.entry.promoted by ws://operators/corpus-curator payload={\"slug\":\"contrarian-short-form-hooks\",\"kind\":\"pattern\"}\n *\n * Why line-per-event (not blocks): every host needs to grep / tail /\n * stream the log without a markdown parser. Inside an .md file =\n * AIP-10 conformant; line-format = ops-friendly.\n *\n * Atomicity: relies on FsPort.appendFile being atomic against\n * concurrent appends. Hosts MUST honor that — cloud topology uses\n * append APIs (S3 Express, GCS), local topology uses POSIX append\n * (atomic up to PIPE_BUF).\n */\n\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type { ClockPort } from \"../ports/clock.port.js\"\nimport type { IdentityPort } from \"../ports/identity.port.js\"\nimport type {\n CorpusEvent,\n CorpusEventKind,\n} from \"../types.js\"\n\nexport interface CorpusEventEmitterOptions {\n readonly fs: FsPort\n readonly clock: ClockPort\n readonly identity: IdentityPort\n /**\n * Workspace root the emitter targets — `_log.md` is written\n * relative to this. Hosts that mount multiple corpora pass one\n * emitter per workspace root.\n */\n readonly workspaceRoot: string\n}\n\nexport class CorpusEventEmitter {\n constructor(private readonly opts: CorpusEventEmitterOptions) {}\n\n /**\n * Emit one event. Returns the event as written (including the\n * ISO timestamp and actor resolved at emit time). The .md log file\n * is created on first append if missing.\n */\n async emit(\n kind: CorpusEventKind,\n payload: Readonly<Record<string, unknown>>\n ): Promise<CorpusEvent> {\n const identity = await this.opts.identity.resolve()\n const event: CorpusEvent = {\n kind,\n at: this.opts.clock.now().toISOString(),\n actor: identity.principal,\n payload,\n }\n const logPath = joinPath(this.opts.workspaceRoot, \"_log.md\")\n const line = formatLine(event) + \"\\n\"\n\n // Initialize the log file with an AIP-10 conformant header on\n // first write, so a fresh corpus' _log.md is also a valid\n // markdown doc (not just a JSON-lines stream).\n if (!(await this.opts.fs.exists(logPath))) {\n await this.opts.fs.writeFile(\n logPath,\n \"# Corpus activity log\\n\\n\" +\n \"Append-only AIP-10 log of corpus state transitions. Each line:\\n\" +\n \"`- <iso> <kind> by <actor> payload=<json>`\\n\\n\"\n )\n }\n await this.opts.fs.appendFile(logPath, line)\n return event\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────\n\nfunction formatLine(event: CorpusEvent): string {\n // Compact JSON keeps lines greppable. Sort keys for deterministic\n // diffs across emitters running on the same workspace.\n const payload = JSON.stringify(event.payload, [...Object.keys(event.payload).sort()])\n return `- ${event.at} ${event.kind} by ${event.actor} payload=${payload}`\n}\n\nfunction joinPath(a: string, b: string): string {\n if (!a) return b\n return a.endsWith(\"/\") ? a + b : a + \"/\" + b\n}\n","/**\n * CorpusWorkspaceReader — scan + parse a corpus workspace via FsPort.\n *\n * Pure path-discipline + YAML parsing — no schema validation here. The\n * reader's job is to surface every .md file in the workspace and\n * classify it by location. Schema validation happens in\n * `validate/validator.ts` so callers can run both in parallel and get\n * crisp error categorization.\n *\n * Pure: no `node:fs`, no `node:path`. All paths are joined manually\n * with \"/\" so the kit runs on Node, Bun, Deno, and browser-side\n * editors (e.g. curator UI lint preview).\n */\n\nimport matter from \"gray-matter\"\nimport { createHash } from \"node:crypto\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type {\n CorpusWorkspaceSnapshot,\n FileKind,\n ParsedFile,\n} from \"../types.js\"\n\nexport interface CorpusWorkspaceReaderOptions {\n readonly fs: FsPort\n}\n\nexport class CorpusWorkspaceReader {\n constructor(private readonly opts: CorpusWorkspaceReaderOptions) {}\n\n /**\n * Scan the workspace rooted at `root` and return a typed snapshot.\n * `root` is workspace-relative (the host resolves to a backing\n * storage); commonly \"\" for the workspace root itself.\n */\n async read(root: string): Promise<CorpusWorkspaceSnapshot> {\n const files = await this.opts.fs.walk(root)\n const mdFiles = files.filter((p) => p.endsWith(\".md\"))\n\n const buckets: Record<FileKind, ParsedFile[]> = {\n \"knowledge-workspace\": [],\n \"knowledge-source\": [],\n \"knowledge-entry\": [],\n \"collection-schema\": [],\n \"collection-item\": [],\n \"playbook\": [],\n \"operator\": [],\n \"workflow\": [],\n \"routine\": [],\n \"unknown\": [],\n }\n\n for (const path of mdFiles) {\n const content = await this.opts.fs.readFile(path)\n const parsed = matter(content)\n const file: ParsedFile = {\n // Workspace-relative path. The walk returns paths anchored at\n // the host's storage root (which already includes `root` for\n // non-empty workspaces — see GuildWorkspaceFsAdapter.walk),\n // so we strip `root` here to match the documented contract\n // (\"paths returned are workspace-relative\"). Without this,\n // call sites that re-join `workspacePath + file.path` (the\n // playbook lifecycle, the evaluator, the promoter's CAS write)\n // double-prefix the path and the next read/CAS misses,\n // surfacing as CorpusVersionConflictError.\n path: stripRoot(path, root),\n kind: classify(path, root),\n frontmatter: (parsed.data ?? {}) as Readonly<Record<string, unknown>>,\n body: parsed.content,\n versionToken: sha256(content),\n }\n buckets[file.kind].push(file)\n }\n\n return {\n root,\n workspace: buckets[\"knowledge-workspace\"][0] ?? null,\n sources: freeze(buckets[\"knowledge-source\"]),\n entries: freeze(buckets[\"knowledge-entry\"]),\n collections: freeze(buckets[\"collection-schema\"]),\n collectionItems: freeze(buckets[\"collection-item\"]),\n playbooks: freeze(buckets[\"playbook\"]),\n operators: freeze(buckets[\"operator\"]),\n workflows: freeze(buckets[\"workflow\"]),\n routines: freeze(buckets[\"routine\"]),\n unknown: freeze(buckets[\"unknown\"]),\n }\n }\n}\n\n// ── Classification ─────────────────────────────────────────────────────\n\n/**\n * Classify a workspace-relative path by AIP convention.\n *\n * Important: the reader does NOT consult frontmatter to decide. Location\n * is authoritative — a file at `entries/principles/foo.md` is always\n * \"knowledge-entry\" even if its frontmatter is wrong. The validator\n * later surfaces the mismatch as a structured error.\n */\nfunction classify(path: string, root: string): FileKind {\n const rel = stripRoot(path, root)\n const segs = rel.split(\"/\").filter(Boolean)\n const fname = segs[segs.length - 1] ?? \"\"\n\n if (segs.length === 1 && fname === \"KNOWLEDGE.md\") return \"knowledge-workspace\"\n\n const top = segs[0]\n switch (top) {\n case \"sources\":\n return \"knowledge-source\"\n case \"entries\":\n return \"knowledge-entry\"\n case \"collections\":\n if (fname === \"COLLECTION.md\") return \"collection-schema\"\n if (fname === \"ITEM.md\" || /^[a-z0-9][a-z0-9-]*\\.md$/.test(fname))\n return \"collection-item\"\n return \"unknown\"\n case \"playbooks\":\n if (fname === \"PLAYBOOK.md\") return \"playbook\"\n return \"unknown\"\n case \"operators\":\n if (fname === \"OPERATOR.md\") return \"operator\"\n return \"unknown\"\n case \"workflows\":\n if (fname === \"WORKFLOW.md\") return \"workflow\"\n return \"unknown\"\n case \"routines\":\n if (fname === \"ROUTINE.md\") return \"routine\"\n return \"unknown\"\n default:\n return \"unknown\"\n }\n}\n\nfunction stripRoot(path: string, root: string): string {\n if (!root) return path\n const prefix = root.endsWith(\"/\") ? root : root + \"/\"\n return path.startsWith(prefix) ? path.slice(prefix.length) : path\n}\n\nfunction sha256(content: string): string {\n return \"sha256:\" + createHash(\"sha256\").update(content).digest(\"hex\")\n}\n\nfunction freeze<T>(arr: T[]): readonly T[] {\n return Object.freeze([...arr])\n}\n","/**\n * CorpusWorkspaceWriter — atomic file writes with versionToken\n * optimistic-concurrency guard.\n *\n * Every write goes through `writeFile(path, content, expected?)`:\n * - If `expected` is provided, the writer reads the current file's\n * content hash and refuses to write if it doesn't match → throws\n * CorpusVersionConflictError. Caller retries with the fresh\n * versionToken.\n * - If `expected` is null, the writer requires the file to NOT\n * exist (create-only).\n * - If `expected` is undefined, the writer overwrites unconditionally\n * (use sparingly — bypasses the concurrency-correctness story).\n *\n * Multi-file transactions (e.g. promote entry + update _index.md +\n * append _log.md) use FsPort.lock on a sentinel path so concurrent\n * promoters serialize cleanly.\n *\n * The writer is the ONLY component allowed to call FsPort.writeFile\n * for workspace content. The reader/validator/linter never write.\n * The event emitter writes only _log.md via append.\n */\n\nimport { createHash } from \"node:crypto\"\nimport matter from \"gray-matter\"\nimport type { FsPort, FsLockHandle } from \"../ports/fs.port.js\"\n\nexport class CorpusVersionConflictError extends Error {\n constructor(\n readonly path: string,\n readonly expected: string,\n readonly actual: string\n ) {\n super(\n `CorpusVersionConflictError: ${path} versionToken mismatch — expected ${expected}, found ${actual}. Re-read the file and retry with the fresh token.`\n )\n this.name = \"CorpusVersionConflictError\"\n }\n}\n\nexport interface CorpusWorkspaceWriterOptions {\n readonly fs: FsPort\n}\n\n/**\n * Frontmatter + body source pair, used by helpers like `writeEntry`\n * that need to serialize the .md back from structured data.\n */\nexport interface MarkdownDoc {\n readonly frontmatter: Readonly<Record<string, unknown>>\n readonly body: string\n}\n\nexport class CorpusWorkspaceWriter {\n constructor(private readonly opts: CorpusWorkspaceWriterOptions) {}\n\n /**\n * Compute the versionToken for raw file content. Exposed so the\n * caller can stage a write and pass the same hash function used\n * inside the writer.\n */\n static versionTokenOf(content: string): string {\n return \"sha256:\" + createHash(\"sha256\").update(content).digest(\"hex\")\n }\n\n /**\n * Atomic write with optimistic concurrency check.\n *\n * - expected === undefined → unconditional overwrite (use sparingly)\n * - expected === null → create-only (refuses if exists)\n * - expected === string → CAS check (refuses if current hash differs)\n *\n * Returns the new versionToken on success.\n */\n async writeFile(\n path: string,\n content: string,\n expected?: string | null\n ): Promise<string> {\n if (expected === null) {\n if (await this.opts.fs.exists(path)) {\n throw new CorpusVersionConflictError(path, \"<must-not-exist>\", \"<exists>\")\n }\n } else if (typeof expected === \"string\") {\n const existing = await this.opts.fs.exists(path)\n if (!existing) {\n throw new CorpusVersionConflictError(path, expected, \"<missing>\")\n }\n const current = await this.opts.fs.readFile(path)\n const actual = CorpusWorkspaceWriter.versionTokenOf(current)\n if (actual !== expected) {\n throw new CorpusVersionConflictError(path, expected, actual)\n }\n }\n await this.opts.fs.writeFile(path, content)\n return CorpusWorkspaceWriter.versionTokenOf(content)\n }\n\n /**\n * Serialize a markdown doc (frontmatter + body) and write atomically.\n * Frontmatter keys are stringified in a stable order so version\n * tokens are deterministic across emitter rebuilds.\n */\n async writeMarkdown(\n path: string,\n doc: MarkdownDoc,\n expected?: string | null\n ): Promise<string> {\n const content = serializeMarkdown(doc)\n return this.writeFile(path, content, expected)\n }\n\n /**\n * Run `fn` while holding a workspace-scoped lock. Used for\n * multi-file transactions (promote entry + update _index.md + log\n * append). The lock path is host-specific; we default to\n * `_log.md` because it's the file every transaction touches.\n *\n * `lockPath` is workspace-relative.\n */\n async transaction<T>(\n lockPath: string,\n fn: () => Promise<T>\n ): Promise<T> {\n let handle: FsLockHandle | null = null\n try {\n handle = await this.opts.fs.lock(lockPath)\n return await fn()\n } finally {\n if (handle) await handle.release()\n }\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────\n\n/**\n * Serialize a MarkdownDoc back to `--- frontmatter --- body` form.\n * gray-matter's `stringify` does this; we wrap it for the deterministic\n * key-order convention.\n */\nfunction serializeMarkdown(doc: MarkdownDoc): string {\n // gray-matter.stringify takes (content, data) — body first, then\n // frontmatter object.\n return matter.stringify(doc.body.startsWith(\"\\n\") ? doc.body : \"\\n\" + doc.body, doc.frontmatter)\n}\n","/**\n * ImporterRunner — drives a CorpusImporter to actually land files\n * + candidate rows in the workspace.\n *\n * Importers themselves are pure source-of-data — they yield\n * `ImportedSource`. The runner is where I/O lives: archives sources\n * to `sources/<importerId>/<batchId>/`, appends `_candidates.yaml`\n * rows, dedups against existing sources by `content_hash`, emits a\n * `corpus.candidate.discovered` event per imported source.\n *\n * Same fs+writer+emitter pattern as the rest of the corpus lifecycle.\n */\n\nimport matter from \"gray-matter\"\nimport { CorpusEventEmitter } from \"../events/emitter.js\"\nimport { CorpusWorkspaceReader } from \"../workspace/reader.js\"\nimport { CorpusWorkspaceWriter } from \"../workspace/writer.js\"\nimport { CandidatesSidecar } from \"../workspace/sidecar.js\"\nimport { isSourceSlug } from \"../util/slug.js\"\nimport type { ClockPort } from \"../ports/clock.port.js\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type { IdentityPort } from \"../ports/identity.port.js\"\nimport type { CandidateRow } from \"../workspace/sidecar.js\"\nimport type {\n BatchReport,\n CorpusImporter,\n ImportedSource,\n ImporterRunnerOptions,\n ImporterTarget,\n} from \"./types.js\"\n\nconst SIDECAR_PATH = \"collections/corpus-candidate/_candidates.yaml\"\n\nexport class ImporterRunner {\n constructor(\n private readonly opts: {\n readonly fs: FsPort\n readonly clock: ClockPort\n readonly identity: IdentityPort\n readonly workspacePath: string\n readonly runner?: ImporterRunnerOptions\n }\n ) {}\n\n /**\n * Run a single importer batch end-to-end.\n *\n * 1. Pre-load existing source content_hashes for dedup.\n * 2. For each source the importer yields:\n * a. Skip if hash already exists in the workspace.\n * b. Otherwise write AIP-10 source frontmatter + body to\n * `sources/<importerId>/<batchId>/<slug>.md`.\n * c. Append candidate row to `_candidates.yaml`.\n * 3. Emit `corpus.candidate.discovered` per archived source.\n *\n * Atomic per-source (each source archived + candidate written\n * inside one writer.transaction).\n */\n async run(\n importer: CorpusImporter,\n target: ImporterTarget\n ): Promise<BatchReport> {\n const fs = this.opts.fs\n const writer = new CorpusWorkspaceWriter({ fs })\n const reader = new CorpusWorkspaceReader({ fs })\n const sidecar = new CandidatesSidecar({\n fs,\n path: joinPath(this.opts.workspacePath, SIDECAR_PATH),\n })\n const emitter = new CorpusEventEmitter({\n fs,\n clock: this.opts.clock,\n identity: this.opts.identity,\n workspaceRoot: this.opts.workspacePath,\n })\n\n const batchId = target.batchId ?? this.opts.clock.now().toISOString().slice(0, 10)\n const archiveDirSegment = `sources/${target.importerId}/${batchId}`\n\n // Pre-load existing content_hashes for dedup. O(n) one-shot scan.\n const snapshot = await reader.read(this.opts.workspacePath)\n const existingHashes = new Set<string>()\n for (const file of snapshot.sources) {\n const h = file.frontmatter.content_hash\n if (typeof h === \"string\") existingHashes.add(h)\n }\n\n const archivedSlugs: string[] = []\n const duplicateSlugs: string[] = []\n const candidateIds: string[] = []\n const warnings: string[] = []\n\n for await (const source of importer.enumerate(target)) {\n if (!isSourceSlug(source.slug)) {\n warnings.push(`source skipped — invalid slug \"${source.slug}\"`)\n continue\n }\n if (existingHashes.has(source.contentHash)) {\n duplicateSlugs.push(source.slug)\n continue\n }\n existingHashes.add(source.contentHash) // dedup within batch too\n\n const sourcePath = joinPath(\n this.opts.workspacePath,\n `${archiveDirSegment}/${source.slug}.md`\n )\n const sourceContent = serializeSource(source, archiveDirSegment, this.opts.clock)\n // Create-only — if the slug somehow collides with an existing file,\n // surface it as a warning and skip.\n try {\n await writer.writeFile(sourcePath, sourceContent, null)\n } catch (err) {\n warnings.push(\n `source \"${source.slug}\" — slug collision in ${archiveDirSegment} (${\n err instanceof Error ? err.message : \"unknown\"\n }); skipped`\n )\n continue\n }\n archivedSlugs.push(source.slug)\n\n // Append candidate row. Use the importer's optional toCandidate\n // mapper if provided; otherwise default to corpusKind=example.\n const toCandidate =\n this.opts.runner?.toCandidate ?? defaultToCandidate\n const sourceId = source.slug\n const row = toCandidate(source, sourceId)\n try {\n await sidecar.append(row)\n candidateIds.push(row.id)\n } catch (err) {\n warnings.push(\n `candidate \"${row.id}\" — sidecar append failed (${\n err instanceof Error ? err.message : \"unknown\"\n })`\n )\n }\n\n // Audit event per archived source.\n await emitter\n .emit(\"corpus.candidate.discovered\", {\n id: row.id,\n importerId: target.importerId,\n batchId,\n contentHash: source.contentHash,\n provenanceKind: `imported-from-${target.importerId}`,\n })\n .catch(() => undefined)\n }\n\n return Object.freeze({\n importerId: target.importerId,\n batchId,\n archivedSlugs: Object.freeze(archivedSlugs),\n duplicateSlugs: Object.freeze(duplicateSlugs),\n candidateIds: Object.freeze(candidateIds),\n warnings: Object.freeze(warnings),\n })\n }\n}\n\n// ── Defaults + helpers ─────────────────────────────────────────────\n\nfunction defaultToCandidate(\n s: ImportedSource,\n sourceId: string\n): CandidateRow {\n return {\n id: sourceId,\n status: \"discovered\",\n corpusKind: \"example\",\n sourcePath: undefined, // filled in by archiver via path mapping\n sourceUrl: s.originalUrl,\n contentHash: s.contentHash,\n title: s.title,\n summary: undefined,\n discoveredAt: new Date().toISOString(),\n discoveredBy: \"ws://operators/importer-runner\",\n provenanceKind: \"imported\",\n }\n}\n\nfunction serializeSource(\n source: ImportedSource,\n archiveDirSegment: string,\n clock: ClockPort\n): string {\n const fm: Record<string, unknown> = {\n schema: \"knowledge.source/v1\",\n id: source.slug,\n path: `${archiveDirSegment}/${source.slug}.md`,\n title: source.title,\n captured_at: clock.now().toISOString(),\n content_hash: source.contentHash,\n authority: source.authority ?? \"secondary\",\n }\n if (source.language) fm.language = source.language\n if (source.tags && source.tags.length > 0) fm.tags = source.tags\n if (source.originalUrl || source.corpusMetadata) {\n fm.metadata = {\n corpus: {\n ...(source.originalUrl ? { originalUrl: source.originalUrl } : {}),\n ...(source.corpusMetadata ?? {}),\n },\n }\n }\n return matter.stringify(\n source.body.startsWith(\"\\n\") ? source.body : \"\\n\" + source.body,\n fm\n )\n}\n\nfunction joinPath(a: string, b: string): string {\n if (!a) return b\n return a.endsWith(\"/\") ? a + b : a + \"/\" + b\n}\n","/**\n * LocalFilesImporter — reads .md files from a configured FsPort path\n * and yields them as ImportedSource. Reference implementation that\n * proves the importer surface end-to-end without external SDKs.\n *\n * Config (target.config):\n * - rootPath: string — workspace-relative path to scan\n * - extensions?: string[] — defaults to [\".md\"]\n * - maxFiles?: number — defaults to 1000\n * - tags?: string[] — applied to every imported source\n * - language?: string — applied to every source (BCP-47)\n *\n * Pure kit code — consumes FsPort, no node:fs / no network.\n *\n * Slug derivation: filename without extension, lowercased + slug-safed.\n * Content hash: sha256 of UTF-8 body bytes.\n */\n\nimport { createHash } from \"node:crypto\"\nimport { slugify } from \"../util/slug.js\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type {\n CorpusImporter,\n ImportedSource,\n ImporterTarget,\n} from \"./types.js\"\n\nexport interface LocalFilesImporterOptions {\n readonly fs: FsPort\n}\n\ninterface LocalFilesConfig {\n readonly rootPath: string\n readonly extensions?: readonly string[]\n readonly maxFiles?: number\n readonly tags?: readonly string[]\n readonly language?: string\n}\n\nexport class LocalFilesImporter implements CorpusImporter {\n readonly id = \"local-files\"\n readonly label = \"Local Files\"\n\n constructor(private readonly opts: LocalFilesImporterOptions) {}\n\n async *enumerate(target: ImporterTarget): AsyncIterable<ImportedSource> {\n const config = parseConfig(target.config)\n const exts = new Set(config.extensions ?? [\".md\"])\n const maxFiles = config.maxFiles ?? 1000\n const paths = await this.opts.fs.walk(config.rootPath)\n let yielded = 0\n for (const p of paths) {\n if (yielded >= maxFiles) break\n const ext = pickExt(p)\n if (!exts.has(ext)) continue\n const body = await this.opts.fs.readFile(p)\n const slug = makeSlug(p, config.rootPath)\n const contentHash = sha256(body)\n const title = readTitleFromBody(body, slug)\n yield {\n slug,\n title,\n contentHash,\n body,\n authority: \"secondary\",\n ...(config.language ? { language: config.language } : {}),\n ...(config.tags && config.tags.length > 0 ? { tags: config.tags } : {}),\n corpusMetadata: {\n importerSourcePath: p,\n importerRoot: config.rootPath,\n },\n }\n yielded++\n }\n }\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\nfunction parseConfig(raw: Readonly<Record<string, unknown>>): LocalFilesConfig {\n if (typeof raw.rootPath !== \"string\") {\n throw new Error(\n `LocalFilesImporter: config.rootPath is required (string)`\n )\n }\n const cfg: LocalFilesConfig = {\n rootPath: raw.rootPath,\n extensions: Array.isArray(raw.extensions)\n ? (raw.extensions as unknown[]).filter(\n (x): x is string => typeof x === \"string\"\n )\n : undefined,\n maxFiles: typeof raw.maxFiles === \"number\" ? raw.maxFiles : undefined,\n tags: Array.isArray(raw.tags)\n ? (raw.tags as unknown[]).filter(\n (x): x is string => typeof x === \"string\"\n )\n : undefined,\n language: typeof raw.language === \"string\" ? raw.language : undefined,\n }\n return cfg\n}\n\nfunction pickExt(path: string): string {\n const i = path.lastIndexOf(\".\")\n if (i < 0) return \"\"\n return path.slice(i).toLowerCase()\n}\n\nfunction makeSlug(path: string, rootPath: string): string {\n // Slug from the root-relative path, extension stripped. Source ids may\n // start with a digit, so no leading-letter constraint here.\n const rel = path.startsWith(rootPath) ? path.slice(rootPath.length) : path\n const stripped = rel.replace(/^\\/+/, \"\").replace(/\\.[^.]+$/, \"\")\n return slugify(stripped, { fallback: \"source\" })\n}\n\nfunction readTitleFromBody(body: string, fallback: string): string {\n // First markdown H1 line, or the filename slug.\n const m = body.match(/^\\s*#\\s+(.+)$/m)\n if (m && m[1]) return m[1].trim().slice(0, 200)\n return fallback\n}\n\nfunction sha256(content: string): string {\n return \"sha256:\" + createHash(\"sha256\").update(content).digest(\"hex\")\n}\n","/**\n * KbMigrationImporter — turn an existing knowledge base into a\n * stream of `ImportedSource` for the runner.\n *\n * Use case: a guild already has a populated qdrant/gbrain KB row\n * with N documents. Day-1 corpus onboarding shouldn't be \"abandon\n * your knowledge and start over\" — this importer reads the source\n * KB via its IKnowledgeProvider, materializes each source as an\n * importable, and the runner archives them into `sources/` +\n * appends candidates. The source KB stays intact (read-only).\n *\n * The minimal IKnowledgeProvider-like shape we consume — keeps the\n * kit decoupled from @agstudio/integration-knowledge.\n *\n * Each migrated source carries `provenanceKind: imported-from-kb`\n * and `sourceKbId` in `metadata.corpus` so curators can trace which\n * KB row each item came from.\n */\n\nimport { createHash } from \"node:crypto\"\nimport type {\n CorpusImporter,\n ImportedSource,\n ImporterTarget,\n} from \"./types.js\"\n\n/**\n * Structural shape — any IKnowledgeProvider satisfies it. We don't\n * import IKnowledgeProvider directly to keep the kit dep-free.\n */\nexport interface KbListLike {\n listSources(): Promise<readonly KbSourceLike[]>\n}\n\nexport interface KbSourceLike {\n readonly id: string\n readonly kind: string\n readonly uri: string\n readonly title?: string\n readonly bytes: number\n readonly metadata: Readonly<Record<string, unknown>>\n}\n\nexport interface KbMigrationConfig {\n /** Stable id of the source KB (used in provenance + archive path). */\n readonly sourceKbId: string\n /** Live provider instance from the source KB. */\n readonly provider: KbListLike\n /**\n * Optional fetcher for the body of each source. The migration\n * importer enumerates source METADATA from listSources(); to\n * archive the actual content, the host must supply a way to fetch\n * the body. If omitted, sources are imported with an empty body +\n * a note pointing back to the source KB.\n */\n readonly fetchBody?: (sourceId: string) => Promise<string>\n /** Optional max sources to import this batch. */\n readonly maxSources?: number\n}\n\nexport class KbMigrationImporter implements CorpusImporter {\n readonly id = \"kb-migration\"\n readonly label = \"Migrate from existing KB\"\n\n async *enumerate(target: ImporterTarget): AsyncIterable<ImportedSource> {\n const config = parseKbMigrationConfig(target.config)\n const sources = await config.provider.listSources()\n const max = config.maxSources ?? sources.length\n let yielded = 0\n for (const s of sources) {\n if (yielded >= max) break\n const body = config.fetchBody\n ? await config.fetchBody(s.id)\n : `(Migrated from KB ${config.sourceKbId}, source id=${s.id}. Body fetcher not configured — archive contains metadata only.)`\n const slug = slugifyKbSource(s.id, config.sourceKbId)\n yield {\n slug,\n title: s.title ?? s.id,\n contentHash: hashKbSource(s, body),\n body,\n originalUrl: typeof s.uri === \"string\" ? s.uri : undefined,\n authority: \"secondary\",\n corpusMetadata: {\n provenanceKind: \"imported-from-kb\",\n sourceKbId: config.sourceKbId,\n sourceKbSourceId: s.id,\n sourceKbBytes: s.bytes,\n sourceKbKind: s.kind,\n // Carry the original KB's metadata through verbatim so\n // curators can see what was lost in translation.\n sourceKbMetadata: s.metadata,\n },\n }\n yielded++\n }\n }\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\nfunction parseKbMigrationConfig(\n raw: Readonly<Record<string, unknown>>\n): KbMigrationConfig {\n const sourceKbId = raw.sourceKbId\n const provider = raw.provider\n if (typeof sourceKbId !== \"string\") {\n throw new Error(\"KbMigrationImporter: config.sourceKbId required (string)\")\n }\n if (!provider || typeof provider !== \"object\" || typeof (provider as KbListLike).listSources !== \"function\") {\n throw new Error(\n \"KbMigrationImporter: config.provider required (must implement listSources)\"\n )\n }\n return {\n sourceKbId,\n provider: provider as KbListLike,\n fetchBody:\n typeof raw.fetchBody === \"function\"\n ? (raw.fetchBody as (id: string) => Promise<string>)\n : undefined,\n maxSources:\n typeof raw.maxSources === \"number\" ? raw.maxSources : undefined,\n }\n}\n\nfunction slugifyKbSource(id: string, kbId: string): string {\n // Prefix with kbId so two KBs migrating sources with overlapping\n // ids don't collide in `sources/<importer>/<batch>/`.\n const combined = `${kbId}-${id}`\n const slug = combined\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .replace(/-{2,}/g, \"-\")\n .slice(0, 96)\n return slug || \"migrated-source\"\n}\n\nfunction hashKbSource(s: KbSourceLike, body: string): string {\n // Stable hash so the dedup gate works across reruns of the same\n // KB. Uses node:crypto for parity with reader.ts; Bun/Deno also\n // ship node:crypto in their stdlib.\n return (\n \"sha256:\" +\n createHash(\"sha256\")\n .update(`${s.id}|${s.bytes}|${body}`)\n .digest(\"hex\")\n )\n}\n","/**\n * WebImporter — turns a list of URLs into corpus sources by reducing\n * each to text through an injected FetcherPort. The importer is pure:\n * it slugs, hashes, and shapes ImportedSource; the FetcherPort supplies\n * the environment-bound \"URL → { title, text }\" capability (YouTube\n * captions, article readability, or — at a fatter tier — transcription).\n *\n * Config (target.config):\n * - urls: string[] — required. The source URLs to import.\n * - maxUrls?: number — defaults to 1000.\n * - tags?: string[] — applied to every imported source.\n * - language?: string — fallback BCP-47 when the fetcher omits one.\n *\n * A URL the fetcher returns `null` for (e.g. a caption-less video on a\n * non-transcribing tier) is skipped — the runner records it as a\n * warning rather than aborting the batch.\n *\n * Pure kit code — consumes FetcherPort, no node:fs / no network of its\n * own. Slug: derived from title, else the URL. Hash: sha256 of the text.\n */\n\nimport { createHash } from \"node:crypto\"\nimport { slugify, uniqueSlug } from \"../util/slug.js\"\nimport { normalizeLanguageTag } from \"../util/language.js\"\nimport type { FetcherPort, FetchedSource } from \"../ports/fetcher.port.js\"\nimport type {\n CorpusImporter,\n ImportedSource,\n ImporterTarget,\n} from \"./types.js\"\n\nexport interface WebImporterOptions {\n readonly fetcher: FetcherPort\n}\n\ninterface WebConfig {\n readonly urls: readonly string[]\n readonly maxUrls?: number\n readonly tags?: readonly string[]\n readonly language?: string\n}\n\nexport class WebImporter implements CorpusImporter {\n readonly id = \"web\"\n readonly label = \"Web (URLs)\"\n\n constructor(private readonly opts: WebImporterOptions) {}\n\n async *enumerate(target: ImporterTarget): AsyncIterable<ImportedSource> {\n const config = parseConfig(target.config)\n const maxUrls = config.maxUrls ?? 1000\n const seenSlugs = new Set<string>()\n let yielded = 0\n\n for (const url of config.urls) {\n if (yielded >= maxUrls) break\n\n // A fetcher signals \"couldn't reduce this URL\" with null. A *thrown*\n // error (transient network failure, browser-MCP disconnect, timeout)\n // must NOT abort the whole batch — the throw would propagate out of\n // this generator and kill every remaining URL. Treat it as a per-URL\n // skip; the importer is resumable, so a re-run retries it.\n let fetched: FetchedSource | null\n try {\n fetched = await this.opts.fetcher.fetch(url)\n } catch {\n continue\n }\n // null = the fetcher couldn't reduce this URL to text; skip it.\n // The runner surfaces skipped URLs as warnings on the batch.\n if (!fetched || !fetched.text.trim()) continue\n\n const slug = uniqueSlug(\n slugify(fetched.title, { fallback: \"\" }) ||\n slugify(url, { stripScheme: true, fallback: \"source\" }),\n seenSlugs\n )\n const language = normalizeLanguageTag(fetched.language ?? config.language)\n\n yield {\n slug,\n title: fetched.title.slice(0, 200) || slug,\n contentHash: sha256(fetched.text),\n body: fetched.text,\n originalUrl: url,\n authority: \"secondary\",\n ...(language ? { language } : {}),\n ...(config.tags && config.tags.length > 0\n ? { tags: config.tags }\n : {}),\n corpusMetadata: {\n importerSourceUrl: url,\n fetchKind: fetched.kind,\n ...(fetched.via ? { fetchedVia: fetched.via } : {}),\n },\n }\n yielded++\n }\n }\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\nfunction parseConfig(raw: Readonly<Record<string, unknown>>): WebConfig {\n const rawUrls = raw.urls\n if (!Array.isArray(rawUrls) || rawUrls.length === 0) {\n throw new Error(\"WebImporter: config.urls is required (non-empty string[])\")\n }\n const urls = rawUrls.filter(\n (x): x is string => typeof x === \"string\" && x.length > 0\n )\n if (urls.length === 0) {\n throw new Error(\"WebImporter: config.urls contained no usable strings\")\n }\n const rawTags = raw.tags\n return {\n urls,\n maxUrls: typeof raw.maxUrls === \"number\" ? raw.maxUrls : undefined,\n tags: Array.isArray(rawTags)\n ? rawTags.filter((x): x is string => typeof x === \"string\")\n : undefined,\n language: typeof raw.language === \"string\" ? raw.language : undefined,\n }\n}\n\nfunction sha256(content: string): string {\n return \"sha256:\" + createHash(\"sha256\").update(content).digest(\"hex\")\n}\n","/**\n * ConversationImporter — turns conversations into corpus sources by rendering\n * each to a transcript through an injected ConversationSourcePort. The importer\n * is pure: it slugs, hashes, and shapes ImportedSource; the port supplies the\n * environment-bound \"ref → turns\" capability (a Mastra thread store, a chat DB).\n *\n * This is the seam for conversation→knowledge distill — the resulting sources\n * feed DistillRunner exactly like web sources do (the pipeline is provenance-\n * agnostic). Chat is append-only, so a single immutable slug per conversation\n * would collide once new turns arrive; the host handles this by WINDOWING —\n * giving each ConversationDoc a window-unique id (e.g. `<thread>-<date>`), so\n * each window distills once and a daily run only sees fresh windows.\n *\n * Config (target.config):\n * - refs: string[] — required. Refs to resolve.\n * - tags?: string[] — applied to every source.\n * - language?: string — fallback BCP-47.\n * - authority?: \"primary\"|\"secondary\"|\"rumour\" — default \"secondary\".\n * - maxRefs?: number — defaults to 1000.\n *\n * Pure kit code — consumes ConversationSourcePort, no chat-store dependency.\n * Slug: derived from the doc id. Hash: sha256 of the rendered transcript, so\n * an unchanged window re-import dedups in ImporterRunner.\n */\n\nimport { createHash } from \"node:crypto\"\nimport { slugify, uniqueSlug } from \"../util/slug.js\"\nimport { normalizeLanguageTag } from \"../util/language.js\"\nimport type {\n ConversationDoc,\n ConversationSourcePort,\n ConversationTurn,\n} from \"../ports/conversation-source.port.js\"\nimport type {\n CorpusImporter,\n ImportedSource,\n ImporterTarget,\n} from \"./types.js\"\n\ntype Authority = \"primary\" | \"secondary\" | \"rumour\"\n\nexport interface ConversationImporterOptions {\n readonly source: ConversationSourcePort\n}\n\ninterface ConversationConfig {\n readonly refs: readonly string[]\n readonly tags?: readonly string[]\n readonly language?: string\n readonly authority?: Authority\n readonly maxRefs?: number\n}\n\nexport class ConversationImporter implements CorpusImporter {\n readonly id = \"conversation\"\n readonly label = \"Conversation\"\n\n constructor(private readonly opts: ConversationImporterOptions) {}\n\n async *enumerate(target: ImporterTarget): AsyncIterable<ImportedSource> {\n const config = parseConfig(target.config)\n const maxRefs = config.maxRefs ?? 1000\n const seenSlugs = new Set<string>()\n let yielded = 0\n\n for (const ref of config.refs) {\n if (yielded >= maxRefs) break\n\n // A port signals \"couldn't resolve this ref\" with null. A *thrown* error\n // (store unreachable, auth) must NOT abort the whole batch — the throw\n // would propagate out of this generator and kill every remaining ref.\n // Treat it as a per-ref skip; the importer is resumable, so a re-run\n // retries it.\n let doc: ConversationDoc | null\n try {\n doc = await this.opts.source.fetchConversation(ref)\n } catch {\n continue\n }\n if (!doc || doc.turns.length === 0) continue\n\n const body = renderTranscript(doc.turns)\n if (!body) continue // every turn was empty — nothing to distill\n\n const slug = uniqueSlug(\n slugify(doc.id, { fallback: \"\" }) ||\n slugify(doc.title ?? \"conversation\", { fallback: \"conversation\" }),\n seenSlugs\n )\n const language = normalizeLanguageTag(doc.language ?? config.language)\n const stamps = doc.turns\n .map(t => t.at)\n .filter((a): a is string => typeof a === \"string\" && a.length > 0)\n .sort()\n\n yield {\n slug,\n title: (doc.title ?? `Conversation ${doc.id}`).slice(0, 200),\n contentHash: sha256(body),\n body,\n authority: config.authority ?? \"secondary\",\n ...(language ? { language } : {}),\n ...(config.tags && config.tags.length > 0 ? { tags: config.tags } : {}),\n corpusMetadata: {\n conversationRef: ref,\n conversationId: doc.id,\n sourceKind: \"conversation\",\n turnCount: countTurns(doc.turns),\n ...(stamps.length\n ? { firstTurnAt: stamps[0], lastTurnAt: stamps[stamps.length - 1] }\n : {}),\n },\n }\n yielded++\n }\n }\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\nfunction parseConfig(\n raw: Readonly<Record<string, unknown>>\n): ConversationConfig {\n const rawRefs = raw.refs\n if (!Array.isArray(rawRefs) || rawRefs.length === 0) {\n throw new Error(\n \"ConversationImporter: config.refs is required (non-empty string[])\"\n )\n }\n const refs = rawRefs.filter(\n (x): x is string => typeof x === \"string\" && x.length > 0\n )\n if (refs.length === 0) {\n throw new Error(\n \"ConversationImporter: config.refs contained no usable strings\"\n )\n }\n const rawTags = raw.tags\n return {\n refs,\n maxRefs: typeof raw.maxRefs === \"number\" ? raw.maxRefs : undefined,\n tags: Array.isArray(rawTags)\n ? rawTags.filter((x): x is string => typeof x === \"string\")\n : undefined,\n language: typeof raw.language === \"string\" ? raw.language : undefined,\n authority: isAuthority(raw.authority) ? raw.authority : undefined,\n }\n}\n\nfunction isAuthority(v: unknown): v is Authority {\n return v === \"primary\" || v === \"secondary\" || v === \"rumour\"\n}\n\n/** Render turns to a plain transcript — `Role: text`, blank-line separated.\n * Empty-text turns are dropped so the distiller sees only substance. */\nfunction renderTranscript(turns: readonly ConversationTurn[]): string {\n const blocks: string[] = []\n for (const turn of turns) {\n const text = turn.text.trim()\n if (!text) continue\n blocks.push(`${labelRole(turn.role)}: ${text}`)\n }\n return blocks.join(\"\\n\\n\")\n}\n\nfunction countTurns(turns: readonly ConversationTurn[]): number {\n let n = 0\n for (const t of turns) if (t.text.trim()) n++\n return n\n}\n\nfunction labelRole(role: string): string {\n const r = role.trim()\n if (!r) return \"Speaker\"\n return r.charAt(0).toUpperCase() + r.slice(1)\n}\n\nfunction sha256(content: string): string {\n return \"sha256:\" + createHash(\"sha256\").update(content).digest(\"hex\")\n}\n","/**\n * DistillRunner — turn one raw source into refined AIP-10 entries.\n *\n * Reads nothing itself beyond what it's handed; writes each distilled item\n * as `entries/<kind-plural>/<year>/<slug>.md` (layout: \"dated\", default) or\n * `entries/<kind-plural>/<slug>.md` (layout: \"flat\") with `sources: [<sourceId>]`\n * (the provenance edge) and inherited `access`. Pure: consumes FsPort +\n * ClockPort + an injected DistillPort. The filesystem refs are the graph.\n */\n\nimport matter from \"gray-matter\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type { ClockPort } from \"../ports/clock.port.js\"\nimport { slugify, uniqueSlug } from \"../util/slug.js\"\nimport type { DistillPort, DistilledItem, RefinedKind } from \"./types.js\"\n\n/** Entry slugs must start with a letter; cap at 80 and fall back to \"entry\". */\nconst ENTRY_SLUG_OPTS = { leadingLetter: true, fallback: \"entry\", maxLen: 80 } as const\n\nconst KIND_DIR: Record<RefinedKind, string> = {\n principle: \"principles\",\n pattern: \"patterns\",\n critique: \"critiques\",\n summary: \"summaries\",\n example: \"examples\",\n}\n\nexport interface DistillSource {\n /** The raw source's AIP-10 id (becomes the `sources:` provenance ref). */\n readonly id: string\n readonly title: string\n readonly body: string\n readonly tags?: readonly string[]\n /** Access scope inherited by every entry distilled from this source. */\n readonly access?: string\n readonly domain?: string\n}\n\nexport interface DistillRunReport {\n readonly sourceId: string\n readonly entryPaths: readonly string[]\n readonly skipped: readonly string[] // slugs skipped (already exist)\n}\n\n/** Where distilled entries land under `entries/<kind>/`. */\nexport type EntryLayout = \"dated\" | \"flat\"\n\nexport interface DistillRunnerOptions {\n readonly fs: FsPort\n readonly clock: ClockPort\n readonly distiller: DistillPort\n /**\n * Entry path layout. \"dated\" (default) → `entries/<kind>/<year>/<slug>.md`\n * (scales to large corpora over time); \"flat\" → `entries/<kind>/<slug>.md`.\n */\n readonly layout?: EntryLayout\n}\n\nexport class DistillRunner {\n constructor(private readonly opts: DistillRunnerOptions) {}\n\n async run(source: DistillSource): Promise<DistillRunReport> {\n const items = await this.opts.distiller.distill({\n title: source.title,\n body: source.body,\n ...(source.tags ? { tags: source.tags } : {}),\n })\n\n const year = this.opts.clock.now().getUTCFullYear()\n const flat = this.opts.layout === \"flat\"\n const seen = new Set<string>()\n const entryPaths: string[] = []\n const skipped: string[] = []\n\n for (const item of items) {\n if (!item.title.trim() || !item.body.trim()) continue\n const slug = uniqueSlug(slugify(item.title, ENTRY_SLUG_OPTS), seen, 80)\n const dir = KIND_DIR[item.kind]\n const path = flat\n ? `entries/${dir}/${slug}.md`\n : `entries/${dir}/${year}/${slug}.md`\n\n if (await this.opts.fs.exists(path)) {\n skipped.push(slug)\n continue\n }\n await this.opts.fs.writeFile(path, serializeEntry(item, slug, source, this.opts.clock))\n entryPaths.push(path)\n }\n return { sourceId: source.id, entryPaths, skipped }\n }\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\nfunction serializeEntry(\n item: DistilledItem,\n slug: string,\n source: DistillSource,\n clock: ClockPort\n): string {\n const now = clock.now().toISOString()\n const fm: Record<string, unknown> = {\n schema: \"knowledge.entry/v1\",\n slug,\n kind: item.kind,\n title: item.title,\n updated_at: now,\n sources: [source.id], // ← derivedFrom / provenance edge\n confidence: typeof item.confidence === \"number\" ? item.confidence : 0.7,\n tags: dedupeTags(item.tags, source.tags),\n metadata: {\n corpus: {\n status: \"active\",\n ...(source.domain ? { domain: source.domain } : {}),\n // access inherited from the source — propagates up the chain so a\n // refined insight is never more visible than its evidence.\n ...(source.access ? { access: source.access } : {}),\n promotionMode: \"auto-distill\",\n promotedAt: now,\n },\n },\n }\n const body = item.body.trim()\n return matter.stringify(body.startsWith(\"\\n\") ? body : \"\\n\" + body, fm)\n}\n\nfunction dedupeTags(\n a: readonly string[] | undefined,\n b: readonly string[] | undefined\n): string[] {\n const out = new Set<string>()\n for (const raw of [...(a ?? []), ...(b ?? [])]) {\n const t = sanitizeTag(raw)\n if (t) out.add(t)\n }\n return [...out]\n}\n\n/** AIP-10 tag pattern is ^[a-z][a-z0-9-]*$ — lowercase, strip accents,\n * kebab-ize, drop anything that can't start with a letter. */\nfunction sanitizeTag(raw: string): string | null {\n const t = raw\n .toLowerCase()\n .normalize(\"NFD\")\n .replace(/[̀-ͯ]/g, \"\")\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .replace(/-{2,}/g, \"-\")\n return /^[a-z][a-z0-9-]*$/.test(t) ? t : null\n}\n\n","/**\n * Shared distill prompt + parse — the model-agnostic core of distillation.\n *\n * Every DistillPort backend (an HTTP Messages-API distiller, a CLI-agent\n * distiller, an in-app model adapter) asks the same thing and reads the same\n * shape back, so the prompt and the tolerant JSON parse live here once. A\n * backend owns only the transport (HTTP vs. child process vs. SDK) and how it\n * extracts the model's text.\n */\n\nimport { z } from \"zod\"\nimport {\n REFINED_KIND_SCHEMA,\n type DistillInput,\n type DistilledItem,\n} from \"./types.js\"\n\n/** A single distilled item as the model is asked to emit it. */\nconst DISTILLED_ITEM = z\n .object({\n kind: REFINED_KIND_SCHEMA,\n title: z.string(),\n body: z.string(),\n confidence: z.number().optional(),\n tags: z.array(z.string()).optional(),\n })\n .loose()\n\n/** Build the distillation prompt for one source, capped at `maxItems`. */\nexport function buildDistillPrompt(\n input: DistillInput,\n maxItems: number\n): string {\n return `You distill a raw source (a video transcript or article) into REFINED, reusable knowledge for an AI operator. Extract the durable insights — not a summary of the video, but the transferable lessons.\n\nReturn a JSON array (max ${maxItems} items). Each item:\n{ \"kind\": one of \"principle\" | \"pattern\" | \"critique\" | \"summary\" | \"example\",\n \"title\": short imperative/declarative title,\n \"body\": 2-5 sentences, SELF-CONTAINED (no \"the speaker says\"), the actual insight,\n \"confidence\": 0-1, \"tags\": [short topic tags] }\n\nGuidance:\n- \"principle\": a durable rule of thumb. \"pattern\": a repeatable technique/sequence.\n \"critique\": a common mistake / anti-pattern. \"summary\": a compact overview.\n \"example\": a concrete worked instance worth remembering.\n- Drop filler, calls-to-action, tangents. Keep only what an operator could ACT on later.\n- Write every title and body in ENGLISH, even when the source is in another language. Translate the insight; do not copy the source language.\n\nSOURCE TITLE: ${input.title}\n${input.tags?.length ? `TAGS: ${input.tags.join(\", \")}\\n` : \"\"}SOURCE BODY:\n${input.body.slice(0, 24000)}\n\nReturn ONLY the JSON array, no prose.`\n}\n\n/** Tolerant parse: grab the first `[...]` block (allows ```json fences / prose). */\nexport function parseItems(text: string): DistilledItem[] {\n const start = text.indexOf(\"[\")\n const end = text.lastIndexOf(\"]\")\n if (start < 0 || end <= start) return []\n let raw: unknown\n try {\n raw = JSON.parse(text.slice(start, end + 1))\n } catch {\n return []\n }\n if (!Array.isArray(raw)) return []\n const out: DistilledItem[] = []\n for (const r of raw) {\n const item = DISTILLED_ITEM.safeParse(r)\n if (!item.success) continue\n const { kind, title, body, confidence, tags } = item.data\n out.push({\n kind,\n title,\n body,\n ...(typeof confidence === \"number\" ? { confidence } : {}),\n ...(tags ? { tags } : {}),\n })\n }\n return out\n}\n","/**\n * scanDistilledSourceIds — which raw source ids already have ≥1 refined entry\n * derived from them, found by reading the `sources:` provenance backlink on\n * every `entries/**​/*.md`. Lets an incremental distill skip sources already\n * done, so a daily re-run is idempotent (no duplicate entries, no wasted spend).\n *\n * Tolerant of both `walk` conventions a host's FsPort may use — paths relative\n * to the walked dir (MemFs) or anchored at the workspace root (a workspace\n * adapter) — by normalizing each back under `entries/` before reading.\n */\n\nimport matter from \"gray-matter\"\nimport { z } from \"zod\"\nimport type { FsPort } from \"../ports/fs.port.js\"\n\nconst ENTRY_SOURCES = z\n .object({ sources: z.array(z.string()).optional().catch(undefined) })\n .loose()\n\nexport async function scanDistilledSourceIds(\n fs: FsPort\n): Promise<Set<string>> {\n const ids = new Set<string>()\n let rels: readonly string[]\n try {\n rels = await fs.walk(\"entries\")\n } catch {\n return ids\n }\n for (const rel of rels) {\n if (!rel.endsWith(\".md\")) continue\n const path = rel.startsWith(\"entries/\") ? rel : `entries/${rel}`\n try {\n const fm = ENTRY_SOURCES.parse(matter(await fs.readFile(path)).data)\n if (fm.sources) for (const s of fm.sources) ids.add(s)\n } catch {\n // unreadable / no frontmatter — skip\n }\n }\n return ids\n}\n","/**\n * Distill registry — the catalog of distill kinds.\n *\n * Distill is four swappable slots: SOURCE (raw material) → IMPORTER (how to\n * render it) → DISTILLER (the LLM) → TARGET (where entries land). A\n * `DistillDescriptor` binds all four for one kind (\"conversation\", \"web\", …);\n * the registry holds them by id so the cron/worker can dispatch polymorphically\n * — adding a kind is registering a descriptor, with zero pipeline changes.\n *\n * Lightweight on purpose (mirrors the AIP-35 filesystem-provider registry):\n * descriptors are code-registered, so there is no `resolveConfig` / secrets /\n * UI-fields surface the way user-connected engine descriptors carry. Vendor-\n * neutral — the kit owns the contract + the generic runner; the per-kind\n * bindings live in each app's core package.\n */\n\nimport type { CorpusImporter, ImportedSource } from \"../importers/types.js\"\nimport type { ClockPort } from \"../ports/clock.port.js\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type { DistillPort } from \"./types.js\"\n\n/**\n * Who a distill runs for. `id` is the durable handle carried on the queued job\n * (`resolveScope` rehydrates it in the worker); `userId` feeds the job's owner.\n * Kinds extend this with their own scope fields (a guild id, a workspace id, …).\n */\nexport interface DistillScope {\n readonly id: string\n readonly userId: string\n readonly [key: string]: unknown\n}\n\n/** Where distilled entries land — the corpus filesystem for a scope. */\nexport interface DistillTarget {\n readonly fs: FsPort\n readonly clock: ClockPort\n /** Optional corpus root within the fs (defaults to the fs root, \"\"). */\n readonly root?: string\n}\n\n/**\n * SOURCE + IMPORTER bound to one scope. Co-constructed so both share a single\n * (cache-bearing) source instance where relevant (e.g. a windowed conversation\n * source loads each thread once). The binding owns the importer-native config\n * AND the provenance mapping, so `runDistill` stays importer-agnostic — a\n * conversation kind keys on `{refs}`/`conversationId`, a web kind on\n * `{urls}`/`originalUrl`, with no per-kind code in the runner.\n */\nexport interface DistillBinding {\n /** The kit importer for this kind (ConversationImporter, WebImporter, …). */\n readonly importer: CorpusImporter\n /**\n * Build the importer's NATIVE config for the fresh (not-yet-distilled)\n * material, or `null` when nothing new is left to import. The config is\n * passed straight to `importer.enumerate({ config })`, so its shape is the\n * importer's own (`{refs}`, `{urls}`, …). Filter against `distilled` (the set\n * of provenance ids already backing ≥1 entry) so a re-run only sees fresh work.\n */\n prepare(\n distilled: ReadonlySet<string>\n ): Promise<Readonly<Record<string, unknown>> | null>\n /**\n * Stable provenance id for an imported source — becomes the entry's\n * `sources:` backlink and the dedup key matched against `distilled`. MUST\n * agree with the ids `prepare` filters on (e.g. the window slug, the URL).\n */\n provenanceId(imported: ImportedSource): string\n}\n\n/**\n * One catalog entry: a distill kind, with its four slots bound to a scope.\n * Generic over the scope shape so each kind keeps its own typed scope while the\n * registry stores them uniformly.\n */\nexport interface DistillDescriptor<S extends DistillScope = DistillScope> {\n /** Stable kind id — \"conversation\" | \"web\" | … */\n readonly id: string\n /** Queue type the cron submits and the worker handles, e.g. \"distill:conversation\". */\n readonly jobType: string\n /** Human-readable label (diagnostics / surfaces). */\n readonly label: string\n /** Tags applied to every source distilled by this kind (e.g. [\"personal\"]). */\n readonly tags?: readonly string[]\n\n /**\n * SOURCE + IMPORTER slots, bound to the scope. Receives the resolved TARGET\n * so an importer that reads the corpus filesystem (e.g. refine-its-own-sources)\n * can bind against it without resolving the target a second time.\n */\n bind(scope: S, target: DistillTarget): DistillBinding\n /** DISTILLER slot: the LLM boundary for this scope. */\n distiller(scope: S): DistillPort\n /** TARGET slot: where entries land for this scope. */\n target(scope: S): Promise<DistillTarget>\n\n /**\n * Consent gate. Checked at fan-out (bulk filter) AND re-checked in the worker\n * (authoritative — it can flip between enqueue and execution). Absent ⇒ no gate.\n */\n consent?(scope: S): Promise<boolean>\n /** Who to run for. Implementations should stream/paginate at scale. */\n scopes(): Promise<readonly S[]>\n /** Rehydrate a scope from its `id` — the worker holds only the id post-enqueue. */\n resolveScope(scopeId: string): Promise<S>\n}\n\nexport interface DistillRegistry {\n /** Register a kind. Throws on duplicate id. */\n register<S extends DistillScope>(descriptor: DistillDescriptor<S>): void\n has(id: string): boolean\n /** Resolve by id. Throws when the id was never registered. */\n resolve(id: string): DistillDescriptor\n /** All registered descriptors (for the cron fan-out + worker handler map). */\n list(): DistillDescriptor[]\n}\n\nexport function createDistillRegistry(): DistillRegistry {\n const descriptors = new Map<string, DistillDescriptor>()\n\n return {\n register(descriptor) {\n if (descriptors.has(descriptor.id)) {\n throw new Error(`Distill descriptor \"${descriptor.id}\" is already registered`)\n }\n descriptors.set(descriptor.id, descriptor)\n },\n has(id) {\n return descriptors.has(id)\n },\n resolve(id) {\n const descriptor = descriptors.get(id)\n if (!descriptor) {\n throw new Error(\n `Distill descriptor \"${id}\" is not registered. Registered: ${[...descriptors.keys()].join(\", \") || \"(none)\"}`\n )\n }\n return descriptor\n },\n list() {\n return [...descriptors.values()]\n },\n }\n}\n","/**\n * runDistill — the generic distill pass for one (descriptor × scope).\n *\n * The kind-agnostic generalization of the conversation pipeline: resolve the\n * scope's TARGET, scan which provenance ids are already distilled, ask the\n * binding (SOURCE + IMPORTER) for the fresh refs, import each, and run the\n * DISTILLER over it — writing refined AIP-10 entries via `DistillRunner`.\n * No per-kind branches: every variation rides on the descriptor's slots.\n *\n * Idempotent: a unit whose provenance id already backs an entry is skipped by\n * the binding's `prepare`, and `DistillRunner` additionally skips any entry\n * slug that already exists — so a daily re-run only adds fresh material.\n */\n\nimport { DistillRunner, type DistillSource } from \"./runner.js\"\nimport { scanDistilledSourceIds } from \"./scan.js\"\nimport type { DistillDescriptor, DistillScope } from \"./registry.js\"\n\nexport interface DistillReport {\n readonly descriptorId: string\n readonly scopeId: string\n /** Sources the importer yielded this run. */\n unitsConsidered: number\n /** Units that produced ≥1 new entry. */\n unitsDistilled: number\n entriesWritten: number\n /** Entry slugs skipped because an identical title already existed. */\n skipped: number\n}\n\nexport async function runDistill<S extends DistillScope>(\n descriptor: DistillDescriptor<S>,\n scope: S\n): Promise<DistillReport> {\n const report: DistillReport = {\n descriptorId: descriptor.id,\n scopeId: scope.id,\n unitsConsidered: 0,\n unitsDistilled: 0,\n entriesWritten: 0,\n skipped: 0,\n }\n\n const target = await descriptor.target(scope)\n const distilled = await scanDistilledSourceIds(target.fs)\n const binding = descriptor.bind(scope, target)\n const config = await binding.prepare(distilled)\n // null ⇒ the binding found nothing fresh to import this run.\n if (!config) return report\n\n const runner = new DistillRunner({\n fs: target.fs,\n clock: target.clock,\n distiller: descriptor.distiller(scope),\n })\n\n for await (const imported of binding.importer.enumerate({\n importerId: descriptor.id,\n config,\n })) {\n report.unitsConsidered++\n // Provenance id is binding-defined (window slug, URL, …) so the skip-scan\n // matches it on the next run — not the slugified entry slug.\n const source: DistillSource = {\n id: binding.provenanceId(imported),\n title: imported.title,\n body: imported.body,\n ...(imported.tags ? { tags: imported.tags } : {}),\n }\n try {\n const r = await runner.run(source)\n if (r.entryPaths.length > 0) report.unitsDistilled++\n report.entriesWritten += r.entryPaths.length\n report.skipped += r.skipped.length\n } catch {\n // One unit failing (rate cap, transient) must not abort the rest — it\n // stays undistilled and is retried next run.\n }\n }\n return report\n}\n","/**\n * ClaudeDistiller — a `DistillPort` backed by Claude over the Messages API.\n * Reuses the kit's shared prompt + tolerant parse (`buildDistillPrompt` /\n * `parseItems`), owning only the HTTP transport. SDK-free (raw fetch) so the\n * job takes no client-lib dependency.\n *\n * Vendor-neutral: the only host coupling is an injected `apiKey` / `model` /\n * `baseUrl` — no app names, no env-name assumptions. Distillation is bulk +\n * background, so a mid-tier model is the sensible default; the caller gates\n * the spend (consent + incremental windows).\n */\n\nimport { z } from \"zod\"\nimport { buildDistillPrompt, parseItems } from \"./prompt.js\"\nimport type { DistillInput, DistilledItem, DistillPort } from \"./types.js\"\n\n/** The Messages API response shape we read (just the text content blocks). */\nconst ANTHROPIC_RESPONSE = z\n .object({\n content: z\n .array(\n z.object({ type: z.string(), text: z.string().optional() }).loose()\n )\n .optional(),\n })\n .loose()\n\nexport interface ClaudeDistillerOptions {\n readonly apiKey: string\n /** Defaults to a mid-tier model — distillation is bulk + background. */\n readonly model?: string\n readonly baseUrl?: string\n /** Max refined items to extract per source. */\n readonly maxItems?: number\n}\n\nexport class ClaudeDistiller implements DistillPort {\n private readonly apiKey: string\n private readonly model: string\n private readonly baseUrl: string\n private readonly maxItems: number\n\n constructor(opts: ClaudeDistillerOptions) {\n this.apiKey = opts.apiKey\n this.model = opts.model ?? \"claude-sonnet-4-6\"\n this.baseUrl = (opts.baseUrl ?? \"https://api.anthropic.com/v1\").replace(\n /\\/+$/,\n \"\"\n )\n this.maxItems = opts.maxItems ?? 8\n }\n\n async distill(input: DistillInput): Promise<readonly DistilledItem[]> {\n const prompt = buildDistillPrompt(input, this.maxItems)\n const res = await fetch(`${this.baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"x-api-key\": this.apiKey,\n \"anthropic-version\": \"2023-06-01\",\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n model: this.model,\n max_tokens: 4096,\n messages: [{ role: \"user\", content: prompt }],\n }),\n })\n if (!res.ok) {\n throw new Error(\n `Claude distill ${res.status}: ${(await res.text()).slice(0, 200)}`\n )\n }\n const parsed = ANTHROPIC_RESPONSE.safeParse(await res.json())\n const text = parsed.success\n ? ((parsed.data.content ?? []).find(c => c.type === \"text\")?.text ?? \"\")\n : \"\"\n return parseItems(text)\n }\n}\n","/**\n * Conversation windowing — pure helpers + the windowed-source contract.\n *\n * Chat is append-only, so a single immutable slug per conversation would\n * collide once new turns arrive. The fix is WINDOWING: each (thread,\n * completed-UTC-day) slice is the unit that distils exactly once (a closed day\n * is immutable). These helpers compose / parse the window ref the importer\n * resolves and the provenance slug the distilled-scan dedups on.\n *\n * No transport, no chat-store, no model dependency — just string algebra over\n * `(threadId, day)` plus a structural source contract. A fake satisfying\n * `ConversationWindowSource` is all a test needs.\n */\n\nimport type { ConversationSourcePort } from \"../ports/conversation-source.port.js\"\n\nconst WINDOW_SEP = \"::\"\n\n/** Compose the importer ref for one (thread, day) window. */\nexport function windowRef(threadId: string, day: string): string {\n return `${threadId}${WINDOW_SEP}${day}`\n}\n\n/** Parse a window ref back to its parts, or null when malformed. */\nexport function parseWindowRef(\n ref: string\n): { threadId: string; day: string } | null {\n const i = ref.indexOf(WINDOW_SEP)\n if (i < 0) return null\n const threadId = ref.slice(0, i)\n const day = ref.slice(i + WINDOW_SEP.length)\n return threadId && day ? { threadId, day } : null\n}\n\n/** Slug base a window resolves to — also the `sources:` provenance id, so the\n * distilled-scan can dedup windows across runs with no slug drift. */\nexport function windowSlug(threadId: string, day: string): string {\n return `${threadId}-${day}`\n}\n\n/** A thread the source owns — minimal shape the enumeration needs. */\nexport interface ConversationThreadRef {\n readonly id: string\n readonly threadId?: string\n}\n\n/**\n * The windowed source the distill pipeline drives: a `ConversationSourcePort`\n * that can also enumerate its threads and each thread's completed-day windows.\n * A fake satisfying this is all a test needs (no DB, no chat store).\n */\nexport interface ConversationWindowSource extends ConversationSourcePort {\n listThreads(): Promise<ConversationThreadRef[]>\n listWindows(threadId: string): Promise<string[]>\n}\n\n/**\n * Enumerate the window refs worth distilling for a windowed source: every\n * (thread, completed-day) window whose provenance slug isn't already distilled.\n * Generic over any `ConversationWindowSource`, so a binding never re-implements\n * the thread→window→skip loop.\n */\nexport async function enumerateWindowRefs(\n source: ConversationWindowSource,\n distilled: ReadonlySet<string>\n): Promise<string[]> {\n const refs: string[] = []\n for (const thread of await source.listThreads()) {\n const threadId = thread.threadId ?? thread.id\n if (!threadId) continue\n for (const day of await source.listWindows(threadId)) {\n if (distilled.has(windowSlug(threadId, day))) continue\n refs.push(windowRef(threadId, day))\n }\n }\n return refs\n}\n","/**\n * OverlayFs — stacks FsPorts so a writable layer shadows read-only ones.\n *\n * This is the customization engine for the SKILL→KNOWLEDGE→SOURCES spine:\n * a guild's editable corpus (its system workspace) sits ON TOP of one or\n * more read-only knowledge packs (shared, shipped). Layers are ordered\n * highest-precedence first.\n *\n * overlay = new OverlayFs([guildFs, packFs]) // guild wins\n *\n * Resolution is by RELATIVE PATH:\n * - reads (readFile/stat/exists) return the first layer that has the path\n * - walk/readdir UNION across layers, deduped — so an entry the guild\n * re-authors at the same path appears ONCE, with the guild's content\n * - a path only in the pack passes through unchanged (the floor)\n * - a path only in the guild is additive (extend)\n * - writes/appends/locks always target the top (writable) layer; the\n * packs stay pristine for every other guild\n *\n * This keeps `resolveKnowledge` untouched: it walks `entries/**` over the\n * overlay and never sees a pack entry that the guild has shadowed.\n */\n\nimport type { FsPort, FsLockHandle, FsStat } from \"../ports/fs.port.js\"\n\n/**\n * Sibling-path marker that removes (whiteouts) a lower layer's entry. To\n * drop `entries/foo.md`, a higher layer authors `entries/foo.md.whiteout`.\n * A marker file (not a frontmatter flag) keeps overlay resolution a pure\n * path operation — listing a directory never reads entry bodies.\n */\nexport const WHITEOUT_SUFFIX = \".whiteout\"\n\nconst isMarker = (p: string): boolean => p.endsWith(WHITEOUT_SUFFIX)\nconst baseOf = (markerPath: string): string =>\n markerPath.slice(0, -WHITEOUT_SUFFIX.length)\n\nexport interface OverlayFsOptions {\n /**\n * Honor `.whiteout` markers so a higher layer can REMOVE (not just\n * shadow) a lower entry. OFF by default: with whiteout disabled the\n * overlay is pure union + shadow, byte-for-byte the original behavior.\n */\n readonly whiteout?: boolean\n /**\n * Index of the writable layer (writes / appends / locks target it).\n * Defaults to 0. Set this when a read-only CONSTRAINT floor is pinned\n * ABOVE the writable layer: read precedence (layer order) and the write\n * target are then independent — the floor wins reads, the guild layer\n * still takes writes.\n */\n readonly writableLayer?: number\n}\n\nexport class OverlayFs implements FsPort {\n /** Layers ordered highest-precedence first. */\n private readonly layers: readonly FsPort[]\n private readonly whiteout: boolean\n private readonly writableIndex: number\n\n constructor(layers: readonly FsPort[], options: OverlayFsOptions = {}) {\n if (layers.length === 0) {\n throw new Error(\"OverlayFs requires at least one layer\")\n }\n this.layers = layers\n this.whiteout = options.whiteout ?? false\n const w = options.writableLayer ?? 0\n if (w < 0 || w >= layers.length) {\n throw new Error(\n `OverlayFs: writableLayer ${w} out of range [0, ${layers.length - 1}]`\n )\n }\n this.writableIndex = w\n }\n\n /**\n * Top-down resolution for a single path: the first layer that declares\n * either the real entry OR its whiteout marker decides. Within one\n * layer a real entry wins over a stale marker. Returns null when no\n * layer declares the path, and `{ removed: true }` when the winning\n * layer tombstones it.\n */\n private async resolvePath(\n path: string\n ): Promise<{ layer: FsPort } | { removed: true } | null> {\n const marker = path + WHITEOUT_SUFFIX\n for (const layer of this.layers) {\n if (await layer.exists(path)) return { layer }\n if (await layer.exists(marker)) return { removed: true }\n }\n return null\n }\n\n async exists(path: string): Promise<boolean> {\n if (!this.whiteout) {\n for (const layer of this.layers) {\n if (await layer.exists(path)) return true\n }\n return false\n }\n if (isMarker(path)) return false // markers are not visible entries\n const r = await this.resolvePath(path)\n return r !== null && !(\"removed\" in r)\n }\n\n async readFile(path: string): Promise<string> {\n if (this.whiteout && !isMarker(path)) {\n const r = await this.resolvePath(path)\n if (r && \"layer\" in r) return await r.layer.readFile(path)\n // Tombstoned or genuinely missing — surface a plain not-found.\n return await this.layers[0]!.readFile(path)\n }\n for (const layer of this.layers) {\n if (await layer.exists(path)) return await layer.readFile(path)\n }\n // Match a plain fs: throw on a genuinely missing path.\n return await this.layers[0]!.readFile(path)\n }\n\n async stat(path: string): Promise<FsStat | null> {\n if (this.whiteout && !isMarker(path)) {\n const r = await this.resolvePath(path)\n if (r && \"layer\" in r) return await r.layer.stat(path)\n return null\n }\n if (this.whiteout && isMarker(path)) return null\n for (const layer of this.layers) {\n const s = await layer.stat(path)\n if (s) return s\n }\n return null\n }\n\n async readdir(path: string): Promise<readonly string[]> {\n if (!this.whiteout) {\n const seen = new Set<string>()\n for (const layer of this.layers) {\n let names: readonly string[]\n try {\n names = await layer.readdir(path)\n } catch {\n continue // layer lacks this dir — skip\n }\n for (const n of names) seen.add(n)\n }\n return [...seen]\n }\n return this.unionWhiteoutAware((layer) => layer.readdir(path))\n }\n\n async walk(path: string): Promise<readonly string[]> {\n if (!this.whiteout) {\n const seen = new Set<string>()\n for (const layer of this.layers) {\n const rels = await layer.walk(path) // NodeFsAdapter returns [] if missing\n for (const rel of rels) seen.add(rel)\n }\n return [...seen]\n }\n return this.unionWhiteoutAware((layer) => layer.walk(path))\n }\n\n /**\n * Union the entries each layer reports for a path (basenames for\n * readdir, relative paths for walk), resolving whiteouts top-down: the\n * first layer (highest precedence) that declares an entry or its marker\n * wins. Real entries win over markers within the same layer; marker\n * files are stripped from the result.\n */\n private async unionWhiteoutAware(\n list: (layer: FsPort) => Promise<readonly string[]>\n ): Promise<readonly string[]> {\n const decided = new Map<string, \"present\" | \"removed\">()\n for (const layer of this.layers) {\n let entries: readonly string[]\n try {\n entries = await list(layer)\n } catch {\n continue // layer lacks this dir — skip\n }\n const reals = entries.filter((e) => !isMarker(e))\n const markerBases = entries.filter(isMarker).map(baseOf)\n // Real entries first so a real entry wins over a same-layer marker.\n for (const r of reals) if (!decided.has(r)) decided.set(r, \"present\")\n for (const b of markerBases) if (!decided.has(b)) decided.set(b, \"removed\")\n }\n const out: string[] = []\n for (const [name, state] of decided) {\n if (state === \"present\") out.push(name)\n }\n return out\n }\n\n // ── mutations target the writable layer only ────────────────────────\n\n async writeFile(path: string, content: string): Promise<void> {\n return await this.layers[this.writableIndex]!.writeFile(path, content)\n }\n\n async appendFile(path: string, content: string): Promise<void> {\n return await this.layers[this.writableIndex]!.appendFile(path, content)\n }\n\n async lock(path: string): Promise<FsLockHandle> {\n return await this.layers[this.writableIndex]!.lock(path)\n }\n}\n\n/**\n * ReadOnlyFs — wraps an FsPort and rejects every mutation. Use to seal a\n * knowledge pack so a misconfigured host can never write into the shared,\n * shipped corpus (the guild's edits belong in its own overlay layer).\n */\nexport class ReadOnlyFs implements FsPort {\n constructor(private readonly inner: FsPort) {}\n\n exists(path: string): Promise<boolean> {\n return this.inner.exists(path)\n }\n readFile(path: string): Promise<string> {\n return this.inner.readFile(path)\n }\n stat(path: string): Promise<FsStat | null> {\n return this.inner.stat(path)\n }\n readdir(path: string): Promise<readonly string[]> {\n return this.inner.readdir(path)\n }\n walk(path: string): Promise<readonly string[]> {\n return this.inner.walk(path)\n }\n\n async writeFile(path: string, _content: string): Promise<void> {\n throw new Error(`ReadOnlyFs: refusing to write \"${path}\" — packs are immutable`)\n }\n async appendFile(path: string, _content: string): Promise<void> {\n throw new Error(`ReadOnlyFs: refusing to append \"${path}\" — packs are immutable`)\n }\n async lock(path: string): Promise<FsLockHandle> {\n throw new Error(`ReadOnlyFs: refusing to lock \"${path}\" — packs are immutable`)\n }\n}\n","/**\n * MemFs — an in-memory FsPort over a flat `path → content` map.\n *\n * Paths are workspace-relative (no leading slash), exactly like the disk\n * adapters; `walk(dir)` returns paths relative to the walked directory, so it\n * composes with `resolveKnowledge` (which re-prefixes) and with `OverlayFs`\n * unchanged.\n *\n * Primary use: a knowledge PACK whose entries are inlined into the JS bundle\n * at build time (see `@guilde/knowledge-packs`). Reading from an in-memory map\n * means packs ride inside `dist` — no runtime `fs`, no path resolution, no\n * loose data files for the deploy to drop. Wrap in `ReadOnlyFs` for packs.\n */\n\nimport type { FsPort, FsStat, FsLockHandle } from \"../ports/fs.port.js\"\n\nexport class MemFs implements FsPort {\n private readonly files: Record<string, string>\n\n constructor(files: Record<string, string>) {\n // Copy so a caller's shared/frozen map can't be mutated through this fs.\n this.files = { ...files }\n }\n\n async exists(path: string): Promise<boolean> {\n return path in this.files\n }\n\n async readFile(path: string): Promise<string> {\n const content = this.files[path]\n if (content === undefined) throw new Error(`MemFs: ENOENT ${path}`)\n return content\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n this.files[path] = content\n }\n\n async appendFile(path: string, content: string): Promise<void> {\n this.files[path] = (this.files[path] ?? \"\") + content\n }\n\n async readdir(path: string): Promise<readonly string[]> {\n const prefix = path.endsWith(\"/\") ? path : `${path}/`\n const names = new Set<string>()\n for (const key of Object.keys(this.files)) {\n if (key.startsWith(prefix)) names.add(key.slice(prefix.length).split(\"/\")[0]!)\n }\n return [...names]\n }\n\n async walk(path: string): Promise<readonly string[]> {\n const prefix = path.endsWith(\"/\") ? path : `${path}/`\n return Object.keys(this.files)\n .filter(key => key.startsWith(prefix))\n .map(key => key.slice(prefix.length))\n }\n\n async stat(path: string): Promise<FsStat | null> {\n const content = this.files[path]\n return content === undefined ? null : { kind: \"file\", bytes: content.length }\n }\n\n async lock(): Promise<FsLockHandle> {\n return { release: async () => {} }\n }\n}\n","/**\n * Deterministic shadow-traffic sampling.\n *\n * A stable token (e.g. a conversation id) is hashed with a per-arm salt\n * into a 0..1 bucket, so the SAME token always lands the same arm — an\n * eval batch partitioned by that token is reproducible, and a shadow\n * layer rolls out to a fixed fraction of traffic rather than flickering\n * per request.\n *\n * Used by both the playbook overlay resolver and the knowledge-stack\n * resolver so % rollout behaves identically across the two.\n */\n\nimport { createHash } from \"node:crypto\"\n\nexport const DEFAULT_SHADOW_TRAFFIC_PCT = 0.1\n\n/** Deterministic bucket in [0, 1) from a token + salt. */\nexport function deterministicBucket(token: string, salt: string): number {\n const h = createHash(\"sha256\").update(`${token}|${salt}`).digest()\n // First 4 bytes as a uint32 → [0, 1).\n return h.readUInt32BE(0) / 0x1_0000_0000\n}\n\n/**\n * True iff this token is sampled into a shadow arm of width `pct`. No\n * token (e.g. a one-shot tool call) → never sampled: shadow arms only\n * fire on traffic with stable identity.\n */\nexport function sampleShadow(\n token: string | undefined,\n salt: string,\n pct: number = DEFAULT_SHADOW_TRAFFIC_PCT\n): boolean {\n if (!token) return false\n if (pct <= 0) return false\n if (pct >= 1) return true\n return deterministicBucket(token, salt) < pct\n}\n","/**\n * StackResolver — given a `ResolutionContext` and a registry of\n * `LayerProvider`s, produce the band-ordered list of layers an operator's\n * recall is resolved against.\n *\n * The generalization of `OperatorOverlayResolver` (playbooks): same\n * ctx → registry → priority-sort → ordered-list shape, same deterministic\n * shadow sampling for % rollout. Pure — no I/O. The host turns the emitted\n * refs into mounted FsPorts (see `buildOverlayFromStack`).\n */\n\nimport type { Registry } from \"@agentproto/registry\"\nimport { sampleShadow } from \"../util/shadow-sample.js\"\nimport type {\n LayerProvider,\n ResolutionContext,\n StackEntry,\n StackResolution,\n StackSkip,\n} from \"./types.js\"\n\nexport class StackResolver<TSubject = unknown> {\n constructor(\n private readonly registry: Registry<LayerProvider<TSubject>>\n ) {}\n\n async resolve(\n ctx: ResolutionContext<TSubject>\n ): Promise<StackResolution> {\n // Lower band = higher precedence. Stable order for equal bands is the\n // registry's insertion order (AIP-43 Maps preserve it).\n const providers = [...this.registry.list()].sort((a, b) => a.band - b.band)\n\n const entries: StackEntry[] = []\n const skipped: StackSkip[] = []\n\n for (const p of providers) {\n let shadowSampled = false\n if (p.shadow) {\n shadowSampled = sampleShadow(ctx.conversationId, p.id, p.shadow.pct)\n if (!shadowSampled) {\n skipped.push({\n providerId: p.id,\n dimension: p.dimension,\n reason: \"shadow-not-sampled\",\n })\n continue\n }\n }\n\n const refs = await p.resolve(ctx)\n if (refs.length === 0) {\n skipped.push({\n providerId: p.id,\n dimension: p.dimension,\n reason: \"empty\",\n })\n continue\n }\n\n entries.push({\n providerId: p.id,\n band: p.band,\n mode: p.mode,\n dimension: p.dimension,\n refs,\n shadowSampled,\n })\n }\n\n return Object.freeze({\n entries: Object.freeze(entries),\n skipped: Object.freeze(skipped),\n })\n }\n}\n","/**\n * Turn a resolved knowledge stack into a mounted `OverlayFs`, and the\n * helpers that flatten it.\n *\n * Mount order encodes the AIP-10 plane-precedence invariant:\n *\n * [ ...constraint layers (read-only floor, band-ordered) ] ← top\n * [ guild writable layer ] ← writes here\n * [ ...lens layers (band-ordered) ] ← floor packs\n *\n * Constraints are hoisted ABOVE the guild layer so neither a guild edit\n * nor a `.whiteout` can shadow or remove them (they sit higher, and\n * top-down resolution + whiteout-only-suppresses-lower make them a true\n * floor). Writes still target the guild layer via `writableLayer`, so the\n * read floor and the write target stay independent.\n */\n\nimport { OverlayFs, ReadOnlyFs } from \"../knowledge/overlay-fs.js\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type { LayerRef, StackResolution } from \"./types.js\"\n\nexport interface BuildOverlayOptions {\n /** The guild's own editable corpus — the single writable layer. */\n readonly guildFs: FsPort\n /** The resolved stack (band-ordered entries). */\n readonly stack: StackResolution\n /** Resolve a layer ref to an FsPort, or null if it has no mountable source. */\n readonly loadFs: (ref: LayerRef) => FsPort | null\n}\n\n/**\n * Build the mounted overlay for a resolved stack. Returns `guildFs`\n * unchanged when no layer resolves to a mountable source (so the\n * single-layer fast path is preserved).\n */\nexport function buildOverlayFromStack(opts: BuildOverlayOptions): FsPort {\n const { guildFs, stack, loadFs } = opts\n\n const constraintFs: FsPort[] = []\n const lensFs: FsPort[] = []\n for (const entry of stack.entries) {\n const target = entry.mode === \"constraint\" ? constraintFs : lensFs\n for (const ref of entry.refs) {\n const fs = loadFs(ref)\n if (fs) target.push(entry.mode === \"constraint\" ? new ReadOnlyFs(fs) : fs)\n }\n }\n\n if (constraintFs.length === 0 && lensFs.length === 0) return guildFs\n\n const layers = [...constraintFs, guildFs, ...lensFs]\n return new OverlayFs(layers, {\n whiteout: true,\n writableLayer: constraintFs.length, // index of guildFs\n })\n}\n\n/**\n * Flatten a resolved stack to a de-duplicated, band-ordered list of pack\n * refs (kind `pack` or unspecified). This reproduces the legacy\n * `resolveOperatorPacks` output shape (operator packs before role packs,\n * each id once) so the pack-id contract stays stable.\n */\nexport function flattenPackRefs(stack: StackResolution): string[] {\n const out: string[] = []\n for (const entry of stack.entries) {\n for (const ref of entry.refs) {\n if (ref.kind && ref.kind !== \"pack\") continue\n if (!out.includes(ref.ref)) out.push(ref.ref)\n }\n }\n return out\n}\n\n/** Pack refs split by composition mode, each list deduped + band-ordered. */\nexport interface StackRefPartition {\n /** Lens packs — mount UNDER the writable layer (the guild shadows them). */\n readonly lens: readonly string[]\n /** Constraint packs — mount ABOVE the writable layer (a non-shadowable floor). */\n readonly constraint: readonly string[]\n}\n\n/**\n * Partition a resolved stack's pack refs by mode. The host mounts `lens`\n * below the guild layer and `constraint` above it (read-only), so a\n * compliance/legal floor cannot be shadowed or tombstoned. With no\n * constraint layers resolved, `lens` equals `flattenPackRefs` — the legacy\n * pack-id contract.\n */\nexport function partitionStackRefs(stack: StackResolution): StackRefPartition {\n const lens: string[] = []\n const constraint: string[] = []\n for (const entry of stack.entries) {\n const target = entry.mode === \"constraint\" ? constraint : lens\n for (const ref of entry.refs) {\n if (ref.kind && ref.kind !== \"pack\") continue\n if (!target.includes(ref.ref)) target.push(ref.ref)\n }\n }\n return { lens, constraint }\n}\n","/**\n * SyncRunner — push refined corpus entries to a SinkPort. Agnostic: it scans\n * `entries/` (via resolveKnowledge), shapes each as a SinkItem, and pushes\n * through the injected sink. The sink (and its host binding) is config, not\n * code here. Sources stay local (raw archive); only refined knowledge syncs.\n */\n\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport { resolveKnowledge, type CorpusEntryQuery } from \"../knowledge/resolve.js\"\nimport type { SinkPort, SinkItem, SinkPushResult } from \"./types.js\"\n\nexport interface SyncRunnerOptions {\n readonly fs: FsPort\n readonly sink: SinkPort\n /** Which entries to sync (tags/kinds). Empty = all refined entries. */\n readonly select?: CorpusEntryQuery\n /** URI scheme for the item address. Default `corpus`. */\n readonly uriScheme?: string\n /** Pace between pushes (ms). Default 0. */\n readonly throttleMs?: number\n readonly sleep?: (ms: number) => Promise<void>\n}\n\nexport interface SyncReport {\n readonly pushed: number\n readonly skipped: number\n readonly failed: number\n readonly results: readonly SinkPushResult[]\n}\n\nexport class SyncRunner {\n constructor(private readonly opts: SyncRunnerOptions) {}\n\n async run(): Promise<SyncReport> {\n const scheme = this.opts.uriScheme ?? \"corpus\"\n const throttle = this.opts.throttleMs ?? 0\n const sleep = this.opts.sleep ?? ((ms: number) => new Promise(r => setTimeout(r, ms)))\n\n const entries = await resolveKnowledge({\n fs: this.opts.fs,\n query: this.opts.select ?? {},\n })\n\n const results: SinkPushResult[] = []\n let pushed = 0\n let skipped = 0\n let failed = 0\n\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i]!\n if (i > 0 && throttle > 0) await sleep(throttle)\n const item: SinkItem = {\n slug: e.slug,\n kind: e.kind,\n title: e.title,\n body: e.body,\n sources: e.sources,\n tags: e.tags,\n confidence: e.confidence,\n ...(e.access ? { access: e.access } : {}),\n uri: `${scheme}://${e.slug}`,\n }\n let res: SinkPushResult\n try {\n res = await this.opts.sink.push(item)\n } catch (err) {\n res = { uri: item.uri, ok: false, error: err instanceof Error ? err.message : String(err) }\n }\n results.push(res)\n if (res.skipped) skipped++\n else if (res.ok) pushed++\n else failed++\n }\n return { pushed, skipped, failed, results }\n }\n}\n","/**\n * Multi-reviewer score aggregation.\n *\n * High-stakes corpus entries (those flagged by curator policy as\n * needing N-reviewer review) get scored by multiple reviewers — the\n * single-reviewer path is fine for the bulk of the queue, but the\n * top quality tier deserves redundancy.\n *\n * Aggregation policy:\n * - **Median** is the default — robust to a single outlier reviewer.\n * - **Weighted-median** uses reviewer track-record weights so a\n * well-calibrated reviewer's score counts for more than a fresh /\n * under-calibrated one.\n *\n * Disagreement detection: when the spread between the highest and\n * lowest review exceeds a threshold, the aggregate carries a\n * `disagreement: true` flag — the curator's queue can route those\n * entries to human adjudication rather than auto-trust the median.\n *\n * Pure — no I/O. Inputs come from the lifecycle workflow; outputs\n * feed the gate evaluator.\n */\n\nexport interface ReviewerScore {\n /** AIP-23-style identity. */\n readonly reviewerIdentity: string\n /** 0..5 (matches metadata.corpus.qualityScore convention). */\n readonly score: number\n /**\n * Optional confidence weight from the reviewer's track record\n * (correlation with downstream utility/lift). Defaults to 1.0\n * for unknown reviewers. See `correlation.ts`.\n */\n readonly weight?: number\n readonly at: string\n readonly note?: string\n}\n\nexport interface AggregateOptions {\n /** Spread threshold above which `disagreement` is flagged. Default: 1.5. */\n readonly disagreementThreshold?: number\n /** When true, use weighted-median; else plain median. */\n readonly weighted?: boolean\n}\n\nexport interface AggregateResult {\n /** Aggregate qualityScore (0..5). */\n readonly aggregate: number\n /** Highest vs lowest review difference. */\n readonly spread: number\n /** True when spread > disagreementThreshold. */\n readonly disagreement: boolean\n /** Number of reviewers that contributed. */\n readonly sampleSize: number\n /** Per-reviewer breakdown for the curator UI. */\n readonly breakdown: readonly {\n readonly reviewerIdentity: string\n readonly score: number\n readonly weight: number\n }[]\n}\n\nconst DEFAULT_DISAGREEMENT_THRESHOLD = 1.5\n\n/**\n * Aggregate N reviewer scores into one final score + a disagreement\n * flag. Empty input → aggregate=0, disagreement=false (caller decides\n * whether that's an error).\n */\nexport function aggregateReviewerScores(\n reviews: readonly ReviewerScore[],\n opts: AggregateOptions = {}\n): AggregateResult {\n if (reviews.length === 0) {\n return Object.freeze({\n aggregate: 0,\n spread: 0,\n disagreement: false,\n sampleSize: 0,\n breakdown: Object.freeze([]),\n })\n }\n const threshold = opts.disagreementThreshold ?? DEFAULT_DISAGREEMENT_THRESHOLD\n const weighted = opts.weighted !== false // default true\n\n const breakdown = reviews.map((r) => ({\n reviewerIdentity: r.reviewerIdentity,\n score: r.score,\n weight: typeof r.weight === \"number\" && r.weight > 0 ? r.weight : 1,\n }))\n const scores = breakdown.map((b) => b.score)\n const min = Math.min(...scores)\n const max = Math.max(...scores)\n const spread = max - min\n\n const aggregate = weighted\n ? weightedMedian(breakdown)\n : plainMedian(scores)\n\n return Object.freeze({\n aggregate,\n spread,\n disagreement: spread > threshold,\n sampleSize: reviews.length,\n breakdown: Object.freeze(breakdown),\n })\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\nfunction plainMedian(values: readonly number[]): number {\n const sorted = [...values].sort((a, b) => a - b)\n const mid = Math.floor(sorted.length / 2)\n if (sorted.length % 2 === 0) {\n return (sorted[mid - 1]! + sorted[mid]!) / 2\n }\n return sorted[mid]!\n}\n\n/**\n * Weighted median: order by score, cumulate weights, pick the score\n * at which the cumulative weight first crosses half the total weight.\n * Robust to outliers AND to the well-calibrated reviewers getting\n * more say than the under-calibrated ones.\n */\nfunction weightedMedian(\n items: readonly { score: number; weight: number }[]\n): number {\n const sorted = [...items].sort((a, b) => a.score - b.score)\n const totalWeight = sorted.reduce((acc, it) => acc + it.weight, 0)\n if (totalWeight === 0) return plainMedian(items.map((i) => i.score))\n const half = totalWeight / 2\n let acc = 0\n for (let i = 0; i < sorted.length; i++) {\n acc += sorted[i]!.weight\n if (acc >= half) {\n // When acc lands exactly on half + the next item also has\n // identical cumulative weight, the median is the average of the\n // two adjacent scores (matches the symmetric definition).\n if (acc === half && i + 1 < sorted.length) {\n return (sorted[i]!.score + sorted[i + 1]!.score) / 2\n }\n return sorted[i]!.score\n }\n }\n return sorted[sorted.length - 1]!.score\n}\n","/**\n * Reviewer track record — per-reviewer history of (score → observed\n * outcome) used to compute calibration weights.\n *\n * Stored at `corpus/_calibration/reviewer-track-record.yaml`:\n *\n * reviewers:\n * \"ws://operators/quality-reviewer\":\n * - { entrySlug, qualityScore, observedUtility?, observedLift?, at }\n * \"ws://operators/junior-reviewer\":\n * - ...\n *\n * Append-only — every review pass adds rows. The calibration routine\n * reads the configured window (typically 90 days), correlates the\n * reviewer's scores against observed retrieval-quality outcomes, and\n * derives a weight in [0, 1] that feeds the multi-reviewer aggregator\n * (see `aggregate.ts`).\n */\n\nimport { parse as yamlParse, stringify as yamlStringify } from \"yaml\"\nimport type { FsPort } from \"../ports/fs.port.js\"\n\nexport interface TrackRecordEntry {\n readonly entrySlug: string\n /** Reviewer-assigned 0..5 quality score at review time. */\n readonly qualityScore: number\n /** Retrieval utility (0..1 — fraction of hits actually cited). */\n readonly observedUtility?: number\n /** Retrieval lift (>1 = boost vs baseline, <1 = drag). */\n readonly observedLift?: number\n readonly at: string\n}\n\ninterface TrackRecordShape {\n reviewers: Record<string, readonly TrackRecordEntry[]>\n}\n\nconst DEFAULT_PATH = \"_calibration/reviewer-track-record.yaml\"\n\nexport interface ReviewerTrackRecordOptions {\n readonly fs: FsPort\n /** Workspace-relative path. Defaults to `_calibration/reviewer-track-record.yaml`. */\n readonly path?: string\n}\n\nexport class ReviewerTrackRecord {\n private readonly path: string\n\n constructor(private readonly opts: ReviewerTrackRecordOptions) {\n this.path = opts.path ?? DEFAULT_PATH\n }\n\n /** Load the full record. Empty when the file doesn't exist yet. */\n async load(): Promise<Readonly<Record<string, readonly TrackRecordEntry[]>>> {\n if (!(await this.opts.fs.exists(this.path))) return {}\n const content = await this.opts.fs.readFile(this.path)\n if (!content.trim()) return {}\n const parsed = yamlParse(content) as Partial<TrackRecordShape> | null\n if (!parsed || typeof parsed.reviewers !== \"object\") return {}\n return Object.freeze(parsed.reviewers as Record<string, readonly TrackRecordEntry[]>)\n }\n\n /** Append one entry under a reviewer's identity. */\n async append(\n reviewerIdentity: string,\n entry: TrackRecordEntry\n ): Promise<void> {\n const existing = await this.load()\n const current = existing[reviewerIdentity] ?? []\n const next: TrackRecordShape = {\n reviewers: {\n ...existing,\n [reviewerIdentity]: [...current, entry],\n },\n }\n const content = yamlStringify(next)\n await this.opts.fs.writeFile(this.path, content)\n }\n\n /**\n * Read all entries for a reviewer in the last N days. Used by the\n * calibration routine to compute correlation on a rolling window.\n */\n async window(\n reviewerIdentity: string,\n days: number,\n now: Date\n ): Promise<readonly TrackRecordEntry[]> {\n const all = await this.load()\n const slice = all[reviewerIdentity] ?? []\n const cutoffMs = now.getTime() - days * 86_400_000\n return slice.filter((e) => Date.parse(e.at) >= cutoffMs)\n }\n\n /** Reviewer identities present in the record. */\n async listReviewers(): Promise<readonly string[]> {\n const all = await this.load()\n return Object.keys(all)\n }\n}\n","/**\n * Calibration — correlate a reviewer's qualityScore against the\n * downstream retrieval-quality outcomes (utility + lift). Reviewers\n * whose scores don't predict outcomes are miscalibrated; their\n * weight drops in the multi-reviewer aggregator until they re-train.\n *\n * Math: Pearson correlation coefficient on two parallel arrays.\n * Returns NaN-safe r in [-1, 1]. Threshold for \"calibrated\" is host\n * policy; the helper just reports.\n *\n * Pure — no I/O. Inputs come from `ReviewerTrackRecord.window`,\n * outputs feed the calibration routine + multi-reviewer aggregator.\n */\n\nimport type { TrackRecordEntry } from \"./track-record.js\"\n\nexport interface ReviewerCalibration {\n readonly reviewerIdentity: string\n readonly sampleSize: number\n /**\n * Pearson r in [-1, 1]. Higher = reviewer's qualityScore predicts\n * downstream outcomes better. Negative = reviewer is inversely\n * correlated (worse than random). NaN when sampleSize < 2 or all\n * scores are identical (no variance).\n */\n readonly correlationUtility: number\n readonly correlationLift: number\n /** Whether this reviewer meets the calibrated threshold. */\n readonly isCalibrated: boolean\n /** Suggested weight for the multi-reviewer aggregator (0..1). */\n readonly suggestedWeight: number\n /** Reason flag — useful for curator UI tooltips. */\n readonly status:\n | \"calibrated\"\n | \"miscalibrated\"\n | \"insufficient-sample\"\n | \"no-variance\"\n}\n\nexport interface CalibrationOptions {\n /** Minimum sample size to compute calibration. Defaults to 10. */\n readonly minSampleSize?: number\n /** Pearson r threshold above which a reviewer is \"calibrated\". Defaults to 0.4. */\n readonly calibratedThreshold?: number\n}\n\nconst DEFAULT_MIN_SAMPLE = 10\nconst DEFAULT_CALIBRATED_THRESHOLD = 0.4\n\n/**\n * Pearson correlation coefficient on two parallel numeric arrays.\n *\n * r = cov(X, Y) / (σ_X · σ_Y)\n *\n * Returns NaN when:\n * - either array is < 2 elements\n * - either array has zero variance (all values identical)\n *\n * NaN is the explicit \"I can't compute this\" signal — callers\n * decide whether NaN means \"default to neutral weight\" or \"flag for\n * human review\".\n */\nexport function pearsonCorrelation(\n xs: readonly number[],\n ys: readonly number[]\n): number {\n if (xs.length !== ys.length) {\n throw new Error(\n `pearsonCorrelation: array length mismatch (xs=${xs.length}, ys=${ys.length})`\n )\n }\n const n = xs.length\n if (n < 2) return Number.NaN\n\n let sumX = 0\n let sumY = 0\n for (let i = 0; i < n; i++) {\n sumX += xs[i]!\n sumY += ys[i]!\n }\n const meanX = sumX / n\n const meanY = sumY / n\n\n let cov = 0\n let varX = 0\n let varY = 0\n for (let i = 0; i < n; i++) {\n const dx = xs[i]! - meanX\n const dy = ys[i]! - meanY\n cov += dx * dy\n varX += dx * dx\n varY += dy * dy\n }\n if (varX === 0 || varY === 0) return Number.NaN\n return cov / Math.sqrt(varX * varY)\n}\n\n/**\n * Compute a single reviewer's calibration from their track-record\n * window. Returns a ReviewerCalibration summary.\n *\n * Strategy: average the utility-correlation and lift-correlation\n * (when both are available). If only one outcome was recorded\n * across the window (rare), use that one alone.\n */\nexport function computeReviewerCalibration(\n reviewerIdentity: string,\n entries: readonly TrackRecordEntry[],\n opts: CalibrationOptions = {}\n): ReviewerCalibration {\n const minSample = opts.minSampleSize ?? DEFAULT_MIN_SAMPLE\n const threshold = opts.calibratedThreshold ?? DEFAULT_CALIBRATED_THRESHOLD\n\n const utilityRows = entries.filter(\n (e) => typeof e.observedUtility === \"number\"\n )\n const liftRows = entries.filter((e) => typeof e.observedLift === \"number\")\n\n if (\n Math.max(utilityRows.length, liftRows.length) < minSample\n ) {\n return Object.freeze({\n reviewerIdentity,\n sampleSize: Math.max(utilityRows.length, liftRows.length),\n correlationUtility: Number.NaN,\n correlationLift: Number.NaN,\n isCalibrated: false,\n suggestedWeight: 1, // neutral — no penalty for insufficient data\n status: \"insufficient-sample\" as const,\n })\n }\n\n const corrUtil =\n utilityRows.length >= minSample\n ? pearsonCorrelation(\n utilityRows.map((e) => e.qualityScore),\n utilityRows.map((e) => e.observedUtility!)\n )\n : Number.NaN\n const corrLift =\n liftRows.length >= minSample\n ? pearsonCorrelation(\n liftRows.map((e) => e.qualityScore),\n liftRows.map((e) => e.observedLift!)\n )\n : Number.NaN\n\n // Compose a single calibration signal: average of available\n // correlations. NaN handling: if both are NaN, the reviewer's\n // scores have no variance in the window (one-note scoring), so\n // flag and de-weight.\n const available = [corrUtil, corrLift].filter((x) => !Number.isNaN(x))\n if (available.length === 0) {\n return Object.freeze({\n reviewerIdentity,\n sampleSize: entries.length,\n correlationUtility: corrUtil,\n correlationLift: corrLift,\n isCalibrated: false,\n suggestedWeight: 0.3, // de-weight but not zero\n status: \"no-variance\" as const,\n })\n }\n const composite = available.reduce((a, b) => a + b, 0) / available.length\n\n // Weight derivation: linearly map [threshold, 1] → [0.7, 1.0] for\n // calibrated, [-1, threshold] → [0, 0.7] for miscalibrated.\n // Negative correlation is worst-case = weight 0.\n let weight: number\n let isCalibrated: boolean\n if (composite >= threshold) {\n isCalibrated = true\n weight = 0.7 + 0.3 * ((composite - threshold) / (1 - threshold))\n } else {\n isCalibrated = false\n weight = Math.max(\n 0,\n 0.7 * ((composite + 1) / (threshold + 1))\n )\n }\n\n return Object.freeze({\n reviewerIdentity,\n sampleSize: entries.length,\n correlationUtility: corrUtil,\n correlationLift: corrLift,\n isCalibrated,\n suggestedWeight: Math.max(0, Math.min(1, weight)),\n status: isCalibrated ? \"calibrated\" : \"miscalibrated\",\n })\n}\n","/**\n * CorpusValidator — validate a workspace snapshot against the AIP JSON\n * Schemas (the spec source-of-truth at\n * projects/agentproto/agentproto/specs/resources/aip-XX/draft/).\n *\n * The validator is constructed once with an AJV instance pre-loaded\n * with every referenced schema, then run against a `ParsedFile` or a\n * whole `CorpusWorkspaceSnapshot`. Schema loading is delegated to a\n * factory function so the kit doesn't carry the spec JSON inside — the\n * host (cloud adapter or local CLI) supplies the schemas at boot.\n *\n * Why AJV not zod: the AgentProto zod schemas at @agentproto/(aip)/schema\n * are partially generated stubs today (z.any() oneOf branches in\n * knowledge/collection/playbook). AJV against the canonical JSON\n * Schemas is the authoritative path until the zod stubs are\n * regenerated from the JSON Schemas. The corpus kit is the place that\n * exercises both, so this discipline matters.\n */\n\nimport type { ValidateFunction } from \"ajv/dist/2020.js\"\nimport Ajv2020 from \"ajv/dist/2020.js\"\nimport addFormats from \"ajv-formats\"\nimport type {\n CorpusWorkspaceSnapshot,\n FileKind,\n ParsedFile,\n ValidationIssue,\n ValidationResult,\n} from \"../types.js\"\n\n/**\n * Map from FileKind → JSON Schema key. The schema bundle the host\n * supplies must include these keys.\n */\nexport type AipSchemaKey =\n | \"knowledge\" // AIP-10 — entries, sources, workspace (oneOf inside)\n | \"collection\" // AIP-18 — both COLLECTION.md (schema) and ITEM.md (item)\n | \"playbook\" // AIP-12\n | \"operator\" // AIP-9\n | \"workflow\" // AIP-15\n | \"routine\" // AIP-41\n\nexport interface AipSchemaBundle {\n /** Schemas keyed by AIP doctype. Values are JSON Schema documents. */\n readonly schemas: Readonly<Record<AipSchemaKey, unknown>>\n /**\n * External schemas to register with AJV before compilation (so\n * `$ref` cross-document references resolve). The known cross-refs\n * today are AIP-16 IO and AIP-17 RUNNER.\n */\n readonly externals?: ReadonlyArray<unknown>\n}\n\nconst FILE_KIND_TO_SCHEMA: Partial<Record<FileKind, AipSchemaKey>> = {\n \"knowledge-workspace\": \"knowledge\",\n \"knowledge-source\": \"knowledge\",\n \"knowledge-entry\": \"knowledge\",\n \"collection-schema\": \"collection\",\n \"collection-item\": \"collection\",\n \"playbook\": \"playbook\",\n \"operator\": \"operator\",\n \"workflow\": \"workflow\",\n \"routine\": \"routine\",\n}\n\nexport interface CorpusValidatorOptions {\n readonly bundle: AipSchemaBundle\n}\n\nexport class CorpusValidator {\n private readonly validators: Readonly<Record<AipSchemaKey, ValidateFunction>>\n\n constructor(opts: CorpusValidatorOptions) {\n const ajv = new Ajv2020({\n strict: false,\n allErrors: true,\n allowUnionTypes: true,\n })\n addFormats(ajv)\n\n // Register externals first so refs from doctype schemas resolve.\n for (const ext of opts.bundle.externals ?? []) {\n const id = (ext as { $id?: string }).$id\n if (id && !ajv.getSchema(id)) ajv.addSchema(ext as object)\n }\n\n const validators: Record<AipSchemaKey, ValidateFunction> = {} as Record<\n AipSchemaKey,\n ValidateFunction\n >\n for (const key of Object.keys(opts.bundle.schemas) as AipSchemaKey[]) {\n validators[key] = ajv.compile(opts.bundle.schemas[key] as object)\n }\n this.validators = validators\n }\n\n /**\n * Validate a single parsed file. Returns issues + a valid flag.\n * Unknown FileKind (\"unknown\" bucket) is reported as a single info\n * issue — the file exists but doesn't fit AIP conventions.\n */\n validateFile(file: ParsedFile): ValidationResult {\n if (file.kind === \"unknown\") {\n return {\n valid: false,\n issues: [\n {\n path: file.path,\n instancePath: \"/\",\n message:\n \"file location does not match any AIP convention; expected under sources/, entries/, collections/, playbooks/, operators/, workflows/, or routines/\",\n severity: \"info\",\n },\n ],\n }\n }\n\n const schemaKey = FILE_KIND_TO_SCHEMA[file.kind]\n if (!schemaKey) {\n // Defensive — shouldn't happen, but never throw on classification drift.\n return {\n valid: true,\n issues: [],\n }\n }\n\n const validator = this.validators[schemaKey]\n const ok = validator(file.frontmatter)\n if (ok) return { valid: true, issues: [] }\n\n const issues: ValidationIssue[] = (validator.errors ?? []).map((e) => ({\n path: file.path,\n instancePath: e.instancePath || \"/\",\n message: `${e.message}${\n e.params && Object.keys(e.params).length > 0\n ? ` (${JSON.stringify(e.params)})`\n : \"\"\n }`,\n severity: \"error\" as const,\n }))\n return { valid: false, issues }\n }\n\n /**\n * Validate every file in a workspace snapshot. Returns a flat list\n * of issues across all files plus a `valid` flag that's true only\n * if zero error-severity issues exist.\n */\n validateWorkspace(snapshot: CorpusWorkspaceSnapshot): ValidationResult {\n const all: ValidationIssue[] = []\n const buckets: ReadonlyArray<readonly ParsedFile[]> = [\n snapshot.workspace ? [snapshot.workspace] : [],\n snapshot.sources,\n snapshot.entries,\n snapshot.collections,\n snapshot.collectionItems,\n snapshot.playbooks,\n snapshot.operators,\n snapshot.workflows,\n snapshot.routines,\n snapshot.unknown,\n ]\n for (const bucket of buckets) {\n for (const file of bucket) {\n all.push(...this.validateFile(file).issues)\n }\n }\n return {\n valid: all.every((i) => i.severity !== \"error\"),\n issues: Object.freeze(all),\n }\n }\n}\n","/**\n * CorpusLinter — implements the AIP-10 lint kinds declared in\n * KNOWLEDGE.md.lints[]. Five canonical kinds + `custom` delegation\n * hook for hosts that ship their own checks.\n *\n * Lint kinds (per AIP-10 spec):\n * - require-source — entries of kinds X MUST have ≥1 source ref\n * - min-confidence — entries of kinds X SHOULD have confidence ≥ N\n * - max-age — entries of kinds X with updated_at older than N days\n * - broken-ref — sources/links/supersedes references that don't resolve\n * - orphan — entries that no other entry references (incoming = 0)\n * - custom — delegated to host-supplied callbacks keyed by lint id\n *\n * The linter assumes the workspace has already passed schema validation.\n * Running lint on invalid workspace yields garbage. Callers should run\n * the validator first; the writer pipeline enforces this.\n */\n\nimport type {\n CorpusWorkspaceSnapshot,\n LintIssue,\n LintReport,\n ParsedFile,\n} from \"../types.js\"\nimport type { ClockPort } from \"../ports/clock.port.js\"\n\ninterface LintDeclaration {\n readonly id: string\n readonly kind:\n | \"require-source\"\n | \"min-confidence\"\n | \"max-age\"\n | \"broken-ref\"\n | \"orphan\"\n | \"custom\"\n readonly appliesTo: string\n readonly severity: \"error\" | \"warn\" | \"info\"\n readonly params?: Readonly<Record<string, unknown>>\n}\n\nexport type CustomLintRunner = (\n decl: LintDeclaration,\n snapshot: CorpusWorkspaceSnapshot\n) => readonly LintIssue[]\n\nexport interface CorpusLinterOptions {\n readonly clock: ClockPort\n /** Per-id implementations for `kind: custom` lints. */\n readonly customRunners?: Readonly<Record<string, CustomLintRunner>>\n}\n\nexport class CorpusLinter {\n constructor(private readonly opts: CorpusLinterOptions) {}\n\n lint(snapshot: CorpusWorkspaceSnapshot): LintReport {\n const decls = extractLintDeclarations(snapshot)\n const issues: LintIssue[] = []\n\n for (const decl of decls) {\n switch (decl.kind) {\n case \"require-source\":\n issues.push(...this.lintRequireSource(decl, snapshot))\n break\n case \"min-confidence\":\n issues.push(...this.lintMinConfidence(decl, snapshot))\n break\n case \"max-age\":\n issues.push(...this.lintMaxAge(decl, snapshot))\n break\n case \"broken-ref\":\n issues.push(...this.lintBrokenRef(decl, snapshot))\n break\n case \"orphan\":\n issues.push(...this.lintOrphan(decl, snapshot))\n break\n case \"custom\": {\n const runner = this.opts.customRunners?.[decl.id]\n if (runner) issues.push(...runner(decl, snapshot))\n break\n }\n }\n }\n\n return reportFrom(issues)\n }\n\n // ── Lint implementations ────────────────────────────────────────────\n\n private lintRequireSource(\n decl: LintDeclaration,\n snapshot: CorpusWorkspaceSnapshot\n ): LintIssue[] {\n const out: LintIssue[] = []\n for (const entry of snapshot.entries) {\n if (!matchesAppliesTo(entry, decl.appliesTo)) continue\n const sources = (entry.frontmatter.sources ?? []) as readonly unknown[]\n if (sources.length === 0) {\n out.push({\n lintId: decl.id,\n path: entry.path,\n message: `entry has no sources[] (kind=${entry.frontmatter.kind ?? \"?\"})`,\n severity: decl.severity,\n })\n }\n }\n return out\n }\n\n private lintMinConfidence(\n decl: LintDeclaration,\n snapshot: CorpusWorkspaceSnapshot\n ): LintIssue[] {\n const min = numberParam(decl, \"min\", 0.5)\n const out: LintIssue[] = []\n for (const entry of snapshot.entries) {\n if (!matchesAppliesTo(entry, decl.appliesTo)) continue\n const c = entry.frontmatter.confidence\n if (typeof c === \"number\" && c < min) {\n out.push({\n lintId: decl.id,\n path: entry.path,\n message: `confidence ${c} < min ${min}`,\n severity: decl.severity,\n })\n }\n }\n return out\n }\n\n private lintMaxAge(\n decl: LintDeclaration,\n snapshot: CorpusWorkspaceSnapshot\n ): LintIssue[] {\n const days = numberParam(decl, \"days\", 365)\n const cutoffMs = this.opts.clock.nowMs() - days * 86_400_000\n const out: LintIssue[] = []\n for (const entry of snapshot.entries) {\n if (!matchesAppliesTo(entry, decl.appliesTo)) continue\n const updated = entry.frontmatter.updated_at\n if (typeof updated !== \"string\") continue\n const t = Date.parse(updated)\n if (Number.isNaN(t)) continue\n if (t < cutoffMs) {\n out.push({\n lintId: decl.id,\n path: entry.path,\n message: `updated_at ${updated} older than ${days}d`,\n severity: decl.severity,\n })\n }\n }\n return out\n }\n\n private lintBrokenRef(\n decl: LintDeclaration,\n snapshot: CorpusWorkspaceSnapshot\n ): LintIssue[] {\n const sourceIds = new Set<string>()\n for (const s of snapshot.sources) {\n const id = s.frontmatter.id\n if (typeof id === \"string\") sourceIds.add(id)\n }\n const entrySlugs = new Set<string>()\n for (const e of snapshot.entries) {\n const slug = e.frontmatter.slug\n if (typeof slug === \"string\") entrySlugs.add(slug)\n }\n\n const out: LintIssue[] = []\n for (const entry of snapshot.entries) {\n if (!matchesAppliesTo(entry, decl.appliesTo)) continue\n // sources[] — must resolve in source registry\n const sources = (entry.frontmatter.sources ?? []) as readonly unknown[]\n for (const s of sources) {\n if (typeof s === \"string\" && !sourceIds.has(s)) {\n out.push({\n lintId: decl.id,\n path: entry.path,\n message: `unresolved source ref: ${s}`,\n severity: decl.severity,\n })\n }\n }\n // supersedes / contradicts / links — must resolve in entry slug set\n for (const field of [\"supersedes\", \"contradicts\", \"links\"] as const) {\n const refs = (entry.frontmatter[field] ?? []) as readonly unknown[]\n for (const r of refs) {\n if (typeof r === \"string\" && !entrySlugs.has(r)) {\n out.push({\n lintId: decl.id,\n path: entry.path,\n message: `unresolved ${field} ref: ${r}`,\n severity: decl.severity,\n })\n }\n }\n }\n }\n return out\n }\n\n private lintOrphan(\n decl: LintDeclaration,\n snapshot: CorpusWorkspaceSnapshot\n ): LintIssue[] {\n // Build the incoming-reference set across all entries\n const incoming = new Set<string>()\n for (const e of snapshot.entries) {\n for (const field of [\"supersedes\", \"contradicts\", \"links\"] as const) {\n const refs = (e.frontmatter[field] ?? []) as readonly unknown[]\n for (const r of refs) {\n if (typeof r === \"string\") incoming.add(r)\n }\n }\n }\n\n const out: LintIssue[] = []\n for (const entry of snapshot.entries) {\n if (!matchesAppliesTo(entry, decl.appliesTo)) continue\n const slug = entry.frontmatter.slug\n if (typeof slug !== \"string\") continue\n if (!incoming.has(slug)) {\n out.push({\n lintId: decl.id,\n path: entry.path,\n message: `entry has no incoming references (orphan)`,\n severity: decl.severity,\n })\n }\n }\n return out\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────\n\nfunction extractLintDeclarations(\n snapshot: CorpusWorkspaceSnapshot\n): readonly LintDeclaration[] {\n if (!snapshot.workspace) return []\n const raw = (snapshot.workspace.frontmatter.lints ?? []) as readonly unknown[]\n const decls: LintDeclaration[] = []\n for (const r of raw) {\n if (!isLintDeclaration(r)) continue\n decls.push(r)\n }\n return decls\n}\n\nfunction isLintDeclaration(x: unknown): x is LintDeclaration {\n if (typeof x !== \"object\" || x === null) return false\n const o = x as Record<string, unknown>\n return (\n typeof o.id === \"string\" &&\n typeof o.kind === \"string\" &&\n typeof o.appliesTo === \"string\" &&\n typeof o.severity === \"string\"\n )\n}\n\nfunction matchesAppliesTo(entry: ParsedFile, appliesTo: string): boolean {\n if (appliesTo === \"*\") return true\n // Compare the AIP-10 `kind` field (lowercase) against the lint's\n // appliesTo PascalCase entity type. We compare case-insensitively\n // because entities are declared as e.g. \"Principle\" in KNOWLEDGE.md\n // but entries set `kind: principle`.\n const kind = entry.frontmatter.kind\n if (typeof kind !== \"string\") return false\n return appliesTo.toLowerCase() === kind.toLowerCase()\n}\n\nfunction numberParam(\n decl: LintDeclaration,\n key: string,\n fallback: number\n): number {\n const params = decl.params ?? {}\n const v = (params as Record<string, unknown>)[key]\n return typeof v === \"number\" ? v : fallback\n}\n\nfunction reportFrom(issues: LintIssue[]): LintReport {\n let errorCount = 0\n let warnCount = 0\n let infoCount = 0\n for (const i of issues) {\n if (i.severity === \"error\") errorCount++\n else if (i.severity === \"warn\") warnCount++\n else infoCount++\n }\n return {\n issues: Object.freeze([...issues]),\n errorCount,\n warnCount,\n infoCount,\n }\n}\n","/**\n * Candidate state machine.\n *\n * AIP-18 collection COLLECTION.md declares the `statuses[]` array\n * with explicit `transitionsTo`. This module enforces those\n * transitions at the corpus-kit boundary so callers can never\n * silently land an item in an illegal state.\n *\n * The corpus' canonical candidate collection (per the plan) has:\n *\n * discovered → analyzed | rejected\n * analyzed → approved | rejected | needs-work\n * needs-work → analyzed | rejected\n * approved = terminal\n * rejected = terminal\n *\n * This module is pure (no I/O). The lifecycle workflow caller pairs\n * it with the writer + emitter to durably enact each transition.\n */\n\nexport type CandidateStatus =\n | \"discovered\"\n | \"analyzed\"\n | \"needs-work\"\n | \"approved\"\n | \"rejected\"\n\n/**\n * Default transition graph mirroring the corpus-candidate AIP-18\n * collection shape shipped in the marketing preset. Hosts that load a\n * custom collection schema may override via\n * `transitionGraphFromCollection()`.\n */\nexport const DEFAULT_TRANSITIONS: Readonly<\n Record<CandidateStatus, readonly CandidateStatus[]>\n> = Object.freeze({\n discovered: [\"analyzed\", \"rejected\"],\n analyzed: [\"approved\", \"rejected\", \"needs-work\"],\n \"needs-work\": [\"analyzed\", \"rejected\"],\n approved: [],\n rejected: [],\n})\n\nexport interface TransitionCheck {\n readonly allowed: boolean\n readonly reason?: string\n}\n\n/**\n * Check whether a candidate can transition from `from` to `to`.\n */\nexport function canTransition(\n from: CandidateStatus,\n to: CandidateStatus,\n graph: Readonly<\n Record<CandidateStatus, readonly CandidateStatus[]>\n > = DEFAULT_TRANSITIONS\n): TransitionCheck {\n if (from === to) {\n return { allowed: false, reason: \"same-status (no-op)\" }\n }\n const allowedTargets = graph[from] ?? []\n if (allowedTargets.length === 0) {\n return {\n allowed: false,\n reason: `\"${from}\" is terminal — no outgoing transitions`,\n }\n }\n if (!allowedTargets.includes(to)) {\n return {\n allowed: false,\n reason: `\"${from}\" cannot transition to \"${to}\". Allowed: ${allowedTargets.join(\", \")}`,\n }\n }\n return { allowed: true }\n}\n\n/**\n * Build a transition graph from a parsed COLLECTION.md frontmatter.\n * Hosts call this once at boot to align the candidate state machine\n * with whatever collection schema the workspace ships.\n *\n * Falls back to DEFAULT_TRANSITIONS if the frontmatter doesn't carry\n * a recognizable `statuses[]` array — the caller is encouraged to\n * pass the parsed frontmatter directly rather than re-flattening.\n */\nexport function transitionGraphFromCollection(\n fm: Readonly<Record<string, unknown>>\n): Readonly<Record<string, readonly string[]>> {\n const statuses = (fm.statuses ?? []) as readonly unknown[]\n const graph: Record<string, string[]> = {}\n for (const s of statuses) {\n if (typeof s !== \"object\" || s === null) continue\n const o = s as { id?: unknown; transitionsTo?: unknown; terminal?: unknown }\n if (typeof o.id !== \"string\") continue\n if (o.terminal === true) {\n graph[o.id] = []\n continue\n }\n if (Array.isArray(o.transitionsTo)) {\n graph[o.id] = (o.transitionsTo as unknown[]).filter(\n (x): x is string => typeof x === \"string\"\n )\n }\n }\n return Object.keys(graph).length > 0 ? Object.freeze(graph) : DEFAULT_TRANSITIONS\n}\n\nexport class IllegalTransitionError extends Error {\n constructor(\n readonly from: CandidateStatus,\n readonly to: CandidateStatus,\n readonly reason: string\n ) {\n super(\n `IllegalTransitionError: ${from} → ${to} is not allowed (${reason})`\n )\n this.name = \"IllegalTransitionError\"\n }\n}\n\n/**\n * Validate a transition and throw if disallowed. Convenience wrapper\n * around canTransition for callers that want fail-fast semantics.\n */\nexport function assertTransition(\n from: CandidateStatus,\n to: CandidateStatus,\n graph?: Readonly<Record<CandidateStatus, readonly CandidateStatus[]>>\n): void {\n const check = canTransition(from, to, graph)\n if (!check.allowed) {\n throw new IllegalTransitionError(from, to, check.reason ?? \"no reason\")\n }\n}\n","/**\n * Auto-promote gate — evaluates a candidate against\n * `KNOWLEDGE.md.metadata.corpus.autoPromote.requires`.\n *\n * The plan's auto-promote requirements (from the workspace manifest\n * example) typically include:\n *\n * qualityScore: { min: 4.2 }\n * riskScore: { max: 1.5 }\n * hasArchiveHash: true\n * requiredFields: [why_it_works, transferable_pattern, use_when, avoid_when]\n * notRestricted: true\n *\n * This gate returns a structured GateResult with pass/fail + the\n * specific rules that failed, so the caller can either auto-promote\n * (all pass) or route to human review (corpus-review collection)\n * with the failure reasons attached.\n *\n * Pure — no I/O.\n */\n\nimport type { CorpusWorkspaceSnapshot } from \"../types.js\"\n\nexport interface AutoPromoteRequirements {\n readonly qualityScore?: { min?: number; max?: number }\n readonly riskScore?: { min?: number; max?: number }\n readonly hasArchiveHash?: boolean\n readonly requiredFields?: readonly string[]\n readonly notRestricted?: boolean\n}\n\nexport interface AutoPromoteConfig {\n readonly enabled: boolean\n readonly requires?: AutoPromoteRequirements\n}\n\nexport interface CandidateForGate {\n /** Parsed candidate frontmatter (analyzed state) + body. */\n readonly frontmatter: Readonly<Record<string, unknown>>\n readonly body: string\n /** Optional analysis output — fields the analyst produced. */\n readonly analysis?: Readonly<Record<string, unknown>>\n}\n\nexport interface GateFailure {\n readonly rule: string\n readonly message: string\n}\n\nexport interface GateResult {\n readonly passed: boolean\n readonly failures: readonly GateFailure[]\n /** True when the workspace itself has auto-promote disabled. */\n readonly disabled: boolean\n}\n\n/**\n * Read the auto-promote config from a workspace snapshot. Returns\n * a \"disabled\" config if the workspace doesn't declare one — the\n * gate will short-circuit to \"always require human review\".\n */\nexport function extractAutoPromoteConfig(\n snapshot: CorpusWorkspaceSnapshot\n): AutoPromoteConfig {\n const ws = snapshot.workspace\n if (!ws) return { enabled: false }\n const corpus = (ws.frontmatter.metadata as { corpus?: unknown })\n ?.corpus as { autoPromote?: AutoPromoteConfig } | undefined\n if (!corpus?.autoPromote) return { enabled: false }\n return corpus.autoPromote\n}\n\n/**\n * Evaluate a candidate against the workspace's auto-promote config.\n * Returns `passed: true` only when every declared requirement holds.\n */\nexport function evaluateGate(\n candidate: CandidateForGate,\n config: AutoPromoteConfig\n): GateResult {\n if (!config.enabled) {\n return { passed: false, failures: [], disabled: true }\n }\n const requires = config.requires ?? {}\n const failures: GateFailure[] = []\n\n // Look at both candidate-level metadata.corpus.* (for promoted-from-analyzed\n // shape) and the candidate's flat fields (for AIP-18 collection items\n // whose fields live at the top level of frontmatter).\n const flat = candidate.frontmatter\n const corpusMeta =\n (flat.metadata as { corpus?: Record<string, unknown> })?.corpus ?? {}\n // Prefer corpus-namespaced fields when present (analyzed → promoted\n // path), falling back to flat ITEM.md fields (AIP-18 raw shape).\n const get = (key: string): unknown => {\n if (corpusMeta[key] !== undefined) return corpusMeta[key]\n if (flat[key] !== undefined) return flat[key]\n return undefined\n }\n\n // qualityScore\n if (requires.qualityScore) {\n const q = get(\"qualityScore\")\n if (typeof q !== \"number\") {\n failures.push({\n rule: \"qualityScore\",\n message: \"qualityScore is missing (required by autoPromote)\",\n })\n } else {\n if (requires.qualityScore.min !== undefined && q < requires.qualityScore.min) {\n failures.push({\n rule: \"qualityScore\",\n message: `qualityScore ${q} < min ${requires.qualityScore.min}`,\n })\n }\n if (requires.qualityScore.max !== undefined && q > requires.qualityScore.max) {\n failures.push({\n rule: \"qualityScore\",\n message: `qualityScore ${q} > max ${requires.qualityScore.max}`,\n })\n }\n }\n }\n\n // riskScore\n if (requires.riskScore) {\n const r = get(\"riskScore\")\n if (typeof r !== \"number\") {\n failures.push({\n rule: \"riskScore\",\n message: \"riskScore is missing (required by autoPromote)\",\n })\n } else {\n if (requires.riskScore.min !== undefined && r < requires.riskScore.min) {\n failures.push({\n rule: \"riskScore\",\n message: `riskScore ${r} < min ${requires.riskScore.min}`,\n })\n }\n if (requires.riskScore.max !== undefined && r > requires.riskScore.max) {\n failures.push({\n rule: \"riskScore\",\n message: `riskScore ${r} > max ${requires.riskScore.max}`,\n })\n }\n }\n }\n\n // hasArchiveHash — the candidate must point at a source whose\n // content_hash exists. We look at the candidate's `contentHash`\n // field (the AIP-18 ITEM convention) for a quick check.\n if (requires.hasArchiveHash) {\n const h = get(\"contentHash\") ?? get(\"content_hash\")\n if (typeof h !== \"string\" || !/^(sha256|sha512|blake3):/.test(h)) {\n failures.push({\n rule: \"hasArchiveHash\",\n message: \"candidate has no archive-grade content_hash\",\n })\n }\n }\n\n // requiredFields — every named field must be present and non-empty\n // in the analysis output (typically the body of the ITEM.md or the\n // candidate's `analysis` block).\n if (requires.requiredFields && requires.requiredFields.length > 0) {\n const analysis = candidate.analysis ?? {}\n const body = candidate.body\n for (const field of requires.requiredFields) {\n const inAnalysis =\n (analysis as Record<string, unknown>)[field]\n const inBody = body.includes(`## ${humanize(field)}`) ||\n body.includes(`## ${field}`)\n if (\n (typeof inAnalysis !== \"string\" || inAnalysis.trim().length === 0) &&\n !inBody\n ) {\n failures.push({\n rule: \"requiredFields\",\n message: `candidate is missing required field \"${field}\" (not in analysis.${field} nor in body section \"## ${humanize(field)}\")`,\n })\n }\n }\n }\n\n // notRestricted — candidate's metadata.corpus.access.classification\n // must not be \"restricted\" or \"secret\".\n if (requires.notRestricted) {\n const access =\n (corpusMeta as { access?: { classification?: string } }).access\n const cls = access?.classification\n if (cls === \"restricted\" || cls === \"secret\") {\n failures.push({\n rule: \"notRestricted\",\n message: `candidate access.classification is \"${cls}\" — fails notRestricted gate`,\n })\n }\n }\n\n return {\n passed: failures.length === 0,\n failures: Object.freeze(failures),\n disabled: false,\n }\n}\n\n/** snake_case + camelCase → \"Snake case\" / \"Camel case\" for body matching. */\nfunction humanize(field: string): string {\n const spaced = field\n .replace(/_/g, \" \")\n .replace(/([a-z])([A-Z])/g, \"$1 $2\")\n .toLowerCase()\n return spaced.charAt(0).toUpperCase() + spaced.slice(1)\n}\n","/**\n * Promote workflow — turn an analyzed candidate into a published\n * AIP-10 entry. The fan-out the plan describes:\n *\n * 1. Validate the promotion request (gate check, slug uniqueness)\n * 2. Acquire workspace lock (atomicity across the multi-file write)\n * 3. Write the entry file (AIP-10 conformant frontmatter + body)\n * 4. Update _index.md (faceted catalog regen)\n * 5. Sync to backing engine via CorpusIndexer\n * 6. Append corpus.entry.promoted event to _log.md\n * 7. Take the candidate row out of the sidecar (or update the\n * AIP-18 ITEM.md if it was materialized already)\n *\n * Idempotent on candidate.id — re-running promote for the same id\n * reuses the existing entry path rather than duplicating. The\n * workspace lock guards against concurrent promoters.\n *\n * Pure-ish: the workflow itself is logic + orchestration; every I/O\n * effect goes through the injected reader/writer/emitter/indexer.\n */\n\nimport type { CorpusWorkspaceSnapshot } from \"../types.js\"\nimport type { ClockPort } from \"../ports/clock.port.js\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport { CorpusWorkspaceReader } from \"../workspace/reader.js\"\nimport {\n CorpusWorkspaceWriter,\n type MarkdownDoc,\n} from \"../workspace/writer.js\"\nimport { CorpusEventEmitter } from \"../events/emitter.js\"\nimport { CorpusIndexer } from \"../index/indexer.js\"\nimport { evaluateGate, extractAutoPromoteConfig } from \"./gate.js\"\nimport { appendAttestation, makeAttestation } from \"./attestations.js\"\nimport type { IdentityPort } from \"../ports/identity.port.js\"\n\nexport interface PromoteOptions {\n /** Workspace root inside FsPort (typically \"\"). */\n readonly workspacePath: string\n /** Slug of the entry to create (or update, if it already exists). */\n readonly entrySlug: string\n /** AIP-10 entry kind (principle | pattern | …). */\n readonly entryKind: string\n /** Path of the entry within the workspace, e.g. entries/patterns/2026/foo.md */\n readonly entryPath: string\n /** AIP-10 entry frontmatter to publish. */\n readonly frontmatter: Readonly<Record<string, unknown>>\n /** Entry body (markdown after frontmatter). */\n readonly body: string\n /**\n * Optional candidate id to consume from a sidecar. When provided,\n * the workflow removes the row from `collections/<name>/_candidates.yaml`\n * on success (caller specifies the collection via `candidateSidecar`).\n */\n readonly candidateId?: string\n readonly candidateSidecarPath?: string\n /**\n * Bypass the auto-promote gate. Used when a curator manually\n * approves a candidate that failed the gate (corpus-review path).\n * The emitted event still records the bypass.\n */\n readonly bypassGate?: boolean\n}\n\nexport interface PromoteResult {\n readonly entryPath: string\n readonly entryVersionToken: string\n readonly chunkCount: number\n readonly gatePassed: boolean\n readonly bypassed: boolean\n}\n\nexport interface PromoteContext {\n readonly fs: FsPort\n readonly clock: ClockPort\n readonly identity: IdentityPort\n readonly indexer: CorpusIndexer\n}\n\nexport class PromoteRejectedError extends Error {\n constructor(\n readonly entrySlug: string,\n readonly failures: ReadonlyArray<{ rule: string; message: string }>\n ) {\n super(\n `PromoteRejectedError: ${entrySlug} failed auto-promote gate — ${failures\n .map((f) => `[${f.rule}] ${f.message}`)\n .join(\" / \")}`\n )\n this.name = \"PromoteRejectedError\"\n }\n}\n\n/**\n * Workspace-scoped promoter. Construct once per workspace + per\n * actor (identity is captured by the injected IdentityPort).\n */\nexport class CorpusPromoter {\n constructor(private readonly ctx: PromoteContext) {}\n\n async promote(opts: PromoteOptions): Promise<PromoteResult> {\n const reader = new CorpusWorkspaceReader({ fs: this.ctx.fs })\n const writer = new CorpusWorkspaceWriter({ fs: this.ctx.fs })\n const emitter = new CorpusEventEmitter({\n fs: this.ctx.fs,\n clock: this.ctx.clock,\n identity: this.ctx.identity,\n workspaceRoot: opts.workspacePath,\n })\n\n // Acquire workspace transaction lock (multi-file write).\n const lockPath = joinPath(opts.workspacePath, \"_log.md\")\n return await writer.transaction(lockPath, async () => {\n const snapshot = await reader.read(opts.workspacePath)\n\n // Gate check unless explicitly bypassed.\n let gatePassed = false\n let bypassed = false\n if (opts.bypassGate) {\n bypassed = true\n } else {\n const config = extractAutoPromoteConfig(snapshot)\n const result = evaluateGate(\n {\n frontmatter: opts.frontmatter,\n body: opts.body,\n },\n config\n )\n gatePassed = result.passed\n if (!result.passed && !result.disabled) {\n throw new PromoteRejectedError(opts.entrySlug, result.failures)\n }\n // If auto-promote is disabled, treat as bypassed (caller is in\n // charge of routing through corpus-review).\n if (result.disabled) bypassed = true\n }\n\n // Resolve existing entry vs new. Idempotency on candidate.id:\n // if the same slug already exists, we overwrite (re-promotion\n // path); if a different slug at this path exists, that's a bug.\n const existing = snapshot.entries.find(\n (e) => e.frontmatter.slug === opts.entrySlug\n )\n const targetPath = existing?.path ?? opts.entryPath\n const expectedToken = existing?.versionToken ?? null\n\n // Append a `promoted` attestation before writing. The chain is\n // append-only — readers get the full history of who promoted\n // when, what gate state, whether bypassed.\n const identity = await this.ctx.identity.resolve()\n const attestedFm = appendAttestation(\n opts.frontmatter,\n makeAttestation({\n kind: \"promoted\",\n identity: identity.principal,\n at: this.ctx.clock.now().toISOString(),\n note: bypassed\n ? `bypassed=true${gatePassed ? \"\" : \" (gate not consulted)\"}`\n : `gatePassed=${gatePassed}`,\n })\n )\n\n // Write entry atomically (CAS for re-promotion).\n const doc: MarkdownDoc = {\n frontmatter: attestedFm,\n body: opts.body,\n }\n const entryAbsPath = joinPath(opts.workspacePath, targetPath)\n const entryVersionToken = await writer.writeMarkdown(\n entryAbsPath,\n doc,\n expectedToken\n )\n\n // Re-snapshot so the indexer sees the freshly-written entry.\n const freshSnapshot = await reader.read(opts.workspacePath)\n const indexResult = await this.ctx.indexer.syncEntry(\n freshSnapshot,\n opts.entrySlug\n )\n\n // Regenerate _index.md (host-maintained faceted catalog).\n await regenIndexFile({\n fs: this.ctx.fs,\n workspacePath: opts.workspacePath,\n snapshot: freshSnapshot,\n clock: this.ctx.clock,\n })\n\n // Consume the sidecar row, if any.\n if (opts.candidateId && opts.candidateSidecarPath) {\n const { CandidatesSidecar } = await import(\"../workspace/sidecar.js\")\n const sidecar = new CandidatesSidecar({\n fs: this.ctx.fs,\n path: joinPath(opts.workspacePath, opts.candidateSidecarPath),\n })\n // Tolerate already-removed rows (re-promotion path).\n try {\n await sidecar.take(opts.candidateId)\n } catch {\n // not-found means it was already taken\n }\n }\n\n // Append the audit event.\n await emitter.emit(\"corpus.entry.promoted\", {\n slug: opts.entrySlug,\n kind: opts.entryKind,\n entryPath: targetPath,\n candidateId: opts.candidateId,\n bypassed,\n gatePassed,\n chunkCount: indexResult.chunkCount,\n })\n\n return {\n entryPath: targetPath,\n entryVersionToken,\n chunkCount: indexResult.chunkCount,\n gatePassed,\n bypassed,\n }\n })\n }\n}\n\n// ── _index.md regeneration ─────────────────────────────────────────\n\ninterface RegenInput {\n readonly fs: FsPort\n readonly workspacePath: string\n readonly snapshot: CorpusWorkspaceSnapshot\n readonly clock: ClockPort\n}\n\n/**\n * Generate a minimal faceted catalog: entries grouped by kind, with\n * quality + recency hints. Richer regen (additional facets, retrieval\n * boost panel) can layer on later; this version is enough to prove\n * the regen runs on every promotion.\n */\nasync function regenIndexFile(input: RegenInput): Promise<void> {\n const lines: string[] = []\n lines.push(\"# Corpus index\")\n lines.push(\"\")\n lines.push(\n `Generated ${input.clock.now().toISOString()} — ${input.snapshot.entries.length} entries.`\n )\n lines.push(\"\")\n\n // Group entries by kind for the at-a-glance facet.\n type Entry = (typeof input.snapshot.entries)[number]\n const byKind = new Map<string, Entry[]>()\n for (const entry of input.snapshot.entries) {\n const k = String(entry.frontmatter.kind ?? \"unknown\")\n const bucket = byKind.get(k) ?? []\n bucket.push(entry)\n byKind.set(k, bucket)\n }\n\n for (const [kind, entries] of [...byKind].sort(([a], [b]) =>\n a.localeCompare(b)\n )) {\n lines.push(`## ${kind} (${entries.length})`)\n lines.push(\"\")\n for (const e of entries.sort((a: Entry, b: Entry) =>\n String(a.frontmatter.slug).localeCompare(String(b.frontmatter.slug))\n )) {\n const slug = e.frontmatter.slug\n const title = e.frontmatter.title ?? slug\n const corpus = (e.frontmatter.metadata as { corpus?: { qualityScore?: number; status?: string } })\n ?.corpus\n const q = corpus?.qualityScore\n const s = corpus?.status ?? \"active\"\n const meta: string[] = []\n if (s !== \"active\") meta.push(`status=${s}`)\n if (typeof q === \"number\") meta.push(`q=${q.toFixed(1)}`)\n const suffix = meta.length > 0 ? ` _(${meta.join(\", \")})_` : \"\"\n lines.push(`- [[${slug}]] — ${title}${suffix}`)\n }\n lines.push(\"\")\n }\n\n const content = lines.join(\"\\n\")\n await input.fs.writeFile(\n joinPath(input.workspacePath, \"_index.md\"),\n content\n )\n}\n\nfunction joinPath(a: string, b: string): string {\n if (!a) return b\n return a.endsWith(\"/\") ? a + b : a + \"/\" + b\n}\n","/**\n * Chunking strategy for corpus entries.\n *\n * Split an entry body into chunks that fit the backing engine's\n * `maxChunkBytes` capability. Naive but predictable — overlap window\n * keeps semantic continuity across boundaries; smarter sentence /\n * semantic chunking can land later behind the same call.\n *\n * Matches the qdrant adapter's CHUNK_TARGET_CHARS / CHUNK_OVERLAP_CHARS\n * numerology so corpus + qdrant agree on chunk shape end-to-end.\n */\n\nexport interface ChunkerOptions {\n /** Soft target per chunk (characters). Default 1500 ≈ 375 tokens. */\n readonly targetChars?: number\n /** Overlap window between adjacent chunks. Default 150. */\n readonly overlapChars?: number\n /** Hard ceiling — backing engine's maxChunkBytes (Buffer-byte). */\n readonly maxBytes?: number\n}\n\nconst DEFAULT_TARGET = 1500\nconst DEFAULT_OVERLAP = 150\nconst DEFAULT_MAX_BYTES = 64 * 1024\n\nexport function chunkText(text: string, opts: ChunkerOptions = {}): string[] {\n const target = opts.targetChars ?? DEFAULT_TARGET\n const overlap = opts.overlapChars ?? DEFAULT_OVERLAP\n const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES\n if (overlap >= target) {\n throw new Error(\"chunkText: overlap must be < target\")\n }\n\n const trimmed = text.trim()\n if (trimmed.length === 0) return []\n if (byteLength(trimmed) <= maxBytes && trimmed.length <= target) {\n return [trimmed]\n }\n\n const chunks: string[] = []\n let cursor = 0\n while (cursor < trimmed.length) {\n let end = Math.min(cursor + target, trimmed.length)\n let slice = trimmed.slice(cursor, end)\n // If the slice exceeds the hard byte ceiling, bisect by char\n // until it fits. Pessimistic but correct for multibyte runs.\n while (byteLength(slice) > maxBytes && slice.length > 1) {\n end = cursor + Math.floor((end - cursor) * 0.9)\n slice = trimmed.slice(cursor, end)\n }\n chunks.push(slice)\n if (end >= trimmed.length) break\n cursor = end - overlap\n if (cursor < 0) cursor = 0\n }\n return chunks\n}\n\nfunction byteLength(s: string): number {\n // TextEncoder is built-in across Node ≥18, Bun, browsers.\n return new TextEncoder().encode(s).length\n}\n","/**\n * CorpusIndexer — coordinator that ships active entries into the\n * backing engine via WriterPort.\n *\n * The kit doesn't know about IKnowledgeProvider — agstudio's\n * CorpusInternalWriter satisfies WriterPort and bridges to the\n * actual engine (qdrant / gbrain). Local topology supplies its own\n * WriterPort (e.g. dockered qdrant).\n *\n * Three public methods:\n * - reindex(snapshot) full sync: pushes every active entry\n * - syncEntry(snapshot, slug) delta: re-push a single entry\n * - removeEntry(slug) delta: drop a deprecated/archived entry\n *\n * Policy: only entries with `metadata.corpus.status === \"active\"`\n * (or unset, treated as active) are shipped. Deprecated/archived\n * entries are removed from the backing engine.\n */\n\nimport { chunkText, type ChunkerOptions } from \"./chunker.js\"\nimport type { WriterPort } from \"../ports/writer.port.js\"\nimport type {\n CorpusWorkspaceSnapshot,\n ParsedFile,\n} from \"../types.js\"\n\nexport interface CorpusIndexerOptions {\n readonly writer: WriterPort\n /** Optional chunker tuning. Defaults match the backing engine's caps. */\n readonly chunker?: ChunkerOptions\n}\n\nexport interface IndexReport {\n readonly pushed: number // entries shipped\n readonly removed: number // entries dropped\n readonly skipped: number // entries skipped (non-active)\n readonly chunkCount: number // total chunks pushed across entries\n}\n\nexport class CorpusIndexer {\n constructor(private readonly opts: CorpusIndexerOptions) {}\n\n /**\n * Re-sync every active entry. Used at boot (cold-install) and by\n * the admin `corpus reindex` command for drift recovery.\n */\n async reindex(snapshot: CorpusWorkspaceSnapshot): Promise<IndexReport> {\n let pushed = 0\n let removed = 0\n let skipped = 0\n let chunkCount = 0\n\n for (const entry of snapshot.entries) {\n const status = readStatus(entry)\n if (status === \"active\") {\n const n = await this.pushEntry(entry)\n pushed++\n chunkCount += n\n } else if (status === \"deprecated\" || status === \"archived\") {\n const slug = entry.frontmatter.slug\n if (typeof slug === \"string\") {\n const r = await this.opts.writer.removeEntry(slug)\n removed += r.removed > 0 ? 1 : 0\n }\n } else {\n skipped++\n }\n }\n return { pushed, removed, skipped, chunkCount }\n }\n\n /**\n * Re-sync a single entry by slug. The lifecycle's `promote`\n * workflow calls this immediately after writing the entry file.\n */\n async syncEntry(\n snapshot: CorpusWorkspaceSnapshot,\n slug: string\n ): Promise<{ chunkCount: number }> {\n const entry = snapshot.entries.find((e) => e.frontmatter.slug === slug)\n if (!entry) {\n // Missing slug = deprecated/erased; drop from backing engine.\n await this.opts.writer.removeEntry(slug)\n return { chunkCount: 0 }\n }\n const status = readStatus(entry)\n if (status !== \"active\") {\n await this.opts.writer.removeEntry(slug)\n return { chunkCount: 0 }\n }\n // Always remove-then-push for syncEntry — backing engine doesn't\n // have an \"upsert by entrySlug\" op. This keeps the chunk set\n // consistent with the current entry body.\n await this.opts.writer.removeEntry(slug)\n const n = await this.pushEntry(entry)\n return { chunkCount: n }\n }\n\n /** Drop one entry from the backing engine (deprecation, GDPR erase). */\n async removeEntry(slug: string): Promise<void> {\n await this.opts.writer.removeEntry(slug)\n }\n\n // ── Internal ─────────────────────────────────────────────────────\n\n private async pushEntry(entry: ParsedFile): Promise<number> {\n const slug = entry.frontmatter.slug\n if (typeof slug !== \"string\") return 0\n const chunks = chunkText(entry.body, this.opts.chunker).map((text) => ({\n text,\n }))\n const corpus = readCorpusMetadata(entry)\n await this.opts.writer.pushChunks({\n entrySlug: slug,\n entryPath: entry.path,\n title: typeof entry.frontmatter.title === \"string\"\n ? entry.frontmatter.title\n : undefined,\n chunks,\n // Forward the corpus-namespaced metadata so the engine adapter\n // can hydrate hits without re-reading the file.\n entryMetadata: {\n kind: entry.frontmatter.kind,\n sources: entry.frontmatter.sources,\n confidence: entry.frontmatter.confidence,\n tags: entry.frontmatter.tags,\n ...corpus,\n },\n })\n return chunks.length\n }\n}\n\nfunction readStatus(entry: ParsedFile): string {\n const corpus = (entry.frontmatter.metadata as { corpus?: { status?: unknown } })\n ?.corpus\n const s = corpus?.status\n return typeof s === \"string\" ? s : \"active\"\n}\n\nfunction readCorpusMetadata(\n entry: ParsedFile\n): Readonly<Record<string, unknown>> {\n const corpus = (entry.frontmatter.metadata as { corpus?: unknown })?.corpus\n return (corpus as Readonly<Record<string, unknown>>) ?? {}\n}\n","/**\n * Attachment-binding axes — the dimensions a selector can target.\n *\n * An axis is a named dimension of the consuming subject (an operator,\n * usually): its identity slug, the AIP-47 role it fulfils, the\n * host-assigned position label, the capabilities it carries. Assets\n * (playbook overlays, knowledge packs, skills) declare a `Selector`\n * over these axes; the host supplies `Dimensions` for the subject and\n * one matcher evaluates `selector ⊨ dimensions`.\n *\n * This package ships only the AIP-concept axes. Hosts register extra\n * axes (org units, regions, compliance regimes, …) on their own\n * registry — nothing here knows about any host's org model.\n */\n\nimport { createRegistry, type Registry } from \"@agentproto/registry\"\n\nexport interface AxisDefinition {\n /** Axis id — the key used in `selector:` frontmatter and in Dimensions. */\n readonly id: string\n /** AIP that owns the axis's value vocabulary, when one does. */\n readonly aip?: number\n /** Doc line for catalog/UI surfaces. */\n readonly description?: string\n /**\n * Authoring-time ref check. Returns an error message, or null when\n * the ref is acceptable. Hosts inject catalog-aware validators here\n * (e.g. \"role ref must be a known catalog slug\").\n */\n readonly validateRef?: (ref: string) => string | null\n /**\n * Canonicalize a ref before matching — absorbs the AIP-12 ref shapes\n * (`operator/<slug>`, `ws://operators/<slug>`, globs → `\"*\"`).\n */\n readonly normalizeRef?: (ref: string) => string\n}\n\n/** Matches any present value on the axis. */\nexport const ANY_REF = \"*\"\n\n/**\n * Ref-shape normalizer for an axis addressed as `<singular>/<slug>` or\n * `ws://<plural>/<slug>` — the shapes AIP-12 targets historically used.\n * Globs (`<singular>/*`, `ws://<plural>/*`) collapse to `ANY_REF`.\n */\nexport function prefixedRefNormalizer(\n singular: string,\n plural: string\n): (ref: string) => string {\n const bare = `${singular}/`\n const ws = `ws://${plural}/`\n return (ref) => {\n const stripped = ref.startsWith(bare)\n ? ref.slice(bare.length)\n : ref.startsWith(ws)\n ? ref.slice(ws.length)\n : ref\n return stripped === \"*\" ? ANY_REF : stripped\n }\n}\n\nconst SLUG_RE = /^[a-z][a-z0-9-]*[a-z0-9]$/\n\nfunction slugValidator(ref: string): string | null {\n if (ref === ANY_REF) return null\n return SLUG_RE.test(ref)\n ? null\n : `not a slug (lowercase, digits, dashes): \"${ref}\"`\n}\n\n/** The operator's own slug — AIP-9 identity. */\nexport const identityAxis: AxisDefinition = {\n id: \"identity\",\n aip: 9,\n description: \"The subject's own slug — targets one specific operator.\",\n normalizeRef: prefixedRefNormalizer(\"operator\", \"operators\"),\n validateRef: slugValidator,\n}\n\n/** The AIP-47 catalog role (job) the operator fulfils. */\nexport const roleAxis: AxisDefinition = {\n id: \"role\",\n aip: 47,\n description:\n \"The AIP-47 catalog role (job) the subject fulfils — targets every operator in the role.\",\n normalizeRef: prefixedRefNormalizer(\"role\", \"roles\"),\n validateRef: slugValidator,\n}\n\n/** The host-assigned, user-settable seat label (slugified). */\nexport const positionAxis: AxisDefinition = {\n id: \"position\",\n aip: 6,\n description:\n \"The host-assigned seat label (slugified) — targets the one operator holding the seat. See AIP-47 §Role vs Position vs Access role.\",\n normalizeRef: prefixedRefNormalizer(\"position\", \"positions\"),\n validateRef: slugValidator,\n}\n\n/** A capability slug the subject carries. */\nexport const capabilityAxis: AxisDefinition = {\n id: \"capability\",\n aip: 9,\n description: \"A capability slug the subject carries.\",\n normalizeRef: prefixedRefNormalizer(\"capability\", \"capabilities\"),\n validateRef: slugValidator,\n}\n\nexport const WELL_KNOWN_AXES: readonly AxisDefinition[] = Object.freeze([\n identityAxis,\n roleAxis,\n positionAxis,\n capabilityAxis,\n])\n\nexport type AxisRegistry = Registry<AxisDefinition>\n\n/**\n * Axis registry seeded with the well-known AIP axes. Hosts pass their\n * extra axes; ids must not collide with the well-known set.\n */\nexport function createAxisRegistry(\n extra: readonly AxisDefinition[] = []\n): AxisRegistry {\n const registry = createRegistry<AxisDefinition>({\n family: \"binding-axis\",\n keyBy: (axis) => axis.id,\n })\n for (const axis of WELL_KNOWN_AXES) registry.register(axis)\n for (const axis of extra) registry.register(axis)\n return registry\n}\n","/**\n * Selector ⊨ Dimensions — the one matcher every attachment kind uses.\n *\n * A `Selector` is a small boolean expression over axis terms; the host\n * supplies the subject's `Dimensions` (axis → value(s)) and the matcher\n * decides whether the asset attaches. Scope (org / guild / workspace\n * reach) is NOT expressed here — reach is decided by which corpus\n * workspaces the host aggregates before matching ever runs.\n */\n\nimport { ANY_REF, type AxisDefinition, type AxisRegistry } from \"./axes.js\"\n\nexport interface SelectorTerm {\n readonly axis: string\n /** Refs the term accepts — OR within the list. `\"*\"` = any present value. */\n readonly anyOf: readonly string[]\n}\n\nexport interface Selector {\n /** Every term must match (AND). */\n readonly allOf?: readonly SelectorTerm[]\n /** At least one term must match (OR). */\n readonly anyOf?: readonly SelectorTerm[]\n}\n\n/**\n * The subject's axis values. A missing key means the subject has no\n * value on that axis — terms against it fail (never match-all).\n */\nexport type Dimensions = Readonly<\n Record<string, string | readonly string[] | undefined>\n>\n\nexport interface MatchOptions {\n /** Axis registry supplying per-axis `normalizeRef`. Optional — without it refs match verbatim. */\n readonly axes?: AxisRegistry\n}\n\nexport const EMPTY_SELECTOR: Selector = Object.freeze({})\n\n/** True when the selector has no terms at all. */\nexport function isEmptySelector(selector: Selector): boolean {\n return !selector.allOf?.length && !selector.anyOf?.length\n}\n\n/**\n * Evaluate `selector ⊨ dimensions`.\n *\n * - An EMPTY selector matches NOTHING — an asset that wants everyone\n * in scope says so with an explicit `{ axis, anyOf: [\"*\"] }` term.\n * (Parity with the legacy empty-`targets` behavior.)\n * - A term fails when the dimension is absent.\n * - A term matches when its normalized refs intersect the dimension's\n * values, or when it carries `\"*\"` and the dimension is present.\n */\nexport function matchesSelector(\n selector: Selector,\n dimensions: Dimensions,\n options: MatchOptions = {}\n): boolean {\n if (isEmptySelector(selector)) return false\n const { allOf, anyOf } = selector\n if (allOf?.length) {\n for (const term of allOf) {\n if (!termMatches(term, dimensions, options)) return false\n }\n }\n if (anyOf?.length) {\n return anyOf.some((term) => termMatches(term, dimensions, options))\n }\n return true\n}\n\nfunction termMatches(\n term: SelectorTerm,\n dimensions: Dimensions,\n options: MatchOptions\n): boolean {\n const raw = dimensions[term.axis]\n if (raw === undefined) return false\n const values = typeof raw === \"string\" ? [raw] : raw\n if (values.length === 0) return false\n const axis = options.axes?.get(term.axis)\n for (const ref of term.anyOf) {\n const normalized = normalizeRef(ref, axis)\n if (normalized === ANY_REF) return true\n if (values.includes(normalized)) return true\n }\n return false\n}\n\nfunction normalizeRef(ref: string, axis: AxisDefinition | undefined): string {\n return axis?.normalizeRef ? axis.normalizeRef(ref) : ref\n}\n","/**\n * `selector:` frontmatter → Selector.\n *\n * Authoring shape (AIP-12 §selector):\n *\n * selector:\n * role: sales-rep # one ref\n * capability: [demo, forecast] # OR within the list\n *\n * Keys are axis ids; multiple keys AND together. The advanced\n * `allOf:`/`anyOf:` long form is accepted verbatim for selectors that\n * need OR across axes.\n *\n * Parsing never throws — malformed input returns null and the caller\n * falls back to the legacy `targets` compile. A selector that silently\n * dropped a malformed term could attach an overlay to the wrong\n * operators; null keeps the file on its legacy binding instead.\n */\n\nimport type { Selector, SelectorTerm } from \"./selector.js\"\n\nexport function parseSelectorFrontmatter(raw: unknown): Selector | null {\n if (!isPlainObject(raw)) return null\n\n // Long form: explicit allOf / anyOf term lists.\n if (\"allOf\" in raw || \"anyOf\" in raw) {\n const allOf = readTermList(raw.allOf)\n const anyOf = readTermList(raw.anyOf)\n if (allOf === null || anyOf === null) return null\n if (!allOf.length && !anyOf.length) return null\n return Object.freeze({\n ...(allOf.length ? { allOf } : {}),\n ...(anyOf.length ? { anyOf } : {}),\n })\n }\n\n // Short form: axis → ref | ref[].\n const allOf: SelectorTerm[] = []\n for (const [axis, value] of Object.entries(raw)) {\n const refs = readRefs(value)\n if (refs === null) return null\n allOf.push(Object.freeze({ axis, anyOf: refs }))\n }\n if (!allOf.length) return null\n return Object.freeze({ allOf: Object.freeze(allOf) })\n}\n\nfunction readTermList(raw: unknown): readonly SelectorTerm[] | null {\n if (raw === undefined) return []\n if (!Array.isArray(raw)) return null\n const out: SelectorTerm[] = []\n for (const entry of raw as readonly unknown[]) {\n if (!isPlainObject(entry)) return null\n const axis = entry.axis\n if (typeof axis !== \"string\" || !axis.length) return null\n const refs = readRefs(entry.anyOf)\n if (refs === null || !refs.length) return null\n out.push(Object.freeze({ axis, anyOf: refs }))\n }\n return Object.freeze(out)\n}\n\nfunction readRefs(value: unknown): readonly string[] | null {\n if (typeof value === \"string\") {\n return value.length ? Object.freeze([value]) : null\n }\n if (Array.isArray(value)) {\n const refs = value as readonly unknown[]\n if (!refs.length) return null\n if (!refs.every((r): r is string => typeof r === \"string\" && r.length > 0))\n return null\n return Object.freeze([...refs])\n }\n return null\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v)\n}\n","/**\n * Legacy `targets[]` / `binds_operator` → Selector compile.\n *\n * Permanent, not transitional: PLAYBOOK.md files authored before\n * `selector:` live in real corpus workspaces and keep working forever.\n *\n * The legacy format is axis-AMBIGUOUS: a `kind: \"operator\"` ref (and\n * `binds_operator`) historically held either an operator slug OR a\n * role slug — the old matcher tried both. The compile preserves that\n * exactly by putting each such ref in BOTH the identity and the role\n * bucket of an `anyOf` selector. `kind: \"role\" | \"skill\" | \"runtime\"`\n * refs compile to their own axes (a host that supplies no `skill`\n * dimension keeps today's no-match behavior for skill targets).\n */\n\nimport {\n capabilityAxis,\n identityAxis,\n positionAxis,\n roleAxis,\n prefixedRefNormalizer,\n} from \"./axes.js\"\nimport type { Selector, SelectorTerm } from \"./selector.js\"\n\ninterface LegacyTarget {\n readonly kind: string\n readonly ref: string\n}\n\nconst normalizeOperatorRef = identityAxis.normalizeRef!\nconst normalizeRoleRef = roleAxis.normalizeRef!\nconst normalizeSkillRef = prefixedRefNormalizer(\"skill\", \"skills\")\nconst normalizeRuntimeRef = prefixedRefNormalizer(\"runtime\", \"runtimes\")\n\nexport function compileLegacyPlaybookBinding(\n targets: readonly LegacyTarget[],\n bindsOperator?: string\n): Selector {\n const identity = new Set<string>()\n const role = new Set<string>()\n const skill = new Set<string>()\n const runtime = new Set<string>()\n\n if (bindsOperator) {\n identity.add(normalizeOperatorRef(bindsOperator))\n role.add(normalizeRoleRef(bindsOperator))\n }\n for (const target of targets) {\n switch (target.kind) {\n case \"operator\":\n identity.add(normalizeOperatorRef(target.ref))\n role.add(normalizeRoleRef(target.ref))\n break\n case \"role\":\n role.add(normalizeRoleRef(target.ref))\n break\n case \"skill\":\n skill.add(normalizeSkillRef(target.ref))\n break\n case \"runtime\":\n runtime.add(normalizeRuntimeRef(target.ref))\n break\n default:\n break\n }\n }\n\n const anyOf: SelectorTerm[] = []\n pushTerm(anyOf, identityAxis.id, identity)\n pushTerm(anyOf, roleAxis.id, role)\n pushTerm(anyOf, \"skill\", skill)\n pushTerm(anyOf, \"runtime\", runtime)\n if (!anyOf.length) return Object.freeze({})\n return Object.freeze({ anyOf: Object.freeze(anyOf) })\n}\n\nfunction pushTerm(out: SelectorTerm[], axis: string, refs: Set<string>): void {\n if (!refs.size) return\n out.push(Object.freeze({ axis, anyOf: Object.freeze([...refs]) }))\n}\n\n// Re-exported so hosts assembling Dimensions use the same axis ids the\n// compile emits.\nexport { identityAxis, roleAxis, positionAxis, capabilityAxis }\n","/**\n * Attachment declarations — \"this asset attaches to subjects matching\n * this selector\", evaluated by the one matcher.\n *\n * A host keeps a flat list of declarations (a knowledge pack attaches to\n * a set of roles, a skill attaches to one position, …) and asks which\n * ones a given subject's `Dimensions` satisfy. This replaces the older\n * shape where bindings were grafted onto the subject (e.g. mutating a\n * role handle at boot): the declaration is data, matching is a pure\n * function, nothing is mutated.\n *\n * Asset-kind-agnostic and vendor-neutral — the `kind` is the host's\n * (`\"pack\" | \"skill\" | …`); the selector axes are AIP concepts. `band` /\n * `mode` are optional layering hints a host's mount step may honor; the\n * matcher itself ignores them.\n */\n\nimport type { LayerMode } from \"../stack/types.js\"\nimport { matchesSelector, type Dimensions, type Selector } from \"./selector.js\"\nimport type { AxisRegistry } from \"./axes.js\"\n\n/** What a declaration attaches — an opaque, host-typed ref under a kind. */\nexport interface AttachmentAsset<Kind extends string = string> {\n readonly kind: Kind\n readonly ref: string\n}\n\n/** An asset + the selector deciding which subjects it attaches to. */\nexport interface AttachmentDeclaration<Kind extends string = string> {\n readonly asset: AttachmentAsset<Kind>\n /** Subjects whose `Dimensions` satisfy this attach the asset. */\n readonly selector: Selector\n /** Optional precedence hint for the host's mount step (see AIP-10 bands). */\n readonly band?: number\n /** Optional composition hint — `lens` vs `constraint`. */\n readonly mode?: LayerMode\n}\n\nexport interface MatchAttachmentsOptions {\n /** Axis registry supplying per-axis `normalizeRef` for the matcher. */\n readonly axes?: AxisRegistry\n}\n\n/**\n * The subset of `declarations` whose selector matches `dimensions`. Order\n * is preserved; de-duplication of resulting refs is the caller's call\n * (the same asset may attach via several declarations).\n */\nexport function matchAttachments<Kind extends string>(\n declarations: readonly AttachmentDeclaration<Kind>[],\n dimensions: Dimensions,\n options: MatchAttachmentsOptions = {}\n): AttachmentDeclaration<Kind>[] {\n return declarations.filter((d) =>\n matchesSelector(d.selector, dimensions, { axes: options.axes })\n )\n}\n\n/**\n * Matched asset refs for one kind, de-duplicated, first-seen order — the\n * flat shape most mount steps want.\n */\nexport function matchAttachmentRefs<Kind extends string>(\n declarations: readonly AttachmentDeclaration<Kind>[],\n kind: Kind,\n dimensions: Dimensions,\n options: MatchAttachmentsOptions = {}\n): string[] {\n const seen = new Set<string>()\n for (const d of matchAttachments(declarations, dimensions, options)) {\n if (d.asset.kind === kind) seen.add(d.asset.ref)\n }\n return [...seen]\n}\n","/**\n * PlaybookRegistry — load + index every AIP-12 PLAYBOOK.md in the\n * workspace's `playbooks/` directory.\n *\n * The registry is a thin read layer over a `CorpusWorkspaceSnapshot`:\n * - parses raw frontmatter into the typed `Playbook` shape,\n * - exposes O(1) lookups by slug,\n * - filters by status / kind / target operator on listBy().\n *\n * No FsPort dependency — the snapshot already carries the parsed\n * files. The lifecycle layer is the one that writes; this registry\n * is pure read.\n */\n\nimport {\n compileLegacyPlaybookBinding,\n createAxisRegistry,\n matchesSelector,\n parseSelectorFrontmatter,\n} from \"../binding/index.js\"\nimport type { CorpusWorkspaceSnapshot, ParsedFile } from \"../types.js\"\nimport type {\n Playbook,\n PlaybookCorpusMeta,\n PlaybookKind,\n PlaybookQuery,\n PlaybookStatus,\n PlaybookTarget,\n} from \"./types.js\"\n\nexport interface PlaybookRegistryOptions {\n readonly snapshot: CorpusWorkspaceSnapshot\n}\n\nexport class PlaybookRegistry {\n private readonly bySlug: ReadonlyMap<string, Playbook>\n private readonly all: readonly Playbook[]\n\n constructor(opts: PlaybookRegistryOptions) {\n const parsed: Playbook[] = []\n for (const file of opts.snapshot.playbooks) {\n const playbook = parsePlaybook(file)\n if (playbook) parsed.push(playbook)\n }\n parsed.sort((a, b) => b.priority - a.priority)\n this.all = Object.freeze(parsed)\n const map = new Map<string, Playbook>()\n for (const p of parsed) map.set(p.slug, p)\n this.bySlug = map\n }\n\n list(): readonly Playbook[] {\n return this.all\n }\n\n bySlugOrNull(slug: string): Playbook | null {\n return this.bySlug.get(slug) ?? null\n }\n\n listBy(query: PlaybookQuery = {}): readonly Playbook[] {\n return this.all.filter((p) => matches(p, query))\n }\n}\n\n// ── Parsing ─────────────────────────────────────────────────────────\n\nfunction parsePlaybook(file: ParsedFile): Playbook | null {\n const fm = file.frontmatter\n const slug = typeof fm.slug === \"string\" ? fm.slug : null\n const title = typeof fm.title === \"string\" ? fm.title : null\n if (!slug || !title) return null\n\n const status = readStatus(fm)\n const kind: PlaybookKind = fm.kind === \"block-replacement\"\n ? \"block-replacement\"\n : \"overlay\"\n const priority = typeof fm.priority === \"number\" ? fm.priority : 100\n const bindsOperator =\n typeof fm.binds_operator === \"string\" ? fm.binds_operator : undefined\n const targets = readTargets(fm)\n const supersedes = readStringArray(fm.supersedes)\n const corpus = readCorpusMeta(fm)\n // Explicit `selector:` wins; malformed or absent falls back to the\n // legacy compile so an old or broken file keeps its targets binding.\n const explicitSelector = parseSelectorFrontmatter(fm.selector)\n const selector =\n explicitSelector ?? compileLegacyPlaybookBinding(targets, bindsOperator)\n const selectorSource = explicitSelector ? \"selector\" : \"legacy\"\n\n return Object.freeze({\n path: file.path,\n slug,\n title,\n status,\n kind,\n priority,\n targets,\n bindsOperator,\n selector,\n selectorSource,\n supersedes,\n body: file.body,\n corpus,\n versionToken: file.versionToken,\n file,\n })\n}\n\nfunction readStatus(fm: Readonly<Record<string, unknown>>): PlaybookStatus {\n const s = fm.status\n if (s === \"active\" || s === \"shadow\" || s === \"archived\") return s\n return \"shadow\"\n}\n\nfunction readTargets(\n fm: Readonly<Record<string, unknown>>\n): readonly PlaybookTarget[] {\n const raw = fm.targets\n if (!Array.isArray(raw)) return []\n const out: PlaybookTarget[] = []\n for (const t of raw as readonly unknown[]) {\n if (typeof t !== \"object\" || t === null) continue\n const o = t as { kind?: unknown; ref?: unknown }\n if (\n typeof o.ref !== \"string\" ||\n (o.kind !== \"operator\" &&\n o.kind !== \"role\" &&\n o.kind !== \"skill\" &&\n o.kind !== \"runtime\")\n )\n continue\n out.push({ kind: o.kind, ref: o.ref })\n }\n return Object.freeze(out)\n}\n\nfunction readStringArray(v: unknown): readonly string[] {\n if (!Array.isArray(v)) return []\n return Object.freeze(\n (v as readonly unknown[]).filter((x): x is string => typeof x === \"string\")\n )\n}\n\nfunction readCorpusMeta(\n fm: Readonly<Record<string, unknown>>\n): PlaybookCorpusMeta {\n const meta = (fm.metadata as { corpus?: unknown })?.corpus\n if (!meta || typeof meta !== \"object\") return {}\n return Object.freeze(meta as PlaybookCorpusMeta)\n}\n\n// ── Query matching ─────────────────────────────────────────────────\n\nconst AXES = createAxisRegistry()\n\nfunction matches(p: Playbook, q: PlaybookQuery): boolean {\n if (q.status !== undefined) {\n const wanted = Array.isArray(q.status) ? q.status : [q.status]\n if (!wanted.includes(p.status)) return false\n }\n if (q.kind !== undefined && p.kind !== q.kind) return false\n if (q.dimensions !== undefined) {\n return matchesSelector(p.selector, q.dimensions, { axes: AXES })\n }\n if (q.forOperatorSlug !== undefined) {\n // Legacy sugar: the caller's slugs are axis-ambiguous handles, so\n // try them on both axes — exactly the old either-axis behavior.\n const slugs = Array.isArray(q.forOperatorSlug)\n ? q.forOperatorSlug\n : [q.forOperatorSlug]\n return matchesSelector(\n p.selector,\n { identity: slugs, role: slugs },\n { axes: AXES }\n )\n }\n if (q.operatorRef !== undefined) {\n return p.targets.some(\n (t) => t.kind === \"operator\" && t.ref === q.operatorRef\n )\n }\n return true\n}\n","/**\n * OperatorOverlayResolver — given an operator + conversation context,\n * returns the playbook overlays to splice into the operator's prompt.\n *\n * Decision rules:\n * 1. `active` playbooks targeting the operator are ALWAYS included.\n * 2. `shadow` playbooks fire on a deterministic-hash subset of\n * conversations (`shadowTrafficPct`, default 0.10) — same\n * conversation always lands the same arm so an eval batch is\n * reproducible.\n * 3. `archived` playbooks are never included (per the AIP-12\n * lifecycle terminal state).\n * 4. Multiple active playbooks for the same operator stack by\n * `priority` (higher first). `kind: block-replacement` overrides\n * the operator's default block for the named trait;\n * `kind: overlay` appends to the prompt.\n *\n * Pure — no I/O. Consumes a `PlaybookRegistry` (read-only) + the\n * resolution context. Lifecycle writes go through the lifecycle\n * module.\n */\n\nimport type { Dimensions } from \"../binding/index.js\"\nimport type {\n Playbook,\n PlaybookStatus,\n} from \"./types.js\"\nimport type { PlaybookRegistry } from \"./registry.js\"\nimport {\n DEFAULT_SHADOW_TRAFFIC_PCT,\n sampleShadow as sampleShadowToken,\n} from \"../util/shadow-sample.js\"\n\nexport interface ResolveContext {\n /**\n * Slug of the operator the overlays apply to. Matches against\n * `binds_operator` AND `targets[].ref` (with operator/* glob).\n */\n readonly operatorSlug: string\n /**\n * The role (job) slug the operator fulfils, when distinct from its\n * identity slug. Overlays bind by role — \"the recruiting SOP for any\n * recruiter\" — so a playbook targeting this role matches every operator\n * fulfilling it, not just one. Matched in addition to `operatorSlug`.\n *\n * @deprecated Supply `dimensions` instead — it carries role, position,\n * capability, and any host-registered axis in one typed map.\n */\n readonly roleSlug?: string\n /**\n * Typed subject dimensions (axis → value(s)) evaluated against each\n * playbook's selector. When present, wins over the\n * `operatorSlug`/`roleSlug` slug-pair matching.\n */\n readonly dimensions?: Dimensions\n /**\n * Conversation id (or another stable bucketing token). Used to\n * deterministically place a conversation into shadow-traffic\n * buckets, so the same conversation consistently sees (or doesn't\n * see) a given shadow overlay.\n */\n readonly conversationId?: string\n}\n\nexport interface ResolvedOverlay {\n readonly playbookSlug: string\n readonly status: PlaybookStatus\n readonly kind: Playbook[\"kind\"]\n readonly priority: number\n /** The overlay body. */\n readonly body: string\n /** Audit attribution. */\n readonly playbookPath: string\n /** True iff this overlay came from a shadow playbook + was sampled in. */\n readonly shadowSampled: boolean\n}\n\nexport interface ResolveResult {\n readonly operatorSlug: string\n readonly overlays: readonly ResolvedOverlay[]\n}\n\nexport class OperatorOverlayResolver {\n constructor(private readonly registry: PlaybookRegistry) {}\n\n resolve(ctx: ResolveContext): ResolveResult {\n const slugs = ctx.roleSlug\n ? [ctx.operatorSlug, ctx.roleSlug]\n : [ctx.operatorSlug]\n const candidates = this.registry.listBy({\n ...(ctx.dimensions\n ? { dimensions: ctx.dimensions }\n : { forOperatorSlug: slugs }),\n status: [\"active\", \"shadow\"],\n })\n\n const overlays: ResolvedOverlay[] = []\n for (const p of candidates) {\n if (p.status === \"archived\") continue\n const shadowSampled =\n p.status === \"shadow\"\n ? sampleShadow(ctx, p)\n : false\n if (p.status === \"shadow\" && !shadowSampled) continue\n overlays.push({\n playbookSlug: p.slug,\n status: p.status,\n kind: p.kind,\n priority: p.priority,\n body: p.body,\n playbookPath: p.path,\n shadowSampled,\n })\n }\n\n // Registry already sorts by priority desc; preserve that.\n return Object.freeze({\n operatorSlug: ctx.operatorSlug,\n overlays: Object.freeze(overlays),\n })\n }\n}\n\n// ── Shadow-traffic sampling ────────────────────────────────────────\n\n/**\n * Deterministic 0..1 bucket from a stable token (conversation id).\n * Same conversation always lands the same bucket — so an eval batch\n * partitioned by conversation id is reproducible.\n *\n * If no conversationId is supplied (e.g. one-shot tool call), we fall\n * back to the default of NOT sampling — shadow overlays only fire on\n * traffic with stable identity.\n */\nfunction sampleShadow(ctx: ResolveContext, p: Playbook): boolean {\n const pct = typeof p.corpus.shadowTrafficPct === \"number\"\n ? p.corpus.shadowTrafficPct\n : DEFAULT_SHADOW_TRAFFIC_PCT\n return sampleShadowToken(ctx.conversationId, p.slug, pct)\n}\n\n/**\n * Render-ready combination of overlays for a prompt. Returns the\n * concatenated overlay bodies (priority-ordered, separated by\n * `\\n\\n---\\n\\n`). `block-replacement` overlays are listed in the\n * `replacements` field separately — the host's prompt assembler\n * decides how to merge those into the operator's named blocks.\n */\nexport interface RenderedOverlays {\n readonly appendBlock: string\n readonly replacements: ReadonlyArray<{\n readonly playbookSlug: string\n readonly body: string\n }>\n}\n\nexport function renderOverlays(result: ResolveResult): RenderedOverlays {\n const overlays = result.overlays.filter((o) => o.kind === \"overlay\")\n const replacements = result.overlays\n .filter((o) => o.kind === \"block-replacement\")\n .map((o) => ({ playbookSlug: o.playbookSlug, body: o.body }))\n return Object.freeze({\n appendBlock: overlays.map((o) => o.body.trim()).join(\"\\n\\n---\\n\\n\"),\n replacements: Object.freeze(replacements),\n })\n}\n","/**\n * PlaybookLifecycle — activate / archive / supersede AIP-12\n * playbooks, atomically.\n *\n * State machine (per the AIP-12 spec):\n * shadow → active | archived\n * active → archived\n * archived = terminal\n *\n * activate(slug):\n * 1. Read current playbook (CAS via versionToken).\n * 2. For each slug in playbook.supersedes that's currently active:\n * transition that slug to `archived` first.\n * 3. Update the target playbook's status → \"active\", clear\n * shadowMetrics.lastEvaluatedAt to mark the activation moment.\n * 4. Atomic file write (CAS).\n * 5. Emit `playbook.activated` event.\n *\n * archive(slug, reason):\n * 1. CAS read.\n * 2. Set status → \"archived\", metadata.corpus.archiveReason = reason.\n * 3. Atomic write.\n * 4. Emit `playbook.archived`.\n *\n * Multi-file transaction guarded by FsPort.lock so a concurrent\n * activate can't half-supersede.\n */\n\nimport matter from \"gray-matter\"\nimport type { ClockPort } from \"../ports/clock.port.js\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type { IdentityPort } from \"../ports/identity.port.js\"\nimport { CorpusEventEmitter } from \"../events/emitter.js\"\nimport { CorpusWorkspaceReader } from \"../workspace/reader.js\"\nimport { CorpusWorkspaceWriter } from \"../workspace/writer.js\"\nimport { appendAttestation, makeAttestation } from \"../lifecycle/attestations.js\"\nimport type { Attestation } from \"../types.js\"\nimport { PlaybookRegistry } from \"./registry.js\"\nimport type { Playbook, PlaybookStatus } from \"./types.js\"\n\nexport class PlaybookNotFoundError extends Error {\n constructor(readonly slug: string) {\n super(`PlaybookNotFoundError: no playbook found with slug \"${slug}\"`)\n this.name = \"PlaybookNotFoundError\"\n }\n}\n\nexport class IllegalPlaybookTransitionError extends Error {\n constructor(\n readonly slug: string,\n readonly from: PlaybookStatus,\n readonly to: PlaybookStatus\n ) {\n super(\n `IllegalPlaybookTransitionError: ${slug}: ${from} → ${to} is not allowed`\n )\n this.name = \"IllegalPlaybookTransitionError\"\n }\n}\n\nexport interface PlaybookLifecycleOptions {\n readonly fs: FsPort\n readonly clock: ClockPort\n readonly identity: IdentityPort\n readonly workspacePath: string\n}\n\nexport interface ActivateResult {\n readonly slug: string\n readonly previousStatus: PlaybookStatus\n readonly versionToken: string\n readonly supersededSlugs: readonly string[]\n}\n\nexport interface ArchiveResult {\n readonly slug: string\n readonly previousStatus: PlaybookStatus\n readonly versionToken: string\n}\n\nexport class PlaybookLifecycle {\n constructor(private readonly opts: PlaybookLifecycleOptions) {}\n\n /**\n * Transition `slug` from shadow → active. Cascades through\n * `supersedes[]`: any currently-active playbook listed there is\n * archived (with `archiveReason: superseded-by-<slug>`) in the\n * same lock-guarded transaction.\n */\n async activate(slug: string): Promise<ActivateResult> {\n const writer = new CorpusWorkspaceWriter({ fs: this.opts.fs })\n const lockPath = joinPath(this.opts.workspacePath, \"_log.md\")\n return await writer.transaction(lockPath, async () => {\n const playbook = await this.loadOne(slug)\n assertTransition(playbook.status, \"active\", slug)\n\n // Supersede chain: archive previous active versions BEFORE\n // we flip this one. If any supersede write fails, the lock\n // protects us from a half-activated state — but the AIP-10\n // log will show the partial sequence so a recovery routine\n // can detect inconsistency.\n const supersededSlugs: string[] = []\n const reg = await this.loadRegistry()\n const identity = await this.opts.identity.resolve()\n for (const supersededSlug of playbook.supersedes) {\n const prev = reg.bySlugOrNull(supersededSlug)\n if (!prev || prev.status !== \"active\") continue\n const att = this.attestation(\n \"archived\",\n identity.principal,\n `superseded-by-${slug}`\n )\n await this.writeWith(prev, (fm) =>\n appendAttestation(\n patchStatus(fm, \"archived\", {\n archiveReason: `superseded-by-${slug}`,\n archivedAt: att.at,\n }),\n att\n )\n )\n await this.emitter().emit(\"playbook.archived\", {\n slug: prev.slug,\n archiveReason: `superseded-by-${slug}`,\n })\n supersededSlugs.push(prev.slug)\n }\n\n const activateAtt = this.attestation(\n \"activated\",\n identity.principal,\n `from=${playbook.status}`\n )\n const newToken = await this.writeWith(playbook, (fm) =>\n appendAttestation(\n patchStatus(fm, \"active\", { activatedAt: activateAtt.at }),\n activateAtt\n )\n )\n await this.emitter().emit(\"playbook.activated\", {\n slug,\n previousStatus: playbook.status,\n supersededSlugs,\n })\n\n return {\n slug,\n previousStatus: playbook.status,\n versionToken: newToken,\n supersededSlugs: Object.freeze(supersededSlugs),\n }\n })\n }\n\n /**\n * Transition `slug` → archived. Skip-no-op if already archived.\n */\n async archive(slug: string, reason: string): Promise<ArchiveResult> {\n const writer = new CorpusWorkspaceWriter({ fs: this.opts.fs })\n const lockPath = joinPath(this.opts.workspacePath, \"_log.md\")\n return await writer.transaction(lockPath, async () => {\n const playbook = await this.loadOne(slug)\n if (playbook.status === \"archived\") {\n return {\n slug,\n previousStatus: \"archived\" as const,\n versionToken: playbook.versionToken,\n }\n }\n assertTransition(playbook.status, \"archived\", slug)\n const identity = await this.opts.identity.resolve()\n const att = this.attestation(\"archived\", identity.principal, reason)\n const newToken = await this.writeWith(playbook, (fm) =>\n appendAttestation(\n patchStatus(fm, \"archived\", {\n archiveReason: reason,\n archivedAt: att.at,\n }),\n att\n )\n )\n await this.emitter().emit(\"playbook.archived\", {\n slug,\n previousStatus: playbook.status,\n archiveReason: reason,\n })\n return {\n slug,\n previousStatus: playbook.status,\n versionToken: newToken,\n }\n })\n }\n\n // ── Internal ─────────────────────────────────────────────────────\n\n private async loadOne(slug: string): Promise<Playbook> {\n const reg = await this.loadRegistry()\n const p = reg.bySlugOrNull(slug)\n if (!p) throw new PlaybookNotFoundError(slug)\n return p\n }\n\n private async loadRegistry(): Promise<PlaybookRegistry> {\n const reader = new CorpusWorkspaceReader({ fs: this.opts.fs })\n const snapshot = await reader.read(this.opts.workspacePath)\n return new PlaybookRegistry({ snapshot })\n }\n\n private async writeWith(\n playbook: Playbook,\n patch: (fm: Record<string, unknown>) => Record<string, unknown>\n ): Promise<string> {\n const writer = new CorpusWorkspaceWriter({ fs: this.opts.fs })\n // Rebuild the file content from the parsed frontmatter +\n // original body. We use the parsed-frontmatter shape (not the\n // raw original .md) so the patch is applied to typed data.\n const nextFm = patch({ ...playbook.file.frontmatter })\n const nextContent = matter.stringify(\n playbook.body.startsWith(\"\\n\") ? playbook.body : \"\\n\" + playbook.body,\n nextFm\n )\n return await writer.writeFile(\n joinPath(this.opts.workspacePath, playbook.path),\n nextContent,\n playbook.versionToken\n )\n }\n\n /** Build a transition attestation from current clock + given identity. */\n private attestation(\n kind: Attestation[\"kind\"],\n identity: string,\n note?: string\n ): Attestation {\n return makeAttestation({\n kind,\n identity,\n at: this.opts.clock.now().toISOString(),\n ...(note ? { note } : {}),\n })\n }\n\n private emitter(): CorpusEventEmitter {\n return new CorpusEventEmitter({\n fs: this.opts.fs,\n clock: this.opts.clock,\n identity: this.opts.identity,\n workspaceRoot: this.opts.workspacePath,\n })\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────\n\nfunction assertTransition(\n from: PlaybookStatus,\n to: PlaybookStatus,\n slug: string\n): void {\n const allowed: Record<PlaybookStatus, readonly PlaybookStatus[]> = {\n shadow: [\"active\", \"archived\"],\n active: [\"archived\"],\n archived: [],\n }\n if (!allowed[from].includes(to)) {\n throw new IllegalPlaybookTransitionError(slug, from, to)\n }\n}\n\nfunction patchStatus(\n fm: Record<string, unknown>,\n newStatus: PlaybookStatus,\n extraCorpusMeta: Record<string, unknown>\n): Record<string, unknown> {\n const metaIn = (fm.metadata as Record<string, unknown> | undefined) ?? {}\n const corpusIn =\n (metaIn.corpus as Record<string, unknown> | undefined) ?? {}\n return {\n ...fm,\n status: newStatus,\n metadata: {\n ...metaIn,\n corpus: {\n ...corpusIn,\n ...extraCorpusMeta,\n },\n },\n }\n}\n\nfunction joinPath(a: string, b: string): string {\n if (!a) return b\n return a.endsWith(\"/\") ? a + b : a + \"/\" + b\n}\n","/**\n * PlaybookEvaluator — runs shadow vs baseline eval batches on AIP-12\n * playbooks, records winRateVsBaseline + sample size, decides\n * promotion readiness against `metadata.corpus.autoPromote`.\n *\n * Inputs (per eval-case the host hands us):\n * - prompt: the test prompt\n * - shadow.response: agent output WITH the playbook overlay applied\n * - baseline.response: agent output WITHOUT the overlay\n * - rubric: how to score both arms\n *\n * Output:\n * - winRateVsBaseline = fraction of cases where shadow.score >= baseline.score\n * - sampleSize = n\n * - readyForActivation = winRate >= threshold && n >= minSampleSize\n *\n * The evaluator does NOT itself activate the playbook — it writes\n * shadowMetrics back to the PLAYBOOK.md (via the writer) and lets\n * the curator's `activate` workflow decide. That keeps the\n * audit chain clean: evaluator measures, curator decides.\n *\n * Pure logic. Backing IEvaluator + writer/emitter come in as ports.\n */\n\nimport matter from \"gray-matter\"\nimport type {\n EvalContextPort,\n EvalRubricPort,\n EvaluatorPort,\n} from \"../ports/evaluator.port.js\"\nimport type { ClockPort } from \"../ports/clock.port.js\"\nimport type { FsPort } from \"../ports/fs.port.js\"\nimport type { IdentityPort } from \"../ports/identity.port.js\"\nimport { CorpusEventEmitter } from \"../events/emitter.js\"\nimport { CorpusWorkspaceReader } from \"../workspace/reader.js\"\nimport { CorpusWorkspaceWriter } from \"../workspace/writer.js\"\nimport {\n appendAttestation,\n makeAttestation,\n} from \"../lifecycle/attestations.js\"\nimport { PlaybookNotFoundError } from \"./lifecycle.js\"\nimport { PlaybookRegistry } from \"./registry.js\"\nimport type { Playbook } from \"./types.js\"\n\nexport interface EvalCase {\n /** Optional stable id — used in event payloads + per-case audit. */\n readonly id?: string\n readonly prompt: string\n /** Agent output WITH the playbook overlay applied. */\n readonly shadowResponse: string\n /** Agent output WITHOUT the overlay (baseline). */\n readonly baselineResponse: string\n}\n\nexport interface PlaybookBatchOptions {\n readonly rubric: EvalRubricPort\n readonly cases: readonly EvalCase[]\n /** Forwarded to evaluator + recorded in event payloads. */\n readonly contextOverrides?: Partial<EvalContextPort>\n}\n\nexport interface PlaybookBatchResult {\n readonly playbookSlug: string\n readonly sampleSize: number\n readonly winRateVsBaseline: number\n readonly shadowAvgScore: number\n readonly baselineAvgScore: number\n readonly readyForActivation: boolean\n /** Per-case details — useful for the curator UI. */\n readonly perCase: readonly {\n readonly id?: string\n readonly shadowScore: number\n readonly baselineScore: number\n readonly winnerArm: \"shadow\" | \"baseline\" | \"tie\"\n }[]\n}\n\nexport interface PlaybookEvaluatorOptions {\n readonly fs: FsPort\n readonly clock: ClockPort\n readonly identity: IdentityPort\n readonly workspacePath: string\n readonly evaluator: EvaluatorPort\n}\n\nexport class PlaybookEvaluator {\n constructor(private readonly opts: PlaybookEvaluatorOptions) {}\n\n /**\n * Run an eval batch against a single playbook. For each case:\n * 1. Score shadow.response against rubric → shadowScore\n * 2. Score baseline.response against rubric → baselineScore\n * 3. shadow \"wins\" if shadowScore >= baselineScore\n * Aggregate: winRateVsBaseline = wins / n.\n *\n * On completion: writes shadowMetrics back to the PLAYBOOK.md (CAS),\n * emits a `corpus.playbook.evaluated` event (held outside the formal\n * AIP-41 taxonomy until the spec adopts it).\n */\n async runBatch(\n playbookSlug: string,\n batch: PlaybookBatchOptions\n ): Promise<PlaybookBatchResult> {\n const playbook = await this.loadPlaybook(playbookSlug)\n const perCase: PlaybookBatchResult[\"perCase\"][number][] = []\n let wins = 0\n let shadowSum = 0\n let baselineSum = 0\n\n for (const c of batch.cases) {\n const shadowResult = await this.opts.evaluator.evaluate({\n rubric: batch.rubric,\n prompt: c.prompt,\n response: c.shadowResponse,\n context: {\n ...(batch.contextOverrides ?? {}),\n arm: \"shadow\",\n appliedPlaybooks: [playbookSlug],\n },\n })\n const baselineResult = await this.opts.evaluator.evaluate({\n rubric: batch.rubric,\n prompt: c.prompt,\n response: c.baselineResponse,\n context: {\n ...(batch.contextOverrides ?? {}),\n arm: \"baseline\",\n appliedPlaybooks: [],\n },\n })\n const winnerArm: \"shadow\" | \"baseline\" | \"tie\" =\n shadowResult.score > baselineResult.score\n ? \"shadow\"\n : shadowResult.score < baselineResult.score\n ? \"baseline\"\n : \"tie\"\n // Tie counts as a NON-win — playbook has to strictly beat baseline.\n if (winnerArm === \"shadow\") wins++\n shadowSum += shadowResult.score\n baselineSum += baselineResult.score\n perCase.push({\n id: c.id,\n shadowScore: shadowResult.score,\n baselineScore: baselineResult.score,\n winnerArm,\n })\n }\n\n const sampleSize = batch.cases.length\n const winRate = sampleSize > 0 ? wins / sampleSize : 0\n const auto = (playbook.corpus.autoPromote ?? {}) as {\n enabled?: boolean\n metric?: string\n threshold?: { gte?: number; lte?: number }\n minSampleSize?: number\n }\n const gteOK =\n typeof auto.threshold?.gte === \"number\"\n ? winRate >= auto.threshold.gte\n : false\n const sizeOK =\n typeof auto.minSampleSize === \"number\"\n ? sampleSize >= auto.minSampleSize\n : sampleSize > 0\n const readyForActivation = !!auto.enabled && gteOK && sizeOK\n\n // Persist shadowMetrics back to PLAYBOOK.md (CAS).\n await this.persistMetrics(playbook, {\n sampleSize,\n winRateVsBaseline: winRate,\n lastEvaluatedAt: this.opts.clock.now().toISOString(),\n })\n\n // Emit a custom event — the formal AIP-41 event taxonomy doesn't\n // yet include a typed name like `playbook.shadow.evaluated`, so we\n // route through the lower-level CorpusWorkspaceWriter / FsPort\n // directly here. The host can tail _log.md and pick this up.\n // (Same `_log.md` format as the standard emitter.)\n await this.appendCustomEvent(\"playbook.shadow.evaluated\", {\n slug: playbook.slug,\n sampleSize,\n winRateVsBaseline: winRate,\n readyForActivation,\n })\n\n return Object.freeze({\n playbookSlug: playbook.slug,\n sampleSize,\n winRateVsBaseline: winRate,\n shadowAvgScore: sampleSize > 0 ? shadowSum / sampleSize : 0,\n baselineAvgScore: sampleSize > 0 ? baselineSum / sampleSize : 0,\n readyForActivation,\n perCase: Object.freeze(perCase),\n })\n }\n\n // ── Internal ─────────────────────────────────────────────────────\n\n private async loadPlaybook(slug: string): Promise<Playbook> {\n const reader = new CorpusWorkspaceReader({ fs: this.opts.fs })\n const snapshot = await reader.read(this.opts.workspacePath)\n const reg = new PlaybookRegistry({ snapshot })\n const p = reg.bySlugOrNull(slug)\n if (!p) throw new PlaybookNotFoundError(slug)\n return p\n }\n\n private async persistMetrics(\n playbook: Playbook,\n metrics: {\n sampleSize: number\n winRateVsBaseline: number\n lastEvaluatedAt: string\n }\n ): Promise<void> {\n const writer = new CorpusWorkspaceWriter({ fs: this.opts.fs })\n const identity = await this.opts.identity.resolve()\n let fm = { ...playbook.file.frontmatter } as Record<string, unknown>\n const metaIn = (fm.metadata as Record<string, unknown> | undefined) ?? {}\n const corpusIn =\n (metaIn.corpus as Record<string, unknown> | undefined) ?? {}\n fm.metadata = {\n ...metaIn,\n corpus: {\n ...corpusIn,\n shadowMetrics: metrics,\n },\n }\n // Append the `evaluated` attestation so the chain records who/when.\n fm = appendAttestation(\n fm,\n makeAttestation({\n kind: \"evaluated\",\n identity: identity.principal,\n at: metrics.lastEvaluatedAt,\n note: `n=${metrics.sampleSize} winRate=${metrics.winRateVsBaseline.toFixed(3)}`,\n })\n )\n const content = matter.stringify(\n playbook.body.startsWith(\"\\n\") ? playbook.body : \"\\n\" + playbook.body,\n fm\n )\n await writer.writeFile(\n joinPath(this.opts.workspacePath, playbook.path),\n content,\n playbook.versionToken\n )\n }\n\n private async appendCustomEvent(\n customKind: string,\n payload: Readonly<Record<string, unknown>>\n ): Promise<void> {\n // Use the canonical emitter shape so _log.md stays homogeneous,\n // but pass through the kit's typed CorpusEventEmitter for the\n // formal kinds. For custom kinds, we hand-craft a line so the\n // file format stays one-event-per-line.\n const identity = await this.opts.identity.resolve()\n const line = `- ${this.opts.clock.now().toISOString()} ${customKind} by ${identity.principal} payload=${JSON.stringify(payload, [...Object.keys(payload).sort()])}\\n`\n const logPath = joinPath(this.opts.workspacePath, \"_log.md\")\n // Initialize the log file with the AIP-10 header on first write\n // (same shape as CorpusEventEmitter).\n if (!(await this.opts.fs.exists(logPath))) {\n // Construct a fresh emitter to write the header for parity.\n const emitter = new CorpusEventEmitter({\n fs: this.opts.fs,\n clock: this.opts.clock,\n identity: this.opts.identity,\n workspaceRoot: this.opts.workspacePath,\n })\n // Cheapest way to materialize the header: emit one canonical\n // event (the host might prefer to just call `appendFile`\n // directly; keeping the header parity is the important bit).\n void emitter\n await this.opts.fs.writeFile(\n logPath,\n \"# Corpus activity log\\n\\nAppend-only AIP-10 log of corpus state transitions. Each line:\\n`- <iso> <kind> by <actor> payload=<json>`\\n\\n\"\n )\n }\n await this.opts.fs.appendFile(logPath, line)\n }\n}\n\nfunction joinPath(a: string, b: string): string {\n if (!a) return b\n return a.endsWith(\"/\") ? a + b : a + \"/\" + b\n}\n","/**\n * @agentproto/corpus — composition of AIP-10/12/18/9/15/41.\n *\n * Spec: https://agentproto.sh/docs/corpus\n */\n\nexport const SPEC_NAME = \"agentcorpus/v1\" as const\nexport const SPEC_VERSION = \"0.1.0-alpha\" as const\n\n// Shared slug + language utilities (single source of truth)\nexport {\n slugify,\n uniqueSlug,\n isSourceSlug,\n isEntrySlug,\n type SlugifyOptions,\n} from \"./util/slug.js\"\nexport { normalizeLanguageTag } from \"./util/language.js\"\n\n// Types\nexport type {\n FileKind,\n ParsedFile,\n CorpusWorkspaceSnapshot,\n ValidationIssue,\n ValidationResult,\n LintIssue,\n LintReport,\n CorpusEventKind,\n CorpusEvent,\n CorpusPreset,\n CorpusPresetBootstrapContext,\n Attestation,\n AttestationKind,\n} from \"./types.js\"\n\n// Access — attestations + access policy + capability levels\nexport {\n appendAttestation,\n readAttestations,\n makeAttestation,\n} from \"./lifecycle/attestations.js\"\nexport {\n evaluateAccess,\n readAccessSpec,\n} from \"./access/policy.js\"\nexport type {\n AccessClassification,\n AccessCaller,\n AccessContext,\n AccessDecision,\n CorpusAccessSpec,\n} from \"./access/policy.js\"\nexport {\n evaluateCapability,\n readAccessModes,\n} from \"./access/capability.js\"\nexport type {\n AccessModesMap,\n Capability,\n CapabilityCaller,\n CapabilityDecision,\n CapabilityRule,\n} from \"./access/capability.js\"\n\n// i18n / language filter\nexport {\n resolveLanguageFilter,\n matchesLanguageFilter,\n readOperatorLocale,\n readWorkspaceDefaultLanguage,\n readEntryLanguage,\n} from \"./access/language.js\"\nexport type {\n LanguageFilter,\n ResolveLanguageFilterInput,\n} from \"./access/language.js\"\n\n// Importers\nexport { ImporterRunner } from \"./importers/runner.js\"\nexport { LocalFilesImporter } from \"./importers/local-files.js\"\nexport { KbMigrationImporter } from \"./importers/kb-migration.js\"\nexport { WebImporter } from \"./importers/web.js\"\nexport { ConversationImporter } from \"./importers/conversation.js\"\nexport type {\n CorpusImporter,\n ImporterTarget,\n ImportedSource,\n BatchReport,\n ImporterRunnerOptions,\n} from \"./importers/types.js\"\nexport type { LocalFilesImporterOptions } from \"./importers/local-files.js\"\nexport type { WebImporterOptions } from \"./importers/web.js\"\nexport type { ConversationImporterOptions } from \"./importers/conversation.js\"\n\n// Distill — raw source → refined entries (KNOWLEDGE layer)\nexport { DistillRunner } from \"./distill/runner.js\"\nexport type {\n DistillRunnerOptions,\n DistillSource,\n DistillRunReport,\n EntryLayout,\n} from \"./distill/runner.js\"\nexport type {\n DistillPort,\n DistillInput,\n DistilledItem,\n RefinedKind,\n} from \"./distill/types.js\"\nexport { REFINED_KIND_SCHEMA, isRefinedKind } from \"./distill/types.js\"\nexport { buildDistillPrompt, parseItems } from \"./distill/prompt.js\"\nexport { scanDistilledSourceIds } from \"./distill/scan.js\"\n\n// Distill registry — the catalog of distill kinds (4 swappable slots per\n// descriptor) + the generic per-(descriptor × scope) runner.\nexport { createDistillRegistry } from \"./distill/registry.js\"\nexport type {\n DistillRegistry,\n DistillDescriptor,\n DistillBinding,\n DistillScope,\n DistillTarget,\n} from \"./distill/registry.js\"\nexport { runDistill } from \"./distill/run.js\"\nexport type { DistillReport } from \"./distill/run.js\"\n\n// ClaudeDistiller — a DistillPort over the Messages API (host-injected key).\nexport { ClaudeDistiller } from \"./distill/claude-distiller.js\"\nexport type { ClaudeDistillerOptions } from \"./distill/claude-distiller.js\"\n\n// Conversation windowing — pure (thread, day) helpers + the windowed-source\n// contract the conversation kind binds against.\nexport {\n windowRef,\n parseWindowRef,\n windowSlug,\n enumerateWindowRefs,\n} from \"./distill/windows.js\"\nexport type {\n ConversationWindowSource,\n ConversationThreadRef,\n} from \"./distill/windows.js\"\n\n// Knowledge resolver — the `knowledge:` binding (KNOWLEDGE → SKILL link)\nexport { resolveKnowledge } from \"./knowledge/resolve.js\"\nexport type {\n CorpusEntryQuery,\n ResolvedEntry,\n SourceRef,\n ResolveKnowledgeOptions,\n} from \"./knowledge/resolve.js\"\n\n// Overlay — guild edits shadow read-only packs (the customization engine)\nexport {\n OverlayFs,\n ReadOnlyFs,\n WHITEOUT_SUFFIX,\n type OverlayFsOptions,\n} from \"./knowledge/overlay-fs.js\"\n\n// In-memory FsPort — backs build-time-inlined knowledge packs (no runtime fs)\nexport { MemFs } from \"./knowledge/mem-fs.js\"\n\n// Knowledge stack — composable layer resolution (register one provider per\n// dimension; resolver emits a band-ordered stack; mount helper overlays it)\nexport {\n StackResolver,\n buildOverlayFromStack,\n flattenPackRefs,\n partitionStackRefs,\n type BuildOverlayOptions,\n type StackRefPartition,\n type LayerMode,\n type LayerRef,\n type LayerProvider,\n type LayerShadow,\n type ResolutionContext,\n type StackEntry,\n type StackResolution,\n type StackSkip,\n} from \"./stack/index.js\"\n\n// Sink — agnostic outbound (corpus → external store via a config/MCP sink)\nexport { SyncRunner } from \"./sink/runner.js\"\nexport type { SyncRunnerOptions, SyncReport } from \"./sink/runner.js\"\nexport type { SinkPort, SinkItem, SinkPushResult } from \"./sink/types.js\"\nexport type {\n KbMigrationConfig,\n KbListLike,\n KbSourceLike,\n} from \"./importers/kb-migration.js\"\n\n// Calibration — reviewer track record + multi-reviewer aggregator\nexport { aggregateReviewerScores } from \"./calibration/aggregate.js\"\nexport type {\n AggregateOptions,\n AggregateResult,\n ReviewerScore,\n} from \"./calibration/aggregate.js\"\nexport { ReviewerTrackRecord } from \"./calibration/track-record.js\"\nexport type {\n ReviewerTrackRecordOptions,\n TrackRecordEntry,\n} from \"./calibration/track-record.js\"\nexport {\n pearsonCorrelation,\n computeReviewerCalibration,\n} from \"./calibration/correlation.js\"\nexport type {\n CalibrationOptions,\n ReviewerCalibration,\n} from \"./calibration/correlation.js\"\n\n// Re-export the most commonly consumed ports from the main barrel so\n// the agstudio side (corpus engine adapter) doesn't need the subpath.\n// Full port surface lives under `@agentproto/corpus/ports`.\nexport type {\n FsPort,\n FsStat,\n FsLockHandle,\n} from \"./ports/fs.port.js\"\nexport type { ClockPort } from \"./ports/clock.port.js\"\nexport type { IdentityPort, CallerIdentity } from \"./ports/identity.port.js\"\nexport type {\n FetcherPort,\n FetchedSource,\n FetchedSourceKind,\n} from \"./ports/fetcher.port.js\"\nexport type {\n ConversationSourcePort,\n ConversationDoc,\n ConversationTurn,\n} from \"./ports/conversation-source.port.js\"\nexport { systemClock } from \"./ports/clock.port.js\"\n\n// Workspace\nexport { CorpusWorkspaceReader } from \"./workspace/reader.js\"\nexport {\n CorpusWorkspaceWriter,\n CorpusVersionConflictError,\n} from \"./workspace/writer.js\"\nexport type {\n CorpusWorkspaceReaderOptions,\n} from \"./workspace/reader.js\"\nexport type {\n CorpusWorkspaceWriterOptions,\n MarkdownDoc,\n} from \"./workspace/writer.js\"\n\n// Validate\nexport { CorpusValidator } from \"./validate/validator.js\"\nexport type {\n CorpusValidatorOptions,\n AipSchemaKey,\n AipSchemaBundle,\n} from \"./validate/validator.js\"\nexport { CorpusLinter } from \"./validate/linter.js\"\nexport type {\n CorpusLinterOptions,\n CustomLintRunner,\n} from \"./validate/linter.js\"\n\n// Events\nexport { CorpusEventEmitter } from \"./events/emitter.js\"\nexport type {\n CorpusEventEmitterOptions,\n} from \"./events/emitter.js\"\n\n// Sidecar\nexport {\n CandidatesSidecar,\n SidecarDuplicateError,\n SidecarNotFoundError,\n} from \"./workspace/sidecar.js\"\nexport type {\n CandidateRow,\n CandidatesSidecarOptions,\n} from \"./workspace/sidecar.js\"\n\n// Lifecycle\nexport {\n DEFAULT_TRANSITIONS,\n canTransition,\n assertTransition,\n transitionGraphFromCollection,\n IllegalTransitionError,\n} from \"./lifecycle/candidate.js\"\nexport type {\n CandidateStatus,\n TransitionCheck,\n} from \"./lifecycle/candidate.js\"\nexport {\n evaluateGate,\n extractAutoPromoteConfig,\n} from \"./lifecycle/gate.js\"\nexport type {\n AutoPromoteConfig,\n AutoPromoteRequirements,\n CandidateForGate,\n GateFailure,\n GateResult,\n} from \"./lifecycle/gate.js\"\nexport { CorpusPromoter, PromoteRejectedError } from \"./lifecycle/promote.js\"\nexport type {\n PromoteOptions,\n PromoteResult,\n PromoteContext,\n} from \"./lifecycle/promote.js\"\n\n// Index\nexport { CorpusIndexer } from \"./index/indexer.js\"\nexport type {\n CorpusIndexerOptions,\n IndexReport,\n} from \"./index/indexer.js\"\nexport { chunkText } from \"./index/chunker.js\"\nexport type { ChunkerOptions } from \"./index/chunker.js\"\n\n// Writer port — the kit's seam into a backing engine\nexport type {\n WriterPort,\n WriterChunk,\n PushChunksInput,\n} from \"./ports/writer.port.js\"\n\n// Evaluator port — the kit's seam into a backing evaluator engine.\n// @agstudio/integration-evaluator's IEvaluator satisfies it structurally.\nexport type {\n EvaluatorPort,\n EvalInputPort,\n EvalResultPort,\n EvalRubricPort,\n EvalContextPort,\n} from \"./ports/evaluator.port.js\"\n\n// Attachment binding plane — Dimensions × Selectors × one matcher\nexport {\n ANY_REF,\n WELL_KNOWN_AXES,\n createAxisRegistry,\n identityAxis,\n roleAxis,\n positionAxis,\n capabilityAxis,\n prefixedRefNormalizer,\n EMPTY_SELECTOR,\n isEmptySelector,\n matchesSelector,\n parseSelectorFrontmatter,\n compileLegacyPlaybookBinding,\n matchAttachments,\n matchAttachmentRefs,\n} from \"./binding/index.js\"\nexport type {\n AxisDefinition,\n AxisRegistry,\n Dimensions,\n MatchOptions,\n Selector,\n SelectorTerm,\n AttachmentAsset,\n AttachmentDeclaration,\n MatchAttachmentsOptions,\n} from \"./binding/index.js\"\n\n// Playbooks (AIP-12)\nexport { PlaybookRegistry } from \"./playbooks/registry.js\"\nexport type { PlaybookRegistryOptions } from \"./playbooks/registry.js\"\nexport {\n OperatorOverlayResolver,\n renderOverlays,\n} from \"./playbooks/resolver.js\"\nexport type {\n ResolveContext,\n ResolveResult,\n ResolvedOverlay,\n RenderedOverlays,\n} from \"./playbooks/resolver.js\"\nexport {\n PlaybookLifecycle,\n PlaybookNotFoundError,\n IllegalPlaybookTransitionError,\n} from \"./playbooks/lifecycle.js\"\nexport type {\n PlaybookLifecycleOptions,\n ActivateResult,\n ArchiveResult,\n} from \"./playbooks/lifecycle.js\"\nexport type {\n Playbook,\n PlaybookCorpusMeta,\n PlaybookKind,\n PlaybookQuery,\n PlaybookStatus,\n PlaybookTarget,\n PlaybookTargetKind,\n} from \"./playbooks/types.js\"\nexport { PlaybookEvaluator } from \"./playbooks/evaluator.js\"\nexport type {\n EvalCase,\n PlaybookBatchOptions,\n PlaybookBatchResult,\n PlaybookEvaluatorOptions,\n} from \"./playbooks/evaluator.js\"\n\n"]}