@use-aistack/cli 0.21.0 → 0.22.1

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
@@ -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((path19) => !unverifiedResidueSet.has(path19)).sort(compareCodePoints);
240
+ const residuePaths = [...new Set(cleanupErrors.flatMap((error) => error.details.residuePaths))].filter((path21) => !unverifiedResidueSet.has(path21)).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,
@@ -477,9 +477,9 @@ var init_errors3 = __esm({
477
477
  name = "DatabaseLockedError";
478
478
  /** Path to locked database file */
479
479
  path;
480
- constructor(path19) {
481
- super(`Database is locked: ${path19}. Close Cursor or retry later.`);
482
- this.path = path19;
480
+ constructor(path21) {
481
+ super(`Database is locked: ${path21}. Close Cursor or retry later.`);
482
+ this.path = path21;
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(path19) {
493
- super(`Database not found: ${path19}. Check dataPath configuration.`);
494
- this.path = path19;
492
+ constructor(path21) {
493
+ super(`Database not found: ${path21}. Check dataPath configuration.`);
494
+ this.path = path21;
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(path19) {
547
- super(`No workspace found for path: ${path19}. Please open the project in Cursor first.`);
548
- this.path = path19;
546
+ constructor(path21) {
547
+ super(`No workspace found for path: ${path21}. Please open the project in Cursor first.`);
548
+ this.path = path21;
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(path19) {
559
- super(`Source and destination are the same: ${path19}`);
560
- this.path = path19;
558
+ constructor(path21) {
559
+ super(`Source and destination are the same: ${path21}`);
560
+ this.path = path21;
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(path19) {
571
- super(`No sessions found for workspace: ${path19}. Use 'cursor-history list --workspace "${path19}"' to verify.`);
572
- this.path = path19;
570
+ constructor(path21) {
571
+ super(`No sessions found for workspace: ${path21}. Use 'cursor-history list --workspace "${path21}"' to verify.`);
572
+ this.path = path21;
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(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;
584
+ constructor(path21, sessionCount) {
585
+ super(`Destination already has ${sessionCount} session(s): ${path21}. Use --force to proceed (will add sessions alongside existing ones).`);
586
+ this.path = path21;
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(path19) {
622
- super(`No Cursor data found at: ${path19}. Verify Cursor is installed and has been used.`);
623
- this.path = path19;
621
+ constructor(path21) {
622
+ super(`No Cursor data found at: ${path21}. Verify Cursor is installed and has been used.`);
623
+ this.path = path21;
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(path19) {
634
- super(`File already exists: ${path19}. Use --force to overwrite.`);
635
- this.path = path19;
633
+ constructor(path21) {
634
+ super(`File already exists: ${path21}. Use --force to overwrite.`);
635
+ this.path = path21;
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(path19) {
672
- super(`Backup file not found: ${path19}`);
673
- this.path = path19;
671
+ constructor(path21) {
672
+ super(`Backup file not found: ${path21}`);
673
+ this.path = path21;
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(path19, reason) {
686
- super(`Invalid backup file: ${path19}. ${reason}`);
687
- this.path = path19;
685
+ constructor(path21, reason) {
686
+ super(`Invalid backup file: ${path21}. ${reason}`);
687
+ this.path = path21;
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(path19) {
699
- super(`Target already has Cursor data: ${path19}. Use --force to overwrite.`);
700
- this.path = path19;
698
+ constructor(path21) {
699
+ super(`Target already has Cursor data: ${path21}. Use --force to overwrite.`);
700
+ this.path = path21;
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 homedir10 } from "node:os";
723
+ import { homedir as homedir11 } 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,21 +757,21 @@ 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(homedir10(), ".cursor");
760
+ const defaultStoreRoot = join6(homedir11(), ".cursor");
761
761
  if (storeRootEnv && !pathsEqual(storeRootEnv, defaultStoreRoot)) {
762
762
  return "store";
763
763
  }
764
764
  return isWSL() ? "store" : "composer";
765
765
  }
766
- function getDefaultCursorDataPath(platform4) {
767
- const p8 = platform4 ?? detectPlatform();
766
+ function getDefaultCursorDataPath(platform5) {
767
+ const p8 = platform5 ?? detectPlatform();
768
768
  switch (p8) {
769
769
  case "windows":
770
- return join6(process.env["APPDATA"] ?? join6(homedir10(), "AppData", "Roaming"), "Cursor", "User", "workspaceStorage");
770
+ return join6(process.env["APPDATA"] ?? join6(homedir11(), "AppData", "Roaming"), "Cursor", "User", "workspaceStorage");
771
771
  case "macos":
772
- return join6(homedir10(), "Library", "Application Support", "Cursor", "User", "workspaceStorage");
772
+ return join6(homedir11(), "Library", "Application Support", "Cursor", "User", "workspaceStorage");
773
773
  case "linux":
774
- return join6(homedir10(), ".config", "Cursor", "User", "workspaceStorage");
774
+ return join6(homedir11(), ".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(path19) {
791
- if (path19.startsWith("~")) {
792
- return join6(homedir10(), path19.slice(1));
790
+ function expandPath(path21) {
791
+ if (path21.startsWith("~")) {
792
+ return join6(homedir11(), path21.slice(1));
793
793
  }
794
- return path19;
794
+ return path21;
795
795
  }
796
- function contractPath(path19) {
797
- const home = homedir10();
798
- if (path19.startsWith(home)) {
799
- return "~" + path19.slice(home.length);
796
+ function contractPath(path21) {
797
+ const home = homedir11();
798
+ if (path21.startsWith(home)) {
799
+ return "~" + path21.slice(home.length);
800
800
  }
801
- return path19;
801
+ return path21;
802
802
  }
803
803
  function normalizePath(filePath) {
804
804
  let normalized = filePath;
805
805
  if (normalized.startsWith("~")) {
806
- normalized = join6(homedir10(), normalized.slice(1));
806
+ normalized = join6(homedir11(), 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(homedir10(), ".cursor");
911
+ return join6(homedir11(), ".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(path19) {
1443
- return path19.caseInsensitive ? path19.path.toLowerCase() : path19.path;
1442
+ function exactComparisonKey(path21) {
1443
+ return path21.caseInsensitive ? path21.path.toLowerCase() : path21.path;
1444
1444
  }
1445
1445
  function componentsEndWith(candidate, request2) {
1446
1446
  if (request2.drive && candidate.drive !== request2.drive)
@@ -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(path19, request2 = READ_SESSION_REQUEST) {
2845
+ async openDatabase(path21, request2 = READ_SESSION_REQUEST) {
2846
2846
  const driver = await this.ensureDriver(request2);
2847
- return openObservedDatabase(request2.io, request2, () => driver.open(path19, { readonly: true }));
2847
+ return openObservedDatabase(request2.io, request2, () => driver.open(path21, { readonly: true }));
2848
2848
  }
2849
2849
  /** Open a database in read-write mode. */
2850
- async openDatabaseReadWrite(path19, request2 = MIGRATION_REQUEST) {
2850
+ async openDatabaseReadWrite(path21, request2 = MIGRATION_REQUEST) {
2851
2851
  const driver = await this.ensureDriver(request2);
2852
- return openObservedDatabase(request2.io, request2, () => driver.open(path19, { readonly: false }));
2852
+ return openObservedDatabase(request2.io, request2, () => driver.open(path21, { 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(path19, options) {
2860
+ openSync(path21, 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(path19, options);
2864
+ return this.currentDriver.open(path21, 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(path19, options) {
3011
+ open(path21, 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(path19, { readonly: options.readonly });
3016
- debugLog(`Opened database with better-sqlite3: ${path19} (readonly: ${options.readonly})`);
3015
+ const db = new BetterSqlite3(path21, { readonly: options.readonly });
3016
+ debugLog(`Opened database with better-sqlite3: ${path21} (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(path19, options) {
3207
+ open(path21, 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(path19, { readOnly: options.readonly });
3212
- debugLog(`Opened database with node:sqlite: ${path19} (readonly: ${options.readonly})`);
3211
+ const db = new nodeSqliteModule.DatabaseSync(path21, { readOnly: options.readonly });
3212
+ debugLog(`Opened database with node:sqlite: ${path21} (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(path19, request2) {
3237
- return registry.openDatabase(path19, request2);
3236
+ async function openDatabase(path21, request2) {
3237
+ return registry.openDatabase(path21, request2);
3238
3238
  }
3239
- async function openDatabaseReadWrite(path19, request2) {
3240
- return registry.openDatabaseReadWrite(path19, request2);
3239
+ async function openDatabaseReadWrite(path21, request2) {
3240
+ return registry.openDatabaseReadWrite(path21, 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(path19, contents) {
3378
- const descriptor = openSync(path19, exclusiveFlags(), 384);
3377
+ function createExclusivePrivateFile(path21, contents) {
3378
+ const descriptor = openSync(path21, exclusiveFlags(), 384);
3379
3379
  try {
3380
3380
  if (IS_PERMISSION_AWARE_POSIX)
3381
3381
  fchmodSync(descriptor, 384);
@@ -3387,10 +3387,10 @@ function createExclusivePrivateFile(path19, contents) {
3387
3387
  closeSync(descriptor);
3388
3388
  }
3389
3389
  }
3390
- function attemptRemoveEntryNoFollow(path19) {
3390
+ function attemptRemoveEntryNoFollow(path21) {
3391
3391
  let stats;
3392
3392
  try {
3393
- stats = lstatSync(path19);
3393
+ stats = lstatSync(path21);
3394
3394
  } catch (error) {
3395
3395
  if (!isMissing(error)) {
3396
3396
  }
@@ -3398,13 +3398,13 @@ function attemptRemoveEntryNoFollow(path19) {
3398
3398
  }
3399
3399
  if (stats.isDirectory() && !stats.isSymbolicLink()) {
3400
3400
  try {
3401
- rmdirSync(path19);
3401
+ rmdirSync(path21);
3402
3402
  } catch {
3403
3403
  }
3404
3404
  return;
3405
3405
  }
3406
3406
  try {
3407
- unlinkSync(path19);
3407
+ unlinkSync(path21);
3408
3408
  } catch {
3409
3409
  }
3410
3410
  }
@@ -3432,9 +3432,9 @@ function attemptRemoveWorkspaceNoFollow(directoryPath) {
3432
3432
  } catch {
3433
3433
  }
3434
3434
  }
3435
- function mayStillExist(path19) {
3435
+ function mayStillExist(path21) {
3436
3436
  try {
3437
- lstatSync(path19);
3437
+ lstatSync(path21);
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(path19, marker, markerPath, signal) {
3735
- this.path = path19;
3734
+ constructor(path21, marker, markerPath, signal) {
3735
+ this.path = path21;
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(path19) {
3766
+ register(path21) {
3767
3767
  this.assertOpen();
3768
- const candidatePath = resolve(path19);
3768
+ const candidatePath = resolve(path21);
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 path19 of tracked)
3783
- attemptRemoveEntryNoFollow(path19);
3782
+ for (const path21 of tracked)
3783
+ attemptRemoveEntryNoFollow(path21);
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(path19, options) {
4807
- return BoundedZipArchive.open(path19, options);
4806
+ async function openBoundedZipArchive(path21, options) {
4807
+ return BoundedZipArchive.open(path21, 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(path19, entries, archiveSize, centralOffset, handle, limits, signal, io) {
4954
- this.path = path19;
4953
+ constructor(path21, entries, archiveSize, centralOffset, handle, limits, signal, io) {
4954
+ this.path = path21;
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(path19, options = {}) {
4966
+ static async open(path21, 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(path19, "r");
4976
+ const handle = await open2(path21, "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(path19, entries, archiveSize, central.offset, handle, limits, options.signal, options.io);
4992
+ return new _BoundedZipArchive(path21, 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(stat12) {
5498
+ function projectStat(stat13) {
5499
5499
  return {
5500
- device: BigInt(stat12.dev),
5501
- inode: BigInt(stat12.ino),
5502
- mode: Number(stat12.mode) & 511,
5503
- regularFile: stat12.isFile()
5500
+ device: BigInt(stat13.dev),
5501
+ inode: BigInt(stat13.ino),
5502
+ mode: Number(stat13.mode) & 511,
5503
+ regularFile: stat13.isFile()
5504
5504
  };
5505
5505
  }
5506
- function hasIdentity(stat12, expected) {
5507
- return stat12.device === expected.device && stat12.inode === expected.inode;
5506
+ function hasIdentity(stat13, expected) {
5507
+ return stat13.device === expected.device && stat13.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: (path19) => openSync2(path19, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0)),
5576
+ openNoFollow: (path21) => openSync2(path21, 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: (path19) => projectStat(lstatSync2(path19, { bigint: true })),
5579
+ statPathNoFollow: (path21) => projectStat(lstatSync2(path21, { 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(stat12, expected) {
5591
- return stat12.isFile() && stat12.dev === expected.device && stat12.ino === expected.inode;
5590
+ function hasIdentity2(stat13, expected) {
5591
+ return stat13.isFile() && stat13.dev === expected.device && stat13.ino === expected.inode;
5592
5592
  }
5593
- function pathIdentityVerified(path19, expected, operations) {
5593
+ function pathIdentityVerified(path21, expected, operations) {
5594
5594
  try {
5595
- return hasIdentity2(operations.statPathNoFollow(path19), expected);
5595
+ return hasIdentity2(operations.statPathNoFollow(path21), 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: (path19) => unlinkSync2(path19),
5647
- statPathNoFollow: (path19) => lstatSync3(path19, { bigint: true })
5646
+ unlink: (path21) => unlinkSync2(path21),
5647
+ statPathNoFollow: (path21) => lstatSync3(path21, { 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(stat12, expected) {
5658
- return stat12.isFile() && stat12.dev === expected.device && stat12.ino === expected.inode;
5657
+ function hasIdentity3(stat13, expected) {
5658
+ return stat13.isFile() && stat13.dev === expected.device && stat13.ino === expected.inode;
5659
5659
  }
5660
- function cleanupError(path19, cause, identityVerified = true) {
5661
- const error = new TemporaryArtifactCleanupError(identityVerified ? [path19] : [], identityVerified ? [] : [path19]);
5660
+ function cleanupError(path21, cause, identityVerified = true) {
5661
+ const error = new TemporaryArtifactCleanupError(identityVerified ? [path21] : [], identityVerified ? [] : [path21]);
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: (path19) => unlinkSync3(path19),
5710
- statPathNoFollow: (path19) => lstatSync4(path19, { bigint: true })
5709
+ unlink: (path21) => unlinkSync3(path21),
5710
+ statPathNoFollow: (path21) => lstatSync4(path21, { 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 homedir11 } from "node:os";
5764
+ import { homedir as homedir12 } 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(homedir11(), "cursor-history-backups");
5804
+ return join8(homedir12(), "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 stat12 = statSync3(globalDbPath);
5824
+ const stat13 = statSync3(globalDbPath);
5825
5825
  files.push({
5826
5826
  absolutePath: globalDbPath,
5827
5827
  relativePath: "globalStorage/state.vscdb",
5828
- size: stat12.size,
5828
+ size: stat13.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 stat12 = statSync3(workspaceDbPath);
5841
+ const stat13 = statSync3(workspaceDbPath);
5842
5842
  files.push({
5843
5843
  absolutePath: workspaceDbPath,
5844
5844
  relativePath: `workspaceStorage/${entry.name}/state.vscdb`,
5845
- size: stat12.size,
5845
+ size: stat13.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 stat12 = statSync3(workspaceJsonPath);
5852
+ const stat13 = statSync3(workspaceJsonPath);
5853
5853
  files.push({
5854
5854
  absolutePath: workspaceJsonPath,
5855
5855
  relativePath: `workspaceStorage/${entry.name}/workspace.json`,
5856
- size: stat12.size,
5856
+ size: stat13.size,
5857
5857
  type: "workspace-json",
5858
5858
  workspaceId: entry.name
5859
5859
  });
@@ -5866,11 +5866,11 @@ function scanDatabaseFiles(dataPath2) {
5866
5866
  return files;
5867
5867
  }
5868
5868
  function createManifest(files, stats, composerWorkspaceInventory) {
5869
- const platform4 = process.platform;
5869
+ const platform5 = process.platform;
5870
5870
  return {
5871
5871
  version: MANIFEST_VERSION,
5872
5872
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
5873
- sourcePlatform: platform4,
5873
+ sourcePlatform: platform5,
5874
5874
  producer: PACKAGE_VERSION,
5875
5875
  cursorHistoryVersion: PACKAGE_VERSION,
5876
5876
  files,
@@ -6075,12 +6075,12 @@ function checkDiskSpace(outputPath, requiredBytes) {
6075
6075
  };
6076
6076
  }
6077
6077
  }
6078
- function syncParentDirectory(path19) {
6078
+ function syncParentDirectory(path21) {
6079
6079
  if (process.platform === "win32")
6080
6080
  return;
6081
6081
  let descriptor;
6082
6082
  try {
6083
- descriptor = openSync3(dirname4(path19), constants3.O_RDONLY);
6083
+ descriptor = openSync3(dirname4(path21), constants3.O_RDONLY);
6084
6084
  fsyncSync2(descriptor);
6085
6085
  } catch {
6086
6086
  } finally {
@@ -6092,13 +6092,13 @@ function syncParentDirectory(path19) {
6092
6092
  }
6093
6093
  }
6094
6094
  }
6095
- function removePrivateArchiveStage(path19, operationError) {
6095
+ function removePrivateArchiveStage(path21, operationError) {
6096
6096
  try {
6097
- unlinkSync4(path19);
6097
+ unlinkSync4(path21);
6098
6098
  } catch (error) {
6099
6099
  if (errorCode3(error) === "ENOENT")
6100
6100
  return;
6101
- const cleanupError2 = new TemporaryArtifactCleanupError([path19]);
6101
+ const cleanupError2 = new TemporaryArtifactCleanupError([path21]);
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((path19) => !unverifiedResidueSet.has(path19));
6365
+ ].filter((path21) => !unverifiedResidueSet.has(path21));
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 path19 = entry["path"];
6474
- const expectedType = backupEntryTypeForCanonicalPath(path19);
6473
+ const path21 = entry["path"];
6474
+ const expectedType = backupEntryTypeForCanonicalPath(path21);
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 = path19.normalize("NFC").toLowerCase();
6478
+ const destinationKey = path21.normalize("NFC").toLowerCase();
6479
6479
  if (destinationKeys.has(destinationKey)) {
6480
- throw new ZipArchiveFormatError(`Backup manifest contains a duplicate restore destination: ${path19}`);
6480
+ throw new ZipArchiveFormatError(`Backup manifest contains a duplicate restore destination: ${path21}`);
6481
6481
  }
6482
6482
  destinationKeys.add(destinationKey);
6483
6483
  return {
6484
- path: path19,
6484
+ path: path21,
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(path19) {
6502
- if (path19 === "globalStorage/state.vscdb")
6501
+ function backupEntryTypeForCanonicalPath(path21) {
6502
+ if (path21 === "globalStorage/state.vscdb")
6503
6503
  return "global-db";
6504
- const match = /^workspaceStorage\/([^/]+)\/(state\.vscdb|workspace\.json)$/u.exec(path19);
6504
+ const match = /^workspaceStorage\/([^/]+)\/(state\.vscdb|workspace\.json)$/u.exec(path21);
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: 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");
6523
+ const expectedWorkspaceIds = files.filter(({ type }) => type === "workspace-db").map(({ path: path21 }) => /^workspaceStorage\/([^/]+)\/state\.vscdb$/u.exec(path21)?.[1]).filter((workspaceId) => workspaceId !== void 0).sort(compareCodePoints4);
6524
+ const containsGlobalDatabase = files.some(({ type, path: path21 }) => type === "global-db" && path21 === "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: path19 }) => path19 === dbPath);
6680
+ const manifestEntry = manifestFiles.find(({ path: path21 }) => path21 === 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: path19 }) => path19 === entryPath);
6735
+ const manifestEntry = validatedManifestFiles(manifest).find(({ path: path21 }) => path21 === 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(path19) {
6791
+ function lstatIfPresent(path21) {
6792
6792
  try {
6793
- return lstatSync5(path19);
6793
+ return lstatSync5(path21);
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, path19, leafKind) {
6800
+ function assertNoLinkedRestorePath(trustedRoot, path21, leafKind) {
6801
6801
  const absoluteRoot = resolve2(trustedRoot);
6802
- const absolutePath = resolve2(path19);
6802
+ const absolutePath = resolve2(path21);
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 stat12 = statSync3(filePath);
7106
+ const stat13 = statSync3(filePath);
7107
7107
  const info = {
7108
7108
  filePath,
7109
7109
  filename: entry.name,
7110
- fileSize: stat12.size,
7111
- modifiedAt: stat12.mtime
7110
+ fileSize: stat13.size,
7111
+ modifiedAt: stat13.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 = homedir11();
7135
+ const home = homedir12();
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(path19, options = {}) {
7764
+ async function parseStoreDb(path21, 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(path19, options.signal, options.io, options.logicalSessionId))
7768
+ if (!pathExists(path21, 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(path19, 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(path19, tmpPath, databaseRequest("store-snapshot", STORE_SNAPSHOT_CAPABILITIES, options.sqliteDriver, options, "store-database"));
7780
+ await backupDatabase(path21, 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(path19, options = {}) {
7824
7824
  operationError = error;
7825
7825
  else {
7826
7826
  options.onDiagnostic?.(error);
7827
- debugLogStorage(`store.db defensive parse failed for ${path19}: ${error.code}`);
7827
+ debugLogStorage(`store.db defensive parse failed for ${path21}: ${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 ${path19}: ${String(error)}`);
7832
+ debugLogStorage(`store.db source/schema parse failed for ${path21}: ${String(error)}`);
7833
7833
  } else {
7834
7834
  operationError = error;
7835
7835
  }
@@ -7854,7 +7854,7 @@ async function parseStoreDb(path19, options = {}) {
7854
7854
  throw operationError;
7855
7855
  return result;
7856
7856
  }
7857
- function pathExists(path19, signal, io, logicalSessionId) {
7857
+ function pathExists(path21, signal, io, logicalSessionId) {
7858
7858
  throwIfAborted4(signal);
7859
7859
  try {
7860
7860
  if (io) {
@@ -7867,7 +7867,7 @@ function pathExists(path19, signal, io, logicalSessionId) {
7867
7867
  ...logicalSessionId ? { logicalSessionId } : {}
7868
7868
  });
7869
7869
  }
7870
- statSync4(path19);
7870
+ statSync4(path21);
7871
7871
  return true;
7872
7872
  } catch (error) {
7873
7873
  const code2 = error?.code;
@@ -8237,14 +8237,14 @@ function decodeMessageObject(data, outcome) {
8237
8237
  return direct;
8238
8238
  let offset = 0;
8239
8239
  while (offset < data.length) {
8240
- const tag = readVarint(data, offset);
8240
+ const tag = readVarint2(data, offset);
8241
8241
  if (!tag)
8242
8242
  return null;
8243
8243
  offset = tag.next;
8244
8244
  const field = tag.value >>> 3;
8245
8245
  const wire = tag.value & 7;
8246
8246
  if (wire === 0) {
8247
- const value = readVarint(data, offset);
8247
+ const value = readVarint2(data, offset);
8248
8248
  if (!value)
8249
8249
  return null;
8250
8250
  offset = value.next;
@@ -8260,7 +8260,7 @@ function decodeMessageObject(data, outcome) {
8260
8260
  }
8261
8261
  if (wire !== 2)
8262
8262
  return null;
8263
- const length = readVarint(data, offset);
8263
+ const length = readVarint2(data, offset);
8264
8264
  if (!length)
8265
8265
  return null;
8266
8266
  offset = length.next;
@@ -8290,7 +8290,7 @@ function parseLeafJson(data, outcome) {
8290
8290
  return null;
8291
8291
  }
8292
8292
  }
8293
- function readVarint(data, start) {
8293
+ function readVarint2(data, start) {
8294
8294
  let value = 0;
8295
8295
  let shift = 0;
8296
8296
  let offset = start;
@@ -8705,7 +8705,7 @@ function mapLine(parsed, sourceLine) {
8705
8705
  return { kind: "skip", rawContentBlocks };
8706
8706
  }
8707
8707
  const sourceRelationships = {};
8708
- const parent = firstString(obj["parentMessageId"], obj["parentId"], nestedRecord["parentMessageId"], nestedRecord["parentId"]);
8708
+ const parent = firstString2(obj["parentMessageId"], obj["parentId"], nestedRecord["parentMessageId"], nestedRecord["parentId"]);
8709
8709
  const sidechain = firstBoolean(obj["isSidechain"], nestedRecord["isSidechain"]);
8710
8710
  if (parent !== void 0)
8711
8711
  sourceRelationships["parentMessageId"] = parent;
@@ -8750,7 +8750,7 @@ function retainUnsupportedTranscriptValue(value) {
8750
8750
  const blocks = Array.isArray(value) ? value : [value];
8751
8751
  return blocks.map((block) => retainRawContentBlock(block, "unsupported", "transcript"));
8752
8752
  }
8753
- function firstString(...values) {
8753
+ function firstString2(...values) {
8754
8754
  return values.find((value) => typeof value === "string" && value.length > 0);
8755
8755
  }
8756
8756
  function firstBoolean(...values) {
@@ -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, path19) {
8839
- return `${representation}\0${path19}`;
8838
+ function occurrenceKey(representation, path21) {
8839
+ return `${representation}\0${path21}`;
8840
8840
  }
8841
- function occurrence(logicalSessionId, representation, path19, workspacePath) {
8841
+ function occurrence(logicalSessionId, representation, path21, workspacePath) {
8842
8842
  return {
8843
- instanceKey: occurrenceKey(representation, path19),
8843
+ instanceKey: occurrenceKey(representation, path21),
8844
8844
  logicalSessionId,
8845
8845
  representation,
8846
- path: path19,
8846
+ path: path21,
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: path19 }) => path19 === nested)) {
9194
+ if (!evidence.transcriptOccurrences.some(({ path: path21 }) => path21 === 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: path19 }) => path19 === transcriptPath)) {
9211
+ if (!evidence.transcriptOccurrences.some(({ path: path21 }) => path21 === 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: path19 }) => path19 === ss.storeDbPath) ?? dbCandidates[0];
9285
+ let selectedDbCandidate = selectedDbTier[0] ?? dbCandidates.find(({ path: path21 }) => path21 === 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: path19 }) => path19 === sessionDir)) {
9499
+ if (!evidence.metadataOccurrences.some(({ path: path21 }) => path21 === sessionDir)) {
9500
9500
  evidence.metadataOccurrences.push(metadataOccurrence);
9501
9501
  }
9502
9502
  if (dbInventoried) {
9503
9503
  evidence.dbInventoried = true;
9504
- if (!evidence.dbOccurrences.some(({ path: path19 }) => path19 === dbPath)) {
9504
+ if (!evidence.dbOccurrences.some(({ path: path21 }) => path21 === 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(path19, signal, io, logicalSessionId, includeDisplayMetadata = true) {
9750
+ function readMeta(path21, 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(path19);
9755
+ raw = readFileSync10(path21);
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(path19, signal, io, resourceClass = "store-root-directory", logicalSessionId) {
9886
+ function pathExists2(path21, signal, io, resourceClass = "store-root-directory", logicalSessionId) {
9887
9887
  throwIfAborted6(signal);
9888
9888
  try {
9889
9889
  observeStoreFs(io, "open", resourceClass, logicalSessionId);
9890
- statSync5(path19);
9890
+ statSync5(path21);
9891
9891
  return true;
9892
9892
  } catch (error) {
9893
9893
  if (isAbsentOrWrongType(error))
@@ -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: path19 }) => type === "global-db" && path19 === "globalStorage/state.vscdb");
11518
+ const containsGlobalDatabase = manifest.files.some(({ type, path: path21 }) => type === "global-db" && path21 === "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]));
@@ -11565,7 +11565,7 @@ async function findWorkspacesFromBackup(backupPath, readOptions) {
11565
11565
  let legacyLinkedGlobalIds;
11566
11566
  if (!countedIds) {
11567
11567
  let db = null;
11568
- let readError3;
11568
+ let readError4;
11569
11569
  try {
11570
11570
  db = await openBackupDatabase(backupPath, workspace.dbPath, readOptions);
11571
11571
  throwIfReadAborted(readOptions.signal);
@@ -11584,18 +11584,18 @@ async function findWorkspacesFromBackup(backupPath, readOptions) {
11584
11584
  legacyLinkedGlobalIds = getWorkspaceComposerPointerIds(db, createComposerSqliteBudget(resolveSourceReadLimits(readOptions.sourceReadLimits)), readOptions.signal);
11585
11585
  }
11586
11586
  } catch (error) {
11587
- readError3 = error;
11587
+ readError4 = error;
11588
11588
  }
11589
11589
  if (db) {
11590
11590
  try {
11591
11591
  db.close();
11592
11592
  } catch (closeError) {
11593
- attachReadFailureCause(closeError, readError3);
11593
+ attachReadFailureCause(closeError, readError4);
11594
11594
  throw closeError;
11595
11595
  }
11596
11596
  }
11597
- if (readError3 !== void 0)
11598
- throw readError3;
11597
+ if (readError4 !== void 0)
11598
+ throw readError4;
11599
11599
  }
11600
11600
  const effectiveLinkedGlobalIds = [
11601
11601
  ...getBackupLinkedGlobalSessionIds(workspace) ?? legacyLinkedGlobalIds ?? []
@@ -12305,7 +12305,7 @@ async function getWorkspaceLinkedComposerIds(workspace, customDataPath) {
12305
12305
  return [];
12306
12306
  }
12307
12307
  let db = null;
12308
- let readError3;
12308
+ let readError4;
12309
12309
  try {
12310
12310
  db = await openDatabase2(globalDbPath);
12311
12311
  const tableCheck = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='cursorDiskKV'").get();
@@ -12350,12 +12350,12 @@ async function getWorkspaceLinkedComposerIds(workspace, customDataPath) {
12350
12350
  }
12351
12351
  return [...ids];
12352
12352
  } catch (error) {
12353
- readError3 = error;
12353
+ readError4 = error;
12354
12354
  if (shouldPropagateReadFailure(error))
12355
12355
  throw error;
12356
12356
  throwOwningDatabaseReadFailure(error);
12357
12357
  } finally {
12358
- closeDatabaseOrThrow(db, readError3);
12358
+ closeDatabaseOrThrow(db, readError4);
12359
12359
  }
12360
12360
  }
12361
12361
  function privateReadState(context) {
@@ -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 path19 = normalizeWorkspacePath(candidate.workspace.path);
12717
- counts2.set(path19, (counts2.get(path19) ?? 0) + 1);
12716
+ const path21 = normalizeWorkspacePath(candidate.workspace.path);
12717
+ counts2.set(path21, (counts2.get(path21) ?? 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: path19 }) => path19),
13409
+ ...composerWorkspaceInventory.map(({ path: path21 }) => path21),
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: path19 }) => !workspaceFilterMatches(path19, activeWorkspacePath));
13675
+ const offScopeWorkspaces = composerWorkspaceInventory.filter(({ path: path21 }) => !workspaceFilterMatches(path21, 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 path19 = getParam(params, "path", "directory", "targetDirectory");
14968
+ const path21 = getParam(params, "path", "directory", "targetDirectory");
14969
14969
  if (pattern)
14970
14970
  lines2.push(`Pattern: ${pattern}`);
14971
- if (path19)
14972
- lines2.push(`Path: ${path19}`);
14971
+ if (path21)
14972
+ lines2.push(`Path: ${path21}`);
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(path19, sourcePrefix, destPrefix) {
15477
+ function transformPath(path21, sourcePrefix, destPrefix) {
15478
15478
  const normalizedSource = sourcePrefix.replace(/\/+$/, "");
15479
- const normalizedPath = path19;
15479
+ const normalizedPath = path21;
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(path19) {
15596
- const normalized = normalizePath(path19);
15595
+ function toFileUri(path21) {
15596
+ const normalized = normalizePath(path21);
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, path19) {
15651
- const normalized = normalizedPathKey(path19);
15652
- if (!existsSync9(path19))
15650
+ function physicalPathIdentity(label, path21) {
15651
+ const normalized = normalizedPathKey(path21);
15652
+ if (!existsSync9(path21))
15653
15653
  return `${label}:${normalized}|missing`;
15654
15654
  try {
15655
- const stat12 = statSync6(path19);
15656
- return `${label}:${normalized}|dev:${String(stat12.dev)}|ino:${String(stat12.ino)}`;
15655
+ const stat13 = statSync6(path21);
15656
+ return `${label}:${normalized}|dev:${String(stat13.dev)}|ino:${String(stat13.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 path19 = readWorkspaceJson(workspaceDirectory);
15805
- if (!path19 || !pathsEqual(path19, normalizedRequest))
15804
+ const path21 = readWorkspaceJson(workspaceDirectory);
15805
+ if (!path21 || !pathsEqual(path21, normalizedRequest))
15806
15806
  continue;
15807
15807
  return {
15808
15808
  workspace: {
15809
15809
  id: entry.name,
15810
- path: normalizePath(path19),
15810
+ path: normalizePath(path21),
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 = (path19, objectIds) => {
15828
+ const scanIds = (path21, 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, '${path19}') AS j
15839
+ FROM ItemTable AS i, json_each(i.value, '${path21}') 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, '${path19}') AS j
15858
+ FROM ItemTable AS i, json_each(i.value, '${path21}') 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.");
@@ -19808,6 +19808,7 @@ var PHASES = [
19808
19808
  var PHASE_RULES_V1 = "phase-rules/v1";
19809
19809
  var UNKNOWN_GATE = 0.2;
19810
19810
  var HANDOFF_MARKERS = {
19811
+ antigravity: ["ask_question"],
19811
19812
  "claude-code": [
19812
19813
  "AskUserQuestion",
19813
19814
  "ExitPlanMode",
@@ -19851,7 +19852,14 @@ var SCOUT_TOOLS = [
19851
19852
  "search_tool",
19852
19853
  "search_files",
19853
19854
  "list_dir",
19854
- "read_file"
19855
+ "read_file",
19856
+ // Antigravity's read and search tools
19857
+ "view_file",
19858
+ "view_code_item",
19859
+ "grep_search",
19860
+ "find_by_name",
19861
+ "search_web",
19862
+ "read_url_content"
19855
19863
  ];
19856
19864
  var EDIT_TOOLS = [
19857
19865
  "Edit",
@@ -19864,7 +19872,8 @@ var EDIT_TOOLS = [
19864
19872
  "multiedit",
19865
19873
  "apply_patch",
19866
19874
  "write_file",
19867
- "edit_file"
19875
+ "edit_file",
19876
+ "replace_file_content"
19868
19877
  ];
19869
19878
  var REVIEW_SKILLS = ["code-review", "security-review", "review"];
19870
19879
  var SCOUT_AGENTS = ["Explore", "Plan", "research"];
@@ -19874,7 +19883,8 @@ var SHELL_TOOLS = [
19874
19883
  "shell",
19875
19884
  "local_shell",
19876
19885
  "exec_command",
19877
- "run_terminal_command"
19886
+ "run_terminal_command",
19887
+ "run_command"
19878
19888
  ];
19879
19889
  var SKILL_TOOLS = ["Skill", "skill"];
19880
19890
  var AGENT_TOOLS = ["Agent", "Task", "task", "agent"];
@@ -19888,7 +19898,12 @@ var BOOKKEEPING_TOOLS = [
19888
19898
  "Monitor",
19889
19899
  "SendUserFile",
19890
19900
  "SendMessage",
19891
- "ListAgents"
19901
+ "ListAgents",
19902
+ // Antigravity's task list and swarm coordination
19903
+ "manage_task",
19904
+ "read_board",
19905
+ "post_message",
19906
+ "swarm_wait"
19892
19907
  ];
19893
19908
  function isShell(tool) {
19894
19909
  return SHELL_TOOLS.includes(tool);
@@ -20341,13 +20356,13 @@ var KNOWN_ROW_IDS = /* @__PURE__ */ new Set([
20341
20356
  ]);
20342
20357
 
20343
20358
  // src/version.ts
20344
- var CLI_VERSION = true ? "0.21.0" : "0.0.0-dev";
20359
+ var CLI_VERSION = true ? "0.22.1" : "0.0.0-dev";
20345
20360
 
20346
20361
  // src/api.ts
20347
20362
  var BASE_URL = process.env.AISTACK_URL || "https://aistack.to";
20348
20363
  var STARTUP_READ_TIMEOUT_MS = 5e3;
20349
- async function request(path19, options = {}) {
20350
- return fetch(`${BASE_URL}${path19}`, {
20364
+ async function request(path21, options = {}) {
20365
+ return fetch(`${BASE_URL}${path21}`, {
20351
20366
  ...options,
20352
20367
  headers: {
20353
20368
  "Content-Type": "application/json",
@@ -20879,9 +20894,9 @@ function canonicalizeRepoUrl(input) {
20879
20894
  function repoNameFromCanonical(canonical) {
20880
20895
  return parseRepo(canonical)?.repo ?? "";
20881
20896
  }
20882
- function normalizeUpstreamPath(path19) {
20883
- if (!path19) return "";
20884
- return path19.split("/").filter(Boolean).join("/");
20897
+ function normalizeUpstreamPath(path21) {
20898
+ if (!path21) return "";
20899
+ return path21.split("/").filter(Boolean).join("/");
20885
20900
  }
20886
20901
 
20887
20902
  // src/git.ts
@@ -20927,16 +20942,16 @@ function buildRepoLinkResource(canonical) {
20927
20942
  import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
20928
20943
  import { homedir as homedir2 } from "node:os";
20929
20944
  import { join as join2 } from "node:path";
20930
- function readJson(path19) {
20945
+ function readJson(path21) {
20931
20946
  try {
20932
- if (!existsSync2(path19)) return null;
20933
- return JSON.parse(readFileSync2(path19, "utf-8"));
20947
+ if (!existsSync2(path21)) return null;
20948
+ return JSON.parse(readFileSync2(path21, "utf-8"));
20934
20949
  } catch {
20935
20950
  return null;
20936
20951
  }
20937
20952
  }
20938
- function hooksFrom(path19, source, out, seen) {
20939
- const hooks = readJson(path19)?.hooks;
20953
+ function hooksFrom(path21, source, out, seen) {
20954
+ const hooks = readJson(path21)?.hooks;
20940
20955
  if (!hooks || typeof hooks !== "object") return;
20941
20956
  for (const [event, config] of Object.entries(hooks)) {
20942
20957
  const stableKey = `hooks:${source}:${event}`;
@@ -21085,16 +21100,16 @@ function buildMcpResource(name, group, pkg) {
21085
21100
  pkg
21086
21101
  };
21087
21102
  }
21088
- function readText(path19) {
21103
+ function readText(path21) {
21089
21104
  try {
21090
- if (!existsSync3(path19)) return null;
21091
- return readFileSync3(path19, "utf-8");
21105
+ if (!existsSync3(path21)) return null;
21106
+ return readFileSync3(path21, "utf-8");
21092
21107
  } catch {
21093
21108
  return null;
21094
21109
  }
21095
21110
  }
21096
- function readParsed(path19, parse2) {
21097
- const raw = readText(path19);
21111
+ function readParsed(path21, parse2) {
21112
+ const raw = readText(path21);
21098
21113
  if (raw === null) return null;
21099
21114
  try {
21100
21115
  return parse2(raw);
@@ -21102,14 +21117,14 @@ function readParsed(path19, parse2) {
21102
21117
  return null;
21103
21118
  }
21104
21119
  }
21105
- function readJson2(path19) {
21106
- return readParsed(path19, JSON.parse);
21120
+ function readJson2(path21) {
21121
+ return readParsed(path21, JSON.parse);
21107
21122
  }
21108
- function readYaml(path19) {
21109
- return readParsed(path19, parseYaml);
21123
+ function readYaml(path21) {
21124
+ return readParsed(path21, parseYaml);
21110
21125
  }
21111
- function readToml(path19) {
21112
- return readParsed(path19, parseToml);
21126
+ function readToml(path21) {
21127
+ return readParsed(path21, parseToml);
21113
21128
  }
21114
21129
  function continueListToMap(file) {
21115
21130
  if (!file?.mcpServers?.length) return void 0;
@@ -21248,8 +21263,8 @@ function resolveSource(entry, mpRepoUrl) {
21248
21263
  const src = entry.source;
21249
21264
  if (typeof src === "string") {
21250
21265
  if (!mpRepoUrl) return null;
21251
- const path19 = src.replace(/^\.\//, "").replace(/\/+$/, "");
21252
- return { url: mpRepoUrl, path: path19 || void 0 };
21266
+ const path21 = src.replace(/^\.\//, "").replace(/\/+$/, "");
21267
+ return { url: mpRepoUrl, path: path21 || void 0 };
21253
21268
  }
21254
21269
  if (src && typeof src === "object" && src.url) {
21255
21270
  return { url: src.url, path: src.path, sha: src.sha };
@@ -21286,10 +21301,10 @@ function resolvePluginLinks(installed, marketplaces, manifests) {
21286
21301
  }
21287
21302
  return out;
21288
21303
  }
21289
- function readJson3(path19) {
21304
+ function readJson3(path21) {
21290
21305
  try {
21291
- if (!existsSync4(path19)) return null;
21292
- return JSON.parse(readFileSync4(path19, "utf-8"));
21306
+ if (!existsSync4(path21)) return null;
21307
+ return JSON.parse(readFileSync4(path21, "utf-8"));
21293
21308
  } catch {
21294
21309
  return null;
21295
21310
  }
@@ -21378,8 +21393,8 @@ function loadGitignore(cwd) {
21378
21393
  }
21379
21394
  function readFileSafe(filePath) {
21380
21395
  try {
21381
- const stat12 = statSync(filePath);
21382
- if (stat12.size > MAX_FILE_SIZE) return null;
21396
+ const stat13 = statSync(filePath);
21397
+ if (stat13.size > MAX_FILE_SIZE) return null;
21383
21398
  return readFileSync5(filePath, "utf-8");
21384
21399
  } catch {
21385
21400
  return null;
@@ -21923,9 +21938,9 @@ function diffResources(current, existing) {
21923
21938
  // src/commands/connect.ts
21924
21939
  import { spawnSync } from "node:child_process";
21925
21940
  import { cpSync, existsSync as existsSync11 } from "node:fs";
21926
- import { homedir as homedir19 } from "node:os";
21941
+ import { homedir as homedir20 } from "node:os";
21927
21942
  import { dirname as dirname5, join as join13 } from "node:path";
21928
- import { fileURLToPath } from "node:url";
21943
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
21929
21944
  import * as p3 from "@clack/prompts";
21930
21945
 
21931
21946
  // src/trace.ts
@@ -22062,6 +22077,9 @@ function traceEnvironment(facts) {
22062
22077
  );
22063
22078
  }
22064
22079
 
22080
+ // src/harness/antigravity/analyzer.ts
22081
+ import { fileURLToPath } from "node:url";
22082
+
22065
22083
  // src/harness/shared/aggregate.ts
22066
22084
  var asObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : null;
22067
22085
  var asStr = (v) => typeof v === "string" && v.length > 0 ? v : null;
@@ -22679,41 +22697,6 @@ function filterAtoms(atoms, sets) {
22679
22697
  return { allowed, keptPrivate, withheld: keptPrivate.length };
22680
22698
  }
22681
22699
 
22682
- // src/harness/shared/recency.ts
22683
- import { readdir, stat } from "node:fs/promises";
22684
- import path from "node:path";
22685
- async function hasRecentFile(roots, matches, sinceMs, opts = {}) {
22686
- const readDir = opts.readdirImpl ?? ((dir) => readdir(dir, { withFileTypes: true }));
22687
- const statFile = opts.statImpl ?? stat;
22688
- const seen = /* @__PURE__ */ new Set();
22689
- const pending = [...roots];
22690
- while (pending.length > 0) {
22691
- const dir = pending.pop();
22692
- if (seen.has(dir)) continue;
22693
- seen.add(dir);
22694
- let entries;
22695
- try {
22696
- entries = await readDir(dir);
22697
- } catch {
22698
- continue;
22699
- }
22700
- for (const e of entries) {
22701
- const full = path.join(dir, e.name);
22702
- if (e.isDirectory()) {
22703
- pending.push(full);
22704
- continue;
22705
- }
22706
- if (!e.isFile() || !matches(e.name)) continue;
22707
- try {
22708
- const st = await statFile(full);
22709
- if (st.mtimeMs >= sinceMs) return true;
22710
- } catch {
22711
- }
22712
- }
22713
- }
22714
- return false;
22715
- }
22716
-
22717
22700
  // src/harness/shared/window.ts
22718
22701
  var DEFAULT_WINDOW_DAYS = 30;
22719
22702
  function windowStartMs(now, days) {
@@ -23251,7 +23234,9 @@ function createHarnessWorkflowReducer(harness, localSources = createWorkflowLoca
23251
23234
  const cells = eventCells.get(date) ?? /* @__PURE__ */ new Map();
23252
23235
  bump2(cells, `${at.getUTCDay()}:${at.getUTCHours()}`);
23253
23236
  eventCells.set(date, cells);
23254
- if (["WebSearch", "web_search", "websearch"].includes(observation.tool))
23237
+ if (["WebSearch", "web_search", "websearch", "search_web"].includes(
23238
+ observation.tool
23239
+ ))
23255
23240
  bump2(webSearchesByDate, date);
23256
23241
  } else if (observation.type === "response") {
23257
23242
  const responseId = observation.responseId ?? `anonymous:${state.nextAnonymousResponse++}`;
@@ -23594,7 +23579,7 @@ function createHarnessWorkflowReducer(harness, localSources = createWorkflowLoca
23594
23579
  0
23595
23580
  );
23596
23581
  const unknown = attributed === 0 ? 0 : windowPhaseSec.unknown / attributed;
23597
- const routesModels = harness === "claude-code" || harness === "opencode" || harness === "grok-build" || harness === "cursor";
23582
+ const routesModels = harness === "claude-code" || harness === "opencode" || harness === "grok-build" || harness === "cursor" || harness === "antigravity";
23598
23583
  const asRows = (map) => {
23599
23584
  const safe = /* @__PURE__ */ new Map();
23600
23585
  for (const [model, tokens] of map) {
@@ -23740,162 +23725,920 @@ function createHarnessWorkflowReducer(harness, localSources = createWorkflowLoca
23740
23725
  };
23741
23726
  }
23742
23727
 
23743
- // src/harness/claude/analyzer.ts
23728
+ // src/harness/antigravity/wire.ts
23729
+ var WireError = class extends Error {
23730
+ code = "wire-malformed";
23731
+ };
23732
+ function readVarint(buf, at) {
23733
+ let value = 0;
23734
+ let scale = 1;
23735
+ for (let i = 0; i < 10; i++) {
23736
+ if (at + i >= buf.length) throw new WireError("truncated varint");
23737
+ const byte = buf[at + i];
23738
+ value += (byte & 127) * scale;
23739
+ scale *= 128;
23740
+ if (byte < 128) return [value, at + i + 1];
23741
+ }
23742
+ throw new WireError("varint too long");
23743
+ }
23744
+ function decodeMessage(buf) {
23745
+ const fields = /* @__PURE__ */ new Map();
23746
+ let at = 0;
23747
+ while (at < buf.length) {
23748
+ const [key2, next] = readVarint(buf, at);
23749
+ at = next;
23750
+ const field = Math.floor(key2 / 8);
23751
+ const wireType = key2 % 8;
23752
+ if (field === 0) throw new WireError("field number 0");
23753
+ let value = null;
23754
+ if (wireType === 0) {
23755
+ [value, at] = readVarint(buf, at);
23756
+ } else if (wireType === 2) {
23757
+ const [length, start] = readVarint(buf, at);
23758
+ if (start + length > buf.length) throw new WireError("truncated bytes");
23759
+ value = buf.subarray(start, start + length);
23760
+ at = start + length;
23761
+ } else if (wireType === 1 || wireType === 5) {
23762
+ const width = wireType === 1 ? 8 : 4;
23763
+ if (at + width > buf.length) throw new WireError("truncated fixed");
23764
+ at += width;
23765
+ } else {
23766
+ throw new WireError(`unsupported wire type ${wireType}`);
23767
+ }
23768
+ if (value === null) continue;
23769
+ const list = fields.get(field);
23770
+ if (list) list.push(value);
23771
+ else fields.set(field, [value]);
23772
+ }
23773
+ return fields;
23774
+ }
23775
+ function firstUint(fields, field) {
23776
+ const value = fields.get(field)?.find((v) => typeof v === "number");
23777
+ return typeof value === "number" ? value : null;
23778
+ }
23779
+ function firstBytes(fields, field) {
23780
+ const value = fields.get(field)?.find((v) => v instanceof Uint8Array);
23781
+ return value instanceof Uint8Array ? value : null;
23782
+ }
23783
+ var utf8 = new TextDecoder("utf-8", { fatal: false });
23784
+ function firstString(fields, field) {
23785
+ const bytes = firstBytes(fields, field);
23786
+ if (!bytes || bytes.length === 0) return null;
23787
+ return utf8.decode(bytes);
23788
+ }
23789
+ function firstMessage(fields, field) {
23790
+ const bytes = firstBytes(fields, field);
23791
+ return bytes ? decodeMessage(bytes) : null;
23792
+ }
23793
+ function timestampMs(buf) {
23794
+ if (buf === null) return null;
23795
+ const fields = buf instanceof Map ? buf : decodeMessage(buf);
23796
+ const seconds2 = firstUint(fields, 1);
23797
+ if (seconds2 === null || seconds2 === 0) return null;
23798
+ const nanos = firstUint(fields, 2) ?? 0;
23799
+ return seconds2 * 1e3 + Math.floor(nanos / 1e6);
23800
+ }
23801
+
23802
+ // src/harness/antigravity/analyzer.ts
23803
+ var ANTIGRAVITY_BUILTIN_TOOLS = /* @__PURE__ */ new Set([
23804
+ "ask_question",
23805
+ "browser_subagent",
23806
+ "command_status",
23807
+ "edit_file",
23808
+ "find_by_name",
23809
+ "generate_image",
23810
+ "grep_search",
23811
+ "list_dir",
23812
+ "list_permissions",
23813
+ "manage_task",
23814
+ "notify_user",
23815
+ "post_message",
23816
+ "read_board",
23817
+ "read_file",
23818
+ "read_url_content",
23819
+ "replace_file_content",
23820
+ "run_command",
23821
+ "schedule",
23822
+ "search_web",
23823
+ "send_command_input",
23824
+ "swarm",
23825
+ "swarm_wait",
23826
+ "task_boundary",
23827
+ "view_code_item",
23828
+ "view_file",
23829
+ "write_file"
23830
+ ]);
23831
+ var STEP_USER_INPUT = 14;
23832
+ var STEP_CHECKPOINT = 23;
23833
+ var GOOGLE_API_PROVIDERS = /* @__PURE__ */ new Set([
23834
+ 3,
23835
+ // API_PROVIDER_GOOGLE_VERTEX
23836
+ 24,
23837
+ // API_PROVIDER_GOOGLE_GEMINI
23838
+ 26,
23839
+ // API_PROVIDER_ANTHROPIC_VERTEX
23840
+ 30,
23841
+ // API_PROVIDER_GOOGLE_EVERGREEN
23842
+ 31,
23843
+ // API_PROVIDER_OPENAI_VERTEX
23844
+ 32
23845
+ // API_PROVIDER_OPENAI_RESPONSES_VERTEX
23846
+ ]);
23744
23847
  function createAggregate2() {
23745
23848
  const workflowLocal = createWorkflowLocalSources();
23746
23849
  return Object.assign(createAggregate(), {
23747
- recordUuids: /* @__PURE__ */ new Set(),
23748
- workflow: createHarnessWorkflowReducer("claude-code", workflowLocal),
23749
- workflowLocal,
23750
- workflowSeenCalls: /* @__PURE__ */ new Set(),
23751
- workflowSeenTurns: /* @__PURE__ */ new Set(),
23752
- contextFirstCall: /* @__PURE__ */ new Map(),
23753
- workflowToolNames: /* @__PURE__ */ new Map(),
23754
- typedCommands: /* @__PURE__ */ new Map()
23850
+ workflow: createHarnessWorkflowReducer("antigravity", workflowLocal),
23851
+ workflowLocal
23755
23852
  });
23756
23853
  }
23757
- function workflowSessionKey(rec) {
23758
- const baseSession = asStr(rec.sessionId);
23759
- if (!baseSession) return null;
23760
- if (rec.isSidechain !== true) return baseSession;
23761
- return `${baseSession}:agent:${asStr(rec.agentId) ?? "unknown"}`;
23762
- }
23763
- function isApiCall(rec) {
23764
- if (asStr(rec.type) !== "assistant") return false;
23765
- const msg = asObj(rec.message);
23766
- if (!msg || !asObj(msg.usage)) return false;
23767
- return !(asName(msg.model) ?? "").startsWith("<");
23768
- }
23769
- function noteRecordBeforeWindow(agg, raw) {
23770
- const rec = asObj(raw);
23771
- if (!rec || !isApiCall(rec)) return;
23772
- const session = workflowSessionKey(rec);
23773
- if (session && !agg.contextFirstCall.has(session)) {
23774
- agg.contextFirstCall.set(session, null);
23854
+ var asBytes = (v) => v instanceof Uint8Array && v.length > 0 ? v : null;
23855
+ var asInt = (v) => {
23856
+ if (typeof v === "number" && Number.isInteger(v)) return v;
23857
+ if (typeof v === "bigint") return Number(v);
23858
+ return null;
23859
+ };
23860
+ function workspaceOf(trajectory) {
23861
+ const workspace = firstMessage(trajectory, 1);
23862
+ const uri = (workspace && firstString(workspace, 1)) ?? firstString(trajectory, 7);
23863
+ if (!uri?.startsWith("file:")) return null;
23864
+ try {
23865
+ return fileURLToPath(uri);
23866
+ } catch {
23867
+ return null;
23775
23868
  }
23776
23869
  }
23777
- function projectWorkspaceDirectory(raw) {
23778
- const rec = asObj(raw);
23779
- return rec ? asStr(rec.cwd) : null;
23780
- }
23781
- function ingestRecord(agg, raw, ctx) {
23782
- const rec = asObj(raw);
23783
- if (!rec) return;
23784
- const uuid = asStr(rec.uuid);
23785
- if (uuid) {
23786
- if (agg.recordUuids.has(uuid)) return;
23787
- agg.recordUuids.add(uuid);
23870
+ function commandOf(argumentsJson) {
23871
+ if (!argumentsJson) return "";
23872
+ try {
23873
+ const args = JSON.parse(argumentsJson);
23874
+ const command = args?.CommandLine;
23875
+ return typeof command === "string" ? command : "";
23876
+ } catch {
23877
+ return "";
23788
23878
  }
23789
- agg.records++;
23790
- const projectDir = projectWorkspaceDirectory(rec) ?? ctx.projectDir;
23791
- const version = asStr(rec.version);
23792
- if (version) agg.ccVersions.add(cleanName(version));
23793
- const sessionId = asStr(rec.sessionId);
23794
- if (sessionId) agg.sessions.add(sessionId);
23795
- let tsMs = null;
23796
- const timestamp2 = asStr(rec.timestamp);
23797
- if (timestamp2) {
23798
- const ts = Date.parse(timestamp2);
23799
- if (!Number.isNaN(ts)) {
23800
- tsMs = ts;
23801
- agg.activeDays.add(timestamp2.slice(0, 10));
23802
- agg.firstTs = agg.firstTs === null ? ts : Math.min(agg.firstTs, ts);
23803
- agg.lastTs = agg.lastTs === null ? ts : Math.max(agg.lastTs, ts);
23879
+ }
23880
+ function decodeConversation(raw) {
23881
+ let parseErrors = 0;
23882
+ const cascadeId = typeof raw.cascadeId === "string" && raw.cascadeId ? raw.cascadeId : null;
23883
+ let parentId = null;
23884
+ let workspace = null;
23885
+ const trajectoryBytes = asBytes(raw.trajectory);
23886
+ if (trajectoryBytes) {
23887
+ try {
23888
+ const trajectory = decodeMessage(trajectoryBytes);
23889
+ parentId = firstString(trajectory, 5);
23890
+ workspace = workspaceOf(trajectory);
23891
+ } catch {
23892
+ parseErrors++;
23804
23893
  }
23805
23894
  }
23806
- if (sessionId) noteSessionStart(agg, sessionId, tsMs);
23807
- if (projectDir !== void 0) {
23808
- agg.projectDirs.add(projectDir);
23895
+ const gens = /* @__PURE__ */ new Map();
23896
+ const modelNames = /* @__PURE__ */ new Map();
23897
+ for (const row of raw.gens) {
23898
+ const idx = asInt(row.idx);
23899
+ const data = asBytes(row.data);
23900
+ if (idx === null || data === null) continue;
23901
+ try {
23902
+ const chat = firstMessage(decodeMessage(data), 1);
23903
+ if (!chat) continue;
23904
+ const modelEnum = firstUint(chat, 3);
23905
+ const name = firstString(chat, 19);
23906
+ gens.set(idx, { modelEnum, name });
23907
+ if (modelEnum !== null && name) modelNames.set(modelEnum, name);
23908
+ } catch {
23909
+ parseErrors++;
23910
+ }
23809
23911
  }
23810
- noteProjectDay(agg, projectDir, tsMs);
23811
- const type = asStr(rec.type);
23812
- if (type === "assistant") {
23813
- ingestClaudeWorkflow(agg, rec, ctx, tsMs);
23814
- ingestAssistant(agg, rec, tsMs);
23815
- } else if (type === "user") {
23816
- ingestUser(agg, rec);
23817
- ingestClaudeToolResults(agg, rec, ctx, tsMs);
23818
- } else if (type === "system") {
23819
- ingestClaudeTurnDuration(agg, rec, ctx, tsMs);
23820
- ingestClaudeCompaction(agg, rec, ctx, tsMs);
23912
+ const id = cascadeId ?? "";
23913
+ const responses = [];
23914
+ const tools = [];
23915
+ const userTurns = [];
23916
+ for (const row of raw.steps) {
23917
+ const idx = asInt(row.idx);
23918
+ const metadata = asBytes(row.metadata);
23919
+ if (idx === null || metadata === null) continue;
23920
+ let step;
23921
+ try {
23922
+ step = decodeMessage(metadata);
23923
+ } catch {
23924
+ parseErrors++;
23925
+ continue;
23926
+ }
23927
+ try {
23928
+ const tsMs = timestampMs(firstMessage(step, 1));
23929
+ if (tsMs === null) continue;
23930
+ const key2 = `${id}:${idx}`;
23931
+ const stepType = asInt(row.stepType);
23932
+ if (stepType === STEP_USER_INPUT) userTurns.push({ key: key2, tsMs });
23933
+ const usageBytes = firstBytes(step, 9);
23934
+ if (usageBytes) {
23935
+ const usage = decodeMessage(usageBytes);
23936
+ const modelEnum = firstUint(usage, 1);
23937
+ const info = firstMessage(step, 20);
23938
+ const gen = gens.get((info && firstUint(info, 3)) ?? 0);
23939
+ responses.push({
23940
+ key: key2,
23941
+ tsMs,
23942
+ finishedMs: timestampMs(firstMessage(step, 7)) ?? timestampMs(firstMessage(step, 8)),
23943
+ modelEnum,
23944
+ modelName: gen?.name && gen.modelEnum === modelEnum ? gen.name : null,
23945
+ apiProvider: firstUint(usage, 6),
23946
+ input: firstUint(usage, 2) ?? 0,
23947
+ output: firstUint(usage, 3) ?? 0,
23948
+ cacheWrite: firstUint(usage, 4) ?? 0,
23949
+ cacheRead: firstUint(usage, 5) ?? 0,
23950
+ thinking: firstUint(usage, 9),
23951
+ checkpoint: stepType === STEP_CHECKPOINT
23952
+ });
23953
+ }
23954
+ const toolCall2 = firstMessage(step, 4);
23955
+ const name = toolCall2 && firstString(toolCall2, 2);
23956
+ if (toolCall2 && name) {
23957
+ tools.push({
23958
+ key: key2,
23959
+ tsMs,
23960
+ name: cleanName(name),
23961
+ command: name === "run_command" ? commandOf(firstString(toolCall2, 3)) : ""
23962
+ });
23963
+ }
23964
+ } catch {
23965
+ parseErrors++;
23966
+ }
23821
23967
  }
23968
+ return {
23969
+ id,
23970
+ parentId,
23971
+ workspace,
23972
+ responses,
23973
+ tools,
23974
+ userTurns,
23975
+ modelNames,
23976
+ parseErrors
23977
+ };
23822
23978
  }
23823
- function ingestClaudeCompaction(agg, rec, ctx, tsMs) {
23824
- if (tsMs === null || asStr(rec.subtype) !== "compact_boundary") return;
23825
- const session = workflowSessionKey(rec);
23826
- if (!session) return;
23827
- agg.workflow.ingest({
23828
- type: "compaction",
23829
- session,
23830
- projectWorkspace: projectWorkspaceDirectory(rec) ?? ctx.projectDir,
23831
- tsMs,
23832
- ...rec.isSidechain === true ? { sidechain: true } : {}
23833
- });
23834
- }
23835
- function contextOf(counts2) {
23836
- return counts2.input + counts2.cacheWrite5m + counts2.cacheWrite1h + counts2.cacheWriteUnsplit + counts2.cacheRead;
23837
- }
23838
- function ingestClaudeTurnDuration(agg, rec, ctx, tsMs) {
23839
- if (tsMs === null || asStr(rec.subtype) !== "turn_duration" || asNum(rec.durationMs) <= 0) {
23840
- return;
23841
- }
23842
- const session = asStr(rec.sessionId);
23843
- if (!session) return;
23844
- agg.workflow.ingest({
23845
- type: "response",
23846
- session,
23847
- projectWorkspace: projectWorkspaceDirectory(rec) ?? ctx.projectDir,
23848
- tsMs,
23849
- ...asStr(rec.uuid) ? { responseId: `duration:${asStr(rec.uuid)}` } : {},
23850
- durationSec: asNum(rec.durationMs) / 1e3
23851
- });
23979
+ function createFoldState() {
23980
+ return { seen: /* @__PURE__ */ new Set() };
23981
+ }
23982
+ function foldConversations(agg, state, conversations, sinceMs) {
23983
+ const modelNames = /* @__PURE__ */ new Map();
23984
+ for (const c of conversations)
23985
+ for (const [modelEnum, name] of c.modelNames)
23986
+ if (!modelNames.has(modelEnum)) modelNames.set(modelEnum, name);
23987
+ for (const c of conversations)
23988
+ foldConversation(agg, state, c, modelNames, sinceMs);
23989
+ }
23990
+ function modelKeyOf(response, modelNames) {
23991
+ const name = response.modelName ?? (response.modelEnum === null ? null : modelNames.get(response.modelEnum));
23992
+ if (!name) return { key: "(unknown)" };
23993
+ const provider = response.apiProvider !== null && GOOGLE_API_PROVIDERS.has(response.apiProvider) ? "google" : "antigravity";
23994
+ const model = cleanName(name);
23995
+ return {
23996
+ key: normalizeModel(modelKeyFor(provider, model)),
23997
+ workflowModel: `${provider}:${model}`
23998
+ };
23852
23999
  }
23853
- function ingestClaudeWorkflow(agg, rec, ctx, tsMs) {
23854
- if (tsMs === null) return;
23855
- const baseSession = asStr(rec.sessionId);
23856
- const msg = asObj(rec.message);
23857
- if (!baseSession || !msg) return;
23858
- const projectWorkspace = projectWorkspaceDirectory(rec) ?? ctx.projectDir;
23859
- const sidechain = rec.isSidechain === true;
23860
- const agentId = asStr(rec.agentId);
23861
- const session = sidechain ? `${baseSession}:agent:${agentId ?? "unknown"}` : baseSession;
23862
- const parentSession = sidechain ? baseSession : void 0;
23863
- const usage = asObj(msg.usage);
23864
- const counts2 = usage ? readCounts(usage) : null;
23865
- const messageId = asStr(msg.id);
23866
- const newTurn = messageId ? !agg.workflowSeenTurns.has(messageId) : true;
23867
- if (messageId) agg.workflowSeenTurns.add(messageId);
23868
- const blocks = { thinking: 0, text: 0 };
23869
- for (const rawBlock of asArr(msg.content)) {
23870
- const block = asObj(rawBlock);
23871
- const kind = block ? asStr(block.type) : null;
23872
- if (kind === "thinking") blocks.thinking++;
23873
- else if (kind === "text") blocks.text++;
24000
+ function foldConversation(agg, state, c, modelNames, sinceMs) {
24001
+ agg.parseErrors += c.parseErrors;
24002
+ if (!c.id) return;
24003
+ const parentSession = c.parentId ?? void 0;
24004
+ const projectWorkspace = c.workspace ?? void 0;
24005
+ const fresh = (key2, tsMs) => {
24006
+ if (tsMs < sinceMs || state.seen.has(key2)) return false;
24007
+ state.seen.add(key2);
24008
+ return true;
24009
+ };
24010
+ const noteActivity3 = (tsMs) => {
24011
+ agg.sessions.add(c.id);
24012
+ noteSessionStart(agg, c.id, tsMs);
24013
+ agg.activeDays.add(new Date(tsMs).toISOString().slice(0, 10));
24014
+ agg.firstTs = agg.firstTs === null ? tsMs : Math.min(agg.firstTs, tsMs);
24015
+ agg.lastTs = agg.lastTs === null ? tsMs : Math.max(agg.lastTs, tsMs);
24016
+ if (c.workspace) {
24017
+ agg.projectDirs.add(c.workspace);
24018
+ noteProjectDay(agg, c.workspace, tsMs);
24019
+ }
24020
+ };
24021
+ for (const turn of c.userTurns) {
24022
+ if (!fresh(`turn:${turn.key}`, turn.tsMs)) continue;
24023
+ agg.records++;
24024
+ noteActivity3(turn.tsMs);
24025
+ agg.workflow.ingest({
24026
+ type: "turn",
24027
+ session: c.id,
24028
+ turnId: turn.key,
24029
+ projectWorkspace,
24030
+ parentSession,
24031
+ tsMs: turn.tsMs,
24032
+ questionBack: false
24033
+ });
23874
24034
  }
23875
- let context = null;
23876
- if (counts2 && isApiCall(rec)) {
23877
- const held = agg.contextFirstCall.get(session);
23878
- let first = false;
23879
- if (held === void 0) {
23880
- agg.contextFirstCall.set(session, messageId);
23881
- first = true;
23882
- } else if (held !== null && held === messageId) first = true;
23883
- context = {
23884
- contextTokens: contextOf(counts2),
23885
- inputTokens: counts2.input,
23886
- cacheReadTokens: counts2.cacheRead,
23887
- cacheWriteTokens: counts2.cacheWrite5m + counts2.cacheWrite1h + counts2.cacheWriteUnsplit,
23888
- // The TTL this call wrote under (v5): a subscription within plan
23889
- // usage writes the main conversation at one hour.
23890
- ...counts2.cacheWrite1h > 0 ? { cacheTtlSec: 3600 } : counts2.cacheWrite5m > 0 ? { cacheTtlSec: 300 } : {},
23891
- ...first ? {
23892
- firstCall: {
23893
- harnessTokens: counts2.cacheRead,
23894
- instructionsTokens: contextOf(counts2) - counts2.cacheRead
23895
- }
23896
- } : {}
24035
+ for (const r of c.responses) {
24036
+ if (!fresh(r.key, r.tsMs)) continue;
24037
+ agg.records++;
24038
+ agg.assistantRecords++;
24039
+ agg.distinctResponses++;
24040
+ noteActivity3(r.tsMs);
24041
+ const counts2 = {
24042
+ input: r.input,
24043
+ output: r.output,
24044
+ cacheWrite5m: 0,
24045
+ cacheWrite1h: 0,
24046
+ cacheWriteUnsplit: r.cacheWrite,
24047
+ cacheRead: r.cacheRead
23897
24048
  };
23898
- }
24049
+ const total = r.input + r.output + r.cacheWrite + r.cacheRead;
24050
+ if (parentSession) agg.sidechainTokens += total;
24051
+ else agg.mainTokens += total;
24052
+ const { key: key2, workflowModel } = modelKeyOf(r, modelNames);
24053
+ addModelUsage(agg, key2, counts2, apiEquivalentCost(key2, counts2, r.tsMs), 1, {
24054
+ tsMs: r.tsMs,
24055
+ sidechain: Boolean(parentSession)
24056
+ });
24057
+ agg.workflow.ingest({
24058
+ type: "response",
24059
+ session: c.id,
24060
+ responseId: r.key,
24061
+ projectWorkspace,
24062
+ parentSession,
24063
+ tsMs: r.tsMs,
24064
+ ...workflowModel ? { model: workflowModel } : {},
24065
+ ...r.thinking !== null ? { thinkingTokens: r.thinking } : {},
24066
+ responseTokens: r.output,
24067
+ routingTokens: total,
24068
+ contextTokens: r.input + r.cacheRead + r.cacheWrite,
24069
+ inputTokens: r.input,
24070
+ cacheReadTokens: r.cacheRead,
24071
+ cacheWriteTokens: r.cacheWrite,
24072
+ ...r.finishedMs !== null && r.finishedMs > r.tsMs ? { durationSec: (r.finishedMs - r.tsMs) / 1e3 } : {}
24073
+ });
24074
+ if (r.checkpoint)
24075
+ agg.workflow.ingest({
24076
+ type: "compaction",
24077
+ session: c.id,
24078
+ projectWorkspace,
24079
+ parentSession,
24080
+ tsMs: r.tsMs
24081
+ });
24082
+ }
24083
+ for (const t of c.tools) {
24084
+ if (!fresh(`tool:${t.key}`, t.tsMs)) continue;
24085
+ agg.records++;
24086
+ noteActivity3(t.tsMs);
24087
+ bump(agg.toolCalls, t.name);
24088
+ agg.workflow.ingest({
24089
+ type: "event",
24090
+ session: c.id,
24091
+ projectWorkspace,
24092
+ parentSession,
24093
+ tsMs: t.tsMs,
24094
+ tool: t.name,
24095
+ arg: t.command
24096
+ });
24097
+ if (t.name === "ask_question")
24098
+ agg.workflow.ingest({
24099
+ type: "turn",
24100
+ session: c.id,
24101
+ turnId: `question:${t.key}`,
24102
+ projectWorkspace,
24103
+ parentSession,
24104
+ tsMs: t.tsMs,
24105
+ questionBack: true
24106
+ });
24107
+ }
24108
+ }
24109
+
24110
+ // src/harness/antigravity/scan.ts
24111
+ import { readdir as readdir2, realpath as realpath2, stat as stat2 } from "node:fs/promises";
24112
+ import { homedir as homedir7 } from "node:os";
24113
+ import path2 from "node:path";
24114
+
24115
+ // src/harness/shared/homes.ts
24116
+ import {
24117
+ mkdir,
24118
+ readdir,
24119
+ readFile,
24120
+ realpath,
24121
+ stat,
24122
+ writeFile
24123
+ } from "node:fs/promises";
24124
+ import { homedir as homedir6 } from "node:os";
24125
+ import path from "node:path";
24126
+ async function discoverHomes(options) {
24127
+ let complete = true;
24128
+ const resolve3 = async (dir) => {
24129
+ try {
24130
+ const real = await realpath(dir);
24131
+ return (await stat(real)).isDirectory() ? real : null;
24132
+ } catch (error) {
24133
+ if (!absent(error)) {
24134
+ complete = false;
24135
+ traceError("harness home resolution", error, "warn");
24136
+ }
24137
+ return null;
24138
+ }
24139
+ };
24140
+ const named = [...options.defaults];
24141
+ for (const { parent, prefix } of options.siblings ?? []) {
24142
+ try {
24143
+ named.push(
24144
+ ...(await readdir(parent, { withFileTypes: true })).filter(
24145
+ (entry) => entry.name.startsWith(prefix) && (entry.isDirectory() || entry.isSymbolicLink())
24146
+ ).map((entry) => path.join(parent, entry.name)).sort()
24147
+ );
24148
+ } catch (error) {
24149
+ if (!absent(error)) {
24150
+ complete = false;
24151
+ traceError("harness home discovery", error, "warn");
24152
+ }
24153
+ }
24154
+ }
24155
+ const homes = [];
24156
+ const add = (real) => {
24157
+ if (real && !homes.includes(real)) homes.push(real);
24158
+ };
24159
+ for (const dir of named) add(await resolve3(dir));
24160
+ const found = new Set(homes);
24161
+ const remembered = options.remember ? await readRemembered(options.remember) : [];
24162
+ const fresh = [];
24163
+ for (const dir of (options.configured ?? []).filter((dir2) => Boolean(dir2?.trim())).map(expandHome)) {
24164
+ const real = await resolve3(dir);
24165
+ add(real);
24166
+ if (real && !found.has(real) && !remembered.includes(real))
24167
+ fresh.push(real);
24168
+ }
24169
+ for (const dir of remembered) add(await resolve3(dir));
24170
+ if (options.remember && fresh.length)
24171
+ await writeRemembered(options.remember, [...remembered, ...fresh]);
24172
+ return { homes, complete };
24173
+ }
24174
+ var rememberedFile = () => path.join(homedir6(), ".config", "aistack", "harness-homes.json");
24175
+ async function rememberedHomes(harness) {
24176
+ return readRemembered(harness);
24177
+ }
24178
+ async function rememberHome(harness, dir) {
24179
+ const list = await readRemembered(harness);
24180
+ if (list.includes(dir)) return false;
24181
+ if (!await writeRemembered(harness, [...list, dir]))
24182
+ throw new Error("Could not save the folder list");
24183
+ return true;
24184
+ }
24185
+ async function forgetHome(harness, dir) {
24186
+ const list = await readRemembered(harness);
24187
+ if (!list.includes(dir)) return false;
24188
+ if (!await writeRemembered(
24189
+ harness,
24190
+ list.filter((entry) => entry !== dir)
24191
+ ))
24192
+ throw new Error("Could not save the folder list");
24193
+ return true;
24194
+ }
24195
+ async function readRemembered(harness) {
24196
+ try {
24197
+ const parsed = JSON.parse(await readFile(rememberedFile(), "utf8"));
24198
+ const list = parsed?.[harness];
24199
+ return Array.isArray(list) ? list.filter((dir) => typeof dir === "string") : [];
24200
+ } catch (error) {
24201
+ if (!absent(error)) traceError("remembered harness homes", error, "warn");
24202
+ return [];
24203
+ }
24204
+ }
24205
+ async function writeRemembered(harness, dirs) {
24206
+ const file = rememberedFile();
24207
+ try {
24208
+ let all = {};
24209
+ try {
24210
+ const parsed = JSON.parse(await readFile(file, "utf8"));
24211
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
24212
+ all = parsed;
24213
+ } catch (error) {
24214
+ if (!absent(error)) throw error;
24215
+ }
24216
+ all[harness] = dirs;
24217
+ await mkdir(path.dirname(file), { recursive: true, mode: 448 });
24218
+ await writeFile(file, `${JSON.stringify(all, null, 2)}
24219
+ `, { mode: 384 });
24220
+ return true;
24221
+ } catch (error) {
24222
+ traceError("remembered harness homes", error, "warn");
24223
+ return false;
24224
+ }
24225
+ }
24226
+ function expandHome(dir) {
24227
+ const trimmed = dir.trim();
24228
+ return path.resolve(
24229
+ trimmed.startsWith("~/") ? path.join(homedir6(), trimmed.slice(2)) : trimmed
24230
+ );
24231
+ }
24232
+ function absent(error) {
24233
+ const code2 = error?.code;
24234
+ return code2 === "ENOENT" || code2 === "ENOTDIR";
24235
+ }
24236
+
24237
+ // src/harness/antigravity/scan.ts
24238
+ function geminiDirs() {
24239
+ const base = path2.join(homedir7(), ".gemini");
24240
+ const configured = process.env.ANTIGRAVITY_GEMINI_DIR?.trim();
24241
+ if (!configured) return [base];
24242
+ return [base, path2.resolve(homedir7(), configured)];
24243
+ }
24244
+ async function antigravityHomes() {
24245
+ const dirs = geminiDirs();
24246
+ const appDataDir = process.env.ANTIGRAVITY_APP_DATA_DIR?.trim();
24247
+ return discoverHomes({
24248
+ defaults: [path2.join(dirs[0], "antigravity-cli")],
24249
+ configured: appDataDir ? dirs.map((dir) => path2.resolve(dir, appDataDir)) : [],
24250
+ siblings: dirs.map((parent) => ({ parent, prefix: "antigravity" })),
24251
+ remember: "antigravity"
24252
+ });
24253
+ }
24254
+ async function storeFilesIn(home) {
24255
+ const dir = path2.join(home, "conversations");
24256
+ try {
24257
+ return (await readdir2(dir, { withFileTypes: true })).filter((e) => e.isFile()).flatMap((e) => {
24258
+ if (e.name.endsWith(".db"))
24259
+ return [{ file: path2.join(dir, e.name), kind: "db" }];
24260
+ if (e.name.endsWith(".pb"))
24261
+ return [{ file: path2.join(dir, e.name), kind: "encrypted" }];
24262
+ return [];
24263
+ }).sort((a, b) => a.file.localeCompare(b.file));
24264
+ } catch (error) {
24265
+ const code2 = error?.code;
24266
+ if (code2 !== "ENOENT" && code2 !== "ENOTDIR")
24267
+ traceError("antigravity conversation discovery", error, "warn");
24268
+ return [];
24269
+ }
24270
+ }
24271
+ async function storeFiles(homes) {
24272
+ const out = [];
24273
+ const seen = /* @__PURE__ */ new Set();
24274
+ for (const home of homes) {
24275
+ for (const store of await storeFilesIn(home)) {
24276
+ let key2 = store.file;
24277
+ try {
24278
+ key2 = await realpath2(store.file);
24279
+ } catch {
24280
+ }
24281
+ if (seen.has(key2)) continue;
24282
+ seen.add(key2);
24283
+ out.push(store);
24284
+ }
24285
+ }
24286
+ return out;
24287
+ }
24288
+ async function loadSqlite() {
24289
+ try {
24290
+ const mod = await import("node:sqlite");
24291
+ if (typeof mod.DatabaseSync !== "function") return null;
24292
+ return (file) => new mod.DatabaseSync(file, { readOnly: true });
24293
+ } catch (error) {
24294
+ traceError("antigravity SQLite initialization", error, "warn");
24295
+ return null;
24296
+ }
24297
+ }
24298
+ function errorClass(e) {
24299
+ const code2 = e?.code;
24300
+ if (typeof code2 === "string" && code2.length > 0) return code2;
24301
+ return e instanceof Error ? e.constructor.name : "unknown";
24302
+ }
24303
+ var readError = (reason) => Object.assign(new Error(reason), { code: reason });
24304
+ function closeQuietly(db) {
24305
+ try {
24306
+ db?.close();
24307
+ } catch {
24308
+ }
24309
+ }
24310
+ function readStore(db) {
24311
+ return {
24312
+ cascadeId: db.prepare("select cascade_id from trajectory_meta limit 1").get()?.cascade_id,
24313
+ trajectory: db.prepare(
24314
+ "select data from trajectory_metadata_blob order by id = 'main' desc limit 1"
24315
+ ).get()?.data,
24316
+ steps: db.prepare("select idx, step_type, metadata from steps order by idx").all().map((r) => ({
24317
+ idx: r.idx,
24318
+ stepType: r.step_type,
24319
+ metadata: r.metadata
24320
+ })),
24321
+ gens: db.prepare("select idx, data from gen_metadata order by idx").all().map((r) => ({ idx: r.idx, data: r.data }))
24322
+ };
24323
+ }
24324
+ function parseSummaryTime(value) {
24325
+ if (typeof value !== "string") return null;
24326
+ const m = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})?$/.exec(
24327
+ value.trim()
24328
+ );
24329
+ if (!m) return null;
24330
+ const ms = (m[3] ?? "").padEnd(3, "0").slice(0, 3);
24331
+ const parsed = Date.parse(`${m[1]}T${m[2]}.${ms}${m[4] ?? "Z"}`);
24332
+ return Number.isFinite(parsed) && parsed > Date.UTC(2e3, 0, 1) ? parsed : null;
24333
+ }
24334
+ function readConversationIndex(open4, homes) {
24335
+ const out = /* @__PURE__ */ new Map();
24336
+ for (const home of homes) {
24337
+ let db = null;
24338
+ try {
24339
+ db = open4(path2.join(home, "conversation_summaries.db"));
24340
+ for (const row of db.prepare(
24341
+ "select conversation_id, last_modified_time from conversation_summaries"
24342
+ ).all()) {
24343
+ const id = row.conversation_id;
24344
+ const at = parseSummaryTime(row.last_modified_time);
24345
+ if (typeof id !== "string" || at === null) continue;
24346
+ out.set(id, Math.max(out.get(id) ?? at, at));
24347
+ }
24348
+ } catch {
24349
+ } finally {
24350
+ closeQuietly(db);
24351
+ }
24352
+ }
24353
+ return out;
24354
+ }
24355
+ async function scan(agg, opts = {}) {
24356
+ const stats = emptyScanStats();
24357
+ const sinceMs = opts.sinceMs ?? 0;
24358
+ const discovery = opts.roots ? { homes: opts.roots, complete: true } : await antigravityHomes();
24359
+ if (!discovery.complete) stats.sourceDiscoveryComplete = false;
24360
+ const stores = await storeFiles(discovery.homes);
24361
+ const open4 = await loadSqlite();
24362
+ const index = open4 ? readConversationIndex(open4, discovery.homes) : /* @__PURE__ */ new Map();
24363
+ const conversations = [];
24364
+ let done = 0;
24365
+ for (const store of stores) {
24366
+ stats.filesFound++;
24367
+ const name = path2.basename(store.file);
24368
+ try {
24369
+ const indexed = store.kind === "encrypted" ? index.get(path2.basename(store.file, ".pb")) : void 0;
24370
+ const changedMs = indexed ?? (await stat2(store.file)).mtimeMs;
24371
+ if (changedMs < sinceMs) {
24372
+ stats.filesSkippedByMtime++;
24373
+ continue;
24374
+ }
24375
+ if (store.kind === "encrypted") throw readError("encrypted");
24376
+ if (open4 === null) throw readError("sqlite-unsupported");
24377
+ let db = null;
24378
+ try {
24379
+ db = open4(store.file);
24380
+ conversations.push(decodeConversation(readStore(db)));
24381
+ } finally {
24382
+ closeQuietly(db);
24383
+ }
24384
+ agg.files++;
24385
+ stats.filesRead++;
24386
+ } catch (e) {
24387
+ traceError("antigravity conversation read", e, "warn");
24388
+ stats.filesUnreadable++;
24389
+ stats.unreadableFiles.push({ path: name, reason: errorClass(e) });
24390
+ } finally {
24391
+ done++;
24392
+ opts.onProgress?.(done, stores.length);
24393
+ }
24394
+ }
24395
+ foldConversations(agg, createFoldState(), conversations, sinceMs);
24396
+ return stats;
24397
+ }
24398
+ async function detectAntigravity(opts) {
24399
+ const homes = opts.roots ?? (await antigravityHomes()).homes;
24400
+ const stores = (await storeFiles(homes)).filter((s) => s.kind === "db");
24401
+ if (stores.length === 0) return false;
24402
+ const open4 = await loadSqlite();
24403
+ if (open4 === null) return false;
24404
+ for (const store of stores) {
24405
+ try {
24406
+ if ((await stat2(store.file)).mtimeMs < opts.sinceMs) continue;
24407
+ } catch {
24408
+ continue;
24409
+ }
24410
+ let db = null;
24411
+ try {
24412
+ db = open4(store.file);
24413
+ if (db.prepare("select 1 as hit from steps limit 1").get() !== void 0)
24414
+ return true;
24415
+ } catch (error) {
24416
+ traceError("antigravity detection", error, "warn");
24417
+ } finally {
24418
+ closeQuietly(db);
24419
+ }
24420
+ }
24421
+ return false;
24422
+ }
24423
+
24424
+ // src/harness/antigravity/adapter.ts
24425
+ var ANTIGRAVITY_HARNESS_NAME = "antigravity";
24426
+ var antigravityAdapter = {
24427
+ name: ANTIGRAVITY_HARNESS_NAME,
24428
+ builtinTools: ANTIGRAVITY_BUILTIN_TOOLS,
24429
+ async detect(opts) {
24430
+ return detectAntigravity({
24431
+ sinceMs: opts.sinceMs,
24432
+ ...opts.roots ? { roots: opts.roots } : {}
24433
+ });
24434
+ },
24435
+ async scan(opts) {
24436
+ const aggregate = createAggregate2();
24437
+ const stats = await scan(aggregate, {
24438
+ sinceMs: opts.sinceMs,
24439
+ ...opts.onProgress ? { onProgress: opts.onProgress } : {}
24440
+ });
24441
+ return {
24442
+ aggregate,
24443
+ stats,
24444
+ scanComplete: stats.sourceDiscoveryComplete !== false,
24445
+ workflow: aggregate.workflow.finish(),
24446
+ workflowLocal: aggregate.workflowLocal
24447
+ };
24448
+ }
24449
+ };
24450
+
24451
+ // src/harness/shared/recency.ts
24452
+ import { readdir as readdir3, stat as stat3 } from "node:fs/promises";
24453
+ import path3 from "node:path";
24454
+ async function hasRecentFile(roots, matches, sinceMs, opts = {}) {
24455
+ const readDir = opts.readdirImpl ?? ((dir) => readdir3(dir, { withFileTypes: true }));
24456
+ const statFile = opts.statImpl ?? stat3;
24457
+ const seen = /* @__PURE__ */ new Set();
24458
+ const pending = [...roots];
24459
+ while (pending.length > 0) {
24460
+ const dir = pending.pop();
24461
+ if (seen.has(dir)) continue;
24462
+ seen.add(dir);
24463
+ let entries;
24464
+ try {
24465
+ entries = await readDir(dir);
24466
+ } catch {
24467
+ continue;
24468
+ }
24469
+ for (const e of entries) {
24470
+ const full = path3.join(dir, e.name);
24471
+ if (e.isDirectory()) {
24472
+ pending.push(full);
24473
+ continue;
24474
+ }
24475
+ if (!e.isFile() || !matches(e.name)) continue;
24476
+ try {
24477
+ const st = await statFile(full);
24478
+ if (st.mtimeMs >= sinceMs) return true;
24479
+ } catch {
24480
+ }
24481
+ }
24482
+ }
24483
+ return false;
24484
+ }
24485
+
24486
+ // src/harness/claude/analyzer.ts
24487
+ function createAggregate3() {
24488
+ const workflowLocal = createWorkflowLocalSources();
24489
+ return Object.assign(createAggregate(), {
24490
+ recordUuids: /* @__PURE__ */ new Set(),
24491
+ workflow: createHarnessWorkflowReducer("claude-code", workflowLocal),
24492
+ workflowLocal,
24493
+ workflowSeenCalls: /* @__PURE__ */ new Set(),
24494
+ workflowSeenTurns: /* @__PURE__ */ new Set(),
24495
+ contextFirstCall: /* @__PURE__ */ new Map(),
24496
+ workflowToolNames: /* @__PURE__ */ new Map(),
24497
+ typedCommands: /* @__PURE__ */ new Map()
24498
+ });
24499
+ }
24500
+ function workflowSessionKey(rec) {
24501
+ const baseSession = asStr(rec.sessionId);
24502
+ if (!baseSession) return null;
24503
+ if (rec.isSidechain !== true) return baseSession;
24504
+ return `${baseSession}:agent:${asStr(rec.agentId) ?? "unknown"}`;
24505
+ }
24506
+ function isApiCall(rec) {
24507
+ if (asStr(rec.type) !== "assistant") return false;
24508
+ const msg = asObj(rec.message);
24509
+ if (!msg || !asObj(msg.usage)) return false;
24510
+ return !(asName(msg.model) ?? "").startsWith("<");
24511
+ }
24512
+ function noteRecordBeforeWindow(agg, raw) {
24513
+ const rec = asObj(raw);
24514
+ if (!rec || !isApiCall(rec)) return;
24515
+ const session = workflowSessionKey(rec);
24516
+ if (session && !agg.contextFirstCall.has(session)) {
24517
+ agg.contextFirstCall.set(session, null);
24518
+ }
24519
+ }
24520
+ function projectWorkspaceDirectory(raw) {
24521
+ const rec = asObj(raw);
24522
+ return rec ? asStr(rec.cwd) : null;
24523
+ }
24524
+ function ingestRecord(agg, raw, ctx) {
24525
+ const rec = asObj(raw);
24526
+ if (!rec) return;
24527
+ const uuid = asStr(rec.uuid);
24528
+ if (uuid) {
24529
+ if (agg.recordUuids.has(uuid)) return;
24530
+ agg.recordUuids.add(uuid);
24531
+ }
24532
+ agg.records++;
24533
+ const projectDir = projectWorkspaceDirectory(rec) ?? ctx.projectDir;
24534
+ const version = asStr(rec.version);
24535
+ if (version) agg.ccVersions.add(cleanName(version));
24536
+ const sessionId = asStr(rec.sessionId);
24537
+ if (sessionId) agg.sessions.add(sessionId);
24538
+ let tsMs = null;
24539
+ const timestamp2 = asStr(rec.timestamp);
24540
+ if (timestamp2) {
24541
+ const ts = Date.parse(timestamp2);
24542
+ if (!Number.isNaN(ts)) {
24543
+ tsMs = ts;
24544
+ agg.activeDays.add(timestamp2.slice(0, 10));
24545
+ agg.firstTs = agg.firstTs === null ? ts : Math.min(agg.firstTs, ts);
24546
+ agg.lastTs = agg.lastTs === null ? ts : Math.max(agg.lastTs, ts);
24547
+ }
24548
+ }
24549
+ if (sessionId) noteSessionStart(agg, sessionId, tsMs);
24550
+ if (projectDir !== void 0) {
24551
+ agg.projectDirs.add(projectDir);
24552
+ }
24553
+ noteProjectDay(agg, projectDir, tsMs);
24554
+ const type = asStr(rec.type);
24555
+ if (type === "assistant") {
24556
+ ingestClaudeWorkflow(agg, rec, ctx, tsMs);
24557
+ ingestAssistant(agg, rec, tsMs);
24558
+ } else if (type === "user") {
24559
+ ingestUser(agg, rec);
24560
+ ingestClaudeToolResults(agg, rec, ctx, tsMs);
24561
+ } else if (type === "system") {
24562
+ ingestClaudeTurnDuration(agg, rec, ctx, tsMs);
24563
+ ingestClaudeCompaction(agg, rec, ctx, tsMs);
24564
+ }
24565
+ }
24566
+ function ingestClaudeCompaction(agg, rec, ctx, tsMs) {
24567
+ if (tsMs === null || asStr(rec.subtype) !== "compact_boundary") return;
24568
+ const session = workflowSessionKey(rec);
24569
+ if (!session) return;
24570
+ agg.workflow.ingest({
24571
+ type: "compaction",
24572
+ session,
24573
+ projectWorkspace: projectWorkspaceDirectory(rec) ?? ctx.projectDir,
24574
+ tsMs,
24575
+ ...rec.isSidechain === true ? { sidechain: true } : {}
24576
+ });
24577
+ }
24578
+ function contextOf(counts2) {
24579
+ return counts2.input + counts2.cacheWrite5m + counts2.cacheWrite1h + counts2.cacheWriteUnsplit + counts2.cacheRead;
24580
+ }
24581
+ function ingestClaudeTurnDuration(agg, rec, ctx, tsMs) {
24582
+ if (tsMs === null || asStr(rec.subtype) !== "turn_duration" || asNum(rec.durationMs) <= 0) {
24583
+ return;
24584
+ }
24585
+ const session = asStr(rec.sessionId);
24586
+ if (!session) return;
24587
+ agg.workflow.ingest({
24588
+ type: "response",
24589
+ session,
24590
+ projectWorkspace: projectWorkspaceDirectory(rec) ?? ctx.projectDir,
24591
+ tsMs,
24592
+ ...asStr(rec.uuid) ? { responseId: `duration:${asStr(rec.uuid)}` } : {},
24593
+ durationSec: asNum(rec.durationMs) / 1e3
24594
+ });
24595
+ }
24596
+ function ingestClaudeWorkflow(agg, rec, ctx, tsMs) {
24597
+ if (tsMs === null) return;
24598
+ const baseSession = asStr(rec.sessionId);
24599
+ const msg = asObj(rec.message);
24600
+ if (!baseSession || !msg) return;
24601
+ const projectWorkspace = projectWorkspaceDirectory(rec) ?? ctx.projectDir;
24602
+ const sidechain = rec.isSidechain === true;
24603
+ const agentId = asStr(rec.agentId);
24604
+ const session = sidechain ? `${baseSession}:agent:${agentId ?? "unknown"}` : baseSession;
24605
+ const parentSession = sidechain ? baseSession : void 0;
24606
+ const usage = asObj(msg.usage);
24607
+ const counts2 = usage ? readCounts(usage) : null;
24608
+ const messageId = asStr(msg.id);
24609
+ const newTurn = messageId ? !agg.workflowSeenTurns.has(messageId) : true;
24610
+ if (messageId) agg.workflowSeenTurns.add(messageId);
24611
+ const blocks = { thinking: 0, text: 0 };
24612
+ for (const rawBlock of asArr(msg.content)) {
24613
+ const block = asObj(rawBlock);
24614
+ const kind = block ? asStr(block.type) : null;
24615
+ if (kind === "thinking") blocks.thinking++;
24616
+ else if (kind === "text") blocks.text++;
24617
+ }
24618
+ let context = null;
24619
+ if (counts2 && isApiCall(rec)) {
24620
+ const held = agg.contextFirstCall.get(session);
24621
+ let first = false;
24622
+ if (held === void 0) {
24623
+ agg.contextFirstCall.set(session, messageId);
24624
+ first = true;
24625
+ } else if (held !== null && held === messageId) first = true;
24626
+ context = {
24627
+ contextTokens: contextOf(counts2),
24628
+ inputTokens: counts2.input,
24629
+ cacheReadTokens: counts2.cacheRead,
24630
+ cacheWriteTokens: counts2.cacheWrite5m + counts2.cacheWrite1h + counts2.cacheWriteUnsplit,
24631
+ // The TTL this call wrote under (v5): a subscription within plan
24632
+ // usage writes the main conversation at one hour.
24633
+ ...counts2.cacheWrite1h > 0 ? { cacheTtlSec: 3600 } : counts2.cacheWrite5m > 0 ? { cacheTtlSec: 300 } : {},
24634
+ ...first ? {
24635
+ firstCall: {
24636
+ harnessTokens: counts2.cacheRead,
24637
+ instructionsTokens: contextOf(counts2) - counts2.cacheRead
24638
+ }
24639
+ } : {}
24640
+ };
24641
+ }
23899
24642
  agg.workflow.ingest({
23900
24643
  type: "response",
23901
24644
  session,
@@ -24243,13 +24986,15 @@ function ingestTypedSkill(agg, rec, text) {
24243
24986
  }
24244
24987
 
24245
24988
  // src/harness/claude/roots.ts
24246
- import { readdir as readdir2, realpath, stat as stat2 } from "node:fs/promises";
24247
- import { homedir as homedir6 } from "node:os";
24248
- import path2 from "node:path";
24989
+ import { readdir as readdir4, realpath as realpath3, stat as stat4 } from "node:fs/promises";
24990
+ import { homedir as homedir8 } from "node:os";
24991
+ import path4 from "node:path";
24992
+ var CLAUDE_HOMES_KEY = "claude";
24993
+ var CCS_HOMES_KEY = "ccs";
24249
24994
  async function discoverClaudeRoots() {
24250
- const home = homedir6();
24251
- const configHome = process.env.XDG_CONFIG_HOME || path2.join(home, ".config");
24252
- const dataHome = process.env.XDG_DATA_HOME || path2.join(home, ".local", "share");
24995
+ const home = homedir8();
24996
+ const configHome = process.env.XDG_CONFIG_HOME || path4.join(home, ".config");
24997
+ const dataHome = process.env.XDG_DATA_HOME || path4.join(home, ".local", "share");
24253
24998
  let complete = true;
24254
24999
  const failed = (error) => {
24255
25000
  const code2 = error?.code;
@@ -24259,55 +25004,90 @@ async function discoverClaudeRoots() {
24259
25004
  };
24260
25005
  const children = async (dir, prefix = "") => {
24261
25006
  try {
24262
- return (await readdir2(dir, { withFileTypes: true })).filter(
25007
+ return (await readdir4(dir, { withFileTypes: true })).filter(
24263
25008
  (entry) => entry.name.startsWith(prefix) && (entry.isDirectory() || entry.isSymbolicLink())
24264
- ).map((entry) => path2.join(dir, entry.name)).sort();
25009
+ ).map((entry) => path4.join(dir, entry.name)).sort();
24265
25010
  } catch (error) {
24266
25011
  failed(error);
24267
25012
  return [];
24268
25013
  }
24269
25014
  };
24270
- const configured = (process.env.CLAUDE_CONFIG_DIR ?? "").split(",").map((s) => s.trim()).filter(Boolean).map(
24271
- (dir) => path2.resolve(dir.startsWith("~/") ? path2.join(home, dir.slice(2)) : dir)
24272
- );
24273
- const profiles = /* @__PURE__ */ new Set([
24274
- path2.join(home, ".claude"),
24275
- path2.join(configHome, "claude"),
24276
- ...configured,
24277
- ...await children(home, ".claude"),
24278
- ...await children(configHome, "claude")
24279
- ]);
24280
- for (const profile of [...profiles]) {
24281
- for (const collection of ["profiles", "accounts"]) {
24282
- for (const child of await children(path2.join(profile, collection)))
24283
- profiles.add(child);
25015
+ const ccsHome = process.env.CCS_HOME?.trim();
25016
+ const ccs = await discoverHomes({
25017
+ defaults: [path4.join(home, ".ccs")],
25018
+ configured: [process.env.CCS_DIR, ccsHome && path4.join(ccsHome, ".ccs")],
25019
+ remember: CCS_HOMES_KEY
25020
+ });
25021
+ if (!ccs.complete) complete = false;
25022
+ const contextGroups = /* @__PURE__ */ new Set();
25023
+ const managed = [];
25024
+ for (const dir of ccs.homes) {
25025
+ managed.push(...await children(path4.join(dir, "instances")));
25026
+ for (const group of await children(
25027
+ path4.join(dir, "shared", "context-groups")
25028
+ )) {
25029
+ contextGroups.add(group);
25030
+ managed.push(group);
24284
25031
  }
24285
25032
  }
25033
+ for (const account of await children(
25034
+ path4.join(home, ".cc-switch", "claude-accounts")
25035
+ ))
25036
+ managed.push(path4.join(account, "config"));
24286
25037
  for (const manager of [
24287
- path2.join(home, ".claude-swap-backup"),
24288
- path2.join(dataHome, "claude-swap")
25038
+ path4.join(home, ".claude-swap-backup"),
25039
+ path4.join(dataHome, "claude-swap")
24289
25040
  ]) {
24290
- for (const collection of [manager, path2.join(manager, "sessions")]) {
24291
- for (const child of await children(collection)) profiles.add(child);
25041
+ for (const collection of [manager, path4.join(manager, "sessions")])
25042
+ managed.push(...await children(collection));
25043
+ }
25044
+ const named = [
25045
+ path4.join(home, ".claude"),
25046
+ path4.join(configHome, "claude"),
25047
+ ...await children(home, ".claude"),
25048
+ ...await children(configHome, "claude"),
25049
+ ...managed
25050
+ ];
25051
+ const found = await discoverHomes({
25052
+ defaults: named,
25053
+ configured: (process.env.CLAUDE_CONFIG_DIR ?? "").split(","),
25054
+ remember: CLAUDE_HOMES_KEY
25055
+ });
25056
+ if (!found.complete) complete = false;
25057
+ const groups = /* @__PURE__ */ new Set();
25058
+ for (const group of contextGroups) {
25059
+ try {
25060
+ groups.add(await realpath3(group));
25061
+ } catch (error) {
25062
+ failed(error);
25063
+ }
25064
+ }
25065
+ const profiles = new Set(found.homes);
25066
+ for (const profile of [...profiles]) {
25067
+ for (const collection of ["profiles", "accounts"]) {
25068
+ for (const child of await children(path4.join(profile, collection)))
25069
+ profiles.add(child);
24292
25070
  }
24293
25071
  }
24294
25072
  const roots = /* @__PURE__ */ new Set();
25073
+ const accounts = /* @__PURE__ */ new Set();
24295
25074
  for (const profile of profiles) {
24296
- const projects = path2.join(profile, "projects");
24297
25075
  try {
24298
- if ((await stat2(projects)).isDirectory())
24299
- roots.add(await realpath(projects));
25076
+ const projects = await realpath3(path4.join(profile, "projects"));
25077
+ if (!(await stat4(projects)).isDirectory()) continue;
25078
+ roots.add(projects);
25079
+ if (!groups.has(profile)) accounts.add(await realpath3(profile));
24300
25080
  } catch (error) {
24301
25081
  failed(error);
24302
25082
  }
24303
25083
  }
24304
- return { roots: [...roots], complete };
25084
+ return { roots: [...roots], profiles: [...accounts], complete };
24305
25085
  }
24306
25086
 
24307
25087
  // src/harness/claude/scan.ts
24308
25088
  import { createReadStream } from "node:fs";
24309
- import { readdir as readdir3, realpath as realpath2, stat as stat3 } from "node:fs/promises";
24310
- import path3 from "node:path";
25089
+ import { readdir as readdir5, realpath as realpath4, stat as stat5 } from "node:fs/promises";
25090
+ import path5 from "node:path";
24311
25091
  import readline from "node:readline";
24312
25092
  var WORKSPACE_FALLBACK_PREFIX = "claude-project:";
24313
25093
  function isClaudeWorkspaceFallback(directory) {
@@ -24319,19 +25099,19 @@ function isTranscriptFile(basename6) {
24319
25099
  async function* walkJsonl(dir) {
24320
25100
  let entries;
24321
25101
  try {
24322
- entries = await readdir3(dir, { withFileTypes: true });
25102
+ entries = await readdir5(dir, { withFileTypes: true });
24323
25103
  } catch (error) {
24324
25104
  if (error?.code !== "ENOENT")
24325
25105
  traceError("claude transcript discovery", error, "warn");
24326
25106
  return;
24327
25107
  }
24328
25108
  for (const e of entries) {
24329
- const full = path3.join(dir, e.name);
25109
+ const full = path5.join(dir, e.name);
24330
25110
  if (e.isDirectory()) yield* walkJsonl(full);
24331
25111
  else if (e.isFile() && isTranscriptFile(e.name)) yield full;
24332
25112
  }
24333
25113
  }
24334
- async function scan(agg, opts = {}) {
25114
+ async function scan2(agg, opts = {}) {
24335
25115
  const stats = emptyScanStats();
24336
25116
  const visited = /* @__PURE__ */ new Set();
24337
25117
  const projectWorkspaces = /* @__PURE__ */ new Map();
@@ -24343,7 +25123,7 @@ async function scan(agg, opts = {}) {
24343
25123
  stats.filesFound++;
24344
25124
  let resolved;
24345
25125
  try {
24346
- resolved = await realpath2(file);
25126
+ resolved = await realpath4(file);
24347
25127
  } catch (error) {
24348
25128
  if (error?.code !== "ENOENT")
24349
25129
  traceError("claude transcript path resolution", error, "warn");
@@ -24356,7 +25136,7 @@ async function scan(agg, opts = {}) {
24356
25136
  visited.add(resolved);
24357
25137
  if (opts.sinceMs !== void 0) {
24358
25138
  try {
24359
- const st = await stat3(file);
25139
+ const st = await stat5(file);
24360
25140
  if (st.mtimeMs < opts.sinceMs) {
24361
25141
  stats.filesSkippedByMtime++;
24362
25142
  continue;
@@ -24366,8 +25146,8 @@ async function scan(agg, opts = {}) {
24366
25146
  traceError("claude transcript stat", error, "warn");
24367
25147
  }
24368
25148
  }
24369
- const parts = path3.relative(root, file).split(path3.sep);
24370
- const projectDir = parts.length > 1 ? `${WORKSPACE_FALLBACK_PREFIX}${path3.resolve(root, parts[0])}` : void 0;
25149
+ const parts = path5.relative(root, file).split(path5.sep);
25150
+ const projectDir = parts.length > 1 ? `${WORKSPACE_FALLBACK_PREFIX}${path5.resolve(root, parts[0])}` : void 0;
24371
25151
  agg.files++;
24372
25152
  stats.filesRead++;
24373
25153
  if (opts.onProgress && agg.files % 20 === 0) opts.onProgress(agg.files);
@@ -24390,7 +25170,7 @@ async function scan(agg, opts = {}) {
24390
25170
  }
24391
25171
  async function exists(p8) {
24392
25172
  try {
24393
- await stat3(p8);
25173
+ await stat5(p8);
24394
25174
  return true;
24395
25175
  } catch (error) {
24396
25176
  if (error?.code !== "ENOENT")
@@ -24451,8 +25231,8 @@ var claudeAdapter = {
24451
25231
  return hasRecentFile(discovery.roots, isTranscriptFile, opts.sinceMs);
24452
25232
  },
24453
25233
  async scan(opts) {
24454
- const aggregate = createAggregate2();
24455
- const stats = await scan(aggregate, {
25234
+ const aggregate = createAggregate3();
25235
+ const stats = await scan2(aggregate, {
24456
25236
  sinceMs: opts.sinceMs,
24457
25237
  ...opts.onProgress ? { onProgress: opts.onProgress } : {}
24458
25238
  });
@@ -24467,7 +25247,7 @@ var claudeAdapter = {
24467
25247
  };
24468
25248
 
24469
25249
  // src/harness/codex/analyzer.ts
24470
- function createAggregate3() {
25250
+ function createAggregate4() {
24471
25251
  const workflowLocal = createWorkflowLocalSources();
24472
25252
  return Object.assign(createAggregate(), {
24473
25253
  workflow: createHarnessWorkflowReducer("codex", workflowLocal),
@@ -24740,196 +25520,72 @@ function countTurnSkill(agg, name, state, typed = false) {
24740
25520
  function ingestToolResult(agg, payload, state, tsMs) {
24741
25521
  if (tsMs === null || !state.sessionId) return;
24742
25522
  const callId = asStr(payload.call_id) ?? asStr(payload.id);
24743
- const output = payload.output;
24744
- const bytes = typeof output === "string" ? Buffer.byteLength(output) : output === void 0 || output === null ? 0 : Buffer.byteLength(JSON.stringify(output));
24745
- agg.workflow.ingest({
24746
- type: "toolResult",
24747
- session: state.sessionId,
24748
- projectWorkspace: state.cwd ?? void 0,
24749
- tsMs,
24750
- tool: callId && state.callNames.get(callId) || "other",
24751
- bytes
24752
- });
24753
- }
24754
- function ingestWorkflowCall(agg, payload, name, callId, state, tsMs) {
24755
- if (tsMs === null || !state.sessionId) return;
24756
- if (callId) {
24757
- if (agg.workflowSeenCalls.has(callId)) return;
24758
- agg.workflowSeenCalls.add(callId);
24759
- }
24760
- state.currentQuestionBack = name === "request_user_input";
24761
- let arg = "";
24762
- if (["exec_command", "shell", "container.exec", "local_shell"].includes(name)) {
24763
- const raw = name === "local_shell" ? asObj(payload.action)?.command : payload.arguments ?? payload.input;
24764
- if (Array.isArray(raw)) arg = unwrapShellCommand(raw.map(String));
24765
- else if (typeof raw === "string" && !raw.trim().startsWith("{")) arg = raw;
24766
- else {
24767
- try {
24768
- const parsed = JSON.parse(String(raw ?? "{}"));
24769
- const command = parsed.cmd ?? parsed.command;
24770
- arg = Array.isArray(command) ? unwrapShellCommand(command.map(String)) : typeof command === "string" ? command : "";
24771
- } catch {
24772
- arg = "";
24773
- }
24774
- }
24775
- }
24776
- agg.workflow.ingest({
24777
- type: "event",
24778
- session: state.sessionId,
24779
- projectWorkspace: state.cwd ?? void 0,
24780
- tsMs,
24781
- tool: name,
24782
- arg
24783
- });
24784
- }
24785
- function unwrapShellCommand(command) {
24786
- if (command.length >= 3 && /^(bash|sh|zsh)$/.test(command[0] ?? "") && /^-l?c$/.test(command[1] ?? ""))
24787
- return command.slice(2).join(" ");
24788
- return command.join(" ");
24789
- }
24790
- function noteConfiguredMcpServers(agg, serverNames) {
24791
- for (const raw of serverNames) {
24792
- const name = cleanName(raw);
24793
- if (!agg.mcpServerCalls.has(name)) agg.mcpServerCalls.set(name, 0);
24794
- }
24795
- }
24796
-
24797
- // src/harness/codex/scan.ts
24798
- import { readFileSync as readFileSync6 } from "node:fs";
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
- import { Readable } from "node:stream";
24803
- import * as zlib from "node:zlib";
24804
- import { parse as parseToml2 } from "smol-toml";
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;
25523
+ const output = payload.output;
25524
+ const bytes = typeof output === "string" ? Buffer.byteLength(output) : output === void 0 || output === null ? 0 : Buffer.byteLength(JSON.stringify(output));
25525
+ agg.workflow.ingest({
25526
+ type: "toolResult",
25527
+ session: state.sessionId,
25528
+ projectWorkspace: state.cwd ?? void 0,
25529
+ tsMs,
25530
+ tool: callId && state.callNames.get(callId) || "other",
25531
+ bytes
25532
+ });
24885
25533
  }
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 [];
25534
+ function ingestWorkflowCall(agg, payload, name, callId, state, tsMs) {
25535
+ if (tsMs === null || !state.sessionId) return;
25536
+ if (callId) {
25537
+ if (agg.workflowSeenCalls.has(callId)) return;
25538
+ agg.workflowSeenCalls.add(callId);
24894
25539
  }
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;
25540
+ state.currentQuestionBack = name === "request_user_input";
25541
+ let arg = "";
25542
+ if (["exec_command", "shell", "container.exec", "local_shell"].includes(name)) {
25543
+ const raw = name === "local_shell" ? asObj(payload.action)?.command : payload.arguments ?? payload.input;
25544
+ if (Array.isArray(raw)) arg = unwrapShellCommand(raw.map(String));
25545
+ else if (typeof raw === "string" && !raw.trim().startsWith("{")) arg = raw;
25546
+ else {
25547
+ try {
25548
+ const parsed = JSON.parse(String(raw ?? "{}"));
25549
+ const command = parsed.cmd ?? parsed.command;
25550
+ arg = Array.isArray(command) ? unwrapShellCommand(command.map(String)) : typeof command === "string" ? command : "";
25551
+ } catch {
25552
+ arg = "";
25553
+ }
24906
25554
  }
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
25555
  }
25556
+ agg.workflow.ingest({
25557
+ type: "event",
25558
+ session: state.sessionId,
25559
+ projectWorkspace: state.cwd ?? void 0,
25560
+ tsMs,
25561
+ tool: name,
25562
+ arg
25563
+ });
24916
25564
  }
24917
- function expandHome(dir) {
24918
- const trimmed = dir.trim();
24919
- return path4.resolve(
24920
- trimmed.startsWith("~/") ? path4.join(homedir7(), trimmed.slice(2)) : trimmed
24921
- );
25565
+ function unwrapShellCommand(command) {
25566
+ if (command.length >= 3 && /^(bash|sh|zsh)$/.test(command[0] ?? "") && /^-l?c$/.test(command[1] ?? ""))
25567
+ return command.slice(2).join(" ");
25568
+ return command.join(" ");
24922
25569
  }
24923
- function absent(error) {
24924
- const code2 = error?.code;
24925
- return code2 === "ENOENT" || code2 === "ENOTDIR";
25570
+ function noteConfiguredMcpServers(agg, serverNames) {
25571
+ for (const raw of serverNames) {
25572
+ const name = cleanName(raw);
25573
+ if (!agg.mcpServerCalls.has(name)) agg.mcpServerCalls.set(name, 0);
25574
+ }
24926
25575
  }
24927
25576
 
24928
25577
  // src/harness/codex/scan.ts
25578
+ import { readFileSync as readFileSync6 } from "node:fs";
25579
+ import { open, readdir as readdir6, stat as stat6 } from "node:fs/promises";
25580
+ import { homedir as homedir9 } from "node:os";
25581
+ import path6 from "node:path";
25582
+ import { Readable } from "node:stream";
25583
+ import * as zlib from "node:zlib";
25584
+ import { parse as parseToml2 } from "smol-toml";
24929
25585
  async function discoverCodexHomes() {
24930
- const home = homedir8();
25586
+ const home = homedir9();
24931
25587
  return discoverHomes({
24932
- defaults: [path5.join(home, ".codex")],
25588
+ defaults: [path6.join(home, ".codex")],
24933
25589
  configured: [process.env.CODEX_HOME],
24934
25590
  siblings: [{ parent: home, prefix: ".codex" }],
24935
25591
  remember: "codex"
@@ -24937,7 +25593,7 @@ async function discoverCodexHomes() {
24937
25593
  }
24938
25594
  async function rolloutRoots() {
24939
25595
  return (await discoverCodexHomes()).homes.map(
24940
- (home) => path5.join(home, "sessions")
25596
+ (home) => path6.join(home, "sessions")
24941
25597
  );
24942
25598
  }
24943
25599
  var ROLLOUT_RE = /^rollout-.*\.jsonl(\.zst)?$/;
@@ -24947,21 +25603,21 @@ function isRolloutFile(basename6) {
24947
25603
  async function* walkRollouts(dir) {
24948
25604
  let entries;
24949
25605
  try {
24950
- entries = await readdir5(dir, { withFileTypes: true });
25606
+ entries = await readdir6(dir, { withFileTypes: true });
24951
25607
  } catch (error) {
24952
25608
  if (error?.code !== "ENOENT")
24953
25609
  traceError("codex rollout discovery", error, "warn");
24954
25610
  return;
24955
25611
  }
24956
25612
  for (const e of entries) {
24957
- const full = path5.join(dir, e.name);
25613
+ const full = path6.join(dir, e.name);
24958
25614
  if (e.isDirectory()) yield* walkRollouts(full);
24959
25615
  else if (e.isFile() && isRolloutFile(e.name)) yield full;
24960
25616
  }
24961
25617
  }
24962
25618
  var createZstdDecompress2 = typeof zlib.createZstdDecompress === "function" ? zlib.createZstdDecompress : null;
24963
25619
  var MAX_LINE_BYTES = 64 * 1024 * 1024;
24964
- async function scan2(agg, opts = {}) {
25620
+ async function scan3(agg, opts = {}) {
24965
25621
  return (await scanWindows(
24966
25622
  [{ aggregate: agg, sinceMs: opts.sinceMs, onProgress: opts.onProgress }],
24967
25623
  opts
@@ -24975,7 +25631,7 @@ async function scanWindows(windows, opts = {}) {
24975
25631
  const discovery = opts.roots ? { homes: [], complete: true } : await discoverCodexHomes();
24976
25632
  for (const { stats } of targets)
24977
25633
  stats.sourceDiscoveryComplete = discovery.complete;
24978
- const roots = opts.roots ?? discovery.homes.map((home) => path5.join(home, "sessions"));
25634
+ const roots = opts.roots ?? discovery.homes.map((home) => path6.join(home, "sessions"));
24979
25635
  const chosen = /* @__PURE__ */ new Map();
24980
25636
  for (const root of roots) {
24981
25637
  if (!await exists2(root)) continue;
@@ -24984,14 +25640,14 @@ async function scanWindows(windows, opts = {}) {
24984
25640
  let size = -1;
24985
25641
  let mtimeMs;
24986
25642
  try {
24987
- const st = await stat5(file);
25643
+ const st = await stat6(file);
24988
25644
  size = st.size;
24989
25645
  mtimeMs = st.mtimeMs;
24990
25646
  } catch (error) {
24991
25647
  if (error?.code !== "ENOENT")
24992
25648
  traceError("codex rollout stat", error, "warn");
24993
25649
  }
24994
- const key2 = path5.basename(file).replace(/\.zst$/, "");
25650
+ const key2 = path6.basename(file).replace(/\.zst$/, "");
24995
25651
  const held = chosen.get(key2);
24996
25652
  if (held) {
24997
25653
  for (const { stats } of targets) stats.filesSkippedAsDuplicate++;
@@ -25021,7 +25677,7 @@ async function scanWindows(windows, opts = {}) {
25021
25677
  stats.filesRead--;
25022
25678
  if (outcome.reason === "zstd-unsupported") stats.filesZstdUnsupported++;
25023
25679
  stats.unreadableFiles.push({
25024
- path: path5.relative(root, file),
25680
+ path: path6.relative(root, file),
25025
25681
  reason: outcome.reason
25026
25682
  });
25027
25683
  } else if (!outcome.genuine) {
@@ -25034,14 +25690,14 @@ async function scanWindows(windows, opts = {}) {
25034
25690
  }
25035
25691
  }
25036
25692
  }
25037
- const configFiles = opts.configFile ? [opts.configFile] : discovery.homes.map((home) => path5.join(home, "config.toml"));
25693
+ const configFiles = opts.configFile ? [opts.configFile] : discovery.homes.map((home) => path6.join(home, "config.toml"));
25038
25694
  for (const { aggregate } of targets)
25039
25695
  for (const file of configFiles) readConfiguredMcpServers(aggregate, file);
25040
25696
  return targets.map((target) => target.stats);
25041
25697
  }
25042
25698
  async function exists2(p8) {
25043
25699
  try {
25044
- await stat5(p8);
25700
+ await stat6(p8);
25045
25701
  return true;
25046
25702
  } catch (error) {
25047
25703
  if (error?.code !== "ENOENT")
@@ -25049,31 +25705,31 @@ async function exists2(p8) {
25049
25705
  return false;
25050
25706
  }
25051
25707
  }
25052
- function errorClass(e) {
25708
+ function errorClass2(e) {
25053
25709
  const code2 = e?.code;
25054
25710
  if (typeof code2 === "string" && code2.length > 0) return code2;
25055
25711
  return e instanceof Error ? e.constructor.name : "unknown";
25056
25712
  }
25057
- var readError = (reason) => Object.assign(new Error(reason), { code: reason });
25713
+ var readError2 = (reason) => Object.assign(new Error(reason), { code: reason });
25058
25714
  async function ingestWithRetry(windows, file, opts) {
25059
25715
  try {
25060
25716
  return await ingestFile2(windows, file, opts);
25061
25717
  } catch (e) {
25062
25718
  traceError("codex rollout read", e);
25063
- if (errorClass(e) === "ENOENT" && !file.endsWith(".zst")) {
25719
+ if (errorClass2(e) === "ENOENT" && !file.endsWith(".zst")) {
25064
25720
  try {
25065
25721
  return await ingestFile2(windows, `${file}.zst`, opts);
25066
25722
  } catch (e2) {
25067
25723
  traceError("codex compressed rollout retry", e2);
25068
- return { ok: false, reason: errorClass(e2) };
25724
+ return { ok: false, reason: errorClass2(e2) };
25069
25725
  }
25070
25726
  }
25071
- return { ok: false, reason: errorClass(e) };
25727
+ return { ok: false, reason: errorClass2(e) };
25072
25728
  }
25073
25729
  }
25074
25730
  async function ingestFile2(windows, file, opts) {
25075
25731
  const compressed = file.endsWith(".zst");
25076
- if (compressed && !createZstdDecompress2) throw readError("zstd-unsupported");
25732
+ if (compressed && !createZstdDecompress2) throw readError2("zstd-unsupported");
25077
25733
  const handle = await open(file, "r");
25078
25734
  try {
25079
25735
  const { size } = await handle.stat();
@@ -25092,7 +25748,7 @@ async function ingestFile2(windows, file, opts) {
25092
25748
  buffer.length,
25093
25749
  position
25094
25750
  );
25095
- if (bytesRead === 0) throw readError("rollout-truncated");
25751
+ if (bytesRead === 0) throw readError2("rollout-truncated");
25096
25752
  position += bytesRead;
25097
25753
  yield buffer.subarray(0, bytesRead);
25098
25754
  }
@@ -25118,7 +25774,7 @@ async function ingestFile2(windows, file, opts) {
25118
25774
  if (count2) nonEmptyLines++;
25119
25775
  let record;
25120
25776
  try {
25121
- if (line === null) throw readError("record-too-large");
25777
+ if (line === null) throw readError2("record-too-large");
25122
25778
  record = JSON.parse(line);
25123
25779
  } catch (error) {
25124
25780
  if (count2) {
@@ -25133,7 +25789,7 @@ async function ingestFile2(windows, file, opts) {
25133
25789
  } catch (error) {
25134
25790
  if (decoder && !sourceError) {
25135
25791
  traceError("codex zstd decompression", error);
25136
- throw readError("zstd-corrupt");
25792
+ throw readError2("zstd-corrupt");
25137
25793
  }
25138
25794
  throw sourceError ?? error;
25139
25795
  } finally {
@@ -25258,8 +25914,8 @@ var codexAdapter = {
25258
25914
  );
25259
25915
  },
25260
25916
  async scan(opts) {
25261
- const aggregate = createAggregate3();
25262
- const stats = await scan2(aggregate, {
25917
+ const aggregate = createAggregate4();
25918
+ const stats = await scan3(aggregate, {
25263
25919
  sinceMs: opts.sinceMs,
25264
25920
  ...opts.onProgress ? { onProgress: opts.onProgress } : {}
25265
25921
  });
@@ -25273,7 +25929,7 @@ var codexAdapter = {
25273
25929
  },
25274
25930
  async scanWindows(options) {
25275
25931
  const windows = options.map((opts) => ({
25276
- aggregate: createAggregate3(),
25932
+ aggregate: createAggregate4(),
25277
25933
  sinceMs: opts.sinceMs,
25278
25934
  onProgress: opts.onProgress
25279
25935
  }));
@@ -25290,8 +25946,8 @@ var codexAdapter = {
25290
25946
 
25291
25947
  // src/harness/cursor/cache.ts
25292
25948
  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";
25949
+ import { homedir as homedir14 } from "node:os";
25950
+ import path9 from "node:path";
25295
25951
 
25296
25952
  // src/harness/cursor/account.ts
25297
25953
  import { createHash as createHash7 } from "node:crypto";
@@ -25504,9 +26160,9 @@ function reconcile(local, api) {
25504
26160
 
25505
26161
  // src/harness/cursor/local.ts
25506
26162
  import { existsSync as existsSync10 } from "node:fs";
25507
- import { stat as stat6 } from "node:fs/promises";
25508
- import { homedir as homedir12 } from "node:os";
25509
- import path7 from "node:path";
26163
+ import { stat as stat7 } from "node:fs/promises";
26164
+ import { homedir as homedir13 } from "node:os";
26165
+ import path8 from "node:path";
25510
26166
  import { Worker } from "node:worker_threads";
25511
26167
 
25512
26168
  // src/harness/cursor/composer.ts
@@ -25710,12 +26366,12 @@ function hasComposerHalf(summary) {
25710
26366
 
25711
26367
  // src/harness/cursor/sessionCache.ts
25712
26368
  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";
26369
+ import { homedir as homedir10 } from "node:os";
26370
+ import path7 from "node:path";
25715
26371
  import { gunzipSync, gzipSync } from "node:zlib";
25716
26372
  var SESSION_CACHE_FORMAT = 1;
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`);
26373
+ var defaultSessionCacheDir = () => path7.join(homedir10(), ".config", "aistack", "cursor");
26374
+ var sessionCacheFile = (dir, root, store) => path7.join(dir, `${digest(`${root}\0${store}`)}.sessions.json.gz`);
25719
26375
  function sessionStamp(summary, newest) {
25720
26376
  if (newest === null) return null;
25721
26377
  const count2 = summary.messageCount;
@@ -25775,7 +26431,7 @@ async function loadSessionCache(file) {
25775
26431
  return out;
25776
26432
  }
25777
26433
  async function saveSessionCache(file, cache) {
25778
- await mkdir2(path6.dirname(file), { recursive: true, mode: 448 });
26434
+ await mkdir2(path7.dirname(file), { recursive: true, mode: 448 });
25779
26435
  const body = gzipSync(
25780
26436
  JSON.stringify({
25781
26437
  format: SESSION_CACHE_FORMAT,
@@ -25788,16 +26444,16 @@ async function saveSessionCache(file, cache) {
25788
26444
  }
25789
26445
 
25790
26446
  // src/harness/cursor/local.ts
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");
26447
+ function dataPath(env = process.env, home = homedir13(), platform5 = process.platform) {
26448
+ if (env.CURSOR_DATA_PATH) return path8.resolve(env.CURSOR_DATA_PATH);
26449
+ const base = platform5 === "darwin" ? path8.join(home, "Library", "Application Support") : platform5 === "win32" ? env.APPDATA || path8.join(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME || path8.join(home, ".config");
26450
+ return path8.join(base, "Cursor", "User", "workspaceStorage");
25795
26451
  }
25796
- var storeRoot = () => process.env.CURSOR_STORE_ROOT || path7.join(homedir12(), ".cursor");
25797
- var globalDb = (root) => path7.join(path7.dirname(root), "globalStorage", "state.vscdb");
26452
+ var storeRoot = () => process.env.CURSOR_STORE_ROOT || path8.join(homedir13(), ".cursor");
26453
+ var globalDb = (root) => path8.join(path8.dirname(root), "globalStorage", "state.vscdb");
25798
26454
  async function exists3(file) {
25799
26455
  try {
25800
- await stat6(file);
26456
+ await stat7(file);
25801
26457
  return true;
25802
26458
  } catch (error) {
25803
26459
  return error.code !== "ENOENT";
@@ -25808,9 +26464,9 @@ async function hasLocalSource(root = dataPath()) {
25808
26464
  [
25809
26465
  root,
25810
26466
  globalDb(root),
25811
- path7.join(storeRoot(), "projects"),
25812
- path7.join(storeRoot(), "chats"),
25813
- path7.join(storeRoot(), "acp-sessions")
26467
+ path8.join(storeRoot(), "projects"),
26468
+ path8.join(storeRoot(), "chats"),
26469
+ path8.join(storeRoot(), "acp-sessions")
25814
26470
  ].map(exists3)
25815
26471
  )).some(Boolean);
25816
26472
  }
@@ -25882,7 +26538,7 @@ async function sourceStamp(root) {
25882
26538
  const values = await Promise.all(
25883
26539
  [globalDb(root), `${globalDb(root)}-wal`].map(async (file) => {
25884
26540
  try {
25885
- const info = await stat6(file);
26541
+ const info = await stat7(file);
25886
26542
  return `${info.size}:${info.mtimeMs}`;
25887
26543
  } catch {
25888
26544
  return "unavailable";
@@ -26271,7 +26927,7 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits, stallMs
26271
26927
  }
26272
26928
  async function globalDbSize(root) {
26273
26929
  try {
26274
- const info = await stat6(globalDb(root));
26930
+ const info = await stat7(globalDb(root));
26275
26931
  return `${(info.size / 1048576).toFixed(0)} MB`;
26276
26932
  } catch {
26277
26933
  return "absent";
@@ -26472,8 +27128,8 @@ var emptyCache = () => ({
26472
27128
  local: [],
26473
27129
  sessions: []
26474
27130
  });
26475
- var cacheFile = (root, store) => path8.join(
26476
- homedir13(),
27131
+ var cacheFile = (root, store) => path9.join(
27132
+ homedir14(),
26477
27133
  ".config",
26478
27134
  "aistack",
26479
27135
  "cursor",
@@ -26512,7 +27168,7 @@ async function loadCache(file) {
26512
27168
  }
26513
27169
  }
26514
27170
  async function saveCache(file, value) {
26515
- await mkdir3(path8.dirname(file), { recursive: true, mode: 448 });
27171
+ await mkdir3(path9.dirname(file), { recursive: true, mode: 448 });
26516
27172
  const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
26517
27173
  await writeFile3(temporary, JSON.stringify(value), { mode: 384 });
26518
27174
  await rename2(temporary, file);
@@ -26568,17 +27224,17 @@ function cachedEvents(cache, sessionIds) {
26568
27224
  }
26569
27225
 
26570
27226
  // src/harness/cursor/roots.ts
26571
- import { readdir as readdir6, readFile as readFile4, stat as stat7 } from "node:fs/promises";
26572
- import { homedir as homedir14 } from "node:os";
26573
- import path9 from "node:path";
27227
+ import { readdir as readdir7, readFile as readFile4, stat as stat8 } from "node:fs/promises";
27228
+ import { homedir as homedir15 } from "node:os";
27229
+ import path10 from "node:path";
26574
27230
  var CURSOR_HOMES_KEY = "cursor";
26575
27231
  async function cursorRootFor(dir) {
26576
27232
  const expanded = expandHome(dir);
26577
- if (path9.basename(expanded) === "workspaceStorage") return expanded;
26578
- const user = path9.join(expanded, "User");
27233
+ if (path10.basename(expanded) === "workspaceStorage") return expanded;
27234
+ const user = path10.join(expanded, "User");
26579
27235
  try {
26580
- if ((await stat7(user)).isDirectory())
26581
- return path9.join(user, "workspaceStorage");
27236
+ if ((await stat8(user)).isDirectory())
27237
+ return path10.join(user, "workspaceStorage");
26582
27238
  } catch {
26583
27239
  }
26584
27240
  return expanded;
@@ -26587,7 +27243,7 @@ var FLAG = "--user-data-dir";
26587
27243
  async function runningUserDataDirs(procDir = "/proc") {
26588
27244
  let pids;
26589
27245
  try {
26590
- pids = (await readdir6(procDir)).filter((name) => /^\d+$/.test(name));
27246
+ pids = (await readdir7(procDir)).filter((name) => /^\d+$/.test(name));
26591
27247
  } catch {
26592
27248
  return [];
26593
27249
  }
@@ -26595,12 +27251,12 @@ async function runningUserDataDirs(procDir = "/proc") {
26595
27251
  for (const pid of pids) {
26596
27252
  let args;
26597
27253
  try {
26598
- args = (await readFile4(path9.join(procDir, pid, "cmdline"), "utf8")).split("\0").filter(Boolean);
27254
+ args = (await readFile4(path10.join(procDir, pid, "cmdline"), "utf8")).split("\0").filter(Boolean);
26599
27255
  } catch {
26600
27256
  continue;
26601
27257
  }
26602
27258
  for (const value of userDataDirArgs(args))
26603
- if (path9.isAbsolute(value)) candidates.add(path9.normalize(value));
27259
+ if (path10.isAbsolute(value)) candidates.add(path10.normalize(value));
26604
27260
  }
26605
27261
  const found = [];
26606
27262
  for (const dir of [...candidates].sort())
@@ -26623,10 +27279,10 @@ function userDataDirArgs(args) {
26623
27279
  return values;
26624
27280
  }
26625
27281
  async function holdsCursorData(dir) {
26626
- const file = path9.join(dir, "User", "globalStorage", "state.vscdb");
27282
+ const file = path10.join(dir, "User", "globalStorage", "state.vscdb");
26627
27283
  let db;
26628
27284
  try {
26629
- if (!(await stat7(file)).isFile()) return false;
27285
+ if (!(await stat8(file)).isFile()) return false;
26630
27286
  const { DatabaseSync } = await import("node:sqlite");
26631
27287
  db = new DatabaseSync(file, { readOnly: true });
26632
27288
  return Boolean(
@@ -26642,14 +27298,14 @@ async function holdsCursorData(dir) {
26642
27298
  }
26643
27299
  async function discoverCursorRoots(options = {}) {
26644
27300
  const env = options.env ?? process.env;
26645
- const platform4 = options.platform ?? process.platform;
27301
+ const platform5 = options.platform ?? process.platform;
26646
27302
  const fallback = dataPath(
26647
27303
  { ...env, CURSOR_DATA_PATH: void 0 },
26648
- homedir14(),
26649
- platform4
27304
+ homedir15(),
27305
+ platform5
26650
27306
  );
26651
27307
  const procDir = options.procDir ?? process.env.AISTACK_CURSOR_PROC_DIR ?? "/proc";
26652
- const running = platform4 === "linux" && procDir ? await runningUserDataDirs(procDir) : [];
27308
+ const running = platform5 === "linux" && procDir ? await runningUserDataDirs(procDir) : [];
26653
27309
  const configured = await Promise.all(
26654
27310
  [env.CURSOR_DATA_PATH, ...running].filter((dir) => Boolean(dir?.trim())).map(cursorRootFor)
26655
27311
  );
@@ -26662,10 +27318,10 @@ async function discoverCursorRoots(options = {}) {
26662
27318
  }
26663
27319
 
26664
27320
  // src/harness/cursor/scan.ts
26665
- import path11 from "node:path";
27321
+ import path12 from "node:path";
26666
27322
 
26667
27323
  // src/harness/cursor/workflow.ts
26668
- import path10 from "node:path";
27324
+ import path11 from "node:path";
26669
27325
  var TOOLS = {
26670
27326
  read_file: "Read",
26671
27327
  read_file_v2: "Read",
@@ -26706,7 +27362,7 @@ function projectHistory(options) {
26706
27362
  const scopes = /* @__PURE__ */ new Map();
26707
27363
  const inWindow = (t) => t !== null && t >= sinceMs && t <= now;
26708
27364
  for (const { session } of locals) {
26709
- const projectWorkspace = session.canonicalWorkspacePath && path10.isAbsolute(session.canonicalWorkspacePath) ? session.canonicalWorkspacePath : void 0;
27365
+ const projectWorkspace = session.canonicalWorkspacePath && path11.isAbsolute(session.canonicalWorkspacePath) ? session.canonicalWorkspacePath : void 0;
26710
27366
  const times = messageTimes(session, api);
26711
27367
  const scopeOf = (message) => {
26712
27368
  const parent = message.parentMessageId && nativeOwners.get(message.parentMessageId);
@@ -26793,7 +27449,7 @@ function projectHistory(options) {
26793
27449
  session: row.sidechain ? `${row.session}:sidechain` : row.session,
26794
27450
  sidechain: row.sidechain
26795
27451
  },
26796
- ...project && path10.isAbsolute(project) ? { projectWorkspace: project } : {},
27452
+ ...project && path11.isAbsolute(project) ? { projectWorkspace: project } : {},
26797
27453
  type: "response",
26798
27454
  tsMs: row.tsMs,
26799
27455
  responseId: `${row.source}:${row.id ?? index}`,
@@ -26896,7 +27552,7 @@ function addStats(into, from) {
26896
27552
  if (from.sourceDiscoveryComplete === false)
26897
27553
  into.sourceDiscoveryComplete = false;
26898
27554
  }
26899
- async function scan3(options) {
27555
+ async function scan4(options) {
26900
27556
  const now = options.now ?? Date.now();
26901
27557
  let discoveryComplete = true;
26902
27558
  let roots = options.roots ?? (options.root ? [options.root] : void 0);
@@ -26971,7 +27627,7 @@ async function scan3(options) {
26971
27627
  aggregate.byModel.set(model, emptyUsage());
26972
27628
  }
26973
27629
  const project = session.canonicalWorkspacePath;
26974
- if (project && path11.isAbsolute(project)) aggregate.projectDirs.add(project);
27630
+ if (project && path12.isAbsolute(project)) aggregate.projectDirs.add(project);
26975
27631
  if (session.metadata?.cursorVersion)
26976
27632
  aggregate.ccVersions.add(session.metadata.cursorVersion);
26977
27633
  let firstTime = null;
@@ -27028,7 +27684,7 @@ async function scan3(options) {
27028
27684
  else aggregate.mainTokens += countsTotal(counts2);
27029
27685
  noteSessionStart(aggregate, session, tsMs);
27030
27686
  const project = sessions.get(session)?.session.canonicalWorkspacePath;
27031
- if (project && path11.isAbsolute(project))
27687
+ if (project && path12.isAbsolute(project))
27032
27688
  noteProjectDay(aggregate, project, tsMs);
27033
27689
  }
27034
27690
  aggregate.files = local.stats.filesRead;
@@ -27070,11 +27726,11 @@ var cursorAdapter = {
27070
27726
  }
27071
27727
  return false;
27072
27728
  },
27073
- scan: scan3
27729
+ scan: scan4
27074
27730
  };
27075
27731
 
27076
27732
  // src/harness/grok/analyzer.ts
27077
- function createAggregate4() {
27733
+ function createAggregate5() {
27078
27734
  const workflowLocal = createWorkflowLocalSources();
27079
27735
  return Object.assign(createAggregate(), {
27080
27736
  workflow: createHarnessWorkflowReducer("grok-build", workflowLocal),
@@ -27098,7 +27754,7 @@ function ingestUpdate(agg, state, value, projectDir, sinceMs) {
27098
27754
  const params = root && asObj(root.params);
27099
27755
  const update2 = params && asObj(params.update);
27100
27756
  const session = params && asStr(params.sessionId);
27101
- const tsMs = timestampMs(
27757
+ const tsMs = timestampMs2(
27102
27758
  asObj(params?._meta)?.agentTimestampMs ?? root?.timestamp
27103
27759
  );
27104
27760
  if (!update2 || !session || tsMs === null) return;
@@ -27186,7 +27842,7 @@ function ingestEvent2(agg, state, value, sessionFallback, projectDir, sinceMs) {
27186
27842
  const row = asObj(value);
27187
27843
  if (!row) return;
27188
27844
  const session = asStr(row.session_id) ?? sessionFallback;
27189
- const tsMs = timestampMs(row.ts);
27845
+ const tsMs = timestampMs2(row.ts);
27190
27846
  if (!session || tsMs === null) return;
27191
27847
  if (asStr(row.type) === "tool_started") {
27192
27848
  const id = asStr(row.tool_call_id);
@@ -27207,7 +27863,7 @@ function ingestEvent2(agg, state, value, sessionFallback, projectDir, sinceMs) {
27207
27863
  });
27208
27864
  }
27209
27865
  }
27210
- var timestampMs = (value) => {
27866
+ var timestampMs2 = (value) => {
27211
27867
  if (typeof value === "string") {
27212
27868
  const parsed = Date.parse(value);
27213
27869
  return Number.isFinite(parsed) ? parsed : null;
@@ -27240,7 +27896,7 @@ function sidecarContributions(value, projectDir) {
27240
27896
  const out = [];
27241
27897
  for (const raw of turns) {
27242
27898
  const turn = asObj(raw);
27243
- const tsMs = turn && timestampMs(turn.endedAt);
27899
+ const tsMs = turn && timestampMs2(turn.endedAt);
27244
27900
  if (!turn || tsMs === null) continue;
27245
27901
  const models = [];
27246
27902
  const perModel = asObj(turn.modelUsage);
@@ -27272,7 +27928,7 @@ function terminalContribution(value, projectDir) {
27272
27928
  if (!update2 || asStr(update2.sessionUpdate) !== "turn_completed") return null;
27273
27929
  const usage = asObj(update2.usage);
27274
27930
  const sessionId = params && asStr(params.sessionId);
27275
- const tsMs = timestampMs(meta?.agentTimestampMs ?? root?.timestamp);
27931
+ const tsMs = timestampMs2(meta?.agentTimestampMs ?? root?.timestamp);
27276
27932
  if (!usage || !sessionId || tsMs === null) return null;
27277
27933
  const models = [];
27278
27934
  for (const [model, row] of Object.entries(asObj(usage.modelUsage) ?? {})) {
@@ -27317,17 +27973,17 @@ function ingestContribution(agg, row) {
27317
27973
 
27318
27974
  // src/harness/grok/scan.ts
27319
27975
  import { createReadStream as createReadStream2 } from "node:fs";
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";
27976
+ import { readdir as readdir9, readFile as readFile6, stat as stat9 } from "node:fs/promises";
27977
+ import { homedir as homedir17 } from "node:os";
27978
+ import path14 from "node:path";
27323
27979
  import readline2 from "node:readline";
27324
27980
  import { parse as parseToml3 } from "smol-toml";
27325
27981
 
27326
27982
  // src/harness/grok/context.ts
27327
27983
  import { createHash as createHash8 } from "node:crypto";
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";
27984
+ import { appendFile, mkdir as mkdir4, readdir as readdir8, readFile as readFile5, unlink as unlink2 } from "node:fs/promises";
27985
+ import { homedir as homedir16 } from "node:os";
27986
+ import path13 from "node:path";
27331
27987
  var DAY_MS = 864e5;
27332
27988
  var hash = (value) => createHash8("sha256").update(value).digest("hex");
27333
27989
  function contextCall(value) {
@@ -27350,12 +28006,12 @@ function contextCall(value) {
27350
28006
  };
27351
28007
  }
27352
28008
  function contextCacheDirectory(root) {
27353
- return path12.join(
27354
- homedir15(),
28009
+ return path13.join(
28010
+ homedir16(),
27355
28011
  ".config",
27356
28012
  "aistack",
27357
28013
  "grok-context",
27358
- hash(path12.resolve(root))
28014
+ hash(path13.resolve(root))
27359
28015
  );
27360
28016
  }
27361
28017
  async function optionalRead(file) {
@@ -27371,21 +28027,21 @@ async function retainedContextCalls(root, sessions, cacheDir = contextCacheDirec
27371
28027
  const calls = /* @__PURE__ */ new Map();
27372
28028
  let files = [];
27373
28029
  try {
27374
- files = await readdir7(cacheDir);
28030
+ files = await readdir8(cacheDir);
27375
28031
  } catch (error) {
27376
28032
  if (error.code !== "ENOENT") throw error;
27377
28033
  }
27378
28034
  for (const file of files) {
27379
28035
  if (!/^\d{4}-\d{2}-\d{2}\.jsonl$/.test(file)) continue;
27380
28036
  if (Date.parse(file.slice(0, 10)) + DAY_MS < cutoff) {
27381
- await unlink2(path12.join(cacheDir, file)).catch(
28037
+ await unlink2(path13.join(cacheDir, file)).catch(
27382
28038
  (error) => {
27383
28039
  if (error.code !== "ENOENT") throw error;
27384
28040
  }
27385
28041
  );
27386
28042
  continue;
27387
28043
  }
27388
- const raw2 = await optionalRead(path12.join(cacheDir, file));
28044
+ const raw2 = await optionalRead(path13.join(cacheDir, file));
27389
28045
  if (raw2 && !raw2.endsWith("\n"))
27390
28046
  throw Object.assign(new Error("Incomplete Grok context cache"), {
27391
28047
  code: "GROK_INCOMPLETE_CONTEXT_CACHE"
@@ -27406,7 +28062,7 @@ async function retainedContextCalls(root, sessions, cacheDir = contextCacheDirec
27406
28062
  }
27407
28063
  }
27408
28064
  const raw = await optionalRead(
27409
- path12.join(root, "..", "logs", "unified.jsonl")
28065
+ path13.join(root, "..", "logs", "unified.jsonl")
27410
28066
  );
27411
28067
  const additions = /* @__PURE__ */ new Map();
27412
28068
  for (const line of raw.slice(0, raw.lastIndexOf("\n") + 1).split("\n")) {
@@ -27429,7 +28085,7 @@ async function retainedContextCalls(root, sessions, cacheDir = contextCacheDirec
27429
28085
  await mkdir4(cacheDir, { recursive: true, mode: 448 });
27430
28086
  for (const [date, lines2] of additions) {
27431
28087
  await appendFile(
27432
- path12.join(cacheDir, `${date}.jsonl`),
28088
+ path13.join(cacheDir, `${date}.jsonl`),
27433
28089
  `${lines2.join("\n")}
27434
28090
  `,
27435
28091
  { mode: 384 }
@@ -27441,9 +28097,9 @@ async function retainedContextCalls(root, sessions, cacheDir = contextCacheDirec
27441
28097
 
27442
28098
  // src/harness/grok/scan.ts
27443
28099
  async function discoverGrokHomes() {
27444
- const home = homedir16();
28100
+ const home = homedir17();
27445
28101
  return discoverHomes({
27446
- defaults: [path13.join(home, ".grok")],
28102
+ defaults: [path14.join(home, ".grok")],
27447
28103
  configured: [process.env.GROK_HOME],
27448
28104
  siblings: [{ parent: home, prefix: ".grok" }],
27449
28105
  remember: "grok-build"
@@ -27451,14 +28107,14 @@ async function discoverGrokHomes() {
27451
28107
  }
27452
28108
  async function sessionRoots() {
27453
28109
  return (await discoverGrokHomes()).homes.map(
27454
- (home) => path13.join(home, "sessions")
28110
+ (home) => path14.join(home, "sessions")
27455
28111
  );
27456
28112
  }
27457
28113
  async function evidenceBytes(dir) {
27458
28114
  let total = 0;
27459
28115
  for (const name of ["usage.json", "updates.jsonl", "events.jsonl"]) {
27460
28116
  try {
27461
- total += (await stat8(path13.join(dir, name))).size;
28117
+ total += (await stat9(path14.join(dir, name))).size;
27462
28118
  } catch (error) {
27463
28119
  if (error?.code !== "ENOENT")
27464
28120
  traceError("grok evidence stat", error, "warn");
@@ -27473,7 +28129,7 @@ async function stableRead(file, jsonl) {
27473
28129
  for (const delay of delays) {
27474
28130
  if (delay) await pause(delay);
27475
28131
  try {
27476
- const before = await stat8(file);
28132
+ const before = await stat9(file);
27477
28133
  if (!before.isFile()) return { complete: false };
27478
28134
  if (jsonl) {
27479
28135
  const lines2 = [];
@@ -27491,12 +28147,12 @@ async function stableRead(file, jsonl) {
27491
28147
  lines2.push(null);
27492
28148
  }
27493
28149
  }
27494
- const after = await stat8(file);
28150
+ const after = await stat9(file);
27495
28151
  if (before.size === after.size && before.mtimeMs === after.mtimeMs)
27496
28152
  return { lines: lines2, complete: true };
27497
28153
  } else {
27498
28154
  const raw = await readFile6(file, "utf8");
27499
- const after = await stat8(file);
28155
+ const after = await stat9(file);
27500
28156
  if (before.size === after.size && before.mtimeMs === after.mtimeMs)
27501
28157
  return { json: JSON.parse(raw), complete: true };
27502
28158
  }
@@ -27509,16 +28165,16 @@ async function stableRead(file, jsonl) {
27509
28165
  }
27510
28166
  function absoluteCwd(value) {
27511
28167
  const cwd = asStr(value);
27512
- return cwd && path13.isAbsolute(cwd) && !cwd.includes("\0") ? cwd : void 0;
28168
+ return cwd && path14.isAbsolute(cwd) && !cwd.includes("\0") ? cwd : void 0;
27513
28169
  }
27514
28170
  async function workspaceCwd(workspacePath, entries) {
27515
28171
  try {
27516
- const cwd = absoluteCwd(decodeURIComponent(path13.basename(workspacePath)));
28172
+ const cwd = absoluteCwd(decodeURIComponent(path14.basename(workspacePath)));
27517
28173
  if (cwd !== void 0) return cwd;
27518
28174
  } catch {
27519
28175
  }
27520
28176
  if (entries.some((entry) => entry.name === ".cwd" && entry.isFile())) {
27521
- const raw = await readFile6(path13.join(workspacePath, ".cwd"), "utf8").catch(
28177
+ const raw = await readFile6(path14.join(workspacePath, ".cwd"), "utf8").catch(
27522
28178
  () => void 0
27523
28179
  );
27524
28180
  return absoluteCwd(raw);
@@ -27526,18 +28182,18 @@ async function workspaceCwd(workspacePath, entries) {
27526
28182
  }
27527
28183
  async function directories(root) {
27528
28184
  try {
27529
- const workspaces = await readdir8(root, { withFileTypes: true });
28185
+ const workspaces = await readdir9(root, { withFileTypes: true });
27530
28186
  const out = [];
27531
28187
  for (const workspace of workspaces) {
27532
28188
  if (!workspace.isDirectory() || workspace.isSymbolicLink()) continue;
27533
- const workspacePath = path13.join(root, workspace.name);
27534
- const entries = await readdir8(workspacePath, {
28189
+ const workspacePath = path14.join(root, workspace.name);
28190
+ const entries = await readdir9(workspacePath, {
27535
28191
  withFileTypes: true
27536
28192
  });
27537
28193
  const cwd = await workspaceCwd(workspacePath, entries);
27538
28194
  for (const session of entries) {
27539
28195
  if (session.isDirectory() && !session.isSymbolicLink())
27540
- out.push({ dir: path13.join(workspacePath, session.name), cwd });
28196
+ out.push({ dir: path14.join(workspacePath, session.name), cwd });
27541
28197
  }
27542
28198
  }
27543
28199
  return out.sort((a, b) => {
@@ -27554,7 +28210,7 @@ async function modelAliasesForRoot(root) {
27554
28210
  if (process.env.GROK_MODELS_BASE_URL) return /* @__PURE__ */ new Map();
27555
28211
  try {
27556
28212
  const parsed = asObj(
27557
- parseToml3(await readFile6(path13.join(root, "..", "config.toml"), "utf8"))
28213
+ parseToml3(await readFile6(path14.join(root, "..", "config.toml"), "utf8"))
27558
28214
  );
27559
28215
  if (!parsed || asObj(parsed.endpoints)?.models_base_url) return /* @__PURE__ */ new Map();
27560
28216
  const models = asObj(parsed.model);
@@ -27570,7 +28226,7 @@ async function modelAliasesForRoot(root) {
27570
28226
  return /* @__PURE__ */ new Map();
27571
28227
  }
27572
28228
  }
27573
- async function scan4(agg, opts = {}) {
28229
+ async function scan5(agg, opts = {}) {
27574
28230
  return (await scanWindows2(
27575
28231
  [{ aggregate: agg, sinceMs: opts.sinceMs, onProgress: opts.onProgress }],
27576
28232
  opts
@@ -27585,14 +28241,14 @@ async function scanWindows2(windows, opts = {}) {
27585
28241
  }));
27586
28242
  const discovery = opts.roots ? { homes: [], complete: true } : await discoverGrokHomes();
27587
28243
  let complete = discovery.complete;
27588
- const roots = opts.roots ?? discovery.homes.map((home) => path13.join(home, "sessions"));
28244
+ const roots = opts.roots ?? discovery.homes.map((home) => path14.join(home, "sessions"));
27589
28245
  const listed = /* @__PURE__ */ new Map();
27590
28246
  const fullest = /* @__PURE__ */ new Map();
27591
28247
  for (const root of roots) {
27592
28248
  const dirs = await directories(root);
27593
28249
  listed.set(root, dirs);
27594
28250
  for (const { dir } of dirs ?? []) {
27595
- const key2 = path13.relative(root, dir);
28251
+ const key2 = path14.relative(root, dir);
27596
28252
  const bytes = await evidenceBytes(dir);
27597
28253
  const held = fullest.get(key2);
27598
28254
  if (!held || bytes > held.bytes) fullest.set(key2, { dir, bytes });
@@ -27607,13 +28263,13 @@ async function scanWindows2(windows, opts = {}) {
27607
28263
  continue;
27608
28264
  }
27609
28265
  for (const { dir, cwd } of dirs) {
27610
- if (fullest.get(path13.relative(root, dir))?.dir !== dir) {
28266
+ if (fullest.get(path14.relative(root, dir))?.dir !== dir) {
27611
28267
  stats.filesSkippedAsDuplicate++;
27612
28268
  continue;
27613
28269
  }
27614
28270
  let entries;
27615
28271
  try {
27616
- entries = await readdir8(dir, { withFileTypes: true });
28272
+ entries = await readdir9(dir, { withFileTypes: true });
27617
28273
  } catch (error) {
27618
28274
  traceError("grok session listing", error);
27619
28275
  complete = false;
@@ -27622,10 +28278,10 @@ async function scanWindows2(windows, opts = {}) {
27622
28278
  const files = new Map(
27623
28279
  entries.filter(
27624
28280
  (e) => e.isFile() && (isGrokEvidenceFile(e.name) || e.name === "summary.json")
27625
- ).map((e) => [e.name, path13.join(dir, e.name)])
28281
+ ).map((e) => [e.name, path14.join(dir, e.name)])
27626
28282
  );
27627
28283
  let projectDir = cwd;
27628
- let sessionFallback = path13.basename(dir);
28284
+ let sessionFallback = path14.basename(dir);
27629
28285
  let child = false;
27630
28286
  let parentSession;
27631
28287
  const summary = files.get("summary.json");
@@ -27803,8 +28459,8 @@ var grokAdapter = {
27803
28459
  opts.sinceMs
27804
28460
  ),
27805
28461
  async scan(opts) {
27806
- const aggregate = createAggregate4();
27807
- const result = await scan4(aggregate, opts);
28462
+ const aggregate = createAggregate5();
28463
+ const result = await scan5(aggregate, opts);
27808
28464
  return {
27809
28465
  aggregate,
27810
28466
  stats: result.stats,
@@ -27816,7 +28472,7 @@ var grokAdapter = {
27816
28472
  },
27817
28473
  async scanWindows(options) {
27818
28474
  const windows = options.map((opts) => ({
27819
- aggregate: createAggregate4(),
28475
+ aggregate: createAggregate5(),
27820
28476
  sinceMs: opts.sinceMs,
27821
28477
  onProgress: opts.onProgress
27822
28478
  }));
@@ -27851,7 +28507,7 @@ var OPENCODE_BUILTIN_TOOLS = /* @__PURE__ */ new Set([
27851
28507
  "websearch",
27852
28508
  "write"
27853
28509
  ]);
27854
- function createAggregate5() {
28510
+ function createAggregate6() {
27855
28511
  const workflowLocal = createWorkflowLocalSources();
27856
28512
  return Object.assign(createAggregate(), {
27857
28513
  workflow: createHarnessWorkflowReducer("opencode", workflowLocal),
@@ -28026,15 +28682,15 @@ function ingestTypedSkill2(agg, row) {
28026
28682
 
28027
28683
  // src/harness/opencode/scan.ts
28028
28684
  import { readFileSync as readFileSync12 } from "node:fs";
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";
28685
+ import { readdir as readdir10, realpath as realpath5, stat as stat10 } from "node:fs/promises";
28686
+ import { homedir as homedir18 } from "node:os";
28687
+ import path15 from "node:path";
28032
28688
  var OPENCODE_MIGRATION_CEILING = 20260622202450;
28033
28689
  async function opencodeDataDirs() {
28034
28690
  const xdg = process.env.XDG_DATA_HOME?.trim();
28035
28691
  return discoverHomes({
28036
- defaults: [path14.join(homedir17(), ".local", "share", "opencode")],
28037
- configured: [xdg ? path14.join(xdg, "opencode") : void 0],
28692
+ defaults: [path15.join(homedir18(), ".local", "share", "opencode")],
28693
+ configured: [xdg ? path15.join(xdg, "opencode") : void 0],
28038
28694
  remember: "opencode"
28039
28695
  });
28040
28696
  }
@@ -28043,23 +28699,23 @@ function isStoreFile(basename6) {
28043
28699
  }
28044
28700
  async function dbFilesIn(root) {
28045
28701
  try {
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();
28702
+ const entries = await readdir10(root, { withFileTypes: true });
28703
+ return entries.filter((e) => e.isFile() && isStoreFile(e.name)).map((e) => path15.join(root, e.name)).sort();
28048
28704
  } catch (error) {
28049
28705
  if (error?.code !== "ENOENT")
28050
28706
  traceError("opencode database discovery", error, "warn");
28051
28707
  return [];
28052
28708
  }
28053
28709
  }
28054
- async function storeFiles(roots) {
28710
+ async function storeFiles2(roots) {
28055
28711
  const dirs = roots ?? (await opencodeDataDirs()).homes;
28056
28712
  const candidates = [];
28057
28713
  for (const root of dirs) candidates.push(...await dbFilesIn(root));
28058
28714
  const override = roots ? void 0 : process.env.OPENCODE_DB?.trim();
28059
28715
  if (override)
28060
28716
  candidates.push(
28061
- path14.resolve(
28062
- process.env.XDG_DATA_HOME?.trim() || path14.join(homedir17(), ".local", "share"),
28717
+ path15.resolve(
28718
+ process.env.XDG_DATA_HOME?.trim() || path15.join(homedir18(), ".local", "share"),
28063
28719
  "opencode",
28064
28720
  override
28065
28721
  )
@@ -28069,7 +28725,7 @@ async function storeFiles(roots) {
28069
28725
  for (const file of candidates) {
28070
28726
  let key2 = file;
28071
28727
  try {
28072
- key2 = await realpath4(file);
28728
+ key2 = await realpath5(file);
28073
28729
  } catch (error) {
28074
28730
  if (error?.code !== "ENOENT")
28075
28731
  traceError("opencode database path resolution", error, "warn");
@@ -28080,7 +28736,7 @@ async function storeFiles(roots) {
28080
28736
  }
28081
28737
  return files;
28082
28738
  }
28083
- async function loadSqlite() {
28739
+ async function loadSqlite2() {
28084
28740
  try {
28085
28741
  const mod = await import("node:sqlite");
28086
28742
  if (typeof mod.DatabaseSync !== "function") return null;
@@ -28091,31 +28747,31 @@ async function loadSqlite() {
28091
28747
  return null;
28092
28748
  }
28093
28749
  }
28094
- function errorClass2(e) {
28750
+ function errorClass3(e) {
28095
28751
  const code2 = e?.code;
28096
28752
  if (typeof code2 === "string" && code2.length > 0) return code2;
28097
28753
  return e instanceof Error ? e.constructor.name : "unknown";
28098
28754
  }
28099
- var readError2 = (reason) => Object.assign(new Error(reason), { code: reason });
28100
- async function scan5(agg, opts = {}) {
28755
+ var readError3 = (reason) => Object.assign(new Error(reason), { code: reason });
28756
+ async function scan6(agg, opts = {}) {
28101
28757
  const stats = emptyScanStats();
28102
- const open4 = await loadSqlite();
28758
+ const open4 = await loadSqlite2();
28103
28759
  const sinceMs = opts.sinceMs ?? 0;
28104
28760
  const state = createDbFoldState();
28105
28761
  readConfiguredMcpServers2(agg, state, opts.configFile);
28106
- for (const file of await storeFiles(opts.roots)) {
28762
+ for (const file of await storeFiles2(opts.roots)) {
28107
28763
  stats.filesFound++;
28108
28764
  agg.files++;
28109
28765
  try {
28110
- if (open4 === null) throw readError2("sqlite-unsupported");
28766
+ if (open4 === null) throw readError3("sqlite-unsupported");
28111
28767
  readDb(agg, state, open4, file, sinceMs);
28112
28768
  stats.filesRead++;
28113
28769
  } catch (e) {
28114
28770
  traceError("opencode database read", e);
28115
28771
  stats.filesUnreadable++;
28116
28772
  stats.unreadableFiles.push({
28117
- path: path14.basename(file),
28118
- reason: errorClass2(e)
28773
+ path: path15.basename(file),
28774
+ reason: errorClass3(e)
28119
28775
  });
28120
28776
  }
28121
28777
  if (opts.onProgress) opts.onProgress(stats.filesFound);
@@ -28129,11 +28785,11 @@ function checkMigrationCeiling(db) {
28129
28785
  } catch (error) {
28130
28786
  if (error?.code !== "ENOENT")
28131
28787
  traceError("opencode database close", error, "warn");
28132
- throw readError2("schema-unversioned");
28788
+ throw readError3("schema-unversioned");
28133
28789
  }
28134
28790
  const prefix = Number.parseInt(String(newest ?? ""), 10);
28135
- if (!Number.isFinite(prefix)) throw readError2("schema-unversioned");
28136
- if (prefix > OPENCODE_MIGRATION_CEILING) throw readError2("schema-too-new");
28791
+ if (!Number.isFinite(prefix)) throw readError3("schema-unversioned");
28792
+ if (prefix > OPENCODE_MIGRATION_CEILING) throw readError3("schema-too-new");
28137
28793
  }
28138
28794
  function readDb(agg, state, open4, file, sinceMs) {
28139
28795
  const db = open4(file);
@@ -28300,8 +28956,8 @@ function pickTs(jsonTs, columnTs) {
28300
28956
  }
28301
28957
  function opencodeConfigFile() {
28302
28958
  const xdg = process.env.XDG_CONFIG_HOME;
28303
- const base = xdg || path14.join(homedir17(), ".config");
28304
- return path14.join(base, "opencode", "opencode.json");
28959
+ const base = xdg || path15.join(homedir18(), ".config");
28960
+ return path15.join(base, "opencode", "opencode.json");
28305
28961
  }
28306
28962
  function readConfiguredMcpServers2(agg, state, configFile) {
28307
28963
  const file = configFile ?? opencodeConfigFile();
@@ -28351,9 +29007,9 @@ function stripJsonc(text) {
28351
29007
  return out.replace(/,(\s*[}\]])/g, "$1");
28352
29008
  }
28353
29009
  async function detectOpencode(opts) {
28354
- const open4 = await loadSqlite();
29010
+ const open4 = await loadSqlite2();
28355
29011
  if (open4 === null) return false;
28356
- for (const file of await storeFiles(opts.roots)) {
29012
+ for (const file of await storeFiles2(opts.roots)) {
28357
29013
  if (!await exists4(file)) continue;
28358
29014
  let db = null;
28359
29015
  try {
@@ -28378,7 +29034,7 @@ async function detectOpencode(opts) {
28378
29034
  }
28379
29035
  async function exists4(p8) {
28380
29036
  try {
28381
- await stat9(p8);
29037
+ await stat10(p8);
28382
29038
  return true;
28383
29039
  } catch (error) {
28384
29040
  if (error?.code !== "ENOENT")
@@ -28399,8 +29055,8 @@ var opencodeAdapter = {
28399
29055
  });
28400
29056
  },
28401
29057
  async scan(opts) {
28402
- const aggregate = createAggregate5();
28403
- const stats = await scan5(aggregate, {
29058
+ const aggregate = createAggregate6();
29059
+ const stats = await scan6(aggregate, {
28404
29060
  sinceMs: opts.sinceMs,
28405
29061
  ...opts.onProgress ? { onProgress: opts.onProgress } : {}
28406
29062
  });
@@ -28414,14 +29070,14 @@ var opencodeAdapter = {
28414
29070
  };
28415
29071
 
28416
29072
  // src/harness/pi/analyzer.ts
28417
- function createAggregate6() {
29073
+ function createAggregate7() {
28418
29074
  const workflowLocal = createWorkflowLocalSources();
28419
29075
  return Object.assign(createAggregate(), {
28420
29076
  workflow: createHarnessWorkflowReducer("pi-mono", workflowLocal),
28421
29077
  workflowLocal
28422
29078
  });
28423
29079
  }
28424
- function createFoldState() {
29080
+ function createFoldState2() {
28425
29081
  return { seenUsage: /* @__PURE__ */ new Set() };
28426
29082
  }
28427
29083
  function createFileState2() {
@@ -28608,17 +29264,17 @@ function readCounts2(usageRaw) {
28608
29264
 
28609
29265
  // src/harness/pi/scan.ts
28610
29266
  import { createReadStream as createReadStream3 } from "node:fs";
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";
29267
+ import { readdir as readdir11, realpath as realpath6, stat as stat11 } from "node:fs/promises";
29268
+ import { homedir as homedir19 } from "node:os";
29269
+ import path16 from "node:path";
28614
29270
  import readline3 from "node:readline";
28615
29271
  var MAX_SESSION_VERSION = 3;
28616
29272
  async function discoverSessionRoots() {
28617
29273
  const agentDir = process.env.PI_CODING_AGENT_DIR?.trim();
28618
29274
  return discoverHomes({
28619
- defaults: [path15.join(homedir18(), ".pi", "agent", "sessions")],
29275
+ defaults: [path16.join(homedir19(), ".pi", "agent", "sessions")],
28620
29276
  configured: [
28621
- agentDir ? path15.join(agentDir, "sessions") : void 0,
29277
+ agentDir ? path16.join(agentDir, "sessions") : void 0,
28622
29278
  process.env.PI_CODING_AGENT_SESSION_DIR
28623
29279
  ],
28624
29280
  remember: "pi-mono"
@@ -28634,22 +29290,22 @@ function isSessionFile(basename6) {
28634
29290
  async function* walkSessions(dir) {
28635
29291
  let entries;
28636
29292
  try {
28637
- entries = await readdir10(dir, { withFileTypes: true });
29293
+ entries = await readdir11(dir, { withFileTypes: true });
28638
29294
  } catch (error) {
28639
29295
  if (error?.code !== "ENOENT")
28640
29296
  traceError("pi transcript discovery", error, "warn");
28641
29297
  return;
28642
29298
  }
28643
29299
  for (const e of entries) {
28644
- const full = path15.join(dir, e.name);
29300
+ const full = path16.join(dir, e.name);
28645
29301
  if (e.isDirectory()) yield* walkSessions(full);
28646
29302
  else if (e.isFile() && isSessionFile(e.name)) yield full;
28647
29303
  }
28648
29304
  }
28649
- async function scan6(agg, opts = {}) {
29305
+ async function scan7(agg, opts = {}) {
28650
29306
  const stats = emptyScanStats();
28651
29307
  const visited = /* @__PURE__ */ new Set();
28652
- const fold = createFoldState();
29308
+ const fold = createFoldState2();
28653
29309
  const discovery = opts.roots ? { homes: opts.roots, complete: true } : await discoverSessionRoots();
28654
29310
  stats.sourceDiscoveryComplete = discovery.complete;
28655
29311
  for (const root of discovery.homes) {
@@ -28658,7 +29314,7 @@ async function scan6(agg, opts = {}) {
28658
29314
  stats.filesFound++;
28659
29315
  let resolved;
28660
29316
  try {
28661
- resolved = await realpath5(file);
29317
+ resolved = await realpath6(file);
28662
29318
  } catch (error) {
28663
29319
  if (error?.code !== "ENOENT")
28664
29320
  traceError("pi transcript path resolution", error, "warn");
@@ -28671,7 +29327,7 @@ async function scan6(agg, opts = {}) {
28671
29327
  visited.add(resolved);
28672
29328
  if (opts.sinceMs !== void 0) {
28673
29329
  try {
28674
- const st = await stat10(file);
29330
+ const st = await stat11(file);
28675
29331
  if (st.mtimeMs < opts.sinceMs) {
28676
29332
  stats.filesSkippedByMtime++;
28677
29333
  continue;
@@ -28695,7 +29351,7 @@ async function scan6(agg, opts = {}) {
28695
29351
  stats.filesUnreadable++;
28696
29352
  stats.filesRead--;
28697
29353
  stats.unreadableFiles.push({
28698
- path: path15.relative(root, file),
29354
+ path: path16.relative(root, file),
28699
29355
  reason: "version-too-new"
28700
29356
  });
28701
29357
  }
@@ -28704,7 +29360,7 @@ async function scan6(agg, opts = {}) {
28704
29360
  stats.filesUnreadable++;
28705
29361
  stats.filesRead--;
28706
29362
  stats.unreadableFiles.push({
28707
- path: path15.relative(root, file),
29363
+ path: path16.relative(root, file),
28708
29364
  reason: "read-error"
28709
29365
  });
28710
29366
  }
@@ -28714,7 +29370,7 @@ async function scan6(agg, opts = {}) {
28714
29370
  }
28715
29371
  async function exists5(p8) {
28716
29372
  try {
28717
- await stat10(p8);
29373
+ await stat11(p8);
28718
29374
  return true;
28719
29375
  } catch (error) {
28720
29376
  if (error?.code !== "ENOENT")
@@ -28785,8 +29441,8 @@ var piAdapter = {
28785
29441
  );
28786
29442
  },
28787
29443
  async scan(opts) {
28788
- const aggregate = createAggregate6();
28789
- const stats = await scan6(aggregate, {
29444
+ const aggregate = createAggregate7();
29445
+ const stats = await scan7(aggregate, {
28790
29446
  sinceMs: opts.sinceMs,
28791
29447
  ...opts.onProgress ? { onProgress: opts.onProgress } : {}
28792
29448
  });
@@ -28807,7 +29463,8 @@ var HARNESS_ADAPTERS = [
28807
29463
  grokAdapter,
28808
29464
  cursorAdapter,
28809
29465
  opencodeAdapter,
28810
- piAdapter
29466
+ piAdapter,
29467
+ antigravityAdapter
28811
29468
  ];
28812
29469
  function harnessLabel2(name) {
28813
29470
  if (name === CLAUDE_HARNESS_NAME) return "Claude Code";
@@ -28816,6 +29473,7 @@ function harnessLabel2(name) {
28816
29473
  if (name === GROK_HARNESS_NAME) return "Grok Build";
28817
29474
  if (name === OPENCODE_HARNESS_NAME) return "opencode";
28818
29475
  if (name === PI_HARNESS_NAME) return "Pi";
29476
+ if (name === ANTIGRAVITY_HARNESS_NAME) return "Antigravity";
28819
29477
  return name;
28820
29478
  }
28821
29479
  function harnessListLabel(adapters) {
@@ -28850,7 +29508,7 @@ var MCP_ADD_ARGS = [
28850
29508
  "mcp"
28851
29509
  ];
28852
29510
  var MCP_REMOVE_ARGS = ["mcp", "remove", "--scope", "user", "aistack"];
28853
- var SKILL_DEST = join13(homedir19(), ".claude", "skills", "aistack-sync");
29511
+ var SKILL_DEST = join13(homedir20(), ".claude", "skills", "aistack-sync");
28854
29512
  function runClaude(args) {
28855
29513
  const r = spawnSync("claude", args, { encoding: "utf-8" });
28856
29514
  const notFound = r.error !== void 0 && r.error.code === "ENOENT";
@@ -28863,7 +29521,7 @@ function runClaude(args) {
28863
29521
  function claudeOnPath(run = runClaude) {
28864
29522
  return !run(["--version"]).notFound;
28865
29523
  }
28866
- function findSkillSource(fromDir = dirname5(fileURLToPath(import.meta.url))) {
29524
+ function findSkillSource(fromDir = dirname5(fileURLToPath2(import.meta.url))) {
28867
29525
  let dir = fromDir;
28868
29526
  for (let i = 0; i < 4; i++) {
28869
29527
  const candidate = join13(dir, "skills", "aistack-sync");
@@ -29080,8 +29738,8 @@ async function createCommand() {
29080
29738
  }
29081
29739
 
29082
29740
  // src/commands/cursorFolders.ts
29083
- import { realpath as realpath6, stat as stat11 } from "node:fs/promises";
29084
- import path16 from "node:path";
29741
+ import { realpath as realpath7, stat as stat12 } from "node:fs/promises";
29742
+ import path17 from "node:path";
29085
29743
  var console_ = { print: (line) => process.stdout.write(`${line}
29086
29744
  `) };
29087
29745
  async function cursorFoldersCommand(action = "list", dir, out = console_) {
@@ -29113,7 +29771,7 @@ async function cursorFoldersCommand(action = "list", dir, out = console_) {
29113
29771
  const root = await cursorRootFor(dir);
29114
29772
  if (action === "remove") {
29115
29773
  const stored = await rememberedHomes(CURSOR_HOMES_KEY);
29116
- const target = [root, await realpath6(root).catch(() => root)].find(
29774
+ const target = [root, await realpath7(root).catch(() => root)].find(
29117
29775
  (entry) => stored.includes(entry)
29118
29776
  ) ?? root;
29119
29777
  if (await forgetHome(CURSOR_HOMES_KEY, target))
@@ -29123,8 +29781,8 @@ async function cursorFoldersCommand(action = "list", dir, out = console_) {
29123
29781
  }
29124
29782
  let real;
29125
29783
  try {
29126
- real = await realpath6(root);
29127
- if (path16.basename(real) !== "workspaceStorage" || !(await stat11(real)).isDirectory())
29784
+ real = await realpath7(root);
29785
+ if (path17.basename(real) !== "workspaceStorage" || !(await stat12(real)).isDirectory())
29128
29786
  throw new Error("not a Cursor folder");
29129
29787
  } catch {
29130
29788
  fail(
@@ -29234,25 +29892,104 @@ async function loginCommand(options = {}) {
29234
29892
  import * as p7 from "@clack/prompts";
29235
29893
 
29236
29894
  // src/autosync/optin.ts
29237
- import { existsSync as existsSync17 } from "node:fs";
29238
- import { homedir as homedir25 } from "node:os";
29895
+ import { existsSync as existsSync18 } from "node:fs";
29896
+ import { homedir as homedir27 } from "node:os";
29239
29897
  import { dirname as dirname12, join as join20 } from "node:path";
29240
29898
  import * as p6 from "@clack/prompts";
29241
29899
 
29242
- // src/autosync/codexHook.ts
29243
- import { createHash as createHash9 } from "node:crypto";
29900
+ // src/autosync/antigravityHook.ts
29244
29901
  import {
29245
29902
  existsSync as existsSync13,
29246
29903
  mkdirSync as mkdirSync4,
29247
29904
  readFileSync as readFileSync14,
29248
- realpathSync as realpathSync3,
29905
+ unlinkSync as unlinkSync5,
29249
29906
  writeFileSync as writeFileSync4
29250
29907
  } from "node:fs";
29251
- import { homedir as homedir20 } from "node:os";
29252
- import { dirname as dirname7, join as join15 } from "node:path";
29908
+ import { homedir as homedir21, platform as platform2 } from "node:os";
29909
+ import path18, { dirname as dirname7 } from "node:path";
29910
+ var HOOK_NAME = "aistack";
29911
+ function antigravityHookFile() {
29912
+ const configured = process.env.ANTIGRAVITY_GEMINI_DIR?.trim();
29913
+ const gemini = configured ? path18.resolve(homedir21(), configured) : path18.join(homedir21(), ".gemini");
29914
+ return path18.join(gemini, "config", "hooks.json");
29915
+ }
29916
+ var SYNC_COMMAND = "npx -y @use-aistack/cli@latest sync --auto || npx -y --prefer-offline @use-aistack/cli sync --auto";
29917
+ function antigravityHookCommand(os = platform2()) {
29918
+ if (os === "win32") {
29919
+ return `Start-Process -WindowStyle Hidden -FilePath "cmd.exe" -ArgumentList '/d /s /c "set AISTACK_HOOK_SOURCE=antigravity&& (${SYNC_COMMAND}) <NUL >NUL 2>&1"'`;
29920
+ }
29921
+ const detach = os === "darwin" ? "nohup" : "setsid nohup";
29922
+ return `${detach} sh -c 'export AISTACK_HOOK_SOURCE=antigravity; ${SYNC_COMMAND}' </dev/null >/dev/null 2>&1 &`;
29923
+ }
29924
+ function readHooksFile(file) {
29925
+ if (!existsSync13(file)) return { value: {} };
29926
+ try {
29927
+ const value = JSON.parse(readFileSync14(file, "utf-8"));
29928
+ if (value && typeof value === "object" && !Array.isArray(value))
29929
+ return { value };
29930
+ } catch {
29931
+ return { error: `${file} is not valid JSON. Fix it, then retry.` };
29932
+ }
29933
+ return { error: `${file} does not hold a JSON object. Fix it, then retry.` };
29934
+ }
29935
+ function isOurs(entry) {
29936
+ const command = entry?.command;
29937
+ return typeof command === "string" && command.includes("@use-aistack/cli") && command.includes("sync --auto");
29938
+ }
29939
+ function installAntigravityAutoSyncHook(file = antigravityHookFile(), os = platform2()) {
29940
+ const read3 = readHooksFile(file);
29941
+ if ("error" in read3) return { ok: false, message: read3.error };
29942
+ const value = {
29943
+ ...read3.value,
29944
+ [HOOK_NAME]: {
29945
+ SessionStart: [
29946
+ { type: "command", command: antigravityHookCommand(os), timeout: 10 }
29947
+ ]
29948
+ }
29949
+ };
29950
+ mkdirSync4(dirname7(file), { recursive: true });
29951
+ writeFileSync4(file, `${JSON.stringify(value, null, 2)}
29952
+ `);
29953
+ return {
29954
+ ok: true,
29955
+ message: `Antigravity SessionStart hook written to ${file}. It runs from the next Antigravity session.`
29956
+ };
29957
+ }
29958
+ function removeAntigravityAutoSyncHook(file = antigravityHookFile()) {
29959
+ if (!existsSync13(file))
29960
+ return { ok: true, message: "no Antigravity hook to remove" };
29961
+ const read3 = readHooksFile(file);
29962
+ if ("error" in read3) return { ok: false, message: read3.error };
29963
+ if (!(HOOK_NAME in read3.value))
29964
+ return { ok: true, message: "no Antigravity hook to remove" };
29965
+ const { [HOOK_NAME]: _ours, ...rest } = read3.value;
29966
+ if (Object.keys(rest).length === 0) unlinkSync5(file);
29967
+ else writeFileSync4(file, `${JSON.stringify(rest, null, 2)}
29968
+ `);
29969
+ return { ok: true, message: `Antigravity hook removed from ${file}` };
29970
+ }
29971
+ function antigravityAutoSyncHookInstalled(file = antigravityHookFile()) {
29972
+ const read3 = readHooksFile(file);
29973
+ if ("error" in read3) return false;
29974
+ const entry = read3.value[HOOK_NAME];
29975
+ const handlers = entry?.SessionStart;
29976
+ return Array.isArray(handlers) && handlers.some(isOurs);
29977
+ }
29978
+
29979
+ // src/autosync/codexHook.ts
29980
+ import { createHash as createHash9 } from "node:crypto";
29981
+ import {
29982
+ existsSync as existsSync14,
29983
+ mkdirSync as mkdirSync5,
29984
+ readFileSync as readFileSync15,
29985
+ realpathSync as realpathSync3,
29986
+ writeFileSync as writeFileSync5
29987
+ } from "node:fs";
29988
+ import { homedir as homedir22 } from "node:os";
29989
+ import { dirname as dirname8, join as join15 } from "node:path";
29253
29990
  import { parse } from "smol-toml";
29254
29991
  function codexHome() {
29255
- return process.env.CODEX_HOME || join15(homedir20(), ".codex");
29992
+ return process.env.CODEX_HOME || join15(homedir22(), ".codex");
29256
29993
  }
29257
29994
  function codexHooksFile() {
29258
29995
  return join15(codexHome(), "hooks.json");
@@ -29261,13 +29998,13 @@ function codexConfigFile() {
29261
29998
  return join15(codexHome(), "config.toml");
29262
29999
  }
29263
30000
  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 &'`;
29264
- function isOurs(entry) {
30001
+ function isOurs2(entry) {
29265
30002
  return typeof entry.command === "string" && entry.command.includes("@use-aistack/cli") && entry.command.includes("sync --auto");
29266
30003
  }
29267
30004
  function readHooksJson(file) {
29268
- if (!existsSync13(file)) return { settings: {} };
30005
+ if (!existsSync14(file)) return { settings: {} };
29269
30006
  try {
29270
- const raw = JSON.parse(readFileSync14(file, "utf-8"));
30007
+ const raw = JSON.parse(readFileSync15(file, "utf-8"));
29271
30008
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
29272
30009
  return { settings: raw };
29273
30010
  }
@@ -29285,20 +30022,20 @@ function installCodexAutoSyncHook(file = codexHooksFile()) {
29285
30022
  const sessionStart = Array.isArray(hooks.SessionStart) ? hooks.SessionStart : [];
29286
30023
  const kept = sessionStart.map((m) => ({
29287
30024
  ...m,
29288
- hooks: (m.hooks ?? []).filter((h) => !isOurs(h))
30025
+ hooks: (m.hooks ?? []).filter((h) => !isOurs2(h))
29289
30026
  })).filter((m) => (m.hooks?.length ?? 0) > 0);
29290
30027
  kept.push({
29291
30028
  matcher: "startup",
29292
30029
  hooks: [{ type: "command", command: CODEX_HOOK_COMMAND, timeout: 30 }]
29293
30030
  });
29294
30031
  settings.hooks = { ...hooks, SessionStart: kept };
29295
- mkdirSync4(dirname7(file), { recursive: true });
29296
- writeFileSync4(file, `${JSON.stringify(settings, null, 2)}
30032
+ mkdirSync5(dirname8(file), { recursive: true });
30033
+ writeFileSync5(file, `${JSON.stringify(settings, null, 2)}
29297
30034
  `);
29298
30035
  return { ok: true, message: CODEX_TRUST_INSTRUCTION };
29299
30036
  }
29300
30037
  function removeCodexAutoSyncHook(file = codexHooksFile()) {
29301
- if (!existsSync13(file))
30038
+ if (!existsSync14(file))
29302
30039
  return { ok: true, message: "no Codex hook to remove" };
29303
30040
  const read3 = readHooksJson(file);
29304
30041
  if ("error" in read3) return { ok: false, message: read3.error };
@@ -29309,7 +30046,7 @@ function removeCodexAutoSyncHook(file = codexHooksFile()) {
29309
30046
  }
29310
30047
  const kept = sessionStart.map((m) => ({
29311
30048
  ...m,
29312
- hooks: (m.hooks ?? []).filter((h) => !isOurs(h))
30049
+ hooks: (m.hooks ?? []).filter((h) => !isOurs2(h))
29313
30050
  })).filter((m) => (m.hooks?.length ?? 0) > 0);
29314
30051
  const hooks = { ...settings.hooks };
29315
30052
  if (kept.length > 0) {
@@ -29322,7 +30059,7 @@ function removeCodexAutoSyncHook(file = codexHooksFile()) {
29322
30059
  } else {
29323
30060
  delete settings.hooks;
29324
30061
  }
29325
- writeFileSync4(file, `${JSON.stringify(settings, null, 2)}
30062
+ writeFileSync5(file, `${JSON.stringify(settings, null, 2)}
29326
30063
  `);
29327
30064
  return { ok: true, message: `hook removed from ${file}` };
29328
30065
  }
@@ -29331,11 +30068,11 @@ function codexAutoSyncHookInstalled(file = codexHooksFile()) {
29331
30068
  if ("error" in read3) return false;
29332
30069
  const sessionStart = read3.settings.hooks?.SessionStart;
29333
30070
  if (!Array.isArray(sessionStart)) return false;
29334
- return sessionStart.some((m) => (m.hooks ?? []).some((h) => isOurs(h)));
30071
+ return sessionStart.some((m) => (m.hooks ?? []).some((h) => isOurs2(h)));
29335
30072
  }
29336
30073
  function codexHookTrusted(configFile = codexConfigFile(), hooksFile = codexHooksFile()) {
29337
30074
  try {
29338
- const config = parse(readFileSync14(configFile, "utf-8"));
30075
+ const config = parse(readFileSync15(configFile, "utf-8"));
29339
30076
  const read3 = readHooksJson(hooksFile);
29340
30077
  if ("error" in read3) return null;
29341
30078
  const sessionStart = read3.settings.hooks?.SessionStart;
@@ -29343,7 +30080,7 @@ function codexHookTrusted(configFile = codexConfigFile(), hooksFile = codexHooks
29343
30080
  const matches = [];
29344
30081
  for (const [groupIndex, group] of sessionStart.entries()) {
29345
30082
  for (const [handlerIndex, handler] of (group.hooks ?? []).entries()) {
29346
- if (!isOurs(handler) || typeof handler.command !== "string") continue;
30083
+ if (!isOurs2(handler) || typeof handler.command !== "string") continue;
29347
30084
  const normalizedHandler = {
29348
30085
  type: "command",
29349
30086
  command: handler.command,
@@ -29401,23 +30138,23 @@ function canonicalJson2(value) {
29401
30138
  }
29402
30139
 
29403
30140
  // src/autosync/cursorHook.ts
29404
- import { existsSync as existsSync15, mkdirSync as mkdirSync6, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "node:fs";
29405
- import { homedir as homedir22, platform as platform2 } from "node:os";
29406
- import { dirname as dirname9, join as join17 } from "node:path";
30141
+ import { existsSync as existsSync16, mkdirSync as mkdirSync7, readFileSync as readFileSync17, writeFileSync as writeFileSync7 } from "node:fs";
30142
+ import { homedir as homedir24, platform as platform3 } from "node:os";
30143
+ import { dirname as dirname10, join as join17 } from "node:path";
29407
30144
 
29408
30145
  // src/autosync/hook.ts
29409
- import { existsSync as existsSync14, mkdirSync as mkdirSync5, readFileSync as readFileSync15, writeFileSync as writeFileSync5 } from "node:fs";
29410
- import { homedir as homedir21 } from "node:os";
29411
- import { dirname as dirname8, join as join16 } from "node:path";
29412
- var CLAUDE_SETTINGS_FILE = join16(homedir21(), ".claude", "settings.json");
30146
+ import { existsSync as existsSync15, mkdirSync as mkdirSync6, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "node:fs";
30147
+ import { homedir as homedir23 } from "node:os";
30148
+ import { dirname as dirname9, join as join16 } from "node:path";
30149
+ var CLAUDE_SETTINGS_FILE = join16(homedir23(), ".claude", "settings.json");
29413
30150
  var AUTO_SYNC_HOOK_COMMAND = "npx -y @use-aistack/cli@latest sync --auto || npx -y --prefer-offline @use-aistack/cli sync --auto";
29414
- function isOurs2(entry) {
30151
+ function isOurs3(entry) {
29415
30152
  return typeof entry.command === "string" && entry.command.includes("@use-aistack/cli") && entry.command.includes("sync --auto");
29416
30153
  }
29417
30154
  function readClaudeSettings(file) {
29418
- if (!existsSync14(file)) return { settings: {} };
30155
+ if (!existsSync15(file)) return { settings: {} };
29419
30156
  try {
29420
- const raw = JSON.parse(readFileSync15(file, "utf-8"));
30157
+ const raw = JSON.parse(readFileSync16(file, "utf-8"));
29421
30158
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
29422
30159
  return { settings: raw };
29423
30160
  }
@@ -29434,19 +30171,19 @@ function installAutoSyncHook(file = CLAUDE_SETTINGS_FILE) {
29434
30171
  const sessionStart = Array.isArray(hooks.SessionStart) ? hooks.SessionStart : [];
29435
30172
  const kept = sessionStart.map((m) => ({
29436
30173
  ...m,
29437
- hooks: (m.hooks ?? []).filter((h) => !isOurs2(h))
30174
+ hooks: (m.hooks ?? []).filter((h) => !isOurs3(h))
29438
30175
  })).filter((m) => (m.hooks?.length ?? 0) > 0);
29439
30176
  kept.push({
29440
30177
  hooks: [{ type: "command", command: AUTO_SYNC_HOOK_COMMAND, async: true }]
29441
30178
  });
29442
30179
  settings.hooks = { ...hooks, SessionStart: kept };
29443
- mkdirSync5(dirname8(file), { recursive: true });
29444
- writeFileSync5(file, `${JSON.stringify(settings, null, 2)}
30180
+ mkdirSync6(dirname9(file), { recursive: true });
30181
+ writeFileSync6(file, `${JSON.stringify(settings, null, 2)}
29445
30182
  `);
29446
30183
  return { ok: true, message: `SessionStart hook written to ${file}` };
29447
30184
  }
29448
30185
  function removeAutoSyncHook(file = CLAUDE_SETTINGS_FILE) {
29449
- if (!existsSync14(file)) return { ok: true, message: "no hook to remove" };
30186
+ if (!existsSync15(file)) return { ok: true, message: "no hook to remove" };
29450
30187
  const read3 = readClaudeSettings(file);
29451
30188
  if ("error" in read3) return { ok: false, message: read3.error };
29452
30189
  const settings = read3.settings;
@@ -29456,7 +30193,7 @@ function removeAutoSyncHook(file = CLAUDE_SETTINGS_FILE) {
29456
30193
  }
29457
30194
  const kept = sessionStart.map((m) => ({
29458
30195
  ...m,
29459
- hooks: (m.hooks ?? []).filter((h) => !isOurs2(h))
30196
+ hooks: (m.hooks ?? []).filter((h) => !isOurs3(h))
29460
30197
  })).filter((m) => (m.hooks?.length ?? 0) > 0);
29461
30198
  const hooks = { ...settings.hooks };
29462
30199
  if (kept.length > 0) {
@@ -29469,7 +30206,7 @@ function removeAutoSyncHook(file = CLAUDE_SETTINGS_FILE) {
29469
30206
  } else {
29470
30207
  delete settings.hooks;
29471
30208
  }
29472
- writeFileSync5(file, `${JSON.stringify(settings, null, 2)}
30209
+ writeFileSync6(file, `${JSON.stringify(settings, null, 2)}
29473
30210
  `);
29474
30211
  return { ok: true, message: `hook removed from ${file}` };
29475
30212
  }
@@ -29478,12 +30215,12 @@ function autoSyncHookInstalled(file = CLAUDE_SETTINGS_FILE) {
29478
30215
  if ("error" in read3) return false;
29479
30216
  const sessionStart = read3.settings.hooks?.SessionStart;
29480
30217
  if (!Array.isArray(sessionStart)) return false;
29481
- return sessionStart.some((m) => (m.hooks ?? []).some((h) => isOurs2(h)));
30218
+ return sessionStart.some((m) => (m.hooks ?? []).some((h) => isOurs3(h)));
29482
30219
  }
29483
30220
 
29484
30221
  // src/autosync/cursorHook.ts
29485
- var CURSOR_HOOK_FILE = join17(homedir22(), ".cursor", "hooks.json");
29486
- function cursorHookCommand(os = platform2()) {
30222
+ var CURSOR_HOOK_FILE = join17(homedir24(), ".cursor", "hooks.json");
30223
+ function cursorHookCommand(os = platform3()) {
29487
30224
  if (os === "win32") {
29488
30225
  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"'`;
29489
30226
  return `powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script, "utf16le").toString("base64")}`;
@@ -29492,8 +30229,8 @@ function cursorHookCommand(os = platform2()) {
29492
30229
  return `${detach} sh -c 'export AISTACK_HOOK_SOURCE=cursor; ${AUTO_SYNC_HOOK_COMMAND}' </dev/null >/dev/null 2>&1 &`;
29493
30230
  }
29494
30231
  function read(file) {
29495
- if (!existsSync15(file)) return {};
29496
- const value = JSON.parse(readFileSync16(file, "utf8"));
30232
+ if (!existsSync16(file)) return {};
30233
+ const value = JSON.parse(readFileSync17(file, "utf8"));
29497
30234
  if (!value || typeof value !== "object" || Array.isArray(value))
29498
30235
  throw new Error("expected a JSON object");
29499
30236
  const config = value;
@@ -29507,7 +30244,7 @@ function read(file) {
29507
30244
  throw new Error("malformed hooks object");
29508
30245
  return config;
29509
30246
  }
29510
- function isOurs3(entry) {
30247
+ function isOurs4(entry) {
29511
30248
  return ["linux", "darwin", "win32"].some(
29512
30249
  (os) => entry.command === cursorHookCommand(os)
29513
30250
  );
@@ -29516,7 +30253,7 @@ function update(file, install, os) {
29516
30253
  try {
29517
30254
  const config = read(file);
29518
30255
  const existing = config.hooks?.stop ?? [];
29519
- const kept = existing.filter((entry) => !isOurs3(entry));
30256
+ const kept = existing.filter((entry) => !isOurs4(entry));
29520
30257
  if (!install && kept.length === existing.length)
29521
30258
  return { ok: true, message: "no Cursor hook to remove" };
29522
30259
  if (install) kept.push({ command: cursorHookCommand(os) });
@@ -29526,8 +30263,8 @@ function update(file, install, os) {
29526
30263
  if (Object.keys(hooks).length) config.hooks = hooks;
29527
30264
  else delete config.hooks;
29528
30265
  if (install) config.version = 1;
29529
- mkdirSync6(dirname9(file), { recursive: true });
29530
- writeFileSync6(file, `${JSON.stringify(config, null, 2)}
30266
+ mkdirSync7(dirname10(file), { recursive: true });
30267
+ writeFileSync7(file, `${JSON.stringify(config, null, 2)}
29531
30268
  `);
29532
30269
  return {
29533
30270
  ok: true,
@@ -29540,15 +30277,15 @@ function update(file, install, os) {
29540
30277
  };
29541
30278
  }
29542
30279
  }
29543
- function installCursorAutoSyncHook(file = CURSOR_HOOK_FILE, os = platform2()) {
30280
+ function installCursorAutoSyncHook(file = CURSOR_HOOK_FILE, os = platform3()) {
29544
30281
  return update(file, true, os);
29545
30282
  }
29546
30283
  function removeCursorAutoSyncHook(file = CURSOR_HOOK_FILE) {
29547
- return update(file, false, platform2());
30284
+ return update(file, false, platform3());
29548
30285
  }
29549
30286
  function cursorAutoSyncHookInstalled(file = CURSOR_HOOK_FILE) {
29550
30287
  try {
29551
- return (read(file).hooks?.stop ?? []).some(isOurs3);
30288
+ return (read(file).hooks?.stop ?? []).some(isOurs4);
29552
30289
  } catch {
29553
30290
  return false;
29554
30291
  }
@@ -29556,33 +30293,33 @@ function cursorAutoSyncHookInstalled(file = CURSOR_HOOK_FILE) {
29556
30293
 
29557
30294
  // src/autosync/grokHook.ts
29558
30295
  import {
29559
- existsSync as existsSync16,
29560
- mkdirSync as mkdirSync7,
29561
- readFileSync as readFileSync17,
29562
- unlinkSync as unlinkSync5,
29563
- writeFileSync as writeFileSync7
30296
+ existsSync as existsSync17,
30297
+ mkdirSync as mkdirSync8,
30298
+ readFileSync as readFileSync18,
30299
+ unlinkSync as unlinkSync6,
30300
+ writeFileSync as writeFileSync8
29564
30301
  } from "node:fs";
29565
- import { homedir as homedir23, platform as platform3 } from "node:os";
29566
- import { dirname as dirname10, join as join18 } from "node:path";
30302
+ import { homedir as homedir25, platform as platform4 } from "node:os";
30303
+ import { dirname as dirname11, join as join18 } from "node:path";
29567
30304
  var GROK_HOOK_FILE = join18(
29568
- process.env.GROK_HOME || join18(homedir23(), ".grok"),
30305
+ process.env.GROK_HOME || join18(homedir25(), ".grok"),
29569
30306
  "hooks",
29570
30307
  "aistack.json"
29571
30308
  );
29572
- var SYNC_COMMAND = "npx -y @use-aistack/cli@latest sync --auto || npx -y --prefer-offline @use-aistack/cli sync --auto";
29573
- function grokHookCommand(os = platform3()) {
30309
+ var SYNC_COMMAND2 = "npx -y @use-aistack/cli@latest sync --auto || npx -y --prefer-offline @use-aistack/cli sync --auto";
30310
+ function grokHookCommand(os = platform4()) {
29574
30311
  if (os === "win32") {
29575
- return `Start-Process -WindowStyle Hidden -FilePath "cmd.exe" -ArgumentList '/d /s /c "set AISTACK_HOOK_SOURCE=grok&& (${SYNC_COMMAND}) >NUL 2>&1"'`;
30312
+ return `Start-Process -WindowStyle Hidden -FilePath "cmd.exe" -ArgumentList '/d /s /c "set AISTACK_HOOK_SOURCE=grok&& (${SYNC_COMMAND2}) >NUL 2>&1"'`;
29576
30313
  }
29577
30314
  if (os === "darwin") {
29578
- return `nohup sh -c 'export AISTACK_HOOK_SOURCE=grok; ${SYNC_COMMAND}' </dev/null >/dev/null 2>&1 &`;
30315
+ return `nohup sh -c 'export AISTACK_HOOK_SOURCE=grok; ${SYNC_COMMAND2}' </dev/null >/dev/null 2>&1 &`;
29579
30316
  }
29580
- return `setsid nohup sh -c 'export AISTACK_HOOK_SOURCE=grok; ${SYNC_COMMAND}' >/dev/null 2>&1 &`;
30317
+ return `setsid nohup sh -c 'export AISTACK_HOOK_SOURCE=grok; ${SYNC_COMMAND2}' >/dev/null 2>&1 &`;
29581
30318
  }
29582
30319
  function readHookFile(file) {
29583
- if (!existsSync16(file)) return { value: {} };
30320
+ if (!existsSync17(file)) return { value: {} };
29584
30321
  try {
29585
- const value = JSON.parse(readFileSync17(file, "utf-8"));
30322
+ const value = JSON.parse(readFileSync18(file, "utf-8"));
29586
30323
  if (value && typeof value === "object" && !Array.isArray(value)) {
29587
30324
  const candidate = value;
29588
30325
  if (candidate.hooks !== void 0 && (!candidate.hooks || typeof candidate.hooks !== "object" || Array.isArray(candidate.hooks) || Object.values(candidate.hooks).some(
@@ -29599,10 +30336,10 @@ function readHookFile(file) {
29599
30336
  }
29600
30337
  return { error: `${file} does not hold a JSON object` };
29601
30338
  }
29602
- function isOurs4(entry) {
30339
+ function isOurs5(entry) {
29603
30340
  return typeof entry.command === "string" && entry.command.includes("@use-aistack/cli") && entry.command.includes("sync --auto");
29604
30341
  }
29605
- function installGrokAutoSyncHook(file = GROK_HOOK_FILE, os = platform3()) {
30342
+ function installGrokAutoSyncHook(file = GROK_HOOK_FILE, os = platform4()) {
29606
30343
  const read3 = readHookFile(file);
29607
30344
  if ("error" in read3) return { ok: false, message: read3.error };
29608
30345
  const foreignKeys = Object.keys(read3.value).filter((key2) => key2 !== "hooks");
@@ -29611,7 +30348,7 @@ function installGrokAutoSyncHook(file = GROK_HOOK_FILE, os = platform3()) {
29611
30348
  );
29612
30349
  const sessionStart = read3.value.hooks?.SessionStart ?? [];
29613
30350
  const foreignHandlers = sessionStart.flatMap(
29614
- (group) => (group.hooks ?? []).filter((entry) => !isOurs4(entry))
30351
+ (group) => (group.hooks ?? []).filter((entry) => !isOurs5(entry))
29615
30352
  );
29616
30353
  if (foreignKeys.length > 0 || foreignEvents.length > 0 || foreignHandlers.length > 0) {
29617
30354
  return {
@@ -29630,8 +30367,8 @@ function installGrokAutoSyncHook(file = GROK_HOOK_FILE, os = platform3()) {
29630
30367
  ]
29631
30368
  }
29632
30369
  };
29633
- mkdirSync7(dirname10(file), { recursive: true });
29634
- writeFileSync7(file, `${JSON.stringify(value, null, 2)}
30370
+ mkdirSync8(dirname11(file), { recursive: true });
30371
+ writeFileSync8(file, `${JSON.stringify(value, null, 2)}
29635
30372
  `);
29636
30373
  return {
29637
30374
  ok: true,
@@ -29639,7 +30376,7 @@ function installGrokAutoSyncHook(file = GROK_HOOK_FILE, os = platform3()) {
29639
30376
  };
29640
30377
  }
29641
30378
  function removeGrokAutoSyncHook(file = GROK_HOOK_FILE) {
29642
- if (!existsSync16(file))
30379
+ if (!existsSync17(file))
29643
30380
  return { ok: true, message: "no Grok Build hook to remove" };
29644
30381
  const read3 = readHookFile(file);
29645
30382
  if ("error" in read3) return { ok: false, message: read3.error };
@@ -29647,7 +30384,7 @@ function removeGrokAutoSyncHook(file = GROK_HOOK_FILE) {
29647
30384
  const onlyOurs = Object.keys(read3.value).every((key2) => key2 === "hooks") && Object.keys(read3.value.hooks ?? {}).every(
29648
30385
  (key2) => key2 === "SessionStart"
29649
30386
  ) && entries.every(
29650
- (group) => (group.hooks ?? []).every((entry) => isOurs4(entry))
30387
+ (group) => (group.hooks ?? []).every((entry) => isOurs5(entry))
29651
30388
  );
29652
30389
  if (!onlyOurs) {
29653
30390
  return {
@@ -29655,21 +30392,21 @@ function removeGrokAutoSyncHook(file = GROK_HOOK_FILE) {
29655
30392
  message: `${file} contains hooks not owned by AI Stack and was not removed.`
29656
30393
  };
29657
30394
  }
29658
- unlinkSync5(file);
30395
+ unlinkSync6(file);
29659
30396
  return { ok: true, message: `Grok Build hook removed from ${file}` };
29660
30397
  }
29661
30398
  function grokAutoSyncHookInstalled(file = GROK_HOOK_FILE) {
29662
30399
  const read3 = readHookFile(file);
29663
30400
  if ("error" in read3) return false;
29664
30401
  return (read3.value.hooks?.SessionStart ?? []).some(
29665
- (group) => (group.hooks ?? []).some((entry) => isOurs4(entry))
30402
+ (group) => (group.hooks ?? []).some((entry) => isOurs5(entry))
29666
30403
  );
29667
30404
  }
29668
30405
 
29669
30406
  // src/autosync/homes.ts
29670
30407
  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";
30408
+ import { homedir as homedir26 } from "node:os";
30409
+ import { basename as basename5, join as join19, relative as relative4, sep as sep3 } from "node:path";
29673
30410
  var HOOK_HARNESSES = [
29674
30411
  "claude",
29675
30412
  "codex",
@@ -29693,15 +30430,15 @@ function withDefault(fallback, found) {
29693
30430
  return homes;
29694
30431
  }
29695
30432
  async function discoverHookHomes() {
29696
- const home = homedir24();
30433
+ const home = homedir26();
29697
30434
  const [claude, codex, grok] = await Promise.all([
29698
30435
  discoverClaudeRoots(),
29699
30436
  discoverCodexHomes(),
29700
30437
  discoverGrokHomes()
29701
30438
  ]);
29702
30439
  return {
29703
- // A Claude Code profile is the folder that holds its `projects` folder.
29704
- claude: withDefault(join19(home, ".claude"), claude.roots.map(dirname11)),
30440
+ // Every Claude Code profile, remembered and CCS folders included.
30441
+ claude: withDefault(join19(home, ".claude"), claude.profiles),
29705
30442
  codex: withDefault(
29706
30443
  process.env.CODEX_HOME || join19(home, ".codex"),
29707
30444
  codex.homes
@@ -29709,7 +30446,7 @@ async function discoverHookHomes() {
29709
30446
  grok: withDefault(process.env.GROK_HOME || join19(home, ".grok"), grok.homes)
29710
30447
  };
29711
30448
  }
29712
- function displayHome(dir, home = homedir24()) {
30449
+ function displayHome(dir, home = homedir26()) {
29713
30450
  const rel = relative4(home, dir);
29714
30451
  if (rel === "") return "~";
29715
30452
  if (!rel.startsWith("..") && !rel.startsWith(sep3) && rel !== dir)
@@ -29718,6 +30455,9 @@ function displayHome(dir, home = homedir24()) {
29718
30455
  }
29719
30456
 
29720
30457
  // src/autosync/optin.ts
30458
+ function withArticle(label) {
30459
+ return `${/^[aeiou]/i.test(label) ? "an" : "a"} ${label}`;
30460
+ }
29721
30461
  var HARNESS_NAME = {
29722
30462
  claude: CLAUDE_HARNESS_NAME,
29723
30463
  codex: CODEX_HARNESS_NAME,
@@ -29797,6 +30537,9 @@ function removeHooks(homes, deps) {
29797
30537
  const cursor = (deps.removeCursorHook ?? removeCursorAutoSyncHook)();
29798
30538
  results.push(cursor);
29799
30539
  if (!cursor.ok) failures.push(cursor.message);
30540
+ const antigravity = (deps.removeAntigravityHook ?? removeAntigravityAutoSyncHook)();
30541
+ results.push(antigravity);
30542
+ if (!antigravity.ok) failures.push(antigravity.message);
29800
30543
  return { results, failures };
29801
30544
  }
29802
30545
  function codexTrustLine(written, deps) {
@@ -29849,6 +30592,10 @@ async function enableAutoSync(frequencyHours = DEFAULT_FREQUENCY_HOURS, deps = {
29849
30592
  const result = (deps.installCursorHook ?? installCursorAutoSyncHook)();
29850
30593
  if (!result.ok) return result;
29851
30594
  }
30595
+ if (names.has(ANTIGRAVITY_HARNESS_NAME)) {
30596
+ const result = (deps.installAntigravityHook ?? installAntigravityAutoSyncHook)();
30597
+ if (!result.ok) return result;
30598
+ }
29852
30599
  saveSettings(
29853
30600
  {
29854
30601
  autoSyncAnswered: true,
@@ -29859,7 +30606,7 @@ async function enableAutoSync(frequencyHours = DEFAULT_FREQUENCY_HOURS, deps = {
29859
30606
  return {
29860
30607
  ok: true,
29861
30608
  message: [
29862
- `Auto-sync is on. It runs about every ${frequencyHours}h when a ${harnessListLabel(detected)} ${names.has(CURSOR_HARNESS_NAME) ? "session is active" : "session starts"}. Turn it off any time: npx @use-aistack/cli@latest sync --auto off`,
30609
+ `Auto-sync is on. It runs about every ${frequencyHours}h when ${withArticle(harnessListLabel(detected))} ${names.has(CURSOR_HARNESS_NAME) ? "session is active" : "session starts"}. Turn it off any time: npx @use-aistack/cli@latest sync --auto off`,
29863
30610
  ...trustLine ? [trustLine] : []
29864
30611
  ].join("\n")
29865
30612
  };
@@ -29956,6 +30703,11 @@ async function reconcileAutoSync(permission, deps = {}) {
29956
30703
  if (result.ok) installed.push(harnessLabel2(CURSOR_HARNESS_NAME));
29957
30704
  else failures.push(result.message);
29958
30705
  }
30706
+ if (names.has(ANTIGRAVITY_HARNESS_NAME) && !(deps.antigravityHookInstalledImpl ?? antigravityAutoSyncHookInstalled)()) {
30707
+ const result = (deps.installAntigravityHook ?? installAntigravityAutoSyncHook)();
30708
+ if (result.ok) installed.push(harnessLabel2(ANTIGRAVITY_HARNESS_NAME));
30709
+ else failures.push(result.message);
30710
+ }
29959
30711
  if (failures.length > 0) {
29960
30712
  return {
29961
30713
  ok: false,
@@ -29975,7 +30727,7 @@ async function reconcileAutoSync(permission, deps = {}) {
29975
30727
  return {
29976
30728
  ok: true,
29977
30729
  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"}.`,
30730
+ 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 ${withArticle(harnessListLabel(detected))} ${names.has(CURSOR_HARNESS_NAME) ? "session is active" : "session starts"}.`,
29979
30731
  ...trustLine ? [trustLine] : []
29980
30732
  ].join("\n")
29981
30733
  };
@@ -30003,7 +30755,7 @@ async function autoSyncStatus(deps = {}) {
30003
30755
  for (const home of hookTargets(harness, homes, deps.settingsFile)) {
30004
30756
  const file = hookFile(harness, home);
30005
30757
  const installed = ops[harness].installed(file);
30006
- if (!installed && !existsSync17(home)) continue;
30758
+ if (!installed && !existsSync18(home)) continue;
30007
30759
  let state = installed ? "hook installed" : "no hook";
30008
30760
  if (installed && harness === "codex") {
30009
30761
  const trust = trusted(join20(home, "config.toml"), file);
@@ -30020,13 +30772,22 @@ async function autoSyncStatus(deps = {}) {
30020
30772
  }
30021
30773
  const cursorHome = dirname12(CURSOR_HOOK_FILE);
30022
30774
  const cursorInstalled = (deps.cursorHookInstalledImpl ?? cursorAutoSyncHookInstalled)();
30023
- if (cursorInstalled || existsSync17(cursorHome)) {
30775
+ if (cursorInstalled || existsSync18(cursorHome)) {
30024
30776
  rows.push([
30025
30777
  harnessLabel2(CURSOR_HARNESS_NAME),
30026
- displayHome(cursorHome, deps.homeDir ?? homedir25()),
30778
+ displayHome(cursorHome, deps.homeDir ?? homedir27()),
30027
30779
  cursorInstalled ? "hook installed" : "no hook"
30028
30780
  ]);
30029
30781
  }
30782
+ const antigravityConfig = dirname12(antigravityHookFile());
30783
+ const antigravityInstalled = (deps.antigravityHookInstalledImpl ?? antigravityAutoSyncHookInstalled)();
30784
+ if (antigravityInstalled || existsSync18(antigravityConfig)) {
30785
+ rows.push([
30786
+ harnessLabel2(ANTIGRAVITY_HARNESS_NAME),
30787
+ displayHome(antigravityConfig, deps.homeDir ?? homedir27()),
30788
+ antigravityInstalled ? "hook installed" : "no hook"
30789
+ ]);
30790
+ }
30030
30791
  if (rows.length === 0) {
30031
30792
  lines2.push("No harness folders found on this machine.");
30032
30793
  return lines2;
@@ -30061,7 +30822,7 @@ async function offerAutoSyncOptIn(deps = {}) {
30061
30822
  {
30062
30823
  value: "enable",
30063
30824
  label: "Enable",
30064
- hint: `a silent sync at most every 6 hours when a ${harnessListLabel(detected)} ${names.has(CURSOR_HARNESS_NAME) ? "session is active" : "session starts"}`
30825
+ hint: `a silent sync at most every 6 hours when ${withArticle(harnessListLabel(detected))} ${names.has(CURSOR_HARNESS_NAME) ? "session is active" : "session starts"}`
30065
30826
  },
30066
30827
  {
30067
30828
  value: "later",
@@ -30103,11 +30864,11 @@ async function offerAutoSyncOptIn(deps = {}) {
30103
30864
  // src/autosync/run.ts
30104
30865
  import {
30105
30866
  appendFileSync,
30106
- mkdirSync as mkdirSync10,
30107
- readFileSync as readFileSync20,
30108
- writeFileSync as writeFileSync10
30867
+ mkdirSync as mkdirSync11,
30868
+ readFileSync as readFileSync21,
30869
+ writeFileSync as writeFileSync11
30109
30870
  } from "node:fs";
30110
- import { homedir as homedir27 } from "node:os";
30871
+ import { homedir as homedir29 } from "node:os";
30111
30872
  import { dirname as dirname14, join as join21 } from "node:path";
30112
30873
 
30113
30874
  // src/sync/stage.ts
@@ -30268,8 +31029,8 @@ function selectDaysToPublish(input) {
30268
31029
 
30269
31030
  // src/workflow/git.ts
30270
31031
  import { execFile, execFileSync as execFileSync2 } from "node:child_process";
30271
- import { existsSync as existsSync18 } from "node:fs";
30272
- import path17 from "node:path";
31032
+ import { existsSync as existsSync19 } from "node:fs";
31033
+ import path19 from "node:path";
30273
31034
  var TEST_FILE_RULE_VERSION = "test-files/v2";
30274
31035
  var FILE_TYPE_RULE_VERSION = "file-types/v3";
30275
31036
  var COMMIT_SET_RULE_VERSION = "commit-set/v1";
@@ -30279,7 +31040,7 @@ function gitDiagnostics() {
30279
31040
  const report = (error, cwd, args, stderr) => {
30280
31041
  const details = error;
30281
31042
  if (args[0] === "rev-parse") {
30282
- if (details.code === "ENOENT" && !existsSync18(cwd)) {
31043
+ if (details.code === "ENOENT" && !existsSync19(cwd)) {
30283
31044
  missing++;
30284
31045
  return;
30285
31046
  }
@@ -30686,9 +31447,9 @@ function reduceGitHistories(histories, options) {
30686
31447
  if (included) seenCommits.add(hash2);
30687
31448
  continue;
30688
31449
  }
30689
- const stat12 = parseNumstat(field);
30690
- if (!stat12) continue;
30691
- let file = stat12.file;
31450
+ const stat13 = parseNumstat(field);
31451
+ if (!stat13) continue;
31452
+ let file = stat13.file;
30692
31453
  if (file.length === 0) {
30693
31454
  fieldIndex += 2;
30694
31455
  file = fields[fieldIndex] ?? fields[fieldIndex - 1] ?? "";
@@ -30696,13 +31457,13 @@ function reduceGitHistories(histories, options) {
30696
31457
  if (!current?.included) continue;
30697
31458
  if (isUnauthoredPath(file)) continue;
30698
31459
  current.authored = true;
30699
- const fileChangedLines = stat12.additions + stat12.removals;
30700
- current.additions += stat12.additions;
30701
- current.removals += stat12.removals;
31460
+ const fileChangedLines = stat13.additions + stat13.removals;
31461
+ current.additions += stat13.additions;
31462
+ current.removals += stat13.removals;
30702
31463
  current.changedLines += fileChangedLines;
30703
31464
  if (isTestFile(file)) current.touchesTest = true;
30704
31465
  if (fileChangedLines <= 0) continue;
30705
- const extension = path17.extname(file).toLowerCase();
31466
+ const extension = path19.extname(file).toLowerCase();
30706
31467
  if (APPROVED_EXTENSIONS.has(extension)) {
30707
31468
  current.extensionLines.set(
30708
31469
  extension,
@@ -30807,11 +31568,11 @@ function buildWorkflowExtraction(harnessWorkflows, git, utcOffsetMinutes = machi
30807
31568
 
30808
31569
  // src/sync/grokDateCache.ts
30809
31570
  import { createHash as createHash10 } from "node:crypto";
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(),
31571
+ import { existsSync as existsSync20, mkdirSync as mkdirSync9, readFileSync as readFileSync19, writeFileSync as writeFileSync9 } from "node:fs";
31572
+ import { homedir as homedir28 } from "node:os";
31573
+ import path20 from "node:path";
31574
+ var defaultFile = path20.join(
31575
+ homedir28(),
30815
31576
  ".config",
30816
31577
  "aistack",
30817
31578
  "grok-session-dates.json"
@@ -30820,9 +31581,9 @@ function grokCacheScope(baseUrl, stack, token) {
30820
31581
  return createHash10("sha256").update(`${baseUrl}\0${stack}\0${token}`).digest("hex");
30821
31582
  }
30822
31583
  function read2(file) {
30823
- if (!existsSync19(file)) return {};
31584
+ if (!existsSync20(file)) return {};
30824
31585
  try {
30825
- const value = JSON.parse(readFileSync18(file, "utf8"));
31586
+ const value = JSON.parse(readFileSync19(file, "utf8"));
30826
31587
  return value && typeof value === "object" ? value : {};
30827
31588
  } catch {
30828
31589
  return {};
@@ -30834,8 +31595,8 @@ function loadGrokDateHints(scope, file = defaultFile) {
30834
31595
  function saveGrokDateHints(scope, hints, file = defaultFile) {
30835
31596
  const cache = read2(file);
30836
31597
  cache[scope] = hints;
30837
- mkdirSync8(path18.dirname(file), { recursive: true });
30838
- writeFileSync8(file, JSON.stringify(cache, null, 2));
31598
+ mkdirSync9(path20.dirname(file), { recursive: true });
31599
+ writeFileSync9(file, JSON.stringify(cache, null, 2));
30839
31600
  }
30840
31601
  function mapToHints(value, floor) {
30841
31602
  return Object.fromEntries(
@@ -31721,12 +32482,12 @@ function describeScan(stats) {
31721
32482
  // src/autosync/reserve.ts
31722
32483
  import { randomUUID as randomUUID3 } from "node:crypto";
31723
32484
  import {
31724
- mkdirSync as mkdirSync9,
31725
- readFileSync as readFileSync19,
32485
+ mkdirSync as mkdirSync10,
32486
+ readFileSync as readFileSync20,
31726
32487
  renameSync as renameSync3,
31727
32488
  rmSync,
31728
32489
  statSync as statSync7,
31729
- writeFileSync as writeFileSync9
32490
+ writeFileSync as writeFileSync10
31730
32491
  } from "node:fs";
31731
32492
  import { dirname as dirname13 } from "node:path";
31732
32493
  var MUTEX_WAIT_MS = 2e3;
@@ -31739,7 +32500,7 @@ function acquire(mutex) {
31739
32500
  const deadline = Date.now() + MUTEX_WAIT_MS;
31740
32501
  for (; ; ) {
31741
32502
  try {
31742
- mkdirSync9(mutex);
32503
+ mkdirSync10(mutex);
31743
32504
  return true;
31744
32505
  } catch (error) {
31745
32506
  if (code(error) !== "EEXIST") throw error;
@@ -31757,7 +32518,7 @@ function acquire(mutex) {
31757
32518
  function isHeld(file, now, windowMs) {
31758
32519
  let content;
31759
32520
  try {
31760
- content = readFileSync19(file, "utf-8").trim();
32521
+ content = readFileSync20(file, "utf-8").trim();
31761
32522
  } catch (error) {
31762
32523
  if (code(error) === "ENOENT") return false;
31763
32524
  throw error;
@@ -31767,13 +32528,13 @@ function isHeld(file, now, windowMs) {
31767
32528
  return Date.now() - statSync7(file).mtimeMs < windowMs;
31768
32529
  }
31769
32530
  function reserveAttempt(file, now, windowMs) {
31770
- mkdirSync9(dirname13(file), { recursive: true });
32531
+ mkdirSync10(dirname13(file), { recursive: true });
31771
32532
  const mutex = `${file}.lock`;
31772
32533
  if (!acquire(mutex)) return false;
31773
32534
  try {
31774
32535
  if (isHeld(file, now, windowMs)) return false;
31775
32536
  const own = `${file}.${process.pid}.${randomUUID3()}`;
31776
- writeFileSync9(own, String(now));
32537
+ writeFileSync10(own, String(now));
31777
32538
  renameSync3(own, file);
31778
32539
  return true;
31779
32540
  } finally {
@@ -31782,17 +32543,17 @@ function reserveAttempt(file, now, windowMs) {
31782
32543
  }
31783
32544
 
31784
32545
  // src/autosync/run.ts
31785
- var SYNC_LOG_FILE = join21(homedir27(), ".config", "aistack", "sync.log");
32546
+ var SYNC_LOG_FILE = join21(homedir29(), ".config", "aistack", "sync.log");
31786
32547
  var SYNC_LOG_MAX_LINES = 200;
31787
32548
  var FIX_COMMAND = "npx @use-aistack/cli@latest sync";
31788
32549
  var REVOKED_RESULT = "off - auto-sync is switched off for this stack";
31789
32550
  function appendLogLine(file, line) {
31790
- mkdirSync10(dirname14(file), { recursive: true });
32551
+ mkdirSync11(dirname14(file), { recursive: true });
31791
32552
  appendFileSync(file, `${line}
31792
32553
  `);
31793
- const lines2 = readFileSync20(file, "utf-8").split("\n").filter(Boolean);
32554
+ const lines2 = readFileSync21(file, "utf-8").split("\n").filter(Boolean);
31794
32555
  if (lines2.length > SYNC_LOG_MAX_LINES) {
31795
- writeFileSync10(file, `${lines2.slice(-SYNC_LOG_MAX_LINES).join("\n")}
32556
+ writeFileSync11(file, `${lines2.slice(-SYNC_LOG_MAX_LINES).join("\n")}
31796
32557
  `);
31797
32558
  }
31798
32559
  }
@@ -31814,7 +32575,7 @@ async function runAutoSync(deps) {
31814
32575
  const state = settings.autoSyncState ?? {};
31815
32576
  const lastRunAt = state.lastRunAt ?? 0;
31816
32577
  if (now - lastRunAt < windowMs) return;
31817
- const reservationFile = deps.reservationFile ?? `${settingsFile ?? join21(homedir27(), ".config", "aistack", "settings.json")}.auto-sync-attempt`;
32578
+ const reservationFile = deps.reservationFile ?? `${settingsFile ?? join21(homedir29(), ".config", "aistack", "settings.json")}.auto-sync-attempt`;
31818
32579
  if (!reserveAttempt(reservationFile, now, windowMs)) return;
31819
32580
  saveSettings({ autoSyncState: { ...state, lastRunAt: now } }, settingsFile);
31820
32581
  const stage = deps.stageImpl ?? stageSync;
@@ -31908,7 +32669,7 @@ async function runAutoSync(deps) {
31908
32669
  logFile,
31909
32670
  `${stamp} fail (${consecutiveFailures} in a row) - ${failure2}`
31910
32671
  );
31911
- if (shouldWarn && deps.suppressOutput !== true && process.env.AISTACK_HOOK_SOURCE !== "grok" && process.env.AISTACK_HOOK_SOURCE !== "cursor") {
32672
+ if (shouldWarn && deps.suppressOutput !== true && process.env.AISTACK_HOOK_SOURCE !== "grok" && process.env.AISTACK_HOOK_SOURCE !== "cursor" && process.env.AISTACK_HOOK_SOURCE !== "antigravity") {
31912
32673
  emit2(
31913
32674
  JSON.stringify({
31914
32675
  systemMessage: `aistack auto-sync failed ${consecutiveFailures} times in a row (${failure2}). Run \`${FIX_COMMAND}\` in a terminal to fix it, or \`${FIX_COMMAND} --auto off\` to stop these runs.`