/**
 * YAML-backed store for group-level default tool grant policies.
 * File: .bobbit/config/tool-group-policies.yaml
 *
 * Maps group name → GrantPolicy. Reloads from disk on every read
 * to stay consistent with manual edits (same pattern as ToolManager).
 */
import fs from "node:fs";
import path from "node:path";
import { stringify, parse } from "yaml";
const VALID_POLICIES = new Set(['allow', 'ask', 'never', 'always-ask', 'ask-once', 'never-ask', 'always-allow']);
export class ToolGroupPolicyStore {
    policyFile;
    builtinPolicies = {};
    constructor(configDir) {
        this.policyFile = path.join(configDir, "tool-group-policies.yaml");
    }
    /*
     * Builtin policies are immutable; user overrides land in <stateDir>/tool-group-policies.yaml.
     * `setBuiltins` is invoked once at boot from `defaults/tool-group-policies.yaml`
     * (or the cascade resolution thereof) and is the only way builtin defaults
     * are populated. Subsequent runtime calls to `setGroupPolicy` only mutate
     * the on-disk YAML override file, never these in-memory defaults.
     */
    setBuiltins(policies) {
        this.builtinPolicies = { ...policies };
    }
    /** Read all group policies from disk. */
    getLocal() {
        const filePath = this.policyFile;
        const result = {};
        try {
            const raw = fs.readFileSync(filePath, "utf-8");
            const data = parse(raw);
            if (!data || typeof data !== "object")
                return result;
            for (const [key, value] of Object.entries(data)) {
                if (typeof value === "string" && VALID_POLICIES.has(value)) {
                    result[key] = value;
                }
            }
            return result;
        }
        catch {
            // File doesn't exist or is invalid — return no local overrides.
            return result;
        }
    }
    /** Read all group policies from disk, merged over builtin defaults. */
    getAll() {
        return { ...this.builtinPolicies, ...this.getLocal() };
    }
    /** Get the default policy for a specific group. Returns null if not set. */
    getGroupPolicy(group) {
        const all = this.getAll();
        return all[group] ?? null;
    }
    /** Set or clear the default policy for a group. Pass null to remove. */
    setGroupPolicy(group, policy) {
        const all = this.getLocal();
        if (policy === null) {
            delete all[group];
        }
        else {
            all[group] = policy;
        }
        const filePath = this.policyFile;
        fs.mkdirSync(path.dirname(filePath), { recursive: true });
        fs.writeFileSync(filePath, stringify(all), "utf-8");
    }
}
//# sourceMappingURL=tool-group-policy-store.js.map