"use strict";
// Persistent sub-agent run log.
//
// Every sub-agent invocation is captured here after it finishes so the
// user can see "what agents have run, with what input, what came out, and
// where any files landed". Lightweight by design: a single append-only
// JSONL under .harness/subagent-runs/runs.jsonl with bounded size.
//
// We deliberately keep this separate from the chat event store so the
// Agents tab UI can read it cheaply without scanning the entire session
// history.
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.appendSubagentRun = appendSubagentRun;
exports.listSubagentRuns = listSubagentRuns;
exports.getSubagentRun = getSubagentRun;
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const atomicFile_1 = require("../persistence/atomicFile");
const silentFailureSink_1 = require("../observability/silentFailureSink");
const MAX_RECORDS = 200;
function runsPath(projectDir) {
    return path.join(projectDir, '.harness', 'subagent-runs', 'runs.jsonl');
}
/** Append a run record, trimming the log to MAX_RECORDS entries. */
async function appendSubagentRun(projectDir, record) {
    const fp = runsPath(projectDir);
    await fs.mkdir(path.dirname(fp), { recursive: true });
    await (0, atomicFile_1.withFileLock)(fp, async () => {
        let existing = '';
        try {
            existing = await fs.readFile(fp, 'utf-8');
        }
        catch { /* first write */ }
        const lines = existing.split(/\r?\n/).filter((line) => line.trim().length > 0);
        lines.push(JSON.stringify(record));
        const trimmed = lines.length > MAX_RECORDS ? lines.slice(lines.length - MAX_RECORDS) : lines;
        await fs.writeFile(fp, trimmed.join('\n') + '\n', 'utf-8');
    }).catch((err) => (0, silentFailureSink_1.recordSwallowed)('subagentRuns.append', err));
}
/** Return the most recent runs, newest first. */
async function listSubagentRuns(projectDir, limit = 50) {
    const fp = runsPath(projectDir);
    let raw = '';
    try {
        raw = await fs.readFile(fp, 'utf-8');
    }
    catch {
        return [];
    }
    const lines = raw.split(/\r?\n/).filter((line) => line.trim().length > 0);
    const records = [];
    for (let i = lines.length - 1; i >= 0 && records.length < limit; i--) {
        try {
            const parsed = JSON.parse(lines[i]);
            if (parsed && typeof parsed.runId === 'string')
                records.push(parsed);
        }
        catch { /* skip corrupt line */ }
    }
    return records;
}
/** Look up a single run by id. */
async function getSubagentRun(projectDir, runId) {
    const all = await listSubagentRuns(projectDir, MAX_RECORDS);
    return all.find((record) => record.runId === runId) ?? null;
}
//# sourceMappingURL=subagentRuns.js.map