@cleocode/core 2026.6.9 → 2026.6.10

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.
@@ -14555,7 +14555,7 @@ var init_sql = __esm({
14555
14555
  return new SQL([new StringChunk(str)]);
14556
14556
  }
14557
14557
  _sql.raw = raw;
14558
- function join22(chunks, separator) {
14558
+ function join23(chunks, separator) {
14559
14559
  const result = [];
14560
14560
  for (const [i, chunk] of chunks.entries()) {
14561
14561
  if (i > 0 && separator !== void 0) result.push(separator);
@@ -14563,7 +14563,7 @@ var init_sql = __esm({
14563
14563
  }
14564
14564
  return new SQL(result);
14565
14565
  }
14566
- _sql.join = join22;
14566
+ _sql.join = join23;
14567
14567
  function identifier(value) {
14568
14568
  return new Name(value);
14569
14569
  }
@@ -16950,7 +16950,7 @@ var init_select2 = __esm({
16950
16950
  const baseTableName = this.tableName;
16951
16951
  const tableName = getTableLikeName(table);
16952
16952
  for (const item of extractUsedTable(table)) this.usedTables.add(item);
16953
- if (typeof tableName === "string" && this.config.joins?.some((join22) => join22.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
16953
+ if (typeof tableName === "string" && this.config.joins?.some((join23) => join23.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
16954
16954
  if (!this.isPartialSelect) {
16955
16955
  if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") this.config.fields = { [baseTableName]: this.config.fields };
16956
16956
  if (typeof tableName === "string" && !is(table, SQL)) {
@@ -20760,7 +20760,7 @@ var init_dialect = __esm({
20760
20760
  if (!joins2) return;
20761
20761
  const withEntries = Object.entries(joins2).filter(([_, v]) => v);
20762
20762
  if (!withEntries.length) return;
20763
- return sql.join(withEntries.map(([k, join22]) => {
20763
+ return sql.join(withEntries.map(([k, join23]) => {
20764
20764
  const relation = tableConfig.relations[k];
20765
20765
  const isSingle2 = is(relation, One);
20766
20766
  const targetTable = aliasedTable(relation.targetTable, `d${currentDepth + 1}`);
@@ -20771,7 +20771,7 @@ var init_dialect = __esm({
20771
20771
  table: targetTable,
20772
20772
  mode: isSingle2 ? "first" : "many",
20773
20773
  schema,
20774
- queryConfig: join22,
20774
+ queryConfig: join23,
20775
20775
  tableConfig: schema[relation.targetTableName],
20776
20776
  relationWhere: filter,
20777
20777
  isNested: true,
@@ -20785,7 +20785,7 @@ var init_dialect = __esm({
20785
20785
  key: k,
20786
20786
  selection: innerQuery.selection,
20787
20787
  isArray: !isSingle2,
20788
- isOptional: (relation.optional ?? false) || join22 !== true && !!join22.where
20788
+ isOptional: (relation.optional ?? false) || join23 !== true && !!join23.where
20789
20789
  });
20790
20790
  const jsonColumns = sql.join(innerQuery.selection.map((s) => {
20791
20791
  return sql`${sql.raw(this.escapeString(s.key))}, ${s.selection ? sql`${jsonb3}(${sql.identifier(s.key)})` : sql.identifier(s.key)}`;
@@ -21606,7 +21606,7 @@ var init_update = __esm({
21606
21606
  createJoin(joinType) {
21607
21607
  return ((table, on) => {
21608
21608
  const tableName = getTableLikeName(table);
21609
- if (typeof tableName === "string" && this.config.joins.some((join22) => join22.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
21609
+ if (typeof tableName === "string" && this.config.joins.some((join23) => join23.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
21610
21610
  if (typeof on === "function") {
21611
21611
  const from = this.config.from ? is(table, SQLiteTable) ? table[Table.Symbol.Columns] : is(table, Subquery) ? table._.selectedFields : is(table, SQLiteViewBase) ? table[ViewBaseConfig].selectedFields : void 0 : void 0;
21612
21612
  on = on(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
@@ -22596,6 +22596,66 @@ var init_with_retry = __esm({
22596
22596
 
22597
22597
  // packages/core/src/store/migration-manager.ts
22598
22598
  import { copyFileSync, existsSync as existsSync2 } from "node:fs";
22599
+ import { dirname, join as join3 } from "node:path";
22600
+ function stripSqlComments(sql39) {
22601
+ return sql39.replace(/--[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "");
22602
+ }
22603
+ function computeEliminatedTables(migrations) {
22604
+ const createTableRegex = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"]?(\w+)[`"]?/i;
22605
+ const dropTableRegex = /DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?[`"]?(\w+)[`"]?/i;
22606
+ const renameRegex = /ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+RENAME\s+TO\s+[`"]?(\w+)[`"]?/i;
22607
+ const disposition = /* @__PURE__ */ new Map();
22608
+ const ordered = [...migrations].sort((a, b) => a.folderMillis - b.folderMillis);
22609
+ for (const migration of ordered) {
22610
+ const statements = Array.isArray(migration.sql) ? migration.sql : [migration.sql ?? ""];
22611
+ for (const rawStatement of statements) {
22612
+ const stripped = stripSqlComments(rawStatement);
22613
+ for (const clause of stripped.split(";")) {
22614
+ const create = createTableRegex.exec(clause);
22615
+ if (create) {
22616
+ disposition.set(create[1], true);
22617
+ continue;
22618
+ }
22619
+ const rename2 = renameRegex.exec(clause);
22620
+ if (rename2) {
22621
+ disposition.set(rename2[2], true);
22622
+ continue;
22623
+ }
22624
+ const drop = dropTableRegex.exec(clause);
22625
+ if (drop) {
22626
+ disposition.set(drop[1], false);
22627
+ }
22628
+ }
22629
+ }
22630
+ }
22631
+ const eliminated = /* @__PURE__ */ new Set();
22632
+ for (const [table, present] of disposition) {
22633
+ if (!present) eliminated.add(table);
22634
+ }
22635
+ return eliminated;
22636
+ }
22637
+ function resolveConsolidationCutoverPrefix(migrationsFolder) {
22638
+ const parent = dirname(migrationsFolder);
22639
+ for (const setName of ["drizzle-cleo-project", "drizzle-cleo-global"]) {
22640
+ const folder = join3(parent, setName);
22641
+ if (!existsSync2(folder)) continue;
22642
+ try {
22643
+ const consolidation = readMigrationFiles({ migrationsFolder: folder }).find(
22644
+ (m) => /-consolidation-cleo-/.test(m.name ?? "")
22645
+ );
22646
+ if (consolidation?.name) {
22647
+ return consolidation.name.slice(0, MIGRATION_TIMESTAMP_PREFIX_LEN);
22648
+ }
22649
+ } catch {
22650
+ }
22651
+ }
22652
+ return CONSOLIDATION_CUTOVER_PREFIX;
22653
+ }
22654
+ function isAtOrBeforeCutover(migrationName, cutoverPrefix) {
22655
+ const prefix = (migrationName ?? "").slice(0, MIGRATION_TIMESTAMP_PREFIX_LEN);
22656
+ if (prefix.length < MIGRATION_TIMESTAMP_PREFIX_LEN) return true;
22657
+ return prefix <= cutoverPrefix;
22658
+ }
22599
22659
  function tableExists(nativeDb, tableName) {
22600
22660
  const result = nativeDb.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(tableName);
22601
22661
  return !!result;
@@ -22622,9 +22682,9 @@ function insertJournalEntry(nativeDb, hash, createdAt, name2) {
22622
22682
  `INSERT OR IGNORE INTO "__drizzle_migrations" ("hash", "created_at", "name") VALUES ('${hash}', ${createdAt}, '${name2}')`
22623
22683
  );
22624
22684
  }
22625
- function probeAndMarkApplied(nativeDb, migration, logSubsystem) {
22685
+ function probeAndMarkApplied(nativeDb, migration, logSubsystem, eliminatedTables = /* @__PURE__ */ new Set(), consolidationCutoverPrefix = CONSOLIDATION_CUTOVER_PREFIX) {
22626
22686
  const sqlStatements = Array.isArray(migration.sql) ? migration.sql : [migration.sql ?? ""];
22627
- const fullSql = sqlStatements.join("\n");
22687
+ const fullSql = stripSqlComments(sqlStatements.join("\n"));
22628
22688
  const alterColumnRegex = /ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+COLUMN\s+[`"]?(\w+)[`"]?/gi;
22629
22689
  const createTableRegex = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"]?(\w+)[`"]?/gi;
22630
22690
  const createIndexRegex = /CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"]?(\w+)[`"]?/gi;
@@ -22651,10 +22711,17 @@ function probeAndMarkApplied(nativeDb, migration, logSubsystem) {
22651
22711
  }
22652
22712
  const isRebuildOnlyMigration = allCreatedTablesAreRenamed && tableTargets.length > 0 && alterTargets.length === 0;
22653
22713
  const performsTableRebuild = renameMap.size > 0;
22714
+ const createIndexWithTableRegex = /CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"]?(\w+)[`"]?\s+ON\s+[`"]?(\w+)[`"]?/gi;
22715
+ const indexOnTable = /* @__PURE__ */ new Map();
22716
+ for (const m of fullSql.matchAll(createIndexWithTableRegex)) {
22717
+ indexOnTable.set(m[1], m[2]);
22718
+ }
22654
22719
  const indexTargets = [];
22655
22720
  if (!isRebuildOnlyMigration && !performsTableRebuild) {
22656
22721
  for (const m of fullSql.matchAll(createIndexRegex)) {
22657
- indexTargets.push(m[1]);
22722
+ const idx = m[1];
22723
+ if (eliminatedTables.has(indexOnTable.get(idx) ?? "")) continue;
22724
+ indexTargets.push(idx);
22658
22725
  }
22659
22726
  }
22660
22727
  const triggerTargets = [];
@@ -22663,6 +22730,14 @@ function probeAndMarkApplied(nativeDb, migration, logSubsystem) {
22663
22730
  }
22664
22731
  const totalTargets = alterTargets.length + tableTargets.length + indexTargets.length + triggerTargets.length;
22665
22732
  if (totalTargets === 0) {
22733
+ if (isAtOrBeforeCutover(migration.name, consolidationCutoverPrefix)) {
22734
+ insertJournalEntry(nativeDb, migration.hash, migration.folderMillis, migration.name ?? "");
22735
+ getLogger(logSubsystem).debug(
22736
+ { migration: migration.name },
22737
+ `Zero-DDL pre-consolidation migration ${migration.name} stamped applied (subsumed; not re-run).`
22738
+ );
22739
+ return true;
22740
+ }
22666
22741
  return false;
22667
22742
  }
22668
22743
  const allAltersPresent = alterTargets.every(({ table, column }) => {
@@ -22670,7 +22745,9 @@ function probeAndMarkApplied(nativeDb, migration, logSubsystem) {
22670
22745
  const cols = nativeDb.prepare(`PRAGMA table_info(${table})`).all();
22671
22746
  return cols.some((c) => c.name === column);
22672
22747
  });
22673
- const allTablesPresent = tableTargets.every((t) => tableExists(nativeDb, t));
22748
+ const allTablesPresent = tableTargets.every(
22749
+ (t) => tableExists(nativeDb, t) || eliminatedTables.has(t)
22750
+ );
22674
22751
  const allIndexesPresent = indexTargets.every((idx) => {
22675
22752
  const rows = nativeDb.prepare(`SELECT name FROM sqlite_master WHERE type='index' AND name=?`).all(idx);
22676
22753
  return rows.length > 0;
@@ -22697,6 +22774,8 @@ function probeAndMarkApplied(nativeDb, migration, logSubsystem) {
22697
22774
  return false;
22698
22775
  }
22699
22776
  function reconcileJournal(nativeDb, migrationsFolder, existenceTable2, logSubsystem) {
22777
+ const eliminatedTables = computeEliminatedTables(readMigrationFiles({ migrationsFolder }));
22778
+ const cutoverPrefix = resolveConsolidationCutoverPrefix(migrationsFolder);
22700
22779
  if (tableExists(nativeDb, existenceTable2) && !tableExists(nativeDb, "__drizzle_migrations")) {
22701
22780
  const migrations = readMigrationFiles({ migrationsFolder });
22702
22781
  const baseline = migrations[0];
@@ -22740,7 +22819,7 @@ function reconcileJournal(nativeDb, migrationsFolder, existenceTable2, logSubsys
22740
22819
  );
22741
22820
  for (const m of localMigrations) {
22742
22821
  if (journaledHashesAfter.has(m.hash)) continue;
22743
- probeAndMarkApplied(nativeDb, m, logSubsystem);
22822
+ probeAndMarkApplied(nativeDb, m, logSubsystem, eliminatedTables, cutoverPrefix);
22744
22823
  }
22745
22824
  }
22746
22825
  }
@@ -22763,7 +22842,7 @@ function reconcileJournal(nativeDb, migrationsFolder, existenceTable2, logSubsys
22763
22842
  });
22764
22843
  }
22765
22844
  if (alterMatches.length === 0) {
22766
- const stripped = fullSql.replace(/--[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "").trim();
22845
+ const stripped = stripSqlComments(fullSql).trim();
22767
22846
  if (stripped === "") {
22768
22847
  const log10 = getLogger(logSubsystem);
22769
22848
  log10.debug(
@@ -22782,9 +22861,11 @@ function reconcileJournal(nativeDb, migrationsFolder, existenceTable2, logSubsys
22782
22861
  const createTableRe = /CREATE\s+TABLE/i;
22783
22862
  const createTriggerRe = /CREATE\s+TRIGGER/i;
22784
22863
  if (renameRe.test(fullSql) && createTableRe.test(fullSql)) {
22785
- probeAndMarkApplied(nativeDb, migration, logSubsystem);
22864
+ probeAndMarkApplied(nativeDb, migration, logSubsystem, eliminatedTables, cutoverPrefix);
22786
22865
  } else if (createTableRe.test(fullSql) || createTriggerRe.test(fullSql)) {
22787
- probeAndMarkApplied(nativeDb, migration, logSubsystem);
22866
+ probeAndMarkApplied(nativeDb, migration, logSubsystem, eliminatedTables, cutoverPrefix);
22867
+ } else {
22868
+ probeAndMarkApplied(nativeDb, migration, logSubsystem, eliminatedTables, cutoverPrefix);
22788
22869
  }
22789
22870
  continue;
22790
22871
  }
@@ -22875,6 +22956,7 @@ function reconcileBrainMigrationsForConsolidatedDb(nativeDb, migrationsFolder) {
22875
22956
  const existingHashes = new Set(
22876
22957
  nativeDb.prepare('SELECT hash FROM "__drizzle_migrations"').all().map((r) => r.hash)
22877
22958
  );
22959
+ const eliminatedTables = computeEliminatedTables(localMigrations);
22878
22960
  const createTableRegex = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"]?(\w+)[`"]?/gi;
22879
22961
  const renameRegex = /ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+RENAME\s+TO\s+[`"]?(\w+)[`"]?/gi;
22880
22962
  const addColumnRegex = /ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+COLUMN\s+[`"]?(\w+)[`"]?/gi;
@@ -22883,7 +22965,6 @@ function reconcileBrainMigrationsForConsolidatedDb(nativeDb, migrationsFolder) {
22883
22965
  const cols = nativeDb.prepare(`PRAGMA table_info("${table}")`).all();
22884
22966
  return cols.some((c) => c.name === column);
22885
22967
  };
22886
- const stripSqlComments = (sql39) => sql39.replace(/--[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "");
22887
22968
  let marked = 0;
22888
22969
  let applied = 0;
22889
22970
  for (const m of localMigrations) {
@@ -22904,7 +22985,7 @@ function reconcileBrainMigrationsForConsolidatedDb(nativeDb, migrationsFolder) {
22904
22985
  for (const match of fullSql.matchAll(addColumnRegex)) {
22905
22986
  addColumns.push({ table: match[1], column: match[2] });
22906
22987
  }
22907
- const tablesSatisfied = resultTables.size > 0 && [...resultTables].every((t) => tableExists(nativeDb, t));
22988
+ const tablesSatisfied = resultTables.size > 0 && [...resultTables].every((t) => tableExists(nativeDb, t) || eliminatedTables.has(t));
22908
22989
  const altersSatisfied = resultTables.size === 0 && addColumns.length > 0 && addColumns.every(({ table, column }) => columnExists(table, column));
22909
22990
  if (tablesSatisfied || altersSatisfied) {
22910
22991
  for (const statement of m.sql) {
@@ -22927,13 +23008,22 @@ function reconcileBrainMigrationsForConsolidatedDb(nativeDb, migrationsFolder) {
22927
23008
  }
22928
23009
  return { marked, applied };
22929
23010
  }
23011
+ function collectErrorMessages(err) {
23012
+ const messages = [];
23013
+ let current = err;
23014
+ for (let depth = 0; current instanceof Error && depth < 16; depth++) {
23015
+ messages.push(current.message);
23016
+ current = current.cause;
23017
+ }
23018
+ return messages.join("\n");
23019
+ }
22930
23020
  function isDuplicateColumnError(err) {
22931
23021
  if (!(err instanceof Error)) return false;
22932
- return /duplicate column name/i.test(err.message);
23022
+ return /duplicate column name/i.test(collectErrorMessages(err));
22933
23023
  }
22934
23024
  function isTableAlreadyExistsError(err) {
22935
23025
  if (!(err instanceof Error)) return false;
22936
- return /table .+ already exists/i.test(err.message);
23026
+ return /table .+ already exists/i.test(collectErrorMessages(err));
22937
23027
  }
22938
23028
  function isExecutableStatement(stmt) {
22939
23029
  if (stmt.trim() === "") return false;
@@ -23004,7 +23094,7 @@ function ensureColumns(nativeDb, tableName, requiredColumns, logSubsystem, conte
23004
23094
  }
23005
23095
  }
23006
23096
  }
23007
- var MAX_MIGRATION_RETRIES, MIGRATION_RETRY_BASE_DELAY_MS, MIGRATION_RETRY_MAX_DELAY_MS;
23097
+ var MAX_MIGRATION_RETRIES, MIGRATION_RETRY_BASE_DELAY_MS, MIGRATION_RETRY_MAX_DELAY_MS, CONSOLIDATION_CUTOVER_PREFIX, MIGRATION_TIMESTAMP_PREFIX_LEN;
23008
23098
  var init_migration_manager = __esm({
23009
23099
  "packages/core/src/store/migration-manager.ts"() {
23010
23100
  "use strict";
@@ -23014,27 +23104,29 @@ var init_migration_manager = __esm({
23014
23104
  MAX_MIGRATION_RETRIES = 5;
23015
23105
  MIGRATION_RETRY_BASE_DELAY_MS = 100;
23016
23106
  MIGRATION_RETRY_MAX_DELAY_MS = 2e3;
23107
+ CONSOLIDATION_CUTOVER_PREFIX = "20260531000001";
23108
+ MIGRATION_TIMESTAMP_PREFIX_LEN = 14;
23017
23109
  }
23018
23110
  });
23019
23111
 
23020
23112
  // packages/core/src/store/resolve-migrations-folder.ts
23021
23113
  import { createRequire } from "node:module";
23022
- import { dirname, join as join3 } from "node:path";
23114
+ import { dirname as dirname2, join as join4 } from "node:path";
23023
23115
  import { fileURLToPath } from "node:url";
23024
23116
  function coreRootFromEntry(entryPath) {
23025
- return dirname(dirname(entryPath));
23117
+ return dirname2(dirname2(entryPath));
23026
23118
  }
23027
23119
  function resolveCorePackageMigrationsFolder(setName) {
23028
23120
  try {
23029
23121
  const resolved = import.meta.resolve("@cleocode/core", import.meta.url);
23030
23122
  const entryPath = fileURLToPath(resolved);
23031
- return join3(coreRootFromEntry(entryPath), "migrations", setName);
23123
+ return join4(coreRootFromEntry(entryPath), "migrations", setName);
23032
23124
  } catch {
23033
23125
  }
23034
23126
  const _require6 = createRequire(import.meta.url);
23035
23127
  try {
23036
23128
  const entryPath = _require6.resolve("@cleocode/core");
23037
- return join3(coreRootFromEntry(entryPath), "migrations", setName);
23129
+ return join4(coreRootFromEntry(entryPath), "migrations", setName);
23038
23130
  } catch (err) {
23039
23131
  throw new Error(
23040
23132
  `resolveCorePackageMigrationsFolder("${setName}"): cannot locate @cleocode/core from "${import.meta.url}". Ensure @cleocode/core is installed (workspace or npm). Original error: ${err.message}`
@@ -31225,11 +31317,11 @@ var init_lock = __esm({
31225
31317
 
31226
31318
  // packages/core/src/store/atomic.ts
31227
31319
  import { mkdir, readFile as readFile2, rename, unlink } from "node:fs/promises";
31228
- import { dirname as dirname2 } from "node:path";
31320
+ import { dirname as dirname3 } from "node:path";
31229
31321
  import writeFileAtomic from "write-file-atomic";
31230
31322
  async function atomicWrite(filePath, data, options) {
31231
31323
  try {
31232
- await mkdir(dirname2(filePath), { recursive: true });
31324
+ await mkdir(dirname3(filePath), { recursive: true });
31233
31325
  await writeFileAtomic(filePath, data, {
31234
31326
  encoding: options?.encoding ?? "utf8",
31235
31327
  mode: options?.mode
@@ -31262,7 +31354,7 @@ var init_atomic = __esm({
31262
31354
 
31263
31355
  // packages/core/src/store/backup.ts
31264
31356
  import { copyFile, rename as fsRename, mkdir as mkdir2, readdir, stat, unlink as unlink2 } from "node:fs/promises";
31265
- import { basename, join as join4 } from "node:path";
31357
+ import { basename, join as join5 } from "node:path";
31266
31358
  async function createBackup(filePath, backupDir, maxBackups = DEFAULT_MAX_BACKUPS) {
31267
31359
  try {
31268
31360
  await mkdir2(backupDir, { recursive: true });
@@ -31273,14 +31365,14 @@ async function createBackup(filePath, backupDir, maxBackups = DEFAULT_MAX_BACKUP
31273
31365
  throw new CleoError(3 /* FILE_ERROR */, `Cannot backup: source file not found: ${filePath}`);
31274
31366
  }
31275
31367
  for (let i = maxBackups; i >= 1; i--) {
31276
- const current = join4(backupDir, `${fileName}.${i}`);
31368
+ const current = join5(backupDir, `${fileName}.${i}`);
31277
31369
  if (i === maxBackups) {
31278
31370
  try {
31279
31371
  await unlink2(current);
31280
31372
  } catch {
31281
31373
  }
31282
31374
  } else {
31283
- const next = join4(backupDir, `${fileName}.${i + 1}`);
31375
+ const next = join5(backupDir, `${fileName}.${i + 1}`);
31284
31376
  try {
31285
31377
  await stat(current);
31286
31378
  await fsRename(current, next);
@@ -31288,7 +31380,7 @@ async function createBackup(filePath, backupDir, maxBackups = DEFAULT_MAX_BACKUP
31288
31380
  }
31289
31381
  }
31290
31382
  }
31291
- const backupPath = join4(backupDir, `${fileName}.1`);
31383
+ const backupPath = join5(backupDir, `${fileName}.1`);
31292
31384
  await copyFile(filePath, backupPath);
31293
31385
  return backupPath;
31294
31386
  } catch (err) {
@@ -31568,15 +31660,15 @@ var init_json2 = __esm({
31568
31660
 
31569
31661
  // packages/core/src/scaffold/ensure-config.ts
31570
31662
  import { existsSync as existsSync3, readFileSync } from "node:fs";
31571
- import { basename as basename2, dirname as dirname3, join as join5, resolve as resolve2 } from "node:path";
31663
+ import { basename as basename2, dirname as dirname4, join as join6, resolve as resolve2 } from "node:path";
31572
31664
  import { fileURLToPath as fileURLToPath2 } from "node:url";
31573
31665
  function getPackageRoot() {
31574
31666
  const thisFile = fileURLToPath2(import.meta.url);
31575
- return resolve2(dirname3(thisFile), "..", "..");
31667
+ return resolve2(dirname4(thisFile), "..", "..");
31576
31668
  }
31577
31669
  function getCleoVersion() {
31578
31670
  try {
31579
- const pkgPath = join5(getPackageRoot(), "package.json");
31671
+ const pkgPath = join6(getPackageRoot(), "package.json");
31580
31672
  const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
31581
31673
  return pkg.version ?? "0.0.0";
31582
31674
  } catch {
@@ -31601,15 +31693,15 @@ import {
31601
31693
  unlinkSync,
31602
31694
  writeFileSync
31603
31695
  } from "node:fs";
31604
- import { basename as basename3, join as join6 } from "node:path";
31696
+ import { basename as basename3, join as join7 } from "node:path";
31605
31697
  function scopeBaseDir(scope, cwd) {
31606
31698
  return scope === "project" ? resolveCleoDir(cwd) : getCleoHome();
31607
31699
  }
31608
31700
  function exodusArchiveDir(scope, cwd) {
31609
- return join6(scopeBaseDir(scope, cwd), ARCHIVE_DIR_NAME);
31701
+ return join7(scopeBaseDir(scope, cwd), ARCHIVE_DIR_NAME);
31610
31702
  }
31611
31703
  function exodusMarkerPath(scope, cwd) {
31612
- return join6(scopeBaseDir(scope, cwd), MARKER_FILENAME_BY_SCOPE[scope]);
31704
+ return join7(scopeBaseDir(scope, cwd), MARKER_FILENAME_BY_SCOPE[scope]);
31613
31705
  }
31614
31706
  function hasExodusCompleteMarker(scope, cwd) {
31615
31707
  try {
@@ -31637,10 +31729,10 @@ function writeExodusCompleteMarker(scope, archivedSources, cwd) {
31637
31729
  }
31638
31730
  function moveFileInto(srcPath, destDir) {
31639
31731
  mkdirSync(destDir, { recursive: true });
31640
- let dest = join6(destDir, basename3(srcPath));
31732
+ let dest = join7(destDir, basename3(srcPath));
31641
31733
  if (existsSync4(dest)) {
31642
31734
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "").replace(/Z$/, "Z");
31643
- dest = join6(destDir, `${basename3(srcPath)}.${stamp}`);
31735
+ dest = join7(destDir, `${basename3(srcPath)}.${stamp}`);
31644
31736
  }
31645
31737
  try {
31646
31738
  renameSync(srcPath, dest);
@@ -31739,11 +31831,11 @@ var init_archive2 = __esm({
31739
31831
 
31740
31832
  // packages/core/src/project-info.ts
31741
31833
  import { existsSync as existsSync5, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
31742
- import { join as join7 } from "node:path";
31834
+ import { join as join8 } from "node:path";
31743
31835
  function getProjectInfoSync(cwd) {
31744
31836
  const projectRoot = resolveOrCwd(cwd);
31745
31837
  const cleoDir = getCleoDirAbsolute(projectRoot);
31746
- const infoPath = join7(cleoDir, "project-info.json");
31838
+ const infoPath = join8(cleoDir, "project-info.json");
31747
31839
  if (!existsSync5(infoPath)) return null;
31748
31840
  try {
31749
31841
  const raw = readFileSync2(infoPath, "utf-8");
@@ -31772,7 +31864,7 @@ var init_project_info = __esm({
31772
31864
 
31773
31865
  // packages/core/src/store/worktree-isolation-guard.ts
31774
31866
  import { existsSync as existsSync6, statSync } from "node:fs";
31775
- import { dirname as dirname4, join as join8 } from "node:path";
31867
+ import { dirname as dirname5, join as join9 } from "node:path";
31776
31868
  function assertDbPathIsNotWorktreeResident(role, cwd) {
31777
31869
  let cleoDir;
31778
31870
  try {
@@ -31780,8 +31872,8 @@ function assertDbPathIsNotWorktreeResident(role, cwd) {
31780
31872
  } catch {
31781
31873
  return;
31782
31874
  }
31783
- const projectRoot = dirname4(cleoDir);
31784
- const projectGit = join8(projectRoot, ".git");
31875
+ const projectRoot = dirname5(cleoDir);
31876
+ const projectGit = join9(projectRoot, ".git");
31785
31877
  let isWorktreeGitlink = false;
31786
31878
  try {
31787
31879
  isWorktreeGitlink = existsSync6(projectGit) && statSync(projectGit).isFile();
@@ -32336,7 +32428,7 @@ var init_count_parity = __esm({
32336
32428
 
32337
32429
  // packages/core/src/store/exodus/plan.ts
32338
32430
  import { existsSync as existsSync8, readdirSync as readdirSync2, statfsSync, statSync as statSync2 } from "node:fs";
32339
- import { join as join9 } from "node:path";
32431
+ import { join as join10 } from "node:path";
32340
32432
  function computeRequiredBytes(totalSourceBytes, largestSourceBytes) {
32341
32433
  return Math.ceil(STAGING_HEADROOM_FACTOR * largestSourceBytes) + totalSourceBytes;
32342
32434
  }
@@ -32347,33 +32439,33 @@ function buildSourceDescriptors(cwd) {
32347
32439
  // Project-tier — go into consolidated project-scope cleo.db
32348
32440
  {
32349
32441
  name: "tasks",
32350
- path: join9(cleoDir, "tasks.db"),
32442
+ path: join10(cleoDir, "tasks.db"),
32351
32443
  targetScope: "project"
32352
32444
  },
32353
32445
  {
32354
32446
  name: "brain (project)",
32355
- path: join9(cleoDir, "brain.db"),
32447
+ path: join10(cleoDir, "brain.db"),
32356
32448
  targetScope: "project"
32357
32449
  },
32358
32450
  {
32359
32451
  name: "conduit",
32360
- path: join9(cleoDir, "conduit.db"),
32452
+ path: join10(cleoDir, "conduit.db"),
32361
32453
  targetScope: "project"
32362
32454
  },
32363
32455
  // Global-tier — go into consolidated global-scope cleo.db
32364
32456
  {
32365
32457
  name: "nexus",
32366
- path: join9(cleoHome, "nexus.db"),
32458
+ path: join10(cleoHome, "nexus.db"),
32367
32459
  targetScope: "global"
32368
32460
  },
32369
32461
  {
32370
32462
  name: "signaldock",
32371
- path: join9(cleoHome, "signaldock.db"),
32463
+ path: join10(cleoHome, "signaldock.db"),
32372
32464
  targetScope: "global"
32373
32465
  },
32374
32466
  {
32375
32467
  name: "skills",
32376
- path: join9(cleoHome, "skills.db"),
32468
+ path: join10(cleoHome, "skills.db"),
32377
32469
  targetScope: "global"
32378
32470
  }
32379
32471
  ];
@@ -32402,7 +32494,7 @@ function findExistingStaging(cleoDir) {
32402
32494
  const entries = readdirSync2(cleoDir, { withFileTypes: true });
32403
32495
  const stagingDirs = entries.filter((e) => e.isDirectory() && e.name.startsWith("exodus-staging-")).map((e) => e.name).sort().reverse();
32404
32496
  if (stagingDirs.length > 0) {
32405
- return join9(cleoDir, stagingDirs[0]);
32497
+ return join10(cleoDir, stagingDirs[0]);
32406
32498
  }
32407
32499
  } catch {
32408
32500
  }
@@ -32418,7 +32510,7 @@ function buildExodusPlan(cwd) {
32418
32510
  const availableBytes = getAvailableBytes(cleoDir);
32419
32511
  const diskPreflight = totalSourceBytes === 0 || availableBytes >= requiredBytes;
32420
32512
  const existingStaging = findExistingStaging(cleoDir);
32421
- const stagingDir = existingStaging ?? join9(cleoDir, deriveStagingDirName());
32513
+ const stagingDir = existingStaging ?? join10(cleoDir, deriveStagingDirName());
32422
32514
  const resumeFromStaging = existingStaging !== null;
32423
32515
  const projectDbPath = resolveDualScopeDbPath("project", cwd);
32424
32516
  const globalDbPath = resolveDualScopeDbPath("global");
@@ -32737,7 +32829,7 @@ import {
32737
32829
  unlinkSync as unlinkSync2,
32738
32830
  writeFileSync as writeFileSync3
32739
32831
  } from "node:fs";
32740
- import { join as join10 } from "node:path";
32832
+ import { join as join11 } from "node:path";
32741
32833
  function getSqliteVersion(db) {
32742
32834
  try {
32743
32835
  const row = db.prepare("SELECT sqlite_version() AS v").get();
@@ -32753,13 +32845,13 @@ function listTables2(db) {
32753
32845
  return rows.map((r) => r.name);
32754
32846
  }
32755
32847
  function writeJournal(stagingDir, journal) {
32756
- const journalPath = join10(stagingDir, JOURNAL_FILENAME);
32848
+ const journalPath = join11(stagingDir, JOURNAL_FILENAME);
32757
32849
  const tmpPath = `${journalPath}.tmp`;
32758
32850
  writeFileSync3(tmpPath, JSON.stringify(journal, null, 2) + "\n", "utf8");
32759
32851
  renameSync2(tmpPath, journalPath);
32760
32852
  }
32761
32853
  function readJournal(stagingDir) {
32762
- const journalPath = join10(stagingDir, JOURNAL_FILENAME);
32854
+ const journalPath = join11(stagingDir, JOURNAL_FILENAME);
32763
32855
  if (!existsSync10(journalPath)) return null;
32764
32856
  try {
32765
32857
  return JSON.parse(readFileSync3(journalPath, "utf8"));
@@ -32768,7 +32860,7 @@ function readJournal(stagingDir) {
32768
32860
  }
32769
32861
  }
32770
32862
  function clearExodusJournal(stagingDir) {
32771
- const journalPath = join10(stagingDir, JOURNAL_FILENAME);
32863
+ const journalPath = join11(stagingDir, JOURNAL_FILENAME);
32772
32864
  try {
32773
32865
  if (!existsSync10(journalPath)) return false;
32774
32866
  unlinkSync2(journalPath);
@@ -33077,7 +33169,7 @@ async function runExodusMigrate(plan, forceCrossVersion = false, onProgress) {
33077
33169
  var extractNativeDb = extractNativeDb2;
33078
33170
  for (const src of sources) {
33079
33171
  if (!existsSync10(src.path)) continue;
33080
- const backupDest = join10(stagingDir, `${src.name.replace(/[^a-z0-9-]/g, "_")}-backup.db`);
33172
+ const backupDest = join11(stagingDir, `${src.name.replace(/[^a-z0-9-]/g, "_")}-backup.db`);
33081
33173
  const srcBytes = safeStatBytes(src.path);
33082
33174
  const skipStagingCopy = srcBytes > plan.stagingCopyThresholdBytes;
33083
33175
  if (skipStagingCopy) {
@@ -33379,9 +33471,9 @@ var init_seal = __esm({
33379
33471
 
33380
33472
  // packages/core/src/store/exodus/status.ts
33381
33473
  import { existsSync as existsSync11, readdirSync as readdirSync3, readFileSync as readFileSync4, statSync as statSync5 } from "node:fs";
33382
- import { join as join11 } from "node:path";
33474
+ import { join as join12 } from "node:path";
33383
33475
  function readJournal2(stagingDir) {
33384
- const p = join11(stagingDir, JOURNAL_FILENAME2);
33476
+ const p = join12(stagingDir, JOURNAL_FILENAME2);
33385
33477
  if (!existsSync11(p)) return null;
33386
33478
  try {
33387
33479
  return JSON.parse(readFileSync4(p, "utf8"));
@@ -33391,7 +33483,7 @@ function readJournal2(stagingDir) {
33391
33483
  }
33392
33484
  function findStagingDirs(cleoDir) {
33393
33485
  try {
33394
- return readdirSync3(cleoDir, { withFileTypes: true }).filter((e) => e.isDirectory() && e.name.startsWith("exodus-staging-")).map((e) => join11(cleoDir, e.name)).sort().reverse();
33486
+ return readdirSync3(cleoDir, { withFileTypes: true }).filter((e) => e.isDirectory() && e.name.startsWith("exodus-staging-")).map((e) => join12(cleoDir, e.name)).sort().reverse();
33395
33487
  } catch {
33396
33488
  return [];
33397
33489
  }
@@ -34243,7 +34335,7 @@ __export(dual_scope_db_exports, {
34243
34335
  });
34244
34336
  import { existsSync as existsSync14, mkdirSync as mkdirSync3 } from "node:fs";
34245
34337
  import { createRequire as createRequire4 } from "node:module";
34246
- import { dirname as dirname5, join as join12 } from "node:path";
34338
+ import { dirname as dirname6, join as join13 } from "node:path";
34247
34339
  function assertWriteDurable(handle) {
34248
34340
  if (handle.exodusAbort) {
34249
34341
  throw new ExodusAbortWriteUnsafeError(handle.exodusAbort);
@@ -34260,9 +34352,9 @@ function cacheKey(scope, dbPath) {
34260
34352
  }
34261
34353
  function resolveDualScopeDbPath(scope, cwd) {
34262
34354
  if (scope === "project") {
34263
- return join12(resolveCleoDir(cwd), "cleo.db");
34355
+ return join13(resolveCleoDir(cwd), "cleo.db");
34264
34356
  }
34265
- return join12(getCleoHome(), "cleo.db");
34357
+ return join13(getCleoHome(), "cleo.db");
34266
34358
  }
34267
34359
  function migrationsSetName(scope) {
34268
34360
  return scope === "project" ? "drizzle-cleo-project" : "drizzle-cleo-global";
@@ -34302,7 +34394,7 @@ async function openDualScopeDb(scope, cwd) {
34302
34394
  }
34303
34395
  async function openDedicatedDualScopeDb(scope, dbPath, log10) {
34304
34396
  log10.debug({ scope, dbPath }, "opening DEDICATED (non-cached) dual-scope cleo.db (T11782 FIX D)");
34305
- const dir = dirname5(dbPath);
34397
+ const dir = dirname6(dbPath);
34306
34398
  if (!existsSync14(dir)) {
34307
34399
  mkdirSync3(dir, { recursive: true });
34308
34400
  }
@@ -34352,7 +34444,7 @@ async function openDualScopeDbAtPath(scope, dbPath, exodusCwd, options) {
34352
34444
  }
34353
34445
  const initPromise = (async () => {
34354
34446
  log10.debug({ scope, dbPath }, "opening dual-scope cleo.db");
34355
- const dir = dirname5(dbPath);
34447
+ const dir = dirname6(dbPath);
34356
34448
  if (!existsSync14(dir)) {
34357
34449
  mkdirSync3(dir, { recursive: true });
34358
34450
  }
@@ -34431,6 +34523,12 @@ async function openDualScopeDbAtPath(scope, dbPath, exodusCwd, options) {
34431
34523
  nativeDb: null,
34432
34524
  initPromise
34433
34525
  });
34526
+ initPromise.catch(() => {
34527
+ const entry = _cache.get(key);
34528
+ if (entry && entry.initPromise === initPromise) {
34529
+ _cache.delete(key);
34530
+ }
34531
+ });
34434
34532
  return initPromise;
34435
34533
  }
34436
34534
  function _resetDualScopeDbCache(scope) {
@@ -35022,7 +35120,7 @@ __export(nexus_sqlite_exports, {
35022
35120
  resolveNexusMigrationsFolder: () => resolveNexusMigrationsFolder
35023
35121
  });
35024
35122
  import { copyFileSync as copyFileSync4, existsSync as existsSync15 } from "node:fs";
35025
- import { join as join13 } from "node:path";
35123
+ import { join as join14 } from "node:path";
35026
35124
  function getNexusDbPath(cwd) {
35027
35125
  return resolveDualScopeDbPath("project", cwd);
35028
35126
  }
@@ -35054,7 +35152,7 @@ function resolveNexusMigrationsFolder() {
35054
35152
  return resolveCorePackageMigrationsFolder("drizzle-nexus");
35055
35153
  }
35056
35154
  function getNestedNexusSentinelPath() {
35057
- return join13(getCleoHome(), "nexus", NESTED_NEXUS_SENTINEL);
35155
+ return join14(getCleoHome(), "nexus", NESTED_NEXUS_SENTINEL);
35058
35156
  }
35059
35157
  function detectAndWarnOnNestedNexus() {
35060
35158
  let nestedPath;
@@ -35357,7 +35455,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
35357
35455
  import { existsSync as existsSync16, readFileSync as readFileSync5, statSync as statSync6 } from "node:fs";
35358
35456
  import { createRequire as createRequire5 } from "node:module";
35359
35457
  import { homedir } from "node:os";
35360
- import { basename as basename4, dirname as dirname6, join as join14, resolve as resolve3 } from "node:path";
35458
+ import { basename as basename4, dirname as dirname7, join as join15, resolve as resolve3 } from "node:path";
35361
35459
  import {
35362
35460
  computeCanonicalProjectId as _computeCanonicalProjectId,
35363
35461
  getCanonicalTemplatesTildePath as _getCanonicalTemplatesTildePath,
@@ -35447,7 +35545,7 @@ function getCleoDirAbsolute(cwd, opts) {
35447
35545
  function _resolveProjectByCwdFromNexus(cwd) {
35448
35546
  try {
35449
35547
  const cleoHome = getCleoHome();
35450
- const globalDbPath = join14(cleoHome, "cleo.db");
35548
+ const globalDbPath = join15(cleoHome, "cleo.db");
35451
35549
  if (!existsSync16(globalDbPath)) return null;
35452
35550
  const start = resolve3(cwd ?? process.cwd());
35453
35551
  let current = start;
@@ -35462,7 +35560,7 @@ function _resolveProjectByCwdFromNexus(cwd) {
35462
35560
  if (row && typeof row.project_id === "string" && row.project_id.length > 0) {
35463
35561
  return row.project_id;
35464
35562
  }
35465
- const parent = dirname6(current);
35563
+ const parent = dirname7(current);
35466
35564
  if (parent === current) break;
35467
35565
  current = parent;
35468
35566
  }
@@ -35487,13 +35585,13 @@ function _findCleoDirRoot(cwd) {
35487
35585
  const isDangerousRoot = current === homeRoot || current === "/" || current === "";
35488
35586
  if (!isDangerousRoot) {
35489
35587
  try {
35490
- if (statSync6(join14(current, ".cleo")).isDirectory()) {
35588
+ if (statSync6(join15(current, ".cleo")).isDirectory()) {
35491
35589
  return current;
35492
35590
  }
35493
35591
  } catch {
35494
35592
  }
35495
35593
  }
35496
- const parent = dirname6(current);
35594
+ const parent = dirname7(current);
35497
35595
  if (parent === current) break;
35498
35596
  current = parent;
35499
35597
  }
@@ -35502,7 +35600,7 @@ function _findCleoDirRoot(cwd) {
35502
35600
  function resolveCleoDir(cwd) {
35503
35601
  const scope = worktreeScope.getStore();
35504
35602
  if (scope !== void 0) {
35505
- return join14(scope.worktreeRoot, ".cleo");
35603
+ return join15(scope.worktreeRoot, ".cleo");
35506
35604
  }
35507
35605
  const override = _cleoDirEnvOverride();
35508
35606
  if (override !== null) {
@@ -35510,16 +35608,16 @@ function resolveCleoDir(cwd) {
35510
35608
  }
35511
35609
  const root = _findCleoDirRoot(cwd);
35512
35610
  if (root !== null) {
35513
- return join14(root, ".cleo");
35611
+ return join15(root, ".cleo");
35514
35612
  }
35515
35613
  const start = resolve3(cwd ?? process.cwd());
35516
35614
  let current = start;
35517
35615
  while (true) {
35518
35616
  const mainRepo = _resolveMainRepoFromGitlink(current);
35519
35617
  if (mainRepo !== null) {
35520
- return join14(mainRepo, ".cleo");
35618
+ return join15(mainRepo, ".cleo");
35521
35619
  }
35522
- const parent = dirname6(current);
35620
+ const parent = dirname7(current);
35523
35621
  if (parent === current) {
35524
35622
  break;
35525
35623
  }
@@ -35559,21 +35657,21 @@ function _cwdHasGitAncestor(cwd) {
35559
35657
  const start = resolve3(cwd ?? process.cwd());
35560
35658
  let current = start;
35561
35659
  while (true) {
35562
- const gitMarker = join14(current, ".git");
35660
+ const gitMarker = join15(current, ".git");
35563
35661
  try {
35564
35662
  if (existsSync16(gitMarker)) {
35565
35663
  return true;
35566
35664
  }
35567
35665
  } catch {
35568
35666
  }
35569
- const parent = dirname6(current);
35667
+ const parent = dirname7(current);
35570
35668
  if (parent === current) return false;
35571
35669
  current = parent;
35572
35670
  }
35573
35671
  }
35574
35672
  function _resolveMainRepoFromGitlink(gitlinkDir) {
35575
35673
  try {
35576
- const gitLinkPath = join14(gitlinkDir, ".git");
35674
+ const gitLinkPath = join15(gitlinkDir, ".git");
35577
35675
  if (!existsSync16(gitLinkPath)) return null;
35578
35676
  const stat2 = statSync6(gitLinkPath);
35579
35677
  if (!stat2.isFile()) return null;
@@ -35581,8 +35679,8 @@ function _resolveMainRepoFromGitlink(gitlinkDir) {
35581
35679
  const match = gitLinkContent.match(/^gitdir:\s*(.+)$/m);
35582
35680
  if (!match) return null;
35583
35681
  const gitdir = match[1].trim();
35584
- const mainRepo = dirname6(dirname6(dirname6(gitdir)));
35585
- if (existsSync16(join14(mainRepo, ".cleo")) && validateProjectRoot(mainRepo)) {
35682
+ const mainRepo = dirname7(dirname7(dirname7(gitdir)));
35683
+ if (existsSync16(join15(mainRepo, ".cleo")) && validateProjectRoot(mainRepo)) {
35586
35684
  return mainRepo;
35587
35685
  }
35588
35686
  } catch {
@@ -35590,17 +35688,17 @@ function _resolveMainRepoFromGitlink(gitlinkDir) {
35590
35688
  return null;
35591
35689
  }
35592
35690
  function validateProjectRoot(candidate) {
35593
- const cleoDir = join14(candidate, ".cleo");
35691
+ const cleoDir = join15(candidate, ".cleo");
35594
35692
  if (!existsSync16(cleoDir)) {
35595
35693
  return false;
35596
35694
  }
35597
- const projectInfoPath = join14(cleoDir, "project-info.json");
35695
+ const projectInfoPath = join15(cleoDir, "project-info.json");
35598
35696
  if (existsSync16(projectInfoPath)) {
35599
35697
  try {
35600
35698
  const raw = readFileSync5(projectInfoPath, "utf-8");
35601
35699
  const parsed = JSON.parse(raw);
35602
35700
  if (typeof parsed === "object" && parsed !== null && "projectId" in parsed && typeof parsed["projectId"] === "string" && parsed["projectId"] !== "") {
35603
- const gitMarker = join14(candidate, ".git");
35701
+ const gitMarker = join15(candidate, ".git");
35604
35702
  if (existsSync16(gitMarker)) {
35605
35703
  try {
35606
35704
  if (!statSync6(gitMarker).isDirectory()) {
@@ -35615,7 +35713,7 @@ function validateProjectRoot(candidate) {
35615
35713
  } catch {
35616
35714
  }
35617
35715
  }
35618
- const gitDir = join14(candidate, ".git");
35716
+ const gitDir = join15(candidate, ".git");
35619
35717
  if (existsSync16(gitDir)) {
35620
35718
  let isRealGitDir = false;
35621
35719
  try {
@@ -35652,7 +35750,7 @@ function getProjectRoot(cwd) {
35652
35750
  const cleoDirEnv = process.env["CLEO_DIR"];
35653
35751
  if (cleoDirEnv && isAbsolutePath(cleoDirEnv)) {
35654
35752
  if (cleoDirEnv.endsWith("/.cleo") || cleoDirEnv.endsWith("\\.cleo")) {
35655
- return dirname6(cleoDirEnv);
35753
+ return dirname7(cleoDirEnv);
35656
35754
  }
35657
35755
  return cleoDirEnv;
35658
35756
  }
@@ -35663,8 +35761,8 @@ function getProjectRoot(cwd) {
35663
35761
  const homeRoot = homedir();
35664
35762
  const skippedCleoDirs = [];
35665
35763
  while (true) {
35666
- const cleoDir = join14(current, ".cleo");
35667
- const gitDir = join14(current, ".git");
35764
+ const cleoDir = join15(current, ".cleo");
35765
+ const gitDir = join15(current, ".git");
35668
35766
  const isDangerousRoot = current === homeRoot || current === "/" || current === "";
35669
35767
  if (existsSync16(cleoDir) && !isDangerousRoot) {
35670
35768
  if (validateProjectRoot(current)) {
@@ -35687,7 +35785,7 @@ function getProjectRoot(cwd) {
35687
35785
  const mainRepoFromWalk = _resolveMainRepoFromGitlink(current);
35688
35786
  if (mainRepoFromWalk !== null) return mainRepoFromWalk;
35689
35787
  }
35690
- const parent = dirname6(current);
35788
+ const parent = dirname7(current);
35691
35789
  if (parent === current) {
35692
35790
  break;
35693
35791
  }
@@ -35717,17 +35815,17 @@ function resolveOrCwd(maybeRoot) {
35717
35815
  return getProjectRoot();
35718
35816
  }
35719
35817
  function getConfigPath(cwd) {
35720
- return join14(_resolveCleoDir(cwd), "config.json");
35818
+ return join15(_resolveCleoDir(cwd), "config.json");
35721
35819
  }
35722
35820
  function getGlobalConfigPath() {
35723
- return join14(getCleoHome(), "config.json");
35821
+ return join15(getCleoHome(), "config.json");
35724
35822
  }
35725
35823
  function isAbsolutePath(path2) {
35726
35824
  return _isAbsolutePath(path2);
35727
35825
  }
35728
35826
  function _readProjectNameFromInfo(projectRoot) {
35729
35827
  try {
35730
- const infoPath = join14(projectRoot, ".cleo", "project-info.json");
35828
+ const infoPath = join15(projectRoot, ".cleo", "project-info.json");
35731
35829
  if (!existsSync16(infoPath)) return void 0;
35732
35830
  const raw = readFileSync5(infoPath, "utf-8");
35733
35831
  const data = JSON.parse(raw);
@@ -35754,8 +35852,8 @@ async function registerProjectOnEncounter(projectRoot, infoProjectId) {
35754
35852
  if (existingRows.length > 0) {
35755
35853
  const existingPath = existingRows[0].projectPath;
35756
35854
  if (existingPath !== resolvedPath) {
35757
- const newBrainDbPath = join14(resolvedPath, ".cleo", "brain.db");
35758
- const newTasksDbPath = join14(resolvedPath, ".cleo", "tasks.db");
35855
+ const newBrainDbPath = join15(resolvedPath, ".cleo", "brain.db");
35856
+ const newTasksDbPath = join15(resolvedPath, ".cleo", "tasks.db");
35759
35857
  await db.update(projectRegistry2).set({
35760
35858
  projectPath: resolvedPath,
35761
35859
  projectHash: generateProjectHash2(resolvedPath),
@@ -35786,8 +35884,8 @@ async function registerProjectOnEncounter(projectRoot, infoProjectId) {
35786
35884
  lastSync: now,
35787
35885
  taskCount: 0,
35788
35886
  labelsJson: "[]",
35789
- brainDbPath: join14(resolvedPath, ".cleo", "brain.db"),
35790
- tasksDbPath: join14(resolvedPath, ".cleo", "tasks.db"),
35887
+ brainDbPath: join15(resolvedPath, ".cleo", "brain.db"),
35888
+ tasksDbPath: join15(resolvedPath, ".cleo", "tasks.db"),
35791
35889
  statsJson: "{}"
35792
35890
  }).onConflictDoNothing();
35793
35891
  const aliases = canonicalResult.legacyAliases ?? [];
@@ -36004,7 +36102,7 @@ __export(config_exports, {
36004
36102
  });
36005
36103
  import { existsSync as existsSync17 } from "node:fs";
36006
36104
  import { mkdir as mkdir3, writeFile } from "node:fs/promises";
36007
- import { dirname as dirname7 } from "node:path";
36105
+ import { dirname as dirname8 } from "node:path";
36008
36106
  function getNestedValue(obj, path2) {
36009
36107
  const parts = path2.split(".");
36010
36108
  let current = obj;
@@ -36127,7 +36225,7 @@ function parseConfigValue(value) {
36127
36225
  async function setConfigValue(key, value, cwd, opts) {
36128
36226
  const configPath = opts?.global ? getGlobalConfigPath() : getConfigPath(cwd);
36129
36227
  if (!existsSync17(configPath)) {
36130
- const dir = dirname7(configPath);
36228
+ const dir = dirname8(configPath);
36131
36229
  await mkdir3(dir, { recursive: true });
36132
36230
  await writeFile(configPath, "{}", "utf-8");
36133
36231
  }
@@ -36141,7 +36239,7 @@ async function applyStrictnessPreset(preset, cwd, opts) {
36141
36239
  const definition = STRICTNESS_PRESETS[preset];
36142
36240
  const configPath = opts?.global ? getGlobalConfigPath() : getConfigPath(cwd);
36143
36241
  if (!existsSync17(configPath)) {
36144
- const dir = dirname7(configPath);
36242
+ const dir = dirname8(configPath);
36145
36243
  await mkdir3(dir, { recursive: true });
36146
36244
  await writeFile(configPath, "{}", "utf-8");
36147
36245
  }
@@ -37316,9 +37414,9 @@ var init_telemetry_schema = __esm({
37316
37414
 
37317
37415
  // packages/core/src/telemetry/sqlite.ts
37318
37416
  import { mkdirSync as mkdirSync4 } from "node:fs";
37319
- import { dirname as dirname8, join as join15 } from "node:path";
37417
+ import { dirname as dirname9, join as join16 } from "node:path";
37320
37418
  function getTelemetryDbPath() {
37321
- return join15(getCleoHome(), DB_FILENAME);
37419
+ return join16(getCleoHome(), DB_FILENAME);
37322
37420
  }
37323
37421
  function resolveTelemetryMigrationsFolder() {
37324
37422
  return resolveCorePackageMigrationsFolder("drizzle-telemetry");
@@ -37366,7 +37464,7 @@ async function getTelemetryDb() {
37366
37464
  _initPromise2 = (async () => {
37367
37465
  const dbPath = requestedPath;
37368
37466
  _dbPath2 = dbPath;
37369
- mkdirSync4(dirname8(dbPath), { recursive: true });
37467
+ mkdirSync4(dirname9(dbPath), { recursive: true });
37370
37468
  const nativeDb = openNativeDatabase(dbPath);
37371
37469
  _nativeDb2 = nativeDb;
37372
37470
  const db = drizzle({ client: nativeDb, schema: telemetry_schema_exports });
@@ -37400,10 +37498,10 @@ var init_sqlite2 = __esm({
37400
37498
 
37401
37499
  // packages/core/src/store/agent-registry-store.ts
37402
37500
  import { existsSync as existsSync18 } from "node:fs";
37403
- import { join as join16 } from "node:path";
37501
+ import { join as join17 } from "node:path";
37404
37502
  function getGlobalAgentRegistryDbPath() {
37405
37503
  const cleoHome = getCleoHome();
37406
- const dbPath = join16(cleoHome, "cleo.db");
37504
+ const dbPath = join17(cleoHome, "cleo.db");
37407
37505
  if (!dbPath.startsWith(cleoHome)) {
37408
37506
  throw new Error(
37409
37507
  `BUG: getGlobalAgentRegistryDbPath() resolved to "${dbPath}" which is NOT under getCleoHome() ("${cleoHome}"). The Agent Registry is global-only per ADR-037. This indicates a code path that bypasses path resolution \u2014 fix the caller, do not suppress this error.`
@@ -37744,11 +37842,11 @@ var init_skills_schema = __esm({
37744
37842
  });
37745
37843
 
37746
37844
  // packages/core/src/store/skills-db.ts
37747
- import { join as join17 } from "node:path";
37845
+ import { join as join18 } from "node:path";
37748
37846
  import { and as and3, eq as eq4 } from "drizzle-orm";
37749
37847
  function getDefaultSkillsDbPath() {
37750
37848
  const cleoHome = getCleoHome();
37751
- const dbPath = join17(cleoHome, "cleo.db");
37849
+ const dbPath = join18(cleoHome, "cleo.db");
37752
37850
  if (!dbPath.startsWith(cleoHome)) {
37753
37851
  throw new Error(
37754
37852
  `BUG: getDefaultSkillsDbPath() resolved to "${dbPath}" which is NOT under getCleoHome() ("${cleoHome}"). The skills registry is global-only per SG-CLEO-SKILLS-architecture-v3.md \xA74. Fix the caller, do not suppress.`
@@ -37824,7 +37922,7 @@ import {
37824
37922
  statSync as statSync7,
37825
37923
  unlinkSync as unlinkSync3
37826
37924
  } from "node:fs";
37827
- import { join as join18 } from "node:path";
37925
+ import { join as join19 } from "node:path";
37828
37926
  function resolveInventoryPath(entry, cwd) {
37829
37927
  try {
37830
37928
  if (entry.tier === "global") {
@@ -37859,7 +37957,7 @@ async function openAgentRegistryDbForSnapshot() {
37859
37957
  }
37860
37958
  async function openTelemetryDbForSnapshot() {
37861
37959
  try {
37862
- const path2 = join18(getCleoHome(), "telemetry.db");
37960
+ const path2 = join19(getCleoHome(), "telemetry.db");
37863
37961
  if (!existsSync20(path2)) return null;
37864
37962
  } catch {
37865
37963
  return null;
@@ -37965,8 +38063,8 @@ function rotateSnapshots(backupDir, prefix) {
37965
38063
  const pattern = snapshotPattern(prefix);
37966
38064
  const files = readdirSync4(backupDir).filter((f) => pattern.test(f)).map((f) => ({
37967
38065
  name: f,
37968
- path: join18(backupDir, f),
37969
- mtimeMs: statSync7(join18(backupDir, f)).mtimeMs
38066
+ path: join19(backupDir, f),
38067
+ mtimeMs: statSync7(join19(backupDir, f)).mtimeMs
37970
38068
  })).sort((a, b) => a.mtimeMs - b.mtimeMs);
37971
38069
  while (files.length >= MAX_SNAPSHOTS) {
37972
38070
  const oldest = files.shift();
@@ -37991,7 +38089,7 @@ async function snapshotOne(target, backupDir, now, cwd) {
37991
38089
  if (!db) return;
37992
38090
  opened = db;
37993
38091
  }
37994
- const dest = join18(backupDir, `${target.prefix}-${formatTimestamp(now)}.db`);
38092
+ const dest = join19(backupDir, `${target.prefix}-${formatTimestamp(now)}.db`);
37995
38093
  try {
37996
38094
  db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
37997
38095
  rotateSnapshots(backupDir, target.prefix);
@@ -38012,7 +38110,7 @@ async function vacuumIntoBackup(opts = {}) {
38012
38110
  }
38013
38111
  try {
38014
38112
  const cleoDir = getCleoDir(opts.cwd);
38015
- const backupDir = join18(cleoDir, "backups", "sqlite");
38113
+ const backupDir = join19(cleoDir, "backups", "sqlite");
38016
38114
  mkdirSync5(backupDir, { recursive: true });
38017
38115
  const target = SNAPSHOT_TARGETS.find((t) => t.prefix === prefix);
38018
38116
  if (!target) return;
@@ -38024,13 +38122,13 @@ async function vacuumIntoBackup(opts = {}) {
38024
38122
  function listSqliteBackupsForPrefix(prefix, cwd) {
38025
38123
  try {
38026
38124
  const cleoDir = getCleoDir(cwd);
38027
- const backupDir = join18(cleoDir, "backups", "sqlite");
38125
+ const backupDir = join19(cleoDir, "backups", "sqlite");
38028
38126
  if (!existsSync20(backupDir)) return [];
38029
38127
  const pattern = snapshotPattern(prefix);
38030
38128
  return readdirSync4(backupDir).filter((f) => pattern.test(f)).map((f) => ({
38031
38129
  name: f,
38032
- path: join18(backupDir, f),
38033
- mtimeMs: statSync7(join18(backupDir, f)).mtimeMs
38130
+ path: join19(backupDir, f),
38131
+ mtimeMs: statSync7(join19(backupDir, f)).mtimeMs
38034
38132
  })).sort((a, b) => b.mtimeMs - a.mtimeMs);
38035
38133
  } catch {
38036
38134
  return [];
@@ -38086,7 +38184,7 @@ __export(sqlite_native_exports, {
38086
38184
  import { realpathSync } from "node:fs";
38087
38185
  import { createRequire as createRequire8 } from "node:module";
38088
38186
  import { tmpdir } from "node:os";
38089
- import { delimiter, dirname as dirname9, isAbsolute, join as join19, resolve as resolve4, sep } from "node:path";
38187
+ import { delimiter, dirname as dirname10, isAbsolute, join as join20, resolve as resolve4, sep } from "node:path";
38090
38188
  function getDbSyncConstructor() {
38091
38189
  if (_ctor === null) {
38092
38190
  const mod = _require5("node:sqlite");
@@ -38102,12 +38200,12 @@ function resolveAbsoluteSafe(p) {
38102
38200
  const missingParts = [];
38103
38201
  let cursor = abs;
38104
38202
  while (true) {
38105
- const parent = dirname9(cursor);
38203
+ const parent = dirname10(cursor);
38106
38204
  if (parent === cursor) return abs;
38107
38205
  missingParts.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
38108
38206
  cursor = parent;
38109
38207
  try {
38110
- return join19(realpathSync(cursor), ...missingParts);
38208
+ return join20(realpathSync(cursor), ...missingParts);
38111
38209
  } catch {
38112
38210
  }
38113
38211
  }
@@ -39613,12 +39711,12 @@ var init_sqlite_data_accessor = __esm({
39613
39711
 
39614
39712
  // packages/core/src/sequence/index.ts
39615
39713
  import { existsSync as existsSync22, readFileSync as readFileSync6, renameSync as renameSync4 } from "node:fs";
39616
- import { join as join20 } from "node:path";
39714
+ import { join as join21 } from "node:path";
39617
39715
  function getLegacySequenceJsonPath(cwd) {
39618
- return join20(resolveOrCwd(cwd), ".cleo", ".sequence.json");
39716
+ return join21(resolveOrCwd(cwd), ".cleo", ".sequence.json");
39619
39717
  }
39620
39718
  function getLegacySequencePath(cwd) {
39621
- return join20(resolveOrCwd(cwd), ".cleo", ".sequence");
39719
+ return join21(resolveOrCwd(cwd), ".cleo", ".sequence");
39622
39720
  }
39623
39721
  function isValidSequenceState(value) {
39624
39722
  if (!value || typeof value !== "object") return false;
@@ -39806,13 +39904,13 @@ var init_sequence = __esm({
39806
39904
  import { execFile as execFile2 } from "node:child_process";
39807
39905
  import { existsSync as existsSync23 } from "node:fs";
39808
39906
  import { readFile as readFile3, writeFile as writeFile2 } from "node:fs/promises";
39809
- import { join as join21, resolve as resolve5 } from "node:path";
39907
+ import { join as join22, resolve as resolve5 } from "node:path";
39810
39908
  import { promisify as promisify2 } from "node:util";
39811
39909
  function makeCleoGitEnv(cleoDir) {
39812
39910
  const abs = resolve5(cleoDir);
39813
39911
  return {
39814
39912
  ...process.env,
39815
- GIT_DIR: join21(abs, ".git"),
39913
+ GIT_DIR: join22(abs, ".git"),
39816
39914
  GIT_WORK_TREE: abs
39817
39915
  };
39818
39916
  }
@@ -39830,7 +39928,7 @@ async function cleoGitCommand(args, cleoDir) {
39830
39928
  }
39831
39929
  }
39832
39930
  function isCleoGitInitialized(cleoDir) {
39833
- return existsSync23(join21(cleoDir, ".git", "HEAD"));
39931
+ return existsSync23(join22(cleoDir, ".git", "HEAD"));
39834
39932
  }
39835
39933
  async function loadStateFileAllowlist(cwd) {
39836
39934
  try {
@@ -39874,25 +39972,25 @@ async function isCleoGitRepo(cleoDir) {
39874
39972
  return result.success && (result.stdout === "true" || isCleoGitInitialized(cleoDir));
39875
39973
  }
39876
39974
  function isMergeInProgress(cleoDir) {
39877
- return existsSync23(join21(cleoDir, ".git", "MERGE_HEAD"));
39975
+ return existsSync23(join22(cleoDir, ".git", "MERGE_HEAD"));
39878
39976
  }
39879
39977
  async function isDetachedHead(cleoDir) {
39880
39978
  const result = await cleoGitCommand(["symbolic-ref", "HEAD"], cleoDir);
39881
39979
  return !result.success;
39882
39980
  }
39883
39981
  function isRebaseInProgress(cleoDir) {
39884
- return existsSync23(join21(cleoDir, ".git", "rebase-merge")) || existsSync23(join21(cleoDir, ".git", "rebase-apply"));
39982
+ return existsSync23(join22(cleoDir, ".git", "rebase-merge")) || existsSync23(join22(cleoDir, ".git", "rebase-apply"));
39885
39983
  }
39886
39984
  async function recordCheckpointTime(cleoDir) {
39887
39985
  try {
39888
- const stateFile = join21(cleoDir, CHECKPOINT_STATE_FILE);
39986
+ const stateFile = join22(cleoDir, CHECKPOINT_STATE_FILE);
39889
39987
  await writeFile2(stateFile, String(Math.floor(Date.now() / 1e3)));
39890
39988
  } catch {
39891
39989
  }
39892
39990
  }
39893
39991
  async function getLastCheckpointTime(cleoDir) {
39894
39992
  try {
39895
- const stateFile = join21(cleoDir, CHECKPOINT_STATE_FILE);
39993
+ const stateFile = join22(cleoDir, CHECKPOINT_STATE_FILE);
39896
39994
  const content = await readFile3(stateFile, "utf-8");
39897
39995
  const epoch = parseInt(content.trim(), 10);
39898
39996
  return Number.isNaN(epoch) ? 0 : epoch;
@@ -39904,7 +40002,7 @@ async function getChangedStateFiles(cleoDir, cwd) {
39904
40002
  const changed = [];
39905
40003
  const allStateFiles = await getAllStateFiles(cwd);
39906
40004
  for (const stateFile of allStateFiles) {
39907
- const fullPath = join21(cleoDir, stateFile);
40005
+ const fullPath = join22(cleoDir, stateFile);
39908
40006
  if (!existsSync23(fullPath)) continue;
39909
40007
  const diffResult = await cleoGitCommand(["diff", "--quiet", "--", stateFile], cleoDir);
39910
40008
  const cachedResult = await cleoGitCommand(