cursor-guard 4.9.9 → 4.9.15

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.
Files changed (35) hide show
  1. package/README.md +697 -697
  2. package/README.zh-CN.md +696 -696
  3. package/ROADMAP.md +1775 -1720
  4. package/SKILL.md +631 -629
  5. package/docs/RELEASE.md +197 -196
  6. package/docs/SNAPSHOT-BOOKMARK.md +47 -0
  7. package/package.json +70 -69
  8. package/references/dashboard/public/app.js +2079 -1832
  9. package/references/dashboard/public/style.css +1660 -1573
  10. package/references/dashboard/server.js +197 -4
  11. package/references/lib/core/backups.js +509 -492
  12. package/references/lib/core/core.test.js +1761 -1616
  13. package/references/lib/core/snapshot.js +441 -369
  14. package/references/mcp/mcp.test.js +381 -362
  15. package/references/mcp/server.js +404 -347
  16. package/references/vscode-extension/dist/{cursor-guard-ide-4.9.9.vsix → cursor-guard-ide-4.9.15.vsix} +0 -0
  17. package/references/vscode-extension/dist/dashboard/public/app.js +2079 -1832
  18. package/references/vscode-extension/dist/dashboard/public/style.css +1660 -1573
  19. package/references/vscode-extension/dist/dashboard/server.js +197 -4
  20. package/references/vscode-extension/dist/extension.js +780 -704
  21. package/references/vscode-extension/dist/guard-version.json +1 -1
  22. package/references/vscode-extension/dist/lib/auto-setup.js +201 -192
  23. package/references/vscode-extension/dist/lib/core/backups.js +509 -492
  24. package/references/vscode-extension/dist/lib/core/snapshot.js +441 -369
  25. package/references/vscode-extension/dist/lib/poller.js +161 -21
  26. package/references/vscode-extension/dist/lib/sidebar-webview.js +22 -0
  27. package/references/vscode-extension/dist/mcp/server.js +152 -35
  28. package/references/vscode-extension/dist/package.json +7 -1
  29. package/references/vscode-extension/dist/skill/ROADMAP.md +1775 -1720
  30. package/references/vscode-extension/dist/skill/SKILL.md +631 -629
  31. package/references/vscode-extension/extension.js +780 -704
  32. package/references/vscode-extension/lib/auto-setup.js +201 -192
  33. package/references/vscode-extension/lib/poller.js +161 -21
  34. package/references/vscode-extension/lib/sidebar-webview.js +22 -0
  35. package/references/vscode-extension/package.json +146 -140
@@ -1,492 +1,509 @@
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})(?:_(\d{3}))?$/);
14
- if (!m) return null;
15
- const ms = m[7] ? `.${m[7]}` : '';
16
- return new Date(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}${ms}`);
17
- }
18
-
19
- function parseBeforeExpression(before) {
20
- if (!before) return null;
21
- const iso = Date.parse(before);
22
- if (!isNaN(iso)) return new Date(iso);
23
- const agoMatch = before.match(/^(\d+)\s*(second|minute|hour|day|week|month)s?\s*ago$/i);
24
- if (agoMatch) {
25
- const n = parseInt(agoMatch[1], 10);
26
- const unit = agoMatch[2].toLowerCase();
27
- const ms = { second: 1000, minute: 60000, hour: 3600000, day: 86400000, week: 604800000, month: 2592000000 }[unit] || 0;
28
- return new Date(Date.now() - n * ms);
29
- }
30
- return null;
31
- }
32
-
33
- function entryToMs(entry) {
34
- if (!entry.timestamp) return 0;
35
- const iso = Date.parse(entry.timestamp);
36
- if (!isNaN(iso)) return iso;
37
- const tsName = typeof entry.timestamp === 'string' && entry.timestamp.startsWith('pre-restore-')
38
- ? entry.timestamp.slice('pre-restore-'.length)
39
- : entry.timestamp;
40
- const d = parseShadowTimestamp(tsName);
41
- return d ? d.getTime() : 0;
42
- }
43
-
44
- const TRAILER_MAP = {
45
- 'Files-Changed': { key: 'filesChanged', parse: v => parseInt(v, 10) },
46
- 'Summary': { key: 'summary' },
47
- 'Trigger': { key: 'trigger' },
48
- 'Intent': { key: 'intent' },
49
- 'Agent': { key: 'agent' },
50
- 'Session': { key: 'session' },
51
- 'From': { key: 'from' },
52
- 'Restore-To': { key: 'restoreTo' },
53
- 'File': { key: 'restoreFile' },
54
- };
55
-
56
- function parseCommitTrailers(body) {
57
- if (!body) return {};
58
- const result = {};
59
- const pattern = new RegExp(`^(${Object.keys(TRAILER_MAP).join('|')}):\\s*(.+)$`);
60
- for (const line of body.split('\n')) {
61
- const m = line.match(pattern);
62
- if (m) {
63
- const def = TRAILER_MAP[m[1]];
64
- result[def.key] = def.parse ? def.parse(m[2]) : m[2];
65
- }
66
- }
67
- return result;
68
- }
69
-
70
- // ── List backups ────────────────────────────────────────────────
71
-
72
- /**
73
- * List available backup/restore points from all sources.
74
- * Returns a globally time-sorted list (newest first), truncated to `limit`.
75
- *
76
- * @param {string} projectDir
77
- * @param {object} [opts]
78
- * @param {string} [opts.file] - Filter to commits touching this relative path
79
- * @param {string} [opts.before] - Time boundary (e.g. '10 minutes ago', ISO string)
80
- * @param {number} [opts.limit=20] - Max total results
81
- * @returns {{ sources: Array<{type: string, ref?: string, commitHash?: string, shortHash?: string, timestamp?: string, message?: string, path?: string, filesChanged?: number, summary?: string, trigger?: string}> }}
82
- */
83
- function listBackups(projectDir, opts = {}) {
84
- const limit = opts.limit || 20;
85
- const sources = [];
86
-
87
- if (opts.file) {
88
- const normalized = path.normalize(opts.file).replace(/\\/g, '/');
89
- if (path.isAbsolute(normalized) || normalized.startsWith('..')) {
90
- return { sources: [], error: 'file path must be relative and within project directory' };
91
- }
92
- }
93
-
94
- const repo = isGitRepo(projectDir);
95
- const beforeDate = parseBeforeExpression(opts.before);
96
-
97
- // Git sources
98
- if (repo) {
99
- // Auto-backup commits (git --before handles native filtering)
100
- const autoRef = 'refs/guard/auto-backup';
101
- const autoExists = git(['rev-parse', '--verify', autoRef], { cwd: projectDir, allowFail: true });
102
- if (autoExists) {
103
- const logArgs = ['log', autoRef, '--format=%H\x1f%aI\x1f%B\x1e', `-${limit}`, '--grep=^guard:'];
104
- if (opts.before) logArgs.push(`--before=${opts.before}`);
105
- if (opts.file) logArgs.push('--', opts.file);
106
- const out = git(logArgs, { cwd: projectDir, allowFail: true });
107
- if (out) {
108
- for (const record of out.split('\x1e').filter(r => r.trim())) {
109
- const parts = record.split('\x1f');
110
- if (parts.length < 3) continue;
111
- const hash = parts[0].trim();
112
- const timestamp = parts[1];
113
- const body = parts[2];
114
- const subject = body.split('\n')[0];
115
- const trailers = parseCommitTrailers(body);
116
- sources.push({
117
- type: 'git-auto-backup',
118
- ref: autoRef,
119
- commitHash: hash,
120
- shortHash: hash.substring(0, 7),
121
- timestamp,
122
- message: subject,
123
- ...trailers,
124
- });
125
- }
126
- }
127
- }
128
-
129
- // Pre-restore snapshots
130
- const preRestoreRefs = git(
131
- ['for-each-ref', 'refs/guard/pre-restore/', '--format=%(refname) %(objectname) %(*objectname) %(creatordate:iso-strict)', '--sort=-creatordate'],
132
- { cwd: projectDir, allowFail: true }
133
- );
134
- if (preRestoreRefs) {
135
- for (const line of preRestoreRefs.split('\n').filter(Boolean)) {
136
- const parts = line.split(' ');
137
- const ref = parts[0];
138
- const hash = parts[1];
139
- const timestamp = parts[3] || parts[2];
140
- if (beforeDate && timestamp) {
141
- const ms = Date.parse(timestamp);
142
- if (!isNaN(ms) && ms > beforeDate.getTime()) continue;
143
- }
144
- const entry = {
145
- type: 'git-pre-restore',
146
- ref,
147
- commitHash: hash,
148
- shortHash: hash.substring(0, 7),
149
- timestamp,
150
- };
151
- const prBody = git(['log', '-1', '--format=%B', hash], { cwd: projectDir, allowFail: true });
152
- if (prBody) {
153
- const prSubject = prBody.split('\n')[0];
154
- if (prSubject) entry.message = prSubject;
155
- Object.assign(entry, parseCommitTrailers(prBody));
156
- }
157
- sources.push(entry);
158
- }
159
- }
160
-
161
- // Agent snapshot ref
162
- const snapshotHash = git(['rev-parse', '--verify', 'refs/guard/snapshot'], { cwd: projectDir, allowFail: true });
163
- if (snapshotHash) {
164
- const snapLog = git(['log', '-1', '--format=%aI\x1f%B', 'refs/guard/snapshot'], { cwd: projectDir, allowFail: true });
165
- const snapParts = snapLog ? snapLog.split('\x1f') : [];
166
- const ts = snapParts[0] || null;
167
- const snapBody = snapParts[1] || '';
168
- const snapTrailers = parseCommitTrailers(snapBody);
169
- const snapSubject = snapBody.split('\n')[0] || '';
170
- const include = !beforeDate || (ts && Date.parse(ts) <= beforeDate.getTime());
171
- if (include) {
172
- sources.push({
173
- type: 'git-snapshot',
174
- ref: 'refs/guard/snapshot',
175
- commitHash: snapshotHash,
176
- shortHash: snapshotHash.substring(0, 7),
177
- timestamp: ts,
178
- message: snapSubject || undefined,
179
- ...snapTrailers,
180
- });
181
- }
182
- }
183
- }
184
-
185
- // Shadow copy directories
186
- const backupDir = path.join(projectDir, '.cursor-guard-backup');
187
- if (fs.existsSync(backupDir)) {
188
- try {
189
- const dirs = fs.readdirSync(backupDir, { withFileTypes: true })
190
- .filter(d => d.isDirectory())
191
- .map(d => d.name)
192
- .sort()
193
- .reverse();
194
-
195
- for (const name of dirs) {
196
- const isPreRestore = name.startsWith('pre-restore-');
197
- const isTimestamp = /^\d{8}_\d{6}(_\d{3})?$/.test(name);
198
- if (!isTimestamp && !isPreRestore) continue;
199
-
200
- if (beforeDate) {
201
- const tsName = isPreRestore ? name.slice('pre-restore-'.length) : name;
202
- const snapDate = parseShadowTimestamp(tsName);
203
- if (snapDate && snapDate.getTime() > beforeDate.getTime()) continue;
204
- }
205
-
206
- const dirPath = path.join(backupDir, name);
207
-
208
- if (opts.file && !fs.existsSync(path.join(dirPath, opts.file))) continue;
209
-
210
- sources.push({
211
- type: isPreRestore ? 'shadow-pre-restore' : 'shadow',
212
- timestamp: name,
213
- path: dirPath,
214
- });
215
- }
216
- } catch { /* ignore */ }
217
- }
218
-
219
- // Unified time sort (newest first) across all sources, then truncate
220
- sources.sort((a, b) => entryToMs(b) - entryToMs(a));
221
-
222
- return { sources: sources.slice(0, limit) };
223
- }
224
-
225
- // ── Shadow retention ────────────────────────────────────────────
226
-
227
- /**
228
- * Clean old shadow copy snapshots based on retention config.
229
- *
230
- * @param {string} backupDir - Path to .cursor-guard-backup/
231
- * @param {object} cfg - Loaded config
232
- * @returns {{ removed: number, mode: string, diskFreeGB?: number, diskWarning?: string }}
233
- */
234
- function cleanShadowRetention(backupDir, cfg) {
235
- const { mode, days, max_count, max_size_mb } = cfg.retention;
236
- let dirs;
237
- try {
238
- dirs = fs.readdirSync(backupDir, { withFileTypes: true })
239
- .filter(d => d.isDirectory() && /^\d{8}_\d{6}(_\d{3})?$/.test(d.name))
240
- .map(d => d.name)
241
- .sort()
242
- .reverse();
243
- } catch { return { removed: 0, mode }; }
244
- if (!dirs || dirs.length === 0) return { removed: 0, mode };
245
-
246
- let removed = 0;
247
-
248
- if (mode === 'days') {
249
- const cutoff = Date.now() - days * 86400000;
250
- for (const name of dirs) {
251
- const dt = parseShadowTimestamp(name);
252
- if (!dt) continue;
253
- if (dt.getTime() < cutoff) {
254
- fs.rmSync(path.join(backupDir, name), { recursive: true, force: true });
255
- removed++;
256
- }
257
- }
258
- } else if (mode === 'count') {
259
- if (dirs.length > max_count) {
260
- for (const name of dirs.slice(max_count)) {
261
- fs.rmSync(path.join(backupDir, name), { recursive: true, force: true });
262
- removed++;
263
- }
264
- }
265
- } else if (mode === 'size') {
266
- let totalBytes = 0;
267
- try {
268
- const allFiles = walkDir(backupDir, backupDir);
269
- for (const f of allFiles) {
270
- try { totalBytes += fs.statSync(f.full).size; } catch { /* skip */ }
271
- }
272
- } catch { /* ignore */ }
273
- const oldestFirst = [...dirs].reverse();
274
- for (const name of oldestFirst) {
275
- if (totalBytes / (1024 * 1024) <= max_size_mb) break;
276
- const dirPath = path.join(backupDir, name);
277
- let dirSize = 0;
278
- try {
279
- const files = walkDir(dirPath, dirPath);
280
- for (const f of files) {
281
- try { dirSize += fs.statSync(f.full).size; } catch { /* skip */ }
282
- }
283
- } catch { /* ignore */ }
284
- fs.rmSync(dirPath, { recursive: true, force: true });
285
- totalBytes -= dirSize;
286
- removed++;
287
- }
288
- }
289
-
290
- const result = { removed, mode };
291
-
292
- const freeGB = diskFreeGB(backupDir);
293
- if (freeGB !== null) {
294
- result.diskFreeGB = parseFloat(freeGB.toFixed(1));
295
- if (freeGB < 1) result.diskWarning = 'critically low';
296
- else if (freeGB < 5) result.diskWarning = 'low';
297
- }
298
-
299
- return result;
300
- }
301
-
302
- // ── Git retention ───────────────────────────────────────────────
303
-
304
- /**
305
- * Clean old git auto-backup commits by rebuilding the branch as an orphan chain.
306
- *
307
- * @param {string} branchRef
308
- * @param {string} gitDirPath
309
- * @param {object} cfg - Loaded config
310
- * @param {string} cwd - Project directory
311
- * @returns {{ kept: number, pruned: number, mode: string, rebuilt: boolean, skipped?: boolean, reason?: string }}
312
- */
313
- function cleanGitRetention(branchRef, gitDirPath, cfg, cwd) {
314
- const { mode, days, max_count } = cfg.git_retention;
315
- if (!cfg.git_retention.enabled) {
316
- return { kept: 0, pruned: 0, mode, rebuilt: false, skipped: true, reason: 'retention disabled' };
317
- }
318
-
319
- const RS = '\x1e', US = '\x1f';
320
- const out = git(['log', branchRef, `--format=%H${US}%aI${US}%cI${US}%s${US}%B${RS}`], { cwd, allowFail: true });
321
- if (!out) {
322
- return { kept: 0, pruned: 0, mode, rebuilt: false, skipped: true, reason: 'no commits on ref' };
323
- }
324
-
325
- const records = out.split(RS).filter(r => r.trim());
326
- const guardCommits = [];
327
- for (const record of records) {
328
- const fields = record.split(US);
329
- if (fields.length < 5) continue;
330
- const hash = fields[0].trim();
331
- const authorDate = fields[1].trim();
332
- const committerDate = fields[2].trim();
333
- const subject = fields[3].trim();
334
- const fullBody = fields[4].trim();
335
- if (subject.startsWith('guard: auto-backup') || subject.startsWith('guard: snapshot')) {
336
- guardCommits.push({ hash, authorDate, committerDate, subject, fullBody });
337
- }
338
- }
339
-
340
- const total = guardCommits.length;
341
- if (total === 0) {
342
- return { kept: 0, pruned: 0, mode, rebuilt: false, skipped: true, reason: 'no guard commits found' };
343
- }
344
-
345
- let keepCount = total;
346
- if (mode === 'count') {
347
- keepCount = Math.min(total, max_count);
348
- } else if (mode === 'days') {
349
- const cutoff = Date.now() - days * 86400000;
350
- keepCount = 0;
351
- for (const c of guardCommits) {
352
- if (new Date(c.authorDate).getTime() >= cutoff) keepCount++;
353
- else break;
354
- }
355
- keepCount = Math.max(keepCount, 10);
356
- }
357
-
358
- if (keepCount >= total) {
359
- return { kept: total, pruned: 0, mode, rebuilt: false };
360
- }
361
-
362
- const toKeep = guardCommits.slice(0, keepCount).reverse();
363
-
364
- function commitTreeWithDate(args, commit) {
365
- const env = {
366
- ...process.env,
367
- GIT_AUTHOR_DATE: commit.authorDate,
368
- GIT_COMMITTER_DATE: commit.committerDate,
369
- };
370
- try {
371
- return execFileSync('git', args, { cwd, env, stdio: 'pipe', encoding: 'utf-8' }).trim() || null;
372
- } catch { return null; }
373
- }
374
-
375
- const rootTree = git(['rev-parse', `${toKeep[0].hash}^{tree}`], { cwd, allowFail: true });
376
- if (!rootTree) {
377
- return { kept: total, pruned: 0, mode, rebuilt: false, reason: 'could not resolve root tree' };
378
- }
379
- const msgOf = (c) => c.fullBody || c.subject;
380
- let prevHash = commitTreeWithDate(['commit-tree', rootTree, '-m', msgOf(toKeep[0])], toKeep[0]);
381
- if (!prevHash) {
382
- return { kept: total, pruned: 0, mode, rebuilt: false, reason: 'commit-tree failed for root' };
383
- }
384
-
385
- for (let i = 1; i < toKeep.length; i++) {
386
- const tree = git(['rev-parse', `${toKeep[i].hash}^{tree}`], { cwd, allowFail: true });
387
- if (!tree) {
388
- return { kept: total, pruned: 0, mode, rebuilt: false, reason: `could not resolve tree for commit ${i}` };
389
- }
390
- prevHash = commitTreeWithDate(['commit-tree', tree, '-p', prevHash, '-m', msgOf(toKeep[i])], toKeep[i]);
391
- if (!prevHash) {
392
- return { kept: total, pruned: 0, mode, rebuilt: false, reason: `commit-tree failed at index ${i}` };
393
- }
394
- }
395
-
396
- git(['update-ref', branchRef, prevHash], { cwd, allowFail: true });
397
-
398
- return { kept: keepCount, pruned: total - keepCount, mode, rebuilt: true };
399
- }
400
-
401
- // ── Get backup file details ─────────────────────────────────────
402
-
403
- /** Git's canonical empty tree (used as diff base for root/orphan commits). */
404
- const GIT_EMPTY_TREE_SHA = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
405
-
406
- /** Normalize paths so numstat / name-status keys match (Windows vs /, quotes). */
407
- function _normalizeBackupPath(p) {
408
- if (!p) return p;
409
- let s = String(p).replace(/\\/g, '/');
410
- if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
411
- s = s.slice(1, -1).replace(/\\"/g, '"');
412
- }
413
- return s;
414
- }
415
-
416
- /** Parse one line of `git diff --numstat` (same semantics as CLI; binary => `- -`). */
417
- function _parseGitDiffNumstatLine(add, del) {
418
- if (add === '-' || del === '-') {
419
- return { added: 0, deleted: 0, binary: true };
420
- }
421
- const a = parseInt(add, 10);
422
- const d = parseInt(del, 10);
423
- return {
424
- added: Number.isNaN(a) ? 0 : a,
425
- deleted: Number.isNaN(d) ? 0 : d,
426
- binary: false,
427
- };
428
- }
429
-
430
- /**
431
- * Get structured file-level changes for a specific git backup commit.
432
- * Uses **only** `git diff --numstat` + `git diff --name-status` (same as terminal),
433
- * so +/- counts match `git diff parent..commit` 100%. Root/orphan commits diff
434
- * against the standard empty tree.
435
- *
436
- * @param {string} projectDir
437
- * @param {string} commitHash - Full or short commit hash
438
- * @returns {{ files: Array<{path: string, action: string, added: number, deleted: number}>, error?: string }}
439
- */
440
- function getBackupFiles(projectDir, commitHash) {
441
- if (!isGitRepo(projectDir)) {
442
- return { files: [], error: 'not a git repository' };
443
- }
444
-
445
- const resolved = git(['rev-parse', '--verify', commitHash], { cwd: projectDir, allowFail: true });
446
- if (!resolved) {
447
- return { files: [], error: `cannot resolve commit: ${commitHash}` };
448
- }
449
-
450
- const parentCommit = git(['rev-parse', '--verify', `${resolved}^`], { cwd: projectDir, allowFail: true });
451
- const parent = parentCommit || GIT_EMPTY_TREE_SHA;
452
-
453
- const numstatOut = git(['diff', '--numstat', parent, resolved], { cwd: projectDir, allowFail: true });
454
- const nameStatusOut = git(['diff', '--name-status', parent, resolved], { cwd: projectDir, allowFail: true });
455
-
456
- const stats = {};
457
- if (numstatOut) {
458
- for (const line of numstatOut.split('\n').filter(Boolean)) {
459
- const [add, del, ...nameParts] = line.split('\t');
460
- const fname = _normalizeBackupPath(nameParts.join('\t'));
461
- stats[fname] = _parseGitDiffNumstatLine(add, del);
462
- }
463
- }
464
-
465
- const ACTION_MAP = { M: 'modified', A: 'added', D: 'deleted' };
466
- const files = [];
467
- if (nameStatusOut) {
468
- for (const line of nameStatusOut.split('\n').filter(Boolean)) {
469
- const tab = line.indexOf('\t');
470
- if (tab < 0) continue;
471
- const code = line.substring(0, tab).trim();
472
- const filePart = line.substring(tab + 1);
473
- let action = ACTION_MAP[code];
474
- if (code.startsWith('R')) action = 'renamed';
475
- else if (code.startsWith('C')) action = 'copied';
476
- else if (!action) action = 'modified';
477
-
478
- const fileName = filePart.split('\t').pop();
479
- const norm = _normalizeBackupPath(fileName);
480
- let s = stats[norm];
481
- if (!s && fileName !== norm) s = stats[fileName];
482
- if (!s) s = { added: 0, deleted: 0, binary: false };
483
-
484
- files.push({ path: fileName, action, added: s.added, deleted: s.deleted });
485
- }
486
- }
487
-
488
- files.sort((a, b) => (b.added + b.deleted) - (a.added + a.deleted));
489
- return { files };
490
- }
491
-
492
- module.exports = { listBackups, getBackupFiles, cleanShadowRetention, cleanGitRetention, parseShadowTimestamp };
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})(?:_(\d{3}))?$/);
14
+ if (!m) return null;
15
+ const ms = m[7] ? `.${m[7]}` : '';
16
+ return new Date(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}${ms}`);
17
+ }
18
+
19
+ function parseBeforeExpression(before) {
20
+ if (!before) return null;
21
+ const iso = Date.parse(before);
22
+ if (!isNaN(iso)) return new Date(iso);
23
+ const agoMatch = before.match(/^(\d+)\s*(second|minute|hour|day|week|month)s?\s*ago$/i);
24
+ if (agoMatch) {
25
+ const n = parseInt(agoMatch[1], 10);
26
+ const unit = agoMatch[2].toLowerCase();
27
+ const ms = { second: 1000, minute: 60000, hour: 3600000, day: 86400000, week: 604800000, month: 2592000000 }[unit] || 0;
28
+ return new Date(Date.now() - n * ms);
29
+ }
30
+ return null;
31
+ }
32
+
33
+ function entryToMs(entry) {
34
+ if (!entry.timestamp) return 0;
35
+ const iso = Date.parse(entry.timestamp);
36
+ if (!isNaN(iso)) return iso;
37
+ const tsName = typeof entry.timestamp === 'string' && entry.timestamp.startsWith('pre-restore-')
38
+ ? entry.timestamp.slice('pre-restore-'.length)
39
+ : entry.timestamp;
40
+ const d = parseShadowTimestamp(tsName);
41
+ return d ? d.getTime() : 0;
42
+ }
43
+
44
+ const TRAILER_MAP = {
45
+ 'Files-Changed': { key: 'filesChanged', parse: v => parseInt(v, 10) },
46
+ 'Summary': { key: 'summary' },
47
+ 'Trigger': { key: 'trigger' },
48
+ 'Intent': { key: 'intent' },
49
+ 'Agent': { key: 'agent' },
50
+ 'Session': { key: 'session' },
51
+ 'Guard-Event': { key: 'guardEvent' },
52
+ 'From': { key: 'from' },
53
+ 'Restore-To': { key: 'restoreTo' },
54
+ 'File': { key: 'restoreFile' },
55
+ 'Guard-Diff-Base': { key: 'guardDiffBase' },
56
+ 'Guard-Scope': { key: 'guardScope' },
57
+ 'Guard-Bookmark': { key: 'guardBookmark', parse: v => String(v).trim().toLowerCase() === 'true' },
58
+ };
59
+
60
+ function parseCommitTrailers(body) {
61
+ if (!body) return {};
62
+ const result = {};
63
+ const pattern = new RegExp(`^(${Object.keys(TRAILER_MAP).join('|')}):\\s*(.+)$`);
64
+ for (const line of body.split('\n')) {
65
+ const m = line.match(pattern);
66
+ if (m) {
67
+ const def = TRAILER_MAP[m[1]];
68
+ const raw = m[2].replace(/\r/g, '');
69
+ const val = def.parse ? def.parse(raw) : raw.trim();
70
+ result[def.key] = typeof val === 'string' ? val.trim() : val;
71
+ }
72
+ }
73
+ return result;
74
+ }
75
+
76
+ // ── List backups ────────────────────────────────────────────────
77
+
78
+ /**
79
+ * List available backup/restore points from all sources.
80
+ * Returns a globally time-sorted list (newest first), truncated to `limit`.
81
+ *
82
+ * @param {string} projectDir
83
+ * @param {object} [opts]
84
+ * @param {string} [opts.file] - Filter to commits touching this relative path
85
+ * @param {string} [opts.before] - Time boundary (e.g. '10 minutes ago', ISO string)
86
+ * @param {number} [opts.limit=20] - Max total results
87
+ * @returns {{ sources: Array<{type: string, ref?: string, commitHash?: string, shortHash?: string, timestamp?: string, message?: string, path?: string, filesChanged?: number, summary?: string, trigger?: string}> }}
88
+ */
89
+ function listBackups(projectDir, opts = {}) {
90
+ const limit = opts.limit || 20;
91
+ const sources = [];
92
+
93
+ if (opts.file) {
94
+ const normalized = path.normalize(opts.file).replace(/\\/g, '/');
95
+ if (path.isAbsolute(normalized) || normalized.startsWith('..')) {
96
+ return { sources: [], error: 'file path must be relative and within project directory' };
97
+ }
98
+ }
99
+
100
+ const repo = isGitRepo(projectDir);
101
+ const beforeDate = parseBeforeExpression(opts.before);
102
+
103
+ // Git sources
104
+ if (repo) {
105
+ // Auto-backup commits (git --before handles native filtering)
106
+ const autoRef = 'refs/guard/auto-backup';
107
+ const autoExists = git(['rev-parse', '--verify', autoRef], { cwd: projectDir, allowFail: true });
108
+ if (autoExists) {
109
+ const logArgs = ['log', autoRef, '--format=%H\x1f%aI\x1f%B\x1e', `-${limit}`, '--grep=^guard:'];
110
+ if (opts.before) logArgs.push(`--before=${opts.before}`);
111
+ if (opts.file) logArgs.push('--', opts.file);
112
+ const out = git(logArgs, { cwd: projectDir, allowFail: true });
113
+ if (out) {
114
+ for (const record of out.split('\x1e').filter(r => r.trim())) {
115
+ const parts = record.split('\x1f');
116
+ if (parts.length < 3) continue;
117
+ const hash = parts[0].trim();
118
+ const timestamp = parts[1];
119
+ const body = parts[2];
120
+ const subject = body.split('\n')[0];
121
+ const trailers = parseCommitTrailers(body);
122
+ sources.push({
123
+ type: 'git-auto-backup',
124
+ ref: autoRef,
125
+ commitHash: hash,
126
+ shortHash: hash.substring(0, 7),
127
+ timestamp,
128
+ message: subject,
129
+ ...trailers,
130
+ });
131
+ }
132
+ }
133
+ }
134
+
135
+ // Pre-restore snapshots
136
+ const preRestoreRefs = git(
137
+ ['for-each-ref', 'refs/guard/pre-restore/', '--format=%(refname) %(objectname) %(*objectname) %(creatordate:iso-strict)', '--sort=-creatordate'],
138
+ { cwd: projectDir, allowFail: true }
139
+ );
140
+ if (preRestoreRefs) {
141
+ for (const line of preRestoreRefs.split('\n').filter(Boolean)) {
142
+ const parts = line.split(' ');
143
+ const ref = parts[0];
144
+ const hash = parts[1];
145
+ const timestamp = parts[3] || parts[2];
146
+ if (beforeDate && timestamp) {
147
+ const ms = Date.parse(timestamp);
148
+ if (!isNaN(ms) && ms > beforeDate.getTime()) continue;
149
+ }
150
+ const entry = {
151
+ type: 'git-pre-restore',
152
+ ref,
153
+ commitHash: hash,
154
+ shortHash: hash.substring(0, 7),
155
+ timestamp,
156
+ };
157
+ const prBody = git(['log', '-1', '--format=%B', hash], { cwd: projectDir, allowFail: true });
158
+ if (prBody) {
159
+ const prSubject = prBody.split('\n')[0];
160
+ if (prSubject) entry.message = prSubject;
161
+ Object.assign(entry, parseCommitTrailers(prBody));
162
+ }
163
+ sources.push(entry);
164
+ }
165
+ }
166
+
167
+ // Manual / IDE snapshot ref (full history on dedicated ref; no subject grep so test/custom messages still list)
168
+ const snapRef = 'refs/guard/snapshot';
169
+ const snapshotExists = git(['rev-parse', '--verify', snapRef], { cwd: projectDir, allowFail: true });
170
+ if (snapshotExists) {
171
+ const snapLogArgs = ['log', snapRef, '--format=%H\x1f%aI\x1f%B\x1e', `-${limit}`];
172
+ if (opts.before) snapLogArgs.push(`--before=${opts.before}`);
173
+ if (opts.file) snapLogArgs.push('--', opts.file);
174
+ const snapOut = git(snapLogArgs, { cwd: projectDir, allowFail: true });
175
+ if (snapOut) {
176
+ for (const record of snapOut.split('\x1e').filter(r => r.trim())) {
177
+ const parts = record.split('\x1f');
178
+ if (parts.length < 3) continue;
179
+ const hash = parts[0].trim();
180
+ const timestamp = parts[1];
181
+ const body = parts[2];
182
+ const subject = body.split('\n')[0];
183
+ const trailers = parseCommitTrailers(body);
184
+ if (beforeDate && timestamp) {
185
+ const ms = Date.parse(timestamp);
186
+ if (!isNaN(ms) && ms > beforeDate.getTime()) continue;
187
+ }
188
+ sources.push({
189
+ type: 'git-snapshot',
190
+ ref: snapRef,
191
+ commitHash: hash,
192
+ shortHash: hash.substring(0, 7),
193
+ timestamp,
194
+ message: subject || undefined,
195
+ ...trailers,
196
+ });
197
+ }
198
+ }
199
+ }
200
+ }
201
+
202
+ // Shadow copy directories
203
+ const backupDir = path.join(projectDir, '.cursor-guard-backup');
204
+ if (fs.existsSync(backupDir)) {
205
+ try {
206
+ const dirs = fs.readdirSync(backupDir, { withFileTypes: true })
207
+ .filter(d => d.isDirectory())
208
+ .map(d => d.name)
209
+ .sort()
210
+ .reverse();
211
+
212
+ for (const name of dirs) {
213
+ const isPreRestore = name.startsWith('pre-restore-');
214
+ const isTimestamp = /^\d{8}_\d{6}(_\d{3})?$/.test(name);
215
+ if (!isTimestamp && !isPreRestore) continue;
216
+
217
+ if (beforeDate) {
218
+ const tsName = isPreRestore ? name.slice('pre-restore-'.length) : name;
219
+ const snapDate = parseShadowTimestamp(tsName);
220
+ if (snapDate && snapDate.getTime() > beforeDate.getTime()) continue;
221
+ }
222
+
223
+ const dirPath = path.join(backupDir, name);
224
+
225
+ if (opts.file && !fs.existsSync(path.join(dirPath, opts.file))) continue;
226
+
227
+ sources.push({
228
+ type: isPreRestore ? 'shadow-pre-restore' : 'shadow',
229
+ timestamp: name,
230
+ path: dirPath,
231
+ });
232
+ }
233
+ } catch { /* ignore */ }
234
+ }
235
+
236
+ // Unified time sort (newest first) across all sources, then truncate
237
+ sources.sort((a, b) => entryToMs(b) - entryToMs(a));
238
+
239
+ return { sources: sources.slice(0, limit) };
240
+ }
241
+
242
+ // ── Shadow retention ────────────────────────────────────────────
243
+
244
+ /**
245
+ * Clean old shadow copy snapshots based on retention config.
246
+ *
247
+ * @param {string} backupDir - Path to .cursor-guard-backup/
248
+ * @param {object} cfg - Loaded config
249
+ * @returns {{ removed: number, mode: string, diskFreeGB?: number, diskWarning?: string }}
250
+ */
251
+ function cleanShadowRetention(backupDir, cfg) {
252
+ const { mode, days, max_count, max_size_mb } = cfg.retention;
253
+ let dirs;
254
+ try {
255
+ dirs = fs.readdirSync(backupDir, { withFileTypes: true })
256
+ .filter(d => d.isDirectory() && /^\d{8}_\d{6}(_\d{3})?$/.test(d.name))
257
+ .map(d => d.name)
258
+ .sort()
259
+ .reverse();
260
+ } catch { return { removed: 0, mode }; }
261
+ if (!dirs || dirs.length === 0) return { removed: 0, mode };
262
+
263
+ let removed = 0;
264
+
265
+ if (mode === 'days') {
266
+ const cutoff = Date.now() - days * 86400000;
267
+ for (const name of dirs) {
268
+ const dt = parseShadowTimestamp(name);
269
+ if (!dt) continue;
270
+ if (dt.getTime() < cutoff) {
271
+ fs.rmSync(path.join(backupDir, name), { recursive: true, force: true });
272
+ removed++;
273
+ }
274
+ }
275
+ } else if (mode === 'count') {
276
+ if (dirs.length > max_count) {
277
+ for (const name of dirs.slice(max_count)) {
278
+ fs.rmSync(path.join(backupDir, name), { recursive: true, force: true });
279
+ removed++;
280
+ }
281
+ }
282
+ } else if (mode === 'size') {
283
+ let totalBytes = 0;
284
+ try {
285
+ const allFiles = walkDir(backupDir, backupDir);
286
+ for (const f of allFiles) {
287
+ try { totalBytes += fs.statSync(f.full).size; } catch { /* skip */ }
288
+ }
289
+ } catch { /* ignore */ }
290
+ const oldestFirst = [...dirs].reverse();
291
+ for (const name of oldestFirst) {
292
+ if (totalBytes / (1024 * 1024) <= max_size_mb) break;
293
+ const dirPath = path.join(backupDir, name);
294
+ let dirSize = 0;
295
+ try {
296
+ const files = walkDir(dirPath, dirPath);
297
+ for (const f of files) {
298
+ try { dirSize += fs.statSync(f.full).size; } catch { /* skip */ }
299
+ }
300
+ } catch { /* ignore */ }
301
+ fs.rmSync(dirPath, { recursive: true, force: true });
302
+ totalBytes -= dirSize;
303
+ removed++;
304
+ }
305
+ }
306
+
307
+ const result = { removed, mode };
308
+
309
+ const freeGB = diskFreeGB(backupDir);
310
+ if (freeGB !== null) {
311
+ result.diskFreeGB = parseFloat(freeGB.toFixed(1));
312
+ if (freeGB < 1) result.diskWarning = 'critically low';
313
+ else if (freeGB < 5) result.diskWarning = 'low';
314
+ }
315
+
316
+ return result;
317
+ }
318
+
319
+ // ── Git retention ───────────────────────────────────────────────
320
+
321
+ /**
322
+ * Clean old git auto-backup commits by rebuilding the branch as an orphan chain.
323
+ *
324
+ * @param {string} branchRef
325
+ * @param {string} gitDirPath
326
+ * @param {object} cfg - Loaded config
327
+ * @param {string} cwd - Project directory
328
+ * @returns {{ kept: number, pruned: number, mode: string, rebuilt: boolean, skipped?: boolean, reason?: string }}
329
+ */
330
+ function cleanGitRetention(branchRef, gitDirPath, cfg, cwd) {
331
+ const { mode, days, max_count } = cfg.git_retention;
332
+ if (!cfg.git_retention.enabled) {
333
+ return { kept: 0, pruned: 0, mode, rebuilt: false, skipped: true, reason: 'retention disabled' };
334
+ }
335
+
336
+ const RS = '\x1e', US = '\x1f';
337
+ const out = git(['log', branchRef, `--format=%H${US}%aI${US}%cI${US}%s${US}%B${RS}`], { cwd, allowFail: true });
338
+ if (!out) {
339
+ return { kept: 0, pruned: 0, mode, rebuilt: false, skipped: true, reason: 'no commits on ref' };
340
+ }
341
+
342
+ const records = out.split(RS).filter(r => r.trim());
343
+ const guardCommits = [];
344
+ for (const record of records) {
345
+ const fields = record.split(US);
346
+ if (fields.length < 5) continue;
347
+ const hash = fields[0].trim();
348
+ const authorDate = fields[1].trim();
349
+ const committerDate = fields[2].trim();
350
+ const subject = fields[3].trim();
351
+ const fullBody = fields[4].trim();
352
+ if (subject.startsWith('guard: auto-backup') || subject.startsWith('guard: snapshot')) {
353
+ guardCommits.push({ hash, authorDate, committerDate, subject, fullBody });
354
+ }
355
+ }
356
+
357
+ const total = guardCommits.length;
358
+ if (total === 0) {
359
+ return { kept: 0, pruned: 0, mode, rebuilt: false, skipped: true, reason: 'no guard commits found' };
360
+ }
361
+
362
+ let keepCount = total;
363
+ if (mode === 'count') {
364
+ keepCount = Math.min(total, max_count);
365
+ } else if (mode === 'days') {
366
+ const cutoff = Date.now() - days * 86400000;
367
+ keepCount = 0;
368
+ for (const c of guardCommits) {
369
+ if (new Date(c.authorDate).getTime() >= cutoff) keepCount++;
370
+ else break;
371
+ }
372
+ keepCount = Math.max(keepCount, 10);
373
+ }
374
+
375
+ if (keepCount >= total) {
376
+ return { kept: total, pruned: 0, mode, rebuilt: false };
377
+ }
378
+
379
+ const toKeep = guardCommits.slice(0, keepCount).reverse();
380
+
381
+ function commitTreeWithDate(args, commit) {
382
+ const env = {
383
+ ...process.env,
384
+ GIT_AUTHOR_DATE: commit.authorDate,
385
+ GIT_COMMITTER_DATE: commit.committerDate,
386
+ };
387
+ try {
388
+ return execFileSync('git', args, { cwd, env, stdio: 'pipe', encoding: 'utf-8' }).trim() || null;
389
+ } catch { return null; }
390
+ }
391
+
392
+ const rootTree = git(['rev-parse', `${toKeep[0].hash}^{tree}`], { cwd, allowFail: true });
393
+ if (!rootTree) {
394
+ return { kept: total, pruned: 0, mode, rebuilt: false, reason: 'could not resolve root tree' };
395
+ }
396
+ const msgOf = (c) => c.fullBody || c.subject;
397
+ let prevHash = commitTreeWithDate(['commit-tree', rootTree, '-m', msgOf(toKeep[0])], toKeep[0]);
398
+ if (!prevHash) {
399
+ return { kept: total, pruned: 0, mode, rebuilt: false, reason: 'commit-tree failed for root' };
400
+ }
401
+
402
+ for (let i = 1; i < toKeep.length; i++) {
403
+ const tree = git(['rev-parse', `${toKeep[i].hash}^{tree}`], { cwd, allowFail: true });
404
+ if (!tree) {
405
+ return { kept: total, pruned: 0, mode, rebuilt: false, reason: `could not resolve tree for commit ${i}` };
406
+ }
407
+ prevHash = commitTreeWithDate(['commit-tree', tree, '-p', prevHash, '-m', msgOf(toKeep[i])], toKeep[i]);
408
+ if (!prevHash) {
409
+ return { kept: total, pruned: 0, mode, rebuilt: false, reason: `commit-tree failed at index ${i}` };
410
+ }
411
+ }
412
+
413
+ git(['update-ref', branchRef, prevHash], { cwd, allowFail: true });
414
+
415
+ return { kept: keepCount, pruned: total - keepCount, mode, rebuilt: true };
416
+ }
417
+
418
+ // ── Get backup file details ─────────────────────────────────────
419
+
420
+ /** Git's canonical empty tree (used as diff base for root/orphan commits). */
421
+ const GIT_EMPTY_TREE_SHA = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
422
+
423
+ /** Normalize paths so numstat / name-status keys match (Windows vs /, quotes). */
424
+ function _normalizeBackupPath(p) {
425
+ if (!p) return p;
426
+ let s = String(p).replace(/\\/g, '/');
427
+ if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
428
+ s = s.slice(1, -1).replace(/\\"/g, '"');
429
+ }
430
+ return s;
431
+ }
432
+
433
+ /** Parse one line of `git diff --numstat` (same semantics as CLI; binary => `- -`). */
434
+ function _parseGitDiffNumstatLine(add, del) {
435
+ if (add === '-' || del === '-') {
436
+ return { added: 0, deleted: 0, binary: true };
437
+ }
438
+ const a = parseInt(add, 10);
439
+ const d = parseInt(del, 10);
440
+ return {
441
+ added: Number.isNaN(a) ? 0 : a,
442
+ deleted: Number.isNaN(d) ? 0 : d,
443
+ binary: false,
444
+ };
445
+ }
446
+
447
+ /**
448
+ * Get structured file-level changes for a specific git backup commit.
449
+ * Uses **only** `git diff --numstat` + `git diff --name-status` (same as terminal),
450
+ * so +/- counts match `git diff parent..commit` 100%. Root/orphan commits diff
451
+ * against the standard empty tree.
452
+ *
453
+ * @param {string} projectDir
454
+ * @param {string} commitHash - Full or short commit hash
455
+ * @returns {{ files: Array<{path: string, action: string, added: number, deleted: number}>, error?: string }}
456
+ */
457
+ function getBackupFiles(projectDir, commitHash) {
458
+ if (!isGitRepo(projectDir)) {
459
+ return { files: [], error: 'not a git repository' };
460
+ }
461
+
462
+ const resolved = git(['rev-parse', '--verify', commitHash], { cwd: projectDir, allowFail: true });
463
+ if (!resolved) {
464
+ return { files: [], error: `cannot resolve commit: ${commitHash}` };
465
+ }
466
+
467
+ const parentCommit = git(['rev-parse', '--verify', `${resolved}^`], { cwd: projectDir, allowFail: true });
468
+ const parent = parentCommit || GIT_EMPTY_TREE_SHA;
469
+
470
+ const numstatOut = git(['diff', '--numstat', parent, resolved], { cwd: projectDir, allowFail: true });
471
+ const nameStatusOut = git(['diff', '--name-status', parent, resolved], { cwd: projectDir, allowFail: true });
472
+
473
+ const stats = {};
474
+ if (numstatOut) {
475
+ for (const line of numstatOut.split('\n').filter(Boolean)) {
476
+ const [add, del, ...nameParts] = line.split('\t');
477
+ const fname = _normalizeBackupPath(nameParts.join('\t'));
478
+ stats[fname] = _parseGitDiffNumstatLine(add, del);
479
+ }
480
+ }
481
+
482
+ const ACTION_MAP = { M: 'modified', A: 'added', D: 'deleted' };
483
+ const files = [];
484
+ if (nameStatusOut) {
485
+ for (const line of nameStatusOut.split('\n').filter(Boolean)) {
486
+ const tab = line.indexOf('\t');
487
+ if (tab < 0) continue;
488
+ const code = line.substring(0, tab).trim();
489
+ const filePart = line.substring(tab + 1);
490
+ let action = ACTION_MAP[code];
491
+ if (code.startsWith('R')) action = 'renamed';
492
+ else if (code.startsWith('C')) action = 'copied';
493
+ else if (!action) action = 'modified';
494
+
495
+ const fileName = filePart.split('\t').pop();
496
+ const norm = _normalizeBackupPath(fileName);
497
+ let s = stats[norm];
498
+ if (!s && fileName !== norm) s = stats[fileName];
499
+ if (!s) s = { added: 0, deleted: 0, binary: false };
500
+
501
+ files.push({ path: fileName, action, added: s.added, deleted: s.deleted });
502
+ }
503
+ }
504
+
505
+ files.sort((a, b) => (b.added + b.deleted) - (a.added + a.deleted));
506
+ return { files };
507
+ }
508
+
509
+ module.exports = { listBackups, getBackupFiles, cleanShadowRetention, cleanGitRetention, parseShadowTimestamp };