import { readFileSync, readdirSync, existsSync, statSync } from "node:fs"; import { join, dirname, extname, relative } from "node:path"; import { fileURLToPath } from "node:url"; import yaml from "js-yaml"; import type { KnowledgeEntry } from "../../_schema/entry.schema.js"; import { validateEntry } from "../../_schema/entry.schema.js"; import type { AnalysisModel } from "../../_schema/analysis-model.schema.js"; import { validateAnalysisModel } from "../../_schema/analysis-model.schema.js"; import type { ScenarioPack } from "../../_schema/scenario-pack.schema.js"; import { validateScenarioPack } from "../../_schema/scenario-pack.schema.js"; import type { Persona } from "../../_schema/persona.schema.js"; import { validatePersonaRegistry } from "../../_schema/persona.schema.js"; import type { TriggerSignal } from "./types.js"; /** Repository root dir (two levels up from knowledge/src/repo/ → knowledge/) */ function defaultBasePath(): string { // When running via tsx, import.meta.dirname is the dir of this file return join(import.meta.dirname, "..", ".."); } interface DimensionRegistry { dimensions: Array<{ id: string; label: string; proposition: string }>; } export class FsYamlKnowledgeRepo { private basePath: string; private _all: KnowledgeEntry[] | null = null; private _dimensions: string[] | null = null; private _analysisModels: AnalysisModel[] | null = null; private _scenarioPacks: ScenarioPack[] | null = null; private _personas: Persona[] | null = null; constructor(basePath?: string) { this.basePath = basePath ?? defaultBasePath(); } /** Load the dimensions registry from _registry/dimensions.yaml */ private loadDimensions(): string[] { if (this._dimensions) return this._dimensions; const path = join(this.basePath, "_registry", "dimensions.yaml"); if (!existsSync(path)) { throw new Error(`维度注册表不存在: ${path}`); } const raw = yaml.load(readFileSync(path, "utf-8")) as DimensionRegistry; if (!raw || !Array.isArray(raw.dimensions)) { throw new Error(`维度注册表格式错误: ${path}`); } const dims = raw.dimensions.map((d) => d.id); this._dimensions = dims; return dims; } /** Collect all .yaml file paths under basePath, excluding _schema/, _registry/ and tests/ */ private collectYamlFiles(dir: string, root: string): string[] { const files: string[] = []; const entries = readdirSync(dir, { withFileTypes: true }); for (const entry of entries) { const fullPath = join(dir, entry.name); if (entry.isDirectory()) { // Skip non-content directories. // analysis-models/ 与 scenario-packs/ 是 COACH-MOD 新增内容类型, // 用独立 schema(非 knowledgeEntrySchema),不能被 loadAll 当处方条目校验, // 否则 validate 报错 / T13 迁移等价性断言崩。它们由 loadAnalysisModels // / loadScenarioPacks 单独加载。 if ( entry.name === "_schema" || entry.name === "_registry" || entry.name === "tests" || entry.name === "analysis-models" || entry.name === "scenario-packs" ) continue; files.push(...this.collectYamlFiles(fullPath, root)); } else if (entry.isFile() && entry.name.endsWith(".yaml")) { files.push(fullPath); } } return files; } async loadAll(): Promise { if (this._all) return this._all; // Load registry first const validDimensions = this.loadDimensions(); const yamlFiles = this.collectYamlFiles(this.basePath, this.basePath); const entries: KnowledgeEntry[] = []; const seenIds = new Set(); for (const filePath of yamlFiles) { const raw = yaml.load(readFileSync(filePath, "utf-8")); const entry = validateEntry(raw); // Check dimension is registered if (!validDimensions.includes(entry.dimension)) { throw new Error( `维度 "${entry.dimension}" 未在 _registry/dimensions.yaml 中登记 ` + `(文件: ${filePath})` ); } // Check duplicate ID if (seenIds.has(entry.id)) { throw new Error(`重复 ID: "${entry.id}" (文件: ${filePath})`); } seenIds.add(entry.id); entries.push(entry); } this._all = entries; return entries; } async getById(id: string): Promise { const entries = await this.loadAll(); return entries.find((e) => e.id === id) ?? null; } async byDimension(dimension: string): Promise { const entries = await this.loadAll(); return entries.filter((e) => e.dimension === dimension); } async matchBySignal(signal: TriggerSignal): Promise { const entries = await this.loadAll(); return entries.filter((e) => { const signals = e.triggers.signals ?? []; return signals.some((s) => { // Quadrant match: exact if (signal.quadrant && s.quadrant) { if (s.quadrant !== signal.quadrant) return false; } else if (signal.quadrant && !s.quadrant) { return false; } // Daily total minutes: parse threshold if (signal.daily_total_minutes && s.daily_total_minutes) { const sv = parseThreshold(s.daily_total_minutes); const qv = parseThreshold(signal.daily_total_minutes); if (sv === null || qv === null) { // If we can't parse, fall back to string equality if (s.daily_total_minutes !== signal.daily_total_minutes) return false; } else if (!matchesThreshold(s.daily_total_minutes, signal.daily_total_minutes)) { return false; } } else if (signal.daily_total_minutes && !s.daily_total_minutes) { return false; } // If neither signal field is being queried, no match if (!signal.quadrant && !signal.daily_total_minutes) return false; return true; }); }); } async matchBySymptom(symptom: string): Promise { const entries = await this.loadAll(); const lowerSymptom = symptom.toLowerCase(); return entries.filter((e) => { const symptoms = e.triggers.symptoms ?? []; return symptoms.some((s) => s.toLowerCase().includes(lowerSymptom)); }); } /** Collect .yaml files directly under one content subdir (non-recursive). */ private collectDirYamlFiles(subdir: string): string[] { const dir = join(this.basePath, subdir); if (!existsSync(dir)) return []; return readdirSync(dir, { withFileTypes: true }) .filter((e) => e.isFile() && e.name.endsWith(".yaml")) .map((e) => join(dir, e.name)); } /** COACH-MOD: load all analysis models from analysis-models/. */ async loadAnalysisModels(): Promise { if (this._analysisModels) return this._analysisModels; const files = this.collectDirYamlFiles("analysis-models"); const models: AnalysisModel[] = []; const seenIds = new Set(); for (const filePath of files) { const raw = yaml.load(readFileSync(filePath, "utf-8")); const model = validateAnalysisModel(raw); if (seenIds.has(model.id)) { throw new Error(`重复分析模型 ID: "${model.id}" (文件: ${filePath})`); } seenIds.add(model.id); models.push(model); } this._analysisModels = models; return models; } /** COACH-MOD: load all scenario packs from scenario-packs/. */ async loadScenarioPacks(): Promise { if (this._scenarioPacks) return this._scenarioPacks; const files = this.collectDirYamlFiles("scenario-packs"); const packs: ScenarioPack[] = []; const seenIds = new Set(); for (const filePath of files) { const raw = yaml.load(readFileSync(filePath, "utf-8")); const pack = validateScenarioPack(raw); if (seenIds.has(pack.id)) { throw new Error(`重复场景包 ID: "${pack.id}" (文件: ${filePath})`); } seenIds.add(pack.id); packs.push(pack); } this._scenarioPacks = packs; return packs; } /** COACH-MOD: load personas from _registry/personas.yaml. */ async loadPersonas(): Promise { if (this._personas) return this._personas; const path = join(this.basePath, "_registry", "personas.yaml"); if (!existsSync(path)) { this._personas = []; return []; } const raw = yaml.load(readFileSync(path, "utf-8")); const { personas } = validatePersonaRegistry(raw ?? {}); const seenIds = new Set(); for (const p of personas) { if (seenIds.has(p.id)) { throw new Error(`重复画像 ID: "${p.id}" (文件: ${path})`); } seenIds.add(p.id); } this._personas = personas; return personas; } /** * COACH-MOD: return the single default analysis model (is_default: true). * §4.5 显式声明:0 个或 >1 个默认都抛错(不静默返回 undefined / 第一个), * 因为"复盘默认装一个基线"是硬约束(spec §2 ①原则·基线)。 */ async getDefaultAnalysisModel(): Promise { const models = await this.loadAnalysisModels(); const defaults = models.filter((m) => m.is_default); if (defaults.length === 0) { throw new Error("没有默认分析模型(需要恰好一个 is_default: true)"); } if (defaults.length > 1) { throw new Error( `默认分析模型不唯一:${defaults.map((m) => m.id).join(", ")}(需要恰好一个 is_default: true)`, ); } return defaults[0]!; } } /** Parse a threshold string like ">600" into { op: ">", value: 600 } */ function parseThreshold(s: string): { op: string; value: number } | null { const match = s.match(/^([><=]?)\s*(\d+)$/); if (!match) return null; return { op: match[1] || ">=", value: parseInt(match[2], 10) }; } /** Check if the entry's daily_total_minutes matches the query threshold */ function matchesThreshold(entryValue: string, queryValue: string): boolean { const pv = parseThreshold(queryValue); if (!pv) return entryValue === queryValue; // For entry values that are plain numbers or threshold expressions const entryMatch = entryValue.match(/^(\d+)$/); if (entryMatch) { const num = parseInt(entryMatch[1], 10); switch (pv.op) { case ">": return num > pv.value; case "<": return num < pv.value; case "=": return num === pv.value; default: return num >= pv.value; } } return entryValue === queryValue; }