burnoff 1.0.0 → 1.1.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.
@@ -644,6 +644,26 @@ export function evaluateDet01GitAndShellSafety(params = {}, _depth = 0) {
644
644
  continue;
645
645
  }
646
646
 
647
+ function isExplicitTempTarget(normArg = '') {
648
+ return /^(?:\/tmp(?:\/|$)|\/var\/folders(?:\/|$)|\$tmpdir(?:\/|$)|\$\{tmpdir\}(?:\/|$)|\$\{?env:(?:temp|tmp)\}?[\\/]|(?:[a-z]:)?[\\/]?(?:temp|tmp)(?:\/|$))/i.test(
649
+ String(normArg || '').replace(/\\/g, '/')
650
+ );
651
+ }
652
+
653
+ function isProtectedRecursiveDeleteTarget(rawArg = '') {
654
+ const norm = String(rawArg || '').trim().replace(/^["']|["']$/g, '').replace(/\\/g, '/');
655
+ if (!norm || norm.startsWith('-')) return false;
656
+ if (isExplicitTempTarget(norm)) return false;
657
+ if (/^(?:\/+|\/\*|\~|\$HOME|\$\{HOME\}|\$env:USERPROFILE|[A-Za-z]:\/?)$/i.test(norm)) {
658
+ return true;
659
+ }
660
+ const stripped = norm.replace(/\/+$/, '').replace(/^\.\//, '');
661
+ if (norm === '.' || norm === './' || stripped === '' || stripped === '*') {
662
+ return true;
663
+ }
664
+ return /^(?:src|test|tests|__tests__)(?:\/\*|\/)?$/i.test(stripped);
665
+ }
666
+
647
667
  if (bin === 'rm' || bin === 'rm.exe' || bin === 'unlink' || bin === 'unlink.exe') {
648
668
  const rmArgs = rawTokens.slice(idx + 1);
649
669
  const hasRecursive = rmArgs.some(
@@ -652,16 +672,14 @@ export function evaluateDet01GitAndShellSafety(params = {}, _depth = 0) {
652
672
  const hasForce = rmArgs.some(
653
673
  (a) => a === '--force' || (/^-[a-zA-Z]+$/.test(a) && /f/.test(a))
654
674
  );
655
- const targetsRootOrHome = rmArgs.some((a) =>
656
- /^(?:\/+|\/\*|\~|\$HOME|\$\{HOME\}|[A-Za-z]:[\\/]?)$/i.test(a)
657
- );
675
+ const targetsRootOrHome = rmArgs.some((a) => isProtectedRecursiveDeleteTarget(a));
658
676
  if (hasRecursive && hasForce && targetsRootOrHome) {
659
677
  return {
660
678
  detectorId: 'DET-01',
661
679
  triggered: true,
662
680
  decision: 'deny',
663
681
  subType: 'DESTRUCTIVE_FS_WIPE',
664
- reason: '[Burnoff DET-01 Destructive Shell Blocked] Recursive root/home deletion is forbidden.'
682
+ reason: '[Burnoff DET-01 Destructive Shell Blocked] Recursive root/home/repo/src/test deletion is forbidden.'
665
683
  };
666
684
  }
667
685
  if (!userExplicitTestIntent) {
@@ -685,16 +703,14 @@ export function evaluateDet01GitAndShellSafety(params = {}, _depth = 0) {
685
703
  const psArgs = rawTokens.slice(idx + 1);
686
704
  const hasRecurse = psArgs.some((a) => /^-r(?:ecurse)?$/i.test(a));
687
705
  const hasForce = psArgs.some((a) => /^-f(?:orce)?$/i.test(a));
688
- const targetsRootOrHome = psArgs.some((a) =>
689
- /^(?:[A-Za-z]:[\\/]?|\/+|\~|\$HOME|\$env:USERPROFILE)$/i.test(a)
690
- );
706
+ const targetsRootOrHome = psArgs.some((a) => isProtectedRecursiveDeleteTarget(a));
691
707
  if (hasRecurse && hasForce && targetsRootOrHome) {
692
708
  return {
693
709
  detectorId: 'DET-01',
694
710
  triggered: true,
695
711
  decision: 'deny',
696
712
  subType: 'DESTRUCTIVE_FS_WIPE',
697
- reason: '[Burnoff DET-01 Destructive Shell Blocked] Recursive root/home deletion is forbidden.'
713
+ reason: '[Burnoff DET-01 Destructive Shell Blocked] Recursive root/home/repo/src/test deletion is forbidden.'
698
714
  };
699
715
  }
700
716
  if (!userExplicitTestIntent) {
@@ -1059,17 +1075,27 @@ export function evaluateDet02SecretBoundary(params = {}) {
1059
1075
  if (params.path) candidates.push(String(params.path));
1060
1076
 
1061
1077
  if (params.command && SHELL_TOOL_REGEX.test(String(params.toolName || 'Bash'))) {
1062
- const tokens = tokenizeShellSegment(String(params.command));
1063
- for (const tok of tokens) {
1064
- if (
1065
- tok.includes('.env') ||
1066
- tok.includes('.pem') ||
1067
- tok.includes('.ssh') ||
1068
- tok.includes('.aws') ||
1069
- tok.includes('id_rsa') ||
1070
- tok.includes('id_ed25519')
1071
- ) {
1072
- candidates.push(tok);
1078
+ const isPowerShell = detectPowerShellSyntax(params.toolName, params.command);
1079
+ const segments = splitCommandSegments(String(params.command), { isPowerShell });
1080
+ const benignGitSubs = new Set(['status', 'diff', 'log', 'branch']);
1081
+ for (const seg of segments) {
1082
+ const tokens = tokenizeShellSegment(seg, { isPowerShell });
1083
+ if (tokens.length === 0) continue;
1084
+ const bin = String(tokens[0] || '').split(/[\\/]/).pop().toLowerCase();
1085
+ if (bin === 'echo' || bin === 'printf' || bin === 'write-output' || bin === 'write-host') {
1086
+ continue;
1087
+ }
1088
+ if ((bin === 'git' || bin === 'git.exe') && benignGitSubs.has(String(tokens[1] || '').toLowerCase())) {
1089
+ continue;
1090
+ }
1091
+ for (const tok of tokens) {
1092
+ const cleaned = String(tok || '').replace(/^[<>&]+/, '').trim();
1093
+ if (!cleaned) continue;
1094
+ candidates.push(cleaned);
1095
+ if (cleaned.startsWith('-') && cleaned.includes('=')) {
1096
+ const val = cleaned.slice(cleaned.indexOf('=') + 1).trim();
1097
+ if (val) candidates.push(val);
1098
+ }
1073
1099
  }
1074
1100
  }
1075
1101
  }
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
 
4
4
  const RETRYABLE_RENAME_CODES = new Set(['EPERM', 'EBUSY', 'EACCES']);
5
- const MAX_RENAME_ATTEMPTS = 5;
5
+ const MAX_RENAME_ATTEMPTS = 8;
6
6
 
7
7
  const atomicIoMetrics = {
8
8
  renameRetries: 0,
@@ -85,7 +85,7 @@ export function atomicWriteFileSync(targetPath, content, options = {}) {
85
85
  offset += written;
86
86
  }
87
87
 
88
- if (typeof fsMod.fsyncSync === 'function') {
88
+ if (!opts.skipFsync && typeof fsMod.fsyncSync === 'function') {
89
89
  fsMod.fsyncSync(fd);
90
90
  }
91
91
  fsMod.closeSync(fd);
@@ -18,7 +18,7 @@ export const LOCK_ORDER_DOC = Object.freeze([
18
18
  'ledger_dedupe'
19
19
  ]);
20
20
 
21
- const DEFAULT_MAX_WAIT_MS = 1500;
21
+ const DEFAULT_MAX_WAIT_MS = 2500;
22
22
  const DEFAULT_STALE_MS = 5000;
23
23
 
24
24
  function isPidAlive(pid) {
@@ -37,7 +37,7 @@ function inspectLockFile(lockPath, staleMs, fsMod) {
37
37
  try {
38
38
  const raw = fsMod.readFileSync(lockPath, 'utf8');
39
39
  const parsed = JSON.parse(raw);
40
- const createdAtMs = Number(parsed?.createdAtMs || 0);
40
+ const createdAtMs = Number(parsed?.createdAtMs ?? parsed?.createdAt ?? 0);
41
41
  const pid = Number(parsed?.pid || 0);
42
42
  const ageMs = createdAtMs > 0 ? Date.now() - createdAtMs : Infinity;
43
43
  const staleByAge = ageMs > staleMs;
@@ -157,17 +157,44 @@ export function withFileLockSync(targetPath, fn, options = {}) {
157
157
  return fn();
158
158
  } finally {
159
159
  try {
160
- const currentRaw = fsMod.readFileSync(lockPath, 'utf8');
161
- const current = JSON.parse(currentRaw);
160
+ let currentRaw = null;
161
+ for (let rAttempt = 0; rAttempt < 8; rAttempt += 1) {
162
+ try {
163
+ currentRaw = fsMod.readFileSync(lockPath, 'utf8');
164
+ break;
165
+ } catch (readErr) {
166
+ if (
167
+ rAttempt < 7 &&
168
+ (readErr?.code === 'EPERM' || readErr?.code === 'EBUSY' || readErr?.code === 'EACCES')
169
+ ) {
170
+ sleepSync(5);
171
+ continue;
172
+ }
173
+ break;
174
+ }
175
+ }
176
+ const current = currentRaw ? JSON.parse(currentRaw) : null;
162
177
  if (current?.nonce === nonce) {
163
- for (let uAttempt = 0; uAttempt < 4; uAttempt += 1) {
178
+ const relPath = `${lockPath}.rel.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 6)}`;
179
+ let released = false;
180
+ for (let rAttempt = 0; rAttempt < 10; rAttempt += 1) {
164
181
  try {
165
- fsMod.unlinkSync(lockPath);
182
+ fsMod.renameSync(lockPath, relPath);
183
+ released = true;
184
+ try {
185
+ fsMod.unlinkSync(relPath);
186
+ } catch {
187
+ // ignore: renamed release tombstone cleanup best-effort
188
+ }
166
189
  break;
167
- } catch (unlinkErr) {
190
+ } catch (relErr) {
191
+ if (relErr?.code === 'ENOENT') {
192
+ released = true;
193
+ break;
194
+ }
168
195
  if (
169
- uAttempt < 3 &&
170
- (unlinkErr?.code === 'EPERM' || unlinkErr?.code === 'EBUSY' || unlinkErr?.code === 'EACCES')
196
+ rAttempt < 9 &&
197
+ (relErr?.code === 'EPERM' || relErr?.code === 'EBUSY' || relErr?.code === 'EACCES')
171
198
  ) {
172
199
  sleepSync(5);
173
200
  continue;
@@ -175,6 +202,23 @@ export function withFileLockSync(targetPath, fn, options = {}) {
175
202
  break;
176
203
  }
177
204
  }
205
+ if (!released) {
206
+ for (let uAttempt = 0; uAttempt < 8; uAttempt += 1) {
207
+ try {
208
+ fsMod.unlinkSync(lockPath);
209
+ break;
210
+ } catch (unlinkErr) {
211
+ if (
212
+ uAttempt < 7 &&
213
+ (unlinkErr?.code === 'EPERM' || unlinkErr?.code === 'EBUSY' || unlinkErr?.code === 'EACCES')
214
+ ) {
215
+ sleepSync(5);
216
+ continue;
217
+ }
218
+ break;
219
+ }
220
+ }
221
+ }
178
222
  }
179
223
  } catch {
180
224
  // ignore: lock already released or vanished
@@ -9,7 +9,7 @@
9
9
  import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import { getHomeDir, getBurnoffCacheDir } from '../config/paths.mjs';
12
- import { openBurnoffDb } from './sqlite-client.mjs';
12
+ import { openBurnoffDb, resolveFallbackDbPath } from './sqlite-client.mjs';
13
13
  import { recordInterventionSavings } from './ledger.mjs';
14
14
 
15
15
  export const FTS5_COMPRESSOR_CONSTANTS = Object.freeze({
@@ -380,7 +380,8 @@ export function compressCliOutputFts5Sync({
380
380
  recordLedger = true,
381
381
  ledgerPath = null,
382
382
  minBytes = 0,
383
- minTokensSaved = 0
383
+ minTokensSaved = 0,
384
+ retentionDays = 30
384
385
  } = {}) {
385
386
  const rawStr = String(rawOutput || '');
386
387
  const rawLines = rawStr.split(/\r?\n/);
@@ -441,7 +442,7 @@ export function compressCliOutputFts5Sync({
441
442
  );
442
443
 
443
444
  try {
444
- pruneExpiredFts5LogsSync(db);
445
+ pruneExpiredFts5LogsSync(db, Date.now(), Number(retentionDays ?? 30));
445
446
  } catch (pruneErr) {
446
447
  void pruneErr; // ignore: non-fatal background retention prune
447
448
  }
@@ -601,7 +602,7 @@ export async function searchToolLogsFts5(dbPath, {
601
602
  DatabaseSync = null
602
603
  } = {}) {
603
604
  const resolvedDbPath = dbPath || getDefaultToolLogsDbPath(homeDir);
604
- if (!fs.existsSync(resolvedDbPath)) {
605
+ if (!fs.existsSync(resolvedDbPath) && !fs.existsSync(resolveFallbackDbPath(resolvedDbPath))) {
605
606
  return { hits: [], matchedLines: [] };
606
607
  }
607
608
 
@@ -609,26 +610,40 @@ export async function searchToolLogsFts5(dbPath, {
609
610
  try {
610
611
  db = openBurnoffDb(resolvedDbPath, { readOnly: true, DatabaseSync });
611
612
  const cleanKeyword = String(keyword || '').replace(/[^A-Za-z0-9_./:-]/g, ' ').trim();
613
+ const maxLimit = Math.max(1, Number(limit) || 10);
614
+ const cleanTurnId = turnId ? String(turnId) : '';
612
615
 
613
616
  let rows = [];
614
617
  if (cleanKeyword) {
615
618
  const ftsToken = cleanKeyword.split(/\s+/).filter(Boolean).map((t) => `"${t}"`).join(' AND ');
619
+ if (cleanTurnId) {
620
+ rows = db.prepare(`
621
+ SELECT session_id AS sessionId, turn_id AS turnId, command, exit_code AS exitCode, raw_output AS rawOutput, created_at AS createdAt
622
+ FROM tool_logs
623
+ WHERE turn_id = ? AND tool_logs MATCH ?
624
+ LIMIT ?
625
+ `).all(cleanTurnId, ftsToken, maxLimit);
626
+ } else {
627
+ rows = db.prepare(`
628
+ SELECT session_id AS sessionId, turn_id AS turnId, command, exit_code AS exitCode, raw_output AS rawOutput, created_at AS createdAt
629
+ FROM tool_logs
630
+ WHERE tool_logs MATCH ?
631
+ LIMIT ?
632
+ `).all(ftsToken, maxLimit);
633
+ }
634
+ } else if (cleanTurnId) {
616
635
  rows = db.prepare(`
617
636
  SELECT session_id AS sessionId, turn_id AS turnId, command, exit_code AS exitCode, raw_output AS rawOutput, created_at AS createdAt
618
637
  FROM tool_logs
619
- WHERE tool_logs MATCH ?
638
+ WHERE turn_id = ?
620
639
  LIMIT ?
621
- `).all(ftsToken, Math.max(1, limit));
640
+ `).all(cleanTurnId, maxLimit);
622
641
  } else {
623
642
  rows = db.prepare(`
624
643
  SELECT session_id AS sessionId, turn_id AS turnId, command, exit_code AS exitCode, raw_output AS rawOutput, created_at AS createdAt
625
644
  FROM tool_logs
626
645
  LIMIT ?
627
- `).all(Math.max(1, limit));
628
- }
629
-
630
- if (turnId) {
631
- rows = rows.filter((r) => String(r.turnId) === String(turnId));
646
+ `).all(maxLimit);
632
647
  }
633
648
 
634
649
  const matchedLines = [];
@@ -669,7 +684,7 @@ export async function searchFts5Logs(options = {}) {
669
684
 
670
685
  export function getFts5CompressionStats(dbPath = null, { DatabaseSync = null, homeDir = getHomeDir() } = {}) {
671
686
  const resolvedDbPath = dbPath || getDefaultToolLogsDbPath(homeDir);
672
- if (!fs.existsSync(resolvedDbPath)) {
687
+ if (!fs.existsSync(resolvedDbPath) && !fs.existsSync(resolveFallbackDbPath(resolvedDbPath))) {
673
688
  return { active: true, logCount: 0, savedTokens: 0, formattedSavedK: '0.0k' };
674
689
  }
675
690