diff --git a/src/server/systems/parsers.ts b/src/server/systems/parsers.ts new file mode 100644 index 0000000..1f7a4ce --- /dev/null +++ b/src/server/systems/parsers.ts @@ -0,0 +1,357 @@ +import type { z } from 'zod'; +import type { SystemHealthRuleSchema, SystemStatusSchema } from '../../shared/schemas/system.schema.js'; + +export type HealthState = 'ok' | 'warn' | 'down' | 'unknown'; +export type SystemStatusConfig = z.infer; +export type SystemHealthRule = z.infer; + +export interface ParsedSubItem { + name: string; + health: HealthState; + stateText?: string; + raw?: Record; +} + +export interface ParsedStatusResult { + health: HealthState; + subItems: ParsedSubItem[]; + rawSummary: string; + exitCode: number | null; +} + +export interface ScannedFolderMatch { + dir: string; + files: string[]; +} + +export function globToRegExp(pattern: string): RegExp { + const escaped = pattern + .replace(/[.+^${}()|[\]\\]/g, '\\$&') + .replace(/\*/g, '.*') + .replace(/\?/g, '.'); + return new RegExp(`^${escaped}$`); +} + +export function parseFolderScanOutput(stdout: string): ScannedFolderMatch[] { + const out: ScannedFolderMatch[] = []; + let current: ScannedFolderMatch | null = null; + + for (const rawLine of stdout.split(/\r?\n/)) { + if (!rawLine) continue; + const tab = rawLine.indexOf('\t'); + if (tab <= 0) continue; + const kind = rawLine.slice(0, tab); + const val = rawLine.slice(tab + 1).trim(); + if (!val) continue; + + if (kind === 'D') { + current = { dir: val, files: [] }; + out.push(current); + } else if (kind === 'F' && current) { + if (!current.files.includes(val)) { + current.files.push(val); + } + } + } + + return out; +} + +function extractNameFromObject(obj: Record, fallback: string): string { + for (const key of ['name', 'Name', 'id', 'ID', 'Id', 'unit', 'Service', 'service']) { + const val = obj[key]; + if (typeof val === 'string' && val.trim()) return val.trim(); + } + return fallback; +} + +export function parseDiscoveryOutput( + stdout: string, + parser: 'lines' | 'json' | 'json-lines', +): string[] { + const trimmed = stdout.trim(); + if (!trimmed) return []; + + const seen = new Set(); + const add = (val: string) => { + const clean = val.trim(); + if (clean && !seen.has(clean)) seen.add(clean); + }; + + if (parser === 'lines') { + for (const line of trimmed.split(/\r?\n/)) { + add(line); + } + return [...seen]; + } + + if (parser === 'json') { + try { + const parsed = JSON.parse(trimmed) as unknown; + const list = Array.isArray(parsed) + ? parsed + : parsed && typeof parsed === 'object' && Array.isArray((parsed as Record).items) + ? ((parsed as Record).items as unknown[]) + : [parsed]; + list.forEach((entry, idx) => { + if (typeof entry === 'string') { + add(entry); + } else if (entry && typeof entry === 'object') { + add(extractNameFromObject(entry as Record, `item-${idx + 1}`)); + } + }); + } catch { + return []; + } + return [...seen]; + } + + // json-lines + trimmed.split(/\r?\n/).forEach((line, idx) => { + const s = line.trim(); + if (!s) return; + try { + const parsed = JSON.parse(s) as unknown; + if (typeof parsed === 'string') add(parsed); + else if (parsed && typeof parsed === 'object') { + add(extractNameFromObject(parsed as Record, `item-${idx + 1}`)); + } + } catch { + // Skip malformed line + } + }); + return [...seen]; +} + +function evaluateHealthRecord( + record: Record | null, + exitCode: number | null, + rule?: SystemHealthRule, +): HealthState { + if (!rule) { + if (exitCode !== null && exitCode !== 0) return 'down'; + return record ? 'ok' : 'unknown'; + } + + if (rule.healthyExitCodes && exitCode !== null) { + if (!rule.healthyExitCodes.includes(exitCode)) { + return 'down'; + } + if (!rule.field) return 'ok'; + } + + if (rule.field && record) { + const rawVal = record[rule.field]; + if (rawVal === undefined || rawVal === null) return 'unknown'; + const norm = String(rawVal).trim().toLowerCase(); + if (rule.healthyValues?.some((v) => v.trim().toLowerCase() === norm)) { + return 'ok'; + } + if (rule.degradedValues?.some((v) => v.trim().toLowerCase() === norm)) { + return 'warn'; + } + if (rule.healthyValues && rule.healthyValues.length > 0) { + return 'down'; + } + return 'unknown'; + } + + if (exitCode !== null) { + return exitCode === 0 ? 'ok' : 'down'; + } + return 'unknown'; +} + +function summarizeRecord(record: Record): string { + const parts: string[] = []; + for (const key of ['State', 'ActiveState', 'SubState', 'Status', 'status', 'Health']) { + const v = record[key]; + if (typeof v === 'string' && v.trim()) { + parts.push(`${key}=${v.trim()}`); + } + } + if (parts.length > 0) return parts.join(' '); + return JSON.stringify(record).slice(0, 120); +} + +function parseJsonObjectOrLines(trimmed: string): Array> { + const rows: Array> = []; + if (trimmed.startsWith('[')) { + try { + const arr = JSON.parse(trimmed) as unknown; + if (Array.isArray(arr)) { + for (const item of arr) { + if (item && typeof item === 'object') { + rows.push(item as Record); + } + } + return rows; + } + } catch { + // Fall through to line-by-line parsing + } + } + + for (const line of trimmed.split(/\r?\n/)) { + const s = line.trim(); + if (!s) continue; + try { + const parsed = JSON.parse(s) as unknown; + if (Array.isArray(parsed)) { + for (const el of parsed) { + if (el && typeof el === 'object') rows.push(el as Record); + } + } else if (parsed && typeof parsed === 'object') { + rows.push(parsed as Record); + } + } catch { + // Skip non-JSON diagnostic noise line + } + } + return rows; +} + +export function rollupHealth(states: HealthState[], fallback: HealthState = 'unknown'): HealthState { + if (states.length === 0) return fallback; + if (states.includes('down')) return 'down'; + if (states.includes('warn')) return 'warn'; + if (states.includes('ok')) return 'ok'; + return fallback; +} + +export function parseStatusOutput( + stdout: string, + stderr: string, + exitCode: number | null, + statusCfg: SystemStatusConfig, +): ParsedStatusResult { + const trimmed = stdout.trim(); + + if (statusCfg.parser === 'exit-code') { + const health = evaluateHealthRecord(null, exitCode, statusCfg.health); + return { + health, + subItems: [], + rawSummary: trimmed || stderr.trim() || `exit=${String(exitCode)}`, + exitCode, + }; + } + + if (statusCfg.parser === 'json-lines') { + const rows = trimmed ? parseJsonObjectOrLines(trimmed) : []; + const subItems: ParsedSubItem[] = rows.map((row, idx) => { + const subName = + (statusCfg.subItemField && typeof row[statusCfg.subItemField] === 'string' + ? String(row[statusCfg.subItemField]).trim() + : '') || extractNameFromObject(row, `service-${idx + 1}`); + const subHealth = evaluateHealthRecord(row, exitCode, statusCfg.health); + return { + name: subName, + health: subHealth, + stateText: summarizeRecord(row), + raw: row, + }; + }); + + const health = + subItems.length > 0 + ? rollupHealth(subItems.map((s) => s.health)) + : exitCode !== null && exitCode !== 0 + ? 'down' + : 'warn'; + + const rawSummary = + subItems.length > 0 + ? subItems.map((s) => `${s.name}:${s.stateText ?? s.health}`).join(' | ') + : stderr.trim() || 'No active sub-items'; + + return { health, subItems, rawSummary, exitCode }; + } + + if (statusCfg.parser === 'json') { + if (!trimmed) { + return { + health: evaluateHealthRecord(null, exitCode, statusCfg.health), + subItems: [], + rawSummary: stderr.trim() || `exit=${String(exitCode)}`, + exitCode, + }; + } + + try { + const parsed = JSON.parse(trimmed) as unknown; + if (Array.isArray(parsed)) { + const subItems: ParsedSubItem[] = []; + for (let i = 0; i < parsed.length; i++) { + const item = parsed[i]; + if (!item || typeof item !== 'object') continue; + const rec = item as Record; + subItems.push({ + name: + (statusCfg.subItemField && typeof rec[statusCfg.subItemField] === 'string' + ? String(rec[statusCfg.subItemField]).trim() + : '') || extractNameFromObject(rec, `item-${i + 1}`), + health: evaluateHealthRecord(rec, exitCode, statusCfg.health), + stateText: summarizeRecord(rec), + raw: rec, + }); + } + return { + health: rollupHealth( + subItems.map((s) => s.health), + exitCode === 0 ? 'warn' : 'down', + ), + subItems, + rawSummary: subItems.map((s) => `${s.name}:${s.stateText ?? s.health}`).join(' | '), + exitCode, + }; + } + + if (parsed && typeof parsed === 'object') { + const rec = parsed as Record; + return { + health: evaluateHealthRecord(rec, exitCode, statusCfg.health), + subItems: [], + rawSummary: summarizeRecord(rec), + exitCode, + }; + } + } catch { + return { + health: 'unknown', + subItems: [], + rawSummary: trimmed.slice(0, 180), + exitCode, + }; + } + } + + if (statusCfg.parser === 'regex') { + const re = statusCfg.regexPattern ? new RegExp(statusCfg.regexPattern, 'm') : null; + const matched = re ? re.test(trimmed) : trimmed.length > 0; + const exitOk = statusCfg.health?.healthyExitCodes + ? exitCode !== null && statusCfg.health.healthyExitCodes.includes(exitCode) + : exitCode === null || exitCode === 0; + return { + health: exitOk && matched ? 'ok' : 'down', + subItems: [], + rawSummary: trimmed.split(/\r?\n/).slice(0, 4).join(' | '), + exitCode, + }; + } + + // 'lines' parser + const lines = trimmed + ? trimmed + .split(/\r?\n/) + .map((l) => l.trim()) + .filter(Boolean) + : []; + const health = evaluateHealthRecord(null, exitCode, statusCfg.health); + return { + health, + subItems: [], + rawSummary: lines.slice(0, 5).join(' | ') || stderr.trim() || `exit=${String(exitCode)}`, + exitCode, + }; +} diff --git a/src/server/systems/systems-engine.ts b/src/server/systems/systems-engine.ts new file mode 100644 index 0000000..5409f54 --- /dev/null +++ b/src/server/systems/systems-engine.ts @@ -0,0 +1,779 @@ +import crypto from 'node:crypto'; +import path from 'node:path'; +import type { ServerConfig } from '../../shared/schemas/server.schema.js'; +import type { SystemAction, SystemConfig } from '../../shared/schemas/system.schema.js'; +import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js'; +import type { WsHub } from '../api/ws-hub.js'; +import type { ConfigManager } from '../config/config-manager.js'; +import type { VaultService } from '../security/vault.js'; +import type { PTYManager, PtySessionInfo } from '../ssh/pty-manager.js'; +import type { SSHPool } from '../ssh/ssh-pool.js'; +import { posixSingleQuote } from '../ssh/sudo.js'; +import { + globToRegExp, + parseDiscoveryOutput, + parseFolderScanOutput, + parseStatusOutput, + rollupHealth, + type HealthState, + type ParsedStatusResult, +} from './parsers.js'; + +export interface DiscoveredSystemItem { + name: string; + dir?: string; + activeFiles: string[]; + selectableFiles: string[]; + editableFiles: string[]; + status: ParsedStatusResult; +} + +export interface ServerSystemSnapshot { + serverId: string; + systemId: string; + fetchedAt: number; + cached: boolean; + error?: string; + params: Record; + items: DiscoveredSystemItem[]; + systemHealth: HealthState; +} + +export type ActionExecutionResult = + | { + mode: 'oneshot'; + exitCode: number | null; + stdout: string; + stderr: string; + durationMs: number; + } + | { + mode: 'stream'; + jobId: string; + } + | { + mode: 'interactive'; + session: PtySessionInfo; + }; + +interface ActiveStreamJob { + jobId: string; + serverId: string; + systemId: string; + frames: ServerWsFrame[]; + bufferBytes: number; + done: boolean; + abort: () => void; +} + +const MAX_STREAM_REPLAY_BYTES = 128 * 1024; +const MAX_RETAINED_DONE_STREAMS = 25; + +export function isValidRelativeOverlayFile(fileName: string): boolean { + const clean = fileName.trim(); + if (!clean) return false; + if (clean.includes('/') || clean.includes('\\') || clean.includes('..')) return false; + if (/[\s'"$;|&<>()`]/.test(clean)) return false; + return true; +} + +function expandShellRoot(root: string): string { + const trimmed = root.trim(); + if (trimmed === '~' || trimmed === '~/') return '"$HOME"'; + if (trimmed.startsWith('~/')) return `"$HOME/"${posixSingleQuote(trimmed.slice(2))}`; + return posixSingleQuote(trimmed); +} + +function buildFolderScanScript(roots: string[], maxDepth: number, matchFiles: string[]): string { + const rootArgs = roots.map(expandShellRoot).join(' '); + const casePatterns = matchFiles + .map((p) => p.replace(/[^A-Za-z0-9._*?[\]-]/g, '')) + .filter(Boolean) + .join('|') || '*'; + + return [ + `for r in ${rootArgs}; do`, + ` [ -d "$r" ] || continue`, + ` find "$r" -maxdepth ${maxDepth} -type d 2>/dev/null | while IFS= read -r d; do`, + ` matched=0`, + ` for f in "$d"/* "$d"/.*; do`, + ` [ -f "$f" ] || continue`, + ` b=\${f##*/}`, + ` case "$b" in`, + ` ${casePatterns}) matched=1; break ;;`, + ` esac`, + ` done`, + ` [ "$matched" -eq 1 ] || continue`, + ` printf 'D\\t%s\\n' "$d"`, + ` for f in "$d"/* "$d"/.*; do`, + ` [ -f "$f" ] || continue`, + ` b=\${f##*/}`, + ` [ "$b" = "." ] || [ "$b" = ".." ] && continue`, + ` printf 'F\\t%s\\n' "$b"`, + ` done`, + ` done`, + `done`, + ].join('\n'); +} + +export class CustomSystemsEngine { + private readonly cache = new Map(); + private readonly streamJobs = new Map(); + private readonly bgTimers = new Map(); + private readonly healthListeners = new Set<(snapshot: ServerSystemSnapshot) => void>(); + + constructor( + private readonly sshPool: SSHPool, + private readonly configManager: ConfigManager, + private readonly vaultService: VaultService, + private readonly ptyManager: PTYManager, + private readonly wsHub: WsHub, + ) {} + + onHealthSnapshot(listener: (snapshot: ServerSystemSnapshot) => void): () => void { + this.healthListeners.add(listener); + return () => { + this.healthListeners.delete(listener); + }; + } + + getStreamReplayFrames(jobId: string): ServerWsFrame[] { + const job = this.streamJobs.get(jobId); + return job ? [...job.frames] : []; + } + + cancelStream(jobId: string): boolean { + const job = this.streamJobs.get(jobId); + if (!job || job.done) return false; + job.abort(); + return true; + } + + invalidateCache(serverId?: string, systemId?: string): void { + for (const key of [...this.cache.keys()]) { + const [sId, sysId] = key.split(':'); + if (serverId && sId !== serverId) continue; + if (systemId && sysId !== systemId) continue; + this.cache.delete(key); + } + } + + listSystemsOverview(): Array<{ + system: SystemConfig; + attachedServers: Array<{ serverId: string; serverName: string; params: Record }>; + }> { + const systems = this.configManager.listSystems(); + const servers = this.configManager.listServers(); + + return systems.map((system) => { + const attachedServers: Array<{ + serverId: string; + serverName: string; + params: Record; + }> = []; + for (const srv of servers) { + const att = srv.systems.find((a) => a.systemId === system.id); + if (att) { + attachedServers.push({ + serverId: srv.id, + serverName: srv.name, + params: this.resolveParams(system, att.params), + }); + } + } + return { system, attachedServers }; + }); + } + + async getSystemAcrossServers( + systemId: string, + opts: { serverId?: string; forceRefresh?: boolean } = {}, + ): Promise<{ system: SystemConfig; snapshots: ServerSystemSnapshot[] }> { + const system = this.configManager.getSystem(systemId); + if (!system) { + throw new Error(`Unknown system "${systemId}"`); + } + + const targets = this.configManager + .listServers() + .filter((s) => s.enabled && s.systems.some((a) => a.systemId === systemId)) + .filter((s) => !opts.serverId || s.id === opts.serverId); + + const snapshots = await Promise.all( + targets.map((srv) => + this.getServerSystem(srv.id, systemId, { forceRefresh: opts.forceRefresh }), + ), + ); + + return { system, snapshots }; + } + + async getServerSystem( + serverId: string, + systemId: string, + opts: { forceRefresh?: boolean } = {}, + ): Promise { + const system = this.configManager.getSystem(systemId); + const server = this.configManager.getServer(serverId); + if (!system || !server) { + throw new Error(`Unknown server "${serverId}" or system "${systemId}"`); + } + const attachment = server.systems.find((a) => a.systemId === systemId); + if (!attachment) { + throw new Error(`System "${systemId}" is not attached to server "${serverId}"`); + } + + const params = this.resolveParams(system, attachment.params); + const cacheKey = `${serverId}:${systemId}`; + const existing = this.cache.get(cacheKey); + const ttlMs = system.cacheTtlSec * 1000; + const now = Date.now(); + + if (!opts.forceRefresh && existing && ttlMs > 0 && now - existing.fetchedAt < ttlMs) { + return { ...existing, cached: true }; + } + + try { + const items = await this.discoverAndInspectItems(server, system, attachment, params); + const snapshot: ServerSystemSnapshot = { + serverId, + systemId, + fetchedAt: Date.now(), + cached: false, + params, + items, + systemHealth: rollupHealth( + items.map((i) => i.status.health), + 'ok', + ), + }; + this.cache.set(cacheKey, snapshot); + this.emitHealth(snapshot); + return snapshot; + } catch (err) { + const snapshot: ServerSystemSnapshot = { + serverId, + systemId, + fetchedAt: Date.now(), + cached: false, + error: err instanceof Error ? err.message : String(err), + params, + items: [], + systemHealth: 'down', + }; + return snapshot; + } + } + + async executeAction(params: { + serverId: string; + systemId: string; + actionId: string; + itemName?: string; + subItemName?: string; + cols?: number; + rows?: number; + }): Promise { + const system = this.configManager.getSystem(params.systemId); + const server = this.configManager.getServer(params.serverId); + if (!system || !server) { + throw new Error(`Unknown server "${params.serverId}" or system "${params.systemId}"`); + } + const attachment = server.systems.find((a) => a.systemId === system.id); + if (!attachment) { + throw new Error(`System "${system.id}" is not attached to server "${server.id}"`); + } + const action = system.actions.find((a) => a.id === params.actionId); + if (!action) { + throw new Error(`Action "${params.actionId}" not found in system "${system.id}"`); + } + + const resolvedParams = this.resolveParams(system, attachment.params); + let item: DiscoveredSystemItem | undefined; + + if (action.scope === 'item' || action.scope === 'subitem') { + if (!params.itemName) { + throw new Error(`Action "${action.id}" requires itemName`); + } + const snap = await this.getServerSystem(server.id, system.id); + item = snap.items.find((i) => i.name === params.itemName); + if (!item) { + throw new Error(`Item "${params.itemName}" not found under ${server.id}/${system.id}`); + } + if (action.scope === 'subitem' && !params.subItemName) { + throw new Error(`Action "${action.id}" requires subItemName`); + } + } + + const env = this.buildExecutionEnv( + server.id, + system.id, + resolvedParams, + item, + params.subItemName, + ); + + const execCmd = item?.dir + ? `cd -- ${posixSingleQuote(item.dir)} && ${action.command}` + : action.command; + + if (action.mode === 'oneshot') { + const res = await this.sshPool.exec(server.id, execCmd, { + env, + sudo: action.sudo, + timeoutMs: 120_000, + }); + this.invalidateCache(server.id, system.id); + return { + mode: 'oneshot', + exitCode: res.exitCode, + stdout: res.stdout, + stderr: res.stderr, + durationMs: res.durationMs, + }; + } + + if (action.mode === 'interactive') { + const session = await this.ptyManager.openSession({ + serverId: server.id, + cwd: item?.dir, + command: action.command, + env, + sudo: action.sudo, + cols: params.cols, + rows: params.rows, + title: `${system.id}/${item?.name ?? server.id}/${params.subItemName ?? action.id}`, + }); + this.invalidateCache(server.id, system.id); + return { mode: 'interactive', session }; + } + + // Stream mode + const jobId = `stream-${crypto.randomBytes(6).toString('hex')}`; + const handle = await this.sshPool.execStream(server.id, execCmd, { + env, + sudo: action.sudo, + }); + + const job: ActiveStreamJob = { + jobId, + serverId: server.id, + systemId: system.id, + frames: [], + bufferBytes: 0, + done: false, + abort: handle.abort, + }; + this.streamJobs.set(jobId, job); + + const pushFrame = (stream: 'stdout' | 'stderr' | 'meta', data: string) => { + const frame: ServerWsFrame = { type: 'stream:chunk', jobId, stream, data }; + const bytes = Buffer.byteLength(data, 'utf8'); + job.frames.push(frame); + job.bufferBytes += bytes; + while (job.bufferBytes > MAX_STREAM_REPLAY_BYTES && job.frames.length > 0) { + const dropped = job.frames.shift()!; + if (dropped.type === 'stream:chunk') { + job.bufferBytes -= Buffer.byteLength(dropped.data, 'utf8'); + } + } + this.wsHub.broadcastChannel(WS_CHANNELS.stream(jobId), frame); + }; + + pushFrame( + 'meta', + JSON.stringify({ + event: 'start', + serverId: server.id, + systemId: system.id, + actionId: action.id, + item: item?.name, + subItem: params.subItemName, + }), + ); + + handle.channel.on('data', (chunk: Buffer) => { + pushFrame('stdout', chunk.toString('utf8')); + }); + handle.channel.stderr?.on('data', (chunk: Buffer) => { + pushFrame('stderr', chunk.toString('utf8')); + }); + + void handle.done + .then(({ exitCode, signal }) => { + job.done = true; + this.invalidateCache(server.id, system.id); + pushFrame('meta', JSON.stringify({ event: 'exit', exitCode, signal })); + this.pruneStreamJobs(); + }) + .catch((err) => { + job.done = true; + this.invalidateCache(server.id, system.id); + pushFrame( + 'meta', + JSON.stringify({ + event: 'error', + message: err instanceof Error ? err.message : String(err), + }), + ); + this.pruneStreamJobs(); + }); + + return { mode: 'stream', jobId }; + } + + attachSystemToServer( + serverId: string, + systemId: string, + params: Record, + ): ServerConfig { + const system = this.configManager.getSystem(systemId); + const server = this.configManager.getServer(serverId); + if (!system || !server) { + throw new Error(`Unknown server "${serverId}" or system "${systemId}"`); + } + + const existing = server.systems.find((a) => a.systemId === systemId); + const nextSystems = existing + ? server.systems.map((a) => (a.systemId === systemId ? { ...a, params } : a)) + : [...server.systems, { systemId, params, itemOverrides: {} }]; + + const updated: ServerConfig = { ...server, systems: nextSystems }; + this.configManager.saveConfigText( + `servers/${server.id}.json`, + JSON.stringify(updated, null, 2), + 'ui', + `Attached system "${systemId}" to "${server.id}"`, + ); + this.invalidateCache(serverId, systemId); + this.syncBackgroundChecks(); + return updated; + } + + detachSystemFromServer(serverId: string, systemId: string): ServerConfig { + const server = this.configManager.getServer(serverId); + if (!server) { + throw new Error(`Unknown server "${serverId}"`); + } + const updated: ServerConfig = { + ...server, + systems: server.systems.filter((a) => a.systemId !== systemId), + }; + this.configManager.saveConfigText( + `servers/${server.id}.json`, + JSON.stringify(updated, null, 2), + 'ui', + `Detached system "${systemId}" from "${server.id}"`, + ); + this.invalidateCache(serverId, systemId); + this.syncBackgroundChecks(); + return updated; + } + + updateItemActiveFiles( + serverId: string, + systemId: string, + itemName: string, + activeFiles: string[], + ): ServerConfig { + const server = this.configManager.getServer(serverId); + if (!server) { + throw new Error(`Unknown server "${serverId}"`); + } + const cleanFiles = activeFiles.map((f) => f.trim()).filter(Boolean); + if (cleanFiles.length === 0) { + throw new Error('At least one active file must be selected'); + } + for (const file of cleanFiles) { + if (!isValidRelativeOverlayFile(file)) { + throw new Error(`Invalid overlay filename: "${file}"`); + } + } + + const hasAtt = server.systems.some((a) => a.systemId === systemId); + if (!hasAtt) { + throw new Error(`System "${systemId}" is not attached to server "${serverId}"`); + } + + const updated: ServerConfig = { + ...server, + systems: server.systems.map((att) => + att.systemId === systemId + ? { + ...att, + itemOverrides: { + ...att.itemOverrides, + [itemName]: { + ...(att.itemOverrides[itemName] ?? {}), + activeFiles: cleanFiles, + }, + }, + } + : att, + ), + }; + + this.configManager.saveConfigText( + `servers/${server.id}.json`, + JSON.stringify(updated, null, 2), + 'ui', + `Updated activeFiles for ${systemId}/${itemName}`, + ); + this.invalidateCache(serverId, systemId); + return updated; + } + + syncBackgroundChecks(): void { + this.stopBackgroundChecks(); + if (this.vaultService.state !== 'unlocked') return; + + for (const server of this.configManager.listServers()) { + if (!server.enabled) continue; + for (const att of server.systems) { + const sys = this.configManager.getSystem(att.systemId); + if (!sys?.backgroundCheckSec) continue; + const key = `${server.id}:${sys.id}`; + const timer = setInterval(() => { + if (this.vaultService.state !== 'unlocked') return; + void this.getServerSystem(server.id, sys.id, { forceRefresh: true }).catch( + () => undefined, + ); + }, sys.backgroundCheckSec * 1000); + timer.unref(); + this.bgTimers.set(key, timer); + } + } + } + + stopBackgroundChecks(): void { + for (const timer of this.bgTimers.values()) { + clearInterval(timer); + } + this.bgTimers.clear(); + } + + cancelAllStreams(): void { + for (const job of this.streamJobs.values()) { + if (!job.done) { + job.done = true; + job.abort(); + } + } + } + + close(): void { + this.stopBackgroundChecks(); + this.cancelAllStreams(); + this.cache.clear(); + } + + private async discoverAndInspectItems( + server: ServerConfig, + system: SystemConfig, + attachment: ServerConfig['systems'][number], + params: Record, + ): Promise { + const baseEnv = this.buildExecutionEnv(server.id, system.id, params); + + if (system.discovery.type === 'folder-scan') { + const rawRoots = params[system.discovery.rootsParam]; + const roots = Array.isArray(rawRoots) + ? rawRoots.map((v) => String(v).trim()).filter(Boolean) + : typeof rawRoots === 'string' && rawRoots.trim() + ? [rawRoots.trim()] + : []; + if (roots.length === 0) return []; + + const script = buildFolderScanScript( + roots, + system.discovery.maxDepth, + system.discovery.matchFiles, + ); + const scanRes = await this.sshPool.exec(server.id, script, { env: baseEnv }); + const rawMatches = parseFolderScanOutput(scanRes.stdout); + + const matchRegexes = system.discovery.matchFiles.map(globToRegExp); + const selectableRegexes = ( + system.discovery.selectableFiles ?? system.discovery.matchFiles + ).map(globToRegExp); + const editableRegexes = system.editableFiles + .filter((p) => !p.includes('/')) + .map(globToRegExp); + + const usedNames = new Map(); + const items: DiscoveredSystemItem[] = []; + + for (const m of rawMatches) { + const matchedFiles = m.files.filter((f) => matchRegexes.some((re) => re.test(f))); + if (matchedFiles.length === 0) continue; + + let baseName = path.posix.basename(m.dir) || 'root'; + const seenCount = (usedNames.get(baseName) ?? 0) + 1; + usedNames.set(baseName, seenCount); + if (seenCount > 1) { + baseName = `${baseName}-${seenCount}`; + } + + const selectableFiles = m.files.filter((f) => selectableRegexes.some((re) => re.test(f))); + const editableFiles = m.files + .filter((f) => editableRegexes.some((re) => re.test(f))) + .map((f) => path.posix.join(m.dir, f)); + + const overrideFiles = attachment.itemOverrides[baseName]?.activeFiles?.filter((f) => + isValidRelativeOverlayFile(f), + ); + const activeFiles = + overrideFiles && overrideFiles.length > 0 + ? overrideFiles + : [matchedFiles[0]!]; + + const draftItem: DiscoveredSystemItem = { + name: baseName, + dir: m.dir, + activeFiles, + selectableFiles: selectableFiles.length > 0 ? selectableFiles : activeFiles, + editableFiles, + status: { + health: 'unknown', + subItems: [], + rawSummary: '', + exitCode: null, + }, + }; + + const itemEnv = this.buildExecutionEnv(server.id, system.id, params, draftItem); + const statusRes = await this.sshPool.exec( + server.id, + `cd -- ${posixSingleQuote(m.dir)} && ${system.status.command}`, + { env: itemEnv }, + ); + draftItem.status = parseStatusOutput( + statusRes.stdout, + statusRes.stderr, + statusRes.exitCode, + system.status, + ); + items.push(draftItem); + } + + return items; + } + + // command discovery + const discRes = await this.sshPool.exec(server.id, system.discovery.command, { + env: baseEnv, + }); + const names = parseDiscoveryOutput(discRes.stdout, system.discovery.parser); + const items: DiscoveredSystemItem[] = []; + + for (const itemName of names) { + const draftItem: DiscoveredSystemItem = { + name: itemName, + activeFiles: [], + selectableFiles: [], + editableFiles: [], + status: { + health: 'unknown', + subItems: [], + rawSummary: '', + exitCode: null, + }, + }; + const itemEnv = this.buildExecutionEnv(server.id, system.id, params, draftItem); + const statusRes = await this.sshPool.exec(server.id, system.status.command, { + env: itemEnv, + }); + draftItem.status = parseStatusOutput( + statusRes.stdout, + statusRes.stderr, + statusRes.exitCode, + system.status, + ); + items.push(draftItem); + } + + return items; + } + + private resolveParams( + system: SystemConfig, + supplied: Record, + ): Record { + const out: Record = {}; + for (const def of system.params) { + if (supplied[def.name] !== undefined) { + out[def.name] = supplied[def.name]; + } else if (def.default !== undefined) { + out[def.name] = structuredClone(def.default); + } + } + return out; + } + + private buildExecutionEnv( + serverId: string, + systemId: string, + params: Record, + item?: DiscoveredSystemItem, + subItem?: string, + ): Record { + const env: Record = { + GCOORD_SERVER_ID: serverId, + GCOORD_SYSTEM_ID: systemId, + }; + + for (const [k, v] of Object.entries(params)) { + const envKey = `GCOORD_PARAM_${k.replace(/[^A-Za-z0-9]/g, '_').toUpperCase()}`; + env[envKey] = Array.isArray(v) ? v.map((x) => String(x)).join('\n') : String(v ?? ''); + } + + if (item) { + env.GCOORD_ITEM_NAME = item.name; + if (item.dir) { + env.GCOORD_ITEM_DIR = item.dir; + } + if (item.activeFiles.length > 0) { + const validFiles = item.activeFiles.filter(isValidRelativeOverlayFile); + if (validFiles.length > 0) { + env.GCOORD_ITEM_FILE = item.dir + ? path.posix.join(item.dir, validFiles[0]!) + : validFiles[0]!; + env.GCOORD_ITEM_FILES = validFiles.join(' '); + env.GCOORD_COMPOSE_FILES = validFiles.map((f) => `-f ${f}`).join(' '); + } + } + } + + if (subItem) { + env.GCOORD_SUBITEM = subItem; + } + + return env; + } + + private emitHealth(snapshot: ServerSystemSnapshot): void { + for (const listener of this.healthListeners) { + try { + listener(snapshot); + } catch { + // Isolate subscriber errors + } + } + } + + private pruneStreamJobs(): void { + const doneJobs = [...this.streamJobs.values()].filter((j) => j.done); + while (doneJobs.length > MAX_RETAINED_DONE_STREAMS) { + const oldest = doneJobs.shift()!; + this.streamJobs.delete(oldest.jobId); + } + } +} + +export function getEditableFileHintPaths( + system: SystemConfig, + item: DiscoveredSystemItem, +): string[] { + if (item.editableFiles.length > 0) return item.editableFiles; + return system.editableFiles.filter((p) => p.startsWith('/')); +}