"use strict";
// Audit-everything hook.
//
// Writes a JSONL line per tool call to `.harness/audit.log`. Captures the
// PreToolUse signal so we always have an entry even if the tool result is
// blocked or never returns, and a PostToolUse / PostToolUseFailure entry
// once the tool finishes (or errors).
//
// Inputs are summarised — full payloads are truncated to a fixed character
// limit per field so the log stays bounded under heavy use. Tools that
// commonly carry secrets (api keys, tokens) get redacted via a small
// allowlist of field names.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.auditFilePath = auditFilePath;
exports.createAuditHooks = createAuditHooks;
exports.readAuditLog = readAuditLog;
exports.renderRecentAuditForPrompt = renderRecentAuditForPrompt;
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const DEFAULT_MAX_FIELD = 2000;
const DEFAULT_REDACT = new Set(['api_key', 'apiKey', 'token', 'password', 'secret', 'authorization', 'auth_token']);
function auditFilePath(projectDir) {
    return path.join(projectDir, '.harness', 'audit.log');
}
function createAuditHooks(options) {
    const filePath = options.filePath ?? auditFilePath(options.projectDir);
    const maxFieldChars = options.maxFieldChars ?? DEFAULT_MAX_FIELD;
    const redact = new Set([...DEFAULT_REDACT, ...(options.redactFields ?? [])]);
    const handler = async (context) => {
        const entry = {
            timestamp: new Date().toISOString(),
            eventType: context.eventType,
            tool: context.toolName,
            input: context.toolInput ? truncate(JSON.stringify(redactInput(context.toolInput, redact)), maxFieldChars) : undefined,
            output: context.toolOutput ? truncate(context.toolOutput, maxFieldChars) : undefined,
            error: context.error,
        };
        try {
            await fs.mkdir(path.dirname(filePath), { recursive: true });
            await fs.appendFile(filePath, JSON.stringify(entry) + '\n', 'utf-8');
        }
        catch {
            // Audit must never break the loop — swallow.
        }
        return { action: 'continue' };
    };
    const wrap = (name, eventType) => ({
        name,
        eventType,
        handler: handler,
    });
    return [
        wrap('audit.preToolUse', 'PreToolUse'),
        wrap('audit.postToolUse', 'PostToolUse'),
        wrap('audit.postToolUseFailure', 'PostToolUseFailure'),
    ];
}
async function readAuditLog(projectDir, limit = 200) {
    const filePath = auditFilePath(projectDir);
    let raw;
    try {
        raw = await fs.readFile(filePath, 'utf-8');
    }
    catch {
        return [];
    }
    const entries = [];
    for (const line of raw.split('\n')) {
        const trimmed = line.trim();
        if (!trimmed)
            continue;
        try {
            entries.push(JSON.parse(trimmed));
        }
        catch {
            // Corrupt lines are skipped rather than crashing the reader.
        }
    }
    return entries.slice(-limit);
}
function truncate(value, max) {
    if (value.length <= max)
        return value;
    return value.slice(0, max) + `…[+${value.length - max} chars]`;
}
function redactInput(input, redactFields) {
    const out = {};
    for (const [key, value] of Object.entries(input)) {
        if (redactFields.has(key)) {
            out[key] = '[redacted]';
            continue;
        }
        if (value && typeof value === 'object' && !Array.isArray(value)) {
            out[key] = redactInput(value, redactFields);
        }
        else {
            out[key] = value;
        }
    }
    return out;
}
/**
 * Build a compact summary of recent tool failures for inclusion in the chat
 * system prompt. Returns an empty string when nothing actionable is in the
 * window; the goal is to surface signal, not chatter.
 */
async function renderRecentAuditForPrompt(projectDir, options = {}) {
    const scanLimit = options.scanLimit ?? 50;
    const windowMs = options.windowMs ?? 10 * 60 * 1000;
    const minFailures = options.minFailures ?? 2;
    const reader = options.reader ?? readAuditLog;
    const entries = await reader(projectDir, scanLimit).catch(() => []);
    if (entries.length === 0)
        return '';
    const cutoff = Date.now() - windowMs;
    const recentFailures = entries.filter((entry) => {
        if (entry.eventType !== 'PostToolUseFailure')
            return false;
        const ts = Date.parse(entry.timestamp);
        return Number.isFinite(ts) && ts >= cutoff;
    });
    if (recentFailures.length < minFailures)
        return '';
    const byTool = new Map();
    for (const entry of recentFailures) {
        const key = entry.tool ?? '(unknown)';
        byTool.set(key, (byTool.get(key) ?? 0) + 1);
    }
    const lines = [`Recent tool failures (last ${Math.round(windowMs / 60_000)} min): ${recentFailures.length} total.`];
    for (const [tool, count] of [...byTool.entries()].sort((a, b) => b[1] - a[1])) {
        lines.push(`- ${tool}: ${count} failure(s)`);
    }
    // Surface up to 3 most recent error messages for context.
    const sample = recentFailures.slice(-3);
    for (const entry of sample) {
        const where = entry.tool ? `${entry.tool} ` : '';
        const why = entry.error ? entry.error.slice(0, 200) : 'no error message';
        lines.push(`- ${where}@ ${entry.timestamp}: ${why}`);
    }
    lines.push('Consider switching tools or asking the user before retrying the same call.');
    return `# Recent Audit\n${lines.join('\n')}`;
}
//# sourceMappingURL=audit.js.map