"use strict";
// Trust Ladder — per-capability autonomy rungs.
//
// Maps each capability (file_write, bash, email_send, slack_send, ambient_act, etc.)
// to one of five rungs:
//
//   0 shadow    — observe only, never act, log proposed action
//   1 suggest   — propose an action in Mission Control, never execute
//   2 ask       — execute only after explicit user click
//   3 confirm   — execute after a typed confirmation token (kill-switch armed)
//   4 act       — execute autonomously, post-hoc evidence card
//
// Rungs decay back toward `ask` after a configurable idle window so a long
// quiet period re-arms the human-in-the-loop. Rungs escalate after a streak
// of accepted suggestions, never automatically — the user must accept the
// promotion via the existing learning-promotion gate.
//
// Storage is a single JSON file under `.harness/jarvis/trust-ladder.json` so
// it survives restarts but is trivially auditable / editable by the operator.
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.RUNG_NAMES = void 0;
exports.loadTrustLadder = loadTrustLadder;
exports.saveTrustLadder = saveTrustLadder;
exports.getRung = getRung;
exports.ensureCapability = ensureCapability;
exports.recordOutcome = recordOutcome;
exports.explainRung = explainRung;
exports.canActAutonomously = canActAutonomously;
exports.requiresConfirmation = requiresConfirmation;
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const atomicFile_1 = require("../persistence/atomicFile");
exports.RUNG_NAMES = {
    0: 'shadow',
    1: 'suggest',
    2: 'ask',
    3: 'confirm',
    4: 'act',
};
const DEFAULT_DECAY_MS = 1000 * 60 * 60 * 24 * 7; // one quiet week → re-arm
const PROMOTION_STREAK = 5;
const DEMOTION_STREAK = 2;
function ladderPath(projectDir) {
    return path.join(projectDir, '.harness', 'jarvis', 'trust-ladder.json');
}
async function loadTrustLadder(projectDir) {
    try {
        const raw = await fs.readFile(ladderPath(projectDir), 'utf8');
        return JSON.parse(raw);
    }
    catch {
        return { capabilities: {}, updatedAt: new Date(0).toISOString() };
    }
}
async function saveTrustLadder(projectDir, snap) {
    const filePath = ladderPath(projectDir);
    await (0, atomicFile_1.withFileLock)(filePath, () => (0, atomicFile_1.atomicWriteFile)(filePath, JSON.stringify(snap, null, 2), { encoding: 'utf-8' }));
}
function getRung(snap, capability) {
    const entry = snap.capabilities[capability];
    if (!entry)
        return 2; // default: ask
    // Apply decay: if quiet for longer than decayAfterMs, drop one rung (floor 2)
    if (entry.lastUsedAt) {
        const elapsed = Date.now() - new Date(entry.lastUsedAt).getTime();
        if (elapsed > entry.decayAfterMs && entry.rung > 2) {
            return (entry.rung - 1);
        }
    }
    return entry.rung;
}
function ensureCapability(snap, capability) {
    let entry = snap.capabilities[capability];
    if (!entry) {
        entry = { capability, rung: 2, acceptedStreak: 0, rejectedStreak: 0, decayAfterMs: DEFAULT_DECAY_MS };
        snap.capabilities[capability] = entry;
    }
    return entry;
}
function recordOutcome(snap, capability, outcome) {
    const entry = ensureCapability(snap, capability);
    entry.lastUsedAt = new Date().toISOString();
    snap.updatedAt = entry.lastUsedAt;
    if (outcome === 'accepted') {
        entry.acceptedStreak += 1;
        entry.rejectedStreak = 0;
        if (entry.acceptedStreak >= PROMOTION_STREAK && entry.rung < 4) {
            entry.rung = (entry.rung + 1);
            entry.acceptedStreak = 0;
            return { promoted: entry.rung };
        }
    }
    else if (outcome === 'rejected') {
        entry.rejectedStreak += 1;
        entry.acceptedStreak = 0;
        if (entry.rejectedStreak >= DEMOTION_STREAK && entry.rung > 0) {
            entry.rung = (entry.rung - 1);
            entry.rejectedStreak = 0;
            return { demoted: entry.rung };
        }
    }
    else {
        // 'used' — neutral activity, just refreshes the decay timer
    }
    return {};
}
function explainRung(rung) {
    return `${rung} ${exports.RUNG_NAMES[rung]}`;
}
/** Decide whether a proposed action may run autonomously right now. */
function canActAutonomously(snap, capability) {
    return getRung(snap, capability) === 4;
}
/** Decide whether a proposed action requires a typed confirmation token. */
function requiresConfirmation(snap, capability) {
    return getRung(snap, capability) === 3;
}
//# sourceMappingURL=trustLadder.js.map