import { existsSync, mkdirSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import { defaultSchemaJson } from "../policy/default-policy.ts"; /** 最小化 home 配置文件:仅 schema 头,用户只需写与内置默认不同的规则。 */ const homeConfigTemplate = `# yaml-language-server: $schema=./ast-guard.schema.json # 用户级策略,覆盖内置默认策略。 # 只需写与内置默认不同的规则,同 id 覆盖,不同 id 追加。 # 规则优先级偏移 -0.3(内置默认 -0.6,项目级 0)。 settings: {} rules: [] `; export interface EnsureHomeConfigResult { /** 本次实际创建了配置文件。 */ configCreated: boolean; homeDir: string; /** 本次实际创建了 schema 文件。 */ schemaCreated: boolean; } /** * 初始化:检测 home 目录(~/.pi/agent)下的配置文件与 JSON Schema, * 缺失即自动创建(yml 已含 schema 头)。已存在不覆盖,失败静默容错。 */ export function ensureHomeConfig( homeDir: string = homedir() ): EnsureHomeConfigResult { const base = join(homeDir, ".pi", "agent"); const configPath = join(base, "ast-guard.yml"); const schemaPath = join(base, "ast-guard.schema.json"); const configCreated = !existsSync(configPath); const schemaCreated = !existsSync(schemaPath); if (!(configCreated || schemaCreated)) { return { configCreated, homeDir, schemaCreated }; } try { mkdirSync(base, { recursive: true }); if (configCreated) { writeFileSync(configPath, homeConfigTemplate, "utf8"); } if (schemaCreated) { writeFileSync(schemaPath, defaultSchemaJson, "utf8"); } } catch { return { configCreated: false, homeDir, schemaCreated: false }; } return { configCreated, homeDir, schemaCreated }; }