@use-aistack/cli 0.20.5 → 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((path16) => !unverifiedResidueSet.has(path16)).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(path16) {
481
- super(`Database is locked: ${path16}. Close Cursor or retry later.`);
482
- this.path = path16;
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(path16) {
493
- super(`Database not found: ${path16}. Check dataPath configuration.`);
494
- this.path = path16;
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(path16) {
547
- super(`No workspace found for path: ${path16}. Please open the project in Cursor first.`);
548
- this.path = path16;
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(path16) {
559
- super(`Source and destination are the same: ${path16}`);
560
- this.path = path16;
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(path16) {
571
- super(`No sessions found for workspace: ${path16}. Use 'cursor-history list --workspace "${path16}"' to verify.`);
572
- this.path = path16;
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(path16, sessionCount) {
585
- super(`Destination already has ${sessionCount} session(s): ${path16}. Use --force to proceed (will add sessions alongside existing ones).`);
586
- this.path = path16;
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(path16) {
622
- super(`No Cursor data found at: ${path16}. Verify Cursor is installed and has been used.`);
623
- this.path = path16;
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(path16) {
634
- super(`File already exists: ${path16}. Use --force to overwrite.`);
635
- this.path = path16;
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(path16) {
672
- super(`Backup file not found: ${path16}`);
673
- this.path = path16;
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(path16, reason) {
686
- super(`Invalid backup file: ${path16}. ${reason}`);
687
- this.path = path16;
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(path16) {
699
- super(`Target already has Cursor data: ${path16}. Use --force to overwrite.`);
700
- this.path = path16;
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
  }
@@ -720,7 +720,7 @@ var init_errors3 = __esm({
720
720
 
721
721
  // ../../node_modules/.pnpm/cursor-history@0.18.0_patch_hash=dbff0ea0e399ea9504168452170a23ee2b432a6dc6a69a20b49bf95ef139fa74/node_modules/cursor-history/dist/lib/platform.js
722
722
  import { existsSync as existsSync6, readFileSync as readFileSync7, readdirSync as readdirSync3 } from "node:fs";
723
- import { homedir as homedir9 } from "node:os";
723
+ import { homedir as homedir10 } from "node:os";
724
724
  import { basename as basename2, dirname as dirname3, join as join6 } from "node:path";
725
725
  function detectPlatform() {
726
726
  switch (process.platform) {
@@ -757,7 +757,7 @@ function detectPreferredStackSource(customDataPath) {
757
757
  return findStoreRoot(explicit) ? "store" : "composer";
758
758
  }
759
759
  const storeRootEnv = process.env["CURSOR_STORE_ROOT"];
760
- const defaultStoreRoot = join6(homedir9(), ".cursor");
760
+ const defaultStoreRoot = join6(homedir10(), ".cursor");
761
761
  if (storeRootEnv && !pathsEqual(storeRootEnv, defaultStoreRoot)) {
762
762
  return "store";
763
763
  }
@@ -767,11 +767,11 @@ function getDefaultCursorDataPath(platform4) {
767
767
  const p8 = platform4 ?? detectPlatform();
768
768
  switch (p8) {
769
769
  case "windows":
770
- return join6(process.env["APPDATA"] ?? join6(homedir9(), "AppData", "Roaming"), "Cursor", "User", "workspaceStorage");
770
+ return join6(process.env["APPDATA"] ?? join6(homedir10(), "AppData", "Roaming"), "Cursor", "User", "workspaceStorage");
771
771
  case "macos":
772
- return join6(homedir9(), "Library", "Application Support", "Cursor", "User", "workspaceStorage");
772
+ return join6(homedir10(), "Library", "Application Support", "Cursor", "User", "workspaceStorage");
773
773
  case "linux":
774
- return join6(homedir9(), ".config", "Cursor", "User", "workspaceStorage");
774
+ return join6(homedir10(), ".config", "Cursor", "User", "workspaceStorage");
775
775
  }
776
776
  }
777
777
  function getCursorDataPath(customPath) {
@@ -787,23 +787,23 @@ function getCursorDataPath(customPath) {
787
787
  function getGlobalStoragePath(customDataPath) {
788
788
  return join6(dirname3(getCursorDataPath(customDataPath)), "globalStorage");
789
789
  }
790
- function expandPath(path16) {
791
- if (path16.startsWith("~")) {
792
- return join6(homedir9(), path16.slice(1));
790
+ function expandPath(path19) {
791
+ if (path19.startsWith("~")) {
792
+ return join6(homedir10(), path19.slice(1));
793
793
  }
794
- return path16;
794
+ return path19;
795
795
  }
796
- function contractPath(path16) {
797
- const home = homedir9();
798
- if (path16.startsWith(home)) {
799
- return "~" + path16.slice(home.length);
796
+ function contractPath(path19) {
797
+ const home = homedir10();
798
+ if (path19.startsWith(home)) {
799
+ return "~" + path19.slice(home.length);
800
800
  }
801
- return path16;
801
+ return path19;
802
802
  }
803
803
  function normalizePath(filePath) {
804
804
  let normalized = filePath;
805
805
  if (normalized.startsWith("~")) {
806
- normalized = join6(homedir9(), normalized.slice(1));
806
+ normalized = join6(homedir10(), normalized.slice(1));
807
807
  }
808
808
  while (normalized.length > 1 && normalized.endsWith("/")) {
809
809
  normalized = normalized.slice(0, -1);
@@ -908,7 +908,7 @@ function resolveStoreRoot(customDataPath) {
908
908
  const storeEnv = process.env["CURSOR_STORE_ROOT"];
909
909
  if (storeEnv)
910
910
  return findStoreRoot(storeEnv) ?? storeEnv;
911
- return join6(homedir9(), ".cursor");
911
+ return join6(homedir10(), ".cursor");
912
912
  }
913
913
  var cachedIsWsl, STORE_CHILDREN;
914
914
  var init_platform = __esm({
@@ -1439,8 +1439,8 @@ function normalizePublicWorkspacePath(value) {
1439
1439
  return void 0;
1440
1440
  }
1441
1441
  }
1442
- function exactComparisonKey(path16) {
1443
- return path16.caseInsensitive ? path16.path.toLowerCase() : path16.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(path16, 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(path16, { 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(path16, 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(path16, { 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(path16, 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(path16, 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(path16, 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(path16, { readonly: options.readonly });
3016
- debugLog(`Opened database with better-sqlite3: ${path16} (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(path16, 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(path16, { readOnly: options.readonly });
3212
- debugLog(`Opened database with node:sqlite: ${path16} (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(path16, request2) {
3237
- return registry.openDatabase(path16, request2);
3236
+ async function openDatabase(path19, request2) {
3237
+ return registry.openDatabase(path19, request2);
3238
3238
  }
3239
- async function openDatabaseReadWrite(path16, request2) {
3240
- return registry.openDatabaseReadWrite(path16, 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(path16, contents) {
3378
- const descriptor = openSync(path16, 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(path16, contents) {
3387
3387
  closeSync(descriptor);
3388
3388
  }
3389
3389
  }
3390
- function attemptRemoveEntryNoFollow(path16) {
3390
+ function attemptRemoveEntryNoFollow(path19) {
3391
3391
  let stats;
3392
3392
  try {
3393
- stats = lstatSync(path16);
3393
+ stats = lstatSync(path19);
3394
3394
  } catch (error) {
3395
3395
  if (!isMissing(error)) {
3396
3396
  }
@@ -3398,13 +3398,13 @@ function attemptRemoveEntryNoFollow(path16) {
3398
3398
  }
3399
3399
  if (stats.isDirectory() && !stats.isSymbolicLink()) {
3400
3400
  try {
3401
- rmdirSync(path16);
3401
+ rmdirSync(path19);
3402
3402
  } catch {
3403
3403
  }
3404
3404
  return;
3405
3405
  }
3406
3406
  try {
3407
- unlinkSync(path16);
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(path16) {
3435
+ function mayStillExist(path19) {
3436
3436
  try {
3437
- lstatSync(path16);
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(path16, marker, markerPath, signal) {
3735
- this.path = path16;
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(path16) {
3766
+ register(path19) {
3767
3767
  this.assertOpen();
3768
- const candidatePath = resolve(path16);
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 path16 of tracked)
3783
- attemptRemoveEntryNoFollow(path16);
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(path16, options) {
4807
- return BoundedZipArchive.open(path16, 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(path16, entries, archiveSize, centralOffset, handle, limits, signal, io) {
4954
- this.path = path16;
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(path16, 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(path16, "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(path16, 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(stat9) {
5498
+ function projectStat(stat12) {
5499
5499
  return {
5500
- device: BigInt(stat9.dev),
5501
- inode: BigInt(stat9.ino),
5502
- mode: Number(stat9.mode) & 511,
5503
- regularFile: stat9.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(stat9, expected) {
5507
- return stat9.device === expected.device && stat9.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: (path16) => openSync2(path16, 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: (path16) => projectStat(lstatSync2(path16, { 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(stat9, expected) {
5591
- return stat9.isFile() && stat9.dev === expected.device && stat9.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(path16, expected, operations) {
5593
+ function pathIdentityVerified(path19, expected, operations) {
5594
5594
  try {
5595
- return hasIdentity2(operations.statPathNoFollow(path16), 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: (path16) => unlinkSync2(path16),
5647
- statPathNoFollow: (path16) => lstatSync3(path16, { 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(stat9, expected) {
5658
- return stat9.isFile() && stat9.dev === expected.device && stat9.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(path16, cause, identityVerified = true) {
5661
- const error = new TemporaryArtifactCleanupError(identityVerified ? [path16] : [], identityVerified ? [] : [path16]);
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: (path16) => unlinkSync3(path16),
5710
- statPathNoFollow: (path16) => lstatSync4(path16, { bigint: true })
5709
+ unlink: (path19) => unlinkSync3(path19),
5710
+ statPathNoFollow: (path19) => lstatSync4(path19, { bigint: true })
5711
5711
  });
5712
5712
  }
5713
5713
  });
@@ -5761,7 +5761,7 @@ var init_session_id = __esm({
5761
5761
  // ../../node_modules/.pnpm/cursor-history@0.18.0_patch_hash=dbff0ea0e399ea9504168452170a23ee2b432a6dc6a69a20b49bf95ef139fa74/node_modules/cursor-history/dist/core/backup.js
5762
5762
  import { createHash as createHash4, randomUUID } from "node:crypto";
5763
5763
  import { chmodSync as chmodSync3, closeSync as closeSync3, constants as constants3, existsSync as existsSync7, copyFileSync, fchmodSync as fchmodSync3, fstatSync as fstatSync3, fsyncSync as fsyncSync2, lstatSync as lstatSync5, mkdirSync as mkdirSync2, openSync as openSync3, readFileSync as readFileSync9, readSync, readdirSync as readdirSync5, realpathSync as realpathSync2, statSync as statSync3, unlinkSync as unlinkSync4, writeSync } from "node:fs";
5764
- import { homedir as homedir10 } from "node:os";
5764
+ import { homedir as homedir11 } from "node:os";
5765
5765
  import { basename as basename4, dirname as dirname4, isAbsolute as isAbsolute2, join as join8, relative as relative3, resolve as resolve2, sep as sep2 } from "node:path";
5766
5766
  function backupDatabaseReadRequest(sqliteDriver, io, dbPath, logicalSessionId) {
5767
5767
  const global = dbPath === "globalStorage/state.vscdb";
@@ -5801,7 +5801,7 @@ function freezeSourceReadOptions(options = {}) {
5801
5801
  });
5802
5802
  }
5803
5803
  function getDefaultBackupDir() {
5804
- return join8(homedir10(), "cursor-history-backups");
5804
+ return join8(homedir11(), "cursor-history-backups");
5805
5805
  }
5806
5806
  function computeChecksum(buffer) {
5807
5807
  return `sha256:${createHash4("sha256").update(buffer).digest("hex")}`;
@@ -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 stat9 = statSync3(globalDbPath);
5824
+ const stat12 = statSync3(globalDbPath);
5825
5825
  files.push({
5826
5826
  absolutePath: globalDbPath,
5827
5827
  relativePath: "globalStorage/state.vscdb",
5828
- size: stat9.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 stat9 = 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: stat9.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 stat9 = 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: stat9.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(path16) {
6078
+ function syncParentDirectory(path19) {
6079
6079
  if (process.platform === "win32")
6080
6080
  return;
6081
6081
  let descriptor;
6082
6082
  try {
6083
- descriptor = openSync3(dirname4(path16), 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(path16) {
6092
6092
  }
6093
6093
  }
6094
6094
  }
6095
- function removePrivateArchiveStage(path16, operationError) {
6095
+ function removePrivateArchiveStage(path19, operationError) {
6096
6096
  try {
6097
- unlinkSync4(path16);
6097
+ unlinkSync4(path19);
6098
6098
  } catch (error) {
6099
6099
  if (errorCode3(error) === "ENOENT")
6100
6100
  return;
6101
- const cleanupError2 = new TemporaryArtifactCleanupError([path16]);
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((path16) => !unverifiedResidueSet.has(path16));
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 path16 = entry["path"];
6474
- const expectedType = backupEntryTypeForCanonicalPath(path16);
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 = path16.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: ${path16}`);
6480
+ throw new ZipArchiveFormatError(`Backup manifest contains a duplicate restore destination: ${path19}`);
6481
6481
  }
6482
6482
  destinationKeys.add(destinationKey);
6483
6483
  return {
6484
- path: path16,
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(path16) {
6502
- if (path16 === "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(path16);
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: path16 }) => /^workspaceStorage\/([^/]+)\/state\.vscdb$/u.exec(path16)?.[1]).filter((workspaceId) => workspaceId !== void 0).sort(compareCodePoints4);
6524
- const containsGlobalDatabase = files.some(({ type, path: path16 }) => type === "global-db" && path16 === "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: path16 }) => path16 === 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: path16 }) => path16 === 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(path16) {
6791
+ function lstatIfPresent(path19) {
6792
6792
  try {
6793
- return lstatSync5(path16);
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, path16, leafKind) {
6800
+ function assertNoLinkedRestorePath(trustedRoot, path19, leafKind) {
6801
6801
  const absoluteRoot = resolve2(trustedRoot);
6802
- const absolutePath = resolve2(path16);
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 stat9 = statSync3(filePath);
7106
+ const stat12 = statSync3(filePath);
7107
7107
  const info = {
7108
7108
  filePath,
7109
7109
  filename: entry.name,
7110
- fileSize: stat9.size,
7111
- modifiedAt: stat9.mtime
7110
+ fileSize: stat12.size,
7111
+ modifiedAt: stat12.mtime
7112
7112
  };
7113
7113
  try {
7114
7114
  const manifest = await readBackupManifest(filePath, readOptions);
@@ -7132,7 +7132,7 @@ async function listBackups(directory, options = {}) {
7132
7132
  return backups;
7133
7133
  }
7134
7134
  function getDefaultCursorDataPath2() {
7135
- const home = homedir10();
7135
+ const home = homedir11();
7136
7136
  switch (process.platform) {
7137
7137
  case "win32":
7138
7138
  return join8(process.env["APPDATA"] ?? join8(home, "AppData", "Roaming"), "Cursor", "User", "workspaceStorage");
@@ -7761,11 +7761,11 @@ function attachErrorCause(error, cause) {
7761
7761
  });
7762
7762
  }
7763
7763
  }
7764
- async function parseStoreDb(path16, 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(path16, 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(path16, 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(path16, 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(path16, options = {}) {
7824
7824
  operationError = error;
7825
7825
  else {
7826
7826
  options.onDiagnostic?.(error);
7827
- debugLogStorage(`store.db defensive parse failed for ${path16}: ${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 ${path16}: ${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(path16, options = {}) {
7854
7854
  throw operationError;
7855
7855
  return result;
7856
7856
  }
7857
- function pathExists(path16, 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(path16, signal, io, logicalSessionId) {
7867
7867
  ...logicalSessionId ? { logicalSessionId } : {}
7868
7868
  });
7869
7869
  }
7870
- statSync4(path16);
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, path16) {
8839
- return `${representation}\0${path16}`;
8838
+ function occurrenceKey(representation, path19) {
8839
+ return `${representation}\0${path19}`;
8840
8840
  }
8841
- function occurrence(logicalSessionId, representation, path16, workspacePath) {
8841
+ function occurrence(logicalSessionId, representation, path19, workspacePath) {
8842
8842
  return {
8843
- instanceKey: occurrenceKey(representation, path16),
8843
+ instanceKey: occurrenceKey(representation, path19),
8844
8844
  logicalSessionId,
8845
8845
  representation,
8846
- path: path16,
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: path16 }) => path16 === 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: path16 }) => path16 === 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: path16 }) => path16 === 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: path16 }) => path16 === 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: path16 }) => path16 === 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(path16, 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(path16);
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(path16, 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(path16);
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: path16 }) => type === "global-db" && path16 === "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 path16 = normalizeWorkspacePath(candidate.workspace.path);
12717
- counts2.set(path16, (counts2.get(path16) ?? 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: path16 }) => path16),
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: path16 }) => !workspaceFilterMatches(path16, 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 path16 = 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 (path16)
14972
- lines2.push(`Path: ${path16}`);
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(path16, sourcePrefix, destPrefix) {
15477
+ function transformPath(path19, sourcePrefix, destPrefix) {
15478
15478
  const normalizedSource = sourcePrefix.replace(/\/+$/, "");
15479
- const normalizedPath = path16;
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(path16) {
15596
- const normalized = normalizePath(path16);
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, path16) {
15651
- const normalized = normalizedPathKey(path16);
15652
- if (!existsSync9(path16))
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 stat9 = statSync6(path16);
15656
- return `${label}:${normalized}|dev:${String(stat9.dev)}|ino:${String(stat9.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 path16 = readWorkspaceJson(workspaceDirectory);
15805
- if (!path16 || !pathsEqual(path16, 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(path16),
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 = (path16, 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, '${path16}') 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, '${path16}') 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.5" : "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(path16, options = {}) {
20350
- return fetch(`${BASE_URL}${path16}`, {
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(path16) {
20883
- if (!path16) return "";
20884
- return path16.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(path16) {
20930
+ function readJson(path19) {
20931
20931
  try {
20932
- if (!existsSync2(path16)) return null;
20933
- return JSON.parse(readFileSync2(path16, "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(path16, source, out, seen) {
20939
- const hooks = readJson(path16)?.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(path16) {
21088
+ function readText(path19) {
21089
21089
  try {
21090
- if (!existsSync3(path16)) return null;
21091
- return readFileSync3(path16, "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(path16, parse2) {
21097
- const raw = readText(path16);
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(path16, parse2) {
21102
21102
  return null;
21103
21103
  }
21104
21104
  }
21105
- function readJson2(path16) {
21106
- return readParsed(path16, JSON.parse);
21105
+ function readJson2(path19) {
21106
+ return readParsed(path19, JSON.parse);
21107
21107
  }
21108
- function readYaml(path16) {
21109
- return readParsed(path16, parseYaml);
21108
+ function readYaml(path19) {
21109
+ return readParsed(path19, parseYaml);
21110
21110
  }
21111
- function readToml(path16) {
21112
- return readParsed(path16, 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 path16 = src.replace(/^\.\//, "").replace(/\/+$/, "");
21252
- return { url: mpRepoUrl, path: path16 || 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(path16) {
21289
+ function readJson3(path19) {
21290
21290
  try {
21291
- if (!existsSync4(path16)) return null;
21292
- return JSON.parse(readFileSync4(path16, "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 stat9 = statSync(filePath);
21382
- if (stat9.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 homedir17 } 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
  }
@@ -24796,33 +24796,165 @@ function noteConfiguredMcpServers(agg, serverNames) {
24796
24796
 
24797
24797
  // src/harness/codex/scan.ts
24798
24798
  import { readFileSync as readFileSync6 } from "node:fs";
24799
- import { open, readdir as readdir4, realpath as realpath3, stat as stat4 } from "node:fs/promises";
24800
- import { homedir as homedir7 } from "node:os";
24801
- import path4 from "node:path";
24799
+ import { open, readdir as readdir5, stat as stat5 } from "node:fs/promises";
24800
+ import { homedir as homedir8 } from "node:os";
24801
+ import path5 from "node:path";
24802
24802
  import { Readable } from "node:stream";
24803
24803
  import * as zlib from "node:zlib";
24804
24804
  import { parse as parseToml2 } from "smol-toml";
24805
- function codexHome() {
24806
- return process.env.CODEX_HOME || path4.join(homedir7(), ".codex");
24805
+
24806
+ // src/harness/shared/homes.ts
24807
+ import {
24808
+ mkdir,
24809
+ readdir as readdir4,
24810
+ readFile,
24811
+ realpath as realpath3,
24812
+ stat as stat4,
24813
+ writeFile
24814
+ } from "node:fs/promises";
24815
+ import { homedir as homedir7 } from "node:os";
24816
+ import path4 from "node:path";
24817
+ async function discoverHomes(options) {
24818
+ let complete = true;
24819
+ const resolve3 = async (dir) => {
24820
+ try {
24821
+ const real = await realpath3(dir);
24822
+ return (await stat4(real)).isDirectory() ? real : null;
24823
+ } catch (error) {
24824
+ if (!absent(error)) {
24825
+ complete = false;
24826
+ traceError("harness home resolution", error, "warn");
24827
+ }
24828
+ return null;
24829
+ }
24830
+ };
24831
+ const named = [...options.defaults];
24832
+ for (const { parent, prefix } of options.siblings ?? []) {
24833
+ try {
24834
+ named.push(
24835
+ ...(await readdir4(parent, { withFileTypes: true })).filter(
24836
+ (entry) => entry.name.startsWith(prefix) && (entry.isDirectory() || entry.isSymbolicLink())
24837
+ ).map((entry) => path4.join(parent, entry.name)).sort()
24838
+ );
24839
+ } catch (error) {
24840
+ if (!absent(error)) {
24841
+ complete = false;
24842
+ traceError("harness home discovery", error, "warn");
24843
+ }
24844
+ }
24845
+ }
24846
+ const homes = [];
24847
+ const add = (real) => {
24848
+ if (real && !homes.includes(real)) homes.push(real);
24849
+ };
24850
+ for (const dir of named) add(await resolve3(dir));
24851
+ const found = new Set(homes);
24852
+ const remembered = options.remember ? await readRemembered(options.remember) : [];
24853
+ const fresh = [];
24854
+ for (const dir of (options.configured ?? []).filter((dir2) => Boolean(dir2?.trim())).map(expandHome)) {
24855
+ const real = await resolve3(dir);
24856
+ add(real);
24857
+ if (real && !found.has(real) && !remembered.includes(real))
24858
+ fresh.push(real);
24859
+ }
24860
+ for (const dir of remembered) add(await resolve3(dir));
24861
+ if (options.remember && fresh.length)
24862
+ await writeRemembered(options.remember, [...remembered, ...fresh]);
24863
+ return { homes, complete };
24864
+ }
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
+ }
24886
+ async function readRemembered(harness) {
24887
+ try {
24888
+ const parsed = JSON.parse(await readFile(rememberedFile(), "utf8"));
24889
+ const list = parsed?.[harness];
24890
+ return Array.isArray(list) ? list.filter((dir) => typeof dir === "string") : [];
24891
+ } catch (error) {
24892
+ if (!absent(error)) traceError("remembered harness homes", error, "warn");
24893
+ return [];
24894
+ }
24895
+ }
24896
+ async function writeRemembered(harness, dirs) {
24897
+ const file = rememberedFile();
24898
+ try {
24899
+ let all = {};
24900
+ try {
24901
+ const parsed = JSON.parse(await readFile(file, "utf8"));
24902
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
24903
+ all = parsed;
24904
+ } catch (error) {
24905
+ if (!absent(error)) throw error;
24906
+ }
24907
+ all[harness] = dirs;
24908
+ await mkdir(path4.dirname(file), { recursive: true, mode: 448 });
24909
+ await writeFile(file, `${JSON.stringify(all, null, 2)}
24910
+ `, { mode: 384 });
24911
+ return true;
24912
+ } catch (error) {
24913
+ traceError("remembered harness homes", error, "warn");
24914
+ return false;
24915
+ }
24916
+ }
24917
+ function expandHome(dir) {
24918
+ const trimmed = dir.trim();
24919
+ return path4.resolve(
24920
+ trimmed.startsWith("~/") ? path4.join(homedir7(), trimmed.slice(2)) : trimmed
24921
+ );
24922
+ }
24923
+ function absent(error) {
24924
+ const code2 = error?.code;
24925
+ return code2 === "ENOENT" || code2 === "ENOTDIR";
24926
+ }
24927
+
24928
+ // src/harness/codex/scan.ts
24929
+ async function discoverCodexHomes() {
24930
+ const home = homedir8();
24931
+ return discoverHomes({
24932
+ defaults: [path5.join(home, ".codex")],
24933
+ configured: [process.env.CODEX_HOME],
24934
+ siblings: [{ parent: home, prefix: ".codex" }],
24935
+ remember: "codex"
24936
+ });
24807
24937
  }
24808
- function rolloutRoots() {
24809
- return [path4.join(codexHome(), "sessions")];
24938
+ async function rolloutRoots() {
24939
+ return (await discoverCodexHomes()).homes.map(
24940
+ (home) => path5.join(home, "sessions")
24941
+ );
24810
24942
  }
24811
24943
  var ROLLOUT_RE = /^rollout-.*\.jsonl(\.zst)?$/;
24812
- function isRolloutFile(basename5) {
24813
- return ROLLOUT_RE.test(basename5);
24944
+ function isRolloutFile(basename6) {
24945
+ return ROLLOUT_RE.test(basename6);
24814
24946
  }
24815
24947
  async function* walkRollouts(dir) {
24816
24948
  let entries;
24817
24949
  try {
24818
- entries = await readdir4(dir, { withFileTypes: true });
24950
+ entries = await readdir5(dir, { withFileTypes: true });
24819
24951
  } catch (error) {
24820
24952
  if (error?.code !== "ENOENT")
24821
24953
  traceError("codex rollout discovery", error, "warn");
24822
24954
  return;
24823
24955
  }
24824
24956
  for (const e of entries) {
24825
- const full = path4.join(dir, e.name);
24957
+ const full = path5.join(dir, e.name);
24826
24958
  if (e.isDirectory()) yield* walkRollouts(full);
24827
24959
  else if (e.isFile() && isRolloutFile(e.name)) yield full;
24828
24960
  }
@@ -24840,76 +24972,76 @@ async function scanWindows(windows, opts = {}) {
24840
24972
  ...window,
24841
24973
  stats: emptyScanStats()
24842
24974
  }));
24843
- const visited = /* @__PURE__ */ new Set();
24844
- for (const root of opts.roots ?? rolloutRoots()) {
24975
+ const discovery = opts.roots ? { homes: [], complete: true } : await discoverCodexHomes();
24976
+ for (const { stats } of targets)
24977
+ stats.sourceDiscoveryComplete = discovery.complete;
24978
+ const roots = opts.roots ?? discovery.homes.map((home) => path5.join(home, "sessions"));
24979
+ const chosen = /* @__PURE__ */ new Map();
24980
+ for (const root of roots) {
24845
24981
  if (!await exists2(root)) continue;
24846
24982
  for await (const file of walkRollouts(root)) {
24847
24983
  for (const { stats } of targets) stats.filesFound++;
24848
- let resolved;
24984
+ let size = -1;
24985
+ let mtimeMs;
24849
24986
  try {
24850
- resolved = await realpath3(file);
24987
+ const st = await stat5(file);
24988
+ size = st.size;
24989
+ mtimeMs = st.mtimeMs;
24851
24990
  } catch (error) {
24852
24991
  if (error?.code !== "ENOENT")
24853
- traceError("codex rollout path resolution", error, "warn");
24854
- resolved = file;
24992
+ traceError("codex rollout stat", error, "warn");
24855
24993
  }
24856
- const dedupKey = resolved.endsWith(".zst") ? resolved.slice(0, -4) : resolved;
24857
- if (visited.has(dedupKey)) {
24994
+ const key2 = path5.basename(file).replace(/\.zst$/, "");
24995
+ const held = chosen.get(key2);
24996
+ if (held) {
24858
24997
  for (const { stats } of targets) stats.filesSkippedAsDuplicate++;
24859
- continue;
24998
+ if (size <= held.size) continue;
24860
24999
  }
24861
- visited.add(dedupKey);
24862
- let mtimeMs;
24863
- if (targets.some((target) => target.sinceMs !== void 0)) {
24864
- try {
24865
- mtimeMs = (await stat4(file)).mtimeMs;
24866
- } catch (error) {
24867
- if (error?.code !== "ENOENT")
24868
- traceError("codex rollout stat", error, "warn");
24869
- }
24870
- }
24871
- const eligible = targets.filter((target) => {
24872
- if (mtimeMs !== void 0 && target.sinceMs !== void 0 && mtimeMs < target.sinceMs) {
24873
- target.stats.filesSkippedByMtime++;
24874
- return false;
24875
- }
24876
- return true;
24877
- });
24878
- if (!eligible.length) continue;
24879
- for (const { aggregate, stats, onProgress } of eligible) {
24880
- aggregate.files++;
24881
- stats.filesRead++;
24882
- if (aggregate.files % 20 === 0) onProgress?.(aggregate.files);
25000
+ chosen.set(key2, { root, file, size, mtimeMs });
25001
+ }
25002
+ }
25003
+ for (const { root, file, mtimeMs } of chosen.values()) {
25004
+ const eligible = targets.filter((target) => {
25005
+ if (mtimeMs !== void 0 && target.sinceMs !== void 0 && mtimeMs < target.sinceMs) {
25006
+ target.stats.filesSkippedByMtime++;
25007
+ return false;
24883
25008
  }
24884
- const outcome = await ingestWithRetry(eligible, file, opts);
24885
- for (const { stats } of eligible) {
24886
- if (!outcome.ok) {
24887
- stats.filesUnreadable++;
24888
- stats.filesRead--;
24889
- if (outcome.reason === "zstd-unsupported")
24890
- stats.filesZstdUnsupported++;
24891
- stats.unreadableFiles.push({
24892
- path: path4.relative(root, file),
24893
- reason: outcome.reason
24894
- });
24895
- } else if (!outcome.genuine) {
24896
- stats.filesForeign++;
24897
- stats.filesRead--;
24898
- stats.foreignOriginators.set(
24899
- outcome.originator,
24900
- (stats.foreignOriginators.get(outcome.originator) ?? 0) + 1
24901
- );
24902
- }
25009
+ return true;
25010
+ });
25011
+ if (!eligible.length) continue;
25012
+ for (const { aggregate, stats, onProgress } of eligible) {
25013
+ aggregate.files++;
25014
+ stats.filesRead++;
25015
+ if (aggregate.files % 20 === 0) onProgress?.(aggregate.files);
25016
+ }
25017
+ const outcome = await ingestWithRetry(eligible, file, opts);
25018
+ for (const { stats } of eligible) {
25019
+ if (!outcome.ok) {
25020
+ stats.filesUnreadable++;
25021
+ stats.filesRead--;
25022
+ if (outcome.reason === "zstd-unsupported") stats.filesZstdUnsupported++;
25023
+ stats.unreadableFiles.push({
25024
+ path: path5.relative(root, file),
25025
+ reason: outcome.reason
25026
+ });
25027
+ } else if (!outcome.genuine) {
25028
+ stats.filesForeign++;
25029
+ stats.filesRead--;
25030
+ stats.foreignOriginators.set(
25031
+ outcome.originator,
25032
+ (stats.foreignOriginators.get(outcome.originator) ?? 0) + 1
25033
+ );
24903
25034
  }
24904
25035
  }
24905
25036
  }
25037
+ const configFiles = opts.configFile ? [opts.configFile] : discovery.homes.map((home) => path5.join(home, "config.toml"));
24906
25038
  for (const { aggregate } of targets)
24907
- readConfiguredMcpServers(aggregate, opts.configFile);
25039
+ for (const file of configFiles) readConfiguredMcpServers(aggregate, file);
24908
25040
  return targets.map((target) => target.stats);
24909
25041
  }
24910
25042
  async function exists2(p8) {
24911
25043
  try {
24912
- await stat4(p8);
25044
+ await stat5(p8);
24913
25045
  return true;
24914
25046
  } catch (error) {
24915
25047
  if (error?.code !== "ENOENT")
@@ -24918,8 +25050,8 @@ async function exists2(p8) {
24918
25050
  }
24919
25051
  }
24920
25052
  function errorClass(e) {
24921
- const code = e?.code;
24922
- if (typeof code === "string" && code.length > 0) return code;
25053
+ const code2 = e?.code;
25054
+ if (typeof code2 === "string" && code2.length > 0) return code2;
24923
25055
  return e instanceof Error ? e.constructor.name : "unknown";
24924
25056
  }
24925
25057
  var readError = (reason) => Object.assign(new Error(reason), { code: reason });
@@ -25080,8 +25212,7 @@ async function classifyRollout(records) {
25080
25212
  if (genuine) return { genuine: true };
25081
25213
  return { genuine: false, originator: originator ?? "(none)" };
25082
25214
  }
25083
- function readConfiguredMcpServers(agg, configFile) {
25084
- const file = configFile ?? path4.join(codexHome(), "config.toml");
25215
+ function readConfiguredMcpServers(agg, file) {
25085
25216
  let names = [];
25086
25217
  try {
25087
25218
  const parsed = parseToml2(readFileSync6(file, "utf8"));
@@ -25121,7 +25252,7 @@ var codexAdapter = {
25121
25252
  builtinTools: CODEX_BUILTIN_TOOLS,
25122
25253
  async detect(opts) {
25123
25254
  return hasRecentFile(
25124
- opts.roots ?? rolloutRoots(),
25255
+ opts.roots ?? await rolloutRoots(),
25125
25256
  isRolloutFile,
25126
25257
  opts.sinceMs
25127
25258
  );
@@ -25135,6 +25266,7 @@ var codexAdapter = {
25135
25266
  return {
25136
25267
  aggregate,
25137
25268
  stats,
25269
+ scanComplete: stats.sourceDiscoveryComplete !== false,
25138
25270
  workflow: aggregate.workflow.finish(),
25139
25271
  workflowLocal: aggregate.workflowLocal
25140
25272
  };
@@ -25149,6 +25281,7 @@ var codexAdapter = {
25149
25281
  return windows.map(({ aggregate }, index) => ({
25150
25282
  aggregate,
25151
25283
  stats: stats[index],
25284
+ scanComplete: stats[index].sourceDiscoveryComplete !== false,
25152
25285
  workflow: aggregate.workflow.finish(),
25153
25286
  workflowLocal: aggregate.workflowLocal
25154
25287
  }));
@@ -25156,9 +25289,9 @@ var codexAdapter = {
25156
25289
  };
25157
25290
 
25158
25291
  // src/harness/cursor/cache.ts
25159
- import { mkdir as mkdir2, readFile as readFile2, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
25160
- import { homedir as homedir12 } from "node:os";
25161
- import path7 from "node:path";
25292
+ import { mkdir as mkdir3, readFile as readFile3, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
25293
+ import { homedir as homedir13 } from "node:os";
25294
+ import path8 from "node:path";
25162
25295
 
25163
25296
  // src/harness/cursor/account.ts
25164
25297
  import { createHash as createHash7 } from "node:crypto";
@@ -25371,9 +25504,9 @@ function reconcile(local, api) {
25371
25504
 
25372
25505
  // src/harness/cursor/local.ts
25373
25506
  import { existsSync as existsSync10 } from "node:fs";
25374
- import { stat as stat5 } from "node:fs/promises";
25375
- import { homedir as homedir11 } from "node:os";
25376
- import path6 from "node:path";
25507
+ import { stat as stat6 } from "node:fs/promises";
25508
+ import { homedir as homedir12 } from "node:os";
25509
+ import path7 from "node:path";
25377
25510
  import { Worker } from "node:worker_threads";
25378
25511
 
25379
25512
  // src/harness/cursor/composer.ts
@@ -25576,13 +25709,13 @@ function hasComposerHalf(summary) {
25576
25709
  }
25577
25710
 
25578
25711
  // src/harness/cursor/sessionCache.ts
25579
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
25580
- import { homedir as homedir8 } from "node:os";
25581
- import path5 from "node:path";
25712
+ import { mkdir as mkdir2, readFile as readFile2, rename, writeFile as writeFile2 } from "node:fs/promises";
25713
+ import { homedir as homedir9 } from "node:os";
25714
+ import path6 from "node:path";
25582
25715
  import { gunzipSync, gzipSync } from "node:zlib";
25583
25716
  var SESSION_CACHE_FORMAT = 1;
25584
- var defaultSessionCacheDir = () => path5.join(homedir8(), ".config", "aistack", "cursor");
25585
- var sessionCacheFile = (dir, root, store) => path5.join(dir, `${digest(`${root}\0${store}`)}.sessions.json.gz`);
25717
+ var defaultSessionCacheDir = () => path6.join(homedir9(), ".config", "aistack", "cursor");
25718
+ var sessionCacheFile = (dir, root, store) => path6.join(dir, `${digest(`${root}\0${store}`)}.sessions.json.gz`);
25586
25719
  function sessionStamp(summary, newest) {
25587
25720
  if (newest === null) return null;
25588
25721
  const count2 = summary.messageCount;
@@ -25622,7 +25755,7 @@ async function loadSessionCache(file) {
25622
25755
  const out = /* @__PURE__ */ new Map();
25623
25756
  let raw;
25624
25757
  try {
25625
- raw = gunzipSync(await readFile(file)).toString("utf8");
25758
+ raw = gunzipSync(await readFile2(file)).toString("utf8");
25626
25759
  } catch (error) {
25627
25760
  if (error.code !== "ENOENT")
25628
25761
  traceError("cursor session cache read", error, "warn");
@@ -25642,7 +25775,7 @@ async function loadSessionCache(file) {
25642
25775
  return out;
25643
25776
  }
25644
25777
  async function saveSessionCache(file, cache) {
25645
- await mkdir(path5.dirname(file), { recursive: true, mode: 448 });
25778
+ await mkdir2(path6.dirname(file), { recursive: true, mode: 448 });
25646
25779
  const body = gzipSync(
25647
25780
  JSON.stringify({
25648
25781
  format: SESSION_CACHE_FORMAT,
@@ -25650,21 +25783,21 @@ async function saveSessionCache(file, cache) {
25650
25783
  })
25651
25784
  );
25652
25785
  const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
25653
- await writeFile(temporary, body, { mode: 384 });
25786
+ await writeFile2(temporary, body, { mode: 384 });
25654
25787
  await rename(temporary, file);
25655
25788
  }
25656
25789
 
25657
25790
  // src/harness/cursor/local.ts
25658
- function dataPath(env = process.env, home = homedir11(), platform4 = process.platform) {
25659
- if (env.CURSOR_DATA_PATH) return path6.resolve(env.CURSOR_DATA_PATH);
25660
- const base = platform4 === "darwin" ? path6.join(home, "Library", "Application Support") : platform4 === "win32" ? env.APPDATA || path6.join(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME || path6.join(home, ".config");
25661
- return path6.join(base, "Cursor", "User", "workspaceStorage");
25791
+ function dataPath(env = process.env, home = homedir12(), platform4 = process.platform) {
25792
+ if (env.CURSOR_DATA_PATH) return path7.resolve(env.CURSOR_DATA_PATH);
25793
+ const base = platform4 === "darwin" ? path7.join(home, "Library", "Application Support") : platform4 === "win32" ? env.APPDATA || path7.join(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME || path7.join(home, ".config");
25794
+ return path7.join(base, "Cursor", "User", "workspaceStorage");
25662
25795
  }
25663
- var storeRoot = () => process.env.CURSOR_STORE_ROOT || path6.join(homedir11(), ".cursor");
25664
- var globalDb = (root) => path6.join(path6.dirname(root), "globalStorage", "state.vscdb");
25796
+ var storeRoot = () => process.env.CURSOR_STORE_ROOT || path7.join(homedir12(), ".cursor");
25797
+ var globalDb = (root) => path7.join(path7.dirname(root), "globalStorage", "state.vscdb");
25665
25798
  async function exists3(file) {
25666
25799
  try {
25667
- await stat5(file);
25800
+ await stat6(file);
25668
25801
  return true;
25669
25802
  } catch (error) {
25670
25803
  return error.code !== "ENOENT";
@@ -25675,9 +25808,9 @@ async function hasLocalSource(root = dataPath()) {
25675
25808
  [
25676
25809
  root,
25677
25810
  globalDb(root),
25678
- path6.join(storeRoot(), "projects"),
25679
- path6.join(storeRoot(), "chats"),
25680
- path6.join(storeRoot(), "acp-sessions")
25811
+ path7.join(storeRoot(), "projects"),
25812
+ path7.join(storeRoot(), "chats"),
25813
+ path7.join(storeRoot(), "acp-sessions")
25681
25814
  ].map(exists3)
25682
25815
  )).some(Boolean);
25683
25816
  }
@@ -25749,7 +25882,7 @@ async function sourceStamp(root) {
25749
25882
  const values = await Promise.all(
25750
25883
  [globalDb(root), `${globalDb(root)}-wal`].map(async (file) => {
25751
25884
  try {
25752
- const info = await stat5(file);
25885
+ const info = await stat6(file);
25753
25886
  return `${info.size}:${info.mtimeMs}`;
25754
25887
  } catch {
25755
25888
  return "unavailable";
@@ -25848,10 +25981,10 @@ async function readLocalOffThread(root, before, onProgress) {
25848
25981
  else fallback();
25849
25982
  })
25850
25983
  );
25851
- worker.on("exit", (code) => {
25852
- if (code !== 0)
25984
+ worker.on("exit", (code2) => {
25985
+ if (code2 !== 0)
25853
25986
  settle(() => {
25854
- trace(`cursor worker exited \xB7 code=${code}; reading inline`, "warn");
25987
+ trace(`cursor worker exited \xB7 code=${code2}; reading inline`, "warn");
25855
25988
  fallback();
25856
25989
  });
25857
25990
  });
@@ -26017,9 +26150,9 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits, stallMs
26017
26150
  onProgress?.(stats.filesRead + stats.filesSkippedByMtime, total);
26018
26151
  } catch (error) {
26019
26152
  if (signal.aborted || isPageByteLimit(error)) throw error;
26020
- const code = traceErrorCode(error);
26021
- if (code === "SESSION_AMBIGUOUS") ambiguous++;
26022
- 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++;
26023
26156
  else traceError(`cursor ${stage}`, error, "warn");
26024
26157
  out.complete = false;
26025
26158
  stats.filesUnreadable++;
@@ -26138,7 +26271,7 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits, stallMs
26138
26271
  }
26139
26272
  async function globalDbSize(root) {
26140
26273
  try {
26141
- const info = await stat5(globalDb(root));
26274
+ const info = await stat6(globalDb(root));
26142
26275
  return `${(info.size / 1048576).toFixed(0)} MB`;
26143
26276
  } catch {
26144
26277
  return "absent";
@@ -26339,8 +26472,8 @@ var emptyCache = () => ({
26339
26472
  local: [],
26340
26473
  sessions: []
26341
26474
  });
26342
- var cacheFile = (root, store) => path7.join(
26343
- homedir12(),
26475
+ var cacheFile = (root, store) => path8.join(
26476
+ homedir13(),
26344
26477
  ".config",
26345
26478
  "aistack",
26346
26479
  "cursor",
@@ -26355,7 +26488,7 @@ function validContribution(value) {
26355
26488
  }
26356
26489
  async function loadCache(file) {
26357
26490
  try {
26358
- const raw = asObj(JSON.parse(await readFile2(file, "utf8")));
26491
+ const raw = asObj(JSON.parse(await readFile3(file, "utf8")));
26359
26492
  const windows = asObj(raw?.windows);
26360
26493
  if (raw?.version !== 1 || !(raw.account === null || typeof raw.account === "string") || !Array.isArray(raw.sessions) || !raw.sessions.every((id) => typeof id === "string") || !Array.isArray(raw.local) || !raw.local.every(validContribution) || !windows)
26361
26494
  throw Object.assign(new Error("Invalid cache"), {
@@ -26379,9 +26512,9 @@ async function loadCache(file) {
26379
26512
  }
26380
26513
  }
26381
26514
  async function saveCache(file, value) {
26382
- await mkdir2(path7.dirname(file), { recursive: true, mode: 448 });
26515
+ await mkdir3(path8.dirname(file), { recursive: true, mode: 448 });
26383
26516
  const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
26384
- await writeFile2(temporary, JSON.stringify(value), { mode: 384 });
26517
+ await writeFile3(temporary, JSON.stringify(value), { mode: 384 });
26385
26518
  await rename2(temporary, file);
26386
26519
  }
26387
26520
  var REFRESH_MS = 3e5;
@@ -26434,11 +26567,105 @@ function cachedEvents(cache, sessionIds) {
26434
26567
  });
26435
26568
  }
26436
26569
 
26437
- // src/harness/cursor/scan.ts
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";
26438
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
+
26664
+ // src/harness/cursor/scan.ts
26665
+ import path11 from "node:path";
26439
26666
 
26440
26667
  // src/harness/cursor/workflow.ts
26441
- import path8 from "node:path";
26668
+ import path10 from "node:path";
26442
26669
  var TOOLS = {
26443
26670
  read_file: "Read",
26444
26671
  read_file_v2: "Read",
@@ -26479,7 +26706,7 @@ function projectHistory(options) {
26479
26706
  const scopes = /* @__PURE__ */ new Map();
26480
26707
  const inWindow = (t) => t !== null && t >= sinceMs && t <= now;
26481
26708
  for (const { session } of locals) {
26482
- const projectWorkspace = session.canonicalWorkspacePath && path8.isAbsolute(session.canonicalWorkspacePath) ? session.canonicalWorkspacePath : void 0;
26709
+ const projectWorkspace = session.canonicalWorkspacePath && path10.isAbsolute(session.canonicalWorkspacePath) ? session.canonicalWorkspacePath : void 0;
26483
26710
  const times = messageTimes(session, api);
26484
26711
  const scopeOf = (message) => {
26485
26712
  const parent = message.parentMessageId && nativeOwners.get(message.parentMessageId);
@@ -26566,7 +26793,7 @@ function projectHistory(options) {
26566
26793
  session: row.sidechain ? `${row.session}:sidechain` : row.session,
26567
26794
  sidechain: row.sidechain
26568
26795
  },
26569
- ...project && path8.isAbsolute(project) ? { projectWorkspace: project } : {},
26796
+ ...project && path10.isAbsolute(project) ? { projectWorkspace: project } : {},
26570
26797
  type: "response",
26571
26798
  tsMs: row.tsMs,
26572
26799
  responseId: `${row.source}:${row.id ?? index}`,
@@ -26578,14 +26805,9 @@ function projectHistory(options) {
26578
26805
 
26579
26806
  // src/harness/cursor/scan.ts
26580
26807
  var accountRefreshes = /* @__PURE__ */ new Map();
26581
- async function scan3(options) {
26582
- const root = options.root ?? dataPath();
26583
- const now = options.now ?? Date.now();
26584
- const file = options.cachePath ?? cacheFile(root, storeRoot());
26585
- const local = await (options.readLocalImpl ?? readLocal)(
26586
- root,
26587
- options.onProgress
26588
- );
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);
26589
26811
  const loaded = await loadCache(file);
26590
26812
  let complete = local.complete && loaded.complete;
26591
26813
  const ids = new Set(local.sessions.map((s) => s.session.id));
@@ -26616,14 +26838,11 @@ async function scan3(options) {
26616
26838
  state: refreshState
26617
26839
  });
26618
26840
  const api = cachedEvents(cache, ids);
26619
- const native = /* @__PURE__ */ new Set();
26620
- const contributions = local.sessions.flatMap((s) => localContributions(s, api)).filter((row) => {
26621
- if (!row.nativeId) return true;
26622
- if (native.has(row.nativeId)) return false;
26623
- native.add(row.nativeId);
26624
- return true;
26625
- });
26626
- 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));
26627
26846
  if (loaded.value.local.some(
26628
26847
  (row) => row.tsMs >= options.sinceMs && !dated.has(row.session)
26629
26848
  )) {
@@ -26633,17 +26852,8 @@ async function scan3(options) {
26633
26852
  );
26634
26853
  complete = false;
26635
26854
  }
26636
- const previousDates = /* @__PURE__ */ new Map();
26637
- for (const row of [
26638
- ...loaded.value.local,
26639
- ...cachedEvents(loaded.value, ids)
26640
- ]) {
26641
- const dates = previousDates.get(row.session) ?? /* @__PURE__ */ new Set();
26642
- dates.add(utcDateOf(row.tsMs));
26643
- previousDates.set(row.session, dates);
26644
- }
26645
26855
  if (complete) {
26646
- cache.local = contributions;
26856
+ cache.local = deduped;
26647
26857
  cache.sessions = [...ids].sort();
26648
26858
  try {
26649
26859
  await saveCache(file, cache);
@@ -26652,6 +26862,102 @@ async function scan3(options) {
26652
26862
  complete = false;
26653
26863
  }
26654
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
+ );
26655
26961
  const aggregate = createAggregate();
26656
26962
  const workflowLocal = createWorkflowLocalSources();
26657
26963
  const workflow = createHarnessWorkflowReducer("cursor", workflowLocal);
@@ -26665,7 +26971,7 @@ async function scan3(options) {
26665
26971
  aggregate.byModel.set(model, emptyUsage());
26666
26972
  }
26667
26973
  const project = session.canonicalWorkspacePath;
26668
- if (project && path9.isAbsolute(project)) aggregate.projectDirs.add(project);
26974
+ if (project && path11.isAbsolute(project)) aggregate.projectDirs.add(project);
26669
26975
  if (session.metadata?.cursorVersion)
26670
26976
  aggregate.ccVersions.add(session.metadata.cursorVersion);
26671
26977
  let firstTime = null;
@@ -26722,7 +27028,7 @@ async function scan3(options) {
26722
27028
  else aggregate.mainTokens += countsTotal(counts2);
26723
27029
  noteSessionStart(aggregate, session, tsMs);
26724
27030
  const project = sessions.get(session)?.session.canonicalWorkspacePath;
26725
- if (project && path9.isAbsolute(project))
27031
+ if (project && path11.isAbsolute(project))
26726
27032
  noteProjectDay(aggregate, project, tsMs);
26727
27033
  }
26728
27034
  aggregate.files = local.stats.filesRead;
@@ -26742,7 +27048,9 @@ var cursorAdapter = {
26742
27048
  name: CURSOR_HARNESS_NAME,
26743
27049
  builtinTools: CURSOR_BUILTIN_TOOLS,
26744
27050
  async detect(options) {
26745
- 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;
26746
27054
  for (const root of roots) {
26747
27055
  const held = await loadCache(cacheFile(root, storeRoot()));
26748
27056
  if (!held.complete || [
@@ -27009,17 +27317,17 @@ function ingestContribution(agg, row) {
27009
27317
 
27010
27318
  // src/harness/grok/scan.ts
27011
27319
  import { createReadStream as createReadStream2 } from "node:fs";
27012
- import { readdir as readdir6, readFile as readFile4, stat as stat6 } from "node:fs/promises";
27013
- import { homedir as homedir14 } from "node:os";
27014
- import path11 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";
27015
27323
  import readline2 from "node:readline";
27016
27324
  import { parse as parseToml3 } from "smol-toml";
27017
27325
 
27018
27326
  // src/harness/grok/context.ts
27019
27327
  import { createHash as createHash8 } from "node:crypto";
27020
- import { appendFile, mkdir as mkdir3, readdir as readdir5, readFile as readFile3, unlink as unlink2 } from "node:fs/promises";
27021
- import { homedir as homedir13 } from "node:os";
27022
- import path10 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";
27023
27331
  var DAY_MS = 864e5;
27024
27332
  var hash = (value) => createHash8("sha256").update(value).digest("hex");
27025
27333
  function contextCall(value) {
@@ -27042,17 +27350,17 @@ function contextCall(value) {
27042
27350
  };
27043
27351
  }
27044
27352
  function contextCacheDirectory(root) {
27045
- return path10.join(
27046
- homedir13(),
27353
+ return path12.join(
27354
+ homedir15(),
27047
27355
  ".config",
27048
27356
  "aistack",
27049
27357
  "grok-context",
27050
- hash(path10.resolve(root))
27358
+ hash(path12.resolve(root))
27051
27359
  );
27052
27360
  }
27053
27361
  async function optionalRead(file) {
27054
27362
  try {
27055
- return await readFile3(file, "utf8");
27363
+ return await readFile5(file, "utf8");
27056
27364
  } catch (error) {
27057
27365
  if (error.code === "ENOENT") return "";
27058
27366
  throw error;
@@ -27063,21 +27371,21 @@ async function retainedContextCalls(root, sessions, cacheDir = contextCacheDirec
27063
27371
  const calls = /* @__PURE__ */ new Map();
27064
27372
  let files = [];
27065
27373
  try {
27066
- files = await readdir5(cacheDir);
27374
+ files = await readdir7(cacheDir);
27067
27375
  } catch (error) {
27068
27376
  if (error.code !== "ENOENT") throw error;
27069
27377
  }
27070
27378
  for (const file of files) {
27071
27379
  if (!/^\d{4}-\d{2}-\d{2}\.jsonl$/.test(file)) continue;
27072
27380
  if (Date.parse(file.slice(0, 10)) + DAY_MS < cutoff) {
27073
- await unlink2(path10.join(cacheDir, file)).catch(
27381
+ await unlink2(path12.join(cacheDir, file)).catch(
27074
27382
  (error) => {
27075
27383
  if (error.code !== "ENOENT") throw error;
27076
27384
  }
27077
27385
  );
27078
27386
  continue;
27079
27387
  }
27080
- const raw2 = await optionalRead(path10.join(cacheDir, file));
27388
+ const raw2 = await optionalRead(path12.join(cacheDir, file));
27081
27389
  if (raw2 && !raw2.endsWith("\n"))
27082
27390
  throw Object.assign(new Error("Incomplete Grok context cache"), {
27083
27391
  code: "GROK_INCOMPLETE_CONTEXT_CACHE"
@@ -27098,7 +27406,7 @@ async function retainedContextCalls(root, sessions, cacheDir = contextCacheDirec
27098
27406
  }
27099
27407
  }
27100
27408
  const raw = await optionalRead(
27101
- path10.join(root, "..", "logs", "unified.jsonl")
27409
+ path12.join(root, "..", "logs", "unified.jsonl")
27102
27410
  );
27103
27411
  const additions = /* @__PURE__ */ new Map();
27104
27412
  for (const line of raw.slice(0, raw.lastIndexOf("\n") + 1).split("\n")) {
@@ -27118,10 +27426,10 @@ async function retainedContextCalls(root, sessions, cacheDir = contextCacheDirec
27118
27426
  additions.set(date, lines2);
27119
27427
  }
27120
27428
  if (additions.size) {
27121
- await mkdir3(cacheDir, { recursive: true, mode: 448 });
27429
+ await mkdir4(cacheDir, { recursive: true, mode: 448 });
27122
27430
  for (const [date, lines2] of additions) {
27123
27431
  await appendFile(
27124
- path10.join(cacheDir, `${date}.jsonl`),
27432
+ path12.join(cacheDir, `${date}.jsonl`),
27125
27433
  `${lines2.join("\n")}
27126
27434
  `,
27127
27435
  { mode: 384 }
@@ -27132,13 +27440,31 @@ async function retainedContextCalls(root, sessions, cacheDir = contextCacheDirec
27132
27440
  }
27133
27441
 
27134
27442
  // src/harness/grok/scan.ts
27135
- function sessionRoots() {
27136
- return [
27137
- path11.join(
27138
- process.env.GROK_HOME || path11.join(homedir14(), ".grok"),
27139
- "sessions"
27140
- )
27141
- ];
27443
+ async function discoverGrokHomes() {
27444
+ const home = homedir16();
27445
+ return discoverHomes({
27446
+ defaults: [path13.join(home, ".grok")],
27447
+ configured: [process.env.GROK_HOME],
27448
+ siblings: [{ parent: home, prefix: ".grok" }],
27449
+ remember: "grok-build"
27450
+ });
27451
+ }
27452
+ async function sessionRoots() {
27453
+ return (await discoverGrokHomes()).homes.map(
27454
+ (home) => path13.join(home, "sessions")
27455
+ );
27456
+ }
27457
+ async function evidenceBytes(dir) {
27458
+ let total = 0;
27459
+ for (const name of ["usage.json", "updates.jsonl", "events.jsonl"]) {
27460
+ try {
27461
+ total += (await stat8(path13.join(dir, name))).size;
27462
+ } catch (error) {
27463
+ if (error?.code !== "ENOENT")
27464
+ traceError("grok evidence stat", error, "warn");
27465
+ }
27466
+ }
27467
+ return total;
27142
27468
  }
27143
27469
  var isGrokEvidenceFile = (name) => name === "usage.json" || name === "updates.jsonl" || name === "events.jsonl";
27144
27470
  var delays = [0, 100, 300];
@@ -27147,7 +27473,7 @@ async function stableRead(file, jsonl) {
27147
27473
  for (const delay of delays) {
27148
27474
  if (delay) await pause(delay);
27149
27475
  try {
27150
- const before = await stat6(file);
27476
+ const before = await stat8(file);
27151
27477
  if (!before.isFile()) return { complete: false };
27152
27478
  if (jsonl) {
27153
27479
  const lines2 = [];
@@ -27165,12 +27491,12 @@ async function stableRead(file, jsonl) {
27165
27491
  lines2.push(null);
27166
27492
  }
27167
27493
  }
27168
- const after = await stat6(file);
27494
+ const after = await stat8(file);
27169
27495
  if (before.size === after.size && before.mtimeMs === after.mtimeMs)
27170
27496
  return { lines: lines2, complete: true };
27171
27497
  } else {
27172
- const raw = await readFile4(file, "utf8");
27173
- const after = await stat6(file);
27498
+ const raw = await readFile6(file, "utf8");
27499
+ const after = await stat8(file);
27174
27500
  if (before.size === after.size && before.mtimeMs === after.mtimeMs)
27175
27501
  return { json: JSON.parse(raw), complete: true };
27176
27502
  }
@@ -27183,16 +27509,16 @@ async function stableRead(file, jsonl) {
27183
27509
  }
27184
27510
  function absoluteCwd(value) {
27185
27511
  const cwd = asStr(value);
27186
- return cwd && path11.isAbsolute(cwd) && !cwd.includes("\0") ? cwd : void 0;
27512
+ return cwd && path13.isAbsolute(cwd) && !cwd.includes("\0") ? cwd : void 0;
27187
27513
  }
27188
27514
  async function workspaceCwd(workspacePath, entries) {
27189
27515
  try {
27190
- const cwd = absoluteCwd(decodeURIComponent(path11.basename(workspacePath)));
27516
+ const cwd = absoluteCwd(decodeURIComponent(path13.basename(workspacePath)));
27191
27517
  if (cwd !== void 0) return cwd;
27192
27518
  } catch {
27193
27519
  }
27194
27520
  if (entries.some((entry) => entry.name === ".cwd" && entry.isFile())) {
27195
- const raw = await readFile4(path11.join(workspacePath, ".cwd"), "utf8").catch(
27521
+ const raw = await readFile6(path13.join(workspacePath, ".cwd"), "utf8").catch(
27196
27522
  () => void 0
27197
27523
  );
27198
27524
  return absoluteCwd(raw);
@@ -27200,18 +27526,18 @@ async function workspaceCwd(workspacePath, entries) {
27200
27526
  }
27201
27527
  async function directories(root) {
27202
27528
  try {
27203
- const workspaces = await readdir6(root, { withFileTypes: true });
27529
+ const workspaces = await readdir8(root, { withFileTypes: true });
27204
27530
  const out = [];
27205
27531
  for (const workspace of workspaces) {
27206
27532
  if (!workspace.isDirectory() || workspace.isSymbolicLink()) continue;
27207
- const workspacePath = path11.join(root, workspace.name);
27208
- const entries = await readdir6(workspacePath, {
27533
+ const workspacePath = path13.join(root, workspace.name);
27534
+ const entries = await readdir8(workspacePath, {
27209
27535
  withFileTypes: true
27210
27536
  });
27211
27537
  const cwd = await workspaceCwd(workspacePath, entries);
27212
27538
  for (const session of entries) {
27213
27539
  if (session.isDirectory() && !session.isSymbolicLink())
27214
- out.push({ dir: path11.join(workspacePath, session.name), cwd });
27540
+ out.push({ dir: path13.join(workspacePath, session.name), cwd });
27215
27541
  }
27216
27542
  }
27217
27543
  return out.sort((a, b) => {
@@ -27228,7 +27554,7 @@ async function modelAliasesForRoot(root) {
27228
27554
  if (process.env.GROK_MODELS_BASE_URL) return /* @__PURE__ */ new Map();
27229
27555
  try {
27230
27556
  const parsed = asObj(
27231
- parseToml3(await readFile4(path11.join(root, "..", "config.toml"), "utf8"))
27557
+ parseToml3(await readFile6(path13.join(root, "..", "config.toml"), "utf8"))
27232
27558
  );
27233
27559
  if (!parsed || asObj(parsed.endpoints)?.models_base_url) return /* @__PURE__ */ new Map();
27234
27560
  const models = asObj(parsed.model);
@@ -27257,19 +27583,37 @@ async function scanWindows2(windows, opts = {}) {
27257
27583
  sessionDates: /* @__PURE__ */ new Map(),
27258
27584
  candidates: /* @__PURE__ */ new Map()
27259
27585
  }));
27260
- let complete = true;
27261
- for (const root of opts.roots ?? sessionRoots()) {
27586
+ const discovery = opts.roots ? { homes: [], complete: true } : await discoverGrokHomes();
27587
+ let complete = discovery.complete;
27588
+ const roots = opts.roots ?? discovery.homes.map((home) => path13.join(home, "sessions"));
27589
+ const listed = /* @__PURE__ */ new Map();
27590
+ const fullest = /* @__PURE__ */ new Map();
27591
+ for (const root of roots) {
27592
+ const dirs = await directories(root);
27593
+ listed.set(root, dirs);
27594
+ for (const { dir } of dirs ?? []) {
27595
+ const key2 = path13.relative(root, dir);
27596
+ const bytes = await evidenceBytes(dir);
27597
+ const held = fullest.get(key2);
27598
+ if (!held || bytes > held.bytes) fullest.set(key2, { dir, bytes });
27599
+ }
27600
+ }
27601
+ for (const root of roots) {
27262
27602
  const aliases = await modelAliasesForRoot(root);
27263
27603
  const contextSessions = /* @__PURE__ */ new Map();
27264
- const dirs = await directories(root);
27265
- if (dirs === null) {
27604
+ const dirs = listed.get(root);
27605
+ if (!dirs) {
27266
27606
  complete = false;
27267
27607
  continue;
27268
27608
  }
27269
27609
  for (const { dir, cwd } of dirs) {
27610
+ if (fullest.get(path13.relative(root, dir))?.dir !== dir) {
27611
+ stats.filesSkippedAsDuplicate++;
27612
+ continue;
27613
+ }
27270
27614
  let entries;
27271
27615
  try {
27272
- entries = await readdir6(dir, { withFileTypes: true });
27616
+ entries = await readdir8(dir, { withFileTypes: true });
27273
27617
  } catch (error) {
27274
27618
  traceError("grok session listing", error);
27275
27619
  complete = false;
@@ -27278,10 +27622,10 @@ async function scanWindows2(windows, opts = {}) {
27278
27622
  const files = new Map(
27279
27623
  entries.filter(
27280
27624
  (e) => e.isFile() && (isGrokEvidenceFile(e.name) || e.name === "summary.json")
27281
- ).map((e) => [e.name, path11.join(dir, e.name)])
27625
+ ).map((e) => [e.name, path13.join(dir, e.name)])
27282
27626
  );
27283
27627
  let projectDir = cwd;
27284
- let sessionFallback = path11.basename(dir);
27628
+ let sessionFallback = path13.basename(dir);
27285
27629
  let child = false;
27286
27630
  let parentSession;
27287
27631
  const summary = files.get("summary.json");
@@ -27453,8 +27797,8 @@ var GROK_BUILTIN_TOOLS = /* @__PURE__ */ new Set([
27453
27797
  var grokAdapter = {
27454
27798
  name: GROK_HARNESS_NAME,
27455
27799
  builtinTools: GROK_BUILTIN_TOOLS,
27456
- detect: (opts) => hasRecentFile(
27457
- opts.roots ?? sessionRoots(),
27800
+ detect: async (opts) => hasRecentFile(
27801
+ opts.roots ?? await sessionRoots(),
27458
27802
  isGrokEvidenceFile,
27459
27803
  opts.sinceMs
27460
27804
  ),
@@ -27682,30 +28026,60 @@ function ingestTypedSkill2(agg, row) {
27682
28026
 
27683
28027
  // src/harness/opencode/scan.ts
27684
28028
  import { readFileSync as readFileSync12 } from "node:fs";
27685
- import { readdir as readdir7, stat as stat7 } from "node:fs/promises";
27686
- import { homedir as homedir15 } from "node:os";
27687
- import path12 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";
27688
28032
  var OPENCODE_MIGRATION_CEILING = 20260622202450;
27689
- function opencodeDataDirs() {
27690
- const xdg = process.env.XDG_DATA_HOME;
27691
- const base = xdg || path12.join(homedir15(), ".local", "share");
27692
- return [path12.join(base, "opencode")];
28033
+ async function opencodeDataDirs() {
28034
+ const xdg = process.env.XDG_DATA_HOME?.trim();
28035
+ return discoverHomes({
28036
+ defaults: [path14.join(homedir17(), ".local", "share", "opencode")],
28037
+ configured: [xdg ? path14.join(xdg, "opencode") : void 0],
28038
+ remember: "opencode"
28039
+ });
27693
28040
  }
27694
- function isStoreFile(basename5) {
27695
- return basename5 === "opencode.db" || /^opencode-[^/]+\.db$/.test(basename5);
28041
+ function isStoreFile(basename6) {
28042
+ return basename6 === "opencode.db" || /^opencode-[^/]+\.db$/.test(basename6);
27696
28043
  }
27697
28044
  async function dbFilesIn(root) {
27698
- const override = process.env.OPENCODE_DB;
27699
- if (override) return [override];
27700
28045
  try {
27701
- const entries = await readdir7(root, { withFileTypes: true });
27702
- return entries.filter((e) => e.isFile() && isStoreFile(e.name)).map((e) => path12.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();
27703
28048
  } catch (error) {
27704
28049
  if (error?.code !== "ENOENT")
27705
28050
  traceError("opencode database discovery", error, "warn");
27706
28051
  return [];
27707
28052
  }
27708
28053
  }
28054
+ async function storeFiles(roots) {
28055
+ const dirs = roots ?? (await opencodeDataDirs()).homes;
28056
+ const candidates = [];
28057
+ for (const root of dirs) candidates.push(...await dbFilesIn(root));
28058
+ const override = roots ? void 0 : process.env.OPENCODE_DB?.trim();
28059
+ if (override)
28060
+ candidates.push(
28061
+ path14.resolve(
28062
+ process.env.XDG_DATA_HOME?.trim() || path14.join(homedir17(), ".local", "share"),
28063
+ "opencode",
28064
+ override
28065
+ )
28066
+ );
28067
+ const files = [];
28068
+ const seen = /* @__PURE__ */ new Set();
28069
+ for (const file of candidates) {
28070
+ let key2 = file;
28071
+ try {
28072
+ key2 = await realpath4(file);
28073
+ } catch (error) {
28074
+ if (error?.code !== "ENOENT")
28075
+ traceError("opencode database path resolution", error, "warn");
28076
+ }
28077
+ if (seen.has(key2)) continue;
28078
+ seen.add(key2);
28079
+ files.push(file);
28080
+ }
28081
+ return files;
28082
+ }
27709
28083
  async function loadSqlite() {
27710
28084
  try {
27711
28085
  const mod = await import("node:sqlite");
@@ -27718,8 +28092,8 @@ async function loadSqlite() {
27718
28092
  }
27719
28093
  }
27720
28094
  function errorClass2(e) {
27721
- const code = e?.code;
27722
- if (typeof code === "string" && code.length > 0) return code;
28095
+ const code2 = e?.code;
28096
+ if (typeof code2 === "string" && code2.length > 0) return code2;
27723
28097
  return e instanceof Error ? e.constructor.name : "unknown";
27724
28098
  }
27725
28099
  var readError2 = (reason) => Object.assign(new Error(reason), { code: reason });
@@ -27729,24 +28103,22 @@ async function scan5(agg, opts = {}) {
27729
28103
  const sinceMs = opts.sinceMs ?? 0;
27730
28104
  const state = createDbFoldState();
27731
28105
  readConfiguredMcpServers2(agg, state, opts.configFile);
27732
- for (const root of opts.roots ?? opencodeDataDirs()) {
27733
- for (const file of await dbFilesIn(root)) {
27734
- stats.filesFound++;
27735
- agg.files++;
27736
- try {
27737
- if (open4 === null) throw readError2("sqlite-unsupported");
27738
- readDb(agg, state, open4, file, sinceMs);
27739
- stats.filesRead++;
27740
- } catch (e) {
27741
- traceError("opencode database read", e);
27742
- stats.filesUnreadable++;
27743
- stats.unreadableFiles.push({
27744
- path: path12.basename(file),
27745
- reason: errorClass2(e)
27746
- });
27747
- }
27748
- if (opts.onProgress) opts.onProgress(stats.filesFound);
28106
+ for (const file of await storeFiles(opts.roots)) {
28107
+ stats.filesFound++;
28108
+ agg.files++;
28109
+ try {
28110
+ if (open4 === null) throw readError2("sqlite-unsupported");
28111
+ readDb(agg, state, open4, file, sinceMs);
28112
+ stats.filesRead++;
28113
+ } catch (e) {
28114
+ traceError("opencode database read", e);
28115
+ stats.filesUnreadable++;
28116
+ stats.unreadableFiles.push({
28117
+ path: path14.basename(file),
28118
+ reason: errorClass2(e)
28119
+ });
27749
28120
  }
28121
+ if (opts.onProgress) opts.onProgress(stats.filesFound);
27750
28122
  }
27751
28123
  return stats;
27752
28124
  }
@@ -27928,8 +28300,8 @@ function pickTs(jsonTs, columnTs) {
27928
28300
  }
27929
28301
  function opencodeConfigFile() {
27930
28302
  const xdg = process.env.XDG_CONFIG_HOME;
27931
- const base = xdg || path12.join(homedir15(), ".config");
27932
- return path12.join(base, "opencode", "opencode.json");
28303
+ const base = xdg || path14.join(homedir17(), ".config");
28304
+ return path14.join(base, "opencode", "opencode.json");
27933
28305
  }
27934
28306
  function readConfiguredMcpServers2(agg, state, configFile) {
27935
28307
  const file = configFile ?? opencodeConfigFile();
@@ -27981,26 +28353,24 @@ function stripJsonc(text) {
27981
28353
  async function detectOpencode(opts) {
27982
28354
  const open4 = await loadSqlite();
27983
28355
  if (open4 === null) return false;
27984
- for (const root of opts.roots ?? opencodeDataDirs()) {
27985
- for (const file of await dbFilesIn(root)) {
27986
- if (!await exists4(file)) continue;
27987
- let db = null;
28356
+ for (const file of await storeFiles(opts.roots)) {
28357
+ if (!await exists4(file)) continue;
28358
+ let db = null;
28359
+ try {
28360
+ db = open4(file);
28361
+ checkMigrationCeiling(db);
28362
+ const probe = (table) => db?.prepare(
28363
+ `select 1 as hit from ${table} where time_created >= ? limit 1`
28364
+ ).get(opts.sinceMs) !== void 0;
28365
+ if (probe("message") || probe("session_message")) return true;
28366
+ } catch (error) {
28367
+ traceError("opencode detection", error, "warn");
28368
+ } finally {
27988
28369
  try {
27989
- db = open4(file);
27990
- checkMigrationCeiling(db);
27991
- const probe = (table) => db?.prepare(
27992
- `select 1 as hit from ${table} where time_created >= ? limit 1`
27993
- ).get(opts.sinceMs) !== void 0;
27994
- if (probe("message") || probe("session_message")) return true;
28370
+ db?.close();
27995
28371
  } catch (error) {
27996
- traceError("opencode detection", error, "warn");
27997
- } finally {
27998
- try {
27999
- db?.close();
28000
- } catch (error) {
28001
- if (error?.code !== "ENOENT")
28002
- traceError("opencode source stat", error, "warn");
28003
- }
28372
+ if (error?.code !== "ENOENT")
28373
+ traceError("opencode source stat", error, "warn");
28004
28374
  }
28005
28375
  }
28006
28376
  }
@@ -28008,7 +28378,7 @@ async function detectOpencode(opts) {
28008
28378
  }
28009
28379
  async function exists4(p8) {
28010
28380
  try {
28011
- await stat7(p8);
28381
+ await stat9(p8);
28012
28382
  return true;
28013
28383
  } catch (error) {
28014
28384
  if (error?.code !== "ENOENT")
@@ -28238,33 +28608,40 @@ function readCounts2(usageRaw) {
28238
28608
 
28239
28609
  // src/harness/pi/scan.ts
28240
28610
  import { createReadStream as createReadStream3 } from "node:fs";
28241
- import { readdir as readdir8, realpath as realpath4, stat as stat8 } from "node:fs/promises";
28242
- import { homedir as homedir16 } from "node:os";
28243
- import path13 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";
28244
28614
  import readline3 from "node:readline";
28245
28615
  var MAX_SESSION_VERSION = 3;
28246
- function piAgentDir() {
28247
- return process.env.PI_CODING_AGENT_DIR || path13.join(homedir16(), ".pi", "agent");
28616
+ async function discoverSessionRoots() {
28617
+ const agentDir = process.env.PI_CODING_AGENT_DIR?.trim();
28618
+ return discoverHomes({
28619
+ defaults: [path15.join(homedir18(), ".pi", "agent", "sessions")],
28620
+ configured: [
28621
+ agentDir ? path15.join(agentDir, "sessions") : void 0,
28622
+ process.env.PI_CODING_AGENT_SESSION_DIR
28623
+ ],
28624
+ remember: "pi-mono"
28625
+ });
28248
28626
  }
28249
- function sessionRoots2() {
28250
- const override = process.env.PI_CODING_AGENT_SESSION_DIR;
28251
- return [override || path13.join(piAgentDir(), "sessions")];
28627
+ async function sessionRoots2() {
28628
+ return (await discoverSessionRoots()).homes;
28252
28629
  }
28253
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$/;
28254
- function isSessionFile(basename5) {
28255
- return SESSION_FILE_RE.test(basename5);
28631
+ function isSessionFile(basename6) {
28632
+ return SESSION_FILE_RE.test(basename6);
28256
28633
  }
28257
28634
  async function* walkSessions(dir) {
28258
28635
  let entries;
28259
28636
  try {
28260
- entries = await readdir8(dir, { withFileTypes: true });
28637
+ entries = await readdir10(dir, { withFileTypes: true });
28261
28638
  } catch (error) {
28262
28639
  if (error?.code !== "ENOENT")
28263
28640
  traceError("pi transcript discovery", error, "warn");
28264
28641
  return;
28265
28642
  }
28266
28643
  for (const e of entries) {
28267
- const full = path13.join(dir, e.name);
28644
+ const full = path15.join(dir, e.name);
28268
28645
  if (e.isDirectory()) yield* walkSessions(full);
28269
28646
  else if (e.isFile() && isSessionFile(e.name)) yield full;
28270
28647
  }
@@ -28273,13 +28650,15 @@ async function scan6(agg, opts = {}) {
28273
28650
  const stats = emptyScanStats();
28274
28651
  const visited = /* @__PURE__ */ new Set();
28275
28652
  const fold = createFoldState();
28276
- for (const root of opts.roots ?? sessionRoots2()) {
28653
+ const discovery = opts.roots ? { homes: opts.roots, complete: true } : await discoverSessionRoots();
28654
+ stats.sourceDiscoveryComplete = discovery.complete;
28655
+ for (const root of discovery.homes) {
28277
28656
  if (!await exists5(root)) continue;
28278
28657
  for await (const file of walkSessions(root)) {
28279
28658
  stats.filesFound++;
28280
28659
  let resolved;
28281
28660
  try {
28282
- resolved = await realpath4(file);
28661
+ resolved = await realpath5(file);
28283
28662
  } catch (error) {
28284
28663
  if (error?.code !== "ENOENT")
28285
28664
  traceError("pi transcript path resolution", error, "warn");
@@ -28292,7 +28671,7 @@ async function scan6(agg, opts = {}) {
28292
28671
  visited.add(resolved);
28293
28672
  if (opts.sinceMs !== void 0) {
28294
28673
  try {
28295
- const st = await stat8(file);
28674
+ const st = await stat10(file);
28296
28675
  if (st.mtimeMs < opts.sinceMs) {
28297
28676
  stats.filesSkippedByMtime++;
28298
28677
  continue;
@@ -28316,7 +28695,7 @@ async function scan6(agg, opts = {}) {
28316
28695
  stats.filesUnreadable++;
28317
28696
  stats.filesRead--;
28318
28697
  stats.unreadableFiles.push({
28319
- path: path13.relative(root, file),
28698
+ path: path15.relative(root, file),
28320
28699
  reason: "version-too-new"
28321
28700
  });
28322
28701
  }
@@ -28325,7 +28704,7 @@ async function scan6(agg, opts = {}) {
28325
28704
  stats.filesUnreadable++;
28326
28705
  stats.filesRead--;
28327
28706
  stats.unreadableFiles.push({
28328
- path: path13.relative(root, file),
28707
+ path: path15.relative(root, file),
28329
28708
  reason: "read-error"
28330
28709
  });
28331
28710
  }
@@ -28335,7 +28714,7 @@ async function scan6(agg, opts = {}) {
28335
28714
  }
28336
28715
  async function exists5(p8) {
28337
28716
  try {
28338
- await stat8(p8);
28717
+ await stat10(p8);
28339
28718
  return true;
28340
28719
  } catch (error) {
28341
28720
  if (error?.code !== "ENOENT")
@@ -28400,7 +28779,7 @@ var piAdapter = {
28400
28779
  builtinTools: PI_BUILTIN_TOOLS,
28401
28780
  async detect(opts) {
28402
28781
  return hasRecentFile(
28403
- opts.roots ?? sessionRoots2(),
28782
+ opts.roots ?? await sessionRoots2(),
28404
28783
  isSessionFile,
28405
28784
  opts.sinceMs
28406
28785
  );
@@ -28414,6 +28793,7 @@ var piAdapter = {
28414
28793
  return {
28415
28794
  aggregate,
28416
28795
  stats,
28796
+ scanComplete: stats.sourceDiscoveryComplete !== false,
28417
28797
  workflow: aggregate.workflow.finish(),
28418
28798
  workflowLocal: aggregate.workflowLocal
28419
28799
  };
@@ -28470,7 +28850,7 @@ var MCP_ADD_ARGS = [
28470
28850
  "mcp"
28471
28851
  ];
28472
28852
  var MCP_REMOVE_ARGS = ["mcp", "remove", "--scope", "user", "aistack"];
28473
- var SKILL_DEST = join13(homedir17(), ".claude", "skills", "aistack-sync");
28853
+ var SKILL_DEST = join13(homedir19(), ".claude", "skills", "aistack-sync");
28474
28854
  function runClaude(args) {
28475
28855
  const r = spawnSync("claude", args, { encoding: "utf-8" });
28476
28856
  const notFound = r.error !== void 0 && r.error.code === "ENOENT";
@@ -28699,6 +29079,68 @@ async function createCommand() {
28699
29079
  outro2(lime("done"));
28700
29080
  }
28701
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
+
28702
29144
  // src/commands/login.ts
28703
29145
  import { hostname } from "node:os";
28704
29146
  import * as p5 from "@clack/prompts";
@@ -28791,20 +29233,32 @@ async function loginCommand(options = {}) {
28791
29233
  // src/commands/sync.ts
28792
29234
  import * as p7 from "@clack/prompts";
28793
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
+
28794
29242
  // src/autosync/codexHook.ts
28795
29243
  import { createHash as createHash9 } from "node:crypto";
28796
- import { existsSync as existsSync13, mkdirSync as mkdirSync4, readFileSync as readFileSync14, writeFileSync as writeFileSync4 } from "node:fs";
28797
- import { homedir as homedir18 } 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";
28798
29252
  import { dirname as dirname7, join as join15 } from "node:path";
28799
29253
  import { parse } from "smol-toml";
28800
- function codexHome2() {
28801
- return process.env.CODEX_HOME || join15(homedir18(), ".codex");
29254
+ function codexHome() {
29255
+ return process.env.CODEX_HOME || join15(homedir20(), ".codex");
28802
29256
  }
28803
29257
  function codexHooksFile() {
28804
- return join15(codexHome2(), "hooks.json");
29258
+ return join15(codexHome(), "hooks.json");
28805
29259
  }
28806
29260
  function codexConfigFile() {
28807
- return join15(codexHome2(), "config.toml");
29261
+ return join15(codexHome(), "config.toml");
28808
29262
  }
28809
29263
  var CODEX_HOOK_COMMAND = `sh -c 'setsid nohup sh -c "npx -y @use-aistack/cli@latest sync --auto || npx -y --prefer-offline @use-aistack/cli sync --auto" >/dev/null 2>&1 &'`;
28810
29264
  function isOurs(entry) {
@@ -28908,8 +29362,12 @@ function codexHookTrusted(configFile = codexConfigFile(), hooksFile = codexHooks
28908
29362
  };
28909
29363
  if (typeof group.matcher === "string") identity.matcher = group.matcher;
28910
29364
  const currentHash = `sha256:${createHash9("sha256").update(JSON.stringify(canonicalJson2(identity))).digest("hex")}`;
28911
- const key2 = `${hooksFile}:session_start:${groupIndex}:${handlerIndex}`;
28912
- 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
+ );
28913
29371
  }
28914
29372
  }
28915
29373
  return matches.length > 0 && matches.every(Boolean);
@@ -28917,6 +29375,14 @@ function codexHookTrusted(configFile = codexConfigFile(), hooksFile = codexHooks
28917
29375
  return null;
28918
29376
  }
28919
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
+ }
28920
29386
  function canonicalJson2(value) {
28921
29387
  if (Array.isArray(value)) return value.map(canonicalJson2);
28922
29388
  if (value && typeof value === "object") {
@@ -28934,19 +29400,16 @@ function canonicalJson2(value) {
28934
29400
  throw new TypeError("hook identity is not JSON-serializable");
28935
29401
  }
28936
29402
 
28937
- // src/autosync/optin.ts
28938
- import * as p6 from "@clack/prompts";
28939
-
28940
29403
  // src/autosync/cursorHook.ts
28941
29404
  import { existsSync as existsSync15, mkdirSync as mkdirSync6, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "node:fs";
28942
- import { homedir as homedir20, platform as platform2 } from "node:os";
29405
+ import { homedir as homedir22, platform as platform2 } from "node:os";
28943
29406
  import { dirname as dirname9, join as join17 } from "node:path";
28944
29407
 
28945
29408
  // src/autosync/hook.ts
28946
29409
  import { existsSync as existsSync14, mkdirSync as mkdirSync5, readFileSync as readFileSync15, writeFileSync as writeFileSync5 } from "node:fs";
28947
- import { homedir as homedir19 } from "node:os";
29410
+ import { homedir as homedir21 } from "node:os";
28948
29411
  import { dirname as dirname8, join as join16 } from "node:path";
28949
- var CLAUDE_SETTINGS_FILE = join16(homedir19(), ".claude", "settings.json");
29412
+ var CLAUDE_SETTINGS_FILE = join16(homedir21(), ".claude", "settings.json");
28950
29413
  var AUTO_SYNC_HOOK_COMMAND = "npx -y @use-aistack/cli@latest sync --auto || npx -y --prefer-offline @use-aistack/cli sync --auto";
28951
29414
  function isOurs2(entry) {
28952
29415
  return typeof entry.command === "string" && entry.command.includes("@use-aistack/cli") && entry.command.includes("sync --auto");
@@ -29019,7 +29482,7 @@ function autoSyncHookInstalled(file = CLAUDE_SETTINGS_FILE) {
29019
29482
  }
29020
29483
 
29021
29484
  // src/autosync/cursorHook.ts
29022
- var CURSOR_HOOK_FILE = join17(homedir20(), ".cursor", "hooks.json");
29485
+ var CURSOR_HOOK_FILE = join17(homedir22(), ".cursor", "hooks.json");
29023
29486
  function cursorHookCommand(os = platform2()) {
29024
29487
  if (os === "win32") {
29025
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"'`;
@@ -29099,10 +29562,10 @@ import {
29099
29562
  unlinkSync as unlinkSync5,
29100
29563
  writeFileSync as writeFileSync7
29101
29564
  } from "node:fs";
29102
- import { homedir as homedir21, platform as platform3 } from "node:os";
29565
+ import { homedir as homedir23, platform as platform3 } from "node:os";
29103
29566
  import { dirname as dirname10, join as join18 } from "node:path";
29104
29567
  var GROK_HOOK_FILE = join18(
29105
- process.env.GROK_HOME || join18(homedir21(), ".grok"),
29568
+ process.env.GROK_HOME || join18(homedir23(), ".grok"),
29106
29569
  "hooks",
29107
29570
  "aistack.json"
29108
29571
  );
@@ -29203,7 +29666,148 @@ function grokAutoSyncHookInstalled(file = GROK_HOOK_FILE) {
29203
29666
  );
29204
29667
  }
29205
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
+
29206
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
+ }
29207
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.";
29208
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.`;
29209
29813
  async function enableAutoSync(frequencyHours = DEFAULT_FREQUENCY_HOURS, deps = {}) {
@@ -29226,21 +29830,20 @@ async function enableAutoSync(frequencyHours = DEFAULT_FREQUENCY_HOURS, deps = {
29226
29830
  message: `Auto-sync was not turned on: ${e instanceof Error ? e.message : String(e)}`
29227
29831
  };
29228
29832
  }
29229
- if (names.has(CLAUDE_HARNESS_NAME)) {
29230
- const result = (deps.installHook ?? installAutoSyncHook)();
29231
- if (!result.ok) return result;
29232
- }
29833
+ const homes = await (deps.homesImpl ?? discoverHookHomes)();
29834
+ const failures = [];
29233
29835
  let trustLine = null;
29234
- if (names.has(CODEX_HARNESS_NAME)) {
29235
- const codexResult = (deps.installCodexHook ?? installCodexAutoSyncHook)();
29236
- if (!codexResult.ok) return codexResult;
29237
- if ((deps.codexHookTrustedImpl ?? codexHookTrusted)() !== true) {
29238
- trustLine = codexResult.message;
29239
- }
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);
29240
29841
  }
29241
- if (names.has(GROK_HARNESS_NAME)) {
29242
- const grokResult = (deps.installGrokHook ?? installGrokAutoSyncHook)();
29243
- 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
+ };
29244
29847
  }
29245
29848
  if (names.has(CURSOR_HARNESS_NAME)) {
29246
29849
  const result = (deps.installCursorHook ?? installCursorAutoSyncHook)();
@@ -29275,11 +29878,8 @@ async function disableAutoSync(deps = {}) {
29275
29878
  },
29276
29879
  deps.settingsFile
29277
29880
  );
29278
- const result = (deps.removeHook ?? removeAutoSyncHook)();
29279
- const codexResult = (deps.removeCodexHook ?? removeCodexAutoSyncHook)();
29280
- const grokResult = (deps.removeGrokHook ?? removeGrokAutoSyncHook)();
29281
- const cursorResult = (deps.removeCursorHook ?? removeCursorAutoSyncHook)();
29282
- 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);
29283
29883
  const token = (deps.getTokenImpl ?? getToken)();
29284
29884
  if (token !== null) {
29285
29885
  try {
@@ -29317,17 +29917,12 @@ async function reconcileAutoSync(permission, deps = {}) {
29317
29917
  },
29318
29918
  deps.settingsFile
29319
29919
  );
29320
- const results = [
29321
- (deps.removeHook ?? removeAutoSyncHook)(),
29322
- (deps.removeCodexHook ?? removeCodexAutoSyncHook)(),
29323
- (deps.removeGrokHook ?? removeGrokAutoSyncHook)(),
29324
- (deps.removeCursorHook ?? removeCursorAutoSyncHook)()
29325
- ];
29326
- const failures2 = results.filter((result) => !result.ok);
29920
+ const homes2 = await (deps.homesImpl ?? discoverHookHomes)();
29921
+ const { results, failures: failures2 } = removeHooks(homes2, deps);
29327
29922
  if (failures2.length > 0) {
29328
29923
  return {
29329
29924
  ok: false,
29330
- 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.`
29331
29926
  };
29332
29927
  }
29333
29928
  const changed = settings.autoSync?.enabled !== false || results.some((result) => !result.message.toLowerCase().startsWith("no "));
@@ -29340,34 +29935,27 @@ async function reconcileAutoSync(permission, deps = {}) {
29340
29935
  const detected = await (deps.detectedImpl ?? detectedAdapters)();
29341
29936
  if (detected.length === 0) return null;
29342
29937
  const names = new Set(detected.map((a) => a.name));
29938
+ const homes = await (deps.homesImpl ?? discoverHookHomes)();
29343
29939
  const installed = [];
29344
29940
  const failures = [];
29345
- const install = (harnessName, isInstalled, write) => {
29346
- if (!names.has(harnessName) || isInstalled()) return;
29347
- const result = write();
29348
- 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));
29349
29957
  else failures.push(result.message);
29350
- };
29351
- install(
29352
- CLAUDE_HARNESS_NAME,
29353
- deps.hookInstalledImpl ?? autoSyncHookInstalled,
29354
- deps.installHook ?? installAutoSyncHook
29355
- );
29356
- install(
29357
- CODEX_HARNESS_NAME,
29358
- deps.codexHookInstalledImpl ?? codexAutoSyncHookInstalled,
29359
- deps.installCodexHook ?? installCodexAutoSyncHook
29360
- );
29361
- install(
29362
- GROK_HARNESS_NAME,
29363
- deps.grokHookInstalledImpl ?? grokAutoSyncHookInstalled,
29364
- deps.installGrokHook ?? installGrokAutoSyncHook
29365
- );
29366
- install(
29367
- CURSOR_HARNESS_NAME,
29368
- deps.cursorHookInstalledImpl ?? cursorAutoSyncHookInstalled,
29369
- deps.installCursorHook ?? installCursorAutoSyncHook
29370
- );
29958
+ }
29371
29959
  if (failures.length > 0) {
29372
29960
  return {
29373
29961
  ok: false,
@@ -29386,9 +29974,71 @@ async function reconcileAutoSync(permission, deps = {}) {
29386
29974
  if (installed.length === 0 && mirrored) return null;
29387
29975
  return {
29388
29976
  ok: true,
29389
- 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")
29390
29981
  };
29391
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
+ }
29392
30042
  async function settleAutoSync(permission, deps = {}) {
29393
30043
  if (permission !== null) {
29394
30044
  const result = await reconcileAutoSync(permission, deps);
@@ -29453,15 +30103,12 @@ async function offerAutoSyncOptIn(deps = {}) {
29453
30103
  // src/autosync/run.ts
29454
30104
  import {
29455
30105
  appendFileSync,
29456
- closeSync as closeSync5,
29457
- mkdirSync as mkdirSync9,
29458
- openSync as openSync5,
29459
- readFileSync as readFileSync19,
29460
- unlinkSync as unlinkSync6,
29461
- writeFileSync as writeFileSync9
30106
+ mkdirSync as mkdirSync10,
30107
+ readFileSync as readFileSync20,
30108
+ writeFileSync as writeFileSync10
29462
30109
  } from "node:fs";
29463
- import { homedir as homedir23 } from "node:os";
29464
- 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";
29465
30112
 
29466
30113
  // src/sync/stage.ts
29467
30114
  import { createHash as createHash11 } from "node:crypto";
@@ -29621,8 +30268,8 @@ function selectDaysToPublish(input) {
29621
30268
 
29622
30269
  // src/workflow/git.ts
29623
30270
  import { execFile, execFileSync as execFileSync2 } from "node:child_process";
29624
- import { existsSync as existsSync17 } from "node:fs";
29625
- import path14 from "node:path";
30271
+ import { existsSync as existsSync18 } from "node:fs";
30272
+ import path17 from "node:path";
29626
30273
  var TEST_FILE_RULE_VERSION = "test-files/v2";
29627
30274
  var FILE_TYPE_RULE_VERSION = "file-types/v3";
29628
30275
  var COMMIT_SET_RULE_VERSION = "commit-set/v1";
@@ -29632,7 +30279,7 @@ function gitDiagnostics() {
29632
30279
  const report = (error, cwd, args, stderr) => {
29633
30280
  const details = error;
29634
30281
  if (args[0] === "rev-parse") {
29635
- if (details.code === "ENOENT" && !existsSync17(cwd)) {
30282
+ if (details.code === "ENOENT" && !existsSync18(cwd)) {
29636
30283
  missing++;
29637
30284
  return;
29638
30285
  }
@@ -29822,8 +30469,8 @@ function isTestFile(file) {
29822
30469
  if (parts.some((part) => ["test", "tests", "__tests__"].includes(part))) {
29823
30470
  return true;
29824
30471
  }
29825
- const basename5 = parts.at(-1) ?? "";
29826
- return /(?:^|[._-])(test|spec)(?:[._-]|$)/.test(basename5);
30472
+ const basename6 = parts.at(-1) ?? "";
30473
+ return /(?:^|[._-])(test|spec)(?:[._-]|$)/.test(basename6);
29827
30474
  }
29828
30475
  function utcCell(authoredMs) {
29829
30476
  const at = new Date(authoredMs);
@@ -30039,9 +30686,9 @@ function reduceGitHistories(histories, options) {
30039
30686
  if (included) seenCommits.add(hash2);
30040
30687
  continue;
30041
30688
  }
30042
- const stat9 = parseNumstat(field);
30043
- if (!stat9) continue;
30044
- let file = stat9.file;
30689
+ const stat12 = parseNumstat(field);
30690
+ if (!stat12) continue;
30691
+ let file = stat12.file;
30045
30692
  if (file.length === 0) {
30046
30693
  fieldIndex += 2;
30047
30694
  file = fields[fieldIndex] ?? fields[fieldIndex - 1] ?? "";
@@ -30049,13 +30696,13 @@ function reduceGitHistories(histories, options) {
30049
30696
  if (!current?.included) continue;
30050
30697
  if (isUnauthoredPath(file)) continue;
30051
30698
  current.authored = true;
30052
- const fileChangedLines = stat9.additions + stat9.removals;
30053
- current.additions += stat9.additions;
30054
- current.removals += stat9.removals;
30699
+ const fileChangedLines = stat12.additions + stat12.removals;
30700
+ current.additions += stat12.additions;
30701
+ current.removals += stat12.removals;
30055
30702
  current.changedLines += fileChangedLines;
30056
30703
  if (isTestFile(file)) current.touchesTest = true;
30057
30704
  if (fileChangedLines <= 0) continue;
30058
- const extension = path14.extname(file).toLowerCase();
30705
+ const extension = path17.extname(file).toLowerCase();
30059
30706
  if (APPROVED_EXTENSIONS.has(extension)) {
30060
30707
  current.extensionLines.set(
30061
30708
  extension,
@@ -30160,11 +30807,11 @@ function buildWorkflowExtraction(harnessWorkflows, git, utcOffsetMinutes = machi
30160
30807
 
30161
30808
  // src/sync/grokDateCache.ts
30162
30809
  import { createHash as createHash10 } from "node:crypto";
30163
- import { existsSync as existsSync18, mkdirSync as mkdirSync8, readFileSync as readFileSync18, writeFileSync as writeFileSync8 } from "node:fs";
30164
- import { homedir as homedir22 } from "node:os";
30165
- import path15 from "node:path";
30166
- var defaultFile = path15.join(
30167
- homedir22(),
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(),
30168
30815
  ".config",
30169
30816
  "aistack",
30170
30817
  "grok-session-dates.json"
@@ -30173,7 +30820,7 @@ function grokCacheScope(baseUrl, stack, token) {
30173
30820
  return createHash10("sha256").update(`${baseUrl}\0${stack}\0${token}`).digest("hex");
30174
30821
  }
30175
30822
  function read2(file) {
30176
- if (!existsSync18(file)) return {};
30823
+ if (!existsSync19(file)) return {};
30177
30824
  try {
30178
30825
  const value = JSON.parse(readFileSync18(file, "utf8"));
30179
30826
  return value && typeof value === "object" ? value : {};
@@ -30187,7 +30834,7 @@ function loadGrokDateHints(scope, file = defaultFile) {
30187
30834
  function saveGrokDateHints(scope, hints, file = defaultFile) {
30188
30835
  const cache = read2(file);
30189
30836
  cache[scope] = hints;
30190
- mkdirSync8(path15.dirname(file), { recursive: true });
30837
+ mkdirSync8(path18.dirname(file), { recursive: true });
30191
30838
  writeFileSync8(file, JSON.stringify(cache, null, 2));
30192
30839
  }
30193
30840
  function mapToHints(value, floor) {
@@ -31071,42 +31718,84 @@ function describeScan(stats) {
31071
31718
  return `${stats.filesRead}/${stats.filesFound} files read, ${stats.filesUnreadable} unreadable`;
31072
31719
  }
31073
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
+
31074
31784
  // src/autosync/run.ts
31075
- var SYNC_LOG_FILE = join19(homedir23(), ".config", "aistack", "sync.log");
31785
+ var SYNC_LOG_FILE = join21(homedir27(), ".config", "aistack", "sync.log");
31076
31786
  var SYNC_LOG_MAX_LINES = 200;
31077
31787
  var FIX_COMMAND = "npx @use-aistack/cli@latest sync";
31078
31788
  var REVOKED_RESULT = "off - auto-sync is switched off for this stack";
31079
31789
  function appendLogLine(file, line) {
31080
- mkdirSync9(dirname11(file), { recursive: true });
31790
+ mkdirSync10(dirname14(file), { recursive: true });
31081
31791
  appendFileSync(file, `${line}
31082
31792
  `);
31083
- const lines2 = readFileSync19(file, "utf-8").split("\n").filter(Boolean);
31793
+ const lines2 = readFileSync20(file, "utf-8").split("\n").filter(Boolean);
31084
31794
  if (lines2.length > SYNC_LOG_MAX_LINES) {
31085
- writeFileSync9(file, `${lines2.slice(-SYNC_LOG_MAX_LINES).join("\n")}
31795
+ writeFileSync10(file, `${lines2.slice(-SYNC_LOG_MAX_LINES).join("\n")}
31086
31796
  `);
31087
31797
  }
31088
31798
  }
31089
- function reserveAttempt(file, now, windowMs) {
31090
- mkdirSync9(dirname11(file), { recursive: true });
31091
- for (; ; ) {
31092
- try {
31093
- const fd = openSync5(file, "wx");
31094
- writeFileSync9(fd, String(now));
31095
- closeSync5(fd);
31096
- return true;
31097
- } catch (error) {
31098
- if (error.code !== "EEXIST") throw error;
31099
- const held = Number(readFileSync19(file, "utf-8"));
31100
- if (Number.isFinite(held) && now - held < windowMs) return false;
31101
- try {
31102
- unlinkSync6(file);
31103
- } catch (unlinkError) {
31104
- if (unlinkError.code !== "ENOENT")
31105
- throw unlinkError;
31106
- }
31107
- }
31108
- }
31109
- }
31110
31799
  async function runAutoSync(deps) {
31111
31800
  const now = (deps.now ?? Date.now)();
31112
31801
  const settingsFile = deps.settingsFile;
@@ -31125,7 +31814,7 @@ async function runAutoSync(deps) {
31125
31814
  const state = settings.autoSyncState ?? {};
31126
31815
  const lastRunAt = state.lastRunAt ?? 0;
31127
31816
  if (now - lastRunAt < windowMs) return;
31128
- const reservationFile = deps.reservationFile ?? `${settingsFile ?? join19(homedir23(), ".config", "aistack", "settings.json")}.auto-sync-attempt`;
31817
+ const reservationFile = deps.reservationFile ?? `${settingsFile ?? join21(homedir27(), ".config", "aistack", "settings.json")}.auto-sync-attempt`;
31129
31818
  if (!reserveAttempt(reservationFile, now, windowMs)) return;
31130
31819
  saveSettings({ autoSyncState: { ...state, lastRunAt: now } }, settingsFile);
31131
31820
  const stage = deps.stageImpl ?? stageSync;
@@ -31400,9 +32089,18 @@ async function syncCommand(options = {}) {
31400
32089
  }
31401
32090
  return;
31402
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
+ }
31403
32099
  if (options.auto !== void 0) {
31404
32100
  intro2("sync");
31405
- outroError(`unknown --auto value "${options.auto}" (use on or off)`);
32101
+ outroError(
32102
+ `unknown --auto value "${options.auto}" (use on, off or status)`
32103
+ );
31406
32104
  process.exitCode = 1;
31407
32105
  return;
31408
32106
  }
@@ -31411,9 +32109,8 @@ async function syncCommand(options = {}) {
31411
32109
  if (lastAuto !== void 0) {
31412
32110
  p7.log.message(dim(`auto-sync: ${lastAuto}`));
31413
32111
  }
31414
- if (codexAutoSyncHookInstalled() && codexHookTrusted() === false) {
31415
- p7.log.warn(CODEX_TRUST_INSTRUCTION);
31416
- }
32112
+ const trustReminder = await codexTrustReminder();
32113
+ if (trustReminder) p7.log.warn(trustReminder);
31417
32114
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
31418
32115
  outroError("sync needs an interactive terminal. Nothing was sent.");
31419
32116
  process.exitCode = 1;
@@ -31645,7 +32342,7 @@ function createSyncServer(deps, send) {
31645
32342
  let nextRequestId = 1;
31646
32343
  const pending = /* @__PURE__ */ new Map();
31647
32344
  const ok = (id, result) => send({ jsonrpc: "2.0", id, result });
31648
- 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 } });
31649
32346
  const request2 = (method, params, onReply) => {
31650
32347
  const id = `aistack-${nextRequestId++}`;
31651
32348
  pending.set(id, onReply);
@@ -31871,7 +32568,7 @@ program.command("mcp").description(
31871
32568
  });
31872
32569
  program.command("sync").description("Scan, preview, and publish measured usage (rolling 30 days)").option(
31873
32570
  "--auto [state]",
31874
- "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"
31875
32572
  ).option(
31876
32573
  "--every <hours>",
31877
32574
  "with --auto on: hours between auto-syncs (default 6)"
@@ -31880,6 +32577,9 @@ program.command("sync").description("Scan, preview, and publish measured usage (
31880
32577
  "print every phase with its duration to stderr, for a sync that looks stuck (same as AISTACK_DEBUG=1)"
31881
32578
  ).action((options) => syncCommand(options));
31882
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));
31883
32583
  if (!supportsNodeVersion(process.versions.node)) {
31884
32584
  process.stderr.write(`${unsupportedNodeMessage(process.versions.node)}
31885
32585
  `);