UNPKG

@phren/cli

Version:

Knowledge layer for AI agents - CLI, MCP server, and data layer

181 lines (180 loc) • 8.41 kB
import { createHash } from "node:crypto"; import { readFileSync } from "node:fs"; import path from "node:path"; import { z } from "zod"; import { withFileLock } from "../governance/locks.js"; import { atomicWriteText, ensurePrivateDir } from "../phren-paths.js"; import { getProjectSourcePath } from "../project-config.js"; import { getProjectDirs } from "../shared.js"; import { localNames } from "./computer-names.js"; import { BridgeError, bridgeRoot } from "./protocol.js"; import { computerMatches, readScheduleDocumentSync } from "./schedule-format.js"; const hash = (text) => createHash("sha256").update(text).digest("hex"); export const scheduleFingerprintSchema = z.string().regex(/^[a-f0-9]{64}$/); const approvalSchema = z.object({ fingerprint: scheduleFingerprintSchema, fields: z.record(z.string(), scheduleFingerprintSchema) }); const stateSchema = z.object({ approved: z.record(z.string(), approvalSchema), skipped: z.array(scheduleFingerprintSchema), }); function canonicalJson(value) { // Normalize YAML's JSON-compatible values first, including timestamps. A cyclic // value cannot be approved. Sort object keys at every level and keep array order. return JSON.stringify(JSON.parse(JSON.stringify(value)), (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item); } export function localScheduleNames() { const names = localNames(); try { names.push(readFileSync(path.join(bridgeRoot(), "computer-id"), "utf8").trim()); } catch { /* The Hook may not be installed yet. */ } return names; } export class ScheduleApprovals { store; names; log; file; constructor(store, names = localScheduleNames, log = message => console.error(message), root = bridgeRoot()) { this.store = store; this.names = names; this.log = log; this.file = path.join(root, "schedule-approvals", `${hash(path.resolve(store))}.json`); } read() { try { return stateSchema.parse(JSON.parse(readFileSync(this.file, "utf8"))); } catch (error) { if (error.code !== "ENOENT") throw error; return undefined; } } write(state) { atomicWriteText(this.file, JSON.stringify(state) + "\n", { mode: 0o600 }); } lock(work) { ensurePrivateDir(path.dirname(this.file)); withFileLock(this.file, work); } *localSchedules() { const names = this.names(); for (const directory of getProjectDirs(this.store)) { let schedules; try { schedules = readScheduleDocumentSync(directory).schedules; } catch { continue; } for (const schedule of schedules) { if (names.some(name => computerMatches(schedule.computer, name))) yield { project: path.basename(directory), schedule }; } } } candidate(project, schedule) { // Clock timing, labels and notifications are editable without changing what // runs. Include otherwise unknown fields so future launch options are covered. const { id, name: _name, every, at: _at, days: _days, interval: _interval, once: _once, cron: _cron, enabled: _enabled, notify: _notify, createdAt: _createdAt, updatedAt: _updatedAt, ...execution } = schedule; const directories = getProjectDirs(this.store).map(directory => path.basename(directory)); const sources = new Map((schedule.projects ?? [project]).map(name => { const target = directories.find(dir => dir.toLowerCase() === name.toLowerCase()) ?? name; return [name, getProjectSourcePath(this.store, target)]; })); const triggerMode = every === "event" ? "event" : "clock"; const sourcePaths = Object.fromEntries([...sources].map(([target, source]) => [target, source ?? null])); const fields = Object.fromEntries(Object.entries({ ...execution, "trigger mode": triggerMode, "project source paths": sourcePaths }) .filter(([, value]) => value !== undefined).map(([field, value]) => [field, hash(canonicalJson(value))])); const fingerprint = hash(canonicalJson({ execution, triggerMode, sourcePaths })); return { key: `${project}/${id}`, approval: { fingerprint, fields }, sources }; } initialize() { if (this.read()) return; this.lock(() => { if (this.read()) return; const state = { approved: {}, skipped: [] }; for (const { project, schedule } of this.localSchedules()) { try { const { key, approval } = this.candidate(project, schedule); state.approved[key] = approval; } catch { this.log(`[schedule] Could not migrate approval for ${project}/${schedule.id}.`); } } this.write(state); this.log(`[schedule] Approved ${Object.keys(state.approved).length} existing local schedules on first use.`); }); } saveLocal(project, schedule) { if (!this.names().some(name => computerMatches(schedule.computer, name))) return; this.approve(this.candidate(project, schedule)); } approve({ key, approval }, expectedFingerprint) { if (expectedFingerprint !== undefined && approval.fingerprint !== expectedFingerprint) { throw new BridgeError(409, "This schedule changed. Refresh it before approving."); } this.initialize(); this.lock(() => { const state = this.read(); if (!state) throw new Error("Schedule approval state disappeared."); if (state.approved[key]?.fingerprint === approval.fingerprint) return; state.approved[key] = approval; this.write(state); }); } permits({ key, approval }) { const state = this.read(); if (!state) throw new Error("Schedule approval state is unavailable."); if (state.approved[key]?.fingerprint === approval.fingerprint) return true; const skipped = hash(canonicalJson([key, approval.fingerprint])); if (!state.skipped.includes(skipped)) this.lock(() => { const current = this.read(); if (!current) throw new Error("Schedule approval state disappeared."); if (current.approved[key]?.fingerprint === approval.fingerprint || current.skipped.includes(skipped)) return; current.skipped = [...current.skipped, skipped].slice(-2000); this.write(current); this.log(`[schedule] Waiting for local approval of ${key} (${approval.fingerprint}).`); }); return false; } inboxSources() { const state = this.read(); if (!state) return []; const sources = []; for (const { project, schedule } of this.localSchedules()) { if (!schedule.enabled) continue; let candidate; try { candidate = this.candidate(project, schedule); } catch { continue; } const { key, approval } = candidate, previous = state.approved[key]; if (previous?.fingerprint === approval.fingerprint) continue; const changed = previous && [...new Set([...Object.keys(previous.fields), ...Object.keys(approval.fields)])] .filter(field => Object.hasOwn(previous.fields, field) !== Object.hasOwn(approval.fields, field) || previous.fields[field] !== approval.fields[field]); const reason = changed?.length ? `Changed fields: ${changed.join(", ")}.` : "No approval on this computer."; sources.push({ source: `schedule-approval:${project}:${schedule.id}`, kind: "blocked", project, actionId: approval.fingerprint, title: `Approve schedule “${schedule.name}” in ${project}. ${reason}`.replace(/[\x00-\x1f\x7f]+/g, " ").slice(0, 500) }); } return sources; } }