cursor-guard 2.1.1 → 3.0.0

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.
@@ -0,0 +1,357 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { execFileSync } = require('child_process');
6
+ const {
7
+ git, isGitRepo, gitDir: getGitDir, walkDir, diskFreeGB,
8
+ } = require('../utils');
9
+
10
+ // ── Helpers ──────────────────────────────────────────────────────
11
+
12
+ function parseShadowTimestamp(name) {
13
+ const m = name.match(/^(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})$/);
14
+ if (!m) return null;
15
+ return new Date(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}`);
16
+ }
17
+
18
+ function parseBeforeExpression(before) {
19
+ if (!before) return null;
20
+ const iso = Date.parse(before);
21
+ if (!isNaN(iso)) return new Date(iso);
22
+ const agoMatch = before.match(/^(\d+)\s*(second|minute|hour|day|week|month)s?\s*ago$/i);
23
+ if (agoMatch) {
24
+ const n = parseInt(agoMatch[1], 10);
25
+ const unit = agoMatch[2].toLowerCase();
26
+ const ms = { second: 1000, minute: 60000, hour: 3600000, day: 86400000, week: 604800000, month: 2592000000 }[unit] || 0;
27
+ return new Date(Date.now() - n * ms);
28
+ }
29
+ return null;
30
+ }
31
+
32
+ function entryToMs(entry) {
33
+ if (!entry.timestamp) return 0;
34
+ const iso = Date.parse(entry.timestamp);
35
+ if (!isNaN(iso)) return iso;
36
+ const tsName = typeof entry.timestamp === 'string' && entry.timestamp.startsWith('pre-restore-')
37
+ ? entry.timestamp.slice('pre-restore-'.length)
38
+ : entry.timestamp;
39
+ const d = parseShadowTimestamp(tsName);
40
+ return d ? d.getTime() : 0;
41
+ }
42
+
43
+ // ── List backups ────────────────────────────────────────────────
44
+
45
+ /**
46
+ * List available backup/restore points from all sources.
47
+ * Returns a globally time-sorted list (newest first), truncated to `limit`.
48
+ *
49
+ * @param {string} projectDir
50
+ * @param {object} [opts]
51
+ * @param {string} [opts.file] - Filter to commits touching this relative path
52
+ * @param {string} [opts.before] - Time boundary (e.g. '10 minutes ago', ISO string)
53
+ * @param {number} [opts.limit=20] - Max total results
54
+ * @returns {{ sources: Array<{type: string, ref?: string, commitHash?: string, shortHash?: string, timestamp?: string, message?: string, path?: string}> }}
55
+ */
56
+ function listBackups(projectDir, opts = {}) {
57
+ const limit = opts.limit || 20;
58
+ const sources = [];
59
+
60
+ if (opts.file) {
61
+ const normalized = path.normalize(opts.file).replace(/\\/g, '/');
62
+ if (path.isAbsolute(normalized) || normalized.startsWith('..')) {
63
+ return { sources: [], error: 'file path must be relative and within project directory' };
64
+ }
65
+ }
66
+
67
+ const repo = isGitRepo(projectDir);
68
+ const beforeDate = parseBeforeExpression(opts.before);
69
+
70
+ // Git sources
71
+ if (repo) {
72
+ // Auto-backup commits (git --before handles native filtering)
73
+ const autoRef = 'refs/guard/auto-backup';
74
+ const autoExists = git(['rev-parse', '--verify', autoRef], { cwd: projectDir, allowFail: true });
75
+ if (autoExists) {
76
+ const logArgs = ['log', autoRef, `--format=%H %aI %s`, `-${limit}`];
77
+ if (opts.before) logArgs.push(`--before=${opts.before}`);
78
+ if (opts.file) logArgs.push('--', opts.file);
79
+ const out = git(logArgs, { cwd: projectDir, allowFail: true });
80
+ if (out) {
81
+ for (const line of out.split('\n').filter(Boolean)) {
82
+ const firstSpace = line.indexOf(' ');
83
+ const secondSpace = line.indexOf(' ', firstSpace + 1);
84
+ const hash = line.substring(0, firstSpace);
85
+ const timestamp = line.substring(firstSpace + 1, secondSpace);
86
+ const message = line.substring(secondSpace + 1);
87
+ sources.push({
88
+ type: 'git-auto-backup',
89
+ ref: autoRef,
90
+ commitHash: hash,
91
+ shortHash: hash.substring(0, 7),
92
+ timestamp,
93
+ message,
94
+ });
95
+ }
96
+ }
97
+ }
98
+
99
+ // Pre-restore snapshots
100
+ const preRestoreRefs = git(
101
+ ['for-each-ref', 'refs/guard/pre-restore/', '--format=%(refname) %(objectname) %(*objectname) %(creatordate:iso-strict)', '--sort=-creatordate'],
102
+ { cwd: projectDir, allowFail: true }
103
+ );
104
+ if (preRestoreRefs) {
105
+ for (const line of preRestoreRefs.split('\n').filter(Boolean)) {
106
+ const parts = line.split(' ');
107
+ const ref = parts[0];
108
+ const hash = parts[1];
109
+ const timestamp = parts[3] || parts[2];
110
+ if (beforeDate && timestamp) {
111
+ const ms = Date.parse(timestamp);
112
+ if (!isNaN(ms) && ms > beforeDate.getTime()) continue;
113
+ }
114
+ sources.push({
115
+ type: 'git-pre-restore',
116
+ ref,
117
+ commitHash: hash,
118
+ shortHash: hash.substring(0, 7),
119
+ timestamp,
120
+ });
121
+ }
122
+ }
123
+
124
+ // Agent snapshot ref
125
+ const snapshotHash = git(['rev-parse', '--verify', 'refs/guard/snapshot'], { cwd: projectDir, allowFail: true });
126
+ if (snapshotHash) {
127
+ const ts = git(['log', '-1', '--format=%aI', 'refs/guard/snapshot'], { cwd: projectDir, allowFail: true });
128
+ const include = !beforeDate || (ts && Date.parse(ts) <= beforeDate.getTime());
129
+ if (include) {
130
+ sources.push({
131
+ type: 'git-snapshot',
132
+ ref: 'refs/guard/snapshot',
133
+ commitHash: snapshotHash,
134
+ shortHash: snapshotHash.substring(0, 7),
135
+ timestamp: ts || null,
136
+ });
137
+ }
138
+ }
139
+ }
140
+
141
+ // Shadow copy directories
142
+ const backupDir = path.join(projectDir, '.cursor-guard-backup');
143
+ if (fs.existsSync(backupDir)) {
144
+ try {
145
+ const dirs = fs.readdirSync(backupDir, { withFileTypes: true })
146
+ .filter(d => d.isDirectory())
147
+ .map(d => d.name)
148
+ .sort()
149
+ .reverse();
150
+
151
+ for (const name of dirs) {
152
+ const isPreRestore = name.startsWith('pre-restore-');
153
+ const isTimestamp = /^\d{8}_\d{6}$/.test(name);
154
+ if (!isTimestamp && !isPreRestore) continue;
155
+
156
+ if (beforeDate) {
157
+ const tsName = isPreRestore ? name.slice('pre-restore-'.length) : name;
158
+ const snapDate = parseShadowTimestamp(tsName);
159
+ if (snapDate && snapDate.getTime() > beforeDate.getTime()) continue;
160
+ }
161
+
162
+ const dirPath = path.join(backupDir, name);
163
+
164
+ if (opts.file && !fs.existsSync(path.join(dirPath, opts.file))) continue;
165
+
166
+ sources.push({
167
+ type: isPreRestore ? 'shadow-pre-restore' : 'shadow',
168
+ timestamp: name,
169
+ path: dirPath,
170
+ });
171
+ }
172
+ } catch { /* ignore */ }
173
+ }
174
+
175
+ // Unified time sort (newest first) across all sources, then truncate
176
+ sources.sort((a, b) => entryToMs(b) - entryToMs(a));
177
+
178
+ return { sources: sources.slice(0, limit) };
179
+ }
180
+
181
+ // ── Shadow retention ────────────────────────────────────────────
182
+
183
+ /**
184
+ * Clean old shadow copy snapshots based on retention config.
185
+ *
186
+ * @param {string} backupDir - Path to .cursor-guard-backup/
187
+ * @param {object} cfg - Loaded config
188
+ * @returns {{ removed: number, mode: string, diskFreeGB?: number, diskWarning?: string }}
189
+ */
190
+ function cleanShadowRetention(backupDir, cfg) {
191
+ const { mode, days, max_count, max_size_mb } = cfg.retention;
192
+ let dirs;
193
+ try {
194
+ dirs = fs.readdirSync(backupDir, { withFileTypes: true })
195
+ .filter(d => d.isDirectory() && /^\d{8}_\d{6}$/.test(d.name))
196
+ .map(d => d.name)
197
+ .sort()
198
+ .reverse();
199
+ } catch { return { removed: 0, mode }; }
200
+ if (!dirs || dirs.length === 0) return { removed: 0, mode };
201
+
202
+ let removed = 0;
203
+
204
+ if (mode === 'days') {
205
+ const cutoff = Date.now() - days * 86400000;
206
+ for (const name of dirs) {
207
+ const m = name.match(/^(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})$/);
208
+ if (!m) continue;
209
+ const dt = new Date(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}`);
210
+ if (dt.getTime() < cutoff) {
211
+ fs.rmSync(path.join(backupDir, name), { recursive: true, force: true });
212
+ removed++;
213
+ }
214
+ }
215
+ } else if (mode === 'count') {
216
+ if (dirs.length > max_count) {
217
+ for (const name of dirs.slice(max_count)) {
218
+ fs.rmSync(path.join(backupDir, name), { recursive: true, force: true });
219
+ removed++;
220
+ }
221
+ }
222
+ } else if (mode === 'size') {
223
+ let totalBytes = 0;
224
+ try {
225
+ const allFiles = walkDir(backupDir, backupDir);
226
+ for (const f of allFiles) {
227
+ try { totalBytes += fs.statSync(f.full).size; } catch { /* skip */ }
228
+ }
229
+ } catch { /* ignore */ }
230
+ const oldestFirst = [...dirs].reverse();
231
+ for (const name of oldestFirst) {
232
+ if (totalBytes / (1024 * 1024) <= max_size_mb) break;
233
+ const dirPath = path.join(backupDir, name);
234
+ let dirSize = 0;
235
+ try {
236
+ const files = walkDir(dirPath, dirPath);
237
+ for (const f of files) {
238
+ try { dirSize += fs.statSync(f.full).size; } catch { /* skip */ }
239
+ }
240
+ } catch { /* ignore */ }
241
+ fs.rmSync(dirPath, { recursive: true, force: true });
242
+ totalBytes -= dirSize;
243
+ removed++;
244
+ }
245
+ }
246
+
247
+ const result = { removed, mode };
248
+
249
+ const freeGB = diskFreeGB(backupDir);
250
+ if (freeGB !== null) {
251
+ result.diskFreeGB = parseFloat(freeGB.toFixed(1));
252
+ if (freeGB < 1) result.diskWarning = 'critically low';
253
+ else if (freeGB < 5) result.diskWarning = 'low';
254
+ }
255
+
256
+ return result;
257
+ }
258
+
259
+ // ── Git retention ───────────────────────────────────────────────
260
+
261
+ /**
262
+ * Clean old git auto-backup commits by rebuilding the branch as an orphan chain.
263
+ *
264
+ * @param {string} branchRef
265
+ * @param {string} gitDirPath
266
+ * @param {object} cfg - Loaded config
267
+ * @param {string} cwd - Project directory
268
+ * @returns {{ kept: number, pruned: number, mode: string, rebuilt: boolean, skipped?: boolean, reason?: string }}
269
+ */
270
+ function cleanGitRetention(branchRef, gitDirPath, cfg, cwd) {
271
+ const { mode, days, max_count } = cfg.git_retention;
272
+ if (!cfg.git_retention.enabled) {
273
+ return { kept: 0, pruned: 0, mode, rebuilt: false, skipped: true, reason: 'retention disabled' };
274
+ }
275
+
276
+ const out = git(['log', branchRef, '--format=%H %aI %cI %s'], { cwd, allowFail: true });
277
+ if (!out) {
278
+ return { kept: 0, pruned: 0, mode, rebuilt: false, skipped: true, reason: 'no commits on ref' };
279
+ }
280
+
281
+ const lines = out.split('\n').filter(Boolean);
282
+ const guardCommits = [];
283
+ for (const line of lines) {
284
+ const firstSpace = line.indexOf(' ');
285
+ const secondSpace = line.indexOf(' ', firstSpace + 1);
286
+ const thirdSpace = line.indexOf(' ', secondSpace + 1);
287
+ const hash = line.substring(0, firstSpace);
288
+ const authorDate = line.substring(firstSpace + 1, secondSpace);
289
+ const committerDate = line.substring(secondSpace + 1, thirdSpace);
290
+ const subject = line.substring(thirdSpace + 1);
291
+ if (subject.startsWith('guard: auto-backup') || subject.startsWith('guard: snapshot')) {
292
+ guardCommits.push({ hash, authorDate, committerDate, subject });
293
+ }
294
+ // Non-guard commits are silently skipped; continue scanning older history
295
+ }
296
+
297
+ const total = guardCommits.length;
298
+ if (total === 0) {
299
+ return { kept: 0, pruned: 0, mode, rebuilt: false, skipped: true, reason: 'no guard commits found' };
300
+ }
301
+
302
+ let keepCount = total;
303
+ if (mode === 'count') {
304
+ keepCount = Math.min(total, max_count);
305
+ } else if (mode === 'days') {
306
+ const cutoff = Date.now() - days * 86400000;
307
+ keepCount = 0;
308
+ for (const c of guardCommits) {
309
+ if (new Date(c.authorDate).getTime() >= cutoff) keepCount++;
310
+ else break;
311
+ }
312
+ keepCount = Math.max(keepCount, 10);
313
+ }
314
+
315
+ if (keepCount >= total) {
316
+ return { kept: total, pruned: 0, mode, rebuilt: false };
317
+ }
318
+
319
+ const toKeep = guardCommits.slice(0, keepCount).reverse();
320
+
321
+ function commitTreeWithDate(args, commit) {
322
+ const env = {
323
+ ...process.env,
324
+ GIT_AUTHOR_DATE: commit.authorDate,
325
+ GIT_COMMITTER_DATE: commit.committerDate,
326
+ };
327
+ try {
328
+ return execFileSync('git', args, { cwd, env, stdio: 'pipe', encoding: 'utf-8' }).trim() || null;
329
+ } catch { return null; }
330
+ }
331
+
332
+ const rootTree = git(['rev-parse', `${toKeep[0].hash}^{tree}`], { cwd, allowFail: true });
333
+ if (!rootTree) {
334
+ return { kept: total, pruned: 0, mode, rebuilt: false, reason: 'could not resolve root tree' };
335
+ }
336
+ let prevHash = commitTreeWithDate(['commit-tree', rootTree, '-m', toKeep[0].subject], toKeep[0]);
337
+ if (!prevHash) {
338
+ return { kept: total, pruned: 0, mode, rebuilt: false, reason: 'commit-tree failed for root' };
339
+ }
340
+
341
+ for (let i = 1; i < toKeep.length; i++) {
342
+ const tree = git(['rev-parse', `${toKeep[i].hash}^{tree}`], { cwd, allowFail: true });
343
+ if (!tree) {
344
+ return { kept: total, pruned: 0, mode, rebuilt: false, reason: `could not resolve tree for commit ${i}` };
345
+ }
346
+ prevHash = commitTreeWithDate(['commit-tree', tree, '-p', prevHash, '-m', toKeep[i].subject], toKeep[i]);
347
+ if (!prevHash) {
348
+ return { kept: total, pruned: 0, mode, rebuilt: false, reason: `commit-tree failed at index ${i}` };
349
+ }
350
+ }
351
+
352
+ git(['update-ref', branchRef, prevHash], { cwd, allowFail: true });
353
+
354
+ return { kept: keepCount, pruned: total - keepCount, mode, rebuilt: true };
355
+ }
356
+
357
+ module.exports = { listBackups, cleanShadowRetention, cleanGitRetention };