import path from 'node:path';
import { nowIso, writeJsonAtomic, writeTextAtomic } from '../fsx.js';
import { analyzeCodexNativeReferenceSource, renderCodexNativeReferenceMarkdown } from './codex-native-reference-source.js';
const PATTERN_ROWS = [
    row('no-global-optional-tooling', 'Optional tooling stays non-global by default', 'adapt', ['src/core/zellij/zellij-self-heal.ts'], ['Keep optional repair/install paths explicit and proof-backed.']),
    row('plugin-lifecycle-state-separation', 'Plugin install and approval are separate states', 'adopt', ['src/core/codex-native/codex-native-feature-broker.ts'], ['Do not count installed tools as approved evidence.']),
    row('hook-approval-gating', 'Hook approval gates counted evidence', 'adopt', ['src/core/codex-app/codex-hook-lifecycle.ts'], ['Unknown or pending hook approval does not count as proof.']),
    row('skill-picker-route-bridge', 'SKS route skills bridge command picker usage', 'adapt', ['src/core/codex-app/codex-skill-sync.ts'], ['Managed skills expose route purpose, command, proof path, and failure recovery.']),
    row('native-agent-role-probe', 'Native agent role payload is probed before use', 'adopt', ['src/core/codex-app/codex-agent-type-probe.ts'], ['Use agent_type only when the probe supports it.']),
    row('message-role-fallback', 'Message-role fallback is explicit', 'adopt', ['src/core/codex-native/codex-native-invocation-router.ts'], ['Fallback remains valid but must be recorded in proof.']),
    row('directory-local-memory', 'Directory-local memory is guidance', 'adapt', ['src/core/codex-app/codex-init-deep.ts', 'src/core/loops/loop-planner.ts'], ['Memory hints never widen owner scope.']),
    row('plan-work-proof-separation', 'Plan, work, and proof stay separate', 'adopt', ['src/core/loops', 'src/core/naruto'], ['Route artifacts separate planning, execution, and verification.']),
    row('continuation-enforcer', 'Continuation is stateful and bounded', 'adapt', ['src/core/loops/loop-continuation-enforcer.ts'], ['Use runtime proof when hook approval is not approved.']),
    row('doctor-harness-matrix', 'Doctor merges readiness into one story', 'adopt', ['src/commands/doctor.ts'], ['Doctor should show Zellij, Codex Native, Loop, QA, and Research together.']),
    row('mcp-tool-candidate-inventory', 'MCP plugin servers are candidates', 'adapt', ['src/core/mcp/mcp-plugin-inventory.ts'], ['Candidate-only inventory prevents accidental destructive auto-enable.']),
    row('non-clobber-managed-assets', 'Managed assets avoid clobbering user files', 'adopt', ['src/core/codex-app/codex-skill-sync.ts', 'src/core/codex-app/codex-agent-role-sync.ts'], ['Skip unmarked user assets and include checksums for managed content.'])
];
export async function buildCodexNativePatternAnalysis(input) {
    const root = path.resolve(input.root);
    const evidence = input.evidence || await analyzeCodexNativeReferenceSource({ root, sourceDir: input.sourceDir || null, writeReport: true }).catch(() => null);
    const evidenceByPattern = new Map();
    for (const item of evidence?.evidence || []) {
        const list = evidenceByPattern.get(item.pattern_id) || [];
        list.push(item.snippet_hash);
        evidenceByPattern.set(item.pattern_id, list);
    }
    return {
        schema: 'sks.codex-native-pattern-analysis.v1',
        generated_at: nowIso(),
        source_kind: 'external-reference-source',
        source_ref: evidence?.source_ref || input.sourceDir || '.sneakoscope/cache/codex-native-reference',
        source_sha: evidence?.source_sha || null,
        patterns: PATTERN_ROWS.map((pattern) => {
            const hashes = evidenceByPattern.get(pattern.id) || [];
            return {
                ...pattern,
                confidence: hashes.length ? 'high' : evidence ? 'medium' : 'low',
                evidence_hashes: hashes
            };
        }),
        blockers: evidence?.blockers || ['source_snapshot_missing'],
        warnings: evidence?.warnings || ['reference_evidence_unavailable']
    };
}
export async function writeCodexNativePatternAnalysis(root, input = {}) {
    const evidence = await analyzeCodexNativeReferenceSource({ root, sourceDir: input.sourceDir || null, writeReport: true }).catch(() => null);
    const report = await buildCodexNativePatternAnalysis({ root, evidence, sourceDir: input.sourceDir || null });
    await writeJsonAtomic(path.join(root, '.sneakoscope', 'reports', 'codex-native-pattern-analysis.json'), report);
    if (evidence)
        await writeTextAtomic(path.join(root, 'docs', 'codex-native-patterns.md'), renderCodexNativeReferenceMarkdown(evidence)).catch(() => undefined);
    return report;
}
function row(id, title, adoption, sks_target_modules, implementation_notes) {
    return { id, title, adoption, sks_target_modules, implementation_notes };
}
//# sourceMappingURL=codex-native-pattern-analysis.js.map