import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
/**
 * agentmemory(跨项目持久记忆)接入 SPS worker —— P1。
 *
 * 把 agentmemory 的 Claude Code hooks **幂等合并**进某个项目的 `.claude/settings.json`。
 * - 作用域 = 仅该项目(SPS worker 的 cwd)→ 只捕获 build worker,不碰用户全局/交互会话。
 * - ACP worker(@anthropic-ai/claude-agent-sdk)的 `settingSources` 含 "project",
 *   会读这个文件并触发 hooks → 拿到**完整 tool_input/tool_output**(daemon 事件流是有损的,只有工具名)。
 * - 链路:PostToolUse→`/agentmemory/observe`(:3111)捕获 → SessionEnd→MiniMax 压缩成教训+抽图谱
 *   → SessionStart→把相关记忆注入对话(AGENTMEMORY_INJECT_CONTEXT=true)。
 * - agentmemory 没装 / 找不到插件 → 静默返回 false,**绝不影响 build**。
 */
const PLUGIN_CANDIDATES = [
    process.env.SPS_AGENTMEMORY_PLUGIN,
    process.env.HOME &&
        join(process.env.HOME, '.npm-global/lib/node_modules/@agentmemory/agentmemory/plugin'),
    process.env.HOME &&
        join(process.env.HOME, '.npm/lib/node_modules/@agentmemory/agentmemory/plugin'),
    '/usr/lib/node_modules/@agentmemory/agentmemory/plugin',
    '/usr/local/lib/node_modules/@agentmemory/agentmemory/plugin',
].filter(Boolean);
function findPluginRoot() {
    for (const c of PLUGIN_CANDIDATES) {
        if (existsSync(join(c, 'hooks/hooks.json')) && existsSync(join(c, 'scripts')))
            return c;
    }
    return null;
}
/** 该 entry 是不是我们(agentmemory 插件 scripts)写的——用于幂等替换、跨版本不留陈旧引用。 */
function isAgentmemoryEntry(e) {
    return (e.hooks ?? []).some((h) => /agentmemory[^"']*plugin[/\\]scripts/.test(h?.command ?? ''));
}
/**
 * 确保 projectDir/.claude/settings.json 含 agentmemory 的 hooks。
 * @returns 是否实际接入(false = agentmemory 未安装,已跳过)
 */
export function ensureAgentmemoryHooks(projectDir) {
    try {
        const pluginRoot = findPluginRoot();
        if (!pluginRoot)
            return false;
        const tmpl = JSON.parse(readFileSync(join(pluginRoot, 'hooks/hooks.json'), 'utf8'));
        // ${CLAUDE_PLUGIN_ROOT}(插件机制变量)→ 绝对插件根(我们直接写 settings,不走插件机制)
        const ours = JSON.parse(JSON.stringify(tmpl.hooks).replaceAll('${CLAUDE_PLUGIN_ROOT}', pluginRoot));
        const claudeDir = join(projectDir, '.claude');
        const settingsPath = join(claudeDir, 'settings.json');
        let settings = {};
        if (existsSync(settingsPath)) {
            try {
                settings = JSON.parse(readFileSync(settingsPath, 'utf8'));
            }
            catch {
                settings = {};
            }
        }
        const merged = { ...(settings.hooks ?? {}) };
        for (const [event, entries] of Object.entries(ours)) {
            // 先剔除我们旧的同类条目(跨版本不留陈旧路径),再加当前;保留用户自有 hooks。
            const userEntries = (Array.isArray(merged[event]) ? merged[event] : []).filter((e) => !isAgentmemoryEntry(e));
            merged[event] = [...userEntries, ...entries];
        }
        settings.hooks = merged;
        if (!existsSync(claudeDir))
            mkdirSync(claudeDir, { recursive: true });
        writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}\n`);
        return true;
    }
    catch {
        return false; // 永不让记忆接入影响 build
    }
}
//# sourceMappingURL=agentmemory.js.map