import { access, mkdir, readFile, writeFile } from "node:fs/promises" import path from "node:path" async function safeRead(filePath) { try { return await readFile(filePath, "utf8") } catch { return null } } function nowIso() { return new Date().toISOString() } async function resolveSyncCommand(directory) { const configured = process.env.FIDELITY_MATTERMOST_SYNC_CMD?.trim() if (configured) return configured const fallbackScript = path.join(directory, "scripts/mattermost/sync.sh") try { await access(fallbackScript) return `bash "${fallbackScript}"` } catch { return "" } } async function resolveSyncContent(directory, stdoutText) { const cleaned = (stdoutText || "").trim() if (cleaned) return cleaned const generatedPath = path.join(directory, "scripts/mattermost/generated/mattermost_context.jsonl") const generated = await safeRead(generatedPath) return (generated || "").trim() } export const MattermostInbox = async ({ $, directory, client }) => { let lastSyncAt = 0 async function writeStatus(statusPath, data) { await mkdir(path.dirname(statusPath), { recursive: true }) await writeFile(statusPath, `${JSON.stringify(data, null, 2)}\n`, "utf8") } async function sync(reason) { const command = await resolveSyncCommand(directory) if (!command) return const intervalMinutes = Number.parseInt( process.env.FIDELITY_MATTERMOST_SYNC_INTERVAL_MINUTES || "15", 10, ) const minIntervalMs = Math.max(1, Number.isNaN(intervalMinutes) ? 15 : intervalMinutes) * 60 * 1000 const now = Date.now() if (now - lastSyncAt < minIntervalMs) return lastSyncAt = now const inboxDir = path.join(directory, "ai/inbox") const latestPath = path.join(inboxDir, "mattermost-latest.md") const statusPath = path.join(inboxDir, "mattermost-status.json") try { await mkdir(inboxDir, { recursive: true }) const stdoutText = await $`bash -lc ${command}`.text() const output = await resolveSyncContent(directory, stdoutText) const previous = await safeRead(latestPath) if (output) { if (previous !== `${output}\n` && previous !== output) { const stamp = nowIso().replace(/[:]/g, "-") const snapshotPath = path.join(inboxDir, `mattermost-${stamp}.md`) await writeFile(latestPath, `${output}\n`, "utf8") await writeFile(snapshotPath, `${output}\n`, "utf8") } await writeStatus(statusPath, { syncedAt: nowIso(), reason, changed: previous !== `${output}\n` && previous !== output, commandConfigured: true, commandSource: process.env.FIDELITY_MATTERMOST_SYNC_CMD?.trim() ? "env" : "workspace-default", }) } else { await writeStatus(statusPath, { syncedAt: nowIso(), reason, changed: false, commandConfigured: true, commandSource: process.env.FIDELITY_MATTERMOST_SYNC_CMD?.trim() ? "env" : "workspace-default", note: "Sync command returned no output.", }) } } catch (error) { await writeStatus(statusPath, { syncedAt: nowIso(), reason, changed: false, commandConfigured: true, commandSource: process.env.FIDELITY_MATTERMOST_SYNC_CMD?.trim() ? "env" : "workspace-default", error: error instanceof Error ? error.message : String(error), }) await client.app.log({ body: { service: "mattermost-inbox", level: "warn", message: "Mattermost sync failed", extra: { reason, error: error instanceof Error ? error.message : String(error), }, }, }) } } return { event: async ({ event }) => { if (event.type === "session.created") { await sync("session.created") } if (event.type === "tui.prompt.append") { await sync("tui.prompt.append") } }, } }