@use-aistack/cli 0.20.6 → 0.21.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.
package/dist/index.js CHANGED
@@ -62,9 +62,9 @@ var init_errors = __esm({
62
62
  code;
63
63
  details;
64
64
  name = "SessionIntegrityError";
65
- constructor(code, message, details) {
65
+ constructor(code2, message, details) {
66
66
  super(message);
67
- this.code = code;
67
+ this.code = code2;
68
68
  this.details = details;
69
69
  if (Error.captureStackTrace)
70
70
  Error.captureStackTrace(this, _SessionIntegrityError);
@@ -237,7 +237,7 @@ var init_errors = __esm({
237
237
  ...new Set(cleanupErrors.flatMap((error) => error.details.unverifiedResiduePaths))
238
238
  ].sort(compareCodePoints);
239
239
  const unverifiedResidueSet = new Set(unverifiedResiduePaths);
240
- const residuePaths = [...new Set(cleanupErrors.flatMap((error) => error.details.residuePaths))].filter((path17) => !unverifiedResidueSet.has(path17)).sort(compareCodePoints);
240
+ const residuePaths = [...new Set(cleanupErrors.flatMap((error) => error.details.residuePaths))].filter((path19) => !unverifiedResidueSet.has(path19)).sort(compareCodePoints);
241
241
  const cleanupRemedy = residuePaths.length > 0 || unverifiedResiduePaths.length > 0 ? " Remove only verified private temporary paths after confirming no operation is active; do not delete unverified paths blindly." : "";
242
242
  super("RESTORE_ROLLBACK_INCOMPLETE", "Restore failed after one or more files were published; automatic rollback was not attempted.", {
243
243
  publishedFileCount,
@@ -256,10 +256,10 @@ var init_errors = __esm({
256
256
  };
257
257
  ReadContextError = class extends SessionIntegrityError {
258
258
  name = "ReadContextError";
259
- constructor(code, message, field) {
260
- super(code, message, {
259
+ constructor(code2, message, field) {
260
+ super(code2, message, {
261
261
  field,
262
- remedy: code === "READ_CONTEXT_DISPOSED" ? "Create a new read context." : "Create a new read context with one immutable source, scope, and option binding."
262
+ remedy: code2 === "READ_CONTEXT_DISPOSED" ? "Create a new read context." : "Create a new read context with one immutable source, scope, and option binding."
263
263
  });
264
264
  }
265
265
  };
@@ -477,9 +477,9 @@ var init_errors3 = __esm({
477
477
  name = "DatabaseLockedError";
478
478
  /** Path to locked database file */
479
479
  path;
480
- constructor(path17) {
481
- super(`Database is locked: ${path17}. Close Cursor or retry later.`);
482
- this.path = path17;
480
+ constructor(path19) {
481
+ super(`Database is locked: ${path19}. Close Cursor or retry later.`);
482
+ this.path = path19;
483
483
  if (Error.captureStackTrace) {
484
484
  Error.captureStackTrace(this, _DatabaseLockedError);
485
485
  }
@@ -489,9 +489,9 @@ var init_errors3 = __esm({
489
489
  name = "DatabaseNotFoundError";
490
490
  /** Path that was not found */
491
491
  path;
492
- constructor(path17) {
493
- super(`Database not found: ${path17}. Check dataPath configuration.`);
494
- this.path = path17;
492
+ constructor(path19) {
493
+ super(`Database not found: ${path19}. Check dataPath configuration.`);
494
+ this.path = path19;
495
495
  if (Error.captureStackTrace) {
496
496
  Error.captureStackTrace(this, _DatabaseNotFoundError);
497
497
  }
@@ -543,9 +543,9 @@ var init_errors3 = __esm({
543
543
  name = "WorkspaceNotFoundError";
544
544
  /** The workspace path that was not found */
545
545
  path;
546
- constructor(path17) {
547
- super(`No workspace found for path: ${path17}. Please open the project in Cursor first.`);
548
- this.path = path17;
546
+ constructor(path19) {
547
+ super(`No workspace found for path: ${path19}. Please open the project in Cursor first.`);
548
+ this.path = path19;
549
549
  if (Error.captureStackTrace) {
550
550
  Error.captureStackTrace(this, _WorkspaceNotFoundError);
551
551
  }
@@ -555,9 +555,9 @@ var init_errors3 = __esm({
555
555
  name = "SameWorkspaceError";
556
556
  /** The path that was specified for both source and destination */
557
557
  path;
558
- constructor(path17) {
559
- super(`Source and destination are the same: ${path17}`);
560
- this.path = path17;
558
+ constructor(path19) {
559
+ super(`Source and destination are the same: ${path19}`);
560
+ this.path = path19;
561
561
  if (Error.captureStackTrace) {
562
562
  Error.captureStackTrace(this, _SameWorkspaceError);
563
563
  }
@@ -567,9 +567,9 @@ var init_errors3 = __esm({
567
567
  name = "NoSessionsFoundError";
568
568
  /** The source workspace path */
569
569
  path;
570
- constructor(path17) {
571
- super(`No sessions found for workspace: ${path17}. Use 'cursor-history list --workspace "${path17}"' to verify.`);
572
- this.path = path17;
570
+ constructor(path19) {
571
+ super(`No sessions found for workspace: ${path19}. Use 'cursor-history list --workspace "${path19}"' to verify.`);
572
+ this.path = path19;
573
573
  if (Error.captureStackTrace) {
574
574
  Error.captureStackTrace(this, _NoSessionsFoundError);
575
575
  }
@@ -581,9 +581,9 @@ var init_errors3 = __esm({
581
581
  path;
582
582
  /** Number of existing sessions at destination */
583
583
  sessionCount;
584
- constructor(path17, sessionCount) {
585
- super(`Destination already has ${sessionCount} session(s): ${path17}. Use --force to proceed (will add sessions alongside existing ones).`);
586
- this.path = path17;
584
+ constructor(path19, sessionCount) {
585
+ super(`Destination already has ${sessionCount} session(s): ${path19}. Use --force to proceed (will add sessions alongside existing ones).`);
586
+ this.path = path19;
587
587
  this.sessionCount = sessionCount;
588
588
  if (Error.captureStackTrace) {
589
589
  Error.captureStackTrace(this, _DestinationHasSessionsError);
@@ -618,9 +618,9 @@ var init_errors3 = __esm({
618
618
  name = "NoDataError";
619
619
  /** Path that was checked for data */
620
620
  path;
621
- constructor(path17) {
622
- super(`No Cursor data found at: ${path17}. Verify Cursor is installed and has been used.`);
623
- this.path = path17;
621
+ constructor(path19) {
622
+ super(`No Cursor data found at: ${path19}. Verify Cursor is installed and has been used.`);
623
+ this.path = path19;
624
624
  if (Error.captureStackTrace) {
625
625
  Error.captureStackTrace(this, _NoDataError);
626
626
  }
@@ -630,9 +630,9 @@ var init_errors3 = __esm({
630
630
  name = "FileExistsError";
631
631
  /** Path to existing file */
632
632
  path;
633
- constructor(path17) {
634
- super(`File already exists: ${path17}. Use --force to overwrite.`);
635
- this.path = path17;
633
+ constructor(path19) {
634
+ super(`File already exists: ${path19}. Use --force to overwrite.`);
635
+ this.path = path19;
636
636
  if (Error.captureStackTrace) {
637
637
  Error.captureStackTrace(this, _FileExistsError);
638
638
  }
@@ -668,9 +668,9 @@ var init_errors3 = __esm({
668
668
  name = "BackupNotFoundError";
669
669
  /** Path to backup file that was not found */
670
670
  path;
671
- constructor(path17) {
672
- super(`Backup file not found: ${path17}`);
673
- this.path = path17;
671
+ constructor(path19) {
672
+ super(`Backup file not found: ${path19}`);
673
+ this.path = path19;
674
674
  if (Error.captureStackTrace) {
675
675
  Error.captureStackTrace(this, _BackupNotFoundError);
676
676
  }
@@ -682,9 +682,9 @@ var init_errors3 = __esm({
682
682
  path;
683
683
  /** Reason for invalidity */
684
684
  reason;
685
- constructor(path17, reason) {
686
- super(`Invalid backup file: ${path17}. ${reason}`);
687
- this.path = path17;
685
+ constructor(path19, reason) {
686
+ super(`Invalid backup file: ${path19}. ${reason}`);
687
+ this.path = path19;
688
688
  this.reason = reason;
689
689
  if (Error.captureStackTrace) {
690
690
  Error.captureStackTrace(this, _InvalidBackupError);
@@ -695,9 +695,9 @@ var init_errors3 = __esm({
695
695
  name = "TargetExistsError";
696
696
  /** Path to existing target */
697
697
  path;
698
- constructor(path17) {
699
- super(`Target already has Cursor data: ${path17}. Use --force to overwrite.`);
700
- this.path = path17;
698
+ constructor(path19) {
699
+ super(`Target already has Cursor data: ${path19}. Use --force to overwrite.`);
700
+ this.path = path19;
701
701
  if (Error.captureStackTrace) {
702
702
  Error.captureStackTrace(this, _TargetExistsError);
703
703
  }
@@ -787,18 +787,18 @@ function getCursorDataPath(customPath) {
787
787
  function getGlobalStoragePath(customDataPath) {
788
788
  return join6(dirname3(getCursorDataPath(customDataPath)), "globalStorage");
789
789
  }
790
- function expandPath(path17) {
791
- if (path17.startsWith("~")) {
792
- return join6(homedir10(), path17.slice(1));
790
+ function expandPath(path19) {
791
+ if (path19.startsWith("~")) {
792
+ return join6(homedir10(), path19.slice(1));
793
793
  }
794
- return path17;
794
+ return path19;
795
795
  }
796
- function contractPath(path17) {
796
+ function contractPath(path19) {
797
797
  const home = homedir10();
798
- if (path17.startsWith(home)) {
799
- return "~" + path17.slice(home.length);
798
+ if (path19.startsWith(home)) {
799
+ return "~" + path19.slice(home.length);
800
800
  }
801
- return path17;
801
+ return path19;
802
802
  }
803
803
  function normalizePath(filePath) {
804
804
  let normalized = filePath;
@@ -1439,8 +1439,8 @@ function normalizePublicWorkspacePath(value) {
1439
1439
  return void 0;
1440
1440
  }
1441
1441
  }
1442
- function exactComparisonKey(path17) {
1443
- return path17.caseInsensitive ? path17.path.toLowerCase() : path17.path;
1442
+ function exactComparisonKey(path19) {
1443
+ return path19.caseInsensitive ? path19.path.toLowerCase() : path19.path;
1444
1444
  }
1445
1445
  function componentsEndWith(candidate, request2) {
1446
1446
  if (request2.drive && candidate.drive !== request2.drive)
@@ -1913,12 +1913,12 @@ function extractCodeBlocks(content) {
1913
1913
  let match;
1914
1914
  while ((match = regex.exec(content)) !== null) {
1915
1915
  const language = match[1] || null;
1916
- const code = match[2] ?? "";
1916
+ const code2 = match[2] ?? "";
1917
1917
  const beforeMatch = content.slice(0, match.index);
1918
1918
  const startLine = beforeMatch.split("\n").length - 1;
1919
1919
  blocks.push({
1920
1920
  language,
1921
- content: code.trimEnd(),
1921
+ content: code2.trimEnd(),
1922
1922
  startLine
1923
1923
  });
1924
1924
  }
@@ -2842,14 +2842,14 @@ var init_registry = __esm({
2842
2842
  return this.selectDatabaseDriver(request2);
2843
2843
  }
2844
2844
  /** Open a database in read-only mode. */
2845
- async openDatabase(path17, request2 = READ_SESSION_REQUEST) {
2845
+ async openDatabase(path19, request2 = READ_SESSION_REQUEST) {
2846
2846
  const driver = await this.ensureDriver(request2);
2847
- return openObservedDatabase(request2.io, request2, () => driver.open(path17, { readonly: true }));
2847
+ return openObservedDatabase(request2.io, request2, () => driver.open(path19, { readonly: true }));
2848
2848
  }
2849
2849
  /** Open a database in read-write mode. */
2850
- async openDatabaseReadWrite(path17, request2 = MIGRATION_REQUEST) {
2850
+ async openDatabaseReadWrite(path19, request2 = MIGRATION_REQUEST) {
2851
2851
  const driver = await this.ensureDriver(request2);
2852
- return openObservedDatabase(request2.io, request2, () => driver.open(path17, { readonly: false }));
2852
+ return openObservedDatabase(request2.io, request2, () => driver.open(path19, { readonly: false }));
2853
2853
  }
2854
2854
  /**
2855
2855
  * Synchronous database open (requires a completed capability-aware selection).
@@ -2857,11 +2857,11 @@ var init_registry = __esm({
2857
2857
  * This remains for backup parsing paths that perform synchronous reads after an awaited
2858
2858
  * selection or snapshot operation.
2859
2859
  */
2860
- openSync(path17, options) {
2860
+ openSync(path19, options) {
2861
2861
  if (!this.currentDriver) {
2862
2862
  throw new Error("No driver is currently active. Capability-aware selection must complete before using openSync().");
2863
2863
  }
2864
- return this.currentDriver.open(path17, options);
2864
+ return this.currentDriver.open(path19, options);
2865
2865
  }
2866
2866
  /** Create an online database snapshot with a provider satisfying the complete request. */
2867
2867
  async backupDatabase(sourcePath, destPath, request2 = BACKUP_REQUEST) {
@@ -3008,12 +3008,12 @@ var init_better_sqlite3 = __esm({
3008
3008
  getCapabilityProfile() {
3009
3009
  return loadBetterSqlite3Profile();
3010
3010
  },
3011
- open(path17, options) {
3011
+ open(path19, options) {
3012
3012
  if (!BetterSqlite3) {
3013
3013
  throw new Error("better-sqlite3 is not loaded. Call isAvailable() first.");
3014
3014
  }
3015
- const db = new BetterSqlite3(path17, { readonly: options.readonly });
3016
- debugLog(`Opened database with better-sqlite3: ${path17} (readonly: ${options.readonly})`);
3015
+ const db = new BetterSqlite3(path19, { readonly: options.readonly });
3016
+ debugLog(`Opened database with better-sqlite3: ${path19} (readonly: ${options.readonly})`);
3017
3017
  return new BetterSqlite3Database(db);
3018
3018
  },
3019
3019
  async backup(sourcePath, destPath) {
@@ -3204,12 +3204,12 @@ var init_node_sqlite = __esm({
3204
3204
  getCapabilityProfile() {
3205
3205
  return loadNodeSqliteProfile();
3206
3206
  },
3207
- open(path17, options) {
3207
+ open(path19, options) {
3208
3208
  if (!nodeSqliteModule) {
3209
3209
  throw new Error("node:sqlite is not loaded. Call isAvailable() first.");
3210
3210
  }
3211
- const db = new nodeSqliteModule.DatabaseSync(path17, { readOnly: options.readonly });
3212
- debugLog(`Opened database with node:sqlite: ${path17} (readonly: ${options.readonly})`);
3211
+ const db = new nodeSqliteModule.DatabaseSync(path19, { readOnly: options.readonly });
3212
+ debugLog(`Opened database with node:sqlite: ${path19} (readonly: ${options.readonly})`);
3213
3213
  return new NodeSqliteDatabaseWrapper(db, options.readonly);
3214
3214
  },
3215
3215
  async backup(sourcePath, destPath) {
@@ -3233,11 +3233,11 @@ var init_node_sqlite = __esm({
3233
3233
  });
3234
3234
 
3235
3235
  // ../../node_modules/.pnpm/cursor-history@0.18.0_patch_hash=dbff0ea0e399ea9504168452170a23ee2b432a6dc6a69a20b49bf95ef139fa74/node_modules/cursor-history/dist/core/database/index.js
3236
- async function openDatabase(path17, request2) {
3237
- return registry.openDatabase(path17, request2);
3236
+ async function openDatabase(path19, request2) {
3237
+ return registry.openDatabase(path19, request2);
3238
3238
  }
3239
- async function openDatabaseReadWrite(path17, request2) {
3240
- return registry.openDatabaseReadWrite(path17, request2);
3239
+ async function openDatabaseReadWrite(path19, request2) {
3240
+ return registry.openDatabaseReadWrite(path19, request2);
3241
3241
  }
3242
3242
  function getActiveDriver() {
3243
3243
  return registry.getActiveDriver();
@@ -3374,8 +3374,8 @@ function exclusiveFlags() {
3374
3374
  flags |= constants.O_NOFOLLOW;
3375
3375
  return flags;
3376
3376
  }
3377
- function createExclusivePrivateFile(path17, contents) {
3378
- const descriptor = openSync(path17, exclusiveFlags(), 384);
3377
+ function createExclusivePrivateFile(path19, contents) {
3378
+ const descriptor = openSync(path19, exclusiveFlags(), 384);
3379
3379
  try {
3380
3380
  if (IS_PERMISSION_AWARE_POSIX)
3381
3381
  fchmodSync(descriptor, 384);
@@ -3387,10 +3387,10 @@ function createExclusivePrivateFile(path17, contents) {
3387
3387
  closeSync(descriptor);
3388
3388
  }
3389
3389
  }
3390
- function attemptRemoveEntryNoFollow(path17) {
3390
+ function attemptRemoveEntryNoFollow(path19) {
3391
3391
  let stats;
3392
3392
  try {
3393
- stats = lstatSync(path17);
3393
+ stats = lstatSync(path19);
3394
3394
  } catch (error) {
3395
3395
  if (!isMissing(error)) {
3396
3396
  }
@@ -3398,13 +3398,13 @@ function attemptRemoveEntryNoFollow(path17) {
3398
3398
  }
3399
3399
  if (stats.isDirectory() && !stats.isSymbolicLink()) {
3400
3400
  try {
3401
- rmdirSync(path17);
3401
+ rmdirSync(path19);
3402
3402
  } catch {
3403
3403
  }
3404
3404
  return;
3405
3405
  }
3406
3406
  try {
3407
- unlinkSync(path17);
3407
+ unlinkSync(path19);
3408
3408
  } catch {
3409
3409
  }
3410
3410
  }
@@ -3432,9 +3432,9 @@ function attemptRemoveWorkspaceNoFollow(directoryPath) {
3432
3432
  } catch {
3433
3433
  }
3434
3434
  }
3435
- function mayStillExist(path17) {
3435
+ function mayStillExist(path19) {
3436
3436
  try {
3437
- lstatSync(path17);
3437
+ lstatSync(path19);
3438
3438
  return true;
3439
3439
  } catch (error) {
3440
3440
  return !isMissing(error);
@@ -3731,8 +3731,8 @@ var init_private_temp = __esm({
3731
3731
  stateValue = "open";
3732
3732
  abortSignal;
3733
3733
  abortHandler;
3734
- constructor(path17, marker, markerPath, signal) {
3735
- this.path = path17;
3734
+ constructor(path19, marker, markerPath, signal) {
3735
+ this.path = path19;
3736
3736
  this.marker = marker;
3737
3737
  this.trackedPaths.add(markerPath);
3738
3738
  this.abortSignal = signal;
@@ -3763,9 +3763,9 @@ var init_private_temp = __esm({
3763
3763
  createExclusivePrivateFile(filePath);
3764
3764
  return filePath;
3765
3765
  }
3766
- register(path17) {
3766
+ register(path19) {
3767
3767
  this.assertOpen();
3768
- const candidatePath = resolve(path17);
3768
+ const candidatePath = resolve(path19);
3769
3769
  if (!isDirectChildPath(this.path, candidatePath)) {
3770
3770
  throw new TypeError("Tracked temporary artifacts must be direct children of their private workspace.");
3771
3771
  }
@@ -3779,8 +3779,8 @@ var init_private_temp = __esm({
3779
3779
  this.abortSignal.removeEventListener("abort", this.abortHandler);
3780
3780
  }
3781
3781
  const tracked = [...this.trackedPaths].sort((left, right) => right.length - left.length);
3782
- for (const path17 of tracked)
3783
- attemptRemoveEntryNoFollow(path17);
3782
+ for (const path19 of tracked)
3783
+ attemptRemoveEntryNoFollow(path19);
3784
3784
  attemptRemoveWorkspaceNoFollow(this.path);
3785
3785
  const residuePaths = tracked.filter(mayStillExist);
3786
3786
  if (mayStillExist(this.path))
@@ -4803,8 +4803,8 @@ async function writeBoundedZipArchive(destinationPath, inputs, options = {}) {
4803
4803
  throw error;
4804
4804
  }
4805
4805
  }
4806
- async function openBoundedZipArchive(path17, options) {
4807
- return BoundedZipArchive.open(path17, options);
4806
+ async function openBoundedZipArchive(path19, options) {
4807
+ return BoundedZipArchive.open(path19, options);
4808
4808
  }
4809
4809
  var EOCD_SIGNATURE, ZIP64_EOCD_SIGNATURE, ZIP64_LOCATOR_SIGNATURE, CENTRAL_FILE_SIGNATURE, LOCAL_FILE_SIGNATURE, ZIP64_EXTRA_FIELD_ID, MAX_EOCD_SEARCH_BYTES, UTF8_FLAG, ENCRYPTED_FLAG, STRONG_ENCRYPTION_FLAG, DATA_DESCRIPTOR_FLAG, STORE_METHOD, DEFLATE_METHOD, MANIFEST_MEMORY_LIMIT, STREAM_CHUNK_BYTES, ZIP_LIMIT_FIELDS, ZipArchiveFormatError, CRC32_TABLE, CompressedVerifier, OutputIntegrityVerifier, BoundedZipArchive;
4810
4810
  var init_zip_stream = __esm({
@@ -4950,8 +4950,8 @@ var init_zip_stream = __esm({
4950
4950
  actualAggregateBytes = 0;
4951
4951
  byName;
4952
4952
  localEndBoundary;
4953
- constructor(path17, entries, archiveSize, centralOffset, handle, limits, signal, io) {
4954
- this.path = path17;
4953
+ constructor(path19, entries, archiveSize, centralOffset, handle, limits, signal, io) {
4954
+ this.path = path19;
4955
4955
  this.entries = entries;
4956
4956
  this.archiveSize = archiveSize;
4957
4957
  this.centralOffset = centralOffset;
@@ -4963,7 +4963,7 @@ var init_zip_stream = __esm({
4963
4963
  const offsets = entries.map((entry) => entry.localHeaderOffset).sort((a, b) => a - b);
4964
4964
  this.localEndBoundary = new Map(offsets.map((offset, index) => [offset, offsets[index + 1] ?? centralOffset]));
4965
4965
  }
4966
- static async open(path17, options = {}) {
4966
+ static async open(path19, options = {}) {
4967
4967
  const limits = resolveSourceReadLimits(options.sourceReadLimits);
4968
4968
  throwIfAborted(options.signal);
4969
4969
  if (options.io) {
@@ -4973,7 +4973,7 @@ var init_zip_stream = __esm({
4973
4973
  resourceClass: "backup-central-directory"
4974
4974
  });
4975
4975
  }
4976
- const handle = await open2(path17, "r");
4976
+ const handle = await open2(path19, "r");
4977
4977
  try {
4978
4978
  if (options.io) {
4979
4979
  observeAdapterIo(options.io, {
@@ -4989,7 +4989,7 @@ var init_zip_stream = __esm({
4989
4989
  const archiveSize = toSafeOffset(metadata.size, "ZIP archive size");
4990
4990
  const central = await locateCentralDirectory(handle, archiveSize, options.signal);
4991
4991
  const entries = await parseCentralDirectory(handle, archiveSize, central, limits, options.signal);
4992
- return new _BoundedZipArchive(path17, entries, archiveSize, central.offset, handle, limits, options.signal, options.io);
4992
+ return new _BoundedZipArchive(path19, entries, archiveSize, central.offset, handle, limits, options.signal, options.io);
4993
4993
  } catch (error) {
4994
4994
  await handle.close();
4995
4995
  throw error;
@@ -5495,16 +5495,16 @@ var init_composer_sqlite = __esm({
5495
5495
 
5496
5496
  // ../../node_modules/.pnpm/cursor-history@0.18.0_patch_hash=dbff0ea0e399ea9504168452170a23ee2b432a6dc6a69a20b49bf95ef139fa74/node_modules/cursor-history/dist/core/backup-publication.js
5497
5497
  import { closeSync as closeSync2, constants as constants2, fchmodSync as fchmodSync2, fstatSync as fstatSync2, lstatSync as lstatSync2, openSync as openSync2 } from "node:fs";
5498
- function projectStat(stat10) {
5498
+ function projectStat(stat12) {
5499
5499
  return {
5500
- device: BigInt(stat10.dev),
5501
- inode: BigInt(stat10.ino),
5502
- mode: Number(stat10.mode) & 511,
5503
- regularFile: stat10.isFile()
5500
+ device: BigInt(stat12.dev),
5501
+ inode: BigInt(stat12.ino),
5502
+ mode: Number(stat12.mode) & 511,
5503
+ regularFile: stat12.isFile()
5504
5504
  };
5505
5505
  }
5506
- function hasIdentity(stat10, expected) {
5507
- return stat10.device === expected.device && stat10.inode === expected.inode;
5506
+ function hasIdentity(stat12, expected) {
5507
+ return stat12.device === expected.device && stat12.inode === expected.inode;
5508
5508
  }
5509
5509
  function identityError(message) {
5510
5510
  const error = new Error(message);
@@ -5573,10 +5573,10 @@ var init_backup_publication = __esm({
5573
5573
  "use strict";
5574
5574
  init_errors();
5575
5575
  DEFAULT_MODE_OPERATIONS = Object.freeze({
5576
- openNoFollow: (path17) => openSync2(path17, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0)),
5576
+ openNoFollow: (path19) => openSync2(path19, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0)),
5577
5577
  statDescriptor: (descriptor) => projectStat(fstatSync2(descriptor, { bigint: true })),
5578
5578
  chmodDescriptor: (descriptor, mode) => fchmodSync2(descriptor, mode),
5579
- statPathNoFollow: (path17) => projectStat(lstatSync2(path17, { bigint: true })),
5579
+ statPathNoFollow: (path19) => projectStat(lstatSync2(path19, { bigint: true })),
5580
5580
  close: (descriptor) => closeSync2(descriptor)
5581
5581
  });
5582
5582
  }
@@ -5587,12 +5587,12 @@ import { linkSync, lstatSync as lstatSync3, renameSync, unlinkSync as unlinkSync
5587
5587
  function errorCode(error) {
5588
5588
  return error instanceof Error && "code" in error ? String(error.code) : void 0;
5589
5589
  }
5590
- function hasIdentity2(stat10, expected) {
5591
- return stat10.isFile() && stat10.dev === expected.device && stat10.ino === expected.inode;
5590
+ function hasIdentity2(stat12, expected) {
5591
+ return stat12.isFile() && stat12.dev === expected.device && stat12.ino === expected.inode;
5592
5592
  }
5593
- function pathIdentityVerified(path17, expected, operations) {
5593
+ function pathIdentityVerified(path19, expected, operations) {
5594
5594
  try {
5595
- return hasIdentity2(operations.statPathNoFollow(path17), expected);
5595
+ return hasIdentity2(operations.statPathNoFollow(path19), expected);
5596
5596
  } catch {
5597
5597
  return false;
5598
5598
  }
@@ -5643,8 +5643,8 @@ var init_backup_archive_publication = __esm({
5643
5643
  DEFAULT_OPERATIONS = Object.freeze({
5644
5644
  rename: (sourcePath, destinationPath) => renameSync(sourcePath, destinationPath),
5645
5645
  link: (sourcePath, destinationPath) => linkSync(sourcePath, destinationPath),
5646
- unlink: (path17) => unlinkSync2(path17),
5647
- statPathNoFollow: (path17) => lstatSync3(path17, { bigint: true })
5646
+ unlink: (path19) => unlinkSync2(path19),
5647
+ statPathNoFollow: (path19) => lstatSync3(path19, { bigint: true })
5648
5648
  });
5649
5649
  }
5650
5650
  });
@@ -5654,11 +5654,11 @@ import { linkSync as linkSync2, lstatSync as lstatSync4, renameSync as renameSyn
5654
5654
  function errorCode2(error) {
5655
5655
  return error instanceof Error && "code" in error ? String(error.code) : void 0;
5656
5656
  }
5657
- function hasIdentity3(stat10, expected) {
5658
- return stat10.isFile() && stat10.dev === expected.device && stat10.ino === expected.inode;
5657
+ function hasIdentity3(stat12, expected) {
5658
+ return stat12.isFile() && stat12.dev === expected.device && stat12.ino === expected.inode;
5659
5659
  }
5660
- function cleanupError(path17, cause, identityVerified = true) {
5661
- const error = new TemporaryArtifactCleanupError(identityVerified ? [path17] : [], identityVerified ? [] : [path17]);
5660
+ function cleanupError(path19, cause, identityVerified = true) {
5661
+ const error = new TemporaryArtifactCleanupError(identityVerified ? [path19] : [], identityVerified ? [] : [path19]);
5662
5662
  Object.defineProperty(error, "cause", { configurable: true, value: cause });
5663
5663
  return error;
5664
5664
  }
@@ -5706,8 +5706,8 @@ var init_restore_publication = __esm({
5706
5706
  DEFAULT_OPERATIONS2 = Object.freeze({
5707
5707
  rename: (sourcePath, destinationPath) => renameSync2(sourcePath, destinationPath),
5708
5708
  link: (sourcePath, destinationPath) => linkSync2(sourcePath, destinationPath),
5709
- unlink: (path17) => unlinkSync3(path17),
5710
- statPathNoFollow: (path17) => lstatSync4(path17, { bigint: true })
5709
+ unlink: (path19) => unlinkSync3(path19),
5710
+ statPathNoFollow: (path19) => lstatSync4(path19, { bigint: true })
5711
5711
  });
5712
5712
  }
5713
5713
  });
@@ -5821,11 +5821,11 @@ function scanDatabaseFiles(dataPath2) {
5821
5821
  const userDir = dirname4(dataPath2);
5822
5822
  const globalDbPath = join8(userDir, "globalStorage", "state.vscdb");
5823
5823
  if (existsSync7(globalDbPath)) {
5824
- const stat10 = statSync3(globalDbPath);
5824
+ const stat12 = statSync3(globalDbPath);
5825
5825
  files.push({
5826
5826
  absolutePath: globalDbPath,
5827
5827
  relativePath: "globalStorage/state.vscdb",
5828
- size: stat10.size,
5828
+ size: stat12.size,
5829
5829
  type: "global-db"
5830
5830
  });
5831
5831
  }
@@ -5838,22 +5838,22 @@ function scanDatabaseFiles(dataPath2) {
5838
5838
  const workspaceDir = join8(workspaceStorageDir, entry.name);
5839
5839
  const workspaceDbPath = join8(workspaceDir, "state.vscdb");
5840
5840
  if (existsSync7(workspaceDbPath)) {
5841
- const stat10 = statSync3(workspaceDbPath);
5841
+ const stat12 = statSync3(workspaceDbPath);
5842
5842
  files.push({
5843
5843
  absolutePath: workspaceDbPath,
5844
5844
  relativePath: `workspaceStorage/${entry.name}/state.vscdb`,
5845
- size: stat10.size,
5845
+ size: stat12.size,
5846
5846
  type: "workspace-db",
5847
5847
  workspaceId: entry.name
5848
5848
  });
5849
5849
  }
5850
5850
  const workspaceJsonPath = join8(workspaceDir, "workspace.json");
5851
5851
  if (existsSync7(workspaceJsonPath)) {
5852
- const stat10 = statSync3(workspaceJsonPath);
5852
+ const stat12 = statSync3(workspaceJsonPath);
5853
5853
  files.push({
5854
5854
  absolutePath: workspaceJsonPath,
5855
5855
  relativePath: `workspaceStorage/${entry.name}/workspace.json`,
5856
- size: stat10.size,
5856
+ size: stat12.size,
5857
5857
  type: "workspace-json",
5858
5858
  workspaceId: entry.name
5859
5859
  });
@@ -6075,12 +6075,12 @@ function checkDiskSpace(outputPath, requiredBytes) {
6075
6075
  };
6076
6076
  }
6077
6077
  }
6078
- function syncParentDirectory(path17) {
6078
+ function syncParentDirectory(path19) {
6079
6079
  if (process.platform === "win32")
6080
6080
  return;
6081
6081
  let descriptor;
6082
6082
  try {
6083
- descriptor = openSync3(dirname4(path17), constants3.O_RDONLY);
6083
+ descriptor = openSync3(dirname4(path19), constants3.O_RDONLY);
6084
6084
  fsyncSync2(descriptor);
6085
6085
  } catch {
6086
6086
  } finally {
@@ -6092,13 +6092,13 @@ function syncParentDirectory(path17) {
6092
6092
  }
6093
6093
  }
6094
6094
  }
6095
- function removePrivateArchiveStage(path17, operationError) {
6095
+ function removePrivateArchiveStage(path19, operationError) {
6096
6096
  try {
6097
- unlinkSync4(path17);
6097
+ unlinkSync4(path19);
6098
6098
  } catch (error) {
6099
6099
  if (errorCode3(error) === "ENOENT")
6100
6100
  return;
6101
- const cleanupError2 = new TemporaryArtifactCleanupError([path17]);
6101
+ const cleanupError2 = new TemporaryArtifactCleanupError([path19]);
6102
6102
  attachCleanupCause(cleanupError2, operationError ?? error);
6103
6103
  throw cleanupError2;
6104
6104
  }
@@ -6362,7 +6362,7 @@ function combineTemporaryCleanupErrors(first, second) {
6362
6362
  const unverifiedResidueSet = new Set(unverifiedResiduePaths);
6363
6363
  const residuePaths = [
6364
6364
  .../* @__PURE__ */ new Set([...first.details.residuePaths, ...second.details.residuePaths])
6365
- ].filter((path17) => !unverifiedResidueSet.has(path17));
6365
+ ].filter((path19) => !unverifiedResidueSet.has(path19));
6366
6366
  const combined = new TemporaryArtifactCleanupError(residuePaths, unverifiedResiduePaths);
6367
6367
  Object.defineProperty(combined, "cause", { configurable: true, value: first });
6368
6368
  return combined;
@@ -6470,18 +6470,18 @@ function validatedManifestFiles(manifest) {
6470
6470
  if (type !== "global-db" && type !== "workspace-db" && type !== "workspace-json" && type !== "manifest") {
6471
6471
  throw new ZipArchiveFormatError(`Backup manifest file ${index + 1} has an invalid type.`);
6472
6472
  }
6473
- const path17 = entry["path"];
6474
- const expectedType = backupEntryTypeForCanonicalPath(path17);
6473
+ const path19 = entry["path"];
6474
+ const expectedType = backupEntryTypeForCanonicalPath(path19);
6475
6475
  if (expectedType === void 0 || type !== expectedType) {
6476
6476
  throw new ZipArchiveFormatError(`Backup manifest file ${index + 1} has an unsupported path/type combination.`);
6477
6477
  }
6478
- const destinationKey = path17.normalize("NFC").toLowerCase();
6478
+ const destinationKey = path19.normalize("NFC").toLowerCase();
6479
6479
  if (destinationKeys.has(destinationKey)) {
6480
- throw new ZipArchiveFormatError(`Backup manifest contains a duplicate restore destination: ${path17}`);
6480
+ throw new ZipArchiveFormatError(`Backup manifest contains a duplicate restore destination: ${path19}`);
6481
6481
  }
6482
6482
  destinationKeys.add(destinationKey);
6483
6483
  return {
6484
- path: path17,
6484
+ path: path19,
6485
6485
  size: Number(entry["size"]),
6486
6486
  checksum: entry["checksum"].toLowerCase(),
6487
6487
  type
@@ -6498,10 +6498,10 @@ function isCanonicalBackupPathSegment(value) {
6498
6498
  }
6499
6499
  return true;
6500
6500
  }
6501
- function backupEntryTypeForCanonicalPath(path17) {
6502
- if (path17 === "globalStorage/state.vscdb")
6501
+ function backupEntryTypeForCanonicalPath(path19) {
6502
+ if (path19 === "globalStorage/state.vscdb")
6503
6503
  return "global-db";
6504
- const match = /^workspaceStorage\/([^/]+)\/(state\.vscdb|workspace\.json)$/u.exec(path17);
6504
+ const match = /^workspaceStorage\/([^/]+)\/(state\.vscdb|workspace\.json)$/u.exec(path19);
6505
6505
  if (!match || !isCanonicalBackupPathSegment(match[1]))
6506
6506
  return void 0;
6507
6507
  return match[2] === "state.vscdb" ? "workspace-db" : "workspace-json";
@@ -6520,8 +6520,8 @@ function validateComposerWorkspaceInventory(manifest, files) {
6520
6520
  if (!Array.isArray(inventory["workspaces"])) {
6521
6521
  throw new ZipArchiveFormatError("Backup manifest Composer workspace inventory workspaces must be an array.");
6522
6522
  }
6523
- const expectedWorkspaceIds = files.filter(({ type }) => type === "workspace-db").map(({ path: path17 }) => /^workspaceStorage\/([^/]+)\/state\.vscdb$/u.exec(path17)?.[1]).filter((workspaceId) => workspaceId !== void 0).sort(compareCodePoints4);
6524
- const containsGlobalDatabase = files.some(({ type, path: path17 }) => type === "global-db" && path17 === "globalStorage/state.vscdb");
6523
+ const expectedWorkspaceIds = files.filter(({ type }) => type === "workspace-db").map(({ path: path19 }) => /^workspaceStorage\/([^/]+)\/state\.vscdb$/u.exec(path19)?.[1]).filter((workspaceId) => workspaceId !== void 0).sort(compareCodePoints4);
6524
+ const containsGlobalDatabase = files.some(({ type, path: path19 }) => type === "global-db" && path19 === "globalStorage/state.vscdb");
6525
6525
  if (inventory["workspaces"].length !== expectedWorkspaceIds.length) {
6526
6526
  throw new ZipArchiveFormatError("Backup manifest Composer workspace inventory does not cover every workspace database.");
6527
6527
  }
@@ -6677,7 +6677,7 @@ async function openBackupDatabase(backupPath, dbPath, options = {}) {
6677
6677
  if (!entry || entry.isDirectory) {
6678
6678
  throw new BackupEntryNotFoundError(dbPath);
6679
6679
  }
6680
- const manifestEntry = manifestFiles.find(({ path: path17 }) => path17 === dbPath);
6680
+ const manifestEntry = manifestFiles.find(({ path: path19 }) => path19 === dbPath);
6681
6681
  if (!manifestEntry) {
6682
6682
  throw new ZipArchiveFormatError(`Backup database is not declared by the manifest: ${dbPath}`);
6683
6683
  }
@@ -6732,7 +6732,7 @@ async function readBackupEntryBuffer(backupPath, entryPath, options = {}, maxByt
6732
6732
  const manifest = await readManifestFromArchive(archive);
6733
6733
  if (!manifest)
6734
6734
  throw new ZipArchiveFormatError("Manifest file not found in backup.");
6735
- const manifestEntry = validatedManifestFiles(manifest).find(({ path: path17 }) => path17 === entryPath);
6735
+ const manifestEntry = validatedManifestFiles(manifest).find(({ path: path19 }) => path19 === entryPath);
6736
6736
  const entry = archive.getEntry(entryPath);
6737
6737
  if (!entry || entry.isDirectory) {
6738
6738
  if (manifestEntry) {
@@ -6788,18 +6788,18 @@ async function validateBackup(backupPath, options = {}) {
6788
6788
  };
6789
6789
  }
6790
6790
  }
6791
- function lstatIfPresent(path17) {
6791
+ function lstatIfPresent(path19) {
6792
6792
  try {
6793
- return lstatSync5(path17);
6793
+ return lstatSync5(path19);
6794
6794
  } catch (error) {
6795
6795
  if (errorCode3(error) === "ENOENT")
6796
6796
  return void 0;
6797
6797
  throw error;
6798
6798
  }
6799
6799
  }
6800
- function assertNoLinkedRestorePath(trustedRoot, path17, leafKind) {
6800
+ function assertNoLinkedRestorePath(trustedRoot, path19, leafKind) {
6801
6801
  const absoluteRoot = resolve2(trustedRoot);
6802
- const absolutePath = resolve2(path17);
6802
+ const absolutePath = resolve2(path19);
6803
6803
  const suffix = relative3(absoluteRoot, absolutePath);
6804
6804
  if (suffix === ".." || suffix.startsWith(`..${sep2}`) || isAbsolute2(suffix)) {
6805
6805
  throw new Error(`Restore destination escapes the Cursor data directory: ${absolutePath}`);
@@ -7103,12 +7103,12 @@ async function listBackups(directory, options = {}) {
7103
7103
  continue;
7104
7104
  }
7105
7105
  const filePath = join8(dir, entry.name);
7106
- const stat10 = statSync3(filePath);
7106
+ const stat12 = statSync3(filePath);
7107
7107
  const info = {
7108
7108
  filePath,
7109
7109
  filename: entry.name,
7110
- fileSize: stat10.size,
7111
- modifiedAt: stat10.mtime
7110
+ fileSize: stat12.size,
7111
+ modifiedAt: stat12.mtime
7112
7112
  };
7113
7113
  try {
7114
7114
  const manifest = await readBackupManifest(filePath, readOptions);
@@ -7761,11 +7761,11 @@ function attachErrorCause(error, cause) {
7761
7761
  });
7762
7762
  }
7763
7763
  }
7764
- async function parseStoreDb(path17, options = {}) {
7764
+ async function parseStoreDb(path19, options = {}) {
7765
7765
  const limits = options.limits ?? SOURCE_READ_LIMITS_V1_DEFAULTS;
7766
7766
  const failureOutcome = options.failureOutcome ?? "fatal";
7767
7767
  throwIfAborted4(options.signal);
7768
- if (!pathExists(path17, options.signal, options.io, options.logicalSessionId))
7768
+ if (!pathExists(path19, options.signal, options.io, options.logicalSessionId))
7769
7769
  return null;
7770
7770
  const budget = new SqliteSourceReadBudget(limits, failureOutcome);
7771
7771
  let workspace = null;
@@ -7777,7 +7777,7 @@ async function parseStoreDb(path17, options = {}) {
7777
7777
  workspace = createPrivateTempWorkspace({ prefix: "ch-store-", signal: options.signal });
7778
7778
  const tmpPath = workspace.createFile("store.db");
7779
7779
  throwIfAborted4(options.signal);
7780
- await backupDatabase(path17, tmpPath, databaseRequest("store-snapshot", STORE_SNAPSHOT_CAPABILITIES, options.sqliteDriver, options, "store-database"));
7780
+ await backupDatabase(path19, tmpPath, databaseRequest("store-snapshot", STORE_SNAPSHOT_CAPABILITIES, options.sqliteDriver, options, "store-database"));
7781
7781
  snapshotComplete = true;
7782
7782
  throwIfAborted4(options.signal);
7783
7783
  if (process.platform !== "win32")
@@ -7824,12 +7824,12 @@ async function parseStoreDb(path17, options = {}) {
7824
7824
  operationError = error;
7825
7825
  else {
7826
7826
  options.onDiagnostic?.(error);
7827
- debugLogStorage(`store.db defensive parse failed for ${path17}: ${error.code}`);
7827
+ debugLogStorage(`store.db defensive parse failed for ${path19}: ${error.code}`);
7828
7828
  }
7829
7829
  } else if (isSessionIntegrityError(error)) {
7830
7830
  operationError = error;
7831
7831
  } else if (error instanceof StoreSourceCorruptError || isSqliteSourceCorruptionError(error)) {
7832
- debugLogStorage(`store.db source/schema parse failed for ${path17}: ${String(error)}`);
7832
+ debugLogStorage(`store.db source/schema parse failed for ${path19}: ${String(error)}`);
7833
7833
  } else {
7834
7834
  operationError = error;
7835
7835
  }
@@ -7854,7 +7854,7 @@ async function parseStoreDb(path17, options = {}) {
7854
7854
  throw operationError;
7855
7855
  return result;
7856
7856
  }
7857
- function pathExists(path17, signal, io, logicalSessionId) {
7857
+ function pathExists(path19, signal, io, logicalSessionId) {
7858
7858
  throwIfAborted4(signal);
7859
7859
  try {
7860
7860
  if (io) {
@@ -7867,18 +7867,18 @@ function pathExists(path17, signal, io, logicalSessionId) {
7867
7867
  ...logicalSessionId ? { logicalSessionId } : {}
7868
7868
  });
7869
7869
  }
7870
- statSync4(path17);
7870
+ statSync4(path19);
7871
7871
  return true;
7872
7872
  } catch (error) {
7873
- const code = error?.code;
7874
- if (code === "ENOENT" || code === "ENOTDIR")
7873
+ const code2 = error?.code;
7874
+ if (code2 === "ENOENT" || code2 === "ENOTDIR")
7875
7875
  return false;
7876
7876
  throw error;
7877
7877
  }
7878
7878
  }
7879
7879
  function isSqliteSourceCorruptionError(error) {
7880
- const code = error?.code;
7881
- if (code === "SQLITE_CORRUPT" || code === "SQLITE_NOTADB")
7880
+ const code2 = error?.code;
7881
+ if (code2 === "SQLITE_CORRUPT" || code2 === "SQLITE_NOTADB")
7882
7882
  return true;
7883
7883
  const message = error instanceof Error ? error.message.toLowerCase() : "";
7884
7884
  return message.includes("database disk image is malformed") || message.includes("file is not a database") || message.includes("malformed database schema") || /^no such (table|column):/.test(message);
@@ -8461,8 +8461,8 @@ function parseTranscriptFile(filePath, limits = SOURCE_READ_LIMITS_V1_DEFAULTS,
8461
8461
  }
8462
8462
  fd = openSync4(filePath, "r");
8463
8463
  } catch (error) {
8464
- const code = error?.code;
8465
- if (code === "ENOENT")
8464
+ const code2 = error?.code;
8465
+ if (code2 === "ENOENT")
8466
8466
  return emptyResult("missing", false);
8467
8467
  throw error;
8468
8468
  }
@@ -8835,15 +8835,15 @@ function compareStringArrays2(left, right) {
8835
8835
  function getStorePhysicalOccurrences(session) {
8836
8836
  return physicalOccurrences.get(session) ?? [];
8837
8837
  }
8838
- function occurrenceKey(representation, path17) {
8839
- return `${representation}\0${path17}`;
8838
+ function occurrenceKey(representation, path19) {
8839
+ return `${representation}\0${path19}`;
8840
8840
  }
8841
- function occurrence(logicalSessionId, representation, path17, workspacePath) {
8841
+ function occurrence(logicalSessionId, representation, path19, workspacePath) {
8842
8842
  return {
8843
- instanceKey: occurrenceKey(representation, path17),
8843
+ instanceKey: occurrenceKey(representation, path19),
8844
8844
  logicalSessionId,
8845
8845
  representation,
8846
- path: path17,
8846
+ path: path19,
8847
8847
  ...workspacePath ? { workspacePath: normalizeWorkspacePath(workspacePath) } : {},
8848
8848
  sourceOrder: 0
8849
8849
  };
@@ -9191,7 +9191,7 @@ async function discoverStoreSessions(storeRoot2, options = {}) {
9191
9191
  const evidence = evidenceFor(uuid);
9192
9192
  evidence.transcriptInventoried = true;
9193
9193
  const transcriptOccurrence = occurrence(uuid, "store-transcript", nested, transcriptWorkspacePath(sanitized, metadataCandidates.get(logicalSessionIdKey(uuid)) ?? []));
9194
- if (!evidence.transcriptOccurrences.some(({ path: path17 }) => path17 === nested)) {
9194
+ if (!evidence.transcriptOccurrences.some(({ path: path19 }) => path19 === nested)) {
9195
9195
  evidence.transcriptOccurrences.push(transcriptOccurrence);
9196
9196
  }
9197
9197
  if (options.metadataOnly) {
@@ -9208,7 +9208,7 @@ async function discoverStoreSessions(storeRoot2, options = {}) {
9208
9208
  evidence.transcriptInventoried = true;
9209
9209
  const transcriptPath = join10(transcriptDir, entry.name);
9210
9210
  const transcriptOccurrence = occurrence(uuid, "store-transcript", transcriptPath, transcriptWorkspacePath(sanitized, metadataCandidates.get(logicalSessionIdKey(uuid)) ?? []));
9211
- if (!evidence.transcriptOccurrences.some(({ path: path17 }) => path17 === transcriptPath)) {
9211
+ if (!evidence.transcriptOccurrences.some(({ path: path19 }) => path19 === transcriptPath)) {
9212
9212
  evidence.transcriptOccurrences.push(transcriptOccurrence);
9213
9213
  }
9214
9214
  if (options.metadataOnly) {
@@ -9282,7 +9282,7 @@ async function discoverStoreSessions(storeRoot2, options = {}) {
9282
9282
  const usableDbCandidates = dbCandidates.filter((candidate) => Boolean(candidate.parsed && candidate.parsed.messages.length > 0));
9283
9283
  const selectedDbFidelity = usableDbCandidates.some(({ parsed }) => parsed.completeness === "complete") ? "complete" : "partial";
9284
9284
  const selectedDbTier = usableDbCandidates.filter(({ parsed }) => parsed.completeness === selectedDbFidelity);
9285
- let selectedDbCandidate = selectedDbTier[0] ?? dbCandidates.find(({ path: path17 }) => path17 === ss.storeDbPath) ?? dbCandidates[0];
9285
+ let selectedDbCandidate = selectedDbTier[0] ?? dbCandidates.find(({ path: path19 }) => path19 === ss.storeDbPath) ?? dbCandidates[0];
9286
9286
  let dbReplicaInstances = [];
9287
9287
  if (selectedDbTier.length > 1) {
9288
9288
  const physical = physicalStoreCandidates(ss.id, "store-db", selectedDbFidelity, selectedDbTier.map((candidate) => ({
@@ -9496,12 +9496,12 @@ function recordInventory(evidence, logicalSessionId, metaRead, sessionDir, dbPat
9496
9496
  if (metaRead.diagnostic)
9497
9497
  evidence.metadataFailures.push(metaRead.diagnostic);
9498
9498
  const metadataOccurrence = occurrence(logicalSessionId, "store-metadata", sessionDir, metaRead.meta?.cwd);
9499
- if (!evidence.metadataOccurrences.some(({ path: path17 }) => path17 === sessionDir)) {
9499
+ if (!evidence.metadataOccurrences.some(({ path: path19 }) => path19 === sessionDir)) {
9500
9500
  evidence.metadataOccurrences.push(metadataOccurrence);
9501
9501
  }
9502
9502
  if (dbInventoried) {
9503
9503
  evidence.dbInventoried = true;
9504
- if (!evidence.dbOccurrences.some(({ path: path17 }) => path17 === dbPath)) {
9504
+ if (!evidence.dbOccurrences.some(({ path: path19 }) => path19 === dbPath)) {
9505
9505
  evidence.dbOccurrences.push(occurrence(logicalSessionId, "store-db", dbPath, metaRead.meta?.cwd));
9506
9506
  }
9507
9507
  }
@@ -9747,12 +9747,12 @@ function listEntries(dir, signal, io) {
9747
9747
  throw error;
9748
9748
  }
9749
9749
  }
9750
- function readMeta(path17, signal, io, logicalSessionId, includeDisplayMetadata = true) {
9750
+ function readMeta(path19, signal, io, logicalSessionId, includeDisplayMetadata = true) {
9751
9751
  throwIfAborted6(signal);
9752
9752
  let raw;
9753
9753
  try {
9754
9754
  observeStoreFs(io, "read", "store-session-metadata", logicalSessionId, "store-db");
9755
- raw = readFileSync10(path17);
9755
+ raw = readFileSync10(path19);
9756
9756
  } catch (error) {
9757
9757
  if (isAbsentOrWrongType(error)) {
9758
9758
  return { present: false, unsupportedExpectationMetadata: false };
@@ -9883,11 +9883,11 @@ function decodeJsonObjectKey(raw, start, end) {
9883
9883
  function isJsonWhitespace(byte) {
9884
9884
  return byte === 32 || byte === 9 || byte === 10 || byte === 13;
9885
9885
  }
9886
- function pathExists2(path17, signal, io, resourceClass = "store-root-directory", logicalSessionId) {
9886
+ function pathExists2(path19, signal, io, resourceClass = "store-root-directory", logicalSessionId) {
9887
9887
  throwIfAborted6(signal);
9888
9888
  try {
9889
9889
  observeStoreFs(io, "open", resourceClass, logicalSessionId);
9890
- statSync5(path17);
9890
+ statSync5(path19);
9891
9891
  return true;
9892
9892
  } catch (error) {
9893
9893
  if (isAbsentOrWrongType(error))
@@ -9908,8 +9908,8 @@ function observeStoreFs(io, operation, resourceClass, logicalSessionId, represen
9908
9908
  });
9909
9909
  }
9910
9910
  function isAbsentOrWrongType(error) {
9911
- const code = error?.code;
9912
- return code === "ENOENT" || code === "ENOTDIR";
9911
+ const code2 = error?.code;
9912
+ return code2 === "ENOENT" || code2 === "ENOTDIR";
9913
9913
  }
9914
9914
  function abortError7(signal) {
9915
9915
  if (signal.reason instanceof Error && signal.reason.name === "AbortError")
@@ -11009,8 +11009,8 @@ function observeStorageAdapterIo(options, input) {
11009
11009
  observeAdapterIo(options.io, input);
11010
11010
  }
11011
11011
  function shouldPropagateReadFailure(error) {
11012
- const code = error instanceof Error && "code" in error ? String(error.code) : void 0;
11013
- return isSessionIntegrityError(error) || error instanceof IoObserverError || typeof error === "object" && error !== null && OWNING_DATABASE_READ_FAILURES.has(error) || error instanceof ZipArchiveFormatError || error instanceof DriverNotAvailableError || error instanceof NoDriverAvailableError || Boolean(code && /^(?:ERR_)?SQLITE_/i.test(code)) || error instanceof Error && error.name === "AbortError";
11012
+ const code2 = error instanceof Error && "code" in error ? String(error.code) : void 0;
11013
+ return isSessionIntegrityError(error) || error instanceof IoObserverError || typeof error === "object" && error !== null && OWNING_DATABASE_READ_FAILURES.has(error) || error instanceof ZipArchiveFormatError || error instanceof DriverNotAvailableError || error instanceof NoDriverAvailableError || Boolean(code2 && /^(?:ERR_)?SQLITE_/i.test(code2)) || error instanceof Error && error.name === "AbortError";
11014
11014
  }
11015
11015
  function throwOwningDatabaseReadFailure(error) {
11016
11016
  if (typeof error === "object" && error !== null || typeof error === "function") {
@@ -11515,7 +11515,7 @@ async function resolveBackupWorkspaceInventory(manifest, backupPath, readOptions
11515
11515
  throw new ZipArchiveFormatError("No intact restorable files found in backup.");
11516
11516
  }
11517
11517
  const databases = backupWorkspaceDatabaseEntries(manifest);
11518
- const containsGlobalDatabase = manifest.files.some(({ type, path: path17 }) => type === "global-db" && path17 === "globalStorage/state.vscdb");
11518
+ const containsGlobalDatabase = manifest.files.some(({ type, path: path19 }) => type === "global-db" && path19 === "globalStorage/state.vscdb");
11519
11519
  const inventory = manifest.composerWorkspaceInventory;
11520
11520
  if (inventory) {
11521
11521
  const dbPathByWorkspaceId = new Map(databases.map(({ workspaceId, dbPath }) => [workspaceId, dbPath]));
@@ -12713,8 +12713,8 @@ function loadExactGlobalComposerSession(db, exactId, workspacePath, budget = cre
12713
12713
  function composerWorkspaceMemberships(candidates) {
12714
12714
  const counts2 = /* @__PURE__ */ new Map();
12715
12715
  for (const candidate of candidates) {
12716
- const path17 = normalizeWorkspacePath(candidate.workspace.path);
12717
- counts2.set(path17, (counts2.get(path17) ?? 0) + 1);
12716
+ const path19 = normalizeWorkspacePath(candidate.workspace.path);
12717
+ counts2.set(path19, (counts2.get(path19) ?? 0) + 1);
12718
12718
  }
12719
12719
  return [...counts2.entries()].sort(([left], [right]) => compareCodePoints8(left, right)).map(([workspacePath, contributingInstanceCount]) => ({
12720
12720
  workspacePath,
@@ -13406,7 +13406,7 @@ async function listSessions(options, customDataPath, backupPath, context) {
13406
13406
  composerWorkspaceInventory = await findComposerWorkspaceInventory(customDataPath, backupPath, context);
13407
13407
  const storeWorkspacePaths = storeCatalogSessions.flatMap(verifiedStoreWorkspacePaths);
13408
13408
  workspaceScopeResult = resolveWorkspaceScope(options.workspacePath, [
13409
- ...composerWorkspaceInventory.map(({ path: path17 }) => path17),
13409
+ ...composerWorkspaceInventory.map(({ path: path19 }) => path19),
13410
13410
  ...storeWorkspacePaths
13411
13411
  ]);
13412
13412
  if (workspaceScopeResult.kind === "not-found") {
@@ -13672,7 +13672,7 @@ async function listSessions(options, customDataPath, backupPath, context) {
13672
13672
  }
13673
13673
  }
13674
13674
  if (activeWorkspacePath) {
13675
- const offScopeWorkspaces = composerWorkspaceInventory.filter(({ path: path17 }) => !workspaceFilterMatches(path17, activeWorkspacePath));
13675
+ const offScopeWorkspaces = composerWorkspaceInventory.filter(({ path: path19 }) => !workspaceFilterMatches(path19, activeWorkspacePath));
13676
13676
  for (const workspace of offScopeWorkspaces) {
13677
13677
  if (backupPath) {
13678
13678
  for (const id of getBackupComposerSessionIds(workspace) ?? []) {
@@ -14965,11 +14965,11 @@ function formatToolCall(toolData, codeBlocks) {
14965
14965
  } else if (toolName === "grep" || toolName === "search" || toolName === "codebase_search") {
14966
14966
  lines2.push(`[Tool: ${toolName === "grep" ? "Grep" : "Search"}]`);
14967
14967
  const pattern = getParam(params, "pattern", "query", "searchQuery", "regex");
14968
- const path17 = getParam(params, "path", "directory", "targetDirectory");
14968
+ const path19 = getParam(params, "path", "directory", "targetDirectory");
14969
14969
  if (pattern)
14970
14970
  lines2.push(`Pattern: ${pattern}`);
14971
- if (path17)
14972
- lines2.push(`Path: ${path17}`);
14971
+ if (path19)
14972
+ lines2.push(`Path: ${path19}`);
14973
14973
  } else if (toolName === "run_terminal_command" || toolName === "run_terminal_cmd" || toolName === "execute_command") {
14974
14974
  lines2.push(`[Tool: Terminal Command]`);
14975
14975
  const cmd = getParam(params, "command", "cmd");
@@ -15474,9 +15474,9 @@ import { pathToFileURL } from "node:url";
15474
15474
  function generateSessionId() {
15475
15475
  return randomUUID2();
15476
15476
  }
15477
- function transformPath(path17, sourcePrefix, destPrefix) {
15477
+ function transformPath(path19, sourcePrefix, destPrefix) {
15478
15478
  const normalizedSource = sourcePrefix.replace(/\/+$/, "");
15479
- const normalizedPath = path17;
15479
+ const normalizedPath = path19;
15480
15480
  if (normalizedPath.startsWith(normalizedSource + "/") || normalizedPath === normalizedSource) {
15481
15481
  return destPrefix + normalizedPath.slice(normalizedSource.length);
15482
15482
  }
@@ -15592,8 +15592,8 @@ function isNestedPath(source, destination) {
15592
15592
  const normalizedDest = normalizePath(destination).replace(/\/+$/, "");
15593
15593
  return normalizedDest.startsWith(normalizedSource + "/");
15594
15594
  }
15595
- function toFileUri(path17) {
15596
- const normalized = normalizePath(path17);
15595
+ function toFileUri(path19) {
15596
+ const normalized = normalizePath(path19);
15597
15597
  const windowsDrivePath = normalized.match(/^([A-Za-z]):[\\/](.*)$/);
15598
15598
  if (windowsDrivePath) {
15599
15599
  const drive = windowsDrivePath[1].toLowerCase();
@@ -15647,13 +15647,13 @@ function createMigrationReadGuard(limits, signal, sqliteDriver) {
15647
15647
  sqliteDriver
15648
15648
  };
15649
15649
  }
15650
- function physicalPathIdentity(label, path17) {
15651
- const normalized = normalizedPathKey(path17);
15652
- if (!existsSync9(path17))
15650
+ function physicalPathIdentity(label, path19) {
15651
+ const normalized = normalizedPathKey(path19);
15652
+ if (!existsSync9(path19))
15653
15653
  return `${label}:${normalized}|missing`;
15654
15654
  try {
15655
- const stat10 = statSync6(path17);
15656
- return `${label}:${normalized}|dev:${String(stat10.dev)}|ino:${String(stat10.ino)}`;
15655
+ const stat12 = statSync6(path19);
15656
+ return `${label}:${normalized}|dev:${String(stat12.dev)}|ino:${String(stat12.ino)}`;
15657
15657
  } catch {
15658
15658
  return `${label}:${normalized}|unavailable`;
15659
15659
  }
@@ -15801,13 +15801,13 @@ async function findMigrationWorkspaceByPath(requested, dataPath2, guard) {
15801
15801
  const databasePath = join12(workspaceDirectory, "state.vscdb");
15802
15802
  if (!existsSync9(databasePath))
15803
15803
  continue;
15804
- const path17 = readWorkspaceJson(workspaceDirectory);
15805
- if (!path17 || !pathsEqual(path17, normalizedRequest))
15804
+ const path19 = readWorkspaceJson(workspaceDirectory);
15805
+ if (!path19 || !pathsEqual(path19, normalizedRequest))
15806
15806
  continue;
15807
15807
  return {
15808
15808
  workspace: {
15809
15809
  id: entry.name,
15810
- path: normalizePath(path17),
15810
+ path: normalizePath(path19),
15811
15811
  dbPath: databasePath,
15812
15812
  sessionCount: 0
15813
15813
  },
@@ -15825,7 +15825,7 @@ function loadWorkspaceComposerAddressInventory(db, budget, signal) {
15825
15825
  if (rootType !== "array" && rootType !== "object") {
15826
15826
  throw new TypeError("Composer workspace catalog is not a JSON array or object.");
15827
15827
  }
15828
- const scanIds = (path17, objectIds) => {
15828
+ const scanIds = (path19, objectIds) => {
15829
15829
  const scanBudget = new SqliteSourceReadBudget(budget.limits, budget.outcome);
15830
15830
  const results = [];
15831
15831
  const pageRows = scanBudget.limits.sqlitePageRows;
@@ -15836,7 +15836,7 @@ function loadWorkspaceComposerAddressInventory(db, budget, signal) {
15836
15836
  throwIfMigrationAborted(signal);
15837
15837
  const rows = db.prepare(`SELECT CAST(j.key AS INTEGER) AS itemIndex,
15838
15838
  length(CAST(${valueExpression} AS BLOB)) AS byteLength
15839
- FROM ItemTable AS i, json_each(i.value, '${path17}') AS j
15839
+ FROM ItemTable AS i, json_each(i.value, '${path19}') AS j
15840
15840
  WHERE i.rowid = ?
15841
15841
  AND ${typePredicate}
15842
15842
  AND CAST(j.key AS INTEGER) > ?
@@ -15855,7 +15855,7 @@ function loadWorkspaceComposerAddressInventory(db, budget, signal) {
15855
15855
  for (const item of metadata) {
15856
15856
  throwIfMigrationAborted(signal);
15857
15857
  const projected = db.prepare(`SELECT ${valueExpression} AS sessionId
15858
- FROM ItemTable AS i, json_each(i.value, '${path17}') AS j
15858
+ FROM ItemTable AS i, json_each(i.value, '${path19}') AS j
15859
15859
  WHERE i.rowid = ? AND CAST(j.key AS INTEGER) = ?`).get(source.rowId, item.itemIndex);
15860
15860
  if (typeof projected?.sessionId !== "string") {
15861
15861
  throw new Error("Composer ID projection changed after metadata admission.");
@@ -20341,13 +20341,13 @@ var KNOWN_ROW_IDS = /* @__PURE__ */ new Set([
20341
20341
  ]);
20342
20342
 
20343
20343
  // src/version.ts
20344
- var CLI_VERSION = true ? "0.20.6" : "0.0.0-dev";
20344
+ var CLI_VERSION = true ? "0.21.0" : "0.0.0-dev";
20345
20345
 
20346
20346
  // src/api.ts
20347
20347
  var BASE_URL = process.env.AISTACK_URL || "https://aistack.to";
20348
20348
  var STARTUP_READ_TIMEOUT_MS = 5e3;
20349
- async function request(path17, options = {}) {
20350
- return fetch(`${BASE_URL}${path17}`, {
20349
+ async function request(path19, options = {}) {
20350
+ return fetch(`${BASE_URL}${path19}`, {
20351
20351
  ...options,
20352
20352
  headers: {
20353
20353
  "Content-Type": "application/json",
@@ -20879,9 +20879,9 @@ function canonicalizeRepoUrl(input) {
20879
20879
  function repoNameFromCanonical(canonical) {
20880
20880
  return parseRepo(canonical)?.repo ?? "";
20881
20881
  }
20882
- function normalizeUpstreamPath(path17) {
20883
- if (!path17) return "";
20884
- return path17.split("/").filter(Boolean).join("/");
20882
+ function normalizeUpstreamPath(path19) {
20883
+ if (!path19) return "";
20884
+ return path19.split("/").filter(Boolean).join("/");
20885
20885
  }
20886
20886
 
20887
20887
  // src/git.ts
@@ -20927,16 +20927,16 @@ function buildRepoLinkResource(canonical) {
20927
20927
  import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
20928
20928
  import { homedir as homedir2 } from "node:os";
20929
20929
  import { join as join2 } from "node:path";
20930
- function readJson(path17) {
20930
+ function readJson(path19) {
20931
20931
  try {
20932
- if (!existsSync2(path17)) return null;
20933
- return JSON.parse(readFileSync2(path17, "utf-8"));
20932
+ if (!existsSync2(path19)) return null;
20933
+ return JSON.parse(readFileSync2(path19, "utf-8"));
20934
20934
  } catch {
20935
20935
  return null;
20936
20936
  }
20937
20937
  }
20938
- function hooksFrom(path17, source, out, seen) {
20939
- const hooks = readJson(path17)?.hooks;
20938
+ function hooksFrom(path19, source, out, seen) {
20939
+ const hooks = readJson(path19)?.hooks;
20940
20940
  if (!hooks || typeof hooks !== "object") return;
20941
20941
  for (const [event, config] of Object.entries(hooks)) {
20942
20942
  const stableKey = `hooks:${source}:${event}`;
@@ -21085,16 +21085,16 @@ function buildMcpResource(name, group, pkg) {
21085
21085
  pkg
21086
21086
  };
21087
21087
  }
21088
- function readText(path17) {
21088
+ function readText(path19) {
21089
21089
  try {
21090
- if (!existsSync3(path17)) return null;
21091
- return readFileSync3(path17, "utf-8");
21090
+ if (!existsSync3(path19)) return null;
21091
+ return readFileSync3(path19, "utf-8");
21092
21092
  } catch {
21093
21093
  return null;
21094
21094
  }
21095
21095
  }
21096
- function readParsed(path17, parse2) {
21097
- const raw = readText(path17);
21096
+ function readParsed(path19, parse2) {
21097
+ const raw = readText(path19);
21098
21098
  if (raw === null) return null;
21099
21099
  try {
21100
21100
  return parse2(raw);
@@ -21102,14 +21102,14 @@ function readParsed(path17, parse2) {
21102
21102
  return null;
21103
21103
  }
21104
21104
  }
21105
- function readJson2(path17) {
21106
- return readParsed(path17, JSON.parse);
21105
+ function readJson2(path19) {
21106
+ return readParsed(path19, JSON.parse);
21107
21107
  }
21108
- function readYaml(path17) {
21109
- return readParsed(path17, parseYaml);
21108
+ function readYaml(path19) {
21109
+ return readParsed(path19, parseYaml);
21110
21110
  }
21111
- function readToml(path17) {
21112
- return readParsed(path17, parseToml);
21111
+ function readToml(path19) {
21112
+ return readParsed(path19, parseToml);
21113
21113
  }
21114
21114
  function continueListToMap(file) {
21115
21115
  if (!file?.mcpServers?.length) return void 0;
@@ -21248,8 +21248,8 @@ function resolveSource(entry, mpRepoUrl) {
21248
21248
  const src = entry.source;
21249
21249
  if (typeof src === "string") {
21250
21250
  if (!mpRepoUrl) return null;
21251
- const path17 = src.replace(/^\.\//, "").replace(/\/+$/, "");
21252
- return { url: mpRepoUrl, path: path17 || void 0 };
21251
+ const path19 = src.replace(/^\.\//, "").replace(/\/+$/, "");
21252
+ return { url: mpRepoUrl, path: path19 || void 0 };
21253
21253
  }
21254
21254
  if (src && typeof src === "object" && src.url) {
21255
21255
  return { url: src.url, path: src.path, sha: src.sha };
@@ -21286,10 +21286,10 @@ function resolvePluginLinks(installed, marketplaces, manifests) {
21286
21286
  }
21287
21287
  return out;
21288
21288
  }
21289
- function readJson3(path17) {
21289
+ function readJson3(path19) {
21290
21290
  try {
21291
- if (!existsSync4(path17)) return null;
21292
- return JSON.parse(readFileSync4(path17, "utf-8"));
21291
+ if (!existsSync4(path19)) return null;
21292
+ return JSON.parse(readFileSync4(path19, "utf-8"));
21293
21293
  } catch {
21294
21294
  return null;
21295
21295
  }
@@ -21378,8 +21378,8 @@ function loadGitignore(cwd) {
21378
21378
  }
21379
21379
  function readFileSafe(filePath) {
21380
21380
  try {
21381
- const stat10 = statSync(filePath);
21382
- if (stat10.size > MAX_FILE_SIZE) return null;
21381
+ const stat12 = statSync(filePath);
21382
+ if (stat12.size > MAX_FILE_SIZE) return null;
21383
21383
  return readFileSync5(filePath, "utf-8");
21384
21384
  } catch {
21385
21385
  return null;
@@ -21577,7 +21577,7 @@ function scanGlobal() {
21577
21577
 
21578
21578
  // src/theme.ts
21579
21579
  import * as p from "@clack/prompts";
21580
- var esc = (code) => `\x1B[${code}m`;
21580
+ var esc = (code2) => `\x1B[${code2}m`;
21581
21581
  var reset = esc("0");
21582
21582
  var LIME = "163;230;53";
21583
21583
  var BLACK = "0;0;0";
@@ -21923,7 +21923,7 @@ function diffResources(current, existing) {
21923
21923
  // src/commands/connect.ts
21924
21924
  import { spawnSync } from "node:child_process";
21925
21925
  import { cpSync, existsSync as existsSync11 } from "node:fs";
21926
- import { homedir as homedir18 } from "node:os";
21926
+ import { homedir as homedir19 } from "node:os";
21927
21927
  import { dirname as dirname5, join as join13 } from "node:path";
21928
21928
  import { fileURLToPath } from "node:url";
21929
21929
  import * as p3 from "@clack/prompts";
@@ -22017,9 +22017,9 @@ var knownNames = /* @__PURE__ */ new Set([
22017
22017
  var object = (value) => value !== null && typeof value === "object" ? value : null;
22018
22018
  function traceErrorCode(error) {
22019
22019
  const value = object(error);
22020
- const code = value?.code;
22021
- if (typeof code === "string" && /^[A-Z][A-Z0-9_]{0,63}$/.test(code))
22022
- return code;
22020
+ const code2 = value?.code;
22021
+ if (typeof code2 === "string" && /^[A-Z][A-Z0-9_]{0,63}$/.test(code2))
22022
+ return code2;
22023
22023
  return typeof value?.name === "string" && knownNames.has(value.name) ? value.name : "unknown";
22024
22024
  }
22025
22025
  function traceError(operation, error, level = "error") {
@@ -22029,11 +22029,11 @@ function traceError(operation, error, level = "error") {
22029
22029
  if (depth >= 4 || seen.has(value)) return "[cause omitted]";
22030
22030
  seen.add(value);
22031
22031
  const row = object(value);
22032
- const code = traceErrorCode(value);
22032
+ const code2 = traceErrorCode(value);
22033
22033
  const name = row?.name;
22034
- const fields = typeof name === "string" && knownNames.has(name) && name !== code ? [name, code] : [code];
22034
+ const fields = typeof name === "string" && knownNames.has(name) && name !== code2 ? [name, code2] : [code2];
22035
22035
  const details = object(row?.details);
22036
- if (code === "SOURCE_LIMIT_EXCEEDED" && details) {
22036
+ if (code2 === "SOURCE_LIMIT_EXCEEDED" && details) {
22037
22037
  if (typeof details.bound === "string" && /^(sqlite|jsonl|zip)-[a-z-]{1,32}$/.test(details.bound))
22038
22038
  fields.push(details.bound);
22039
22039
  for (const key2 of ["limit", "observedAtLeast"]) {
@@ -24252,8 +24252,8 @@ async function discoverClaudeRoots() {
24252
24252
  const dataHome = process.env.XDG_DATA_HOME || path2.join(home, ".local", "share");
24253
24253
  let complete = true;
24254
24254
  const failed = (error) => {
24255
- const code = error?.code;
24256
- if (code === "ENOENT" || code === "ENOTDIR") return;
24255
+ const code2 = error?.code;
24256
+ if (code2 === "ENOENT" || code2 === "ENOTDIR") return;
24257
24257
  complete = false;
24258
24258
  traceError("claude profile discovery", error, "warn");
24259
24259
  };
@@ -24313,8 +24313,8 @@ var WORKSPACE_FALLBACK_PREFIX = "claude-project:";
24313
24313
  function isClaudeWorkspaceFallback(directory) {
24314
24314
  return directory.startsWith(WORKSPACE_FALLBACK_PREFIX);
24315
24315
  }
24316
- function isTranscriptFile(basename5) {
24317
- return basename5.endsWith(".jsonl");
24316
+ function isTranscriptFile(basename6) {
24317
+ return basename6.endsWith(".jsonl");
24318
24318
  }
24319
24319
  async function* walkJsonl(dir) {
24320
24320
  let entries;
@@ -24652,9 +24652,9 @@ function ingestCall(agg, name, callId) {
24652
24652
  if (agg.toolCallDedup.has(callId)) return;
24653
24653
  agg.toolCallDedup.add(callId);
24654
24654
  }
24655
- const sep3 = name.indexOf("__");
24656
- if (sep3 > 0) {
24657
- bump(agg.mcpServerCalls, cleanName(name.slice(0, sep3)));
24655
+ const sep4 = name.indexOf("__");
24656
+ if (sep4 > 0) {
24657
+ bump(agg.mcpServerCalls, cleanName(name.slice(0, sep4)));
24658
24658
  bump(agg.mcpToolCalls, cleanName(name));
24659
24659
  return;
24660
24660
  }
@@ -24863,6 +24863,26 @@ async function discoverHomes(options) {
24863
24863
  return { homes, complete };
24864
24864
  }
24865
24865
  var rememberedFile = () => path4.join(homedir7(), ".config", "aistack", "harness-homes.json");
24866
+ async function rememberedHomes(harness) {
24867
+ return readRemembered(harness);
24868
+ }
24869
+ async function rememberHome(harness, dir) {
24870
+ const list = await readRemembered(harness);
24871
+ if (list.includes(dir)) return false;
24872
+ if (!await writeRemembered(harness, [...list, dir]))
24873
+ throw new Error("Could not save the folder list");
24874
+ return true;
24875
+ }
24876
+ async function forgetHome(harness, dir) {
24877
+ const list = await readRemembered(harness);
24878
+ if (!list.includes(dir)) return false;
24879
+ if (!await writeRemembered(
24880
+ harness,
24881
+ list.filter((entry) => entry !== dir)
24882
+ ))
24883
+ throw new Error("Could not save the folder list");
24884
+ return true;
24885
+ }
24866
24886
  async function readRemembered(harness) {
24867
24887
  try {
24868
24888
  const parsed = JSON.parse(await readFile(rememberedFile(), "utf8"));
@@ -24888,8 +24908,10 @@ async function writeRemembered(harness, dirs) {
24888
24908
  await mkdir(path4.dirname(file), { recursive: true, mode: 448 });
24889
24909
  await writeFile(file, `${JSON.stringify(all, null, 2)}
24890
24910
  `, { mode: 384 });
24911
+ return true;
24891
24912
  } catch (error) {
24892
24913
  traceError("remembered harness homes", error, "warn");
24914
+ return false;
24893
24915
  }
24894
24916
  }
24895
24917
  function expandHome(dir) {
@@ -24899,8 +24921,8 @@ function expandHome(dir) {
24899
24921
  );
24900
24922
  }
24901
24923
  function absent(error) {
24902
- const code = error?.code;
24903
- return code === "ENOENT" || code === "ENOTDIR";
24924
+ const code2 = error?.code;
24925
+ return code2 === "ENOENT" || code2 === "ENOTDIR";
24904
24926
  }
24905
24927
 
24906
24928
  // src/harness/codex/scan.ts
@@ -24919,8 +24941,8 @@ async function rolloutRoots() {
24919
24941
  );
24920
24942
  }
24921
24943
  var ROLLOUT_RE = /^rollout-.*\.jsonl(\.zst)?$/;
24922
- function isRolloutFile(basename5) {
24923
- return ROLLOUT_RE.test(basename5);
24944
+ function isRolloutFile(basename6) {
24945
+ return ROLLOUT_RE.test(basename6);
24924
24946
  }
24925
24947
  async function* walkRollouts(dir) {
24926
24948
  let entries;
@@ -25028,8 +25050,8 @@ async function exists2(p8) {
25028
25050
  }
25029
25051
  }
25030
25052
  function errorClass(e) {
25031
- const code = e?.code;
25032
- if (typeof code === "string" && code.length > 0) return code;
25053
+ const code2 = e?.code;
25054
+ if (typeof code2 === "string" && code2.length > 0) return code2;
25033
25055
  return e instanceof Error ? e.constructor.name : "unknown";
25034
25056
  }
25035
25057
  var readError = (reason) => Object.assign(new Error(reason), { code: reason });
@@ -25959,10 +25981,10 @@ async function readLocalOffThread(root, before, onProgress) {
25959
25981
  else fallback();
25960
25982
  })
25961
25983
  );
25962
- worker.on("exit", (code) => {
25963
- if (code !== 0)
25984
+ worker.on("exit", (code2) => {
25985
+ if (code2 !== 0)
25964
25986
  settle(() => {
25965
- trace(`cursor worker exited \xB7 code=${code}; reading inline`, "warn");
25987
+ trace(`cursor worker exited \xB7 code=${code2}; reading inline`, "warn");
25966
25988
  fallback();
25967
25989
  });
25968
25990
  });
@@ -26128,9 +26150,9 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits, stallMs
26128
26150
  onProgress?.(stats.filesRead + stats.filesSkippedByMtime, total);
26129
26151
  } catch (error) {
26130
26152
  if (signal.aborted || isPageByteLimit(error)) throw error;
26131
- const code = traceErrorCode(error);
26132
- if (code === "SESSION_AMBIGUOUS") ambiguous++;
26133
- else if (code === "SOURCE_ENCODING_INVALID") encodingInvalid++;
26153
+ const code2 = traceErrorCode(error);
26154
+ if (code2 === "SESSION_AMBIGUOUS") ambiguous++;
26155
+ else if (code2 === "SOURCE_ENCODING_INVALID") encodingInvalid++;
26134
26156
  else traceError(`cursor ${stage}`, error, "warn");
26135
26157
  out.complete = false;
26136
26158
  stats.filesUnreadable++;
@@ -26545,11 +26567,105 @@ function cachedEvents(cache, sessionIds) {
26545
26567
  });
26546
26568
  }
26547
26569
 
26570
+ // src/harness/cursor/roots.ts
26571
+ import { readdir as readdir6, readFile as readFile4, stat as stat7 } from "node:fs/promises";
26572
+ import { homedir as homedir14 } from "node:os";
26573
+ import path9 from "node:path";
26574
+ var CURSOR_HOMES_KEY = "cursor";
26575
+ async function cursorRootFor(dir) {
26576
+ const expanded = expandHome(dir);
26577
+ if (path9.basename(expanded) === "workspaceStorage") return expanded;
26578
+ const user = path9.join(expanded, "User");
26579
+ try {
26580
+ if ((await stat7(user)).isDirectory())
26581
+ return path9.join(user, "workspaceStorage");
26582
+ } catch {
26583
+ }
26584
+ return expanded;
26585
+ }
26586
+ var FLAG = "--user-data-dir";
26587
+ async function runningUserDataDirs(procDir = "/proc") {
26588
+ let pids;
26589
+ try {
26590
+ pids = (await readdir6(procDir)).filter((name) => /^\d+$/.test(name));
26591
+ } catch {
26592
+ return [];
26593
+ }
26594
+ const candidates = /* @__PURE__ */ new Set();
26595
+ for (const pid of pids) {
26596
+ let args;
26597
+ try {
26598
+ args = (await readFile4(path9.join(procDir, pid, "cmdline"), "utf8")).split("\0").filter(Boolean);
26599
+ } catch {
26600
+ continue;
26601
+ }
26602
+ for (const value of userDataDirArgs(args))
26603
+ if (path9.isAbsolute(value)) candidates.add(path9.normalize(value));
26604
+ }
26605
+ const found = [];
26606
+ for (const dir of [...candidates].sort())
26607
+ if (await holdsCursorData(dir)) found.push(dir);
26608
+ if (found.length)
26609
+ trace(`cursor \xB7 ${found.length} running instance folder(s)`);
26610
+ return found;
26611
+ }
26612
+ function userDataDirArgs(args) {
26613
+ const values = [];
26614
+ for (const [index, arg] of args.entries()) {
26615
+ if (arg === FLAG && args[index + 1]) values.push(args[index + 1]);
26616
+ if (arg.startsWith(`${FLAG}=`) && !arg.includes(" --")) {
26617
+ values.push(arg.slice(FLAG.length + 1));
26618
+ continue;
26619
+ }
26620
+ for (const match of arg.matchAll(/(?:^| )--user-data-dir=(.+?)(?= --|$)/g))
26621
+ values.push(match[1]);
26622
+ }
26623
+ return values;
26624
+ }
26625
+ async function holdsCursorData(dir) {
26626
+ const file = path9.join(dir, "User", "globalStorage", "state.vscdb");
26627
+ let db;
26628
+ try {
26629
+ if (!(await stat7(file)).isFile()) return false;
26630
+ const { DatabaseSync } = await import("node:sqlite");
26631
+ db = new DatabaseSync(file, { readOnly: true });
26632
+ return Boolean(
26633
+ db.prepare(
26634
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'cursorDiskKV'"
26635
+ ).get()
26636
+ );
26637
+ } catch {
26638
+ return false;
26639
+ } finally {
26640
+ db?.close();
26641
+ }
26642
+ }
26643
+ async function discoverCursorRoots(options = {}) {
26644
+ const env = options.env ?? process.env;
26645
+ const platform4 = options.platform ?? process.platform;
26646
+ const fallback = dataPath(
26647
+ { ...env, CURSOR_DATA_PATH: void 0 },
26648
+ homedir14(),
26649
+ platform4
26650
+ );
26651
+ const procDir = options.procDir ?? process.env.AISTACK_CURSOR_PROC_DIR ?? "/proc";
26652
+ const running = platform4 === "linux" && procDir ? await runningUserDataDirs(procDir) : [];
26653
+ const configured = await Promise.all(
26654
+ [env.CURSOR_DATA_PATH, ...running].filter((dir) => Boolean(dir?.trim())).map(cursorRootFor)
26655
+ );
26656
+ const discovery = await discoverHomes({
26657
+ defaults: [fallback],
26658
+ configured,
26659
+ remember: CURSOR_HOMES_KEY
26660
+ });
26661
+ return discovery.homes.length ? discovery : { homes: [fallback], complete: discovery.complete };
26662
+ }
26663
+
26548
26664
  // src/harness/cursor/scan.ts
26549
- import path10 from "node:path";
26665
+ import path11 from "node:path";
26550
26666
 
26551
26667
  // src/harness/cursor/workflow.ts
26552
- import path9 from "node:path";
26668
+ import path10 from "node:path";
26553
26669
  var TOOLS = {
26554
26670
  read_file: "Read",
26555
26671
  read_file_v2: "Read",
@@ -26590,7 +26706,7 @@ function projectHistory(options) {
26590
26706
  const scopes = /* @__PURE__ */ new Map();
26591
26707
  const inWindow = (t) => t !== null && t >= sinceMs && t <= now;
26592
26708
  for (const { session } of locals) {
26593
- const projectWorkspace = session.canonicalWorkspacePath && path9.isAbsolute(session.canonicalWorkspacePath) ? session.canonicalWorkspacePath : void 0;
26709
+ const projectWorkspace = session.canonicalWorkspacePath && path10.isAbsolute(session.canonicalWorkspacePath) ? session.canonicalWorkspacePath : void 0;
26594
26710
  const times = messageTimes(session, api);
26595
26711
  const scopeOf = (message) => {
26596
26712
  const parent = message.parentMessageId && nativeOwners.get(message.parentMessageId);
@@ -26677,7 +26793,7 @@ function projectHistory(options) {
26677
26793
  session: row.sidechain ? `${row.session}:sidechain` : row.session,
26678
26794
  sidechain: row.sidechain
26679
26795
  },
26680
- ...project && path9.isAbsolute(project) ? { projectWorkspace: project } : {},
26796
+ ...project && path10.isAbsolute(project) ? { projectWorkspace: project } : {},
26681
26797
  type: "response",
26682
26798
  tsMs: row.tsMs,
26683
26799
  responseId: `${row.source}:${row.id ?? index}`,
@@ -26689,14 +26805,9 @@ function projectHistory(options) {
26689
26805
 
26690
26806
  // src/harness/cursor/scan.ts
26691
26807
  var accountRefreshes = /* @__PURE__ */ new Map();
26692
- async function scan3(options) {
26693
- const root = options.root ?? dataPath();
26694
- const now = options.now ?? Date.now();
26695
- const file = options.cachePath ?? cacheFile(root, storeRoot());
26696
- const local = await (options.readLocalImpl ?? readLocal)(
26697
- root,
26698
- options.onProgress
26699
- );
26808
+ async function readFolder(root, options, now, onProgress) {
26809
+ const file = typeof options.cachePath === "function" ? options.cachePath(root) : options.cachePath ?? cacheFile(root, storeRoot());
26810
+ const local = await (options.readLocalImpl ?? readLocal)(root, onProgress);
26700
26811
  const loaded = await loadCache(file);
26701
26812
  let complete = local.complete && loaded.complete;
26702
26813
  const ids = new Set(local.sessions.map((s) => s.session.id));
@@ -26727,14 +26838,11 @@ async function scan3(options) {
26727
26838
  state: refreshState
26728
26839
  });
26729
26840
  const api = cachedEvents(cache, ids);
26730
- const native = /* @__PURE__ */ new Set();
26731
- const contributions = local.sessions.flatMap((s) => localContributions(s, api)).filter((row) => {
26732
- if (!row.nativeId) return true;
26733
- if (native.has(row.nativeId)) return false;
26734
- native.add(row.nativeId);
26735
- return true;
26736
- });
26737
- const dated = new Set(contributions.map((row) => row.session));
26841
+ const contributions = local.sessions.flatMap(
26842
+ (s) => localContributions(s, api)
26843
+ );
26844
+ const deduped = dedupeNative(contributions);
26845
+ const dated = new Set(deduped.map((row) => row.session));
26738
26846
  if (loaded.value.local.some(
26739
26847
  (row) => row.tsMs >= options.sinceMs && !dated.has(row.session)
26740
26848
  )) {
@@ -26744,17 +26852,8 @@ async function scan3(options) {
26744
26852
  );
26745
26853
  complete = false;
26746
26854
  }
26747
- const previousDates = /* @__PURE__ */ new Map();
26748
- for (const row of [
26749
- ...loaded.value.local,
26750
- ...cachedEvents(loaded.value, ids)
26751
- ]) {
26752
- const dates = previousDates.get(row.session) ?? /* @__PURE__ */ new Set();
26753
- dates.add(utcDateOf(row.tsMs));
26754
- previousDates.set(row.session, dates);
26755
- }
26756
26855
  if (complete) {
26757
- cache.local = contributions;
26856
+ cache.local = deduped;
26758
26857
  cache.sessions = [...ids].sort();
26759
26858
  try {
26760
26859
  await saveCache(file, cache);
@@ -26763,6 +26862,102 @@ async function scan3(options) {
26763
26862
  complete = false;
26764
26863
  }
26765
26864
  }
26865
+ return {
26866
+ local,
26867
+ api,
26868
+ contributions,
26869
+ previous: [...loaded.value.local, ...cachedEvents(loaded.value, ids)],
26870
+ complete
26871
+ };
26872
+ }
26873
+ function dedupeNative(rows) {
26874
+ const native = /* @__PURE__ */ new Set();
26875
+ return rows.filter((row) => {
26876
+ if (!row.nativeId) return true;
26877
+ if (native.has(row.nativeId)) return false;
26878
+ native.add(row.nativeId);
26879
+ return true;
26880
+ });
26881
+ }
26882
+ function addStats(into, from) {
26883
+ into.filesFound += from.filesFound;
26884
+ into.filesRead += from.filesRead;
26885
+ into.filesSkippedByMtime += from.filesSkippedByMtime;
26886
+ into.filesSkippedAsDuplicate += from.filesSkippedAsDuplicate;
26887
+ into.filesUnreadable += from.filesUnreadable;
26888
+ into.filesForeign += from.filesForeign;
26889
+ into.filesZstdUnsupported += from.filesZstdUnsupported;
26890
+ into.unreadableFiles.push(...from.unreadableFiles);
26891
+ for (const [name, count2] of from.foreignOriginators)
26892
+ into.foreignOriginators.set(
26893
+ name,
26894
+ (into.foreignOriginators.get(name) ?? 0) + count2
26895
+ );
26896
+ if (from.sourceDiscoveryComplete === false)
26897
+ into.sourceDiscoveryComplete = false;
26898
+ }
26899
+ async function scan3(options) {
26900
+ const now = options.now ?? Date.now();
26901
+ let discoveryComplete = true;
26902
+ let roots = options.roots ?? (options.root ? [options.root] : void 0);
26903
+ if (!roots) {
26904
+ const discovered = await discoverCursorRoots();
26905
+ roots = discovered.homes;
26906
+ discoveryComplete = discovered.complete;
26907
+ }
26908
+ const folders = [];
26909
+ let filesBefore = 0;
26910
+ for (const root of roots) {
26911
+ const offset = filesBefore;
26912
+ const folder = await readFolder(
26913
+ root,
26914
+ options,
26915
+ now,
26916
+ options.onProgress && ((files, total) => options.onProgress?.(
26917
+ offset + files,
26918
+ total === void 0 ? void 0 : offset + total
26919
+ ))
26920
+ );
26921
+ filesBefore += folder.local.stats.filesRead;
26922
+ folders.push(folder);
26923
+ }
26924
+ const complete = discoveryComplete && folders.every((f) => f.complete);
26925
+ const owner = /* @__PURE__ */ new Map();
26926
+ for (const [index, folder] of folders.entries())
26927
+ for (const { session } of folder.local.sessions) {
26928
+ const held = owner.get(session.id);
26929
+ if (!held || session.messages.length > held.messages)
26930
+ owner.set(session.id, {
26931
+ folder: index,
26932
+ messages: session.messages.length
26933
+ });
26934
+ }
26935
+ const owns = (index) => (row) => owner.get(row.session)?.folder === index;
26936
+ const local = {
26937
+ sessions: folders.flatMap(
26938
+ (f, index) => f.local.sessions.filter(
26939
+ ({ session }) => owner.get(session.id)?.folder === index
26940
+ )
26941
+ ),
26942
+ complete: folders.every((f) => f.local.complete),
26943
+ stats: emptyScanStats()
26944
+ };
26945
+ for (const folder of folders) addStats(local.stats, folder.local.stats);
26946
+ if (!discoveryComplete) local.stats.sourceDiscoveryComplete = false;
26947
+ const api = folders.flatMap((f, index) => f.api.filter(owns(index)));
26948
+ const contributions = dedupeNative(
26949
+ folders.flatMap((f, index) => f.contributions.filter(owns(index)))
26950
+ );
26951
+ const previousDates = /* @__PURE__ */ new Map();
26952
+ for (const row of folders.flatMap((f) => f.previous)) {
26953
+ const dates = previousDates.get(row.session) ?? /* @__PURE__ */ new Set();
26954
+ dates.add(utcDateOf(row.tsMs));
26955
+ previousDates.set(row.session, dates);
26956
+ }
26957
+ if (folders.length > 1)
26958
+ trace(
26959
+ `cursor \xB7 ${folders.length} data folders \xB7 ${local.sessions.length} sessions`
26960
+ );
26766
26961
  const aggregate = createAggregate();
26767
26962
  const workflowLocal = createWorkflowLocalSources();
26768
26963
  const workflow = createHarnessWorkflowReducer("cursor", workflowLocal);
@@ -26776,7 +26971,7 @@ async function scan3(options) {
26776
26971
  aggregate.byModel.set(model, emptyUsage());
26777
26972
  }
26778
26973
  const project = session.canonicalWorkspacePath;
26779
- if (project && path10.isAbsolute(project)) aggregate.projectDirs.add(project);
26974
+ if (project && path11.isAbsolute(project)) aggregate.projectDirs.add(project);
26780
26975
  if (session.metadata?.cursorVersion)
26781
26976
  aggregate.ccVersions.add(session.metadata.cursorVersion);
26782
26977
  let firstTime = null;
@@ -26833,7 +27028,7 @@ async function scan3(options) {
26833
27028
  else aggregate.mainTokens += countsTotal(counts2);
26834
27029
  noteSessionStart(aggregate, session, tsMs);
26835
27030
  const project = sessions.get(session)?.session.canonicalWorkspacePath;
26836
- if (project && path10.isAbsolute(project))
27031
+ if (project && path11.isAbsolute(project))
26837
27032
  noteProjectDay(aggregate, project, tsMs);
26838
27033
  }
26839
27034
  aggregate.files = local.stats.filesRead;
@@ -26853,7 +27048,9 @@ var cursorAdapter = {
26853
27048
  name: CURSOR_HARNESS_NAME,
26854
27049
  builtinTools: CURSOR_BUILTIN_TOOLS,
26855
27050
  async detect(options) {
26856
- const roots = options.roots ?? [dataPath()];
27051
+ const discovered = options.roots ? { homes: options.roots, complete: true } : await discoverCursorRoots();
27052
+ if (!discovered.complete) return true;
27053
+ const roots = discovered.homes;
26857
27054
  for (const root of roots) {
26858
27055
  const held = await loadCache(cacheFile(root, storeRoot()));
26859
27056
  if (!held.complete || [
@@ -27120,17 +27317,17 @@ function ingestContribution(agg, row) {
27120
27317
 
27121
27318
  // src/harness/grok/scan.ts
27122
27319
  import { createReadStream as createReadStream2 } from "node:fs";
27123
- import { readdir as readdir7, readFile as readFile5, stat as stat7 } from "node:fs/promises";
27124
- import { homedir as homedir15 } from "node:os";
27125
- import path12 from "node:path";
27320
+ import { readdir as readdir8, readFile as readFile6, stat as stat8 } from "node:fs/promises";
27321
+ import { homedir as homedir16 } from "node:os";
27322
+ import path13 from "node:path";
27126
27323
  import readline2 from "node:readline";
27127
27324
  import { parse as parseToml3 } from "smol-toml";
27128
27325
 
27129
27326
  // src/harness/grok/context.ts
27130
27327
  import { createHash as createHash8 } from "node:crypto";
27131
- import { appendFile, mkdir as mkdir4, readdir as readdir6, readFile as readFile4, unlink as unlink2 } from "node:fs/promises";
27132
- import { homedir as homedir14 } from "node:os";
27133
- import path11 from "node:path";
27328
+ import { appendFile, mkdir as mkdir4, readdir as readdir7, readFile as readFile5, unlink as unlink2 } from "node:fs/promises";
27329
+ import { homedir as homedir15 } from "node:os";
27330
+ import path12 from "node:path";
27134
27331
  var DAY_MS = 864e5;
27135
27332
  var hash = (value) => createHash8("sha256").update(value).digest("hex");
27136
27333
  function contextCall(value) {
@@ -27153,17 +27350,17 @@ function contextCall(value) {
27153
27350
  };
27154
27351
  }
27155
27352
  function contextCacheDirectory(root) {
27156
- return path11.join(
27157
- homedir14(),
27353
+ return path12.join(
27354
+ homedir15(),
27158
27355
  ".config",
27159
27356
  "aistack",
27160
27357
  "grok-context",
27161
- hash(path11.resolve(root))
27358
+ hash(path12.resolve(root))
27162
27359
  );
27163
27360
  }
27164
27361
  async function optionalRead(file) {
27165
27362
  try {
27166
- return await readFile4(file, "utf8");
27363
+ return await readFile5(file, "utf8");
27167
27364
  } catch (error) {
27168
27365
  if (error.code === "ENOENT") return "";
27169
27366
  throw error;
@@ -27174,21 +27371,21 @@ async function retainedContextCalls(root, sessions, cacheDir = contextCacheDirec
27174
27371
  const calls = /* @__PURE__ */ new Map();
27175
27372
  let files = [];
27176
27373
  try {
27177
- files = await readdir6(cacheDir);
27374
+ files = await readdir7(cacheDir);
27178
27375
  } catch (error) {
27179
27376
  if (error.code !== "ENOENT") throw error;
27180
27377
  }
27181
27378
  for (const file of files) {
27182
27379
  if (!/^\d{4}-\d{2}-\d{2}\.jsonl$/.test(file)) continue;
27183
27380
  if (Date.parse(file.slice(0, 10)) + DAY_MS < cutoff) {
27184
- await unlink2(path11.join(cacheDir, file)).catch(
27381
+ await unlink2(path12.join(cacheDir, file)).catch(
27185
27382
  (error) => {
27186
27383
  if (error.code !== "ENOENT") throw error;
27187
27384
  }
27188
27385
  );
27189
27386
  continue;
27190
27387
  }
27191
- const raw2 = await optionalRead(path11.join(cacheDir, file));
27388
+ const raw2 = await optionalRead(path12.join(cacheDir, file));
27192
27389
  if (raw2 && !raw2.endsWith("\n"))
27193
27390
  throw Object.assign(new Error("Incomplete Grok context cache"), {
27194
27391
  code: "GROK_INCOMPLETE_CONTEXT_CACHE"
@@ -27209,7 +27406,7 @@ async function retainedContextCalls(root, sessions, cacheDir = contextCacheDirec
27209
27406
  }
27210
27407
  }
27211
27408
  const raw = await optionalRead(
27212
- path11.join(root, "..", "logs", "unified.jsonl")
27409
+ path12.join(root, "..", "logs", "unified.jsonl")
27213
27410
  );
27214
27411
  const additions = /* @__PURE__ */ new Map();
27215
27412
  for (const line of raw.slice(0, raw.lastIndexOf("\n") + 1).split("\n")) {
@@ -27232,7 +27429,7 @@ async function retainedContextCalls(root, sessions, cacheDir = contextCacheDirec
27232
27429
  await mkdir4(cacheDir, { recursive: true, mode: 448 });
27233
27430
  for (const [date, lines2] of additions) {
27234
27431
  await appendFile(
27235
- path11.join(cacheDir, `${date}.jsonl`),
27432
+ path12.join(cacheDir, `${date}.jsonl`),
27236
27433
  `${lines2.join("\n")}
27237
27434
  `,
27238
27435
  { mode: 384 }
@@ -27244,9 +27441,9 @@ async function retainedContextCalls(root, sessions, cacheDir = contextCacheDirec
27244
27441
 
27245
27442
  // src/harness/grok/scan.ts
27246
27443
  async function discoverGrokHomes() {
27247
- const home = homedir15();
27444
+ const home = homedir16();
27248
27445
  return discoverHomes({
27249
- defaults: [path12.join(home, ".grok")],
27446
+ defaults: [path13.join(home, ".grok")],
27250
27447
  configured: [process.env.GROK_HOME],
27251
27448
  siblings: [{ parent: home, prefix: ".grok" }],
27252
27449
  remember: "grok-build"
@@ -27254,14 +27451,14 @@ async function discoverGrokHomes() {
27254
27451
  }
27255
27452
  async function sessionRoots() {
27256
27453
  return (await discoverGrokHomes()).homes.map(
27257
- (home) => path12.join(home, "sessions")
27454
+ (home) => path13.join(home, "sessions")
27258
27455
  );
27259
27456
  }
27260
27457
  async function evidenceBytes(dir) {
27261
27458
  let total = 0;
27262
27459
  for (const name of ["usage.json", "updates.jsonl", "events.jsonl"]) {
27263
27460
  try {
27264
- total += (await stat7(path12.join(dir, name))).size;
27461
+ total += (await stat8(path13.join(dir, name))).size;
27265
27462
  } catch (error) {
27266
27463
  if (error?.code !== "ENOENT")
27267
27464
  traceError("grok evidence stat", error, "warn");
@@ -27276,7 +27473,7 @@ async function stableRead(file, jsonl) {
27276
27473
  for (const delay of delays) {
27277
27474
  if (delay) await pause(delay);
27278
27475
  try {
27279
- const before = await stat7(file);
27476
+ const before = await stat8(file);
27280
27477
  if (!before.isFile()) return { complete: false };
27281
27478
  if (jsonl) {
27282
27479
  const lines2 = [];
@@ -27294,12 +27491,12 @@ async function stableRead(file, jsonl) {
27294
27491
  lines2.push(null);
27295
27492
  }
27296
27493
  }
27297
- const after = await stat7(file);
27494
+ const after = await stat8(file);
27298
27495
  if (before.size === after.size && before.mtimeMs === after.mtimeMs)
27299
27496
  return { lines: lines2, complete: true };
27300
27497
  } else {
27301
- const raw = await readFile5(file, "utf8");
27302
- const after = await stat7(file);
27498
+ const raw = await readFile6(file, "utf8");
27499
+ const after = await stat8(file);
27303
27500
  if (before.size === after.size && before.mtimeMs === after.mtimeMs)
27304
27501
  return { json: JSON.parse(raw), complete: true };
27305
27502
  }
@@ -27312,16 +27509,16 @@ async function stableRead(file, jsonl) {
27312
27509
  }
27313
27510
  function absoluteCwd(value) {
27314
27511
  const cwd = asStr(value);
27315
- return cwd && path12.isAbsolute(cwd) && !cwd.includes("\0") ? cwd : void 0;
27512
+ return cwd && path13.isAbsolute(cwd) && !cwd.includes("\0") ? cwd : void 0;
27316
27513
  }
27317
27514
  async function workspaceCwd(workspacePath, entries) {
27318
27515
  try {
27319
- const cwd = absoluteCwd(decodeURIComponent(path12.basename(workspacePath)));
27516
+ const cwd = absoluteCwd(decodeURIComponent(path13.basename(workspacePath)));
27320
27517
  if (cwd !== void 0) return cwd;
27321
27518
  } catch {
27322
27519
  }
27323
27520
  if (entries.some((entry) => entry.name === ".cwd" && entry.isFile())) {
27324
- const raw = await readFile5(path12.join(workspacePath, ".cwd"), "utf8").catch(
27521
+ const raw = await readFile6(path13.join(workspacePath, ".cwd"), "utf8").catch(
27325
27522
  () => void 0
27326
27523
  );
27327
27524
  return absoluteCwd(raw);
@@ -27329,18 +27526,18 @@ async function workspaceCwd(workspacePath, entries) {
27329
27526
  }
27330
27527
  async function directories(root) {
27331
27528
  try {
27332
- const workspaces = await readdir7(root, { withFileTypes: true });
27529
+ const workspaces = await readdir8(root, { withFileTypes: true });
27333
27530
  const out = [];
27334
27531
  for (const workspace of workspaces) {
27335
27532
  if (!workspace.isDirectory() || workspace.isSymbolicLink()) continue;
27336
- const workspacePath = path12.join(root, workspace.name);
27337
- const entries = await readdir7(workspacePath, {
27533
+ const workspacePath = path13.join(root, workspace.name);
27534
+ const entries = await readdir8(workspacePath, {
27338
27535
  withFileTypes: true
27339
27536
  });
27340
27537
  const cwd = await workspaceCwd(workspacePath, entries);
27341
27538
  for (const session of entries) {
27342
27539
  if (session.isDirectory() && !session.isSymbolicLink())
27343
- out.push({ dir: path12.join(workspacePath, session.name), cwd });
27540
+ out.push({ dir: path13.join(workspacePath, session.name), cwd });
27344
27541
  }
27345
27542
  }
27346
27543
  return out.sort((a, b) => {
@@ -27357,7 +27554,7 @@ async function modelAliasesForRoot(root) {
27357
27554
  if (process.env.GROK_MODELS_BASE_URL) return /* @__PURE__ */ new Map();
27358
27555
  try {
27359
27556
  const parsed = asObj(
27360
- parseToml3(await readFile5(path12.join(root, "..", "config.toml"), "utf8"))
27557
+ parseToml3(await readFile6(path13.join(root, "..", "config.toml"), "utf8"))
27361
27558
  );
27362
27559
  if (!parsed || asObj(parsed.endpoints)?.models_base_url) return /* @__PURE__ */ new Map();
27363
27560
  const models = asObj(parsed.model);
@@ -27388,14 +27585,14 @@ async function scanWindows2(windows, opts = {}) {
27388
27585
  }));
27389
27586
  const discovery = opts.roots ? { homes: [], complete: true } : await discoverGrokHomes();
27390
27587
  let complete = discovery.complete;
27391
- const roots = opts.roots ?? discovery.homes.map((home) => path12.join(home, "sessions"));
27588
+ const roots = opts.roots ?? discovery.homes.map((home) => path13.join(home, "sessions"));
27392
27589
  const listed = /* @__PURE__ */ new Map();
27393
27590
  const fullest = /* @__PURE__ */ new Map();
27394
27591
  for (const root of roots) {
27395
27592
  const dirs = await directories(root);
27396
27593
  listed.set(root, dirs);
27397
27594
  for (const { dir } of dirs ?? []) {
27398
- const key2 = path12.relative(root, dir);
27595
+ const key2 = path13.relative(root, dir);
27399
27596
  const bytes = await evidenceBytes(dir);
27400
27597
  const held = fullest.get(key2);
27401
27598
  if (!held || bytes > held.bytes) fullest.set(key2, { dir, bytes });
@@ -27410,13 +27607,13 @@ async function scanWindows2(windows, opts = {}) {
27410
27607
  continue;
27411
27608
  }
27412
27609
  for (const { dir, cwd } of dirs) {
27413
- if (fullest.get(path12.relative(root, dir))?.dir !== dir) {
27610
+ if (fullest.get(path13.relative(root, dir))?.dir !== dir) {
27414
27611
  stats.filesSkippedAsDuplicate++;
27415
27612
  continue;
27416
27613
  }
27417
27614
  let entries;
27418
27615
  try {
27419
- entries = await readdir7(dir, { withFileTypes: true });
27616
+ entries = await readdir8(dir, { withFileTypes: true });
27420
27617
  } catch (error) {
27421
27618
  traceError("grok session listing", error);
27422
27619
  complete = false;
@@ -27425,10 +27622,10 @@ async function scanWindows2(windows, opts = {}) {
27425
27622
  const files = new Map(
27426
27623
  entries.filter(
27427
27624
  (e) => e.isFile() && (isGrokEvidenceFile(e.name) || e.name === "summary.json")
27428
- ).map((e) => [e.name, path12.join(dir, e.name)])
27625
+ ).map((e) => [e.name, path13.join(dir, e.name)])
27429
27626
  );
27430
27627
  let projectDir = cwd;
27431
- let sessionFallback = path12.basename(dir);
27628
+ let sessionFallback = path13.basename(dir);
27432
27629
  let child = false;
27433
27630
  let parentSession;
27434
27631
  const summary = files.get("summary.json");
@@ -27829,25 +28026,25 @@ function ingestTypedSkill2(agg, row) {
27829
28026
 
27830
28027
  // src/harness/opencode/scan.ts
27831
28028
  import { readFileSync as readFileSync12 } from "node:fs";
27832
- import { readdir as readdir8, realpath as realpath4, stat as stat8 } from "node:fs/promises";
27833
- import { homedir as homedir16 } from "node:os";
27834
- import path13 from "node:path";
28029
+ import { readdir as readdir9, realpath as realpath4, stat as stat9 } from "node:fs/promises";
28030
+ import { homedir as homedir17 } from "node:os";
28031
+ import path14 from "node:path";
27835
28032
  var OPENCODE_MIGRATION_CEILING = 20260622202450;
27836
28033
  async function opencodeDataDirs() {
27837
28034
  const xdg = process.env.XDG_DATA_HOME?.trim();
27838
28035
  return discoverHomes({
27839
- defaults: [path13.join(homedir16(), ".local", "share", "opencode")],
27840
- configured: [xdg ? path13.join(xdg, "opencode") : void 0],
28036
+ defaults: [path14.join(homedir17(), ".local", "share", "opencode")],
28037
+ configured: [xdg ? path14.join(xdg, "opencode") : void 0],
27841
28038
  remember: "opencode"
27842
28039
  });
27843
28040
  }
27844
- function isStoreFile(basename5) {
27845
- return basename5 === "opencode.db" || /^opencode-[^/]+\.db$/.test(basename5);
28041
+ function isStoreFile(basename6) {
28042
+ return basename6 === "opencode.db" || /^opencode-[^/]+\.db$/.test(basename6);
27846
28043
  }
27847
28044
  async function dbFilesIn(root) {
27848
28045
  try {
27849
- const entries = await readdir8(root, { withFileTypes: true });
27850
- return entries.filter((e) => e.isFile() && isStoreFile(e.name)).map((e) => path13.join(root, e.name)).sort();
28046
+ const entries = await readdir9(root, { withFileTypes: true });
28047
+ return entries.filter((e) => e.isFile() && isStoreFile(e.name)).map((e) => path14.join(root, e.name)).sort();
27851
28048
  } catch (error) {
27852
28049
  if (error?.code !== "ENOENT")
27853
28050
  traceError("opencode database discovery", error, "warn");
@@ -27861,8 +28058,8 @@ async function storeFiles(roots) {
27861
28058
  const override = roots ? void 0 : process.env.OPENCODE_DB?.trim();
27862
28059
  if (override)
27863
28060
  candidates.push(
27864
- path13.resolve(
27865
- process.env.XDG_DATA_HOME?.trim() || path13.join(homedir16(), ".local", "share"),
28061
+ path14.resolve(
28062
+ process.env.XDG_DATA_HOME?.trim() || path14.join(homedir17(), ".local", "share"),
27866
28063
  "opencode",
27867
28064
  override
27868
28065
  )
@@ -27895,8 +28092,8 @@ async function loadSqlite() {
27895
28092
  }
27896
28093
  }
27897
28094
  function errorClass2(e) {
27898
- const code = e?.code;
27899
- if (typeof code === "string" && code.length > 0) return code;
28095
+ const code2 = e?.code;
28096
+ if (typeof code2 === "string" && code2.length > 0) return code2;
27900
28097
  return e instanceof Error ? e.constructor.name : "unknown";
27901
28098
  }
27902
28099
  var readError2 = (reason) => Object.assign(new Error(reason), { code: reason });
@@ -27917,7 +28114,7 @@ async function scan5(agg, opts = {}) {
27917
28114
  traceError("opencode database read", e);
27918
28115
  stats.filesUnreadable++;
27919
28116
  stats.unreadableFiles.push({
27920
- path: path13.basename(file),
28117
+ path: path14.basename(file),
27921
28118
  reason: errorClass2(e)
27922
28119
  });
27923
28120
  }
@@ -28103,8 +28300,8 @@ function pickTs(jsonTs, columnTs) {
28103
28300
  }
28104
28301
  function opencodeConfigFile() {
28105
28302
  const xdg = process.env.XDG_CONFIG_HOME;
28106
- const base = xdg || path13.join(homedir16(), ".config");
28107
- return path13.join(base, "opencode", "opencode.json");
28303
+ const base = xdg || path14.join(homedir17(), ".config");
28304
+ return path14.join(base, "opencode", "opencode.json");
28108
28305
  }
28109
28306
  function readConfiguredMcpServers2(agg, state, configFile) {
28110
28307
  const file = configFile ?? opencodeConfigFile();
@@ -28181,7 +28378,7 @@ async function detectOpencode(opts) {
28181
28378
  }
28182
28379
  async function exists4(p8) {
28183
28380
  try {
28184
- await stat8(p8);
28381
+ await stat9(p8);
28185
28382
  return true;
28186
28383
  } catch (error) {
28187
28384
  if (error?.code !== "ENOENT")
@@ -28411,17 +28608,17 @@ function readCounts2(usageRaw) {
28411
28608
 
28412
28609
  // src/harness/pi/scan.ts
28413
28610
  import { createReadStream as createReadStream3 } from "node:fs";
28414
- import { readdir as readdir9, realpath as realpath5, stat as stat9 } from "node:fs/promises";
28415
- import { homedir as homedir17 } from "node:os";
28416
- import path14 from "node:path";
28611
+ import { readdir as readdir10, realpath as realpath5, stat as stat10 } from "node:fs/promises";
28612
+ import { homedir as homedir18 } from "node:os";
28613
+ import path15 from "node:path";
28417
28614
  import readline3 from "node:readline";
28418
28615
  var MAX_SESSION_VERSION = 3;
28419
28616
  async function discoverSessionRoots() {
28420
28617
  const agentDir = process.env.PI_CODING_AGENT_DIR?.trim();
28421
28618
  return discoverHomes({
28422
- defaults: [path14.join(homedir17(), ".pi", "agent", "sessions")],
28619
+ defaults: [path15.join(homedir18(), ".pi", "agent", "sessions")],
28423
28620
  configured: [
28424
- agentDir ? path14.join(agentDir, "sessions") : void 0,
28621
+ agentDir ? path15.join(agentDir, "sessions") : void 0,
28425
28622
  process.env.PI_CODING_AGENT_SESSION_DIR
28426
28623
  ],
28427
28624
  remember: "pi-mono"
@@ -28431,20 +28628,20 @@ async function sessionRoots2() {
28431
28628
  return (await discoverSessionRoots()).homes;
28432
28629
  }
28433
28630
  var SESSION_FILE_RE = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.jsonl$/;
28434
- function isSessionFile(basename5) {
28435
- return SESSION_FILE_RE.test(basename5);
28631
+ function isSessionFile(basename6) {
28632
+ return SESSION_FILE_RE.test(basename6);
28436
28633
  }
28437
28634
  async function* walkSessions(dir) {
28438
28635
  let entries;
28439
28636
  try {
28440
- entries = await readdir9(dir, { withFileTypes: true });
28637
+ entries = await readdir10(dir, { withFileTypes: true });
28441
28638
  } catch (error) {
28442
28639
  if (error?.code !== "ENOENT")
28443
28640
  traceError("pi transcript discovery", error, "warn");
28444
28641
  return;
28445
28642
  }
28446
28643
  for (const e of entries) {
28447
- const full = path14.join(dir, e.name);
28644
+ const full = path15.join(dir, e.name);
28448
28645
  if (e.isDirectory()) yield* walkSessions(full);
28449
28646
  else if (e.isFile() && isSessionFile(e.name)) yield full;
28450
28647
  }
@@ -28474,7 +28671,7 @@ async function scan6(agg, opts = {}) {
28474
28671
  visited.add(resolved);
28475
28672
  if (opts.sinceMs !== void 0) {
28476
28673
  try {
28477
- const st = await stat9(file);
28674
+ const st = await stat10(file);
28478
28675
  if (st.mtimeMs < opts.sinceMs) {
28479
28676
  stats.filesSkippedByMtime++;
28480
28677
  continue;
@@ -28498,7 +28695,7 @@ async function scan6(agg, opts = {}) {
28498
28695
  stats.filesUnreadable++;
28499
28696
  stats.filesRead--;
28500
28697
  stats.unreadableFiles.push({
28501
- path: path14.relative(root, file),
28698
+ path: path15.relative(root, file),
28502
28699
  reason: "version-too-new"
28503
28700
  });
28504
28701
  }
@@ -28507,7 +28704,7 @@ async function scan6(agg, opts = {}) {
28507
28704
  stats.filesUnreadable++;
28508
28705
  stats.filesRead--;
28509
28706
  stats.unreadableFiles.push({
28510
- path: path14.relative(root, file),
28707
+ path: path15.relative(root, file),
28511
28708
  reason: "read-error"
28512
28709
  });
28513
28710
  }
@@ -28517,7 +28714,7 @@ async function scan6(agg, opts = {}) {
28517
28714
  }
28518
28715
  async function exists5(p8) {
28519
28716
  try {
28520
- await stat9(p8);
28717
+ await stat10(p8);
28521
28718
  return true;
28522
28719
  } catch (error) {
28523
28720
  if (error?.code !== "ENOENT")
@@ -28653,7 +28850,7 @@ var MCP_ADD_ARGS = [
28653
28850
  "mcp"
28654
28851
  ];
28655
28852
  var MCP_REMOVE_ARGS = ["mcp", "remove", "--scope", "user", "aistack"];
28656
- var SKILL_DEST = join13(homedir18(), ".claude", "skills", "aistack-sync");
28853
+ var SKILL_DEST = join13(homedir19(), ".claude", "skills", "aistack-sync");
28657
28854
  function runClaude(args) {
28658
28855
  const r = spawnSync("claude", args, { encoding: "utf-8" });
28659
28856
  const notFound = r.error !== void 0 && r.error.code === "ENOENT";
@@ -28882,6 +29079,68 @@ async function createCommand() {
28882
29079
  outro2(lime("done"));
28883
29080
  }
28884
29081
 
29082
+ // src/commands/cursorFolders.ts
29083
+ import { realpath as realpath6, stat as stat11 } from "node:fs/promises";
29084
+ import path16 from "node:path";
29085
+ var console_ = { print: (line) => process.stdout.write(`${line}
29086
+ `) };
29087
+ async function cursorFoldersCommand(action = "list", dir, out = console_) {
29088
+ const fail = (line) => {
29089
+ out.print(line);
29090
+ process.exitCode = 1;
29091
+ };
29092
+ try {
29093
+ if (action === "list") {
29094
+ const list = await rememberedHomes(CURSOR_HOMES_KEY);
29095
+ if (!list.length) {
29096
+ out.print(
29097
+ "No extra Cursor folders. Sync reads the default folder. Add one with: aistack cursor-folders add <dir>"
29098
+ );
29099
+ return;
29100
+ }
29101
+ out.print("Extra Cursor folders sync reads:");
29102
+ for (const entry of list) out.print(` ${entry}`);
29103
+ return;
29104
+ }
29105
+ if (action !== "add" && action !== "remove") {
29106
+ fail(`Unknown action "${action}". Use list, add or remove.`);
29107
+ return;
29108
+ }
29109
+ if (!dir) {
29110
+ fail(`Name a folder: aistack cursor-folders ${action} <dir>`);
29111
+ return;
29112
+ }
29113
+ const root = await cursorRootFor(dir);
29114
+ if (action === "remove") {
29115
+ const stored = await rememberedHomes(CURSOR_HOMES_KEY);
29116
+ const target = [root, await realpath6(root).catch(() => root)].find(
29117
+ (entry) => stored.includes(entry)
29118
+ ) ?? root;
29119
+ if (await forgetHome(CURSOR_HOMES_KEY, target))
29120
+ out.print(`Removed ${target}`);
29121
+ else fail(`${root} is not in the list.`);
29122
+ return;
29123
+ }
29124
+ let real;
29125
+ try {
29126
+ real = await realpath6(root);
29127
+ if (path16.basename(real) !== "workspaceStorage" || !(await stat11(real)).isDirectory())
29128
+ throw new Error("not a Cursor folder");
29129
+ } catch {
29130
+ fail(
29131
+ `${dir} holds no Cursor data. Pass the folder you start Cursor with (cursor --user-data-dir <dir>).`
29132
+ );
29133
+ return;
29134
+ }
29135
+ if (await rememberHome(CURSOR_HOMES_KEY, real)) out.print(`Added ${real}`);
29136
+ else out.print(`Already in the list: ${real}`);
29137
+ } catch (error) {
29138
+ fail(
29139
+ `Could not update the Cursor folder list: ${error.message}`
29140
+ );
29141
+ }
29142
+ }
29143
+
28885
29144
  // src/commands/login.ts
28886
29145
  import { hostname } from "node:os";
28887
29146
  import * as p5 from "@clack/prompts";
@@ -28974,14 +29233,26 @@ async function loginCommand(options = {}) {
28974
29233
  // src/commands/sync.ts
28975
29234
  import * as p7 from "@clack/prompts";
28976
29235
 
29236
+ // src/autosync/optin.ts
29237
+ import { existsSync as existsSync17 } from "node:fs";
29238
+ import { homedir as homedir25 } from "node:os";
29239
+ import { dirname as dirname12, join as join20 } from "node:path";
29240
+ import * as p6 from "@clack/prompts";
29241
+
28977
29242
  // src/autosync/codexHook.ts
28978
29243
  import { createHash as createHash9 } from "node:crypto";
28979
- import { existsSync as existsSync13, mkdirSync as mkdirSync4, readFileSync as readFileSync14, writeFileSync as writeFileSync4 } from "node:fs";
28980
- import { homedir as homedir19 } from "node:os";
29244
+ import {
29245
+ existsSync as existsSync13,
29246
+ mkdirSync as mkdirSync4,
29247
+ readFileSync as readFileSync14,
29248
+ realpathSync as realpathSync3,
29249
+ writeFileSync as writeFileSync4
29250
+ } from "node:fs";
29251
+ import { homedir as homedir20 } from "node:os";
28981
29252
  import { dirname as dirname7, join as join15 } from "node:path";
28982
29253
  import { parse } from "smol-toml";
28983
29254
  function codexHome() {
28984
- return process.env.CODEX_HOME || join15(homedir19(), ".codex");
29255
+ return process.env.CODEX_HOME || join15(homedir20(), ".codex");
28985
29256
  }
28986
29257
  function codexHooksFile() {
28987
29258
  return join15(codexHome(), "hooks.json");
@@ -29091,8 +29362,12 @@ function codexHookTrusted(configFile = codexConfigFile(), hooksFile = codexHooks
29091
29362
  };
29092
29363
  if (typeof group.matcher === "string") identity.matcher = group.matcher;
29093
29364
  const currentHash = `sha256:${createHash9("sha256").update(JSON.stringify(canonicalJson2(identity))).digest("hex")}`;
29094
- const key2 = `${hooksFile}:session_start:${groupIndex}:${handlerIndex}`;
29095
- matches.push(config.hooks?.state?.[key2]?.trusted_hash === currentHash);
29365
+ const suffix = `:session_start:${groupIndex}:${handlerIndex}`;
29366
+ matches.push(
29367
+ Object.entries(config.hooks?.state ?? {}).some(
29368
+ ([key2, state]) => key2.endsWith(suffix) && state?.trusted_hash === currentHash && samePath(key2.slice(0, -suffix.length), hooksFile)
29369
+ )
29370
+ );
29096
29371
  }
29097
29372
  }
29098
29373
  return matches.length > 0 && matches.every(Boolean);
@@ -29100,6 +29375,14 @@ function codexHookTrusted(configFile = codexConfigFile(), hooksFile = codexHooks
29100
29375
  return null;
29101
29376
  }
29102
29377
  }
29378
+ function samePath(a, b) {
29379
+ if (a === b) return true;
29380
+ try {
29381
+ return realpathSync3(a) === realpathSync3(b);
29382
+ } catch {
29383
+ return false;
29384
+ }
29385
+ }
29103
29386
  function canonicalJson2(value) {
29104
29387
  if (Array.isArray(value)) return value.map(canonicalJson2);
29105
29388
  if (value && typeof value === "object") {
@@ -29117,19 +29400,16 @@ function canonicalJson2(value) {
29117
29400
  throw new TypeError("hook identity is not JSON-serializable");
29118
29401
  }
29119
29402
 
29120
- // src/autosync/optin.ts
29121
- import * as p6 from "@clack/prompts";
29122
-
29123
29403
  // src/autosync/cursorHook.ts
29124
29404
  import { existsSync as existsSync15, mkdirSync as mkdirSync6, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "node:fs";
29125
- import { homedir as homedir21, platform as platform2 } from "node:os";
29405
+ import { homedir as homedir22, platform as platform2 } from "node:os";
29126
29406
  import { dirname as dirname9, join as join17 } from "node:path";
29127
29407
 
29128
29408
  // src/autosync/hook.ts
29129
29409
  import { existsSync as existsSync14, mkdirSync as mkdirSync5, readFileSync as readFileSync15, writeFileSync as writeFileSync5 } from "node:fs";
29130
- import { homedir as homedir20 } from "node:os";
29410
+ import { homedir as homedir21 } from "node:os";
29131
29411
  import { dirname as dirname8, join as join16 } from "node:path";
29132
- var CLAUDE_SETTINGS_FILE = join16(homedir20(), ".claude", "settings.json");
29412
+ var CLAUDE_SETTINGS_FILE = join16(homedir21(), ".claude", "settings.json");
29133
29413
  var AUTO_SYNC_HOOK_COMMAND = "npx -y @use-aistack/cli@latest sync --auto || npx -y --prefer-offline @use-aistack/cli sync --auto";
29134
29414
  function isOurs2(entry) {
29135
29415
  return typeof entry.command === "string" && entry.command.includes("@use-aistack/cli") && entry.command.includes("sync --auto");
@@ -29202,7 +29482,7 @@ function autoSyncHookInstalled(file = CLAUDE_SETTINGS_FILE) {
29202
29482
  }
29203
29483
 
29204
29484
  // src/autosync/cursorHook.ts
29205
- var CURSOR_HOOK_FILE = join17(homedir21(), ".cursor", "hooks.json");
29485
+ var CURSOR_HOOK_FILE = join17(homedir22(), ".cursor", "hooks.json");
29206
29486
  function cursorHookCommand(os = platform2()) {
29207
29487
  if (os === "win32") {
29208
29488
  const script = `Start-Process -WindowStyle Hidden -FilePath 'cmd.exe' -ArgumentList '/d /s /c "set AISTACK_HOOK_SOURCE=cursor&& (${AUTO_SYNC_HOOK_COMMAND}) <NUL >NUL 2>&1"'`;
@@ -29282,10 +29562,10 @@ import {
29282
29562
  unlinkSync as unlinkSync5,
29283
29563
  writeFileSync as writeFileSync7
29284
29564
  } from "node:fs";
29285
- import { homedir as homedir22, platform as platform3 } from "node:os";
29565
+ import { homedir as homedir23, platform as platform3 } from "node:os";
29286
29566
  import { dirname as dirname10, join as join18 } from "node:path";
29287
29567
  var GROK_HOOK_FILE = join18(
29288
- process.env.GROK_HOME || join18(homedir22(), ".grok"),
29568
+ process.env.GROK_HOME || join18(homedir23(), ".grok"),
29289
29569
  "hooks",
29290
29570
  "aistack.json"
29291
29571
  );
@@ -29386,7 +29666,148 @@ function grokAutoSyncHookInstalled(file = GROK_HOOK_FILE) {
29386
29666
  );
29387
29667
  }
29388
29668
 
29669
+ // src/autosync/homes.ts
29670
+ import { realpathSync as realpathSync4 } from "node:fs";
29671
+ import { homedir as homedir24 } from "node:os";
29672
+ import { basename as basename5, dirname as dirname11, join as join19, relative as relative4, sep as sep3 } from "node:path";
29673
+ var HOOK_HARNESSES = [
29674
+ "claude",
29675
+ "codex",
29676
+ "grok"
29677
+ ];
29678
+ function hookFile(harness, home) {
29679
+ if (harness === "claude") return join19(home, "settings.json");
29680
+ if (harness === "codex") return join19(home, "hooks.json");
29681
+ return join19(home, "hooks", "aistack.json");
29682
+ }
29683
+ function realOrSelf(dir) {
29684
+ try {
29685
+ return realpathSync4(dir);
29686
+ } catch {
29687
+ return dir;
29688
+ }
29689
+ }
29690
+ function withDefault(fallback, found) {
29691
+ const homes = [realOrSelf(fallback)];
29692
+ for (const dir of found) if (!homes.includes(dir)) homes.push(dir);
29693
+ return homes;
29694
+ }
29695
+ async function discoverHookHomes() {
29696
+ const home = homedir24();
29697
+ const [claude, codex, grok] = await Promise.all([
29698
+ discoverClaudeRoots(),
29699
+ discoverCodexHomes(),
29700
+ discoverGrokHomes()
29701
+ ]);
29702
+ return {
29703
+ // A Claude Code profile is the folder that holds its `projects` folder.
29704
+ claude: withDefault(join19(home, ".claude"), claude.roots.map(dirname11)),
29705
+ codex: withDefault(
29706
+ process.env.CODEX_HOME || join19(home, ".codex"),
29707
+ codex.homes
29708
+ ),
29709
+ grok: withDefault(process.env.GROK_HOME || join19(home, ".grok"), grok.homes)
29710
+ };
29711
+ }
29712
+ function displayHome(dir, home = homedir24()) {
29713
+ const rel = relative4(home, dir);
29714
+ if (rel === "") return "~";
29715
+ if (!rel.startsWith("..") && !rel.startsWith(sep3) && rel !== dir)
29716
+ return `~/${rel.split(sep3).join("/")}`;
29717
+ return `\u2026/${basename5(dir)}`;
29718
+ }
29719
+
29389
29720
  // src/autosync/optin.ts
29721
+ var HARNESS_NAME = {
29722
+ claude: CLAUDE_HARNESS_NAME,
29723
+ codex: CODEX_HARNESS_NAME,
29724
+ grok: GROK_HARNESS_NAME
29725
+ };
29726
+ function hookOps(deps) {
29727
+ return {
29728
+ claude: {
29729
+ install: deps.installHook ?? ((file) => installAutoSyncHook(file)),
29730
+ remove: deps.removeHook ?? ((file) => removeAutoSyncHook(file)),
29731
+ installed: deps.hookInstalledImpl ?? ((file) => autoSyncHookInstalled(file))
29732
+ },
29733
+ codex: {
29734
+ install: deps.installCodexHook ?? ((file) => installCodexAutoSyncHook(file)),
29735
+ remove: deps.removeCodexHook ?? ((file) => removeCodexAutoSyncHook(file)),
29736
+ installed: deps.codexHookInstalledImpl ?? ((file) => codexAutoSyncHookInstalled(file))
29737
+ },
29738
+ grok: {
29739
+ install: deps.installGrokHook ?? ((file) => installGrokAutoSyncHook(file)),
29740
+ remove: deps.removeGrokHook ?? ((file) => removeGrokAutoSyncHook(file)),
29741
+ installed: deps.grokHookInstalledImpl ?? ((file) => grokAutoSyncHookInstalled(file))
29742
+ }
29743
+ };
29744
+ }
29745
+ function hookTargets(harness, homes, settingsFile) {
29746
+ const recorded = getSettings(settingsFile).autoSyncHookHomes?.[harness] ?? [];
29747
+ return [.../* @__PURE__ */ new Set([...homes[harness], ...recorded])];
29748
+ }
29749
+ function recordHookHomes(settingsFile, harness, update2) {
29750
+ const all = getSettings(settingsFile).autoSyncHookHomes ?? {};
29751
+ const next = update2(all[harness] ?? []);
29752
+ saveSettings(
29753
+ { autoSyncHookHomes: { ...all, [harness]: next } },
29754
+ settingsFile
29755
+ );
29756
+ }
29757
+ function writeHooks(harness, homes, deps, onlyMissing) {
29758
+ const ops = hookOps(deps)[harness];
29759
+ const written = [];
29760
+ const failures = [];
29761
+ for (const home of homes) {
29762
+ const file = hookFile(harness, home);
29763
+ if (onlyMissing && ops.installed(file)) continue;
29764
+ const result = ops.install(file);
29765
+ if (result.ok) written.push(home);
29766
+ else
29767
+ failures.push(
29768
+ `${harnessLabel2(HARNESS_NAME[harness])} (${displayHome(home, deps.homeDir)}): ${result.message}`
29769
+ );
29770
+ }
29771
+ if (written.length > 0) {
29772
+ recordHookHomes(deps.settingsFile, harness, (recorded) => [
29773
+ .../* @__PURE__ */ new Set([...recorded, ...written])
29774
+ ]);
29775
+ }
29776
+ return { written, failures };
29777
+ }
29778
+ function removeHooks(homes, deps) {
29779
+ const results = [];
29780
+ const failures = [];
29781
+ const ops = hookOps(deps);
29782
+ for (const harness of HOOK_HARNESSES) {
29783
+ const removed = [];
29784
+ for (const home of hookTargets(harness, homes, deps.settingsFile)) {
29785
+ const result = ops[harness].remove(hookFile(harness, home));
29786
+ results.push(result);
29787
+ if (result.ok) removed.push(home);
29788
+ else failures.push(result.message);
29789
+ }
29790
+ if ((getSettings(deps.settingsFile).autoSyncHookHomes?.[harness] ?? []).length)
29791
+ recordHookHomes(
29792
+ deps.settingsFile,
29793
+ harness,
29794
+ (recorded) => recorded.filter((home) => !removed.includes(home))
29795
+ );
29796
+ }
29797
+ const cursor = (deps.removeCursorHook ?? removeCursorAutoSyncHook)();
29798
+ results.push(cursor);
29799
+ if (!cursor.ok) failures.push(cursor.message);
29800
+ return { results, failures };
29801
+ }
29802
+ function codexTrustLine(written, deps) {
29803
+ const trusted = deps.codexHookTrustedImpl ?? codexHookTrusted;
29804
+ const untrusted = written.filter(
29805
+ (home) => trusted(join20(home, "config.toml"), hookFile("codex", home)) !== true
29806
+ );
29807
+ if (untrusted.length === 0) return null;
29808
+ const names = untrusted.map((home) => displayHome(home, deps.homeDir));
29809
+ return untrusted.length === 1 ? `Codex hook written to ${names[0]}. Open Codex with that account and run /hooks once to trust it, or it will not run.` : `Codex hook written to ${names.join(", ")}. Open Codex with each of these accounts and run /hooks once to trust it, or it will not run there.`;
29810
+ }
29390
29811
  var NOT_LINKED = "This machine is not linked to an aistack account, and the auto-sync permission lives on your stack. Run `npx @use-aistack/cli@latest sync` first.";
29391
29812
  var NOTHING_TO_TRIGGER = `No supported session on this machine in the last ${DEFAULT_WINDOW_DAYS} days, so nothing would trigger an auto-sync. Nothing was changed.`;
29392
29813
  async function enableAutoSync(frequencyHours = DEFAULT_FREQUENCY_HOURS, deps = {}) {
@@ -29409,21 +29830,20 @@ async function enableAutoSync(frequencyHours = DEFAULT_FREQUENCY_HOURS, deps = {
29409
29830
  message: `Auto-sync was not turned on: ${e instanceof Error ? e.message : String(e)}`
29410
29831
  };
29411
29832
  }
29412
- if (names.has(CLAUDE_HARNESS_NAME)) {
29413
- const result = (deps.installHook ?? installAutoSyncHook)();
29414
- if (!result.ok) return result;
29415
- }
29833
+ const homes = await (deps.homesImpl ?? discoverHookHomes)();
29834
+ const failures = [];
29416
29835
  let trustLine = null;
29417
- if (names.has(CODEX_HARNESS_NAME)) {
29418
- const codexResult = (deps.installCodexHook ?? installCodexAutoSyncHook)();
29419
- if (!codexResult.ok) return codexResult;
29420
- if ((deps.codexHookTrustedImpl ?? codexHookTrusted)() !== true) {
29421
- trustLine = codexResult.message;
29422
- }
29836
+ for (const harness of HOOK_HARNESSES) {
29837
+ if (!names.has(HARNESS_NAME[harness])) continue;
29838
+ const result = writeHooks(harness, homes[harness], deps, false);
29839
+ failures.push(...result.failures);
29840
+ if (harness === "codex") trustLine = codexTrustLine(result.written, deps);
29423
29841
  }
29424
- if (names.has(GROK_HARNESS_NAME)) {
29425
- const grokResult = (deps.installGrokHook ?? installGrokAutoSyncHook)();
29426
- if (!grokResult.ok) return grokResult;
29842
+ if (failures.length > 0) {
29843
+ return {
29844
+ ok: false,
29845
+ message: `Auto-sync is on for this stack, but a hook could not be written: ${failures.join("; ")}`
29846
+ };
29427
29847
  }
29428
29848
  if (names.has(CURSOR_HARNESS_NAME)) {
29429
29849
  const result = (deps.installCursorHook ?? installCursorAutoSyncHook)();
@@ -29458,11 +29878,8 @@ async function disableAutoSync(deps = {}) {
29458
29878
  },
29459
29879
  deps.settingsFile
29460
29880
  );
29461
- const result = (deps.removeHook ?? removeAutoSyncHook)();
29462
- const codexResult = (deps.removeCodexHook ?? removeCodexAutoSyncHook)();
29463
- const grokResult = (deps.removeGrokHook ?? removeGrokAutoSyncHook)();
29464
- const cursorResult = (deps.removeCursorHook ?? removeCursorAutoSyncHook)();
29465
- const failures = [result, codexResult, grokResult, cursorResult].filter((r) => !r.ok).map((r) => r.message);
29881
+ const homes = await (deps.homesImpl ?? discoverHookHomes)();
29882
+ const { failures } = removeHooks(homes, deps);
29466
29883
  const token = (deps.getTokenImpl ?? getToken)();
29467
29884
  if (token !== null) {
29468
29885
  try {
@@ -29500,17 +29917,12 @@ async function reconcileAutoSync(permission, deps = {}) {
29500
29917
  },
29501
29918
  deps.settingsFile
29502
29919
  );
29503
- const results = [
29504
- (deps.removeHook ?? removeAutoSyncHook)(),
29505
- (deps.removeCodexHook ?? removeCodexAutoSyncHook)(),
29506
- (deps.removeGrokHook ?? removeGrokAutoSyncHook)(),
29507
- (deps.removeCursorHook ?? removeCursorAutoSyncHook)()
29508
- ];
29509
- const failures2 = results.filter((result) => !result.ok);
29920
+ const homes2 = await (deps.homesImpl ?? discoverHookHomes)();
29921
+ const { results, failures: failures2 } = removeHooks(homes2, deps);
29510
29922
  if (failures2.length > 0) {
29511
29923
  return {
29512
29924
  ok: false,
29513
- message: `Auto-sync is off on this machine, but a trigger could not be removed: ${failures2.map((result) => result.message).join("; ")}. The next interactive sync will retry.`
29925
+ message: `Auto-sync is off on this machine, but a trigger could not be removed: ${failures2.join("; ")}. The next interactive sync will retry.`
29514
29926
  };
29515
29927
  }
29516
29928
  const changed = settings.autoSync?.enabled !== false || results.some((result) => !result.message.toLowerCase().startsWith("no "));
@@ -29523,34 +29935,27 @@ async function reconcileAutoSync(permission, deps = {}) {
29523
29935
  const detected = await (deps.detectedImpl ?? detectedAdapters)();
29524
29936
  if (detected.length === 0) return null;
29525
29937
  const names = new Set(detected.map((a) => a.name));
29938
+ const homes = await (deps.homesImpl ?? discoverHookHomes)();
29526
29939
  const installed = [];
29527
29940
  const failures = [];
29528
- const install = (harnessName, isInstalled, write) => {
29529
- if (!names.has(harnessName) || isInstalled()) return;
29530
- const result = write();
29531
- if (result.ok) installed.push(harnessLabel2(harnessName));
29941
+ let trustLine = null;
29942
+ for (const harness of HOOK_HARNESSES) {
29943
+ if (!names.has(HARNESS_NAME[harness])) continue;
29944
+ const result = writeHooks(harness, homes[harness], deps, true);
29945
+ failures.push(...result.failures);
29946
+ if (result.written.length > 0) {
29947
+ const label = harnessLabel2(HARNESS_NAME[harness]);
29948
+ installed.push(
29949
+ homes[harness].length > 1 ? `${label} (${result.written.map((home) => displayHome(home, deps.homeDir)).join(", ")})` : label
29950
+ );
29951
+ }
29952
+ if (harness === "codex") trustLine = codexTrustLine(result.written, deps);
29953
+ }
29954
+ if (names.has(CURSOR_HARNESS_NAME) && !(deps.cursorHookInstalledImpl ?? cursorAutoSyncHookInstalled)()) {
29955
+ const result = (deps.installCursorHook ?? installCursorAutoSyncHook)();
29956
+ if (result.ok) installed.push(harnessLabel2(CURSOR_HARNESS_NAME));
29532
29957
  else failures.push(result.message);
29533
- };
29534
- install(
29535
- CLAUDE_HARNESS_NAME,
29536
- deps.hookInstalledImpl ?? autoSyncHookInstalled,
29537
- deps.installHook ?? installAutoSyncHook
29538
- );
29539
- install(
29540
- CODEX_HARNESS_NAME,
29541
- deps.codexHookInstalledImpl ?? codexAutoSyncHookInstalled,
29542
- deps.installCodexHook ?? installCodexAutoSyncHook
29543
- );
29544
- install(
29545
- GROK_HARNESS_NAME,
29546
- deps.grokHookInstalledImpl ?? grokAutoSyncHookInstalled,
29547
- deps.installGrokHook ?? installGrokAutoSyncHook
29548
- );
29549
- install(
29550
- CURSOR_HARNESS_NAME,
29551
- deps.cursorHookInstalledImpl ?? cursorAutoSyncHookInstalled,
29552
- deps.installCursorHook ?? installCursorAutoSyncHook
29553
- );
29958
+ }
29554
29959
  if (failures.length > 0) {
29555
29960
  return {
29556
29961
  ok: false,
@@ -29569,9 +29974,71 @@ async function reconcileAutoSync(permission, deps = {}) {
29569
29974
  if (installed.length === 0 && mirrored) return null;
29570
29975
  return {
29571
29976
  ok: true,
29572
- message: installed.length > 0 ? `Auto-sync is on for this stack. Installed the ${installed.join(" and ")} trigger on this machine; it runs about every ${frequencyHours}h during session activity.` : `Auto-sync is on for this stack. It runs about every ${frequencyHours}h when a ${harnessListLabel(detected)} ${names.has(CURSOR_HARNESS_NAME) ? "session is active" : "session starts"}.`
29977
+ message: [
29978
+ installed.length > 0 ? `Auto-sync is on for this stack. Installed the ${installed.join(" and ")} trigger on this machine; it runs about every ${frequencyHours}h during session activity.` : `Auto-sync is on for this stack. It runs about every ${frequencyHours}h when a ${harnessListLabel(detected)} ${names.has(CURSOR_HARNESS_NAME) ? "session is active" : "session starts"}.`,
29979
+ ...trustLine ? [trustLine] : []
29980
+ ].join("\n")
29573
29981
  };
29574
29982
  }
29983
+ async function codexTrustReminder(deps = {}) {
29984
+ const homes = await (deps.homesImpl ?? discoverHookHomes)();
29985
+ const installed = hookOps(deps).codex.installed;
29986
+ const trusted = deps.codexHookTrustedImpl ?? codexHookTrusted;
29987
+ const untrusted = hookTargets("codex", homes, deps.settingsFile).filter(
29988
+ (home) => installed(hookFile("codex", home)) && trusted(join20(home, "config.toml"), hookFile("codex", home)) === false
29989
+ );
29990
+ if (untrusted.length === 0) return null;
29991
+ return `The auto-sync hook in ${untrusted.map((home) => displayHome(home, deps.homeDir)).join(", ")} is not trusted yet. Open Codex with ${untrusted.length === 1 ? "that account" : "each of these accounts"} and run /hooks once, or it will not run.`;
29992
+ }
29993
+ async function autoSyncStatus(deps = {}) {
29994
+ const config = getSettings(deps.settingsFile).autoSync;
29995
+ const lines2 = [
29996
+ config === void 0 ? "Auto-sync is not set up on this machine." : config.enabled ? `Auto-sync is on, about every ${normalizeFrequencyHours(config.frequencyHours)}h.` : "Auto-sync is off on this machine."
29997
+ ];
29998
+ const homes = await (deps.homesImpl ?? discoverHookHomes)();
29999
+ const ops = hookOps(deps);
30000
+ const trusted = deps.codexHookTrustedImpl ?? codexHookTrusted;
30001
+ const rows = [];
30002
+ for (const harness of HOOK_HARNESSES) {
30003
+ for (const home of hookTargets(harness, homes, deps.settingsFile)) {
30004
+ const file = hookFile(harness, home);
30005
+ const installed = ops[harness].installed(file);
30006
+ if (!installed && !existsSync17(home)) continue;
30007
+ let state = installed ? "hook installed" : "no hook";
30008
+ if (installed && harness === "codex") {
30009
+ const trust = trusted(join20(home, "config.toml"), file);
30010
+ if (trust === true) state = "hook installed, trusted";
30011
+ else if (trust === false)
30012
+ state = "hook installed, not trusted yet: run /hooks in Codex";
30013
+ }
30014
+ rows.push([
30015
+ harnessLabel2(HARNESS_NAME[harness]),
30016
+ displayHome(home, deps.homeDir),
30017
+ state
30018
+ ]);
30019
+ }
30020
+ }
30021
+ const cursorHome = dirname12(CURSOR_HOOK_FILE);
30022
+ const cursorInstalled = (deps.cursorHookInstalledImpl ?? cursorAutoSyncHookInstalled)();
30023
+ if (cursorInstalled || existsSync17(cursorHome)) {
30024
+ rows.push([
30025
+ harnessLabel2(CURSOR_HARNESS_NAME),
30026
+ displayHome(cursorHome, deps.homeDir ?? homedir25()),
30027
+ cursorInstalled ? "hook installed" : "no hook"
30028
+ ]);
30029
+ }
30030
+ if (rows.length === 0) {
30031
+ lines2.push("No harness folders found on this machine.");
30032
+ return lines2;
30033
+ }
30034
+ const width = (i) => Math.max(...rows.map((row) => row[i].length));
30035
+ for (const [label, folder, state] of rows) {
30036
+ lines2.push(
30037
+ `${label.padEnd(width(0))} ${folder.padEnd(width(1))} ${state}`
30038
+ );
30039
+ }
30040
+ return lines2;
30041
+ }
29575
30042
  async function settleAutoSync(permission, deps = {}) {
29576
30043
  if (permission !== null) {
29577
30044
  const result = await reconcileAutoSync(permission, deps);
@@ -29636,15 +30103,12 @@ async function offerAutoSyncOptIn(deps = {}) {
29636
30103
  // src/autosync/run.ts
29637
30104
  import {
29638
30105
  appendFileSync,
29639
- closeSync as closeSync5,
29640
- mkdirSync as mkdirSync9,
29641
- openSync as openSync5,
29642
- readFileSync as readFileSync19,
29643
- unlinkSync as unlinkSync6,
29644
- writeFileSync as writeFileSync9
30106
+ mkdirSync as mkdirSync10,
30107
+ readFileSync as readFileSync20,
30108
+ writeFileSync as writeFileSync10
29645
30109
  } from "node:fs";
29646
- import { homedir as homedir24 } from "node:os";
29647
- import { dirname as dirname11, join as join19 } from "node:path";
30110
+ import { homedir as homedir27 } from "node:os";
30111
+ import { dirname as dirname14, join as join21 } from "node:path";
29648
30112
 
29649
30113
  // src/sync/stage.ts
29650
30114
  import { createHash as createHash11 } from "node:crypto";
@@ -29804,8 +30268,8 @@ function selectDaysToPublish(input) {
29804
30268
 
29805
30269
  // src/workflow/git.ts
29806
30270
  import { execFile, execFileSync as execFileSync2 } from "node:child_process";
29807
- import { existsSync as existsSync17 } from "node:fs";
29808
- import path15 from "node:path";
30271
+ import { existsSync as existsSync18 } from "node:fs";
30272
+ import path17 from "node:path";
29809
30273
  var TEST_FILE_RULE_VERSION = "test-files/v2";
29810
30274
  var FILE_TYPE_RULE_VERSION = "file-types/v3";
29811
30275
  var COMMIT_SET_RULE_VERSION = "commit-set/v1";
@@ -29815,7 +30279,7 @@ function gitDiagnostics() {
29815
30279
  const report = (error, cwd, args, stderr) => {
29816
30280
  const details = error;
29817
30281
  if (args[0] === "rev-parse") {
29818
- if (details.code === "ENOENT" && !existsSync17(cwd)) {
30282
+ if (details.code === "ENOENT" && !existsSync18(cwd)) {
29819
30283
  missing++;
29820
30284
  return;
29821
30285
  }
@@ -30005,8 +30469,8 @@ function isTestFile(file) {
30005
30469
  if (parts.some((part) => ["test", "tests", "__tests__"].includes(part))) {
30006
30470
  return true;
30007
30471
  }
30008
- const basename5 = parts.at(-1) ?? "";
30009
- return /(?:^|[._-])(test|spec)(?:[._-]|$)/.test(basename5);
30472
+ const basename6 = parts.at(-1) ?? "";
30473
+ return /(?:^|[._-])(test|spec)(?:[._-]|$)/.test(basename6);
30010
30474
  }
30011
30475
  function utcCell(authoredMs) {
30012
30476
  const at = new Date(authoredMs);
@@ -30222,9 +30686,9 @@ function reduceGitHistories(histories, options) {
30222
30686
  if (included) seenCommits.add(hash2);
30223
30687
  continue;
30224
30688
  }
30225
- const stat10 = parseNumstat(field);
30226
- if (!stat10) continue;
30227
- let file = stat10.file;
30689
+ const stat12 = parseNumstat(field);
30690
+ if (!stat12) continue;
30691
+ let file = stat12.file;
30228
30692
  if (file.length === 0) {
30229
30693
  fieldIndex += 2;
30230
30694
  file = fields[fieldIndex] ?? fields[fieldIndex - 1] ?? "";
@@ -30232,13 +30696,13 @@ function reduceGitHistories(histories, options) {
30232
30696
  if (!current?.included) continue;
30233
30697
  if (isUnauthoredPath(file)) continue;
30234
30698
  current.authored = true;
30235
- const fileChangedLines = stat10.additions + stat10.removals;
30236
- current.additions += stat10.additions;
30237
- current.removals += stat10.removals;
30699
+ const fileChangedLines = stat12.additions + stat12.removals;
30700
+ current.additions += stat12.additions;
30701
+ current.removals += stat12.removals;
30238
30702
  current.changedLines += fileChangedLines;
30239
30703
  if (isTestFile(file)) current.touchesTest = true;
30240
30704
  if (fileChangedLines <= 0) continue;
30241
- const extension = path15.extname(file).toLowerCase();
30705
+ const extension = path17.extname(file).toLowerCase();
30242
30706
  if (APPROVED_EXTENSIONS.has(extension)) {
30243
30707
  current.extensionLines.set(
30244
30708
  extension,
@@ -30343,11 +30807,11 @@ function buildWorkflowExtraction(harnessWorkflows, git, utcOffsetMinutes = machi
30343
30807
 
30344
30808
  // src/sync/grokDateCache.ts
30345
30809
  import { createHash as createHash10 } from "node:crypto";
30346
- import { existsSync as existsSync18, mkdirSync as mkdirSync8, readFileSync as readFileSync18, writeFileSync as writeFileSync8 } from "node:fs";
30347
- import { homedir as homedir23 } from "node:os";
30348
- import path16 from "node:path";
30349
- var defaultFile = path16.join(
30350
- homedir23(),
30810
+ import { existsSync as existsSync19, mkdirSync as mkdirSync8, readFileSync as readFileSync18, writeFileSync as writeFileSync8 } from "node:fs";
30811
+ import { homedir as homedir26 } from "node:os";
30812
+ import path18 from "node:path";
30813
+ var defaultFile = path18.join(
30814
+ homedir26(),
30351
30815
  ".config",
30352
30816
  "aistack",
30353
30817
  "grok-session-dates.json"
@@ -30356,7 +30820,7 @@ function grokCacheScope(baseUrl, stack, token) {
30356
30820
  return createHash10("sha256").update(`${baseUrl}\0${stack}\0${token}`).digest("hex");
30357
30821
  }
30358
30822
  function read2(file) {
30359
- if (!existsSync18(file)) return {};
30823
+ if (!existsSync19(file)) return {};
30360
30824
  try {
30361
30825
  const value = JSON.parse(readFileSync18(file, "utf8"));
30362
30826
  return value && typeof value === "object" ? value : {};
@@ -30370,7 +30834,7 @@ function loadGrokDateHints(scope, file = defaultFile) {
30370
30834
  function saveGrokDateHints(scope, hints, file = defaultFile) {
30371
30835
  const cache = read2(file);
30372
30836
  cache[scope] = hints;
30373
- mkdirSync8(path16.dirname(file), { recursive: true });
30837
+ mkdirSync8(path18.dirname(file), { recursive: true });
30374
30838
  writeFileSync8(file, JSON.stringify(cache, null, 2));
30375
30839
  }
30376
30840
  function mapToHints(value, floor) {
@@ -31254,42 +31718,84 @@ function describeScan(stats) {
31254
31718
  return `${stats.filesRead}/${stats.filesFound} files read, ${stats.filesUnreadable} unreadable`;
31255
31719
  }
31256
31720
 
31721
+ // src/autosync/reserve.ts
31722
+ import { randomUUID as randomUUID3 } from "node:crypto";
31723
+ import {
31724
+ mkdirSync as mkdirSync9,
31725
+ readFileSync as readFileSync19,
31726
+ renameSync as renameSync3,
31727
+ rmSync,
31728
+ statSync as statSync7,
31729
+ writeFileSync as writeFileSync9
31730
+ } from "node:fs";
31731
+ import { dirname as dirname13 } from "node:path";
31732
+ var MUTEX_WAIT_MS = 2e3;
31733
+ var MUTEX_STALE_MS = 3e4;
31734
+ var code = (error) => error?.code;
31735
+ function sleep(ms) {
31736
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
31737
+ }
31738
+ function acquire(mutex) {
31739
+ const deadline = Date.now() + MUTEX_WAIT_MS;
31740
+ for (; ; ) {
31741
+ try {
31742
+ mkdirSync9(mutex);
31743
+ return true;
31744
+ } catch (error) {
31745
+ if (code(error) !== "EEXIST") throw error;
31746
+ }
31747
+ try {
31748
+ if (Date.now() - statSync7(mutex).mtimeMs >= MUTEX_STALE_MS)
31749
+ rmSync(mutex, { recursive: true, force: true });
31750
+ } catch (error) {
31751
+ if (code(error) !== "ENOENT") throw error;
31752
+ }
31753
+ if (Date.now() >= deadline) return false;
31754
+ sleep(5 + Math.random() * 10);
31755
+ }
31756
+ }
31757
+ function isHeld(file, now, windowMs) {
31758
+ let content;
31759
+ try {
31760
+ content = readFileSync19(file, "utf-8").trim();
31761
+ } catch (error) {
31762
+ if (code(error) === "ENOENT") return false;
31763
+ throw error;
31764
+ }
31765
+ const held = content === "" ? Number.NaN : Number(content);
31766
+ if (Number.isFinite(held)) return now - held < windowMs;
31767
+ return Date.now() - statSync7(file).mtimeMs < windowMs;
31768
+ }
31769
+ function reserveAttempt(file, now, windowMs) {
31770
+ mkdirSync9(dirname13(file), { recursive: true });
31771
+ const mutex = `${file}.lock`;
31772
+ if (!acquire(mutex)) return false;
31773
+ try {
31774
+ if (isHeld(file, now, windowMs)) return false;
31775
+ const own = `${file}.${process.pid}.${randomUUID3()}`;
31776
+ writeFileSync9(own, String(now));
31777
+ renameSync3(own, file);
31778
+ return true;
31779
+ } finally {
31780
+ rmSync(mutex, { recursive: true, force: true });
31781
+ }
31782
+ }
31783
+
31257
31784
  // src/autosync/run.ts
31258
- var SYNC_LOG_FILE = join19(homedir24(), ".config", "aistack", "sync.log");
31785
+ var SYNC_LOG_FILE = join21(homedir27(), ".config", "aistack", "sync.log");
31259
31786
  var SYNC_LOG_MAX_LINES = 200;
31260
31787
  var FIX_COMMAND = "npx @use-aistack/cli@latest sync";
31261
31788
  var REVOKED_RESULT = "off - auto-sync is switched off for this stack";
31262
31789
  function appendLogLine(file, line) {
31263
- mkdirSync9(dirname11(file), { recursive: true });
31790
+ mkdirSync10(dirname14(file), { recursive: true });
31264
31791
  appendFileSync(file, `${line}
31265
31792
  `);
31266
- const lines2 = readFileSync19(file, "utf-8").split("\n").filter(Boolean);
31793
+ const lines2 = readFileSync20(file, "utf-8").split("\n").filter(Boolean);
31267
31794
  if (lines2.length > SYNC_LOG_MAX_LINES) {
31268
- writeFileSync9(file, `${lines2.slice(-SYNC_LOG_MAX_LINES).join("\n")}
31795
+ writeFileSync10(file, `${lines2.slice(-SYNC_LOG_MAX_LINES).join("\n")}
31269
31796
  `);
31270
31797
  }
31271
31798
  }
31272
- function reserveAttempt(file, now, windowMs) {
31273
- mkdirSync9(dirname11(file), { recursive: true });
31274
- for (; ; ) {
31275
- try {
31276
- const fd = openSync5(file, "wx");
31277
- writeFileSync9(fd, String(now));
31278
- closeSync5(fd);
31279
- return true;
31280
- } catch (error) {
31281
- if (error.code !== "EEXIST") throw error;
31282
- const held = Number(readFileSync19(file, "utf-8"));
31283
- if (Number.isFinite(held) && now - held < windowMs) return false;
31284
- try {
31285
- unlinkSync6(file);
31286
- } catch (unlinkError) {
31287
- if (unlinkError.code !== "ENOENT")
31288
- throw unlinkError;
31289
- }
31290
- }
31291
- }
31292
- }
31293
31799
  async function runAutoSync(deps) {
31294
31800
  const now = (deps.now ?? Date.now)();
31295
31801
  const settingsFile = deps.settingsFile;
@@ -31308,7 +31814,7 @@ async function runAutoSync(deps) {
31308
31814
  const state = settings.autoSyncState ?? {};
31309
31815
  const lastRunAt = state.lastRunAt ?? 0;
31310
31816
  if (now - lastRunAt < windowMs) return;
31311
- const reservationFile = deps.reservationFile ?? `${settingsFile ?? join19(homedir24(), ".config", "aistack", "settings.json")}.auto-sync-attempt`;
31817
+ const reservationFile = deps.reservationFile ?? `${settingsFile ?? join21(homedir27(), ".config", "aistack", "settings.json")}.auto-sync-attempt`;
31312
31818
  if (!reserveAttempt(reservationFile, now, windowMs)) return;
31313
31819
  saveSettings({ autoSyncState: { ...state, lastRunAt: now } }, settingsFile);
31314
31820
  const stage = deps.stageImpl ?? stageSync;
@@ -31583,9 +32089,18 @@ async function syncCommand(options = {}) {
31583
32089
  }
31584
32090
  return;
31585
32091
  }
32092
+ if (options.auto === "status") {
32093
+ intro2("sync");
32094
+ const [first, ...rows] = await autoSyncStatus();
32095
+ p7.log.message([first, ...rows.map((row) => dim(row))].join("\n"));
32096
+ outro2("done");
32097
+ return;
32098
+ }
31586
32099
  if (options.auto !== void 0) {
31587
32100
  intro2("sync");
31588
- outroError(`unknown --auto value "${options.auto}" (use on or off)`);
32101
+ outroError(
32102
+ `unknown --auto value "${options.auto}" (use on, off or status)`
32103
+ );
31589
32104
  process.exitCode = 1;
31590
32105
  return;
31591
32106
  }
@@ -31594,9 +32109,8 @@ async function syncCommand(options = {}) {
31594
32109
  if (lastAuto !== void 0) {
31595
32110
  p7.log.message(dim(`auto-sync: ${lastAuto}`));
31596
32111
  }
31597
- if (codexAutoSyncHookInstalled() && codexHookTrusted() === false) {
31598
- p7.log.warn(CODEX_TRUST_INSTRUCTION);
31599
- }
32112
+ const trustReminder = await codexTrustReminder();
32113
+ if (trustReminder) p7.log.warn(trustReminder);
31600
32114
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
31601
32115
  outroError("sync needs an interactive terminal. Nothing was sent.");
31602
32116
  process.exitCode = 1;
@@ -31828,7 +32342,7 @@ function createSyncServer(deps, send) {
31828
32342
  let nextRequestId = 1;
31829
32343
  const pending = /* @__PURE__ */ new Map();
31830
32344
  const ok = (id, result) => send({ jsonrpc: "2.0", id, result });
31831
- const err = (id, code, message) => send({ jsonrpc: "2.0", id, error: { code, message } });
32345
+ const err = (id, code2, message) => send({ jsonrpc: "2.0", id, error: { code: code2, message } });
31832
32346
  const request2 = (method, params, onReply) => {
31833
32347
  const id = `aistack-${nextRequestId++}`;
31834
32348
  pending.set(id, onReply);
@@ -32054,7 +32568,7 @@ program.command("mcp").description(
32054
32568
  });
32055
32569
  program.command("sync").description("Scan, preview, and publish measured usage (rolling 30 days)").option(
32056
32570
  "--auto [state]",
32057
- "silent background sync; 'on' asks your stack for the permission and installs harness hooks, 'off' revokes both"
32571
+ "silent background sync; 'on' asks your stack for the permission and installs a hook in every account folder of each harness, 'off' revokes both, 'status' lists each folder's hook"
32058
32572
  ).option(
32059
32573
  "--every <hours>",
32060
32574
  "with --auto on: hours between auto-syncs (default 6)"
@@ -32063,6 +32577,9 @@ program.command("sync").description("Scan, preview, and publish measured usage (
32063
32577
  "print every phase with its duration to stderr, for a sync that looks stuck (same as AISTACK_DEBUG=1)"
32064
32578
  ).action((options) => syncCommand(options));
32065
32579
  program.command("connect").description("Install the in-session sync surface (MCP server + Skill)").argument("<harness>", 'the harness to connect ("claude")').action(connectCommand);
32580
+ program.command("cursor-folders").description(
32581
+ "List, add or remove extra Cursor data folders (cursor --user-data-dir) that sync reads"
32582
+ ).argument("[action]", "list, add or remove", "list").argument("[dir]", "the folder you start Cursor with").action((action, dir) => cursorFoldersCommand(action, dir));
32066
32583
  if (!supportsNodeVersion(process.versions.node)) {
32067
32584
  process.stderr.write(`${unsupportedNodeMessage(process.versions.node)}
32068
32585
  `);