agent-cleandrive 0.0.0-stage → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +357 -2
- package/bin/cleandrive.js +280 -0
- package/config.example.json +35 -0
- package/docs/offload-strategy.md +132 -0
- package/lib/actions.js +263 -0
- package/lib/archives.js +242 -0
- package/lib/catalog.js +222 -0
- package/lib/offload.js +534 -0
- package/lib/projects.js +114 -0
- package/lib/scan.js +236 -0
- package/lib/server.js +261 -0
- package/lib/util.js +134 -0
- package/package.json +60 -4
- package/ui/index.html +521 -0
package/lib/archives.js
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
// Versioned project archives. Local removal is gated on verification and durable receipts.
|
|
2
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
3
|
+
import { createReadStream, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync,
|
|
4
|
+
writeFileSync, openSync, closeSync, fsyncSync, unlinkSync, rmSync, renameSync, mkdtempSync } from 'node:fs';
|
|
5
|
+
import { readdir, lstat, readlink } from 'node:fs/promises';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { DATA_DIR, loadConfig, ensureDataDir, writeJson, run, withCatalog } from './util.js';
|
|
8
|
+
import { checkRemoteDrive, sshOpts, validateTarget, remotePathRefusal } from './actions.js';
|
|
9
|
+
import { isPinned, contains } from './projects.js';
|
|
10
|
+
export const RECEIPT_EXT = '.cleandrive-archive.json';
|
|
11
|
+
const catalog = () => path.join(DATA_DIR,'archives');
|
|
12
|
+
const q = s => "'" + String(s).replace(/'/g,"'\\''") + "'";
|
|
13
|
+
const present = p => { try { lstatSync(p); return true; } catch(e) { if(e.code==='ENOENT')return false; throw e; } };
|
|
14
|
+
const idValid = id => typeof id==='string' && /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(id);
|
|
15
|
+
|
|
16
|
+
function remoteConfig(cfg) {
|
|
17
|
+
const r=cfg.remote;
|
|
18
|
+
if(!r || !/^[a-zA-Z0-9][a-zA-Z0-9.-]*$/.test(r.host||'') || (r.user && !/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(r.user))) throw Error('invalid remote host/user');
|
|
19
|
+
const bad=remotePathRefusal(r.path); if(bad) throw Error('invalid remote path: '+bad);
|
|
20
|
+
return r;
|
|
21
|
+
}
|
|
22
|
+
// No -s: stock macOS openrsync rejects it. Remote paths are remote.path (shell-inert by
|
|
23
|
+
// remotePathRefusal) plus /archives/<uuid>/payload, so they pass the remote shell unquoted.
|
|
24
|
+
// Never shell-quote them: rsync >=3.2.4 keeps the quotes literally and lands the payload
|
|
25
|
+
// under ~/'…' (the 2026-11-17 archive failure).
|
|
26
|
+
function transport(cfg) { return ['-e',['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5',...sshOpts(cfg)].map(q).join(' ')]; }
|
|
27
|
+
function dest(cfg,p) {const r=remoteConfig(cfg);return `${r.user?r.user+'@':''}${r.host}:${p}`;}
|
|
28
|
+
async function ssh(cfg, command, runner) {
|
|
29
|
+
const r=remoteConfig(cfg);
|
|
30
|
+
return runner('ssh',['-o','BatchMode=yes','-o','ConnectTimeout=5',...sshOpts(cfg),`${r.user?r.user+'@':''}${r.host}`,command],{timeoutMs:30000});
|
|
31
|
+
}
|
|
32
|
+
// A lock whose holder pid is provably gone (ESRCH) is stale — a killed run — and is
|
|
33
|
+
// cleared once. A live holder, an EPERM pid, or an unreadable/pid-less lock still blocks.
|
|
34
|
+
function staleLockContent(file) {
|
|
35
|
+
let raw; try {raw=readFileSync(file,'utf8');} catch {return null;}
|
|
36
|
+
let pid; try {pid=JSON.parse(raw).pid;} catch {return null;}
|
|
37
|
+
if(!Number.isInteger(pid) || pid<=0 || pid===process.pid)return null;
|
|
38
|
+
try {process.kill(pid,0);return null;} catch(e) {return e.code==='ESRCH'?raw:null;}
|
|
39
|
+
}
|
|
40
|
+
export function acquireLock() {
|
|
41
|
+
ensureDataDir(); const file=path.join(DATA_DIR,'archives.lock');
|
|
42
|
+
let fd;
|
|
43
|
+
for(let attempt=0;;attempt++) {
|
|
44
|
+
try {fd=openSync(file,'wx',0o600);break;} catch(e) {
|
|
45
|
+
if(e.code!=='EEXIST')throw e;
|
|
46
|
+
const stale=attempt===0 && staleLockContent(file);
|
|
47
|
+
// re-read just before unlinking so a lock another run created meanwhile is never removed
|
|
48
|
+
if(!stale || (()=>{try {return readFileSync(file,'utf8')!==stale;} catch {return false;}})())
|
|
49
|
+
throw Error('archive operation locked; inspect archives.lock before removing a stale lock');
|
|
50
|
+
try {unlinkSync(file);} catch(u) {if(u.code!=='ENOENT')throw u;}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
try {writeFileSync(fd,JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()}));fsyncSync(fd);} finally {closeSync(fd);}
|
|
54
|
+
return ()=>unlinkSync(file);
|
|
55
|
+
}
|
|
56
|
+
function syncDir(dir) {const fd=openSync(dir,'r');try {fsyncSync(fd);} finally {closeSync(fd);}}
|
|
57
|
+
function saveRecord(r) {mkdirSync(catalog(),{recursive:true});writeJson(path.join(catalog(),r.id+'.json'),r);syncDir(catalog());syncDir(DATA_DIR);}
|
|
58
|
+
function exclusiveReceipt(file,r) {
|
|
59
|
+
const fd=openSync(file,'wx',0o600);try {writeFileSync(fd,JSON.stringify(r,null,2)+'\n');fsyncSync(fd);} finally {closeSync(fd);}
|
|
60
|
+
syncDir(path.dirname(file));
|
|
61
|
+
}
|
|
62
|
+
function updateReceipt(file,r) {
|
|
63
|
+
const old=JSON.parse(readFileSync(file,'utf8'));
|
|
64
|
+
if(lstatSync(file).isSymbolicLink() || old.id!==r.id)throw Error('receipt changed; refusing overwrite');
|
|
65
|
+
writeJson(file,r);syncDir(path.dirname(file));
|
|
66
|
+
}
|
|
67
|
+
// The receipt defines no executable shell text. Derive the only permitted remote
|
|
68
|
+
// payload path from the configured archive root and a validated UUID.
|
|
69
|
+
export function validateReceipt(r, cfg=loadConfig()) {
|
|
70
|
+
if(!r || r.type!=='cleandrive-project-archive' || r.version!==1 || !idValid(r.id) || typeof r.originalPath!=='string' || !path.isAbsolute(r.originalPath))throw Error('invalid archive receipt');
|
|
71
|
+
if(path.resolve(r.originalPath)!==r.originalPath)throw Error('receipt original path must be canonical');
|
|
72
|
+
validateTarget({path:r.originalPath});
|
|
73
|
+
const remote=remoteConfig(cfg);
|
|
74
|
+
const expected=remote.path.replace(/\/$/,'')+'/archives/'+r.id+'/payload';
|
|
75
|
+
if(r.remotePath!==expected || r.remote?.host!==remote.host || (r.remote?.user||'')!==(remote.user||'') || (r.remote?.uuid||'')!==(remote.uuid||'') || r.remote?.path!==remote.path)throw Error('receipt remote does not match configured archive drive');
|
|
76
|
+
if(r.verification?.status!=='verified' || !/^[a-f0-9]{64}$/.test(r.contentHash||''))throw Error('receipt lacks verified content');
|
|
77
|
+
return r;
|
|
78
|
+
}
|
|
79
|
+
export function listArchives(query='') {
|
|
80
|
+
if(!existsSync(catalog()))return [];
|
|
81
|
+
const result=[];
|
|
82
|
+
for(const f of readdirSync(catalog())) {
|
|
83
|
+
if(!/^[0-9a-f-]+\.json$/.test(f))continue;
|
|
84
|
+
try {
|
|
85
|
+
const r=JSON.parse(readFileSync(path.join(catalog(),f),'utf8'));
|
|
86
|
+
if(!idValid(r.id) || r.type!=='cleandrive-project-archive' || r.version!==1
|
|
87
|
+
|| typeof r.originalPath!=='string' || typeof r.remotePath!=='string'
|
|
88
|
+
|| typeof r.remote?.host!=='string' || typeof r.state!=='string'
|
|
89
|
+
|| !Number.isFinite(r.bytes) || r.bytes<0
|
|
90
|
+
|| r.verification?.status!=='verified' || !Number.isFinite(Date.parse(r.verification.checkedAt)))continue;
|
|
91
|
+
const localPresent=typeof r.originalPath==='string' && present(r.originalPath);
|
|
92
|
+
const state=r.state==='removing'?'removal-interrupted':r.state==='remote-only'&&localPresent?'local-present':r.state==='local-and-remote'&&!localPresent?'local-missing':r.state;
|
|
93
|
+
if(JSON.stringify([r.id,r.originalPath,r.remotePath,r.label]).toLowerCase().includes(String(query).toLowerCase()))result.push({...r,state,localPresent,independentBackup:'unknown'});
|
|
94
|
+
} catch { /* malformed records never become executable */ }
|
|
95
|
+
}
|
|
96
|
+
return result.sort((a,b)=>String(b.createdAt).localeCompare(String(a.createdAt)));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Content digest is portable; stability digest additionally detects local inode,
|
|
100
|
+
// metadata and timestamp changes during transfer, including generated files.
|
|
101
|
+
async function fingerprint(root) {
|
|
102
|
+
const content=createHash('sha256'), stability=createHash('sha256'); let bytes=0;
|
|
103
|
+
async function visit(p) {
|
|
104
|
+
const st=await lstat(p),rel=path.relative(root,p);
|
|
105
|
+
const type=st.isDirectory()?'d':st.isFile()?'f':st.isSymbolicLink()?'l':'special';
|
|
106
|
+
if(type==='special')throw Error('unsupported special file: '+p);
|
|
107
|
+
const fields=[rel,type];
|
|
108
|
+
if(type==='f') {
|
|
109
|
+
const h=createHash('sha256');for await(const chunk of createReadStream(p))h.update(chunk);
|
|
110
|
+
fields.push(st.size,h.digest('hex'));bytes+=st.size;
|
|
111
|
+
} else if(type==='l') {
|
|
112
|
+
const link=await readlink(p);
|
|
113
|
+
// External references are not self-contained archives.
|
|
114
|
+
if(path.isAbsolute(link) || !contains(root,path.resolve(path.dirname(p),link)))throw Error('external symlink needs review: '+p);
|
|
115
|
+
fields.push(link);
|
|
116
|
+
}
|
|
117
|
+
content.update(JSON.stringify(fields)+'\n');
|
|
118
|
+
stability.update(JSON.stringify([rel,st.dev,st.ino,st.size,st.mtimeMs,st.ctimeMs,st.mode,st.nlink])+'\n');
|
|
119
|
+
if(type==='d')for(const name of (await readdir(p)).sort())await visit(path.join(p,name));
|
|
120
|
+
}
|
|
121
|
+
await visit(root);
|
|
122
|
+
return {content:content.digest('hex'),stability:stability.digest('hex'),bytes};
|
|
123
|
+
}
|
|
124
|
+
function same(a,b) {return a.content===b.content && a.stability===b.stability;}
|
|
125
|
+
function verified(r) {
|
|
126
|
+
if(r.code!==0)return false;
|
|
127
|
+
return !r.out.trim().split('\n').filter(Boolean).some(l=>{
|
|
128
|
+
const flags=l.split(' ')[0];return flags[0]!=='.' || flags.includes('c') || flags.includes('s') || flags.includes('+');
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
async function assertClosed(src, runner) {
|
|
132
|
+
const r=await runner('lsof',['-nP','-F','p','+D',src],{timeoutMs:15000});
|
|
133
|
+
if(r.code!==1 || r.out.trim() || r.err.trim())throw Error(r.code===0?'project has open files; close it before removal':'open-file inspection failed; local copy kept');
|
|
134
|
+
}
|
|
135
|
+
async function remoteReceipt(cfg, r, runner) {
|
|
136
|
+
const file=r.remotePath.replace(/\/payload$/,'')+'/receipt.json';
|
|
137
|
+
const encoded=Buffer.from(JSON.stringify(r,null,2)+'\n').toString('base64');
|
|
138
|
+
const res=await ssh(cfg,`printf %s ${q(encoded)} | base64 -d > ${q(file+'.tmp')} && mv -- ${q(file+'.tmp')} ${q(file)} && sync -f -- ${q(path.posix.dirname(file))}`,runner);
|
|
139
|
+
if(res.code!==0)throw Error('remote receipt write failed');
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export async function archiveProject(item,{dryRun=false,removeLocal=false,onData,runner=run,checkDrive=checkRemoteDrive}={}) {
|
|
143
|
+
let release,receipt,receiptFile;
|
|
144
|
+
try {
|
|
145
|
+
const cfg=loadConfig(),src=validateTarget(item);remoteConfig(cfg);
|
|
146
|
+
if(item.kind==='group')throw Error('grouping folder: select individual projects');
|
|
147
|
+
if(!lstatSync(src).isDirectory())throw Error('project archive requires a directory');
|
|
148
|
+
if(removeLocal && isPinned(src,cfg))throw Error('project is pinned to keep local');
|
|
149
|
+
if(removeLocal && present(path.join(src,'.git')) && lstatSync(path.join(src,'.git')).isFile())throw Error('Git worktree uses external metadata; keep local until made self-contained');
|
|
150
|
+
receiptFile=src+RECEIPT_EXT;
|
|
151
|
+
if(removeLocal && present(receiptFile))throw Error('archive receipt already exists; keep it or relocate it before another offload');
|
|
152
|
+
if(dryRun) {
|
|
153
|
+
const drive=await checkDrive(cfg,item.grossKb||item.kb||0);
|
|
154
|
+
if(!drive.ok)throw Error(drive.msg);
|
|
155
|
+
return {ok:true,verified:false,output:`would archive ${src} to a new version under ${cfg.remote.path}/archives/${removeLocal?' and remove local only after verification and receipts':''}`};
|
|
156
|
+
}
|
|
157
|
+
release=acquireLock();
|
|
158
|
+
if(removeLocal)await assertClosed(src,runner);
|
|
159
|
+
const before=await fingerprint(src);
|
|
160
|
+
const drive=await checkDrive(cfg,Math.max(item.grossKb||item.kb||0,Math.ceil(before.bytes/1024)));
|
|
161
|
+
if(!drive.ok)throw Error(drive.msg);
|
|
162
|
+
const id=randomUUID(),r=remoteConfig(cfg),remotePath=r.path.replace(/\/$/,'')+'/archives/'+id+'/payload';
|
|
163
|
+
const make=await ssh(cfg,`test ! -L ${q(path.posix.dirname(path.posix.dirname(remotePath)))} && mkdir -p -- ${q(path.posix.dirname(path.posix.dirname(remotePath)))} && mkdir -- ${q(path.posix.dirname(remotePath))} && mkdir -- ${q(remotePath)}`,runner);
|
|
164
|
+
if(make.code!==0)throw Error('cannot create unique remote archive directory');
|
|
165
|
+
const target=dest(cfg,remotePath+'/');
|
|
166
|
+
const transfer=await runner('rsync',['-aH','--partial','--stats',...transport(cfg),src+'/',target],{onData});
|
|
167
|
+
if(transfer.code!==0)throw Error('archive transfer failed: '+(transfer.err||transfer.out));
|
|
168
|
+
const check=await runner('rsync',['-aHnc','--delete','--itemize-changes',...transport(cfg),src+'/',target]);
|
|
169
|
+
if(!verified(check))throw Error('archive checksum verification failed');
|
|
170
|
+
if(!same(before,await fingerprint(src)))throw Error('source changed during archive; local copy kept');
|
|
171
|
+
receipt={type:'cleandrive-project-archive',version:1,id,originalPath:src,label:path.basename(src),remote:{host:r.host,user:r.user||'',path:r.path,uuid:r.uuid||''},remotePath,bytes:before.bytes,contentHash:before.content,createdAt:new Date().toISOString(),verification:{status:'verified',checkedAt:new Date().toISOString()},independentBackup:'unknown',state:'local-and-remote',restoreCommand:`cleandrive restore ${id}`};
|
|
172
|
+
await remoteReceipt(cfg,receipt,runner);saveRecord(receipt);
|
|
173
|
+
await withCatalog(c=>c.record({
|
|
174
|
+
id:receipt.id, type:'archive', local_path:src, remote_host:r.host,
|
|
175
|
+
remote_path:remotePath, size_bytes:before.bytes, sha256:before.content,
|
|
176
|
+
state:'local-and-remote', label:receipt.label, created_at:receipt.createdAt,
|
|
177
|
+
metadata:{verification:receipt.verification, independentBackup:'unknown'},
|
|
178
|
+
}));
|
|
179
|
+
if(removeLocal) {
|
|
180
|
+
exclusiveReceipt(receiptFile,receipt);
|
|
181
|
+
// Recheck live policy and activity after every durable record is in place.
|
|
182
|
+
validateTarget(item);
|
|
183
|
+
if(isPinned(src,loadConfig()))throw Error('project is now pinned; local copy kept');
|
|
184
|
+
await assertClosed(src,runner);
|
|
185
|
+
if(!same(before,await fingerprint(src)))throw Error('source changed before removal; local copy kept');
|
|
186
|
+
receipt.state='removing';await remoteReceipt(cfg,receipt,runner);saveRecord(receipt);updateReceipt(receiptFile,receipt);
|
|
187
|
+
validateTarget(item);
|
|
188
|
+
if(isPinned(src,loadConfig()))throw Error('project is now pinned; local copy kept');
|
|
189
|
+
await assertClosed(src,runner);
|
|
190
|
+
if(!same(before,await fingerprint(src)))throw Error('source changed before removal; local copy kept');
|
|
191
|
+
// Quiescence is required: these checks are not an atomic filesystem snapshot.
|
|
192
|
+
try {rmSync(src,{recursive:true});receipt.state='remote-only';}
|
|
193
|
+
catch(err) {receipt.state='removal-failed';receipt.error=err.message;}
|
|
194
|
+
saveRecord(receipt);updateReceipt(receiptFile,receipt);
|
|
195
|
+
await withCatalog(c=>c.updateState(receipt.id, receipt.state));
|
|
196
|
+
await remoteReceipt(cfg,receipt,runner);
|
|
197
|
+
if(receipt.state==='removal-failed')throw Error('local removal failed; verified archive and receipt retained');
|
|
198
|
+
}
|
|
199
|
+
return {ok:true,verified:true,receipt,output:`VERIFIED: ${remotePath}\n${receipt.state}; independent backup unknown`};
|
|
200
|
+
} catch(err) {
|
|
201
|
+
return {ok:false,verified:!!receipt,receipt,output:err.message + (receipt?.state==='remote-only' ? '; local copy already removed; verified remote archive and local receipt retained' : '')};
|
|
202
|
+
} finally {release?.();}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export async function restoreArchive(idOrReceipt,{dryRun=false,onData,runner=run,checkDrive=checkRemoteDrive}={}) {
|
|
206
|
+
const cfg=loadConfig();
|
|
207
|
+
const file=idValid(idOrReceipt)?path.join(catalog(),idOrReceipt+'.json'):path.resolve(idOrReceipt);
|
|
208
|
+
const receipt=validateReceipt(JSON.parse(readFileSync(file,'utf8')),cfg);
|
|
209
|
+
const dst=receipt.originalPath;
|
|
210
|
+
if(present(dst))throw Error('restore destination already exists; nothing overwritten');
|
|
211
|
+
if(!existsSync(path.dirname(dst)))throw Error('restore parent directory is missing; create it before restoring');
|
|
212
|
+
const drive=await checkDrive(cfg,0);if(!drive.ok)throw Error(drive.msg);
|
|
213
|
+
if(dryRun)return {ok:true,output:`would restore ${receipt.remotePath} to ${dst}, verifying before publishing`};
|
|
214
|
+
const release=acquireLock();let staging;
|
|
215
|
+
try {
|
|
216
|
+
validateTarget({path:dst});
|
|
217
|
+
staging=mkdtempSync(path.join(path.dirname(dst),'.cleandrive-restore-'));
|
|
218
|
+
const source=dest(cfg,receipt.remotePath+'/');
|
|
219
|
+
const copy=await runner('rsync',['-aH','--partial',...transport(cfg),source,staging+'/'],{onData});
|
|
220
|
+
if(copy.code!==0)throw Error('restore transfer failed');
|
|
221
|
+
const check=await runner('rsync',['-aHnc','--delete','--itemize-changes',...transport(cfg),source,staging+'/']);
|
|
222
|
+
if(!verified(check))throw Error('restore checksum verification failed');
|
|
223
|
+
if((await fingerprint(staging)).content!==receipt.contentHash)throw Error('restored content does not match archived receipt');
|
|
224
|
+
validateTarget({path:dst});
|
|
225
|
+
// mkdir is an exclusive reservation: a concurrent creator cannot be overwritten.
|
|
226
|
+
mkdirSync(dst);
|
|
227
|
+
try {renameSync(staging,dst);staging=null;} catch(err) {throw Error('restore publish failed; staged copy retained: '+err.message);}
|
|
228
|
+
const updated={...receipt,state:'local-and-remote',restoredAt:new Date().toISOString()};
|
|
229
|
+
saveRecord(updated);
|
|
230
|
+
await withCatalog(c=>c.updateState(receipt.id, 'local-and-remote', {restoredAt:updated.restoredAt}));
|
|
231
|
+
if(present(dst+RECEIPT_EXT)) {
|
|
232
|
+
try {const prior=JSON.parse(readFileSync(dst+RECEIPT_EXT,'utf8'));if(prior.id===receipt.id)updateReceipt(dst+RECEIPT_EXT,updated);} catch { /* restored data is already safe; unrelated receipt stays untouched */ }
|
|
233
|
+
}
|
|
234
|
+
return {ok:true,output:`restored and verified: ${dst}`,receipt:updated};
|
|
235
|
+
} catch (err) {
|
|
236
|
+
if (staging) err.message += `; staged files retained at ${staging}`;
|
|
237
|
+
throw err;
|
|
238
|
+
} finally {
|
|
239
|
+
// Failed staging is retained for recovery, never confused with a published restore.
|
|
240
|
+
release();
|
|
241
|
+
}
|
|
242
|
+
}
|
package/lib/catalog.js
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
// Unified SQLite catalog of everything stored on the remote archive drive.
|
|
2
|
+
// The JSON files (offloaded.json, archive receipts, manifest.jsonl) remain the
|
|
3
|
+
// durable source of truth; this DB mirrors them for fast local queries.
|
|
4
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
5
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { DATA_DIR, ensureDataDir, readJson, fmtGB, loadConfig } from './util.js';
|
|
8
|
+
import { loadIndex } from './offload.js';
|
|
9
|
+
import { listArchives } from './archives.js';
|
|
10
|
+
import { checkRemoteDrive, sshOpts } from './actions.js';
|
|
11
|
+
import { run } from './util.js';
|
|
12
|
+
|
|
13
|
+
const DB_FILE = path.join(DATA_DIR, 'catalog.db');
|
|
14
|
+
|
|
15
|
+
const SCHEMA = `
|
|
16
|
+
CREATE TABLE IF NOT EXISTS items (
|
|
17
|
+
id TEXT PRIMARY KEY,
|
|
18
|
+
type TEXT NOT NULL CHECK(type IN ('offload','archive')),
|
|
19
|
+
local_path TEXT NOT NULL,
|
|
20
|
+
remote_host TEXT NOT NULL,
|
|
21
|
+
remote_path TEXT NOT NULL,
|
|
22
|
+
size_bytes INTEGER NOT NULL,
|
|
23
|
+
sha256 TEXT,
|
|
24
|
+
state TEXT NOT NULL,
|
|
25
|
+
label TEXT,
|
|
26
|
+
created_at TEXT NOT NULL,
|
|
27
|
+
updated_at TEXT,
|
|
28
|
+
metadata TEXT
|
|
29
|
+
);
|
|
30
|
+
CREATE INDEX IF NOT EXISTS idx_local_path ON items(local_path);
|
|
31
|
+
CREATE INDEX IF NOT EXISTS idx_state ON items(state);
|
|
32
|
+
CREATE INDEX IF NOT EXISTS idx_type ON items(type);
|
|
33
|
+
`;
|
|
34
|
+
|
|
35
|
+
let _db;
|
|
36
|
+
function db() {
|
|
37
|
+
if (_db) return _db;
|
|
38
|
+
ensureDataDir();
|
|
39
|
+
_db = new DatabaseSync(DB_FILE);
|
|
40
|
+
_db.exec('PRAGMA journal_mode=WAL');
|
|
41
|
+
_db.exec('PRAGMA foreign_keys=ON');
|
|
42
|
+
_db.exec(SCHEMA);
|
|
43
|
+
return _db;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function closeDb() {
|
|
47
|
+
if (_db) { _db.close(); _db = null; }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// --- write ---
|
|
51
|
+
|
|
52
|
+
export function record(item) {
|
|
53
|
+
const d = db();
|
|
54
|
+
d.prepare(`
|
|
55
|
+
INSERT INTO items (id, type, local_path, remote_host, remote_path,
|
|
56
|
+
size_bytes, sha256, state, label, created_at, updated_at, metadata)
|
|
57
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
58
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
59
|
+
state=excluded.state, updated_at=excluded.updated_at,
|
|
60
|
+
local_path=excluded.local_path, metadata=excluded.metadata
|
|
61
|
+
`).run(
|
|
62
|
+
item.id, item.type, item.local_path, item.remote_host, item.remote_path,
|
|
63
|
+
item.size_bytes, item.sha256 || null, item.state, item.label || null,
|
|
64
|
+
item.created_at, item.updated_at || null, item.metadata ? JSON.stringify(item.metadata) : null,
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function updateState(id, state, extra = {}) {
|
|
69
|
+
const d = db();
|
|
70
|
+
const now = new Date().toISOString();
|
|
71
|
+
if (Object.keys(extra).length) {
|
|
72
|
+
const row = d.prepare('SELECT metadata FROM items WHERE id=?').get(id);
|
|
73
|
+
const prev = row?.metadata ? JSON.parse(row.metadata) : {};
|
|
74
|
+
d.prepare('UPDATE items SET state=?, updated_at=?, metadata=? WHERE id=?')
|
|
75
|
+
.run(state, now, JSON.stringify({ ...prev, ...extra }), id);
|
|
76
|
+
} else {
|
|
77
|
+
d.prepare('UPDATE items SET state=?, updated_at=? WHERE id=?').run(state, now, id);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function remove(id) {
|
|
82
|
+
db().prepare('DELETE FROM items WHERE id=?').run(id);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// --- read ---
|
|
86
|
+
|
|
87
|
+
export function all(filters = {}) {
|
|
88
|
+
let sql = 'SELECT * FROM items WHERE 1=1';
|
|
89
|
+
const params = [];
|
|
90
|
+
if (filters.type) { sql += ' AND type=?'; params.push(filters.type); }
|
|
91
|
+
if (filters.state) { sql += ' AND state=?'; params.push(filters.state); }
|
|
92
|
+
sql += ' ORDER BY size_bytes DESC';
|
|
93
|
+
return db().prepare(sql).all(...params);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function search(query) {
|
|
97
|
+
return db().prepare(
|
|
98
|
+
"SELECT * FROM items WHERE local_path LIKE ? OR label LIKE ? ORDER BY size_bytes DESC"
|
|
99
|
+
).all(`%${query}%`, `%${query}%`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function get(id) {
|
|
103
|
+
return db().prepare('SELECT * FROM items WHERE id=?').get(id) || null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function stats() {
|
|
107
|
+
const d = db();
|
|
108
|
+
const total = d.prepare('SELECT COUNT(*) as n, COALESCE(SUM(size_bytes),0) as bytes FROM items').get();
|
|
109
|
+
const byType = d.prepare('SELECT type, COUNT(*) as n, COALESCE(SUM(size_bytes),0) as bytes FROM items GROUP BY type').all();
|
|
110
|
+
const byState = d.prepare('SELECT state, COUNT(*) as n, COALESCE(SUM(size_bytes),0) as bytes FROM items GROUP BY state').all();
|
|
111
|
+
const onRemote = d.prepare(
|
|
112
|
+
"SELECT COUNT(*) as n, COALESCE(SUM(size_bytes),0) as bytes FROM items WHERE state NOT IN ('local','fetched')"
|
|
113
|
+
).get();
|
|
114
|
+
return { total, byType, byState, onRemote };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// --- sync: rebuild from existing JSON sources ---
|
|
118
|
+
|
|
119
|
+
export function sync({ onData } = {}) {
|
|
120
|
+
const d = db();
|
|
121
|
+
const cfg = loadConfig();
|
|
122
|
+
const host = cfg.remote?.host || 'unknown';
|
|
123
|
+
const basePath = cfg.remote?.path || '';
|
|
124
|
+
let added = 0, updated = 0;
|
|
125
|
+
|
|
126
|
+
// 1. Offloaded files from offloaded.json
|
|
127
|
+
const idx = loadIndex();
|
|
128
|
+
for (const [absPath, entry] of Object.entries(idx.files || {})) {
|
|
129
|
+
const id = entry.sha256 || absPath;
|
|
130
|
+
const existing = d.prepare('SELECT id, state FROM items WHERE id=?').get(id);
|
|
131
|
+
const item = {
|
|
132
|
+
id,
|
|
133
|
+
type: 'offload',
|
|
134
|
+
local_path: absPath,
|
|
135
|
+
remote_host: host,
|
|
136
|
+
remote_path: `${basePath.replace(/\/$/, '')}/offload/${entry.object || ''}`,
|
|
137
|
+
size_bytes: entry.size || 0,
|
|
138
|
+
sha256: entry.sha256 || null,
|
|
139
|
+
state: entry.state || 'offloaded',
|
|
140
|
+
label: path.basename(absPath),
|
|
141
|
+
created_at: entry.offloadedAt || new Date().toISOString(),
|
|
142
|
+
updated_at: entry.fetchedAt || null,
|
|
143
|
+
metadata: { mtimeMs: entry.mtimeMs, object: entry.object },
|
|
144
|
+
};
|
|
145
|
+
record(item);
|
|
146
|
+
if (existing) updated++; else added++;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// 2. Archived projects from receipt files
|
|
150
|
+
const archives = listArchives();
|
|
151
|
+
for (const a of archives) {
|
|
152
|
+
const existing = d.prepare('SELECT id FROM items WHERE id=?').get(a.id);
|
|
153
|
+
record({
|
|
154
|
+
id: a.id,
|
|
155
|
+
type: 'archive',
|
|
156
|
+
local_path: a.originalPath,
|
|
157
|
+
remote_host: a.remote?.host || host,
|
|
158
|
+
remote_path: a.remotePath,
|
|
159
|
+
size_bytes: a.bytes || 0,
|
|
160
|
+
sha256: a.contentHash || null,
|
|
161
|
+
state: a.state,
|
|
162
|
+
label: a.label || path.basename(a.originalPath),
|
|
163
|
+
created_at: a.createdAt || new Date().toISOString(),
|
|
164
|
+
updated_at: a.restoredAt || null,
|
|
165
|
+
metadata: { verification: a.verification, independentBackup: a.independentBackup },
|
|
166
|
+
});
|
|
167
|
+
if (existing) updated++; else added++;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
onData?.(`synced: ${added} added, ${updated} updated\n`);
|
|
171
|
+
return { added, updated };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Pull manifest.jsonl from the remote and merge entries not yet in the catalog.
|
|
175
|
+
export async function syncRemote({ onData } = {}) {
|
|
176
|
+
const cfg = loadConfig();
|
|
177
|
+
const r = cfg.remote;
|
|
178
|
+
if (!r?.host || !r?.path) throw new Error('remote not configured');
|
|
179
|
+
const drive = await checkRemoteDrive(cfg);
|
|
180
|
+
if (!drive.ok) throw new Error(drive.msg);
|
|
181
|
+
|
|
182
|
+
const dest = `${r.user ? r.user + '@' : ''}${r.host}`;
|
|
183
|
+
const base = ['-o', 'ConnectTimeout=10', '-o', 'BatchMode=yes', ...sshOpts(cfg)];
|
|
184
|
+
const manifestPath = `${r.path.replace(/\/$/, '')}/offload/manifest.jsonl`;
|
|
185
|
+
const q = `'${manifestPath.replace(/'/g, `'\\''`)}'`;
|
|
186
|
+
const res = await run('ssh', [...base, dest, `cat ${q} 2>/dev/null`]);
|
|
187
|
+
|
|
188
|
+
let added = 0;
|
|
189
|
+
if (res.code === 0 && res.out.trim()) {
|
|
190
|
+
const d = db();
|
|
191
|
+
for (const line of res.out.trim().split('\n')) {
|
|
192
|
+
let entry;
|
|
193
|
+
try { entry = JSON.parse(line); } catch { continue; }
|
|
194
|
+
if (entry.event !== 'offload' || !entry.sha256) continue;
|
|
195
|
+
const existing = d.prepare('SELECT id FROM items WHERE id=?').get(entry.sha256);
|
|
196
|
+
if (existing) continue;
|
|
197
|
+
record({
|
|
198
|
+
id: entry.sha256,
|
|
199
|
+
type: 'offload',
|
|
200
|
+
local_path: entry.path,
|
|
201
|
+
remote_host: r.host,
|
|
202
|
+
remote_path: `${r.path.replace(/\/$/, '')}/offload/${entry.object || ''}`,
|
|
203
|
+
size_bytes: entry.size || 0,
|
|
204
|
+
sha256: entry.sha256,
|
|
205
|
+
state: entry.state || 'offloaded',
|
|
206
|
+
label: path.basename(entry.path),
|
|
207
|
+
created_at: entry.offloadedAt || new Date().toISOString(),
|
|
208
|
+
metadata: { mtimeMs: entry.mtimeMs, object: entry.object, mac: entry.mac },
|
|
209
|
+
});
|
|
210
|
+
added++;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Also check for archive receipts on the remote
|
|
215
|
+
const archiveDir = `${r.path.replace(/\/$/, '')}/archives`;
|
|
216
|
+
const q2 = `'${archiveDir.replace(/'/g, `'\\''`)}'`;
|
|
217
|
+
const ls = await run('ssh', [...base, dest, `ls ${q2} 2>/dev/null`]);
|
|
218
|
+
const remoteArchiveIds = ls.code === 0 ? ls.out.trim().split('\n').filter(Boolean) : [];
|
|
219
|
+
onData?.(`remote: ${res.code === 0 ? 'manifest read' : 'manifest not found'}, ${remoteArchiveIds.length} archive dirs\n`);
|
|
220
|
+
onData?.(`synced from remote: ${added} new offload entries\n`);
|
|
221
|
+
return { added, remoteArchiveIds };
|
|
222
|
+
}
|