import { existsSync, lstatSync, renameSync, unlinkSync } from 'node:fs'; import { join, relative, sep } from 'node:path'; import { SynomemError } from './errors.js'; import { assertNoSymlinkEscape, atomicWriteDerivedFile, atomicWriteFile, ensureDirectory, } from './fs-utils.js'; import type { SynomemStorage } from './storage.js'; import type { ProjectionWriter } from './ports/projections.js'; import type { AgentProfile, EvidenceReference, SynomemEvent, KudosRecord, MemoRecord, NoteRecord, PostRecord, TaskDue, TaskRecord, TodoRecord, } from './types.js'; /** * The instant a deadline has passed. * * A date-only deadline does not invent a time of day; it lapses at the end of * that UTC day, which is the latest reading that cannot call work late while * the stated day is still running. Every projection must use this one rule, or * two stores would disagree about what is overdue. */ export function dueInstant(due: TaskDue | undefined): string | undefined { if (!due) return undefined; return due.kind === 'date' ? `${due.date}T23:59:59.999Z` : due.datetime; } const generatedMarker = ''; function manifestPath(home: string, path: string): string { return relative(home, path).split(sep).join('/'); } export function escapeMarkdown(value: string): string { return value .replaceAll('&', '&') .replaceAll('<', '<') .replaceAll('>', '>') .replace(/([\\`*_{}[\]()#+!|])/g, '\\$1') .replace(/^(\s*)(-|\d+\.)\s/gm, '$1\\$2 '); } function evidenceLine(evidence: EvidenceReference): string { const kind = evidence.kind.replace('-', ' '); const label = evidence.label ? `${escapeMarkdown(evidence.label)} — ` : ''; return `- **${escapeMarkdown(kind[0]?.toUpperCase() + kind.slice(1))}:** ${label}${escapeMarkdown(evidence.value)}`; } function recordMarkdown(record: KudosRecord, includeTitle = true): string { const event = record.event; const lines = [ ...(includeTitle ? [`### ${escapeMarkdown(event.title)}`, ''] : []), `**Received:** ${event.createdAt.slice(0, 10)} `, `**From:** ${escapeMarkdown(event.actor.displayName ?? event.actor.id)} `, `**Status:** ${record.status === 'acknowledged' ? 'Acknowledged' : 'Unacknowledged'} `, ]; if (event.tags?.length) lines.push(`**Tags:** ${event.tags.map(escapeMarkdown).join(', ')} `); lines.push('', escapeMarkdown(event.reason), ''); if (event.evidence?.length) { lines.push('**Evidence**', '', ...event.evidence.map(evidenceLine), ''); } if (record.acknowledgment?.note) { lines.push(`**Acknowledgment note:** ${escapeMarkdown(record.acknowledgment.note)}`, ''); } lines.push(`**Kudos ID:** \`${event.id}\``, ''); return lines.join('\n'); } function winsMarkdown(profile: AgentProfile, records: KudosRecord[], rebuiltAt: string): string { const active = records.filter((record) => !record.revocation); const lines = [ generatedMarker, '', `# Wins — ${escapeMarkdown(profile.displayName)}`, '', `_Last rebuilt: ${rebuiltAt}_`, '', ]; if (active.length === 0) { lines.push('_No kudos yet. Excellent work remains entirely possible._', ''); return `${lines.join('\n')}\n`; } let year = ''; for (const record of active) { const nextYear = record.event.createdAt.slice(0, 4); if (nextYear !== year) { year = nextYear; lines.push(`## ${year}`, ''); } lines.push(recordMarkdown(record)); } return `${lines.join('\n')}\n`; } function inboxMarkdown(record: KudosRecord): string { return `${[ generatedMarker, '', `# ${escapeMarkdown(record.event.title)}`, '', recordMarkdown(record, false), ].join('\n')}\n`; } function memoInboxMarkdown(record: MemoRecord): string { return `${[ generatedMarker, '', `# ${escapeMarkdown(record.event.subject)}`, '', `**From:** ${escapeMarkdown(record.event.actor.displayName ?? record.event.actor.id)} `, `**Sent:** ${record.event.createdAt} `, `**Memo ID:** \`${record.event.id}\``, '', escapeMarkdown(record.event.body), '', ].join('\n')}\n`; } function taskInboxMarkdown(record: TaskRecord): string { const due = record.current.due?.kind === 'date' ? record.current.due.date : record.current.due ? `${record.current.due.datetime} (${record.current.due.timeZone})` : 'None'; return `${[ generatedMarker, '', `# ${escapeMarkdown(record.current.title)}`, '', `**Status:** ${record.status} `, `**Priority:** ${record.current.priority} `, `**Due:** ${escapeMarkdown(due)} `, `**Task ID:** \`${record.event.id}\``, '', ...(record.current.description ? [escapeMarkdown(record.current.description), ''] : []), ].join('\n')}\n`; } function memoryMarkdown(profile: AgentProfile, records: NoteRecord[], rebuiltAt: string): string { const active = records.filter((record) => record.status === 'active'); const lines = [ generatedMarker, '', `# Memory — ${escapeMarkdown(profile.displayName)}`, '', `_Last rebuilt: ${rebuiltAt}_`, '', ]; if (!active.length) lines.push('_No canonical notes yet._', ''); for (const record of active) { lines.push( `## ${escapeMarkdown(record.current.title)}`, '', escapeMarkdown(record.current.body), '', `**Version:** ${record.current.version} `, `**Note ID:** \`${record.event.id}\``, '', ); } return `${lines.join('\n')}\n`; } function tasksMarkdown(profile: AgentProfile, records: TaskRecord[], rebuiltAt: string): string { const lines = [ generatedMarker, '', `# Tasks — ${escapeMarkdown(profile.displayName)}`, '', `_Last rebuilt: ${rebuiltAt}_`, '', ]; if (!records.length) lines.push('_No tasks yet._', ''); for (const record of records) { const due = record.current.due?.kind === 'date' ? record.current.due.date : record.current.due ? `${record.current.due.datetime} (${record.current.due.timeZone})` : 'None'; lines.push( `## ${escapeMarkdown(record.current.title)}`, '', `**Status:** ${record.status} `, `**Priority:** ${record.current.priority} `, `**Due:** ${escapeMarkdown(due)} `, `**Task ID:** \`${record.event.id}\``, '', ); } return `${lines.join('\n')}\n`; } export function recordsFromEvents(events: SynomemEvent[]): KudosRecord[] { const acknowledgments = new Map(); const revocations = new Map(); for (const event of events) { if (event.type === 'kudos.acknowledged' && !acknowledgments.has(event.kudosId)) { acknowledgments.set(event.kudosId, event); } if (event.type === 'kudos.revoked' && !revocations.has(event.kudosId)) { revocations.set(event.kudosId, event); } } return events .filter((event) => event.type === 'kudos.given') .map((event) => { const acknowledgment = acknowledgments.get(event.id); const revocation = revocations.get(event.id); return { event, ...(acknowledgment ? { acknowledgment } : {}), ...(revocation ? { revocation } : {}), status: acknowledgment ? 'acknowledged' : 'unacknowledged', revocationStatus: revocation ? 'revoked' : 'active', } satisfies KudosRecord; }) .sort( (a, b) => b.event.createdAt.localeCompare(a.event.createdAt) || b.event.id.localeCompare(a.event.id), ); } export function memoRecordsFromEvents(events: SynomemEvent[]): MemoRecord[] { const records = new Map(); for (const event of events) { if (event.type === 'memo.sent') { records.set(event.id, { event, status: 'unread' }); } else if (event.type === 'memo.read') { const record = records.get(event.memoId); if (record) { record.read = event; if (!record.archived) record.status = 'read'; } } else if (event.type === 'memo.archived') { const record = records.get(event.memoId); if (record) { record.archived = event; record.status = 'archived'; } } } return [...records.values()].sort((a, b) => b.event.createdAt.localeCompare(a.event.createdAt)); } /** * Rebuilds posts from their events, acknowledgements included. * * Edits are kept as a list rather than collapsed into the current text. A reader * has to be able to see that a post changed after somebody acknowledged it — * silently rewriting what was acknowledged is how a record becomes a lie. */ export function postRecordsFromEvents(events: SynomemEvent[]): PostRecord[] { const records = new Map(); for (const event of events) { if (event.type === 'post.created') { records.set(event.id, { event, edits: [], mentions: event.mentions ?? [], acknowledgments: [], status: 'active', title: event.title, body: event.body, ...(event.tags ? { tags: event.tags } : {}), topicIds: event.topicIds ?? [], // The text version, counting only changes to the text. // // Deliberately not the aggregate version, which also counts every // acknowledgement. If they were the same number, somebody // acknowledging a post would invalidate an edit the author was in the // middle of making — a conflict with nothing to reconcile. version: 1, }); } else if (event.type === 'post.edited') { const record = records.get(event.postId); if (record) { record.edits.push(event); record.mentions = event.mentions ?? []; record.title = event.title; record.body = event.body; if (event.tags) record.tags = event.tags; // An edit carries the complete topic list (an empty one clears them); edits // written before posts had topics carry none and leave them as they were. if (event.topicIds) record.topicIds = event.topicIds; record.version += 1; } } else if (event.type === 'post.archived') { const record = records.get(event.postId); if (record) { record.archived = event; record.status = 'archived'; } } else if (event.type === 'post.acknowledged') { const record = records.get(event.postId); if (record) { // One statement per actor: a repeat replaces rather than accumulates. const existing = record.acknowledgments.findIndex( (entry) => entry.actor.id === event.actor.id && entry.actor.kind === event.actor.kind, ); const entry = { actor: event.actor, acknowledgedAt: event.createdAt, ...(event.note ? { note: event.note } : {}), }; if (existing >= 0) record.acknowledgments[existing] = entry; else record.acknowledgments.push(entry); } } else if (event.type === 'post.acknowledgment.withdrawn') { const record = records.get(event.postId); if (record) { record.acknowledgments = record.acknowledgments.filter( (entry) => !(entry.actor.id === event.actor.id && entry.actor.kind === event.actor.kind), ); } } } return [...records.values()]; } export function noteRecordsFromEvents(events: SynomemEvent[]): NoteRecord[] { const records = new Map(); for (const event of events) { if (event.type === 'note.created') { records.set(event.id, { event, current: { title: event.title, body: event.body, tags: event.tags ?? [], topicIds: event.topicIds ?? [], visibility: event.visibility, version: event.aggregateVersion, }, status: 'active', }); } else if (event.type === 'note.revised') { const record = records.get(event.noteId); if (record) { record.revision = event; record.current = { title: event.title, body: event.body, tags: event.tags ?? [], topicIds: event.topicIds ?? [], visibility: event.visibility, version: event.aggregateVersion, }; } } else if (event.type === 'note.archived') { const record = records.get(event.noteId); if (record) { record.archived = event; record.current.version = event.aggregateVersion; record.status = 'archived'; } } } return [...records.values()].sort((a, b) => b.event.createdAt.localeCompare(a.event.createdAt)); } /** * Builds private Todo records. * * Deliberately simpler than the Task reducer: there is no acceptance state and * no response history, because there is nobody to negotiate with. A Todo goes * open → completed / canceled / archived, and back to open on reopen. */ export function todoRecordsFromEvents(events: SynomemEvent[]): TodoRecord[] { const records = new Map(); for (const event of events) { if (event.type === 'todo.created') { records.set(event.id, { event, current: { title: event.title, ...(event.details !== undefined ? { details: event.details } : {}), priority: event.priority, ...(event.due ? { due: event.due } : {}), tags: event.tags ?? [], topicIds: event.topicIds ?? [], version: event.aggregateVersion, }, status: 'open', }); } else if (event.type === 'todo.updated') { const record = records.get(event.todoId); if (record) { record.update = event; record.current = { title: event.title, ...(event.details !== undefined ? { details: event.details } : {}), priority: event.priority, ...(event.due ? { due: event.due } : {}), tags: event.tags ?? [], topicIds: event.topicIds ?? [], version: event.aggregateVersion, }; } } else if (event.type === 'todo.reopened') { const record = records.get(event.todoId); if (record) { record.reopened = event; record.current.version = event.aggregateVersion; record.status = 'open'; delete record.terminal; } } else if ( event.type === 'todo.completed' || event.type === 'todo.canceled' || event.type === 'todo.archived' ) { const record = records.get(event.todoId); if (record) { record.terminal = event; record.current.version = event.aggregateVersion; record.status = event.type === 'todo.completed' ? 'completed' : event.type === 'todo.canceled' ? 'canceled' : 'archived'; } } } return [...records.values()]; } export function taskRecordsFromEvents(events: SynomemEvent[]): TaskRecord[] { const records = new Map(); for (const event of events) { if (event.type === 'task.created') { records.set(event.id, { event, current: { title: event.title, ...(event.description !== undefined ? { description: event.description } : {}), priority: event.priority, ...(event.due ? { due: event.due } : {}), tags: event.tags ?? [], topicIds: event.topicIds ?? [], visibility: event.visibility, version: event.aggregateVersion, }, status: event.requiresAcceptance ? 'assigned' : 'open', responses: [], }); } else if (event.type === 'task.updated') { const record = records.get(event.taskId); if (record) { record.update = event; record.current = { title: event.title, ...(event.description !== undefined ? { description: event.description } : {}), priority: event.priority, ...(event.due ? { due: event.due } : {}), tags: event.tags ?? [], topicIds: event.topicIds ?? [], visibility: event.visibility, version: event.aggregateVersion, }; } } else if (event.type === 'task.decision_overridden') { const record = records.get(event.taskId); if (record) { record.status = event.nextStatus; record.current.version = event.aggregateVersion; record.overrides = [...(record.overrides ?? []), event]; delete record.terminal; } } else if (event.type === 'task.accepted') { const record = records.get(event.taskId); if (record) { record.current.version = event.aggregateVersion; record.status = 'open'; record.responses.push({ kind: 'accepted', ...(event.response !== undefined ? { response: event.response } : {}), actor: event.actor, at: event.createdAt, }); } } else if ( event.type === 'task.completed' || event.type === 'task.rejected' || event.type === 'task.canceled' ) { const record = records.get(event.taskId); if (record) { record.terminal = event; record.current.version = event.aggregateVersion; if (event.type === 'task.rejected') { record.responses.push({ kind: 'rejected', response: event.response, actor: event.actor, at: event.createdAt, }); } record.status = event.type === 'task.completed' ? 'completed' : event.type === 'task.rejected' ? 'rejected' : 'canceled'; } } else if (event.type === 'task.reopened') { const record = records.get(event.taskId); if (record) { record.reopened = event; record.current.version = event.aggregateVersion; record.status = 'open'; } } } return [...records.values()].sort((a, b) => b.event.createdAt.localeCompare(a.event.createdAt)); } /** Render a portable human-readable export without reading generated projections. */ export function renderMarkdownExport(events: SynomemEvent[]): string { const sections = [ ...recordsFromEvents(events).map( (record) => `## Kudos: ${escapeMarkdown(record.event.title)}\n\n${escapeMarkdown(record.event.reason)}\n\nStatus: ${record.revocationStatus === 'revoked' ? 'Revoked' : record.status}\n\nID: \`${record.event.id}\``, ), ...memoRecordsFromEvents(events).map( (record) => `## Memo: ${escapeMarkdown(record.event.subject)}\n\n${escapeMarkdown(record.event.body)}\n\nStatus: ${record.status}\n\nID: \`${record.event.id}\``, ), ...noteRecordsFromEvents(events).map( (record) => `## Note: ${escapeMarkdown(record.current.title)}\n\n${escapeMarkdown(record.current.body)}\n\nStatus: ${record.status}; version ${record.current.version}\n\nID: \`${record.event.id}\``, ), ...taskRecordsFromEvents(events).map( (record) => `## Task: ${escapeMarkdown(record.current.title)}\n\n${record.current.description ? `${escapeMarkdown(record.current.description)}\n\n` : ''}Status: ${record.status}; priority ${record.current.priority}\n\nID: \`${record.event.id}\``, ), ]; return `${sections.join('\n\n')}\n`; } export class ProjectionManager implements ProjectionWriter { constructor(private readonly storage: SynomemStorage) {} rebuild(): { generated: string[]; removed: string[]; } { this.storage.assertWritable(); const events = this.storage.getEvents(); this.storage.transactionSync(() => { this.storage.rebuildKudosCurrentIndex(); this.storage.rebuildItemsCurrentIndex(); this.storage.rebuildParticipationCurrentIndex(); }); const profiles = this.storage.listAgents(); const records = recordsFromEvents(events); const memos = memoRecordsFromEvents(events); const notes = noteRecordsFromEvents(events); const tasks = taskRecordsFromEvents(events); const rebuiltAt = events.at(-1)?.createdAt ?? new Date(0).toISOString(); const generated: string[] = []; for (const profile of profiles) { const agentDirectory = join(this.storage.home, profile.handle); assertNoSymlinkEscape(this.storage.home, agentDirectory); ensureDirectory(agentDirectory); const profilePath = join(agentDirectory, 'profile.json'); const winsPath = join(agentDirectory, 'WINS.md'); const notesPath = join(agentDirectory, 'NOTES.md'); const inboxDirectory = join(agentDirectory, 'inbox'); const kudosInboxDirectory = join(inboxDirectory, 'kudos'); const memoInboxDirectory = join(inboxDirectory, 'memos'); const taskInboxDirectory = join(inboxDirectory, 'tasks'); assertNoSymlinkEscape(this.storage.home, inboxDirectory); ensureDirectory(inboxDirectory); ensureDirectory(kudosInboxDirectory); ensureDirectory(memoInboxDirectory); ensureDirectory(taskInboxDirectory); atomicWriteDerivedFile( profilePath, `${JSON.stringify({ _generatedBy: 'synomem', ...profile }, null, 2)}\n`, ); generated.push(manifestPath(this.storage.home, profilePath)); if (!existsSync(notesPath)) { atomicWriteFile( notesPath, `# Notes — ${profile.displayName}\n\n\n`, ); } const agentRecords = records.filter( (record) => record.event.recipient?.kind === 'agent' && record.event.recipient.id === profile.id, ); if (this.storage.config.projection.writeWinsMarkdown) { atomicWriteDerivedFile(winsPath, winsMarkdown(profile, agentRecords, rebuiltAt)); generated.push(manifestPath(this.storage.home, winsPath)); } const agentNotes = notes.filter( (record) => record.event.owner?.kind === 'agent' && record.event.owner.id === profile.id, ); if (this.storage.config.projection.writeMemoryMarkdown) { const memoryPath = join(agentDirectory, 'MEMORY.md'); atomicWriteDerivedFile(memoryPath, memoryMarkdown(profile, agentNotes, rebuiltAt)); generated.push(manifestPath(this.storage.home, memoryPath)); } const agentTasks = tasks.filter( (record) => record.event.assignee?.kind === 'agent' && record.event.assignee.id === profile.id, ); if (this.storage.config.projection.writeTasksMarkdown) { const tasksPath = join(agentDirectory, 'TASKS.md'); atomicWriteDerivedFile(tasksPath, tasksMarkdown(profile, agentTasks, rebuiltAt)); generated.push(manifestPath(this.storage.home, tasksPath)); } if (this.storage.config.projection.writeInboxEntries) { for (const record of agentRecords.filter( (item) => item.status === 'unacknowledged' && item.revocationStatus === 'active', )) { const inboxPath = join(kudosInboxDirectory, `${record.event.id}.md`); atomicWriteDerivedFile(inboxPath, inboxMarkdown(record)); generated.push(manifestPath(this.storage.home, inboxPath)); } for (const record of memos.filter( (item) => item.event.recipient?.kind === 'agent' && item.event.recipient.id === profile.id && item.status === 'unread', )) { const inboxPath = join(memoInboxDirectory, `${record.event.id}.md`); atomicWriteDerivedFile(inboxPath, memoInboxMarkdown(record)); generated.push(manifestPath(this.storage.home, inboxPath)); } for (const record of agentTasks.filter( (item) => item.status === 'open' || item.status === 'assigned', )) { const inboxPath = join(taskInboxDirectory, `${record.event.id}.md`); atomicWriteDerivedFile(inboxPath, taskInboxMarkdown(record)); generated.push(manifestPath(this.storage.home, inboxPath)); } } } const keep = new Set(generated); const removed: string[] = []; for (const stale of this.storage.projectionManifest()) { if (keep.has(stale)) continue; const path = join(this.storage.home, stale); assertNoSymlinkEscape(this.storage.home, path); if (!existsSync(path)) continue; const stat = lstatSync(path); if (!stat.isFile() || stat.isSymbolicLink()) { throw new SynomemError('UNSAFE_PATH', `Refusing to remove unsafe generated path: ${stale}`); } unlinkSync(path); removed.push(stale); } this.storage.replaceProjectionManifest(generated, rebuiltAt); return { generated: generated.sort(), removed: removed.sort() }; } /** * Move an agent's directory when its handle changes. * * Without this a rename left the old directory behind, and with it `NOTES.md` * -- the one file in there that is the reader's rather than Synomem's, and so * the one file a rebuild will never delete. The generated files moved to the * new handle and the hand-written notes stayed at the old one. * * Moving rather than copy-and-delete, and moving rather than letting the * rebuild sort it out, because a rename is a known identity change: the * destination is new, so nothing is overwritten, and the human file arrives * intact instead of being stranded. */ renameAgentDirectory(previousHandle: string, nextHandle: string): void { if (previousHandle === nextHandle) return; this.storage.assertWritable(); const from = join(this.storage.home, previousHandle); const to = join(this.storage.home, nextHandle); assertNoSymlinkEscape(this.storage.home, from); assertNoSymlinkEscape(this.storage.home, to); if (!existsSync(from)) return; // A directory already at the destination means the handle is in use, which // the caller checks before reaching here. Refuse rather than merge. if (existsSync(to)) { throw new SynomemError( 'UNSAFE_PATH', `Refusing to rename over an existing directory: ${nextHandle}`, ); } const stat = lstatSync(from); if (!stat.isDirectory() || stat.isSymbolicLink()) { throw new SynomemError('UNSAFE_PATH', `Agent directory is not a plain directory: ${from}`); } renameSync(from, to); this.storage.renameProjectionManifestPrefix(previousHandle, nextHandle); } syncAgent(agentId: string): { generated: string[]; removed: string[]; } { this.storage.assertWritable(); const profile = this.storage.getAgent(agentId); if (!profile) throw new SynomemError('AGENT_NOT_FOUND', `Unknown agent: ${agentId}`); const events = this.storage.getEvents(); const records = recordsFromEvents(events).filter( (record) => record.event.recipient?.kind === 'agent' && record.event.recipient.id === profile.id, ); const memos = memoRecordsFromEvents(events).filter( (record) => record.event.recipient?.kind === 'agent' && record.event.recipient.id === profile.id, ); const notes = noteRecordsFromEvents(events).filter( (record) => record.event.owner?.kind === 'agent' && record.event.owner.id === profile.id, ); const tasks = taskRecordsFromEvents(events).filter( (record) => record.event.assignee?.kind === 'agent' && record.event.assignee.id === profile.id, ); const rebuiltAt = events.at(-1)?.createdAt ?? new Date(0).toISOString(); const agentDirectory = join(this.storage.home, profile.handle); const inboxDirectory = join(agentDirectory, 'inbox'); const kudosInboxDirectory = join(inboxDirectory, 'kudos'); const memoInboxDirectory = join(inboxDirectory, 'memos'); const taskInboxDirectory = join(inboxDirectory, 'tasks'); assertNoSymlinkEscape(this.storage.home, agentDirectory); assertNoSymlinkEscape(this.storage.home, inboxDirectory); ensureDirectory(agentDirectory); ensureDirectory(inboxDirectory); ensureDirectory(kudosInboxDirectory); ensureDirectory(memoInboxDirectory); ensureDirectory(taskInboxDirectory); const generated: string[] = []; const profilePath = join(agentDirectory, 'profile.json'); atomicWriteDerivedFile( profilePath, `${JSON.stringify({ _generatedBy: 'synomem', ...profile }, null, 2)}\n`, ); generated.push(manifestPath(this.storage.home, profilePath)); const notesPath = join(agentDirectory, 'NOTES.md'); if (!existsSync(notesPath)) { atomicWriteFile( notesPath, `# Notes — ${profile.displayName}\n\n\n`, ); } if (this.storage.config.projection.writeWinsMarkdown) { const winsPath = join(agentDirectory, 'WINS.md'); atomicWriteDerivedFile(winsPath, winsMarkdown(profile, records, rebuiltAt)); generated.push(manifestPath(this.storage.home, winsPath)); } if (this.storage.config.projection.writeMemoryMarkdown) { const memoryPath = join(agentDirectory, 'MEMORY.md'); atomicWriteDerivedFile(memoryPath, memoryMarkdown(profile, notes, rebuiltAt)); generated.push(manifestPath(this.storage.home, memoryPath)); } if (this.storage.config.projection.writeTasksMarkdown) { const tasksPath = join(agentDirectory, 'TASKS.md'); atomicWriteDerivedFile(tasksPath, tasksMarkdown(profile, tasks, rebuiltAt)); generated.push(manifestPath(this.storage.home, tasksPath)); } if (this.storage.config.projection.writeInboxEntries) { for (const record of records.filter( (item) => item.status === 'unacknowledged' && item.revocationStatus === 'active', )) { const inboxPath = join(kudosInboxDirectory, `${record.event.id}.md`); const relativePath = manifestPath(this.storage.home, inboxPath); if (!existsSync(inboxPath)) atomicWriteDerivedFile(inboxPath, inboxMarkdown(record)); generated.push(relativePath); } for (const record of memos.filter((item) => item.status === 'unread')) { const inboxPath = join(memoInboxDirectory, `${record.event.id}.md`); const relativePath = manifestPath(this.storage.home, inboxPath); if (!existsSync(inboxPath)) atomicWriteDerivedFile(inboxPath, memoInboxMarkdown(record)); generated.push(relativePath); } for (const record of tasks.filter( (item) => item.status === 'open' || item.status === 'assigned', )) { const inboxPath = join(taskInboxDirectory, `${record.event.id}.md`); const relativePath = manifestPath(this.storage.home, inboxPath); if (!existsSync(inboxPath)) atomicWriteDerivedFile(inboxPath, taskInboxMarkdown(record)); generated.push(relativePath); } } const keep = new Set(generated); const prefixes = [`${profile.handle}/`, `${profile.handle}\\`]; const removed: string[] = []; for (const stale of this.storage .projectionManifest() .filter((path) => prefixes.some((prefix) => path.startsWith(prefix)))) { if (keep.has(stale)) continue; const path = join(this.storage.home, stale); assertNoSymlinkEscape(this.storage.home, path); if (!existsSync(path)) continue; const stat = lstatSync(path); if (!stat.isFile() || stat.isSymbolicLink()) { throw new SynomemError('UNSAFE_PATH', `Refusing to remove unsafe generated path: ${stale}`); } unlinkSync(path); removed.push(stale); } this.storage.replaceAgentProjectionManifest(profile.handle, generated, rebuiltAt); return { generated: generated.sort(), removed: removed.sort() }; } /* * The paths a rebuild would produce, for comparison against the manifest. * * Directories are named by HANDLE, matching what the writers above create, * while the record filters match on the canonical agent ID, which is what * stored events carry. Mixing the two up makes the comparison never agree, * and `doctor` then reports every workspace's projections as stale forever. */ expectedPaths(): string[] { const profiles = this.storage.listAgents(); const events = this.storage.getReadableEvents(); const records = recordsFromEvents(events); const memos = memoRecordsFromEvents(events); const tasks = taskRecordsFromEvents(events); const paths: string[] = []; for (const profile of profiles) { paths.push(`${profile.handle}/profile.json`); if (this.storage.config.projection.writeWinsMarkdown) paths.push(`${profile.handle}/WINS.md`); if (this.storage.config.projection.writeMemoryMarkdown) paths.push(`${profile.handle}/MEMORY.md`); if (this.storage.config.projection.writeTasksMarkdown) paths.push(`${profile.handle}/TASKS.md`); if (this.storage.config.projection.writeInboxEntries) { for (const record of records.filter( (item) => item.event.recipient?.kind === 'agent' && item.event.recipient.id === profile.id && item.status === 'unacknowledged' && item.revocationStatus === 'active', )) { paths.push(`${profile.handle}/inbox/kudos/${record.event.id}.md`); } for (const record of memos.filter( (item) => item.event.recipient?.kind === 'agent' && item.event.recipient.id === profile.id && item.status === 'unread', )) { paths.push(`${profile.handle}/inbox/memos/${record.event.id}.md`); } for (const record of tasks.filter( (item) => item.event.assignee?.kind === 'agent' && item.event.assignee.id === profile.id && (item.status === 'open' || item.status === 'assigned'), )) { paths.push(`${profile.handle}/inbox/tasks/${record.event.id}.md`); } } } return paths.sort(); } }