"use strict";
/**
 * CorePresence — record the most-recent core CLI invocation so the daemon
 * (or anything reading from Telegram) knows which cwd to address.
 *
 * v1.11.0 — Core ↔ Agent Bridge (Phase 4).
 *
 * File: `~/.openlife/core-presence.json` (mode 0o600, atomic).
 *
 * The file is written on every `openlife <command>` invocation. TTL is
 * advisory — readers should treat presence as fresh if `invokedAt` is
 * within 60s, stale beyond that. Multiple concurrent invocations
 * last-writer-wins (acceptable: the goal is "most recent context").
 */
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.CorePresence = exports.PRESENCE_FRESH_S = void 0;
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const AtomicWriter_1 = require("../orchestrator/util/AtomicWriter");
exports.PRESENCE_FRESH_S = 60;
function presenceFile() {
    return path.join(os.homedir(), '.openlife', 'core-presence.json');
}
exports.CorePresence = {
    /**
     * Publish presence for the current process. Best-effort: failures are
     * logged in debug mode but never throw — presence is advisory.
     *
     * Pass the resolved Commander subcommand string for `command` (e.g.
     * "agent push", "bridge status"). When unavailable, falls back to argv[2].
     */
    publish(command) {
        try {
            const file = presenceFile();
            fs.mkdirSync(path.dirname(file), { recursive: true });
            const record = {
                schemaVersion: 1,
                pid: process.pid,
                cwd: process.cwd(),
                invokedAt: new Date().toISOString(),
                command: command || (process.argv.slice(2).join(' ') || 'openlife'),
                argv: [...process.argv],
            };
            (0, AtomicWriter_1.writeJsonAtomic)(file, record);
            try {
                fs.chmodSync(file, 0o600);
            }
            catch { /* best-effort */ }
        }
        catch (err) {
            if ((process.env.OPENLIFE_DEBUG || '').toLowerCase() === 'true') {
                console.error('[CORE-PRESENCE] publish failed:', err);
            }
        }
    },
    /** Read the most recent presence record (or null if missing/unparseable). */
    read() {
        const file = presenceFile();
        if (!fs.existsSync(file))
            return null;
        try {
            const raw = JSON.parse(fs.readFileSync(file, 'utf-8'));
            if (!raw || typeof raw.pid !== 'number' || typeof raw.cwd !== 'string')
                return null;
            return raw;
        }
        catch {
            return null;
        }
    },
    /** Compute age of the presence record in seconds (null if missing). */
    ageSeconds() {
        const r = this.read();
        if (!r)
            return null;
        const ts = Date.parse(r.invokedAt);
        if (!Number.isFinite(ts))
            return null;
        return Math.max(0, Math.floor((Date.now() - ts) / 1000));
    },
    /** Is the presence record fresh enough for the daemon to trust the cwd? */
    isFresh() {
        const age = this.ageSeconds();
        return age !== null && age <= exports.PRESENCE_FRESH_S;
    },
    /** Exposed for tests. */
    _file() {
        return presenceFile();
    },
};
