Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(data): add Data Manager page for storage visibility and management
Adam Eivyba4d4aa927d6
diff --git a/client/src/App.jsx b/client/src/App.jsxindex 98e67b58a4..5ee7e3f2a9 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -19,6 +19,7 @@ import Shell from './pages/Shell';import BrowserPage from './pages/Browser';import Jira from './pages/Jira';import JiraReports from './pages/JiraReports';+import DataManager from './pages/DataManager';import Insights from './pages/Insights';import Instances from './pages/Instances';import MeatSpace from './pages/MeatSpace';@@ -136,6 +137,7 @@ export default function App() {<Route path="devtools/jira/reports" element={<JiraReports />} /><Route path="city" element={<CyberCity />} /><Route path="city/settings" element={<CyberCity />} />+ <Route path="data" element={<DataManager />} /><Route path="character" element={<CharacterSheet />} /><Route path="agents" element={<Agents />} /><Route path="agents/:agentId" element={<Agents />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 5a223c5095..8d55f4f18d 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -67,7 +67,8 @@ import {FilePen,MessageCircle,Swords,- Image as ImageIcon+ Image as ImageIcon,+ HardDrive} from 'lucide-react';/* global __APP_VERSION__ */import Logo from './Logo';@@ -158,6 +159,7 @@ const navItems = [{ to: '/devtools/usage', label: 'Usage', icon: BarChart3 }]},+ { to: '/data', label: 'Data', icon: HardDrive, single: true },{label: 'Digital Twin',icon: Heart,diff --git a/client/src/pages/DataManager.jsx b/client/src/pages/DataManager.jsxnew file mode 100644index 0000000000..e4b491d2bc--- /dev/null+++ b/client/src/pages/DataManager.jsx@@ -0,0 +1,337 @@+import { useState, useEffect, useCallback } from 'react';+import { HardDrive, RefreshCw, Archive, Trash2, ChevronDown, ChevronRight, FolderOpen, File, AlertTriangle, Download, Package } from 'lucide-react';+import * as api from '../services/api';++function formatBytes(bytes) {+ if (!bytes || bytes === 0) return '0 B';+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];+ const i = Math.floor(Math.log(bytes) / Math.log(1024));+ return `${(bytes / Math.pow(1024, i)).toFixed(i > 1 ? 1 : 0)} ${units[i]}`;+}++function SizeBar({ size, maxSize }) {+ const pct = maxSize > 0 ? Math.max(1, (size / maxSize) * 100) : 0;+ const color = pct > 60 ? 'bg-port-warning' : pct > 30 ? 'bg-port-accent' : 'bg-port-success';+ return (+ <div className="w-full h-1.5 bg-port-border/50 rounded-full overflow-hidden">+ <div className={`h-full ${color} rounded-full transition-all`} style={{ width: `${Math.min(pct, 100)}%` }} />+ </div>+ );+}++function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPurge, archiving, purging }) {+ return (+ <div className="border border-port-border rounded-lg overflow-hidden">+ <button+ onClick={() => onExpand(cat.key)}+ className="w-full flex items-center gap-3 p-3 hover:bg-port-card/50 transition-colors text-left"+ >+ {expanded ? <ChevronDown size={14} className="text-gray-500 shrink-0" /> : <ChevronRight size={14} className="text-gray-500 shrink-0" />}+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium text-white">{cat.label}</span>+ <span className="text-xs text-gray-500">{cat.description}</span>+ </div>+ <div className="mt-1">+ <SizeBar size={cat.size} maxSize={maxSize} />+ </div>+ </div>+ <div className="text-right shrink-0 ml-2">+ <div className="text-sm font-mono text-white">{formatBytes(cat.size)}</div>+ <div className="text-xs text-gray-500">{cat.fileCount.toLocaleString()} files</div>+ </div>+ </button>++ {expanded && (+ <div className="border-t border-port-border bg-port-bg/50">+ {/* Actions */}+ <div className="flex items-center gap-2 p-3 border-b border-port-border/50">+ {cat.archivable && (+ <button+ onClick={() => onArchive(cat.key)}+ disabled={archiving}+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium bg-port-accent/10 text-port-accent rounded hover:bg-port-accent/20 transition-colors disabled:opacity-50"+ >+ <Archive size={12} />+ {archiving ? 'Archiving...' : 'Archive'}+ </button>+ )}+ {cat.deletable && (+ <button+ onClick={() => onPurge(cat.key)}+ disabled={purging}+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium bg-port-error/10 text-port-error rounded hover:bg-port-error/20 transition-colors disabled:opacity-50"+ >+ <Trash2 size={12} />+ {purging ? 'Purging...' : 'Purge'}+ </button>+ )}+ {!cat.archivable && !cat.deletable && (+ <span className="text-xs text-gray-500">This category is protected and cannot be archived or deleted</span>+ )}+ </div>++ {/* Detail items */}+ {detail ? (+ <div className="max-h-64 overflow-auto">+ {detail.items.length === 0 ? (+ <div className="p-3 text-xs text-gray-500">Empty</div>+ ) : (+ <table className="w-full text-xs">+ <thead>+ <tr className="text-gray-500 border-b border-port-border/30">+ <th className="text-left p-2 pl-3 font-medium">Name</th>+ <th className="text-right p-2 font-medium">Size</th>+ <th className="text-right p-2 pr-3 font-medium">Files</th>+ </tr>+ </thead>+ <tbody>+ {detail.items.map(item => (+ <tr key={item.name} className="border-b border-port-border/20 hover:bg-port-card/30">+ <td className="p-2 pl-3 text-gray-300 flex items-center gap-1.5">+ {item.type === 'directory' ? <FolderOpen size={11} className="text-port-accent shrink-0" /> : <File size={11} className="text-gray-500 shrink-0" />}+ <span className="truncate">{item.name}</span>+ </td>+ <td className="p-2 text-right text-gray-400 font-mono">{formatBytes(item.size)}</td>+ <td className="p-2 pr-3 text-right text-gray-500">{item.type === 'directory' ? item.fileCount?.toLocaleString() : '—'}</td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ ) : (+ <div className="p-3 flex items-center gap-2 text-xs text-gray-500">+ <RefreshCw size={11} className="animate-spin" /> Loading...+ </div>+ )}+ </div>+ )}+ </div>+ );+}++function BackupsSection({ backups, loading, onDelete, onRefresh }) {+ if (loading) return null;+ if (!backups.length) return null;++ return (+ <div className="mt-6">+ <div className="flex items-center gap-2 mb-3">+ <Package size={16} className="text-port-accent" />+ <h2 className="text-sm font-semibold text-white">Backup Archives</h2>+ <span className="text-xs text-gray-500">{backups.length} archives</span>+ </div>+ <div className="border border-port-border rounded-lg overflow-hidden">+ <table className="w-full text-xs">+ <thead>+ <tr className="text-gray-500 border-b border-port-border/30 bg-port-card/30">+ <th className="text-left p-2 pl-3 font-medium">Archive</th>+ <th className="text-right p-2 font-medium">Size</th>+ <th className="text-right p-2 font-medium">Created</th>+ <th className="text-right p-2 pr-3 font-medium"></th>+ </tr>+ </thead>+ <tbody>+ {backups.map(b => (+ <tr key={b.name} className="border-b border-port-border/20 hover:bg-port-card/30">+ <td className="p-2 pl-3 text-gray-300 flex items-center gap-1.5">+ <Archive size={11} className="text-port-accent shrink-0" />+ <span className="truncate">{b.name}</span>+ </td>+ <td className="p-2 text-right text-gray-400 font-mono">{formatBytes(b.size)}</td>+ <td className="p-2 text-right text-gray-500">{b.created ? new Date(b.created).toLocaleDateString() : '—'}</td>+ <td className="p-2 pr-3 text-right">+ <button+ onClick={() => onDelete(b.name)}+ className="text-gray-500 hover:text-port-error transition-colors"+ title="Delete backup"+ >+ <Trash2 size={12} />+ </button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ );+}++export default function DataManager() {+ const [overview, setOverview] = useState(null);+ const [backups, setBackups] = useState([]);+ const [loading, setLoading] = useState(true);+ const [expandedCat, setExpandedCat] = useState(null);+ const [detail, setDetail] = useState(null);+ const [archiving, setArchiving] = useState(null);+ const [purging, setPurging] = useState(null);+ const [confirmPurge, setConfirmPurge] = useState(null);++ const fetchOverview = useCallback(async () => {+ const [data, bk] = await Promise.all([+ api.getDataOverview().catch(() => null),+ api.getDataBackups().catch(() => [])+ ]);+ setOverview(data);+ setBackups(bk);+ setLoading(false);+ }, []);++ useEffect(() => { fetchOverview(); }, [fetchOverview]);++ const handleExpand = async (key) => {+ if (expandedCat === key) {+ setExpandedCat(null);+ setDetail(null);+ return;+ }+ setExpandedCat(key);+ setDetail(null);+ const d = await api.getDataCategory(key).catch(() => null);+ setDetail(d);+ };++ const handleArchive = async (key) => {+ setArchiving(key);+ const result = await api.archiveDataCategory(key).catch(err => {+ console.error(`Archive failed: ${err.message}`);+ return null;+ });+ setArchiving(null);+ if (result) {+ fetchOverview();+ if (expandedCat === key) {+ const d = await api.getDataCategory(key).catch(() => null);+ setDetail(d);+ }+ }+ };++ const handlePurge = (key) => {+ if (confirmPurge === key) {+ executePurge(key);+ } else {+ setConfirmPurge(key);+ setTimeout(() => setConfirmPurge(null), 5000);+ }+ };++ const executePurge = async (key) => {+ setPurging(key);+ setConfirmPurge(null);+ await api.purgeDataCategory(key).catch(err => {+ console.error(`Purge failed: ${err.message}`);+ });+ setPurging(null);+ fetchOverview();+ if (expandedCat === key) {+ const d = await api.getDataCategory(key).catch(() => null);+ setDetail(d);+ }+ };++ const handleDeleteBackup = async (filename) => {+ await api.deleteDataBackup(filename).catch(() => null);+ setBackups(prev => prev.filter(b => b.name !== filename));+ };++ if (loading) {+ return (+ <div className="flex items-center justify-center h-full">+ <RefreshCw className="w-8 h-8 text-port-accent animate-spin" />+ </div>+ );+ }++ const maxSize = overview?.categories?.[0]?.size || 1;++ return (+ <div className="flex flex-col h-full">+ {/* Header */}+ <div className="flex items-center justify-between p-4 border-b border-port-border">+ <div className="flex items-center gap-3">+ <HardDrive className="w-8 h-8 text-port-accent" />+ <div>+ <h1 className="text-xl font-bold text-white">Data Manager</h1>+ <p className="text-sm text-gray-500">Storage visibility, archiving, and cleanup</p>+ </div>+ </div>+ <div className="flex items-center gap-4">+ <div className="text-right">+ <div className="text-lg font-mono font-bold text-white">{formatBytes(overview?.totalSize || 0)}</div>+ <div className="text-xs text-gray-500">total in <code className="text-gray-400">{overview?.dataDir}/</code></div>+ </div>+ <button+ onClick={() => { setLoading(true); fetchOverview(); }}+ className="p-2 text-gray-400 hover:text-white hover:bg-port-card rounded transition-colors"+ title="Refresh"+ >+ <RefreshCw size={16} />+ </button>+ </div>+ </div>++ {/* Content */}+ <div className="flex-1 overflow-auto p-4">+ {/* Summary cards */}+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-4">+ <div className="bg-port-card rounded-lg p-3 border border-port-border">+ <div className="text-xs text-gray-500 mb-1">Categories</div>+ <div className="text-lg font-bold text-white">{overview?.categories?.length || 0}</div>+ </div>+ <div className="bg-port-card rounded-lg p-3 border border-port-border">+ <div className="text-xs text-gray-500 mb-1">Total Size</div>+ <div className="text-lg font-bold text-white">{formatBytes(overview?.totalSize || 0)}</div>+ </div>+ <div className="bg-port-card rounded-lg p-3 border border-port-border">+ <div className="text-xs text-gray-500 mb-1">Largest</div>+ <div className="text-lg font-bold text-white">{overview?.categories?.[0]?.label || '—'}</div>+ <div className="text-xs text-gray-500">{formatBytes(overview?.categories?.[0]?.size || 0)}</div>+ </div>+ <div className="bg-port-card rounded-lg p-3 border border-port-border">+ <div className="text-xs text-gray-500 mb-1">Backups</div>+ <div className="text-lg font-bold text-white">{backups.length}</div>+ </div>+ </div>++ {/* Category list */}+ <div className="space-y-2">+ {overview?.categories?.map(cat => (+ <CategoryRow+ key={cat.key}+ cat={cat}+ maxSize={maxSize}+ expanded={expandedCat === cat.key}+ detail={expandedCat === cat.key ? detail : null}+ onExpand={handleExpand}+ onArchive={handleArchive}+ onPurge={confirmPurge === cat.key+ ? handlePurge+ : handlePurge}+ archiving={archiving === cat.key}+ purging={purging === cat.key}+ />+ ))}+ </div>++ {/* Confirm purge banner */}+ {confirmPurge && (+ <div className="fixed bottom-4 left-1/2 -translate-x-1/2 bg-port-error/90 text-white px-4 py-2 rounded-lg flex items-center gap-3 text-sm shadow-lg z-50">+ <AlertTriangle size={16} />+ <span>Click Purge again to confirm deletion of <strong>{confirmPurge}</strong></span>+ </div>+ )}++ {/* Backups section */}+ <BackupsSection+ backups={backups}+ loading={loading}+ onDelete={handleDeleteBackup}+ onRefresh={fetchOverview}+ />+ </div>+ </div>+ );+}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex ec3b253b80..b3d03374c2 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1755,6 +1755,14 @@ export const connectPeer = (id) => request(`/instances/peers/${id}/connect`, { mexport const probePeer = (id) => request(`/instances/peers/${id}/probe`, { method: 'POST' });export const queryPeer = (id, path) => request(`/instances/peers/${id}/query?path=${encodeURIComponent(path)}`);+// Data Manager+export const getDataOverview = () => request('/data');+export const getDataCategory = (key) => request(`/data/${key}`);+export const archiveDataCategory = (key, opts) => request(`/data/${key}/archive`, { method: 'POST', body: JSON.stringify(opts || {}) });+export const purgeDataCategory = (key, opts) => request(`/data/${key}`, { method: 'DELETE', body: JSON.stringify(opts || {}) });+export const getDataBackups = () => request('/data/backups');+export const deleteDataBackup = (filename) => request(`/data/backups/${filename}`, { method: 'DELETE' });+// GSD (Get Stuff Done) Integrationexport const getGsdProjects = () => request('/cos/gsd/projects');export const getGsdProject = (appId) => request(`/cos/gsd/projects/${appId}`);diff --git a/server/index.js b/server/index.jsindex 885c7ebfb4..37eb105a97 100644--- a/server/index.js+++ b/server/index.js@@ -48,6 +48,7 @@ import moltworldToolsRoutes from './routes/moltworldTools.js';import moltworldWsRoutes from './routes/moltworldWs.js';import insightsRoutes from './routes/insights.js';import datadogRoutes from './routes/datadog.js';+import dataManagerRoutes from './routes/dataManager.js';import jiraRoutes from './routes/jira.js';import autobiographyRoutes from './routes/autobiography.js';import backupRoutes from './routes/backup.js';@@ -252,6 +253,7 @@ app.use('/api/digital-twin/autobiography', autobiographyRoutes);app.use('/api/digital-twin', digitalTwinRoutes);app.use('/api/lmstudio', lmstudioRoutes);app.use('/api/browser', browserRoutes);+app.use('/api/data', dataManagerRoutes);app.use('/api/datadog', datadogRoutes);app.use('/api/jira', jiraRoutes);app.use('/api/health', appleHealthRoutes);diff --git a/server/routes/dataManager.js b/server/routes/dataManager.jsnew file mode 100644index 0000000000..77871afdeb--- /dev/null+++ b/server/routes/dataManager.js@@ -0,0 +1,53 @@+import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import {+ getDataOverview,+ getCategoryDetail,+ archiveCategory,+ purgeCategory,+ getBackups,+ deleteBackup+} from '../services/dataManager.js';++const router = Router();++// GET /api/data — overview of all data categories+router.get('/', asyncHandler(async (req, res) => {+ const overview = await getDataOverview();+ res.json(overview);+}));++// GET /api/data/backups — list all backup archives+router.get('/backups', asyncHandler(async (req, res) => {+ const backups = await getBackups();+ res.json(backups);+}));++// GET /api/data/:category — detailed breakdown of a category+router.get('/:category', asyncHandler(async (req, res) => {+ const detail = await getCategoryDetail(req.params.category);+ if (!detail) throw new ServerError('Category not found', { status: 404, code: 'NOT_FOUND' });+ res.json(detail);+}));++// POST /api/data/:category/archive — archive a category to backup+router.post('/:category/archive', asyncHandler(async (req, res) => {+ const { daysToKeep } = req.body || {};+ const result = await archiveCategory(req.params.category, { daysToKeep });+ res.json(result);+}));++// DELETE /api/data/:category — purge a category's contents+router.delete('/:category', asyncHandler(async (req, res) => {+ const { subPath } = req.body || {};+ const result = await purgeCategory(req.params.category, { subPath });+ res.json(result);+}));++// DELETE /api/data/backups/:filename — delete a backup file+router.delete('/backups/:filename', asyncHandler(async (req, res) => {+ const result = await deleteBackup(req.params.filename);+ res.json(result);+}));++export default router;diff --git a/server/services/dataManager.js b/server/services/dataManager.jsnew file mode 100644index 0000000000..ccee788cc5--- /dev/null+++ b/server/services/dataManager.js@@ -0,0 +1,288 @@+import { readdir, stat, rm } from 'fs/promises';+import { join, relative } from 'path';+import { existsSync } from 'fs';+import { execSync } from 'child_process';++const DATA_DIR = join(process.cwd(), 'data');++// Category definitions with display names and archivability+const CATEGORIES = {+ 'browser-profile': { label: 'Browser Profile', description: 'Chrome/Chromium browser data', archivable: false, deletable: true },+ 'repos': { label: 'Cloned Repos', description: 'Git repositories cloned by agents', archivable: false, deletable: true },+ 'health': { label: 'Apple Health', description: 'Daily health JSON snapshots', archivable: true, deletable: false },+ 'meatspace': { label: 'MeatSpace', description: 'Body metrics, blood tests, eyes', archivable: true, deletable: false },+ 'autofixer': { label: 'Autofixer', description: 'Autofixer run data', archivable: true, deletable: true },+ 'db-dumps': { label: 'DB Dumps', description: 'PostgreSQL database backups', archivable: true, deletable: true },+ 'screenshots': { label: 'Screenshots', description: 'Task-related screenshots', archivable: true, deletable: true },+ 'cos': { label: 'Chief of Staff', description: 'Agent data, reports, memories', archivable: true, deletable: false },+ 'runs': { label: 'AI Runs', description: 'Agent run logs and outputs', archivable: true, deletable: true },+ 'images': { label: 'Images', description: 'Uploaded and generated images', archivable: true, deletable: true },+ 'calendar': { label: 'Calendar', description: 'Calendar sync data', archivable: true, deletable: false },+ 'digital-twin': { label: 'Digital Twin', description: 'Identity, goals, character data', archivable: true, deletable: false },+ 'messages': { label: 'Messages', description: 'Email and messaging data', archivable: true, deletable: true },+ 'prompts': { label: 'Prompts', description: 'AI prompt templates', archivable: false, deletable: false },+ 'brain': { label: 'Brain', description: 'Brain items and sync log', archivable: true, deletable: false },+ 'agents': { label: 'Agents', description: 'Agent personality data', archivable: false, deletable: false },+ 'review': { label: 'Review', description: 'Review hub items', archivable: true, deletable: true },+ 'tools': { label: 'Tools', description: 'Tool execution data', archivable: true, deletable: true },+ 'backup': { label: 'Backups', description: 'Data backup archives', archivable: false, deletable: true },+ 'telegram': { label: 'Telegram', description: 'Telegram bot data', archivable: true, deletable: true }+};++/**+ * Get size of a directory using du (fast, accurate)+ */+function getDirSize(dirPath) {+ if (!existsSync(dirPath)) return 0;+ const output = execSync(`du -sk "${dirPath}" 2>/dev/null || echo "0"`, {+ encoding: 'utf-8',+ windowsHide: true+ }).trim();+ const kb = parseInt(output.split('\t')[0], 10) || 0;+ return kb * 1024; // bytes+}++/**+ * Count files in a directory+ */+function countFiles(dirPath) {+ if (!existsSync(dirPath)) return 0;+ const output = execSync(`find "${dirPath}" -type f 2>/dev/null | wc -l`, {+ encoding: 'utf-8',+ windowsHide: true+ }).trim();+ return parseInt(output, 10) || 0;+}++/**+ * Get overview of all data categories with sizes+ */+export async function getDataOverview() {+ const totalSize = getDirSize(DATA_DIR);++ // Get top-level items+ const entries = await readdir(DATA_DIR, { withFileTypes: true }).catch(() => []);++ const categories = [];+ let categorizedSize = 0;++ for (const entry of entries) {+ const fullPath = join(DATA_DIR, entry.name);++ if (entry.isDirectory()) {+ const size = getDirSize(fullPath);+ const fileCount = countFiles(fullPath);+ const meta = CATEGORIES[entry.name] || {+ label: entry.name,+ description: 'Unknown category',+ archivable: false,+ deletable: false+ };++ categorizedSize += size;+ categories.push({+ key: entry.name,+ path: relative(process.cwd(), fullPath),+ ...meta,+ size,+ fileCount+ });+ } else {+ // Top-level files+ const fileStat = await stat(fullPath).catch(() => null);+ if (fileStat) categorizedSize += fileStat.size;+ }+ }++ // Sort by size descending+ categories.sort((a, b) => b.size - a.size);++ // Count top-level JSON files+ const topLevelFiles = entries.filter(e => !e.isDirectory());++ return {+ totalSize,+ categorizedSize,+ topLevelFileCount: topLevelFiles.length,+ categories,+ dataDir: relative(process.cwd(), DATA_DIR)+ };+}++/**+ * Get detailed breakdown of a specific category+ */+export async function getCategoryDetail(categoryKey) {+ const dirPath = join(DATA_DIR, categoryKey);+ if (!existsSync(dirPath)) return null;++ const entries = await readdir(dirPath, { withFileTypes: true }).catch(() => []);+ const items = [];++ for (const entry of entries) {+ const fullPath = join(dirPath, entry.name);+ if (entry.isDirectory()) {+ items.push({+ name: entry.name,+ type: 'directory',+ size: getDirSize(fullPath),+ fileCount: countFiles(fullPath)+ });+ } else {+ const fileStat = await stat(fullPath).catch(() => null);+ items.push({+ name: entry.name,+ type: 'file',+ size: fileStat?.size || 0,+ modified: fileStat?.mtime?.toISOString() || null+ });+ }+ }++ items.sort((a, b) => b.size - a.size);++ const meta = CATEGORIES[categoryKey] || { label: categoryKey, archivable: false, deletable: false };++ return {+ key: categoryKey,+ ...meta,+ totalSize: getDirSize(dirPath),+ items+ };+}++/**+ * Archive a category's old data (compress into backup)+ */+export async function archiveCategory(categoryKey, options = {}) {+ const meta = CATEGORIES[categoryKey];+ if (!meta?.archivable) throw new Error(`Category "${categoryKey}" is not archivable`);++ const dirPath = join(DATA_DIR, categoryKey);+ if (!existsSync(dirPath)) throw new Error(`Category directory not found: ${categoryKey}`);++ const backupDir = join(DATA_DIR, 'backup');+ if (!existsSync(backupDir)) {+ execSync(`mkdir -p "${backupDir}"`, { windowsHide: true });+ }++ const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);+ const archiveName = `${categoryKey}-${timestamp}.tar.gz`;+ const archivePath = join(backupDir, archiveName);++ // For health data, archive everything older than cutoff (default: 1 year)+ const daysToKeep = options.daysToKeep ?? 365;++ if (categoryKey === 'health') {+ // Archive health files older than threshold+ const cutoff = new Date();+ cutoff.setDate(cutoff.getDate() - daysToKeep);+ const cutoffStr = cutoff.toISOString().slice(0, 10);++ // Find old files+ const files = await readdir(dirPath).catch(() => []);+ const oldFiles = files.filter(f => f.endsWith('.json') && f.slice(0, 10) < cutoffStr);++ if (oldFiles.length === 0) return { archived: 0, archivePath: null, message: 'No old files to archive' };++ // Create tar of old files+ const fileList = oldFiles.join('\n');+ execSync(`echo "${fileList}" | tar -czf "${archivePath}" -C "${dirPath}" -T -`, {+ windowsHide: true, timeout: 120000+ });++ // Remove archived files+ for (const f of oldFiles) {+ await rm(join(dirPath, f)).catch(() => {});+ }++ return { archived: oldFiles.length, archivePath: relative(process.cwd(), archivePath), size: getDirSize(archivePath) };+ }++ // Generic category: archive entire contents+ const sizeBefore = getDirSize(dirPath);+ execSync(`tar -czf "${archivePath}" -C "${DATA_DIR}" "${categoryKey}"`, {+ windowsHide: true, timeout: 120000+ });++ return {+ archived: countFiles(dirPath),+ archivePath: relative(process.cwd(), archivePath),+ originalSize: sizeBefore,+ archiveSize: getDirSize(archivePath)+ };+}++/**+ * Delete contents of a category (with safety checks)+ */+export async function purgeCategory(categoryKey, options = {}) {+ const meta = CATEGORIES[categoryKey];+ if (!meta?.deletable) throw new Error(`Category "${categoryKey}" is not purgeable`);++ const dirPath = join(DATA_DIR, categoryKey);+ if (!existsSync(dirPath)) throw new Error(`Category directory not found: ${categoryKey}`);++ const sizeBefore = getDirSize(dirPath);+ const filesBefore = countFiles(dirPath);++ if (options.subPath) {+ // Delete a specific subdirectory within the category+ const targetPath = join(dirPath, options.subPath);+ if (!existsSync(targetPath)) throw new Error(`Path not found: ${options.subPath}`);+ if (!targetPath.startsWith(dirPath)) throw new Error('Path traversal not allowed');+ await rm(targetPath, { recursive: true, force: true });+ } else {+ // Clear all contents but keep the directory+ const entries = await readdir(dirPath).catch(() => []);+ for (const entry of entries) {+ await rm(join(dirPath, entry), { recursive: true, force: true });+ }+ }++ const sizeAfter = getDirSize(dirPath);++ return {+ freedBytes: sizeBefore - sizeAfter,+ filesRemoved: filesBefore - countFiles(dirPath),+ category: categoryKey,+ subPath: options.subPath || null+ };+}++/**+ * Get list of existing backups+ */+export async function getBackups() {+ const backupDir = join(DATA_DIR, 'backup');+ if (!existsSync(backupDir)) return [];++ const entries = await readdir(backupDir, { withFileTypes: true }).catch(() => []);+ const backups = [];++ for (const entry of entries) {+ if (!entry.isFile()) continue;+ const fullPath = join(backupDir, entry.name);+ const fileStat = await stat(fullPath).catch(() => null);+ backups.push({+ name: entry.name,+ size: fileStat?.size || 0,+ created: fileStat?.birthtime?.toISOString() || fileStat?.mtime?.toISOString() || null+ });+ }++ backups.sort((a, b) => (b.created || '').localeCompare(a.created || ''));+ return backups;+}++/**+ * Delete a specific backup file+ */+export async function deleteBackup(filename) {+ const backupDir = join(DATA_DIR, 'backup');+ const fullPath = join(backupDir, filename);+ if (!fullPath.startsWith(backupDir)) throw new Error('Path traversal not allowed');+ if (!existsSync(fullPath)) throw new Error(`Backup not found: ${filename}`);+ await rm(fullPath);+ return { deleted: filename };+}