"use strict";
// Ambient Sensor Daemon — watches the local environment and emits NervousSignal
// events when something interesting happens. The user does not have to ask;
// the harness notices.
//
// Built-in watchers (all opt-in via start options):
//
//   * file watcher       — fs.watch on a directory, debounced, emits per change
//   * git poll watcher   — `git status --porcelain` every N ms, emits when state shifts
//   * scheduler watcher  — wakes on a fixed cadence so other engines can react to time
//
// The daemon does NOT take actions. It only emits signals onto a SignalBus.
// The Predictive Engine and Mission Control consume those signals and decide
// (according to the Trust Ladder) whether to surface, propose, or act.
//
// Storage: zero. The daemon is purely event-driven; durable history lives in
// the SignalBus rolling log and the Knowledge Graph if a consumer ingests it.
//
// Cross-platform note: Node `fs.watch` is best-effort on macOS/Linux/Windows.
// We debounce and de-dup to absorb the noisy bursts. For production-grade
// recursive watching, swap to `chokidar` in a follow-up — kept stdlib-only
// for now to honor the no-new-deps constraint.
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.startAmbientDaemon = startAmbientDaemon;
exports.collectAmbientSignals = collectAmbientSignals;
const events_1 = require("events");
const fs = __importStar(require("fs"));
const child_process_1 = require("child_process");
const signals_1 = require("../nervous/signals");
const DEFAULT_DEBOUNCE_MS = 250;
const DEFAULT_GIT_POLL_MS = 5_000;
function startAmbientDaemon(bus, options = {}) {
    const emitter = new events_1.EventEmitter();
    const projectDir = options.projectDir ?? process.cwd();
    const debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;
    const active = [];
    let stopped = false;
    // ─── File watcher ───────────────────────────────────────────────
    let fileWatcher = null;
    let fileTimer = null;
    const pendingFiles = new Set();
    if (options.watchDir) {
        try {
            fileWatcher = fs.watch(options.watchDir, { recursive: true }, (_event, filename) => {
                if (!filename || stopped)
                    return;
                const name = filename.toString();
                if (options.fileFilters && !options.fileFilters.some((f) => name.includes(f)))
                    return;
                pendingFiles.add(name);
                if (fileTimer)
                    clearTimeout(fileTimer);
                fileTimer = setTimeout(() => {
                    const batch = Array.from(pendingFiles);
                    pendingFiles.clear();
                    if (batch.length === 0)
                        return;
                    const sig = (0, signals_1.createSignal)('USER_INTENT', 'ambient.file', 'low', `Files changed: ${batch.slice(0, 5).join(', ')}${batch.length > 5 ? ` (+${batch.length - 5})` : ''}`);
                    sig.metadata = { files: batch, watchDir: options.watchDir };
                    bus.publish(sig);
                    emitter.emit('signal', sig);
                }, debounceMs);
            });
            active.push('file');
        }
        catch (err) {
            const sig = (0, signals_1.createSignal)('TOOL_ERROR', 'ambient.file', 'medium', `File watcher failed to start: ${err.message}`);
            bus.publish(sig);
        }
    }
    // ─── Git poll watcher ───────────────────────────────────────────
    let gitTimer = null;
    let lastGitState = null;
    const gitPollMs = options.gitPollMs ?? DEFAULT_GIT_POLL_MS;
    if (gitPollMs > 0) {
        const pollGit = () => {
            if (stopped)
                return;
            const proc = (0, child_process_1.spawn)('git', ['status', '--porcelain'], { cwd: projectDir });
            let buf = '';
            proc.stdout.on('data', (chunk) => { buf += chunk.toString(); });
            proc.on('close', () => {
                if (stopped)
                    return;
                const trimmed = buf.trim();
                if (lastGitState !== null && trimmed !== lastGitState) {
                    const dirty = trimmed.length > 0;
                    const sig = (0, signals_1.createSignal)(dirty ? 'USER_INTENT' : 'TOOL_SUCCESS', 'ambient.git', 'low', dirty ? 'Git working tree changed' : 'Git working tree clean');
                    sig.metadata = { porcelain: trimmed.split('\n').slice(0, 20) };
                    bus.publish(sig);
                    emitter.emit('signal', sig);
                }
                lastGitState = trimmed;
            });
            proc.on('error', () => { });
        };
        pollGit();
        gitTimer = setInterval(pollGit, gitPollMs);
        if (typeof gitTimer.unref === 'function')
            gitTimer.unref();
        active.push('git');
    }
    // ─── Scheduler tick ─────────────────────────────────────────────
    let schedulerTimer = null;
    if (options.schedulerMs && options.schedulerMs > 0) {
        schedulerTimer = setInterval(() => {
            if (stopped)
                return;
            const sig = (0, signals_1.createSignal)('USER_INTENT', 'ambient.scheduler', 'info', 'Scheduler tick');
            sig.metadata = { tickAt: new Date().toISOString() };
            bus.publish(sig);
            emitter.emit('signal', sig);
        }, options.schedulerMs);
        if (typeof schedulerTimer.unref === 'function')
            schedulerTimer.unref();
        active.push('scheduler');
    }
    return {
        stop() {
            stopped = true;
            if (fileWatcher) {
                try {
                    fileWatcher.close();
                }
                catch { /* noop */ }
            }
            if (fileTimer)
                clearTimeout(fileTimer);
            if (gitTimer)
                clearInterval(gitTimer);
            if (schedulerTimer)
                clearInterval(schedulerTimer);
        },
        emitter,
        isRunning: () => !stopped,
        watchersActive: () => [...active],
    };
}
/** Helper for tests: collect all signals emitted in a window. */
function collectAmbientSignals(handle, windowMs) {
    return new Promise((resolve) => {
        const out = [];
        const onSignal = (s) => out.push(s);
        handle.emitter.on('signal', onSignal);
        setTimeout(() => {
            handle.emitter.off('signal', onSignal);
            resolve(out);
        }, windowMs);
    });
}
//# sourceMappingURL=ambientDaemon.js.map