an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
feat(memory): MemoryReflector — the janitor's missing condense half (#3)
Chaitanya Giri109c22b8945e
diff --git a/src/main/config.ts b/src/main/config.tsindex a83ce5bf..89c78eec 100644--- a/src/main/config.ts+++ b/src/main/config.ts@@ -69,6 +69,22 @@ export interface HarnessConfig {slackChannelId?: string;/** Local HTTP port the webhook server binds to (default 3847). */slackPort?: number;++ // ─── Memory reflection (the janitor's condense half) ───────────────────────+ /** Master toggle for the in-process MemoryReflector. Default on. */+ reflectEnabled?: boolean;+ /** How often to scan agent memory.md files for condensing (default 30 min). */+ reflectIntervalMs?: number;+ /** Condense when bytes exceed this percent of the 128 KB budget (matches the+ * janitor's TRIGGER_PCT). DECIDED: 50. */+ reflectByteTriggerPct?: number;+ /** ...OR when `## ` section count exceeds this (AND bytes > floor). DECIDED: 50. */+ reflectSectionTrigger?: number;+ /** Newest K verbatim `## ` sections kept untouched on each condense. */+ reflectRecentKeep?: number;+ /** Never condense a file smaller than this; also the section-trigger byte floor.+ * DECIDED: 16 KB. */+ reflectMinBytes?: number;}const DEFAULTS: HarnessConfig = {@@ -85,7 +101,16 @@ const DEFAULTS: HarnessConfig = {slackSigningSecret: undefined,slackBotToken: undefined,slackChannelId: undefined,- slackPort: undefined+ slackPort: undefined,+ // Memory reflection — preventive; nobody is over threshold today, so it sits+ // dark until an agent's memory crosses one of these (the verify gate is the+ // safety for the LLM step). Thresholds DECIDED by god 2026-06-06.+ reflectEnabled: true,+ reflectIntervalMs: 1_800_000,+ reflectByteTriggerPct: 50,+ reflectSectionTrigger: 50,+ reflectRecentKeep: 12,+ reflectMinBytes: 16_384};function configPath(): string {diff --git a/src/main/index.ts b/src/main/index.tsindex c96a5e50..54a0056f 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -15,6 +15,7 @@ import {import { HiveManager, type AgentMeta, type HiveMessage, type HiveTask } from './hive';import { HookServer } from './hooks';import { MemoryManager } from './memory';+import { MemoryReflector, type ReflectSettings } from './reflect';import { enrichMessage } from './assistant';import { readAgentUsage } from './transcript';import { listIssues, listCIRuns } from './github';@@ -34,6 +35,28 @@ const memory = new MemoryManager(() => readConfig().harnessHome,() => { const c = readConfig(); return { enabled: c.semanticMemory !== false, model: c.embeddingModel ?? 'minilm' }; });+/** Reads the reflect tunables from config each tick (defaults baked in here so a+ * pre-existing config.json without the keys still gets sane values). */+function reflectSettings(): ReflectSettings {+ const c = readConfig();+ return {+ enabled: c.reflectEnabled !== false,+ intervalMs: c.reflectIntervalMs ?? 1_800_000,+ byteTriggerPct: c.reflectByteTriggerPct ?? 50,+ sectionTrigger: c.reflectSectionTrigger ?? 50,+ recentKeep: c.reflectRecentKeep ?? 12,+ minBytes: c.reflectMinBytes ?? 16_384+ };+}+// Finishes the janitor's missing condense half: bounds each agent's memory.md+// (Haiku tail-summary, backup→verify→atomic-swap) so it never grows unbounded.+const reflector = new MemoryReflector(+ () => readConfig().harnessHome,+ () => readConfig().defaultCommand ?? 'claude',+ () => memory.env(),+ reflectSettings,+ (event) => { try { hive.appendLog(event); } catch { /* best-effort */ } }+);let mainWindow: BrowserWindow | null = null;/** When true, skip the quit interceptor (user already confirmed). */@@ -490,6 +513,10 @@ ipcMain.handle('hive:searchMemory', (_evt, query: unknown, wing: unknown) => {ipcMain.handle('hive:memoryWakeUp', (_evt, wing: unknown) =>memory.wakeUp(typeof wing === 'string' ? wing : undefined));ipcMain.handle('hive:mineNow', () => { memory.mineNow(); return { ok: true }; });+// Condense memory.md on demand: an explicit id condenses that one agent (skips+// the size trigger — a "condense now" button); no id runs a full threshold scan.+ipcMain.handle('memory:reflectNow', (_evt, id: unknown) =>+ reflector.reflectNow(typeof id === 'string' && id ? id : undefined));// ─── IPC: quit confirmation ─────────────────────────────────────────────────ipcMain.handle('app:confirmClose', () => {@@ -501,6 +528,7 @@ ipcMain.handle('app:confirmClose', () => {try { hookServer.stop(); } catch (e) { console.error('[quit] hookServer.stop:', e); }try { stopSlackServer(); } catch (e) { console.error('[quit] slack.stop:', e); }try { memory.stop(); } catch (e) { console.error('[quit] memory.stop:', e); }+ try { reflector.stop(); } catch (e) { console.error('[quit] reflector.stop:', e); }try { ptyManager.killAll(); } catch (e) { console.error('[quit] killAll:', e); }app.quit();});@@ -517,6 +545,7 @@ ipcMain.handle('app:resetAll', () => {try { hookServer.stop(); } catch (e) { console.error('[reset] hookServer.stop:', e); }try { stopSlackServer(); } catch (e) { console.error('[reset] slack.stop:', e); }try { memory.stop(); } catch (e) { console.error('[reset] memory.stop:', e); }+ try { reflector.stop(); } catch (e) { console.error('[reset] reflector.stop:', e); }try { ptyManager.killAll(); } catch (e) { console.error('[reset] killAll:', e); }// Erase the hive (Michael's + every agent's memory, inboxes, tasks, board,// git history) and the semantic-memory palace. Only these harness-created@@ -637,6 +666,7 @@ app.whenReady().then(() => {syncMissions(); // arm recurring auto-dispatch missions now the router is livehookServer.start();memory.start(); // init shared palace + mine loop (no-op without mempalace)+ reflector.start(); // bound oversized memory.md files on a timer (no-op until threshold)}createWindow();// Auto-start the Slack webhook server when configured. Best-effort: a tunneldiff --git a/src/main/reflect.ts b/src/main/reflect.tsnew file mode 100644index 00000000..10222336--- /dev/null+++ b/src/main/reflect.ts@@ -0,0 +1,461 @@+/**+ * MemoryReflector — the missing CONDENSE half of the janitor.+ *+ * The janitor flags an oversized `agents/<id>/memory.md` ("Needs condensing.")+ * but never shrinks it. This service finishes that job: on an in-process timer it+ * finds memory files that crossed a size/section threshold and rewrites them into+ * a bounded 3-region shape — pinned durable facts (never touched), one rolling+ * recursive summary, and the newest K verbatim sections — using a cheap headless+ * `claude -p` (Haiku) summarization of the evicted tail.+ *+ * Why in-process (Electron main), NOT launchd: launchd-spawned shells are blocked+ * by macOS TCC from `~/Documents`; only this process has the folder grant. So the+ * loop lives alongside `memory.start()` — never a cron.+ *+ * Safety is layered so a bad LLM pass can NEVER lose data:+ * backup-first (lossless cold copy) → verify-don't-trust gate → atomic swap.+ * If any check fails the original file is left byte-for-byte untouched and the+ * only side effect is a `condense-abort` log line. The miner re-indexes the new+ * file automatically on the next tick because its mtime changed (memory.ts).+ *+ * Runs in the Electron main process.+ */+import { spawn } from 'node:child_process';+import {+ existsSync, statSync, readdirSync, readFileSync, writeFileSync,+ mkdirSync, copyFileSync, renameSync, openSync, fsyncSync, closeSync+} from 'node:fs';+import { join, dirname } from 'node:path';+import { resolveCommand, userShellPath } from './shellEnv';++/** Total memory.md budget — mirrors the janitor's CONTEXT_BUDGET_BYTES (128 KB). */+const BUDGET_BYTES = 131_072;+/** Cheap tail-summarizer (DECIDED by god). The verify gate covers quality. */+const CONDENSE_MODEL = 'claude-haiku-4-5';+/** Hard cap so a wedged headless run can't stall the reflect loop. */+const DEFAULT_TIMEOUT_MS = 180_000;++/** The fixed region headings of the bounded memory shape (the stable contract). */+const PINNED_HEADING = '## 📌 Durable facts (pinned — never condensed)';+const CONDENSED_HEADING = '## 🗜 Condensed history';+const RECENT_HEADING = '## Recent';++/** Instruction prefix — kept byte-identical across calls (no dates/ids spliced+ * in) so Claude Code prompt-caches it; the dynamic content goes in the tail. */+const CONDENSE_SYSTEM = [+ "You are compacting one AI agent's long-term memory file. You will receive:",+ '(A) the current CONDENSED summary, (B) older RECENT sections being evicted,',+ '(C) the PINNED durable-facts block (for context only — do not rewrite it).',+ 'Produce STRICT JSON: {"condensed": "<text>", "hoist": ["<line>", ...]}.',+ 'RULES:',+ '- "condensed" = a single bounded summary of (A)+(B). Re-summarize (A) together',+ ' with (B) so the result does not grow unbounded. Target <= 1500 words. Preserve',+ ' every decision, root cause, protocol, file path, commit SHA, and numeric result.',+ ' Drop routine standup chatter, resolved blockers, and superseded plans.',+ '- "hoist" = any NEW high-importance durable fact found in (B) that belongs in the',+ ' pinned block and is not already in (C). Lines only; may be empty.',+ '- Output ONLY the JSON object. No prose, no code fence.'+].join('\n');++export interface ReflectSettings {+ enabled: boolean;+ /** How often to scan for oversized memory files. */+ intervalMs: number;+ /** Condense when bytes exceed this percent of BUDGET_BYTES. */+ byteTriggerPct: number;+ /** ...OR when `## ` section count exceeds this (AND bytes > minBytes). */+ sectionTrigger: number;+ /** Newest K verbatim `## ` sections always kept untouched. */+ recentKeep: number;+ /** Never condense a file smaller than this — both a "don't waste an LLM call"+ * guard and the byte floor for the section-count trigger. */+ minBytes: number;+}++/** A `## ` section: its heading line and the body text beneath it. */+interface Section { heading: string; body: string }++/** A parsed memory.md split into the three regions. `pinned`/`condensed` are null+ * for legacy (un-structured) files — they're created on first condense. */+interface Parsed {+ header: string; // the `# Memory …` H1 + any preamble before the first `##`+ pinned: string | null; // body under the pinned heading (no heading line)+ condensed: string | null; // body under the condensed heading+ recent: Section[]; // every other `## ` section, in file order (oldest→newest)+}++/** Outcome of one agent's reflect attempt — surfaced to the manual IPC + tests. */+export interface ReflectResult {+ id: string;+ condensed: boolean; // did we actually rewrite the file?+ reason: string; // why (skipped/aborted/done), for logging + UI+ oldBytes?: number;+ newBytes?: number;+}++export class MemoryReflector {+ private timer: NodeJS.Timeout | null = null;+ private started = false;+ /** True while a reflectNow() pass is in flight — serializes the loop (a slow+ * LLM pass must not overlap the next interval tick), mirroring MemoryManager. */+ private reflecting = false;++ /**+ * @param getHome Lazily resolve harnessHome so reflection follows config.+ * @param getCommand The base `claude` command (only its binary name is used).+ * @param getMemoryEnv Extra env (the shared MemPalace path) merged into the call.+ * @param getSettings Reflect tunables (interval + thresholds), read each tick.+ * @param appendLog Sink for `condense`/`condense-abort` events (hive log.jsonl).+ */+ constructor(+ private getHome: () => string | null,+ private getCommand: () => string,+ private getMemoryEnv: () => Record<string, string>,+ private getSettings: () => ReflectSettings,+ private appendLog: (event: Record<string, unknown>) => void+ ) {}++ // — lifecycle (mirrors MemoryManager) —++ start(): void {+ if (this.started) return;+ if (!this.getSettings().enabled) return;+ if (!this.getHome()) return;+ this.started = true;+ // First scan one interval out, not on boot, so launch isn't competing with an+ // LLM call (and a freshly-restored home isn't condensed before it's mined).+ const ms = Math.max(60_000, this.getSettings().intervalMs);+ this.timer = setInterval(() => { void this.reflectNow(); }, ms);+ }++ stop(): void {+ if (this.timer) { clearInterval(this.timer); this.timer = null; }+ this.started = false;+ }++ // — scan —++ /** Reflect every agent whose memory crossed a threshold (or just `onlyId`),+ * one at a time. Serialized via `reflecting` so a slow pass can't overlap the+ * next tick. Returns the per-agent outcomes (used by the manual IPC + tests). */+ async reflectNow(onlyId?: string): Promise<ReflectResult[]> {+ const home = this.getHome();+ if (!home) return [];+ if (this.reflecting) return [];+ const agentsDir = join(home, 'hive', 'agents');+ if (!existsSync(agentsDir)) return [];+ const settings = this.getSettings();+ let ids: string[];+ try { ids = readdirSync(agentsDir); } catch { return []; }+ if (onlyId) ids = ids.filter((id) => id === onlyId);++ this.reflecting = true;+ const results: ReflectResult[] = [];+ try {+ for (const id of ids) {+ const mem = join(agentsDir, id, 'memory.md');+ if (!existsSync(mem)) continue;+ let bytes = 0;+ let text = '';+ try {+ bytes = statSync(mem).size;+ // A manual single-agent call condenses on demand (skips the trigger);+ // the autonomous loop honors the threshold.+ if (!onlyId && !this.shouldCondense(bytes, mem, settings)) continue;+ text = readFileSync(mem, 'utf8');+ } catch { continue; }+ results.push(await this.condense(home, id, mem, text, settings));+ }+ } finally {+ this.reflecting = false;+ }+ return results;+ }++ /** The dual trigger (DECIDED): bytes > pct% of budget, OR many-section sprawl+ * above the byte floor. The floor doubles as the "never burn an LLM call on a+ * tiny file" guard, so it gates BOTH paths. */+ private shouldCondense(bytes: number, mem: string, s: ReflectSettings): boolean {+ if (bytes < s.minBytes) return false;+ if (bytes > (BUDGET_BYTES * s.byteTriggerPct) / 100) return true;+ let sections = 0;+ try { sections = countSections(readFileSync(mem, 'utf8')); } catch { return false; }+ return sections > s.sectionTrigger;+ }++ // — condense one file —++ private async condense(+ home: string, id: string, mem: string, text: string, s: ReflectSettings+ ): Promise<ReflectResult> {+ const oldBytes = Buffer.byteLength(text, 'utf8');+ const parsed = parseMemory(text);+ // Split recent into KEEP (newest K, verbatim) and EVICT (older — summarized).+ const keepCount = Math.max(1, s.recentKeep);+ const keep = parsed.recent.slice(-keepCount);+ const evict = parsed.recent.slice(0, Math.max(0, parsed.recent.length - keepCount));+ if (evict.length === 0) {+ return { id, condensed: false, reason: 'nothing-to-evict', oldBytes };+ }++ // 1) BACK UP first — a lossless cold copy makes every later step recoverable.+ const stamp = utcStamp();+ const backup = join(home, 'hive', 'backups', stamp, id, 'memory.md');+ try {+ mkdirSync(dirname(backup), { recursive: true });+ copyFileSync(mem, backup);+ } catch (e) {+ this.logAbort(id, 'backup-failed', String(e));+ return { id, condensed: false, reason: 'backup-failed', oldBytes };+ }++ // 2) SUMMARIZE the (condensed + evicted) tail via headless Haiku.+ let summary: { condensed: string; hoist: string[] };+ try {+ summary = await this.summarize(home, parsed.condensed, evict, parsed.pinned);+ } catch (e) {+ this.logAbort(id, 'summarize-failed', String(e));+ return { id, condensed: false, reason: 'summarize-failed', oldBytes };+ }++ // 3) REBUILD into the 3-region shape.+ const oldPinnedLines = pinnedLines(parsed.pinned);+ const mergedPinned = mergePinned(oldPinnedLines, summary.hoist);+ const rebuilt = rebuild(parsed.header, mergedPinned, summary.condensed, keep);+ const newBytes = Buffer.byteLength(rebuilt, 'utf8');++ // 4) VERIFY-DON'T-TRUST — reject the rewrite unless every check holds.+ const verdict = verify({+ rebuilt, newBytes, oldBytes, oldPinnedLines, mergedPinned,+ condensed: summary.condensed, keep+ });+ if (!verdict.ok) {+ this.logAbort(id, verdict.reason, undefined, { oldBytes, newBytes });+ return { id, condensed: false, reason: verdict.reason, oldBytes, newBytes };+ }++ // 5) ATOMIC SWAP — write a temp sibling, fsync, rename over the original.+ try {+ atomicWrite(mem, rebuilt);+ } catch (e) {+ this.logAbort(id, 'swap-failed', String(e), { oldBytes, newBytes });+ return { id, condensed: false, reason: 'swap-failed', oldBytes, newBytes };+ }++ try {+ this.appendLog({+ kind: 'condense', agentId: id, oldBytes, newBytes,+ evicted: evict.length, kept: keep.length, hoisted: summary.hoist.length, backup+ });+ } catch { /* logging is best-effort */ }+ // The miner re-indexes within its next cycle — mtime changed, no extra wiring.+ return { id, condensed: true, reason: 'condensed', oldBytes, newBytes };+ }++ private logAbort(id: string, reason: string, detail?: string, extra?: Record<string, unknown>): void {+ try { this.appendLog({ kind: 'condense-abort', agentId: id, reason, ...(detail ? { detail } : {}), ...extra }); }+ catch { /* best-effort */ }+ }++ // — the headless LLM call (the only non-deterministic step) —++ private summarize(+ home: string, condensed: string | null, evict: Section[], pinned: string | null+ ): Promise<{ condensed: string; hoist: string[] }> {+ return new Promise((resolve, reject) => {+ const binary = (this.getCommand() || 'claude').trim().split(/\s+/)[0] || 'claude';+ const exe = resolveCommand(binary);+ const evictText = evict.map((s) => `${s.heading}\n${s.body}`).join('\n\n').trim();+ const prompt = [+ CONDENSE_SYSTEM,+ '',+ '--- INPUT ---',+ '(A) CURRENT CONDENSED SUMMARY:',+ condensed?.trim() || '(none yet)',+ '',+ '(B) OLDER SECTIONS BEING EVICTED:',+ evictText || '(none)',+ '',+ '(C) PINNED DURABLE FACTS (context only — do not rewrite):',+ pinned?.trim() || '(none)'+ ].join('\n');++ const args = [+ '-p', prompt,+ '--model', CONDENSE_MODEL,+ '--output-format', 'json',+ '--permission-mode', 'bypassPermissions',+ // Pure text transform — it must never touch the repo or shell out.+ '--disallowedTools', 'Edit', 'Write', 'NotebookEdit', 'Bash'+ ];++ let child;+ try {+ child = spawn(exe, args, {+ cwd: home,+ env: { ...process.env, PATH: userShellPath(), ...this.getMemoryEnv() } as Record<string, string>,+ stdio: ['ignore', 'pipe', 'pipe']+ });+ } catch (e) { reject(e); return; }++ let stdout = '';+ let stderr = '';+ let settled = false;+ const finish = (fn: () => void): void => { if (settled) return; settled = true; clearTimeout(timer); fn(); };+ const timer = setTimeout(() => {+ try { child.kill('SIGKILL'); } catch { /* noop */ }+ finish(() => reject(new Error('condense timed out')));+ }, DEFAULT_TIMEOUT_MS);++ child.stdout?.on('data', (d) => { stdout += d.toString(); });+ child.stderr?.on('data', (d) => { stderr += d.toString(); });+ child.on('error', (e) => finish(() => reject(e)));+ child.on('close', (code) => finish(() => {+ const parsed = parseSummary(stdout);+ if (parsed) { resolve(parsed); return; }+ reject(new Error(stderr.trim() || `condense exited ${code ?? '?'} with no parseable JSON`));+ }));+ });+ }+}++// ─── pure helpers (the deterministic, unit-testable half) ────────────────────++/** Count level-2 (`## `) headings — `# ` H1 and `### ` deeper headings excluded. */+export function countSections(text: string): number {+ return (text.match(/^##\s/gm) ?? []).length;+}++/** Split a memory.md into header + the three regions. A legacy flat file (no+ * pinned/condensed headings) parses with those null and every `## ` section in+ * `recent`; the structured blocks are created on first condense. */+export function parseMemory(text: string): Parsed {+ const lines = text.split('\n');+ let firstSection = lines.findIndex((l) => /^##\s/.test(l));+ if (firstSection === -1) firstSection = lines.length;+ const header = lines.slice(0, firstSection).join('\n').replace(/\s+$/, '');++ // Carve the remaining lines into `## ` sections (heading + body until next `##`).+ const sections: Section[] = [];+ let cur: Section | null = null;+ for (let i = firstSection; i < lines.length; i++) {+ const line = lines[i];+ if (/^##\s/.test(line)) {+ if (cur) sections.push(cur);+ cur = { heading: line, body: '' };+ } else if (cur) {+ cur.body += (cur.body ? '\n' : '') + line;+ }+ }+ if (cur) sections.push(cur);++ let pinned: string | null = null;+ let condensed: string | null = null;+ const recent: Section[] = [];+ for (const s of sections) {+ const h = s.heading.trim();+ if (h.startsWith('## 📌')) pinned = s.body.replace(/\s+$/, '');+ else if (h.startsWith('## 🗜')) condensed = s.body.replace(/\s+$/, '');+ else if (h === RECENT_HEADING) { /* divider — its siblings ARE the recent list */ }+ else recent.push(s);+ }+ return { header, pinned, condensed, recent };+}++/** Non-empty, trimmed lines of the pinned block (the set we must never lose). */+export function pinnedLines(pinned: string | null): string[] {+ if (!pinned) return [];+ return pinned.split('\n').map((l) => l.trim()).filter(Boolean);+}++/** Append hoisted durable facts to the pinned set, skipping any already present. */+export function mergePinned(oldLines: string[], hoist: string[]): string[] {+ const have = new Set(oldLines);+ const out = [...oldLines];+ for (const raw of hoist) {+ const line = (raw ?? '').trim();+ if (line && !have.has(line)) { have.add(line); out.push(line); }+ }+ return out;+}++/** Reassemble the canonical 3-region file. */+export function rebuild(header: string, pinned: string[], condensed: string, keep: Section[]): string {+ const parts: string[] = [];+ if (header.trim()) parts.push(header.trim());+ parts.push(PINNED_HEADING);+ parts.push(pinned.length ? pinned.join('\n') : '_(none yet)_');+ parts.push(CONDENSED_HEADING);+ parts.push(condensed.trim());+ parts.push(RECENT_HEADING);+ for (const s of keep) parts.push(`${s.heading}\n${s.body}`.replace(/\s+$/, ''));+ return parts.join('\n\n') + '\n';+}++/** The verify-don't-trust gate. The rewrite is rejected — original kept verbatim+ * — unless ALL checks pass. The lossless backup makes a rejection a pure no-op. */+export function verify(args: {+ rebuilt: string; newBytes: number; oldBytes: number;+ oldPinnedLines: string[]; mergedPinned: string[];+ condensed: string; keep: Section[];+}): { ok: true } | { ok: false; reason: string } {+ const { rebuilt, newBytes, oldBytes, oldPinnedLines, mergedPinned, condensed, keep } = args;+ // 6) Valid summary JSON already enforced upstream (parseSummary). Here: structure.+ // 1) Parses back into the 3-region structure.+ const re = parseMemory(rebuilt);+ if (re.pinned === null || re.condensed === null) return { ok: false, reason: 'structure-missing-region' };+ // 4) Non-empty + sane.+ if (newBytes <= 200) return { ok: false, reason: 'too-small' };+ if (!condensed.trim()) return { ok: false, reason: 'empty-condensed' };+ // 3) Actually smaller (a no-op condense is a failure).+ if (!(newBytes < oldBytes * 0.95)) return { ok: false, reason: 'not-smaller' };+ // 2) Pinned preserved: every old pinned line survives (hoist only adds).+ const newPinned = new Set(pinnedLines(re.pinned));+ for (const line of oldPinnedLines) if (!newPinned.has(line)) return { ok: false, reason: 'pinned-line-dropped' };+ for (const line of mergedPinned) if (!newPinned.has(line)) return { ok: false, reason: 'pinned-merge-mismatch' };+ // 5) Recent integrity: the kept newest sections round-trip byte-for-byte.+ if (re.recent.length !== keep.length) return { ok: false, reason: 'recent-count-mismatch' };+ for (let i = 0; i < keep.length; i++) {+ const a = `${keep[i].heading}\n${keep[i].body}`.replace(/\s+$/, '');+ const b = `${re.recent[i].heading}\n${re.recent[i].body}`.replace(/\s+$/, '');+ if (a !== b) return { ok: false, reason: 'recent-section-altered' };+ }+ return { ok: true };+}++/** Pull `{condensed, hoist}` out of `claude -p --output-format json` output.+ * Two layers: the CLI envelope `{result: "<text>"}`, then the model's strict+ * JSON (tolerating an accidental ```json fence). Returns null on any failure. */+export function parseSummary(stdout: string): { condensed: string; hoist: string[] } | null {+ const raw = stdout.trim();+ if (!raw) return null;+ let inner = raw;+ try {+ const env = JSON.parse(raw) as { result?: unknown; text?: unknown };+ if (typeof env.result === 'string') inner = env.result;+ else if (typeof env.text === 'string') inner = env.text;+ } catch { /* not the CLI envelope — treat stdout itself as the model output */ }+ inner = inner.trim().replace(/^```(?:json)?\s*/i, '').replace(/```\s*$/, '').trim();+ try {+ const obj = JSON.parse(inner) as { condensed?: unknown; hoist?: unknown };+ if (typeof obj.condensed !== 'string' || !obj.condensed.trim()) return null;+ const hoist = Array.isArray(obj.hoist) ? obj.hoist.filter((x): x is string => typeof x === 'string') : [];+ return { condensed: obj.condensed, hoist };+ } catch { return null; }+}++/** `20260606T110912Z` — matches the janitor's backup-dir stamp format. */+function utcStamp(): string {+ return new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z');+}++/** Write `text` to `path` atomically: temp sibling → fsync → rename over target. */+function atomicWrite(path: string, text: string): void {+ const tmp = `${path}.tmp-${Math.random().toString(36).slice(2, 10)}`;+ writeFileSync(tmp, text, 'utf8');+ try {+ const fd = openSync(tmp, 'r+');+ try { fsyncSync(fd); } finally { closeSync(fd); }+ } catch { /* fsync best-effort; rename is the durability guarantee */ }+ renameSync(tmp, path);+}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 0323c403..4d62a329 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -241,6 +241,11 @@ const api = {memoryWakeUp: (wing?: string): Promise<{ ok: boolean; output: string; error?: string }> =>ipcRenderer.invoke('hive:memoryWakeUp', wing),mineNow: (): Promise<{ ok: boolean }> => ipcRenderer.invoke('hive:mineNow'),+ /** Condense agent memory.md files (the janitor's missing half). With an id,+ * condense that agent on demand; without, run a full threshold scan. Returns+ * the per-agent outcomes ({ id, condensed, reason, oldBytes?, newBytes? }). */+ reflectNow: (id?: string): Promise<Array<{ id: string; condensed: boolean; reason: string; oldBytes?: number; newBytes?: number }>> =>+ ipcRenderer.invoke('memory:reflectNow', id),hiveSend: (msg: Partial<HiveMessage>, from?: string): Promise<{ ok: boolean; error?: string; message?: HiveMessage }> =>ipcRenderer.invoke('hive:send', msg, from),