feat(config): implement ConfigManager with atomic writes, chokidar hot-reload, isolated fallback, presets, and revisions

This commit is contained in:
tyuXX 2026-11-26 18:23:21 +00:00
parent 05abda3417
commit 6520b81d82
3 changed files with 1335 additions and 0 deletions

View file

@ -0,0 +1,906 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import type Database from 'better-sqlite3';
import chokidar, { type FSWatcher } from 'chokidar';
import type { ZodError, ZodSchema } from 'zod';
import {
AlertsFileSchema,
ServerConfigSchema,
SettingsSchema,
SnippetsFileSchema,
SystemConfigSchema,
WorkflowConfigSchema,
type AlertsFile,
type ServerConfig,
type SettingsConfig,
type SnippetsFile,
type SystemConfig,
type WorkflowConfig,
} from '../../shared/schemas/index.js';
import type { ConfigError, ConfigWarning } from '../../shared/ws-protocol.js';
import type { VaultService } from '../security/vault.js';
import { computeLineDiff, type DiffResult } from './diff.js';
import { seedDefaultConfigs } from './presets.js';
export type ConfigEntityType =
| 'server'
| 'system'
| 'workflow'
| 'snippets'
| 'alerts'
| 'settings';
export type RevisionSource = 'seed' | 'ui' | 'disk' | 'rollback';
export interface ConfigRevisionRecord {
id: number;
filePath: string;
sha256: string;
source: string;
summary: string | null;
content: string;
createdAt: number;
}
export interface ConfigChangeEvent {
entityType: ConfigEntityType | 'all';
id?: string;
relPath: string;
warnings: ConfigWarning[];
errors: ConfigError[];
}
interface ParsedTarget {
relPath: string;
entityType: ConfigEntityType;
expectedId?: string;
schema: ZodSchema<unknown>;
}
const SINGLETON_TARGETS: Record<string, { entityType: ConfigEntityType; schema: ZodSchema<unknown> }> = {
'settings.json': { entityType: 'settings', schema: SettingsSchema },
'alerts.json': { entityType: 'alerts', schema: AlertsFileSchema },
'snippets.json': { entityType: 'snippets', schema: SnippetsFileSchema },
};
const COLLECTION_TARGETS: Record<string, { entityType: ConfigEntityType; schema: ZodSchema<unknown> }> = {
servers: { entityType: 'server', schema: ServerConfigSchema },
systems: { entityType: 'system', schema: SystemConfigSchema },
workflows: { entityType: 'workflow', schema: WorkflowConfigSchema },
};
function sha256Text(text: string): string {
return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
}
function formatZodIssues(err: ZodError): Array<{ path: string; message: string }> {
return err.issues.map((issue) => ({
path: issue.path.join('.') || '(root)',
message: issue.message,
}));
}
export class ConfigManager {
private servers = new Map<string, ServerConfig>();
private systems = new Map<string, SystemConfig>();
private workflows = new Map<string, WorkflowConfig>();
private snippets: SnippetsFile = SnippetsFileSchema.parse({});
private alerts: AlertsFile = AlertsFileSchema.parse({});
private settings: SettingsConfig = SettingsSchema.parse({});
private errors = new Map<string, ConfigError>();
private warnings: ConfigWarning[] = [];
private knownFiles = new Set<string>();
private watcher: FSWatcher | null = null;
private readonly debounceTimers = new Map<string, NodeJS.Timeout>();
private readonly recentSelfWrites = new Map<string, { sha256: string; ts: number }>();
private readonly changeListeners = new Set<(event: ConfigChangeEvent) => void>();
constructor(
private readonly configDir: string,
private readonly db: Database.Database,
private readonly vault?: VaultService,
) {}
async init(options: { watch?: boolean } = {}): Promise<void> {
const seeded = seedDefaultConfigs(this.configDir);
const seededSet = new Set(seeded);
const files = this.discoverAllConfigPaths();
for (const relPath of files) {
this.knownFiles.add(relPath);
this.loadFileFromDisk(relPath, seededSet.has(relPath) ? 'seed' : 'disk', false);
}
this.recomputeWarnings();
if (options.watch !== false) {
this.startWatcher();
}
}
async close(): Promise<void> {
for (const timer of this.debounceTimers.values()) {
clearTimeout(timer);
}
this.debounceTimers.clear();
if (this.watcher) {
await this.watcher.close();
this.watcher = null;
}
}
onChange(listener: (event: ConfigChangeEvent) => void): () => void {
this.changeListeners.add(listener);
return () => {
this.changeListeners.delete(listener);
};
}
getSettings(): SettingsConfig {
return structuredClone(this.settings);
}
getAlerts(): AlertsFile {
return structuredClone(this.alerts);
}
getSnippets(): SnippetsFile {
return structuredClone(this.snippets);
}
listServers(): ServerConfig[] {
return [...this.servers.values()].map((s) => structuredClone(s));
}
getServer(id: string): ServerConfig | undefined {
const s = this.servers.get(id);
return s ? structuredClone(s) : undefined;
}
listSystems(): SystemConfig[] {
return [...this.systems.values()].map((s) => structuredClone(s));
}
getSystem(id: string): SystemConfig | undefined {
const s = this.systems.get(id);
return s ? structuredClone(s) : undefined;
}
listWorkflows(): WorkflowConfig[] {
return [...this.workflows.values()].map((w) => structuredClone(w));
}
getWorkflow(id: string): WorkflowConfig | undefined {
const w = this.workflows.get(id);
return w ? structuredClone(w) : undefined;
}
getDiagnostics(): { warnings: ConfigWarning[]; errors: ConfigError[] } {
return {
warnings: structuredClone(this.warnings),
errors: [...this.errors.values()].map((e) => structuredClone(e)),
};
}
recomputeWarnings(): ConfigWarning[] {
const next: ConfigWarning[] = [];
// 1. Server cross-references & jumpHost cycles
for (const server of this.servers.values()) {
const relPath = `servers/${server.id}.json`;
if (this.vault && this.vault.state === 'unlocked') {
if (!this.vault.hasCredential(server.credentialId)) {
next.push({
filePath: relPath,
code: 'MISSING_CREDENTIAL',
message: `credentialId "${server.credentialId}" does not exist in Vault.`,
});
}
if (server.sudoCredentialId && !this.vault.hasCredential(server.sudoCredentialId)) {
next.push({
filePath: relPath,
code: 'MISSING_SUDO_CREDENTIAL',
message: `sudoCredentialId "${server.sudoCredentialId}" does not exist in Vault.`,
});
}
}
if (server.jumpHostId) {
if (!this.servers.has(server.jumpHostId)) {
next.push({
filePath: relPath,
code: 'MISSING_JUMP_HOST',
message: `jumpHostId "${server.jumpHostId}" does not match any server config.`,
});
} else {
// Cycle detection along jumpHost chain
const visited = new Set<string>([server.id]);
let cursor: string | undefined = server.jumpHostId;
while (cursor) {
if (visited.has(cursor)) {
next.push({
filePath: relPath,
code: 'JUMP_HOST_CYCLE',
message: `jumpHostId chain forms a cycle involving "${cursor}".`,
});
break;
}
visited.add(cursor);
cursor = this.servers.get(cursor)?.jumpHostId;
}
}
}
for (const sysAttachment of server.systems) {
if (!this.systems.has(sysAttachment.systemId)) {
next.push({
filePath: relPath,
code: 'MISSING_SYSTEM',
message: `Attached system "${sysAttachment.systemId}" is not defined in systems/.`,
});
}
}
}
// 2. Workflow cross-references
for (const wf of this.workflows.values()) {
const relPath = `workflows/${wf.id}.json`;
for (const step of wf.steps) {
if (step.type === 'system-action' && !this.systems.has(step.systemId)) {
next.push({
filePath: relPath,
code: 'MISSING_SYSTEM',
message: `Step "${step.id}" references missing system "${step.systemId}".`,
});
}
if (
(step.type === 'exec' || step.type === 'read-file' || step.type === 'system-action') &&
step.target.serverId &&
!step.target.serverId.includes('{{') &&
!this.servers.has(step.target.serverId)
) {
next.push({
filePath: relPath,
code: 'MISSING_SERVER',
message: `Step "${step.id}" targets unknown server "${step.target.serverId}".`,
});
}
if (step.type === 'transfer') {
if (
!step.source.serverId.includes('{{') &&
!this.servers.has(step.source.serverId)
) {
next.push({
filePath: relPath,
code: 'MISSING_SERVER',
message: `Transfer step "${step.id}" references unknown source server "${step.source.serverId}".`,
});
}
if (
!step.destination.serverId.includes('{{') &&
!this.servers.has(step.destination.serverId)
) {
next.push({
filePath: relPath,
code: 'MISSING_SERVER',
message: `Transfer step "${step.id}" references unknown destination server "${step.destination.serverId}".`,
});
}
}
}
}
// 3. Alerts cross-references
const channelIds = new Set(this.alerts.channels.map((c) => c.id));
if (this.vault && this.vault.state === 'unlocked') {
for (const ch of this.alerts.channels) {
if (!this.vault.hasCredential(ch.secretRef)) {
next.push({
filePath: 'alerts.json',
code: 'MISSING_CHANNEL_SECRET',
message: `Alert channel "${ch.id}" references missing vault secret "${ch.secretRef}".`,
});
}
}
if (this.settings.ai.secretRef && !this.vault.hasCredential(this.settings.ai.secretRef)) {
next.push({
filePath: 'settings.json',
code: 'MISSING_AI_SECRET',
message: `AI secretRef "${this.settings.ai.secretRef}" does not exist in Vault.`,
});
}
}
for (const rule of this.alerts.rules) {
for (const cid of rule.channelIds) {
if (!channelIds.has(cid)) {
next.push({
filePath: 'alerts.json',
code: 'MISSING_ALERT_CHANNEL',
message: `Rule "${rule.id}" references unknown channel "${cid}".`,
});
}
}
if (rule.remediationWorkflowId && !this.workflows.has(rule.remediationWorkflowId)) {
next.push({
filePath: 'alerts.json',
code: 'MISSING_WORKFLOW',
message: `Rule "${rule.id}" references missing remediationWorkflowId "${rule.remediationWorkflowId}".`,
});
}
if (rule.target.serverId && !this.servers.has(rule.target.serverId)) {
next.push({
filePath: 'alerts.json',
code: 'MISSING_SERVER',
message: `Rule "${rule.id}" targets unknown server "${rule.target.serverId}".`,
});
}
if (rule.kind === 'system' && !this.systems.has(rule.systemId)) {
next.push({
filePath: 'alerts.json',
code: 'MISSING_SYSTEM',
message: `Rule "${rule.id}" references missing system "${rule.systemId}".`,
});
}
}
this.warnings = next;
return structuredClone(this.warnings);
}
listFiles(): Array<{
filePath: string;
entityType: ConfigEntityType;
id?: string;
hasError: boolean;
warningCount: number;
}> {
const allPaths = new Set(this.knownFiles);
for (const p of this.discoverAllConfigPaths()) allPaths.add(p);
const out: Array<{
filePath: string;
entityType: ConfigEntityType;
id?: string;
hasError: boolean;
warningCount: number;
}> = [];
for (const relPath of [...allPaths].sort()) {
const target = this.resolveTarget(relPath);
if (!target) continue;
out.push({
filePath: relPath,
entityType: target.entityType,
id: target.expectedId,
hasError: this.errors.has(relPath),
warningCount: this.warnings.filter((w) => w.filePath === relPath).length,
});
}
return out;
}
readRawFile(relPathInput: string): {
filePath: string;
entityType: ConfigEntityType;
rawContent: string;
activeConfig: unknown;
error: ConfigError | null;
warnings: ConfigWarning[];
} {
const target = this.resolveTargetStrict(relPathInput);
const absPath = this.resolveSafeAbsPath(target.relPath);
if (!fs.existsSync(absPath)) {
throw new Error(`Config file not found: ${target.relPath}`);
}
const rawContent = fs.readFileSync(absPath, 'utf8');
return {
filePath: target.relPath,
entityType: target.entityType,
rawContent,
activeConfig: this.getActiveEntity(target),
error: this.errors.get(target.relPath) ?? null,
warnings: this.warnings.filter((w) => w.filePath === target.relPath),
};
}
saveConfigText(
relPathInput: string,
rawJsonText: string,
source: RevisionSource = 'ui',
summary?: string,
): {
filePath: string;
entityType: ConfigEntityType;
id?: string;
config: unknown;
warnings: ConfigWarning[];
} {
const target = this.resolveTargetStrict(relPathInput);
const validated = this.parseAndValidate(target, rawJsonText);
const formatted = `${JSON.stringify(validated, null, 2)}\n`;
const absPath = this.resolveSafeAbsPath(target.relPath);
const hash = sha256Text(formatted);
this.recentSelfWrites.set(target.relPath, { sha256: hash, ts: Date.now() });
this.writeAtomicFile(absPath, formatted);
this.knownFiles.add(target.relPath);
this.errors.delete(target.relPath);
this.storeActiveEntity(target, validated);
this.recordRevision(target.relPath, formatted, hash, source, summary);
this.recomputeWarnings();
const event: ConfigChangeEvent = {
entityType: target.entityType,
id: target.expectedId,
relPath: target.relPath,
warnings: structuredClone(this.warnings),
errors: [...this.errors.values()].map((e) => structuredClone(e)),
};
this.emitChange(event);
return {
filePath: target.relPath,
entityType: target.entityType,
id: target.expectedId,
config: structuredClone(validated),
warnings: this.warnings.filter((w) => w.filePath === target.relPath),
};
}
deleteEntityFile(relPathInput: string): boolean {
const target = this.resolveTargetStrict(relPathInput);
if (!target.expectedId) {
throw new Error(`Cannot delete singleton config file: ${target.relPath}`);
}
const absPath = this.resolveSafeAbsPath(target.relPath);
if (!fs.existsSync(absPath)) return false;
this.recentSelfWrites.set(target.relPath, { sha256: '__deleted__', ts: Date.now() });
fs.unlinkSync(absPath);
this.removeActiveEntity(target);
this.errors.delete(target.relPath);
this.knownFiles.delete(target.relPath);
this.recomputeWarnings();
this.emitChange({
entityType: target.entityType,
id: target.expectedId,
relPath: target.relPath,
warnings: structuredClone(this.warnings),
errors: [...this.errors.values()].map((e) => structuredClone(e)),
});
return true;
}
listRevisions(relPathInput: string, limit = 50): ConfigRevisionRecord[] {
const target = this.resolveTargetStrict(relPathInput);
const rows = this.db
.prepare(
`SELECT id, file_path AS filePath, sha256, source, summary, content, created_at AS createdAt
FROM config_revisions
WHERE file_path = ?
ORDER BY id DESC
LIMIT ?`,
)
.all(target.relPath, Math.max(1, Math.min(200, limit))) as ConfigRevisionRecord[];
return rows;
}
getRevision(revisionId: number): ConfigRevisionRecord | undefined {
const row = this.db
.prepare(
`SELECT id, file_path AS filePath, sha256, source, summary, content, created_at AS createdAt
FROM config_revisions
WHERE id = ?`,
)
.get(revisionId) as ConfigRevisionRecord | undefined;
return row;
}
diffRevision(revisionId: number): {
revision: ConfigRevisionRecord;
currentContent: string;
diff: DiffResult;
} {
const rev = this.getRevision(revisionId);
if (!rev) {
throw new Error(`Revision #${revisionId} not found`);
}
const target = this.resolveTargetStrict(rev.filePath);
const absPath = this.resolveSafeAbsPath(target.relPath);
const currentContent = fs.existsSync(absPath)
? fs.readFileSync(absPath, 'utf8')
: '';
const diff = computeLineDiff(
rev.content,
currentContent,
`revision#${rev.id} (${rev.source})`,
`current (${rev.filePath})`,
);
return { revision: rev, currentContent, diff };
}
rollbackRevision(revisionId: number): {
filePath: string;
entityType: ConfigEntityType;
id?: string;
config: unknown;
warnings: ConfigWarning[];
} {
const rev = this.getRevision(revisionId);
if (!rev) {
throw new Error(`Revision #${revisionId} not found`);
}
return this.saveConfigText(
rev.filePath,
rev.content,
'rollback',
`Rollback to revision #${rev.id}`,
);
}
private startWatcher(): void {
this.watcher = chokidar.watch(this.configDir, {
ignoreInitial: true,
persistent: true,
depth: 2,
});
const scheduleReload = (absPath: string, kind: 'upsert' | 'unlink') => {
if (!absPath.endsWith('.json')) return;
const relRaw = path.relative(this.configDir, absPath).split(path.sep).join('/');
if (relRaw.includes('.tmp')) return;
if (!this.resolveTarget(relRaw)) return;
const prev = this.debounceTimers.get(relRaw);
if (prev) clearTimeout(prev);
const timer = setTimeout(() => {
this.debounceTimers.delete(relRaw);
if (kind === 'unlink') {
this.handleExternalUnlink(relRaw);
} else {
this.handleExternalUpsert(relRaw);
}
}, 300);
this.debounceTimers.set(relRaw, timer);
};
this.watcher.on('add', (p) => scheduleReload(p, 'upsert'));
this.watcher.on('change', (p) => scheduleReload(p, 'upsert'));
this.watcher.on('unlink', (p) => scheduleReload(p, 'unlink'));
}
private handleExternalUpsert(relPath: string): void {
const target = this.resolveTarget(relPath);
if (!target) return;
const absPath = this.resolveSafeAbsPath(relPath);
if (!fs.existsSync(absPath)) return;
const rawText = fs.readFileSync(absPath, 'utf8');
const hash = sha256Text(rawText);
const selfWrite = this.recentSelfWrites.get(relPath);
if (selfWrite && selfWrite.sha256 === hash && Date.now() - selfWrite.ts < 5000) {
this.recentSelfWrites.delete(relPath);
return;
}
this.knownFiles.add(relPath);
this.loadFileFromDisk(relPath, 'disk', true);
}
private handleExternalUnlink(relPath: string): void {
const target = this.resolveTarget(relPath);
if (!target) return;
const selfWrite = this.recentSelfWrites.get(relPath);
if (
selfWrite &&
selfWrite.sha256 === '__deleted__' &&
Date.now() - selfWrite.ts < 5000
) {
this.recentSelfWrites.delete(relPath);
return;
}
if (target.expectedId) {
this.removeActiveEntity(target);
this.errors.delete(relPath);
this.knownFiles.delete(relPath);
this.recomputeWarnings();
this.emitChange({
entityType: target.entityType,
id: target.expectedId,
relPath,
warnings: structuredClone(this.warnings),
errors: [...this.errors.values()].map((e) => structuredClone(e)),
});
} else {
this.errors.set(relPath, {
filePath: relPath,
message: `Required config file ${relPath} was deleted on disk; retaining last valid configuration in memory.`,
});
this.emitChange({
entityType: target.entityType,
relPath,
warnings: structuredClone(this.warnings),
errors: [...this.errors.values()].map((e) => structuredClone(e)),
});
}
}
private loadFileFromDisk(
relPath: string,
source: RevisionSource,
emitOnResult: boolean,
): void {
const target = this.resolveTarget(relPath);
if (!target) return;
const absPath = this.resolveSafeAbsPath(relPath);
let rawText: string;
try {
rawText = fs.readFileSync(absPath, 'utf8');
} catch (err) {
this.errors.set(relPath, {
filePath: relPath,
message: err instanceof Error ? err.message : 'Unable to read config file',
});
if (emitOnResult) {
this.emitChange({
entityType: target.entityType,
id: target.expectedId,
relPath,
warnings: structuredClone(this.warnings),
errors: [...this.errors.values()].map((e) => structuredClone(e)),
});
}
return;
}
try {
const validated = this.parseAndValidate(target, rawText);
this.errors.delete(relPath);
this.storeActiveEntity(target, validated);
const formatted = `${JSON.stringify(validated, null, 2)}\n`;
this.recordRevision(relPath, formatted, sha256Text(formatted), source);
this.recomputeWarnings();
} catch (err) {
// Isolated fallback: preserve previous valid entity in memory; only flag this file
if (err instanceof Error && 'issues' in err) {
const zodErr = err as ZodError;
this.errors.set(relPath, {
filePath: relPath,
message: 'Schema validation failed; retaining last valid config in memory.',
issues: formatZodIssues(zodErr),
});
} else {
this.errors.set(relPath, {
filePath: relPath,
message: `${err instanceof Error ? err.message : String(err)}; retaining last valid config in memory.`,
});
}
}
if (emitOnResult) {
this.emitChange({
entityType: target.entityType,
id: target.expectedId,
relPath,
warnings: structuredClone(this.warnings),
errors: [...this.errors.values()].map((e) => structuredClone(e)),
});
}
}
private parseAndValidate(target: ParsedTarget, rawJsonText: string): unknown {
const rawObj = JSON.parse(rawJsonText);
const parsed = target.schema.parse(rawObj);
if (target.expectedId) {
const id = (parsed as { id?: string }).id;
if (id !== target.expectedId) {
throw new Error(
`Filename "${target.relPath}" expects id "${target.expectedId}", got "${String(id)}"`,
);
}
}
return parsed;
}
private resolveTarget(relPathInput: string): ParsedTarget | null {
const normalized = relPathInput.replace(/\\/g, '/').replace(/^\/+/, '');
if (!normalized || normalized.includes('..')) return null;
const singleton = SINGLETON_TARGETS[normalized];
if (singleton) {
return {
relPath: normalized,
entityType: singleton.entityType,
schema: singleton.schema,
};
}
const parts = normalized.split('/');
if (parts.length !== 2) return null;
const [folder, fileName] = parts;
if (!folder || !fileName || !fileName.endsWith('.json')) return null;
const collection = COLLECTION_TARGETS[folder];
if (!collection) return null;
const expectedId = fileName.slice(0, -5);
if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(expectedId)) return null;
return {
relPath: `${folder}/${fileName}`,
entityType: collection.entityType,
expectedId,
schema: collection.schema,
};
}
private resolveTargetStrict(relPathInput: string): ParsedTarget {
const target = this.resolveTarget(relPathInput);
if (!target) {
throw new Error(`Invalid config file path: ${relPathInput}`);
}
return target;
}
private resolveSafeAbsPath(relPath: string): string {
const resolved = path.resolve(this.configDir, relPath);
const root = path.resolve(this.configDir);
if (!resolved.startsWith(`${root}${path.sep}`)) {
throw new Error(`Path escapes config directory: ${relPath}`);
}
return resolved;
}
private discoverAllConfigPaths(): string[] {
const paths: string[] = [];
for (const name of Object.keys(SINGLETON_TARGETS)) {
if (fs.existsSync(path.join(this.configDir, name))) {
paths.push(name);
}
}
for (const folder of Object.keys(COLLECTION_TARGETS)) {
const dir = path.join(this.configDir, folder);
if (!fs.existsSync(dir)) continue;
for (const entry of fs.readdirSync(dir)) {
if (!entry.endsWith('.json') || entry.includes('.tmp')) continue;
const candidate = `${folder}/${entry}`;
if (this.resolveTarget(candidate)) {
paths.push(candidate);
}
}
}
return paths.sort();
}
private storeActiveEntity(target: ParsedTarget, value: unknown): void {
switch (target.entityType) {
case 'server':
this.servers.set(target.expectedId!, value as ServerConfig);
break;
case 'system':
this.systems.set(target.expectedId!, value as SystemConfig);
break;
case 'workflow':
this.workflows.set(target.expectedId!, value as WorkflowConfig);
break;
case 'snippets':
this.snippets = value as SnippetsFile;
break;
case 'alerts':
this.alerts = value as AlertsFile;
break;
case 'settings':
this.settings = value as SettingsConfig;
break;
}
}
private removeActiveEntity(target: ParsedTarget): void {
if (!target.expectedId) return;
switch (target.entityType) {
case 'server':
this.servers.delete(target.expectedId);
break;
case 'system':
this.systems.delete(target.expectedId);
break;
case 'workflow':
this.workflows.delete(target.expectedId);
break;
}
}
private getActiveEntity(target: ParsedTarget): unknown {
switch (target.entityType) {
case 'server':
return this.servers.get(target.expectedId!) ?? null;
case 'system':
return this.systems.get(target.expectedId!) ?? null;
case 'workflow':
return this.workflows.get(target.expectedId!) ?? null;
case 'snippets':
return this.snippets;
case 'alerts':
return this.alerts;
case 'settings':
return this.settings;
}
}
private writeAtomicFile(absPath: string, content: string): void {
fs.mkdirSync(path.dirname(absPath), { recursive: true });
const tmpPath = `${absPath}.tmp.${process.pid}.${Date.now()}`;
const fd = fs.openSync(tmpPath, 'w', 0o600);
try {
fs.writeFileSync(fd, content, 'utf8');
fs.fsyncSync(fd);
} finally {
fs.closeSync(fd);
}
fs.renameSync(tmpPath, absPath);
}
private recordRevision(
relPath: string,
content: string,
sha256: string,
source: RevisionSource,
summary?: string,
): void {
const latest = this.db
.prepare(
'SELECT sha256 FROM config_revisions WHERE file_path = ? ORDER BY id DESC LIMIT 1',
)
.get(relPath) as { sha256: string } | undefined;
if (latest && latest.sha256 === sha256) return;
const limit = this.settings.configRevisionLimit;
const tx = this.db.transaction(() => {
this.db
.prepare(
`INSERT INTO config_revisions (file_path, sha256, source, summary, content, created_at)
VALUES (?, ?, ?, ?, ?, ?)`,
)
.run(relPath, sha256, source, summary ?? null, content, Date.now());
this.db
.prepare(
`DELETE FROM config_revisions
WHERE file_path = ?
AND id NOT IN (
SELECT id FROM config_revisions
WHERE file_path = ?
ORDER BY id DESC
LIMIT ?
)`,
)
.run(relPath, relPath, limit);
});
tx();
}
private emitChange(event: ConfigChangeEvent): void {
for (const listener of this.changeListeners) {
try {
listener(event);
} catch {
// Isolate subscriber failures
}
}
}
}

98
src/server/config/diff.ts Normal file
View file

@ -0,0 +1,98 @@
export interface DiffLine {
type: 'equal' | 'add' | 'del';
oldLine?: number;
newLine?: number;
text: string;
}
export interface DiffResult {
lines: DiffLine[];
unified: string;
additions: number;
deletions: number;
}
export function computeLineDiff(
oldText: string,
newText: string,
oldLabel = 'revision',
newLabel = 'current',
): DiffResult {
const a = oldText.replace(/\r\n/g, '\n').split('\n');
const b = newText.replace(/\r\n/g, '\n').split('\n');
const m = a.length;
const n = b.length;
let lines: DiffLine[];
// DP LCS works cleanly for config files up to a few thousand lines
if (m * n <= 2_500_000) {
const dp = new Int32Array((m + 1) * (n + 1));
const stride = n + 1;
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
if (a[i] === b[j]) {
dp[i * stride + j] = dp[(i + 1) * stride + (j + 1)]! + 1;
} else {
const down = dp[(i + 1) * stride + j]!;
const right = dp[i * stride + (j + 1)]!;
dp[i * stride + j] = down >= right ? down : right;
}
}
}
lines = [];
let i = 0;
let j = 0;
while (i < m && j < n) {
if (a[i] === b[j]) {
lines.push({ type: 'equal', oldLine: i + 1, newLine: j + 1, text: a[i]! });
i++;
j++;
} else if (dp[(i + 1) * stride + j]! >= dp[i * stride + (j + 1)]!) {
lines.push({ type: 'del', oldLine: i + 1, text: a[i]! });
i++;
} else {
lines.push({ type: 'add', newLine: j + 1, text: b[j]! });
j++;
}
}
while (i < m) {
lines.push({ type: 'del', oldLine: i + 1, text: a[i]! });
i++;
}
while (j < n) {
lines.push({ type: 'add', newLine: j + 1, text: b[j]! });
j++;
}
} else {
// Fallback linear diff for unexpectedly massive inputs
lines = [
...a.map((text, idx) => ({ type: 'del' as const, oldLine: idx + 1, text })),
...b.map((text, idx) => ({ type: 'add' as const, newLine: idx + 1, text })),
];
}
let additions = 0;
let deletions = 0;
const body: string[] = [`--- ${oldLabel}`, `+++ ${newLabel}`];
for (const line of lines) {
if (line.type === 'add') {
additions++;
body.push(`+${line.text}`);
} else if (line.type === 'del') {
deletions++;
body.push(`-${line.text}`);
} else {
body.push(` ${line.text}`);
}
}
return {
lines,
unified: body.join('\n'),
additions,
deletions,
};
}

View file

@ -0,0 +1,331 @@
import fs from 'node:fs';
import path from 'node:path';
import {
AlertsFileSchema,
SettingsSchema,
SnippetsFileSchema,
SystemConfigSchema,
type SystemConfig,
} from '../../shared/schemas/index.js';
export const PRESET_SYSTEMS: SystemConfig[] = [
SystemConfigSchema.parse({
id: 'docker-compose',
name: 'Docker Compose Stacks',
description: 'Discover and manage Compose stacks across configured root directories.',
cacheTtlSec: 45,
backgroundCheckSec: 60,
params: [
{
name: 'rootDirs',
type: 'string[]',
default: ['~/Services'],
required: true,
description: 'Directories scanned for compose.yml / docker-compose.yml stacks.',
},
],
discovery: {
type: 'folder-scan',
rootsParam: 'rootDirs',
maxDepth: 1,
matchFiles: ['compose.yml', 'compose.yaml', 'docker-compose.yml', 'docker-compose.yaml'],
selectableFiles: ['*compose*.yml', '*compose*.yaml'],
},
status: {
command:
'docker compose --project-directory "$GCOORD_ITEM_DIR" $GCOORD_COMPOSE_FILES ps --all --format json',
parser: 'json-lines',
subItemField: 'Service',
health: {
field: 'State',
healthyValues: ['running'],
degradedValues: ['restarting', 'paused', 'created'],
},
},
actions: [
{
id: 'up',
label: 'Run',
scope: 'item',
mode: 'oneshot',
command:
'docker compose --project-directory "$GCOORD_ITEM_DIR" $GCOORD_COMPOSE_FILES up -d',
},
{
id: 'down',
label: 'Shut Down',
scope: 'item',
mode: 'oneshot',
confirm: true,
command:
'docker compose --project-directory "$GCOORD_ITEM_DIR" $GCOORD_COMPOSE_FILES down',
},
{
id: 'restart',
label: 'Restart',
scope: 'item',
mode: 'oneshot',
command:
'docker compose --project-directory "$GCOORD_ITEM_DIR" $GCOORD_COMPOSE_FILES restart',
},
{
id: 'rebuild',
label: 'Rebuild',
scope: 'item',
mode: 'stream',
command:
'docker compose --project-directory "$GCOORD_ITEM_DIR" $GCOORD_COMPOSE_FILES up -d --build --force-recreate',
},
{
id: 'update',
label: 'Pull & Update',
scope: 'item',
mode: 'stream',
command:
'docker compose --project-directory "$GCOORD_ITEM_DIR" $GCOORD_COMPOSE_FILES pull && docker compose --project-directory "$GCOORD_ITEM_DIR" $GCOORD_COMPOSE_FILES up -d',
},
{
id: 'logs',
label: 'Logs',
scope: 'item',
mode: 'stream',
command:
'docker compose --project-directory "$GCOORD_ITEM_DIR" $GCOORD_COMPOSE_FILES logs -f --tail 100',
},
{
id: 'debug-shell',
label: 'Debug Shell',
scope: 'subitem',
mode: 'interactive',
command:
'docker compose --project-directory "$GCOORD_ITEM_DIR" $GCOORD_COMPOSE_FILES exec "$GCOORD_SUBITEM" sh -c \'command -v bash >/dev/null && exec bash || exec sh\'',
},
{
id: 'inspect',
label: 'Inspect',
scope: 'subitem',
mode: 'oneshot',
command:
'docker compose --project-directory "$GCOORD_ITEM_DIR" $GCOORD_COMPOSE_FILES ps "$GCOORD_SUBITEM" --format json && docker inspect "$(docker compose --project-directory "$GCOORD_ITEM_DIR" $GCOORD_COMPOSE_FILES ps -q "$GCOORD_SUBITEM")"',
},
{
id: 'prune',
label: 'Prune Host',
scope: 'system',
mode: 'stream',
confirm: true,
command: 'docker system prune -f',
},
],
editableFiles: ['*compose*.yml', '*compose*.yaml', '.env'],
}),
SystemConfigSchema.parse({
id: 'systemd',
name: 'systemd Services',
description: 'Monitor and control systemd units, overrides, and live journalctl streams.',
cacheTtlSec: 30,
backgroundCheckSec: 60,
params: [
{
name: 'unitFilter',
type: 'string',
default: '',
required: false,
description: 'Optional extended regex matching unit names to track.',
},
],
discovery: {
type: 'command',
command:
'systemctl list-units --type=service --all --no-pager --no-legend --plain | awk \'{print $1}\' | { if [ -n "$GCOORD_PARAM_UNITFILTER" ]; then grep -E "$GCOORD_PARAM_UNITFILTER" || true; else cat; fi; }',
parser: 'lines',
},
status: {
command:
'systemctl show "$GCOORD_ITEM_NAME" --property=Id,LoadState,ActiveState,SubState,MainPID --no-pager | awk -F= \'BEGIN{printf "{"} NR>1{printf ","} {gsub(/"/,"\\\\\"",$2); printf "\\"%s\\":\\"%s\\"",$1,$2} END{printf "}\\n"}\'',
parser: 'json',
health: {
field: 'ActiveState',
healthyValues: ['active'],
degradedValues: ['activating', 'reloading', 'deactivating'],
},
},
actions: [
{
id: 'start',
label: 'Start',
scope: 'item',
mode: 'oneshot',
sudo: true,
command: 'systemctl start "$GCOORD_ITEM_NAME"',
},
{
id: 'stop',
label: 'Stop',
scope: 'item',
mode: 'oneshot',
sudo: true,
confirm: true,
command: 'systemctl stop "$GCOORD_ITEM_NAME"',
},
{
id: 'restart',
label: 'Restart',
scope: 'item',
mode: 'oneshot',
sudo: true,
command: 'systemctl restart "$GCOORD_ITEM_NAME"',
},
{
id: 'reload',
label: 'Reload',
scope: 'item',
mode: 'oneshot',
sudo: true,
command: 'systemctl reload "$GCOORD_ITEM_NAME"',
},
{
id: 'enable',
label: 'Enable',
scope: 'item',
mode: 'oneshot',
sudo: true,
command: 'systemctl enable "$GCOORD_ITEM_NAME"',
},
{
id: 'disable',
label: 'Disable',
scope: 'item',
mode: 'oneshot',
sudo: true,
confirm: true,
command: 'systemctl disable "$GCOORD_ITEM_NAME"',
},
{
id: 'logs',
label: 'Journal Logs',
scope: 'item',
mode: 'stream',
sudo: true,
command: 'journalctl -u "$GCOORD_ITEM_NAME" -f -n 100 --no-pager',
},
],
editableFiles: ['/etc/systemd/system/*.service', '/etc/systemd/system/*.d/*.conf'],
}),
SystemConfigSchema.parse({
id: 'os-packages',
name: 'OS Package Updates',
description: 'Cross-distro package update status and streamed upgrades (apt/dnf/apk/pacman).',
cacheTtlSec: 300,
params: [],
discovery: {
type: 'command',
command: 'echo "system-packages"',
parser: 'lines',
},
status: {
command:
'if command -v apt-get >/dev/null; then echo "manager=apt"; apt list --upgradable 2>/dev/null | tail -n +2 | head -n 50; elif command -v dnf >/dev/null; then echo "manager=dnf"; dnf check-update -q || true; elif command -v apk >/dev/null; then echo "manager=apk"; apk version -l "<" || true; elif command -v pacman >/dev/null; then echo "manager=pacman"; pacman -Qu || true; fi; [ -f /var/run/reboot-required ] && echo "REBOOT_REQUIRED=true" || echo "REBOOT_REQUIRED=false"',
parser: 'lines',
health: {
healthyExitCodes: [0],
},
},
actions: [
{
id: 'refresh',
label: 'Refresh Index',
scope: 'system',
mode: 'stream',
sudo: true,
command:
'if command -v apt-get >/dev/null; then apt-get update; elif command -v dnf >/dev/null; then dnf makecache; elif command -v apk >/dev/null; then apk update; elif command -v pacman >/dev/null; then pacman -Sy; fi',
},
{
id: 'upgrade',
label: 'Upgrade Packages',
scope: 'system',
mode: 'stream',
sudo: true,
confirm: true,
command:
'if command -v apt-get >/dev/null; then DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get upgrade -y; elif command -v dnf >/dev/null; then dnf upgrade -y; elif command -v apk >/dev/null; then apk upgrade; elif command -v pacman >/dev/null; then pacman -Syu --noconfirm; fi',
},
],
editableFiles: [],
}),
];
export const DEFAULT_SNIPPETS = SnippetsFileSchema.parse({
version: 1,
snippets: [
{
id: 'disk-usage',
name: 'Disk Usage (Real FS)',
description: 'Show mounted real filesystems with types and usage percentages.',
command: 'df -hPT -x tmpfs -x devtmpfs',
tags: ['diagnostics', 'disk'],
inputs: [],
sudo: false,
confirm: false,
},
{
id: 'listening-ports',
name: 'Listening Sockets',
description: 'Inspect listening TCP/UDP sockets and owning processes.',
command: 'ss -tulnp 2>/dev/null || netstat -tulnp',
tags: ['network', 'diagnostics'],
inputs: [],
sudo: true,
confirm: false,
},
{
id: 'failed-units',
name: 'Failed systemd Units',
description: 'List failed systemd services.',
command: 'systemctl --failed --no-pager',
tags: ['systemd'],
inputs: [],
sudo: false,
confirm: false,
},
{
id: 'docker-stats-once',
name: 'Docker Container Stats (Snapshot)',
description: 'Print a single snapshot of running Docker container CPU/RAM usage.',
command: 'docker stats --no-stream --format "table {{.Name}}\\t{{.CPUPerc}}\\t{{.MemUsage}}\\t{{.NetIO}}"',
tags: ['docker'],
inputs: [],
sudo: false,
confirm: false,
},
],
});
export function seedDefaultConfigs(configDir: string): string[] {
const created: string[] = [];
for (const sub of ['servers', 'workflows', 'systems']) {
fs.mkdirSync(path.join(configDir, sub), { recursive: true });
}
const defaults: Array<[string, unknown]> = [
['settings.json', SettingsSchema.parse({})],
['alerts.json', AlertsFileSchema.parse({})],
['snippets.json', DEFAULT_SNIPPETS],
...PRESET_SYSTEMS.map(
(sys): [string, SystemConfig] => [`systems/${sys.id}.json`, sys],
),
];
for (const [relPath, obj] of defaults) {
const absPath = path.join(configDir, relPath);
if (!fs.existsSync(absPath)) {
fs.writeFileSync(absPath, `${JSON.stringify(obj, null, 2)}\n`, 'utf8');
created.push(relPath);
}
}
return created;
}