@cleocode/cleo 2026.4.107 → 2026.4.108

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/cli/index.js CHANGED
@@ -557,7 +557,7 @@ function createSuccessResult() {
557
557
  function isErrorResult(result) {
558
558
  return !result.success;
559
559
  }
560
- var ThinAgentViolationError;
560
+ var ThinAgentViolationError, LifecycleScopeDeniedError;
561
561
  var init_errors = __esm({
562
562
  "packages/contracts/src/errors.ts"() {
563
563
  "use strict";
@@ -585,6 +585,26 @@ var init_errors = __esm({
585
585
  /** Numeric exit code aligned with {@link ExitCode.THIN_AGENT_VIOLATION}. */
586
586
  exitCode = 68 /* THIN_AGENT_VIOLATION */;
587
587
  };
588
+ LifecycleScopeDeniedError = class extends Error {
589
+ /**
590
+ * @param epicId - The epic whose lifecycle mutation was blocked.
591
+ * @param sessionScope - Human-readable description of the current session scope.
592
+ */
593
+ constructor(epicId, sessionScope) {
594
+ super(
595
+ `E_LIFECYCLE_SCOPE_DENIED: lifecycle stage advancement for epic '${epicId}' requires a session scoped to that epic or an owner override. Current session scope: ${sessionScope}. Use CLEO_OWNER_OVERRIDE=1 if this is an authorized operation.`
596
+ );
597
+ this.epicId = epicId;
598
+ this.sessionScope = sessionScope;
599
+ this.name = "LifecycleScopeDeniedError";
600
+ }
601
+ epicId;
602
+ sessionScope;
603
+ /** Stable LAFS error code string for envelope emission. */
604
+ code = "E_LIFECYCLE_SCOPE_DENIED";
605
+ /** Numeric exit code aligned with {@link ExitCode.TASK_NOT_IN_SCOPE} (34). */
606
+ exitCode = 34 /* TASK_NOT_IN_SCOPE */;
607
+ };
588
608
  }
589
609
  });
590
610
 
@@ -881,12 +901,12 @@ var init_session2 = __esm({
881
901
  "use strict";
882
902
  SessionView = class _SessionView {
883
903
  _sessions;
884
- constructor(sessions2) {
885
- this._sessions = sessions2;
904
+ constructor(sessions3) {
905
+ this._sessions = sessions3;
886
906
  }
887
907
  /** Create a SessionView from a Session array. */
888
- static from(sessions2) {
889
- return new _SessionView(sessions2);
908
+ static from(sessions3) {
909
+ return new _SessionView(sessions3);
890
910
  }
891
911
  /** All sessions in the view (readonly). */
892
912
  get all() {
@@ -2148,10 +2168,10 @@ var init_subquery = __esm({
2148
2168
  init_entity();
2149
2169
  Subquery = class {
2150
2170
  static [entityKind] = "Subquery";
2151
- constructor(sql18, fields, alias, isWith = false, usedTables = []) {
2171
+ constructor(sql19, fields, alias, isWith = false, usedTables = []) {
2152
2172
  this._ = {
2153
2173
  brand: "Subquery",
2154
- sql: sql18,
2174
+ sql: sql19,
2155
2175
  selectedFields: fields,
2156
2176
  alias,
2157
2177
  isWith,
@@ -2582,8 +2602,8 @@ var init_sql = __esm({
2582
2602
  isSelectionField = false;
2583
2603
  /** @internal */
2584
2604
  origin;
2585
- constructor(sql18, fieldAlias) {
2586
- this.sql = sql18;
2605
+ constructor(sql19, fieldAlias) {
2606
+ this.sql = sql19;
2587
2607
  this.fieldAlias = fieldAlias;
2588
2608
  }
2589
2609
  getSQL() {
@@ -3661,8 +3681,8 @@ var init_custom = __esm({
3661
3681
  mapFromJsonValue(value) {
3662
3682
  return typeof this.mapJson === "function" ? this.mapJson(value) : this.mapFromDriverValue(value);
3663
3683
  }
3664
- jsonSelectIdentifier(identifier, sql18, arrayDimensions) {
3665
- if (typeof this.forJsonSelect === "function") return this.forJsonSelect(identifier, sql18, arrayDimensions);
3684
+ jsonSelectIdentifier(identifier, sql19, arrayDimensions) {
3685
+ if (typeof this.forJsonSelect === "function") return this.forJsonSelect(identifier, sql19, arrayDimensions);
3666
3686
  const rawType = this.getSQLType().toLowerCase();
3667
3687
  const parenPos = rawType.indexOf("(");
3668
3688
  switch (parenPos + 1 ? rawType.slice(0, parenPos) : rawType) {
@@ -3672,7 +3692,7 @@ var init_custom = __esm({
3672
3692
  case "numeric":
3673
3693
  case "bigint": {
3674
3694
  const arrVal = "[]".repeat(arrayDimensions ?? 0);
3675
- return sql18`${identifier}::text${sql18.raw(arrVal).if(arrayDimensions)}`;
3695
+ return sql19`${identifier}::text${sql19.raw(arrVal).if(arrayDimensions)}`;
3676
3696
  }
3677
3697
  default:
3678
3698
  return identifier;
@@ -6624,17 +6644,17 @@ var init_custom2 = __esm({
6624
6644
  mapFromJsonValue(value) {
6625
6645
  return typeof this.mapJson === "function" ? this.mapJson(value) : this.mapFromDriverValue(value);
6626
6646
  }
6627
- jsonSelectIdentifier(identifier, sql18) {
6628
- if (typeof this.forJsonSelect === "function") return this.forJsonSelect(identifier, sql18);
6647
+ jsonSelectIdentifier(identifier, sql19) {
6648
+ if (typeof this.forJsonSelect === "function") return this.forJsonSelect(identifier, sql19);
6629
6649
  const rawType = this.getSQLType().toLowerCase();
6630
6650
  const parenPos = rawType.indexOf("(");
6631
6651
  switch (parenPos + 1 ? rawType.slice(0, parenPos) : rawType) {
6632
6652
  case "numeric":
6633
6653
  case "decimal":
6634
6654
  case "bigint":
6635
- return sql18`cast(${identifier} as text)`;
6655
+ return sql19`cast(${identifier} as text)`;
6636
6656
  case "blob":
6637
- return sql18`hex(${identifier})`;
6657
+ return sql19`hex(${identifier})`;
6638
6658
  default:
6639
6659
  return identifier;
6640
6660
  }
@@ -8375,8 +8395,8 @@ var init_dialect = __esm({
8375
8395
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
8376
8396
  return sql`${withSql}insert into ${table} ${insertOrder} ${valuesSql}${onConflict?.length ? sql.join(onConflict) : void 0}${returningSql}`;
8377
8397
  }
8378
- sqlToQuery(sql18, invokeSource) {
8379
- return sql18.toQuery({
8398
+ sqlToQuery(sql19, invokeSource) {
8399
+ return sql19.toQuery({
8380
8400
  casing: this.casing,
8381
8401
  escapeName: this.escapeName,
8382
8402
  escapeParam: this.escapeParam,
@@ -9473,8 +9493,8 @@ var init_db = __esm({
9473
9493
  });
9474
9494
 
9475
9495
  // node_modules/.pnpm/drizzle-orm@1.0.0-beta.22-ec7b61d_@opentelemetry+api@1.9.0_@sinclair+typebox@0.34.49_@t_a07afdeca00339cf8cd15f0f0c1cd4e1/node_modules/drizzle-orm/cache/core/cache.js
9476
- async function hashQuery(sql18, params) {
9477
- const dataToHash = `${sql18}-${JSON.stringify(params, (_2, v2) => typeof v2 === "bigint" ? `${v2}n` : v2)}`;
9496
+ async function hashQuery(sql19, params) {
9497
+ const dataToHash = `${sql19}-${JSON.stringify(params, (_2, v2) => typeof v2 === "bigint" ? `${v2}n` : v2)}`;
9478
9498
  const data = new TextEncoder().encode(dataToHash);
9479
9499
  const hashBuffer = await crypto.subtle.digest("SHA-256", data);
9480
9500
  return [...new Uint8Array(hashBuffer)].map((b2) => b2.toString(16).padStart(2, "0")).join("");
@@ -9653,8 +9673,8 @@ var init_session3 = __esm({
9653
9673
  values(query) {
9654
9674
  return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).values();
9655
9675
  }
9656
- async count(sql18) {
9657
- return (await this.values(sql18))[0][0];
9676
+ async count(sql19) {
9677
+ return (await this.values(sql19))[0][0];
9658
9678
  }
9659
9679
  /** @internal */
9660
9680
  extractRawValuesValueFromBatchResult(_result) {
@@ -12637,17 +12657,6 @@ var init_migrator = __esm({
12637
12657
  }
12638
12658
  });
12639
12659
 
12640
- // node_modules/.pnpm/drizzle-orm@1.0.0-beta.22-ec7b61d_@opentelemetry+api@1.9.0_@sinclair+typebox@0.34.49_@t_a07afdeca00339cf8cd15f0f0c1cd4e1/node_modules/drizzle-orm/node-sqlite/migrator.js
12641
- function migrate(db, config2) {
12642
- const migrations = readMigrationFiles(config2);
12643
- return db.dialect.migrate(migrations, db.session, config2);
12644
- }
12645
- var init_migrator2 = __esm({
12646
- "node_modules/.pnpm/drizzle-orm@1.0.0-beta.22-ec7b61d_@opentelemetry+api@1.9.0_@sinclair+typebox@0.34.49_@t_a07afdeca00339cf8cd15f0f0c1cd4e1/node_modules/drizzle-orm/node-sqlite/migrator.js"() {
12647
- init_migrator();
12648
- }
12649
- });
12650
-
12651
12660
  // packages/core/src/store/migration-manager.ts
12652
12661
  import { copyFileSync, existsSync as existsSync5 } from "node:fs";
12653
12662
  function tableExists(nativeDb, tableName) {
@@ -12808,10 +12817,27 @@ function reconcileJournal(nativeDb, migrationsFolder, existenceTable, logSubsyst
12808
12817
  });
12809
12818
  }
12810
12819
  if (alterMatches.length === 0) {
12820
+ const stripped = fullSql.replace(/--[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "").trim();
12821
+ if (stripped === "") {
12822
+ const log15 = getLogger(logSubsystem);
12823
+ log15.debug(
12824
+ { migration: migration.name },
12825
+ `Migration ${migration.name} is a comment-only baseline marker \u2014 marking applied on existing DB.`
12826
+ );
12827
+ insertJournalEntry(
12828
+ nativeDb,
12829
+ migration.hash,
12830
+ migration.folderMillis,
12831
+ migration.name ?? ""
12832
+ );
12833
+ continue;
12834
+ }
12811
12835
  const renameRe = /ALTER\s+TABLE\s+[`"]?\w+[`"]?\s+RENAME\s+TO\s+[`"]?\w+[`"]?/i;
12812
12836
  const createTableRe = /CREATE\s+TABLE/i;
12813
12837
  if (renameRe.test(fullSql) && createTableRe.test(fullSql)) {
12814
12838
  probeAndMarkApplied(nativeDb, migration, logSubsystem);
12839
+ } else if (createTableRe.test(fullSql)) {
12840
+ probeAndMarkApplied(nativeDb, migration, logSubsystem);
12815
12841
  }
12816
12842
  continue;
12817
12843
  }
@@ -12892,11 +12918,28 @@ function isDuplicateColumnError(err) {
12892
12918
  if (!(err instanceof Error)) return false;
12893
12919
  return /duplicate column name/i.test(err.message);
12894
12920
  }
12921
+ function isExecutableStatement(stmt) {
12922
+ if (stmt.trim() === "") return false;
12923
+ const stripped = stmt.replace(/--[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "").trim();
12924
+ return stripped !== "";
12925
+ }
12926
+ function sanitizeMigrationStatements(migrations) {
12927
+ return migrations.map((migration) => ({
12928
+ ...migration,
12929
+ sql: migration.sql.filter(isExecutableStatement)
12930
+ }));
12931
+ }
12932
+ function migrateSanitized(db, config2) {
12933
+ const raw = readMigrationFiles(config2);
12934
+ const sanitized = sanitizeMigrationStatements(raw);
12935
+ const dbInternal = db;
12936
+ dbInternal.dialect.migrate(sanitized, dbInternal.session, config2);
12937
+ }
12895
12938
  function migrateWithRetry(db, migrationsFolder, nativeDb, existenceTable, logSubsystem) {
12896
12939
  let duplicateColumnReconciled = false;
12897
12940
  for (let attempt = 1; attempt <= MAX_MIGRATION_RETRIES; attempt++) {
12898
12941
  try {
12899
- migrate(db, { migrationsFolder });
12942
+ migrateSanitized(db, { migrationsFolder });
12900
12943
  return;
12901
12944
  } catch (err) {
12902
12945
  if (isDuplicateColumnError(err) && !duplicateColumnReconciled && nativeDb !== void 0 && existenceTable !== void 0 && logSubsystem !== void 0) {
@@ -12936,7 +12979,6 @@ var init_migration_manager = __esm({
12936
12979
  "packages/core/src/store/migration-manager.ts"() {
12937
12980
  "use strict";
12938
12981
  init_migrator();
12939
- init_migrator2();
12940
12982
  init_logger();
12941
12983
  MAX_MIGRATION_RETRIES = 5;
12942
12984
  MIGRATION_RETRY_BASE_DELAY_MS = 100;
@@ -13042,12 +13084,12 @@ function detachAgentFromProject(db, agentId) {
13042
13084
  }
13043
13085
  function listProjectAgentRefs(db, opts) {
13044
13086
  const enabledOnly = opts?.enabledOnly ?? true;
13045
- const sql18 = enabledOnly ? `SELECT agent_id, attached_at, role, capabilities_override, last_used_at, enabled
13087
+ const sql19 = enabledOnly ? `SELECT agent_id, attached_at, role, capabilities_override, last_used_at, enabled
13046
13088
  FROM project_agent_refs WHERE enabled = 1
13047
13089
  ORDER BY attached_at DESC` : `SELECT agent_id, attached_at, role, capabilities_override, last_used_at, enabled
13048
13090
  FROM project_agent_refs
13049
13091
  ORDER BY attached_at DESC`;
13050
- const rows = db.prepare(sql18).all();
13092
+ const rows = db.prepare(sql19).all();
13051
13093
  return rows.map((r) => ({
13052
13094
  agentId: r.agent_id,
13053
13095
  attachedAt: r.attached_at,
@@ -13866,7 +13908,7 @@ function runNexusMigrations(nativeDb, db) {
13866
13908
  let lastError;
13867
13909
  for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
13868
13910
  try {
13869
- migrate(db, { migrationsFolder });
13911
+ migrateSanitized(db, { migrationsFolder });
13870
13912
  ensureColumns(
13871
13913
  nativeDb,
13872
13914
  "nexus_nodes",
@@ -13949,7 +13991,6 @@ var init_nexus_sqlite = __esm({
13949
13991
  "use strict";
13950
13992
  init_migrator();
13951
13993
  init_node_sqlite();
13952
- init_migrator2();
13953
13994
  init_paths();
13954
13995
  init_migration_manager();
13955
13996
  init_nexus_schema();
@@ -13963,6 +14004,277 @@ var init_nexus_sqlite = __esm({
13963
14004
  }
13964
14005
  });
13965
14006
 
14007
+ // packages/core/src/store/signaldock-schema.ts
14008
+ var signaldock_schema_exports = {};
14009
+ __export(signaldock_schema_exports, {
14010
+ accounts: () => accounts,
14011
+ agentCapabilities: () => agentCapabilities,
14012
+ agentConnections: () => agentConnections,
14013
+ agentSkills: () => agentSkills,
14014
+ agents: () => agents,
14015
+ capabilities: () => capabilities,
14016
+ claimCodes: () => claimCodes,
14017
+ orgAgentKeys: () => orgAgentKeys,
14018
+ organization: () => organization,
14019
+ sessions: () => sessions,
14020
+ skills: () => skills,
14021
+ users: () => users,
14022
+ verifications: () => verifications
14023
+ });
14024
+ import { sql as sql4 } from "drizzle-orm";
14025
+ var users, organization, agents, claimCodes, capabilities, skills, agentCapabilities, agentSkills, agentConnections, accounts, sessions, verifications, orgAgentKeys;
14026
+ var init_signaldock_schema = __esm({
14027
+ "packages/core/src/store/signaldock-schema.ts"() {
14028
+ "use strict";
14029
+ init_sqlite_core();
14030
+ users = sqliteTable(
14031
+ "users",
14032
+ {
14033
+ id: text2("id").primaryKey(),
14034
+ email: text2("email").notNull().unique(),
14035
+ passwordHash: text2("password_hash").notNull(),
14036
+ name: text2("name"),
14037
+ slug: text2("slug"),
14038
+ defaultAgentId: text2("default_agent_id"),
14039
+ username: text2("username"),
14040
+ displayUsername: text2("display_username"),
14041
+ emailVerified: integer2("email_verified").notNull().default(0),
14042
+ image: text2("image"),
14043
+ role: text2("role").notNull().default("user"),
14044
+ banned: integer2("banned").notNull().default(0),
14045
+ banReason: text2("ban_reason"),
14046
+ banExpires: text2("ban_expires"),
14047
+ twoFactorEnabled: integer2("two_factor_enabled").notNull().default(0),
14048
+ metadata: text2("metadata"),
14049
+ createdAt: integer2("created_at").notNull(),
14050
+ updatedAt: integer2("updated_at").notNull()
14051
+ },
14052
+ (table) => [index("idx_users_slug").on(table.slug)]
14053
+ );
14054
+ organization = sqliteTable(
14055
+ "organization",
14056
+ {
14057
+ id: text2("id").primaryKey().notNull(),
14058
+ name: text2("name").notNull(),
14059
+ slug: text2("slug"),
14060
+ logo: text2("logo"),
14061
+ metadata: text2("metadata"),
14062
+ ownerId: text2("owner_id"),
14063
+ createdAt: integer2("created_at").notNull().default(sql4`(strftime('%s','now'))`),
14064
+ updatedAt: integer2("updated_at").notNull().default(sql4`(strftime('%s','now'))`)
14065
+ },
14066
+ (table) => [index("idx_organization_slug").on(table.slug)]
14067
+ );
14068
+ agents = sqliteTable(
14069
+ "agents",
14070
+ {
14071
+ id: text2("id").primaryKey(),
14072
+ agentId: text2("agent_id").notNull().unique(),
14073
+ name: text2("name").notNull(),
14074
+ description: text2("description"),
14075
+ class: text2("class").notNull().default("custom"),
14076
+ privacyTier: text2("privacy_tier").notNull().default("public"),
14077
+ ownerId: text2("owner_id").references(() => users.id),
14078
+ endpoint: text2("endpoint"),
14079
+ webhookSecret: text2("webhook_secret"),
14080
+ capabilities: text2("capabilities").notNull().default("[]"),
14081
+ skills: text2("skills").notNull().default("[]"),
14082
+ avatar: text2("avatar"),
14083
+ messagesSent: integer2("messages_sent").notNull().default(0),
14084
+ messagesReceived: integer2("messages_received").notNull().default(0),
14085
+ conversationCount: integer2("conversation_count").notNull().default(0),
14086
+ friendCount: integer2("friend_count").notNull().default(0),
14087
+ status: text2("status").notNull().default("online"),
14088
+ lastSeen: integer2("last_seen"),
14089
+ paymentConfig: text2("payment_config"),
14090
+ apiKeyHash: text2("api_key_hash"),
14091
+ organizationId: text2("organization_id").references(() => organization.id, {
14092
+ onDelete: "set null"
14093
+ }),
14094
+ createdAt: integer2("created_at").notNull(),
14095
+ updatedAt: integer2("updated_at").notNull(),
14096
+ transportType: text2("transport_type").notNull().default("http"),
14097
+ apiKeyEncrypted: text2("api_key_encrypted"),
14098
+ apiBaseUrl: text2("api_base_url").notNull().default("https://api.signaldock.io"),
14099
+ classification: text2("classification"),
14100
+ transportConfig: text2("transport_config").notNull().default("{}"),
14101
+ isActive: integer2("is_active").notNull().default(1),
14102
+ lastUsedAt: integer2("last_used_at"),
14103
+ requiresReauth: integer2("requires_reauth").notNull().default(0),
14104
+ // T897 v3 columns
14105
+ /** Tier taxonomy from ADR-044: project, global, packaged, fallback. */
14106
+ tier: text2("tier").notNull().default("global"),
14107
+ /** Whether this agent is permitted to spawn sub-agents. */
14108
+ canSpawn: integer2("can_spawn").notNull().default(0),
14109
+ /** Orchestration level: 0=worker, 1=lead, 2=orchestrator. */
14110
+ orchLevel: integer2("orch_level").notNull().default(2),
14111
+ /** Agent ID this agent reports to (parent in hierarchy). */
14112
+ reportsTo: text2("reports_to"),
14113
+ /** Absolute path to the agent's .cant definition file. */
14114
+ cantPath: text2("cant_path"),
14115
+ /** SHA-256 checksum of the .cant file at install time. */
14116
+ cantSha256: text2("cant_sha256"),
14117
+ /** Installation provenance: seed, user, manual. */
14118
+ installedFrom: text2("installed_from"),
14119
+ /** ISO 8601 timestamp when the agent was installed. */
14120
+ installedAt: text2("installed_at")
14121
+ },
14122
+ (table) => [
14123
+ index("agents_owner_idx").on(table.ownerId),
14124
+ index("agents_class_idx").on(table.class),
14125
+ index("agents_privacy_idx").on(table.privacyTier),
14126
+ index("agents_org_idx").on(table.organizationId),
14127
+ index("idx_agents_transport_type").on(table.transportType),
14128
+ index("idx_agents_is_active").on(table.isActive),
14129
+ index("idx_agents_last_used").on(table.lastUsedAt),
14130
+ // Partial index: only rows where requires_reauth = 1.
14131
+ // NOTE: drizzle-orm sqlite-core does not directly support WHERE on index.
14132
+ // The partial index is created by the migration SQL but omitted from the
14133
+ // schema definition (drizzle does not generate WHERE clauses for indexes).
14134
+ // T897 indexes:
14135
+ index("idx_agents_tier").on(table.tier),
14136
+ index("idx_agents_cant_path").on(table.cantPath)
14137
+ ]
14138
+ );
14139
+ claimCodes = sqliteTable(
14140
+ "claim_codes",
14141
+ {
14142
+ id: text2("id").primaryKey(),
14143
+ agentId: text2("agent_id").notNull().references(() => agents.id),
14144
+ code: text2("code").notNull().unique(),
14145
+ expiresAt: integer2("expires_at").notNull(),
14146
+ usedAt: integer2("used_at"),
14147
+ usedBy: text2("used_by").references(() => users.id),
14148
+ createdAt: integer2("created_at").notNull()
14149
+ },
14150
+ (table) => [index("claim_codes_agent_idx").on(table.agentId)]
14151
+ );
14152
+ capabilities = sqliteTable("capabilities", {
14153
+ id: text2("id").primaryKey(),
14154
+ slug: text2("slug").notNull().unique(),
14155
+ name: text2("name").notNull(),
14156
+ description: text2("description").notNull(),
14157
+ category: text2("category").notNull(),
14158
+ createdAt: integer2("created_at").notNull()
14159
+ });
14160
+ skills = sqliteTable("skills", {
14161
+ id: text2("id").primaryKey(),
14162
+ slug: text2("slug").notNull().unique(),
14163
+ name: text2("name").notNull(),
14164
+ description: text2("description").notNull(),
14165
+ category: text2("category").notNull(),
14166
+ createdAt: integer2("created_at").notNull()
14167
+ });
14168
+ agentCapabilities = sqliteTable(
14169
+ "agent_capabilities",
14170
+ {
14171
+ agentId: text2("agent_id").notNull().references(() => agents.id),
14172
+ capabilityId: text2("capability_id").notNull().references(() => capabilities.id)
14173
+ },
14174
+ (table) => [primaryKey({ columns: [table.agentId, table.capabilityId] })]
14175
+ );
14176
+ agentSkills = sqliteTable(
14177
+ "agent_skills",
14178
+ {
14179
+ agentId: text2("agent_id").notNull().references(() => agents.id),
14180
+ skillId: text2("skill_id").notNull().references(() => skills.id),
14181
+ /** Skill attachment provenance: cant, manual, computed. */
14182
+ source: text2("source").notNull().default("manual"),
14183
+ /** ISO 8601 timestamp when the skill was attached to this agent. */
14184
+ attachedAt: text2("attached_at").notNull().default(sql4`(datetime('now'))`)
14185
+ },
14186
+ (table) => [
14187
+ primaryKey({ columns: [table.agentId, table.skillId] }),
14188
+ index("idx_agent_skills_source").on(table.source)
14189
+ ]
14190
+ );
14191
+ agentConnections = sqliteTable(
14192
+ "agent_connections",
14193
+ {
14194
+ id: text2("id").primaryKey().notNull(),
14195
+ agentId: text2("agent_id").notNull(),
14196
+ transportType: text2("transport_type").notNull().default("http"),
14197
+ connectionId: text2("connection_id"),
14198
+ connectedAt: integer2("connected_at").notNull(),
14199
+ lastHeartbeat: integer2("last_heartbeat").notNull(),
14200
+ connectionMetadata: text2("connection_metadata"),
14201
+ createdAt: integer2("created_at").notNull()
14202
+ },
14203
+ (table) => [
14204
+ index("idx_agent_connections_agent").on(table.agentId),
14205
+ index("idx_agent_connections_transport").on(table.transportType),
14206
+ index("idx_agent_connections_heartbeat").on(table.lastHeartbeat),
14207
+ unique().on(table.agentId, table.connectionId)
14208
+ ]
14209
+ );
14210
+ accounts = sqliteTable(
14211
+ "accounts",
14212
+ {
14213
+ id: text2("id").primaryKey().notNull(),
14214
+ userId: text2("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
14215
+ accountId: text2("account_id").notNull(),
14216
+ providerId: text2("provider_id").notNull(),
14217
+ accessToken: text2("access_token"),
14218
+ refreshToken: text2("refresh_token"),
14219
+ idToken: text2("id_token"),
14220
+ accessTokenExpiresAt: text2("access_token_expires_at"),
14221
+ refreshTokenExpiresAt: text2("refresh_token_expires_at"),
14222
+ scope: text2("scope"),
14223
+ password: text2("password"),
14224
+ createdAt: text2("created_at").notNull(),
14225
+ updatedAt: text2("updated_at").notNull()
14226
+ },
14227
+ (table) => [
14228
+ index("idx_accounts_user_id").on(table.userId),
14229
+ unique("idx_accounts_provider").on(table.providerId, table.accountId)
14230
+ ]
14231
+ );
14232
+ sessions = sqliteTable(
14233
+ "sessions",
14234
+ {
14235
+ id: text2("id").primaryKey().notNull(),
14236
+ userId: text2("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
14237
+ token: text2("token").notNull().unique(),
14238
+ ipAddress: text2("ip_address"),
14239
+ userAgent: text2("user_agent"),
14240
+ expiresAt: text2("expires_at").notNull(),
14241
+ activeOrganizationId: text2("active_organization_id"),
14242
+ impersonatedBy: text2("impersonated_by"),
14243
+ active: integer2("active").notNull().default(1),
14244
+ createdAt: text2("created_at").notNull(),
14245
+ updatedAt: text2("updated_at").notNull()
14246
+ },
14247
+ (table) => [index("idx_sessions_user_id").on(table.userId)]
14248
+ );
14249
+ verifications = sqliteTable(
14250
+ "verifications",
14251
+ {
14252
+ id: text2("id").primaryKey().notNull(),
14253
+ identifier: text2("identifier").notNull(),
14254
+ value: text2("value").notNull(),
14255
+ expiresAt: text2("expires_at").notNull(),
14256
+ createdAt: text2("created_at").notNull(),
14257
+ updatedAt: text2("updated_at").notNull()
14258
+ },
14259
+ (table) => [index("idx_verifications_identifier").on(table.identifier)]
14260
+ );
14261
+ orgAgentKeys = sqliteTable(
14262
+ "org_agent_keys",
14263
+ {
14264
+ id: text2("id").primaryKey().notNull(),
14265
+ organizationId: text2("organization_id").notNull().references(() => organization.id, { onDelete: "cascade" }),
14266
+ agentId: text2("agent_id").notNull().references(() => agents.id, { onDelete: "cascade" }),
14267
+ createdBy: text2("created_by").notNull(),
14268
+ createdAt: integer2("created_at").notNull()
14269
+ },
14270
+ (table) => [
14271
+ index("org_agent_keys_org_idx").on(table.organizationId),
14272
+ index("org_agent_keys_agent_idx").on(table.agentId)
14273
+ ]
14274
+ );
14275
+ }
14276
+ });
14277
+
13966
14278
  // packages/core/src/store/signaldock-sqlite.ts
13967
14279
  var signaldock_sqlite_exports = {};
13968
14280
  __export(signaldock_sqlite_exports, {
@@ -13976,11 +14288,12 @@ __export(signaldock_sqlite_exports, {
13976
14288
  ensureSignaldockDb: () => ensureSignaldockDb,
13977
14289
  getGlobalSignaldockDbPath: () => getGlobalSignaldockDbPath,
13978
14290
  getGlobalSignaldockNativeDb: () => getGlobalSignaldockNativeDb,
13979
- getSignaldockDbPath: () => getSignaldockDbPath
14291
+ getSignaldockDbPath: () => getSignaldockDbPath,
14292
+ resolveSignaldockMigrationsFolder: () => resolveSignaldockMigrationsFolder
13980
14293
  });
13981
14294
  import { existsSync as existsSync8, mkdirSync as mkdirSync3 } from "node:fs";
13982
- import { createRequire as createRequire2 } from "node:module";
13983
- import { join as join8 } from "node:path";
14295
+ import { dirname as dirname5, join as join8 } from "node:path";
14296
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
13984
14297
  function getGlobalSignaldockDbPath() {
13985
14298
  const cleoHome = getCleoHome();
13986
14299
  const dbPath = join8(cleoHome, GLOBAL_SIGNALDOCK_DB_FILENAME);
@@ -13999,54 +14312,23 @@ function getSignaldockDbPath(cwd) {
13999
14312
  }
14000
14313
  return getGlobalSignaldockDbPath();
14001
14314
  }
14002
- function readColumnSet(db, table) {
14003
- const rows = db.prepare(`PRAGMA table_info(${table})`).all();
14004
- return new Set(rows.map((r) => r.name));
14005
- }
14006
- function applyV3ColumnAlters(db) {
14007
- for (const [table, additions] of Object.entries(V3_COLUMN_ADDITIONS)) {
14008
- const existing = readColumnSet(db, table);
14009
- for (const { name: name2, ddl } of additions) {
14010
- if (!existing.has(name2)) {
14011
- db.exec(`ALTER TABLE ${table} ${ddl}`);
14012
- }
14013
- }
14315
+ function resolveSignaldockMigrationsFolder() {
14316
+ const __filename = fileURLToPath2(import.meta.url);
14317
+ let current = dirname5(__filename);
14318
+ const root = "/";
14319
+ for (let depth = 0; depth < 8 && current !== root; depth++) {
14320
+ const candidate = join8(current, "migrations", "drizzle-signaldock");
14321
+ if (existsSync8(candidate)) return candidate;
14322
+ current = dirname5(current);
14014
14323
  }
14324
+ const fallback = join8(dirname5(__filename), "..", "..", "migrations", "drizzle-signaldock");
14325
+ return fallback;
14015
14326
  }
14016
- function applyGlobalSignaldockSchema(db) {
14017
- db.exec(`
14018
- CREATE TABLE IF NOT EXISTS _signaldock_meta (
14019
- key TEXT PRIMARY KEY,
14020
- value TEXT NOT NULL,
14021
- updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
14022
- )
14023
- `);
14024
- db.exec(`
14025
- CREATE TABLE IF NOT EXISTS _signaldock_migrations (
14026
- name TEXT PRIMARY KEY,
14027
- applied_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
14028
- )
14029
- `);
14030
- for (const migration of GLOBAL_EMBEDDED_MIGRATIONS) {
14031
- const applied = db.prepare("SELECT name FROM _signaldock_migrations WHERE name = ?").get(migration.name);
14032
- if (applied) continue;
14033
- db.exec("BEGIN TRANSACTION");
14034
- try {
14035
- if (migration.preApply) {
14036
- migration.preApply(db);
14037
- }
14038
- db.exec(migration.sql);
14039
- db.prepare("INSERT INTO _signaldock_migrations (name) VALUES (?)").run(migration.name);
14040
- db.exec("COMMIT");
14041
- } catch (err) {
14042
- db.exec("ROLLBACK");
14043
- throw err;
14044
- }
14045
- }
14046
- db.exec(`
14047
- INSERT OR REPLACE INTO _signaldock_meta (key, value, updated_at)
14048
- VALUES ('schema_version', '${GLOBAL_SIGNALDOCK_SCHEMA_VERSION}', strftime('%s', 'now'))
14049
- `);
14327
+ function runSignaldockMigrations(nativeDb) {
14328
+ const migrationsFolder = resolveSignaldockMigrationsFolder();
14329
+ reconcileJournal(nativeDb, migrationsFolder, "agents", "signaldock");
14330
+ const db = drizzle({ client: nativeDb, schema: signaldock_schema_exports });
14331
+ migrateSanitized(db, { migrationsFolder });
14050
14332
  }
14051
14333
  async function ensureGlobalSignaldockDb() {
14052
14334
  const dbPath = getGlobalSignaldockDbPath();
@@ -14055,29 +14337,24 @@ async function ensureGlobalSignaldockDb() {
14055
14337
  if (!existsSync8(cleoHome)) {
14056
14338
  mkdirSync3(cleoHome, { recursive: true });
14057
14339
  }
14058
- const db = new DatabaseSyncClass(dbPath);
14340
+ const nativeDb = openNativeDatabase(dbPath);
14059
14341
  try {
14060
- db.exec("PRAGMA journal_mode = WAL");
14061
- db.exec("PRAGMA busy_timeout = 5000");
14062
- db.exec("PRAGMA synchronous = NORMAL");
14063
- db.exec("PRAGMA foreign_keys = ON");
14064
- db.exec("PRAGMA cache_size = -64000");
14065
14342
  const hasSchema = (() => {
14066
14343
  try {
14067
- const result = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='agents'").get();
14344
+ const result = nativeDb.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='agents'").get();
14068
14345
  return !!result;
14069
14346
  } catch {
14070
14347
  return false;
14071
14348
  }
14072
14349
  })();
14073
- applyGlobalSignaldockSchema(db);
14074
- _globalSignaldockNativeDb = db;
14350
+ runSignaldockMigrations(nativeDb);
14351
+ _globalSignaldockNativeDb = nativeDb;
14075
14352
  return {
14076
14353
  action: alreadyExists && hasSchema ? "exists" : "created",
14077
14354
  path: dbPath
14078
14355
  };
14079
14356
  } catch (err) {
14080
- db.close();
14357
+ nativeDb.close();
14081
14358
  _globalSignaldockNativeDb = null;
14082
14359
  throw err;
14083
14360
  }
@@ -14102,19 +14379,28 @@ async function checkGlobalSignaldockDbHealth() {
14102
14379
  foreignKeysEnabled: false
14103
14380
  };
14104
14381
  }
14105
- const db = new DatabaseSyncClass(dbPath);
14382
+ const nativeDb = openNativeDatabase(dbPath, { readonly: true });
14106
14383
  try {
14107
- const tables = db.prepare(
14384
+ const tables = nativeDb.prepare(
14108
14385
  "SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"
14109
14386
  ).get();
14110
- const journalMode = db.prepare("PRAGMA journal_mode").get();
14111
- const fkEnabled = db.prepare("PRAGMA foreign_keys").get();
14387
+ const journalMode = nativeDb.prepare("PRAGMA journal_mode").get();
14388
+ const fkEnabled = nativeDb.prepare("PRAGMA foreign_keys").get();
14112
14389
  let schemaVersion = null;
14113
14390
  try {
14114
- const meta3 = db.prepare("SELECT value FROM _signaldock_meta WHERE key = 'schema_version'").get();
14115
- schemaVersion = meta3?.value ?? null;
14391
+ const journalRow = nativeDb.prepare('SELECT COUNT(*) as cnt FROM "__drizzle_migrations"').get();
14392
+ if (journalRow && journalRow.cnt > 0) {
14393
+ schemaVersion = GLOBAL_SIGNALDOCK_SCHEMA_VERSION;
14394
+ }
14116
14395
  } catch {
14117
14396
  }
14397
+ if (!schemaVersion) {
14398
+ try {
14399
+ const meta3 = nativeDb.prepare("SELECT value FROM _signaldock_meta WHERE key = 'schema_version'").get();
14400
+ schemaVersion = meta3?.value ?? null;
14401
+ } catch {
14402
+ }
14403
+ }
14118
14404
  return {
14119
14405
  exists: true,
14120
14406
  path: dbPath,
@@ -14124,7 +14410,7 @@ async function checkGlobalSignaldockDbHealth() {
14124
14410
  foreignKeysEnabled: fkEnabled.foreign_keys === 1
14125
14411
  };
14126
14412
  } finally {
14127
- db.close();
14413
+ nativeDb.close();
14128
14414
  }
14129
14415
  }
14130
14416
  async function checkSignaldockDbHealth(cwd) {
@@ -14149,274 +14435,18 @@ function _resetGlobalSignaldockDb_TESTING_ONLY() {
14149
14435
  _globalSignaldockNativeDb = null;
14150
14436
  }
14151
14437
  }
14152
- var _require2, DatabaseSyncClass, GLOBAL_SIGNALDOCK_DB_FILENAME, GLOBAL_SIGNALDOCK_SCHEMA_VERSION, SIGNALDOCK_SCHEMA_VERSION, GLOBAL_EMBEDDED_MIGRATIONS, V3_COLUMN_ADDITIONS, _globalSignaldockNativeDb;
14438
+ var GLOBAL_SIGNALDOCK_DB_FILENAME, GLOBAL_SIGNALDOCK_SCHEMA_VERSION, SIGNALDOCK_SCHEMA_VERSION, _globalSignaldockNativeDb;
14153
14439
  var init_signaldock_sqlite = __esm({
14154
14440
  "packages/core/src/store/signaldock-sqlite.ts"() {
14155
14441
  "use strict";
14442
+ init_node_sqlite();
14156
14443
  init_paths();
14157
- _require2 = createRequire2(import.meta.url);
14158
- ({ DatabaseSync: DatabaseSyncClass } = _require2("node:sqlite"));
14444
+ init_migration_manager();
14445
+ init_signaldock_schema();
14446
+ init_sqlite2();
14159
14447
  GLOBAL_SIGNALDOCK_DB_FILENAME = "signaldock.db";
14160
14448
  GLOBAL_SIGNALDOCK_SCHEMA_VERSION = "2026.4.12";
14161
14449
  SIGNALDOCK_SCHEMA_VERSION = GLOBAL_SIGNALDOCK_SCHEMA_VERSION;
14162
- GLOBAL_EMBEDDED_MIGRATIONS = [
14163
- {
14164
- name: "2026-04-12-000000_initial_global_signaldock",
14165
- sql: `-- Global-tier signaldock.db initial migration (T310, ADR-037 \xA72.2).
14166
- -- Consolidated from pre-T310 incremental migrations. Global identity and
14167
- -- cloud-sync tables only. Project-local messaging state is in conduit.db.
14168
-
14169
- -- Cloud-sync: user accounts (zero rows in pure-local mode).
14170
- CREATE TABLE IF NOT EXISTS users (
14171
- id TEXT PRIMARY KEY,
14172
- email TEXT NOT NULL UNIQUE,
14173
- password_hash TEXT NOT NULL,
14174
- name TEXT,
14175
- slug TEXT,
14176
- default_agent_id TEXT,
14177
- username TEXT,
14178
- display_username TEXT,
14179
- email_verified INTEGER NOT NULL DEFAULT 0,
14180
- image TEXT,
14181
- role TEXT NOT NULL DEFAULT 'user',
14182
- banned INTEGER NOT NULL DEFAULT 0,
14183
- ban_reason TEXT,
14184
- ban_expires TEXT,
14185
- two_factor_enabled INTEGER NOT NULL DEFAULT 0,
14186
- metadata TEXT,
14187
- created_at INTEGER NOT NULL,
14188
- updated_at INTEGER NOT NULL
14189
- );
14190
- CREATE UNIQUE INDEX IF NOT EXISTS idx_users_slug ON users(slug);
14191
-
14192
- -- Cloud-sync: organization/team records.
14193
- CREATE TABLE IF NOT EXISTS organization (
14194
- id TEXT PRIMARY KEY NOT NULL,
14195
- name TEXT NOT NULL,
14196
- slug TEXT,
14197
- logo TEXT,
14198
- metadata TEXT,
14199
- owner_id TEXT,
14200
- created_at INTEGER NOT NULL DEFAULT (strftime('%s','now')),
14201
- updated_at INTEGER NOT NULL DEFAULT (strftime('%s','now'))
14202
- );
14203
- CREATE UNIQUE INDEX IF NOT EXISTS idx_organization_slug ON organization(slug);
14204
-
14205
- -- Global identity: canonical agent registry (cross-project).
14206
- -- api_key_encrypted uses KDF: HMAC-SHA256(machine-key || global-salt, agentId) \u2014 ADR-037 \xA75.
14207
- -- requires_reauth=1 is set during T310 migration for all pre-existing agents.
14208
- CREATE TABLE IF NOT EXISTS agents (
14209
- id TEXT PRIMARY KEY,
14210
- agent_id TEXT NOT NULL UNIQUE,
14211
- name TEXT NOT NULL,
14212
- description TEXT,
14213
- class TEXT NOT NULL DEFAULT 'custom',
14214
- privacy_tier TEXT NOT NULL DEFAULT 'public',
14215
- owner_id TEXT REFERENCES users(id),
14216
- endpoint TEXT,
14217
- webhook_secret TEXT,
14218
- capabilities TEXT NOT NULL DEFAULT '[]',
14219
- skills TEXT NOT NULL DEFAULT '[]',
14220
- avatar TEXT,
14221
- messages_sent INTEGER NOT NULL DEFAULT 0,
14222
- messages_received INTEGER NOT NULL DEFAULT 0,
14223
- conversation_count INTEGER NOT NULL DEFAULT 0,
14224
- friend_count INTEGER NOT NULL DEFAULT 0,
14225
- status TEXT NOT NULL DEFAULT 'online',
14226
- last_seen INTEGER,
14227
- payment_config TEXT,
14228
- api_key_hash TEXT,
14229
- organization_id TEXT REFERENCES organization(id) ON DELETE SET NULL,
14230
- created_at INTEGER NOT NULL,
14231
- updated_at INTEGER NOT NULL,
14232
- transport_type TEXT NOT NULL DEFAULT 'http',
14233
- api_key_encrypted TEXT,
14234
- api_base_url TEXT NOT NULL DEFAULT 'https://api.signaldock.io',
14235
- classification TEXT,
14236
- transport_config TEXT NOT NULL DEFAULT '{}',
14237
- is_active INTEGER NOT NULL DEFAULT 1,
14238
- last_used_at INTEGER,
14239
- requires_reauth INTEGER NOT NULL DEFAULT 0
14240
- );
14241
- CREATE UNIQUE INDEX IF NOT EXISTS agents_agent_id_idx ON agents(agent_id);
14242
- CREATE INDEX IF NOT EXISTS agents_owner_idx ON agents(owner_id);
14243
- CREATE INDEX IF NOT EXISTS agents_class_idx ON agents(class);
14244
- CREATE INDEX IF NOT EXISTS agents_privacy_idx ON agents(privacy_tier);
14245
- CREATE INDEX IF NOT EXISTS agents_org_idx ON agents(organization_id);
14246
- CREATE INDEX IF NOT EXISTS idx_agents_transport_type ON agents(transport_type);
14247
- CREATE INDEX IF NOT EXISTS idx_agents_is_active ON agents(is_active);
14248
- CREATE INDEX IF NOT EXISTS idx_agents_last_used ON agents(last_used_at);
14249
- CREATE INDEX IF NOT EXISTS idx_agents_reauth ON agents(requires_reauth) WHERE requires_reauth = 1;
14250
-
14251
- -- Cloud-sync: one-time agent claim tokens (api.signaldock.io provisioning).
14252
- CREATE TABLE IF NOT EXISTS claim_codes (
14253
- id TEXT PRIMARY KEY,
14254
- agent_id TEXT NOT NULL REFERENCES agents(id),
14255
- code TEXT NOT NULL UNIQUE,
14256
- expires_at INTEGER NOT NULL,
14257
- used_at INTEGER,
14258
- used_by TEXT REFERENCES users(id),
14259
- created_at INTEGER NOT NULL
14260
- );
14261
- CREATE UNIQUE INDEX IF NOT EXISTS claim_codes_code_idx ON claim_codes(code);
14262
- CREATE INDEX IF NOT EXISTS claim_codes_agent_idx ON claim_codes(agent_id);
14263
-
14264
- -- Identity catalog: pre-seeded capability slugs (19 entries).
14265
- CREATE TABLE IF NOT EXISTS capabilities (
14266
- id TEXT PRIMARY KEY,
14267
- slug TEXT NOT NULL UNIQUE,
14268
- name TEXT NOT NULL,
14269
- description TEXT NOT NULL,
14270
- category TEXT NOT NULL,
14271
- created_at INTEGER NOT NULL
14272
- );
14273
-
14274
- -- Identity catalog: pre-seeded skill slugs (36 entries).
14275
- CREATE TABLE IF NOT EXISTS skills (
14276
- id TEXT PRIMARY KEY,
14277
- slug TEXT NOT NULL UNIQUE,
14278
- name TEXT NOT NULL,
14279
- description TEXT NOT NULL,
14280
- category TEXT NOT NULL,
14281
- created_at INTEGER NOT NULL
14282
- );
14283
-
14284
- -- Junction: agent <-> capability catalog bindings.
14285
- CREATE TABLE IF NOT EXISTS agent_capabilities (
14286
- agent_id TEXT NOT NULL REFERENCES agents(id),
14287
- capability_id TEXT NOT NULL REFERENCES capabilities(id),
14288
- PRIMARY KEY (agent_id, capability_id)
14289
- );
14290
-
14291
- -- Junction: agent <-> skill catalog bindings.
14292
- CREATE TABLE IF NOT EXISTS agent_skills (
14293
- agent_id TEXT NOT NULL REFERENCES agents(id),
14294
- skill_id TEXT NOT NULL REFERENCES skills(id),
14295
- PRIMARY KEY (agent_id, skill_id)
14296
- );
14297
-
14298
- -- Live transport connection tracking (heartbeat state).
14299
- CREATE TABLE IF NOT EXISTS agent_connections (
14300
- id TEXT PRIMARY KEY NOT NULL,
14301
- agent_id TEXT NOT NULL,
14302
- transport_type TEXT NOT NULL DEFAULT 'http',
14303
- connection_id TEXT,
14304
- connected_at BIGINT NOT NULL,
14305
- last_heartbeat BIGINT NOT NULL,
14306
- connection_metadata TEXT,
14307
- created_at BIGINT NOT NULL,
14308
- FOREIGN KEY (agent_id) REFERENCES agents(agent_id) ON DELETE CASCADE,
14309
- UNIQUE(agent_id, connection_id)
14310
- );
14311
- CREATE INDEX IF NOT EXISTS idx_agent_connections_agent ON agent_connections(agent_id);
14312
- CREATE INDEX IF NOT EXISTS idx_agent_connections_transport ON agent_connections(transport_type);
14313
- CREATE INDEX IF NOT EXISTS idx_agent_connections_heartbeat ON agent_connections(last_heartbeat);
14314
-
14315
- -- Cloud-sync: OAuth/provider accounts.
14316
- CREATE TABLE IF NOT EXISTS accounts (
14317
- id TEXT PRIMARY KEY NOT NULL,
14318
- user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
14319
- account_id TEXT NOT NULL,
14320
- provider_id TEXT NOT NULL,
14321
- access_token TEXT,
14322
- refresh_token TEXT,
14323
- id_token TEXT,
14324
- access_token_expires_at TEXT,
14325
- refresh_token_expires_at TEXT,
14326
- scope TEXT,
14327
- password TEXT,
14328
- created_at TEXT NOT NULL,
14329
- updated_at TEXT NOT NULL
14330
- );
14331
- CREATE INDEX IF NOT EXISTS idx_accounts_user_id ON accounts(user_id);
14332
- CREATE UNIQUE INDEX IF NOT EXISTS idx_accounts_provider ON accounts(provider_id, account_id);
14333
-
14334
- -- Cloud-sync: authenticated sessions.
14335
- CREATE TABLE IF NOT EXISTS sessions (
14336
- id TEXT PRIMARY KEY NOT NULL,
14337
- user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
14338
- token TEXT NOT NULL UNIQUE,
14339
- ip_address TEXT,
14340
- user_agent TEXT,
14341
- expires_at TEXT NOT NULL,
14342
- active_organization_id TEXT,
14343
- impersonated_by TEXT,
14344
- active INTEGER NOT NULL DEFAULT 1,
14345
- created_at TEXT NOT NULL,
14346
- updated_at TEXT NOT NULL
14347
- );
14348
- CREATE UNIQUE INDEX IF NOT EXISTS idx_sessions_token ON sessions(token);
14349
- CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id);
14350
-
14351
- -- Cloud-sync: email/2FA verification tokens.
14352
- CREATE TABLE IF NOT EXISTS verifications (
14353
- id TEXT PRIMARY KEY NOT NULL,
14354
- identifier TEXT NOT NULL,
14355
- value TEXT NOT NULL,
14356
- expires_at TEXT NOT NULL,
14357
- created_at TEXT NOT NULL,
14358
- updated_at TEXT NOT NULL
14359
- );
14360
- CREATE INDEX IF NOT EXISTS idx_verifications_identifier ON verifications(identifier);
14361
-
14362
- -- Org-scoped agent API keys (cloud use; zero rows locally).
14363
- CREATE TABLE IF NOT EXISTS org_agent_keys (
14364
- id TEXT PRIMARY KEY NOT NULL,
14365
- organization_id TEXT NOT NULL REFERENCES organization(id) ON DELETE CASCADE,
14366
- agent_id TEXT NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
14367
- created_by TEXT NOT NULL,
14368
- created_at INTEGER NOT NULL
14369
- );
14370
- CREATE INDEX IF NOT EXISTS org_agent_keys_org_idx ON org_agent_keys(organization_id);
14371
- CREATE INDEX IF NOT EXISTS org_agent_keys_agent_idx ON org_agent_keys(agent_id);`
14372
- },
14373
- {
14374
- name: "2026-04-17-213120_T897_agent_registry_v3",
14375
- sql: `-- T889 / T897: agent_registry v3 \u2014 add tier, canSpawn, cantPath, checksum, orch fields.
14376
- -- Column additions are filtered at application time by applyV3ColumnAlters()
14377
- -- because SQLite does NOT support \`ADD COLUMN IF NOT EXISTS\`. Index creates
14378
- -- use IF NOT EXISTS natively.
14379
-
14380
- CREATE INDEX IF NOT EXISTS idx_agents_tier ON agents(tier);
14381
- CREATE INDEX IF NOT EXISTS idx_agents_cant_path ON agents(cant_path);
14382
- CREATE INDEX IF NOT EXISTS idx_agent_skills_source ON agent_skills(source);`,
14383
- preApply: applyV3ColumnAlters
14384
- }
14385
- ];
14386
- V3_COLUMN_ADDITIONS = {
14387
- agents: [
14388
- {
14389
- name: "tier",
14390
- ddl: "ADD COLUMN tier TEXT NOT NULL DEFAULT 'global' CHECK (tier IN ('project','global','packaged','fallback'))"
14391
- },
14392
- {
14393
- name: "can_spawn",
14394
- ddl: "ADD COLUMN can_spawn INTEGER NOT NULL DEFAULT 0 CHECK (can_spawn IN (0,1))"
14395
- },
14396
- {
14397
- name: "orch_level",
14398
- ddl: "ADD COLUMN orch_level INTEGER NOT NULL DEFAULT 2 CHECK (orch_level BETWEEN 0 AND 2)"
14399
- },
14400
- { name: "reports_to", ddl: "ADD COLUMN reports_to TEXT" },
14401
- { name: "cant_path", ddl: "ADD COLUMN cant_path TEXT" },
14402
- { name: "cant_sha256", ddl: "ADD COLUMN cant_sha256 TEXT" },
14403
- {
14404
- name: "installed_from",
14405
- ddl: "ADD COLUMN installed_from TEXT CHECK (installed_from IN ('seed','user','manual') OR installed_from IS NULL)"
14406
- },
14407
- { name: "installed_at", ddl: "ADD COLUMN installed_at TEXT" }
14408
- ],
14409
- agent_skills: [
14410
- {
14411
- name: "source",
14412
- ddl: "ADD COLUMN source TEXT NOT NULL DEFAULT 'manual' CHECK (source IN ('cant','manual','computed'))"
14413
- },
14414
- {
14415
- name: "attached_at",
14416
- ddl: "ADD COLUMN attached_at TEXT NOT NULL DEFAULT (datetime('now'))"
14417
- }
14418
- ]
14419
- };
14420
14450
  _globalSignaldockNativeDb = null;
14421
14451
  }
14422
14452
  });
@@ -14699,7 +14729,7 @@ var init_status_registry2 = __esm({
14699
14729
  });
14700
14730
 
14701
14731
  // packages/core/src/agents/agent-schema.ts
14702
- import { sql as sql4 } from "drizzle-orm";
14732
+ import { sql as sql5 } from "drizzle-orm";
14703
14733
  var AGENT_INSTANCE_STATUSES2, AGENT_TYPES2, agentInstances, agentErrorLog;
14704
14734
  var init_agent_schema = __esm({
14705
14735
  "packages/core/src/agents/agent-schema.ts"() {
@@ -14732,8 +14762,8 @@ var init_agent_schema = __esm({
14732
14762
  // Application-layer validation via agentExistsInSignaldockDb (T238).
14733
14763
  sessionId: text2("session_id"),
14734
14764
  taskId: text2("task_id"),
14735
- startedAt: text2("started_at").notNull().default(sql4`(datetime('now'))`),
14736
- lastHeartbeat: text2("last_heartbeat").notNull().default(sql4`(datetime('now'))`),
14765
+ startedAt: text2("started_at").notNull().default(sql5`(datetime('now'))`),
14766
+ lastHeartbeat: text2("last_heartbeat").notNull().default(sql5`(datetime('now'))`),
14737
14767
  stoppedAt: text2("stopped_at"),
14738
14768
  errorCount: integer2("error_count").notNull().default(0),
14739
14769
  totalTasksCompleted: integer2("total_tasks_completed").notNull().default(0),
@@ -14760,7 +14790,7 @@ var init_agent_schema = __esm({
14760
14790
  }).notNull(),
14761
14791
  message: text2("message").notNull(),
14762
14792
  stack: text2("stack"),
14763
- occurredAt: text2("occurred_at").notNull().default(sql4`(datetime('now'))`),
14793
+ occurredAt: text2("occurred_at").notNull().default(sql5`(datetime('now'))`),
14764
14794
  resolved: integer2("resolved", { mode: "boolean" }).notNull().default(false)
14765
14795
  },
14766
14796
  (table) => [
@@ -14773,7 +14803,7 @@ var init_agent_schema = __esm({
14773
14803
  });
14774
14804
 
14775
14805
  // packages/core/src/store/chain-schema.ts
14776
- import { sql as sql5 } from "drizzle-orm";
14806
+ import { sql as sql6 } from "drizzle-orm";
14777
14807
  var warpChains, warpChainInstances;
14778
14808
  var init_chain_schema = __esm({
14779
14809
  "packages/core/src/store/chain-schema.ts"() {
@@ -14789,8 +14819,8 @@ var init_chain_schema = __esm({
14789
14819
  definition: text2("definition").notNull(),
14790
14820
  // JSON-serialized WarpChain
14791
14821
  validated: integer2("validated", { mode: "boolean" }).default(false),
14792
- createdAt: text2("created_at").default(sql5`(datetime('now'))`),
14793
- updatedAt: text2("updated_at").default(sql5`(datetime('now'))`)
14822
+ createdAt: text2("created_at").default(sql6`(datetime('now'))`),
14823
+ updatedAt: text2("updated_at").default(sql6`(datetime('now'))`)
14794
14824
  },
14795
14825
  (table) => [index("idx_warp_chains_name").on(table.name)]
14796
14826
  );
@@ -14808,8 +14838,8 @@ var init_chain_schema = __esm({
14808
14838
  currentStage: text2("current_stage"),
14809
14839
  gateResults: text2("gate_results"),
14810
14840
  // JSON array of GateResult
14811
- createdAt: text2("created_at").default(sql5`(datetime('now'))`),
14812
- updatedAt: text2("updated_at").default(sql5`(datetime('now'))`)
14841
+ createdAt: text2("created_at").default(sql6`(datetime('now'))`),
14842
+ updatedAt: text2("updated_at").default(sql6`(datetime('now'))`)
14813
14843
  },
14814
14844
  (table) => [
14815
14845
  index("idx_warp_instances_chain").on(table.chainId),
@@ -14870,7 +14900,7 @@ __export(tasks_schema_exports, {
14870
14900
  pipelineManifest: () => pipelineManifest,
14871
14901
  releaseManifests: () => releaseManifests,
14872
14902
  schemaMeta: () => schemaMeta,
14873
- sessions: () => sessions,
14903
+ sessions: () => sessions2,
14874
14904
  statusRegistryTable: () => statusRegistryTable,
14875
14905
  taskDependencies: () => taskDependencies,
14876
14906
  taskRelations: () => taskRelations,
@@ -14880,8 +14910,8 @@ __export(tasks_schema_exports, {
14880
14910
  warpChainInstances: () => warpChainInstances,
14881
14911
  warpChains: () => warpChains
14882
14912
  });
14883
- import { sql as sql6 } from "drizzle-orm";
14884
- var TASK_PRIORITIES, TASK_TYPES, TASK_ROLES, TASK_SCOPES, TASK_SEVERITIES, TASK_SIZES, LIFECYCLE_STAGE_NAMES, LIFECYCLE_GATE_RESULTS, LIFECYCLE_EVIDENCE_TYPES, TOKEN_USAGE_METHODS, TOKEN_USAGE_CONFIDENCE, TOKEN_USAGE_TRANSPORTS, TASK_RELATION_TYPES, LIFECYCLE_TRANSITION_TYPES, EXTERNAL_LINK_TYPES, SYNC_DIRECTIONS, tasks, taskDependencies, taskRelations, sessions, taskWorkHistory, lifecyclePipelines, lifecycleStages, lifecycleGateResults, lifecycleEvidence, lifecycleTransitions, manifestEntries, pipelineManifest, releaseManifests, schemaMeta, auditLog, tokenUsage, architectureDecisions, adrTaskLinks, adrRelations, externalTaskLinks, BACKGROUND_JOB_STATUSES, backgroundJobs, statusRegistryTable, ATTACHMENT_OWNER_TYPES, attachments, attachmentRefs, experiments;
14913
+ import { sql as sql7 } from "drizzle-orm";
14914
+ var TASK_PRIORITIES, TASK_TYPES, TASK_ROLES, TASK_SCOPES, TASK_SEVERITIES, TASK_SIZES, LIFECYCLE_STAGE_NAMES, LIFECYCLE_GATE_RESULTS, LIFECYCLE_EVIDENCE_TYPES, TOKEN_USAGE_METHODS, TOKEN_USAGE_CONFIDENCE, TOKEN_USAGE_TRANSPORTS, TASK_RELATION_TYPES, LIFECYCLE_TRANSITION_TYPES, EXTERNAL_LINK_TYPES, SYNC_DIRECTIONS, tasks, taskDependencies, taskRelations, sessions2, taskWorkHistory, lifecyclePipelines, lifecycleStages, lifecycleGateResults, lifecycleEvidence, lifecycleTransitions, manifestEntries, pipelineManifest, releaseManifests, schemaMeta, auditLog, tokenUsage, architectureDecisions, adrTaskLinks, adrRelations, externalTaskLinks, BACKGROUND_JOB_STATUSES, backgroundJobs, statusRegistryTable, ATTACHMENT_OWNER_TYPES, attachments, attachmentRefs, experiments;
14885
14915
  var init_tasks_schema = __esm({
14886
14916
  "packages/core/src/store/tasks-schema.ts"() {
14887
14917
  "use strict";
@@ -14971,7 +15001,7 @@ var init_tasks_schema = __esm({
14971
15001
  epicLifecycle: text2("epic_lifecycle"),
14972
15002
  noAutoComplete: integer2("no_auto_complete", { mode: "boolean" }),
14973
15003
  // Timestamps
14974
- createdAt: text2("created_at").notNull().default(sql6`(datetime('now'))`),
15004
+ createdAt: text2("created_at").notNull().default(sql7`(datetime('now'))`),
14975
15005
  updatedAt: text2("updated_at"),
14976
15006
  completedAt: text2("completed_at"),
14977
15007
  cancelledAt: text2("cancelled_at"),
@@ -14985,7 +15015,7 @@ var init_tasks_schema = __esm({
14985
15015
  // Provenance tracking
14986
15016
  createdBy: text2("created_by"),
14987
15017
  modifiedBy: text2("modified_by"),
14988
- sessionId: text2("session_id").references(() => sessions.id, {
15018
+ sessionId: text2("session_id").references(() => sessions2.id, {
14989
15019
  onDelete: "set null"
14990
15020
  }),
14991
15021
  // T060: pipeline stage name (RCASD-IVTR+C). Stored as a plain stage name string.
@@ -15014,12 +15044,11 @@ var init_tasks_schema = __esm({
15014
15044
  // T944 role/scope axes
15015
15045
  index("idx_tasks_role").on(table.role),
15016
15046
  index("idx_tasks_scope").on(table.scope),
15017
- index("idx_tasks_role_status").on(table.role, table.status)
15018
- // T1126 — partial index for Tier-2 proposal rate-limiter.
15019
- // Drizzle ORM beta.22 does not support partial indexes in sqliteTable,
15020
- // so the canonical definition lives in the raw SQL migration:
15021
- // packages/cleo/migrations/drizzle-tasks/20260421000001_t1126-sentient-proposal-index
15022
- // Re-run `drizzle-kit generate` will NOT emit this index.
15047
+ index("idx_tasks_role_status").on(table.role, table.status),
15048
+ // T1126 / T1174 — partial index now schema-expressed (see .where() call below).
15049
+ // The corresponding migration is packages/core/migrations/drizzle-tasks/20260421000002_t1126-sentient-proposal-index/
15050
+ // which remains in place for existing DBs' journal continuity.
15051
+ index("idx_tasks_sentient_proposals_today").on(sql7`date(${table.createdAt})`).where(sql7`${table.labelsJson} LIKE '%sentient-tier2%'`)
15023
15052
  ]
15024
15053
  );
15025
15054
  taskDependencies = sqliteTable(
@@ -15048,7 +15077,7 @@ var init_tasks_schema = __esm({
15048
15077
  index("idx_task_relations_related_to").on(table.relatedTo)
15049
15078
  ]
15050
15079
  );
15051
- sessions = sqliteTable(
15080
+ sessions2 = sqliteTable(
15052
15081
  "sessions",
15053
15082
  {
15054
15083
  id: text2("id").primaryKey(),
@@ -15066,13 +15095,13 @@ var init_tasks_schema = __esm({
15066
15095
  tasksCompletedJson: text2("tasks_completed_json").default("[]"),
15067
15096
  tasksCreatedJson: text2("tasks_created_json").default("[]"),
15068
15097
  handoffJson: text2("handoff_json"),
15069
- startedAt: text2("started_at").notNull().default(sql6`(datetime('now'))`),
15098
+ startedAt: text2("started_at").notNull().default(sql7`(datetime('now'))`),
15070
15099
  endedAt: text2("ended_at"),
15071
15100
  // Session chain columns (T4959)
15072
- previousSessionId: text2("previous_session_id").references(() => sessions.id, {
15101
+ previousSessionId: text2("previous_session_id").references(() => sessions2.id, {
15073
15102
  onDelete: "set null"
15074
15103
  }),
15075
- nextSessionId: text2("next_session_id").references(() => sessions.id, {
15104
+ nextSessionId: text2("next_session_id").references(() => sessions2.id, {
15076
15105
  onDelete: "set null"
15077
15106
  }),
15078
15107
  agentIdentifier: text2("agent_identifier"),
@@ -15101,9 +15130,9 @@ var init_tasks_schema = __esm({
15101
15130
  "task_work_history",
15102
15131
  {
15103
15132
  id: integer2("id").primaryKey({ autoIncrement: true }),
15104
- sessionId: text2("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
15133
+ sessionId: text2("session_id").notNull().references(() => sessions2.id, { onDelete: "cascade" }),
15105
15134
  taskId: text2("task_id").notNull().references(() => tasks.id, { onDelete: "cascade" }),
15106
- setAt: text2("set_at").notNull().default(sql6`(datetime('now'))`),
15135
+ setAt: text2("set_at").notNull().default(sql7`(datetime('now'))`),
15107
15136
  clearedAt: text2("cleared_at")
15108
15137
  },
15109
15138
  (table) => [index("idx_work_history_session").on(table.sessionId)]
@@ -15117,9 +15146,9 @@ var init_tasks_schema = __esm({
15117
15146
  enum: LIFECYCLE_PIPELINE_STATUSES
15118
15147
  }).notNull().default("active"),
15119
15148
  currentStageId: text2("current_stage_id"),
15120
- startedAt: text2("started_at").notNull().default(sql6`(datetime('now'))`),
15149
+ startedAt: text2("started_at").notNull().default(sql7`(datetime('now'))`),
15121
15150
  completedAt: text2("completed_at"),
15122
- updatedAt: text2("updated_at").default(sql6`(datetime('now'))`),
15151
+ updatedAt: text2("updated_at").default(sql7`(datetime('now'))`),
15123
15152
  version: integer2("version").notNull().default(1)
15124
15153
  },
15125
15154
  (table) => [
@@ -15171,7 +15200,7 @@ var init_tasks_schema = __esm({
15171
15200
  result: text2("result", {
15172
15201
  enum: LIFECYCLE_GATE_RESULTS
15173
15202
  }).notNull(),
15174
- checkedAt: text2("checked_at").notNull().default(sql6`(datetime('now'))`),
15203
+ checkedAt: text2("checked_at").notNull().default(sql7`(datetime('now'))`),
15175
15204
  checkedBy: text2("checked_by").notNull(),
15176
15205
  details: text2("details"),
15177
15206
  reason: text2("reason")
@@ -15187,7 +15216,7 @@ var init_tasks_schema = __esm({
15187
15216
  type: text2("type", {
15188
15217
  enum: LIFECYCLE_EVIDENCE_TYPES
15189
15218
  }).notNull(),
15190
- recordedAt: text2("recorded_at").notNull().default(sql6`(datetime('now'))`),
15219
+ recordedAt: text2("recorded_at").notNull().default(sql7`(datetime('now'))`),
15191
15220
  recordedBy: text2("recorded_by"),
15192
15221
  description: text2("description")
15193
15222
  },
@@ -15204,7 +15233,7 @@ var init_tasks_schema = __esm({
15204
15233
  enum: LIFECYCLE_TRANSITION_TYPES
15205
15234
  }).notNull().default("automatic"),
15206
15235
  transitionedBy: text2("transitioned_by"),
15207
- createdAt: text2("created_at").notNull().default(sql6`(datetime('now'))`)
15236
+ createdAt: text2("created_at").notNull().default(sql7`(datetime('now'))`)
15208
15237
  },
15209
15238
  (table) => [index("idx_lifecycle_transitions_pipeline_id").on(table.pipelineId)]
15210
15239
  );
@@ -15225,7 +15254,7 @@ var init_tasks_schema = __esm({
15225
15254
  findingsJson: text2("findings_json").default("[]"),
15226
15255
  linkedTasksJson: text2("linked_tasks_json").default("[]"),
15227
15256
  createdBy: text2("created_by"),
15228
- createdAt: text2("created_at").notNull().default(sql6`(datetime('now'))`)
15257
+ createdAt: text2("created_at").notNull().default(sql7`(datetime('now'))`)
15229
15258
  },
15230
15259
  (table) => [
15231
15260
  index("idx_manifest_entries_pipeline_id").on(table.pipelineId),
@@ -15237,7 +15266,7 @@ var init_tasks_schema = __esm({
15237
15266
  "pipeline_manifest",
15238
15267
  {
15239
15268
  id: text2("id").primaryKey(),
15240
- sessionId: text2("session_id").references(() => sessions.id, { onDelete: "set null" }),
15269
+ sessionId: text2("session_id").references(() => sessions2.id, { onDelete: "set null" }),
15241
15270
  taskId: text2("task_id").references(() => tasks.id, { onDelete: "set null" }),
15242
15271
  epicId: text2("epic_id").references(() => tasks.id, { onDelete: "set null" }),
15243
15272
  type: text2("type").notNull(),
@@ -15295,7 +15324,7 @@ var init_tasks_schema = __esm({
15295
15324
  "audit_log",
15296
15325
  {
15297
15326
  id: text2("id").primaryKey(),
15298
- timestamp: text2("timestamp").notNull().default(sql6`(datetime('now'))`),
15327
+ timestamp: text2("timestamp").notNull().default(sql7`(datetime('now'))`),
15299
15328
  action: text2("action").notNull(),
15300
15329
  taskId: text2("task_id").notNull(),
15301
15330
  actor: text2("actor").notNull().default("system"),
@@ -15332,14 +15361,14 @@ var init_tasks_schema = __esm({
15332
15361
  "token_usage",
15333
15362
  {
15334
15363
  id: text2("id").primaryKey(),
15335
- createdAt: text2("created_at").notNull().default(sql6`(datetime('now'))`),
15364
+ createdAt: text2("created_at").notNull().default(sql7`(datetime('now'))`),
15336
15365
  provider: text2("provider").notNull().default("unknown"),
15337
15366
  model: text2("model"),
15338
15367
  transport: text2("transport", { enum: TOKEN_USAGE_TRANSPORTS }).notNull().default("unknown"),
15339
15368
  gateway: text2("gateway"),
15340
15369
  domain: text2("domain"),
15341
15370
  operation: text2("operation"),
15342
- sessionId: text2("session_id").references(() => sessions.id, { onDelete: "set null" }),
15371
+ sessionId: text2("session_id").references(() => sessions2.id, { onDelete: "set null" }),
15343
15372
  taskId: text2("task_id").references(() => tasks.id, { onDelete: "set null" }),
15344
15373
  requestId: text2("request_id"),
15345
15374
  inputChars: integer2("input_chars").notNull().default(0),
@@ -15384,7 +15413,7 @@ var init_tasks_schema = __esm({
15384
15413
  { onDelete: "set null" }
15385
15414
  ),
15386
15415
  content: text2("content").notNull(),
15387
- createdAt: text2("created_at").notNull().default(sql6`(datetime('now'))`),
15416
+ createdAt: text2("created_at").notNull().default(sql7`(datetime('now'))`),
15388
15417
  updatedAt: text2("updated_at"),
15389
15418
  // ADR-017 §5.3 extension columns
15390
15419
  date: text2("date").notNull().default(""),
@@ -15454,7 +15483,7 @@ var init_tasks_schema = __esm({
15454
15483
  /** Arbitrary provider-specific metadata (JSON). */
15455
15484
  metadataJson: text2("metadata_json").default("{}"),
15456
15485
  /** When the link was first established. */
15457
- linkedAt: text2("linked_at").notNull().default(sql6`(datetime('now'))`),
15486
+ linkedAt: text2("linked_at").notNull().default(sql7`(datetime('now'))`),
15458
15487
  /** When the external task was last synchronized. */
15459
15488
  lastSyncAt: text2("last_sync_at")
15460
15489
  },
@@ -15626,9 +15655,9 @@ __export(sqlite_exports, {
15626
15655
  schema: () => tasks_schema_exports
15627
15656
  });
15628
15657
  import { copyFileSync as copyFileSync4, existsSync as existsSync10, mkdirSync as mkdirSync5, renameSync, unlinkSync as unlinkSync2 } from "node:fs";
15629
- import { createRequire as createRequire3 } from "node:module";
15630
- import { dirname as dirname5, join as join10, resolve as resolve3, sep } from "node:path";
15631
- import { fileURLToPath as fileURLToPath2 } from "node:url";
15658
+ import { createRequire as createRequire2 } from "node:module";
15659
+ import { dirname as dirname6, join as join10, resolve as resolve3, sep } from "node:path";
15660
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
15632
15661
  import { eq as eq2 } from "drizzle-orm";
15633
15662
  function openNativeDatabase(path15, options) {
15634
15663
  const db = new DatabaseSync3(path15, {
@@ -15737,7 +15766,7 @@ async function getDb(cwd) {
15737
15766
  _initPromise = (async () => {
15738
15767
  const dbPath = requestedPath;
15739
15768
  _dbPath = dbPath;
15740
- mkdirSync5(dirname5(dbPath), { recursive: true });
15769
+ mkdirSync5(dirname6(dbPath), { recursive: true });
15741
15770
  const nativeDb = openNativeDatabase(dbPath);
15742
15771
  _nativeDb = nativeDb;
15743
15772
  const db = drizzle({ client: nativeDb, schema: tasks_schema_exports });
@@ -15787,8 +15816,8 @@ async function getDb(cwd) {
15787
15816
  }
15788
15817
  }
15789
15818
  function resolveMigrationsFolder() {
15790
- const __filename = fileURLToPath2(import.meta.url);
15791
- const __dirname = dirname5(__filename);
15819
+ const __filename = fileURLToPath3(import.meta.url);
15820
+ const __dirname = dirname6(__filename);
15792
15821
  const isBundled = __dirname.endsWith("/dist") || __dirname.endsWith("\\dist");
15793
15822
  const pkgRoot = isBundled ? join10(__dirname, "..") : join10(__dirname, "..", "..");
15794
15823
  return join10(pkgRoot, "migrations", "drizzle-tasks");
@@ -15858,7 +15887,7 @@ async function closeAllDatabases() {
15858
15887
  } catch {
15859
15888
  }
15860
15889
  }
15861
- var _require3, DatabaseSync3, DB_FILENAME2, SQLITE_SCHEMA_VERSION, SCHEMA_VERSION, _db, _nativeDb, _dbPath, _initPromise, _gitTrackingChecked, MIN_BACKUP_TASK_COUNT, REQUIRED_TASK_COLUMNS, REQUIRED_SESSION_COLUMNS;
15890
+ var _require2, DatabaseSync3, DB_FILENAME2, SQLITE_SCHEMA_VERSION, SCHEMA_VERSION, _db, _nativeDb, _dbPath, _initPromise, _gitTrackingChecked, MIN_BACKUP_TASK_COUNT, REQUIRED_TASK_COLUMNS, REQUIRED_SESSION_COLUMNS;
15862
15891
  var init_sqlite2 = __esm({
15863
15892
  "packages/core/src/store/sqlite.ts"() {
15864
15893
  "use strict";
@@ -15869,8 +15898,8 @@ var init_sqlite2 = __esm({
15869
15898
  init_sqlite_backup();
15870
15899
  init_tasks_schema();
15871
15900
  init_migration_manager();
15872
- _require3 = createRequire3(import.meta.url);
15873
- ({ DatabaseSync: DatabaseSync3 } = _require3("node:sqlite"));
15901
+ _require2 = createRequire2(import.meta.url);
15902
+ ({ DatabaseSync: DatabaseSync3 } = _require2("node:sqlite"));
15874
15903
  DB_FILENAME2 = "tasks.db";
15875
15904
  SQLITE_SCHEMA_VERSION = "2.0.0";
15876
15905
  SCHEMA_VERSION = SQLITE_SCHEMA_VERSION;
@@ -15908,11 +15937,11 @@ __export(atomic_exports, {
15908
15937
  });
15909
15938
  import { existsSync as existsSync11 } from "node:fs";
15910
15939
  import { mkdir, readFile, rename, unlink } from "node:fs/promises";
15911
- import { dirname as dirname6 } from "node:path";
15940
+ import { dirname as dirname7 } from "node:path";
15912
15941
  import writeFileAtomic from "write-file-atomic";
15913
15942
  async function atomicWrite(filePath, data, options) {
15914
15943
  try {
15915
- await mkdir(dirname6(filePath), { recursive: true });
15944
+ await mkdir(dirname7(filePath), { recursive: true });
15916
15945
  await writeFileAtomic(filePath, data, {
15917
15946
  encoding: options?.encoding ?? "utf8",
15918
15947
  mode: options?.mode
@@ -15989,8 +16018,8 @@ async function cleanupMigrationArtifacts(backupPath) {
15989
16018
  }
15990
16019
  async function validateSqliteDatabase(dbPath) {
15991
16020
  try {
15992
- const { createRequire: createRequire24 } = await import("node:module");
15993
- const _req = createRequire24(import.meta.url);
16021
+ const { createRequire: createRequire23 } = await import("node:module");
16022
+ const _req = createRequire23(import.meta.url);
15994
16023
  const { DatabaseSync: DatabaseSync11 } = _req("node:sqlite");
15995
16024
  const db = new DatabaseSync11(dbPath, { readOnly: true });
15996
16025
  const integrityRow = db.prepare("PRAGMA integrity_check").get();
@@ -16206,7 +16235,7 @@ __export(config_exports, {
16206
16235
  });
16207
16236
  import { existsSync as existsSync12 } from "node:fs";
16208
16237
  import { mkdir as mkdir3, writeFile } from "node:fs/promises";
16209
- import { dirname as dirname7 } from "node:path";
16238
+ import { dirname as dirname8 } from "node:path";
16210
16239
  function getNestedValue(obj, path15) {
16211
16240
  const parts = path15.split(".");
16212
16241
  let current = obj;
@@ -16329,7 +16358,7 @@ function parseConfigValue(value) {
16329
16358
  async function setConfigValue(key, value, cwd, opts) {
16330
16359
  const configPath = opts?.global ? getGlobalConfigPath() : getConfigPath(cwd);
16331
16360
  if (!existsSync12(configPath)) {
16332
- const dir = dirname7(configPath);
16361
+ const dir = dirname8(configPath);
16333
16362
  await mkdir3(dir, { recursive: true });
16334
16363
  await writeFile(configPath, "{}", "utf-8");
16335
16364
  }
@@ -16343,7 +16372,7 @@ async function applyStrictnessPreset(preset, cwd, opts) {
16343
16372
  const definition = STRICTNESS_PRESETS[preset];
16344
16373
  const configPath = opts?.global ? getGlobalConfigPath() : getConfigPath(cwd);
16345
16374
  if (!existsSync12(configPath)) {
16346
- const dir = dirname7(configPath);
16375
+ const dir = dirname8(configPath);
16347
16376
  await mkdir3(dir, { recursive: true });
16348
16377
  await writeFile(configPath, "{}", "utf-8");
16349
16378
  }
@@ -16646,15 +16675,15 @@ __export(memory_sqlite_exports, {
16646
16675
  resolveBrainMigrationsFolder: () => resolveBrainMigrationsFolder
16647
16676
  });
16648
16677
  import { mkdirSync as mkdirSync6 } from "node:fs";
16649
- import { createRequire as createRequire4 } from "node:module";
16650
- import { dirname as dirname8, join as join12 } from "node:path";
16651
- import { fileURLToPath as fileURLToPath3 } from "node:url";
16678
+ import { createRequire as createRequire3 } from "node:module";
16679
+ import { dirname as dirname9, join as join12 } from "node:path";
16680
+ import { fileURLToPath as fileURLToPath4 } from "node:url";
16652
16681
  function getBrainDbPath(cwd) {
16653
16682
  return join12(getCleoDirAbsolute(cwd), DB_FILENAME3);
16654
16683
  }
16655
16684
  function resolveBrainMigrationsFolder() {
16656
- const __filename = fileURLToPath3(import.meta.url);
16657
- const __dirname = dirname8(__filename);
16685
+ const __filename = fileURLToPath4(import.meta.url);
16686
+ const __dirname = dirname9(__filename);
16658
16687
  const isBundled = __dirname.endsWith("/dist") || __dirname.endsWith("\\dist");
16659
16688
  const pkgRoot = isBundled ? join12(__dirname, "..") : join12(__dirname, "..", "..");
16660
16689
  return join12(pkgRoot, "migrations", "drizzle-brain");
@@ -16869,7 +16898,7 @@ function runBrainMigrations(nativeDb, db) {
16869
16898
  }
16870
16899
  function loadBrainVecExtension(nativeDb) {
16871
16900
  try {
16872
- const sqliteVec = _require4("sqlite-vec");
16901
+ const sqliteVec = _require3("sqlite-vec");
16873
16902
  sqliteVec.load(nativeDb);
16874
16903
  return true;
16875
16904
  } catch {
@@ -16905,7 +16934,7 @@ async function getBrainDb(cwd) {
16905
16934
  _initPromise2 = (async () => {
16906
16935
  const dbPath = requestedPath;
16907
16936
  _dbPath2 = dbPath;
16908
- mkdirSync6(dirname8(dbPath), { recursive: true });
16937
+ mkdirSync6(dirname9(dbPath), { recursive: true });
16909
16938
  const nativeDb = openNativeDatabase(dbPath, { allowExtension: true });
16910
16939
  _nativeDb2 = nativeDb;
16911
16940
  _vecLoaded = loadBrainVecExtension(nativeDb);
@@ -16964,7 +16993,7 @@ function resetBrainDbState() {
16964
16993
  function getBrainNativeDb() {
16965
16994
  return _nativeDb2;
16966
16995
  }
16967
- var _require4, DB_FILENAME3, BRAIN_SCHEMA_VERSION, _db2, _nativeDb2, _dbPath2, _initPromise2, _vecLoaded;
16996
+ var _require3, DB_FILENAME3, BRAIN_SCHEMA_VERSION, _db2, _nativeDb2, _dbPath2, _initPromise2, _vecLoaded;
16968
16997
  var init_memory_sqlite = __esm({
16969
16998
  "packages/core/src/store/memory-sqlite.ts"() {
16970
16999
  "use strict";
@@ -16973,7 +17002,7 @@ var init_memory_sqlite = __esm({
16973
17002
  init_memory_schema();
16974
17003
  init_migration_manager();
16975
17004
  init_sqlite2();
16976
- _require4 = createRequire4(import.meta.url);
17005
+ _require3 = createRequire3(import.meta.url);
16977
17006
  DB_FILENAME3 = "brain.db";
16978
17007
  BRAIN_SCHEMA_VERSION = "1.0.0";
16979
17008
  _db2 = null;
@@ -17106,9 +17135,9 @@ async function reconcileOrphanedRefs(cwd) {
17106
17135
  return result;
17107
17136
  }
17108
17137
  async function sessionExistsInTasksDb(sessionId, tasksDb) {
17109
- const { sessions: sessions2 } = await Promise.resolve().then(() => (init_tasks_schema(), tasks_schema_exports));
17138
+ const { sessions: sessions3 } = await Promise.resolve().then(() => (init_tasks_schema(), tasks_schema_exports));
17110
17139
  const { eq: eqOp } = await import("drizzle-orm");
17111
- const result = await tasksDb.select({ id: sessions2.id }).from(sessions2).where(eqOp(sessions2.id, sessionId)).all();
17140
+ const result = await tasksDb.select({ id: sessions3.id }).from(sessions3).where(eqOp(sessions3.id, sessionId)).all();
17112
17141
  return result.length > 0;
17113
17142
  }
17114
17143
  var init_cross_db_cleanup = __esm({
@@ -17203,7 +17232,7 @@ async function upsertSession(db, session) {
17203
17232
  gradeMode: session.gradeMode ? 1 : null
17204
17233
  };
17205
17234
  const { id: _id, ...setFields } = values;
17206
- await db.insert(sessions).values(values).onConflictDoUpdate({ target: sessions.id, set: setFields }).run();
17235
+ await db.insert(sessions2).values(values).onConflictDoUpdate({ target: sessions2.id, set: setFields }).run();
17207
17236
  }
17208
17237
  async function updateDependencies(db, taskId, depends, validIds) {
17209
17238
  await db.delete(taskDependencies).where(eq4(taskDependencies.taskId, taskId)).run();
@@ -17304,7 +17333,7 @@ __export(registry_exports2, {
17304
17333
  updateAgentStatus: () => updateAgentStatus
17305
17334
  });
17306
17335
  import { randomBytes } from "node:crypto";
17307
- import { and as and3, eq as eq5, inArray as inArray3, lt as lt2, sql as sql7 } from "drizzle-orm";
17336
+ import { and as and3, eq as eq5, inArray as inArray3, lt as lt2, sql as sql8 } from "drizzle-orm";
17308
17337
  function generateAgentId() {
17309
17338
  const now2 = /* @__PURE__ */ new Date();
17310
17339
  const ts2 = now2.toISOString().replace(/[-:T]/g, "").substring(0, 14);
@@ -17386,7 +17415,7 @@ async function updateAgentStatus(id, opts, cwd) {
17386
17415
  }
17387
17416
  async function incrementTasksCompleted(id, cwd) {
17388
17417
  const db = await getDb(cwd);
17389
- await db.update(agentInstances).set({ totalTasksCompleted: sql7`${agentInstances.totalTasksCompleted} + 1` }).where(eq5(agentInstances.id, id));
17418
+ await db.update(agentInstances).set({ totalTasksCompleted: sql8`${agentInstances.totalTasksCompleted} + 1` }).where(eq5(agentInstances.id, id));
17390
17419
  }
17391
17420
  async function listAgentInstances(filters, cwd) {
17392
17421
  const db = await getDb(cwd);
@@ -17532,7 +17561,7 @@ __export(sqlite_data_accessor_exports, {
17532
17561
  createSqliteDataAccessor: () => createSqliteDataAccessor,
17533
17562
  setMetaValue: () => setMetaValue
17534
17563
  });
17535
- import { and as and4, eq as eq6, inArray as inArray4, isNull as isNull2, like as like2, ne as ne2, notInArray as notInArray2, or as or3, sql as sql8 } from "drizzle-orm";
17564
+ import { and as and4, eq as eq6, inArray as inArray4, isNull as isNull2, like as like2, ne as ne2, notInArray as notInArray2, or as or3, sql as sql9 } from "drizzle-orm";
17536
17565
  function generateAuditLogId() {
17537
17566
  const epoch = Math.floor(Date.now() / 1e3);
17538
17567
  const rand = Math.random().toString(36).slice(2, 8);
@@ -17629,21 +17658,21 @@ async function createSqliteDataAccessor(cwd) {
17629
17658
  // ---- loadSessions ----
17630
17659
  async loadSessions() {
17631
17660
  const db = await getDb(cwd);
17632
- const sessionRows = await db.select().from(sessions).all();
17661
+ const sessionRows = await db.select().from(sessions2).all();
17633
17662
  return sessionRows.map(rowToSession);
17634
17663
  },
17635
17664
  // ---- saveSessions ----
17636
- async saveSessions(sessions2) {
17665
+ async saveSessions(sessions3) {
17637
17666
  const db = await getDb(cwd);
17638
- const existingRows = await db.select({ id: sessions.id }).from(sessions).all();
17667
+ const existingRows = await db.select({ id: sessions2.id }).from(sessions2).all();
17639
17668
  const existingIds = new Set(existingRows.map((r) => r.id));
17640
- const incomingIds = new Set(sessions2.map((s3) => s3.id));
17669
+ const incomingIds = new Set(sessions3.map((s3) => s3.id));
17641
17670
  for (const eid of existingIds) {
17642
17671
  if (!incomingIds.has(eid)) {
17643
- await db.delete(sessions).where(eq6(sessions.id, eid)).run();
17672
+ await db.delete(sessions2).where(eq6(sessions2.id, eid)).run();
17644
17673
  }
17645
17674
  }
17646
- for (const session of sessions2) {
17675
+ for (const session of sessions3) {
17647
17676
  await upsertSession(db, session);
17648
17677
  }
17649
17678
  },
@@ -17722,7 +17751,7 @@ async function createSqliteDataAccessor(cwd) {
17722
17751
  },
17723
17752
  async getActiveSession() {
17724
17753
  const db = await getDb(cwd);
17725
- const rows = await db.select().from(sessions).where(eq6(sessions.status, "active")).orderBy(sql8`${sessions.startedAt} DESC`).limit(1).all();
17754
+ const rows = await db.select().from(sessions2).where(eq6(sessions2.status, "active")).orderBy(sql9`${sessions2.startedAt} DESC`).limit(1).all();
17726
17755
  if (rows.length === 0 || !rows[0]) return null;
17727
17756
  return rowToSession(rows[0]);
17728
17757
  },
@@ -17732,7 +17761,7 @@ async function createSqliteDataAccessor(cwd) {
17732
17761
  },
17733
17762
  async removeSingleSession(sessionId) {
17734
17763
  const db = await getDb(cwd);
17735
- await db.delete(sessions).where(eq6(sessions.id, sessionId)).run();
17764
+ await db.delete(sessions2).where(eq6(sessions2.id, sessionId)).run();
17736
17765
  void cleanupBrainRefsOnSessionDelete(sessionId, cwd);
17737
17766
  },
17738
17767
  // ---- Targeted query methods (Phase 2 modernization) ----
@@ -17777,24 +17806,24 @@ async function createSqliteDataAccessor(cwd) {
17777
17806
  conditions.push(like2(tasks.labelsJson, `%${JSON.stringify(filters.label)}%`));
17778
17807
  }
17779
17808
  const where = conditions.length > 0 ? and4(...conditions) : void 0;
17780
- const countResult = await db.select({ count: sql8`count(*)` }).from(tasks).where(where).get();
17809
+ const countResult = await db.select({ count: sql9`count(*)` }).from(tasks).where(where).get();
17781
17810
  const total = countResult?.count ?? 0;
17782
17811
  let orderClause;
17783
17812
  switch (filters.orderBy) {
17784
17813
  case "createdAt":
17785
- orderClause = sql8`${tasks.createdAt} ASC`;
17814
+ orderClause = sql9`${tasks.createdAt} ASC`;
17786
17815
  break;
17787
17816
  case "updatedAt":
17788
- orderClause = sql8`${tasks.updatedAt} DESC NULLS LAST`;
17817
+ orderClause = sql9`${tasks.updatedAt} DESC NULLS LAST`;
17789
17818
  break;
17790
17819
  case "priority": {
17791
- orderClause = sql8`CASE ${tasks.priority}
17820
+ orderClause = sql9`CASE ${tasks.priority}
17792
17821
  WHEN 'critical' THEN 0 WHEN 'high' THEN 1
17793
17822
  WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END ASC`;
17794
17823
  break;
17795
17824
  }
17796
17825
  default:
17797
- orderClause = sql8`${tasks.position} ASC, ${tasks.createdAt} ASC`;
17826
+ orderClause = sql9`${tasks.position} ASC, ${tasks.createdAt} ASC`;
17798
17827
  }
17799
17828
  let query = db.select().from(tasks).where(where).orderBy(orderClause);
17800
17829
  if (filters.limit !== void 0) {
@@ -17825,12 +17854,12 @@ async function createSqliteDataAccessor(cwd) {
17825
17854
  conditions.push(eq6(tasks.parentId, filters.parentId));
17826
17855
  }
17827
17856
  const where = conditions.length > 0 ? and4(...conditions) : void 0;
17828
- const result = await db.select({ count: sql8`count(*)` }).from(tasks).where(where).get();
17857
+ const result = await db.select({ count: sql9`count(*)` }).from(tasks).where(where).get();
17829
17858
  return result?.count ?? 0;
17830
17859
  },
17831
17860
  async getChildren(parentId) {
17832
17861
  const db = await getDb(cwd);
17833
- const rows = await db.select().from(tasks).where(and4(eq6(tasks.parentId, parentId), ne2(tasks.status, "archived"))).orderBy(sql8`${tasks.position} ASC, ${tasks.createdAt} ASC`).all();
17862
+ const rows = await db.select().from(tasks).where(and4(eq6(tasks.parentId, parentId), ne2(tasks.status, "archived"))).orderBy(sql9`${tasks.position} ASC, ${tasks.createdAt} ASC`).all();
17834
17863
  const tasks2 = rows.map(rowToTask);
17835
17864
  if (tasks2.length > 0) {
17836
17865
  const allIds = await getAllTaskIds();
@@ -17841,12 +17870,12 @@ async function createSqliteDataAccessor(cwd) {
17841
17870
  },
17842
17871
  async countChildren(parentId) {
17843
17872
  const db = await getDb(cwd);
17844
- const result = await db.select({ count: sql8`count(*)` }).from(tasks).where(and4(eq6(tasks.parentId, parentId), ne2(tasks.status, "archived"))).get();
17873
+ const result = await db.select({ count: sql9`count(*)` }).from(tasks).where(and4(eq6(tasks.parentId, parentId), ne2(tasks.status, "archived"))).get();
17845
17874
  return result?.count ?? 0;
17846
17875
  },
17847
17876
  async countActiveChildren(parentId) {
17848
17877
  const db = await getDb(cwd);
17849
- const result = await db.select({ count: sql8`count(*)` }).from(tasks).where(
17878
+ const result = await db.select({ count: sql9`count(*)` }).from(tasks).where(
17850
17879
  and4(
17851
17880
  eq6(tasks.parentId, parentId),
17852
17881
  notInArray2(tasks.status, [...TERMINAL_TASK_STATUSES])
@@ -21239,19 +21268,19 @@ async function updateCapacity(id, capacity, cwd) {
21239
21268
  return { ...existing, capacity: capacityStr };
21240
21269
  }
21241
21270
  async function getAvailableCapacity(cwd) {
21242
- const agents = await listAgentInstances({ status: ["active", "idle"] }, cwd);
21243
- return agents.reduce((sum, agent) => sum + parseCapacity(agent.capacity), 0);
21271
+ const agents2 = await listAgentInstances({ status: ["active", "idle"] }, cwd);
21272
+ return agents2.reduce((sum, agent) => sum + parseCapacity(agent.capacity), 0);
21244
21273
  }
21245
21274
  async function findLeastLoadedAgent(agentType, cwd) {
21246
21275
  const filters = agentType ? { status: ["active", "idle"], agentType } : { status: ["active", "idle"] };
21247
- const agents = await listAgentInstances(filters, cwd);
21248
- if (agents.length === 0) return null;
21249
- let best = agents[0];
21276
+ const agents2 = await listAgentInstances(filters, cwd);
21277
+ if (agents2.length === 0) return null;
21278
+ let best = agents2[0];
21250
21279
  let bestCapacity = parseCapacity(best.capacity);
21251
- for (let i = 1; i < agents.length; i++) {
21252
- const cap = parseCapacity(agents[i].capacity);
21280
+ for (let i = 1; i < agents2.length; i++) {
21281
+ const cap = parseCapacity(agents2[i].capacity);
21253
21282
  if (cap > bestCapacity) {
21254
- best = agents[i];
21283
+ best = agents2[i];
21255
21284
  bestCapacity = cap;
21256
21285
  }
21257
21286
  }
@@ -21262,9 +21291,9 @@ async function isOverloaded(threshold = 0.1, cwd) {
21262
21291
  return capacity < threshold;
21263
21292
  }
21264
21293
  async function getCapacitySummary(threshold = 0.1, cwd) {
21265
- const agents = await listAgentInstances({ status: ["active", "idle"] }, cwd);
21266
- const totalCapacity = agents.reduce((sum, a) => sum + parseCapacity(a.capacity), 0);
21267
- const activeAgentCount = agents.length;
21294
+ const agents2 = await listAgentInstances({ status: ["active", "idle"] }, cwd);
21295
+ const totalCapacity = agents2.reduce((sum, a) => sum + parseCapacity(a.capacity), 0);
21296
+ const activeAgentCount = agents2.length;
21268
21297
  return {
21269
21298
  totalCapacity,
21270
21299
  activeAgentCount,
@@ -21307,8 +21336,8 @@ async function checkAgentHealth2(agentId, thresholdMs = STALE_THRESHOLD_MS, cwd)
21307
21336
  return buildHealthStatus(agent, thresholdMs);
21308
21337
  }
21309
21338
  async function detectStaleAgents(thresholdMs = STALE_THRESHOLD_MS, cwd) {
21310
- const agents = await listAgentInstances({ status: ALIVE_STATUSES }, cwd);
21311
- return agents.map((a) => buildHealthStatus(a, thresholdMs)).filter((s3) => s3.stale).sort((a, b2) => b2.heartbeatAgeMs - a.heartbeatAgeMs);
21339
+ const agents2 = await listAgentInstances({ status: ALIVE_STATUSES }, cwd);
21340
+ return agents2.map((a) => buildHealthStatus(a, thresholdMs)).filter((s3) => s3.stale).sort((a, b2) => b2.heartbeatAgeMs - a.heartbeatAgeMs);
21312
21341
  }
21313
21342
  async function detectCrashedAgents(thresholdMs = STALE_THRESHOLD_MS, cwd) {
21314
21343
  const activeAgents = await listAgentInstances({ status: "active" }, cwd);
@@ -21740,9 +21769,9 @@ function checkProviderCapability(provider, capabilityPath) {
21740
21769
  }
21741
21770
  return providerSupports(provider, capabilityPath);
21742
21771
  }
21743
- function checkProviderCapabilities(providerId, capabilities) {
21772
+ function checkProviderCapabilities(providerId, capabilities2) {
21744
21773
  const results = {};
21745
- for (const cap of capabilities) {
21774
+ for (const cap of capabilities2) {
21746
21775
  results[cap] = providerSupportsById(providerId, cap);
21747
21776
  }
21748
21777
  return results;
@@ -21836,11 +21865,11 @@ var init_tree_sitter_languages = __esm({
21836
21865
 
21837
21866
  // packages/nexus/src/code/parser.ts
21838
21867
  import { readFileSync as readFileSync8 } from "node:fs";
21839
- import { createRequire as createRequire5 } from "node:module";
21868
+ import { createRequire as createRequire4 } from "node:module";
21840
21869
  import { relative } from "node:path";
21841
21870
  function tryRequire(id) {
21842
21871
  try {
21843
- return _require5(id);
21872
+ return _require4(id);
21844
21873
  } catch {
21845
21874
  return null;
21846
21875
  }
@@ -22032,12 +22061,12 @@ function batchParse(filePaths, projectRoot) {
22032
22061
  const totalSymbols = results.reduce((sum, r) => sum + r.symbols.length, 0);
22033
22062
  return { results, skipped, totalSymbols };
22034
22063
  }
22035
- var _require5, _ParserClass, _QueryClass, _parserInstance, _availabilityChecked, _available, _grammarCache, GRAMMAR_SPECS, QUERY_PATTERNS, _queryCache;
22064
+ var _require4, _ParserClass, _QueryClass, _parserInstance, _availabilityChecked, _available, _grammarCache, GRAMMAR_SPECS, QUERY_PATTERNS, _queryCache;
22036
22065
  var init_parser = __esm({
22037
22066
  "packages/nexus/src/code/parser.ts"() {
22038
22067
  "use strict";
22039
22068
  init_tree_sitter_languages();
22040
- _require5 = createRequire5(import.meta.url);
22069
+ _require4 = createRequire4(import.meta.url);
22041
22070
  _ParserClass = null;
22042
22071
  _QueryClass = null;
22043
22072
  _parserInstance = null;
@@ -24306,7 +24335,7 @@ var init_leiden = __esm({
24306
24335
  });
24307
24336
 
24308
24337
  // packages/nexus/src/pipeline/community-processor.ts
24309
- import { createRequire as createRequire6 } from "node:module";
24338
+ import { createRequire as createRequire5 } from "node:module";
24310
24339
  async function detectCommunities(graph) {
24311
24340
  let symbolCount = 0;
24312
24341
  for (const node of graph.nodes.values()) {
@@ -24536,13 +24565,13 @@ function calculateCohesion(memberIds, gGraph) {
24536
24565
  if (totalEdges === 0) return 1;
24537
24566
  return Math.min(1, internalEdges / totalEdges);
24538
24567
  }
24539
- var _require6, GraphCtor, CLUSTERING_EDGE_TYPES, SYMBOL_KINDS, MIN_CONFIDENCE_LARGE, LEIDEN_RESOLUTION;
24568
+ var _require5, GraphCtor, CLUSTERING_EDGE_TYPES, SYMBOL_KINDS, MIN_CONFIDENCE_LARGE, LEIDEN_RESOLUTION;
24540
24569
  var init_community_processor = __esm({
24541
24570
  "packages/nexus/src/pipeline/community-processor.ts"() {
24542
24571
  "use strict";
24543
24572
  init_leiden();
24544
- _require6 = createRequire6(import.meta.url);
24545
- GraphCtor = _require6("graphology");
24573
+ _require5 = createRequire5(import.meta.url);
24574
+ GraphCtor = _require5("graphology");
24546
24575
  CLUSTERING_EDGE_TYPES = /* @__PURE__ */ new Set(["calls", "extends", "implements"]);
24547
24576
  SYMBOL_KINDS = /* @__PURE__ */ new Set(["function", "method", "class", "interface"]);
24548
24577
  MIN_CONFIDENCE_LARGE = 0.5;
@@ -26835,10 +26864,10 @@ var init_rust_extractor = __esm({
26835
26864
  // packages/nexus/src/pipeline/workers/worker-pool.ts
26836
26865
  import fs5 from "node:fs";
26837
26866
  import os from "node:os";
26838
- import { fileURLToPath as fileURLToPath4 } from "node:url";
26867
+ import { fileURLToPath as fileURLToPath5 } from "node:url";
26839
26868
  import { Worker } from "node:worker_threads";
26840
26869
  function createWorkerPool(workerUrl, poolSize) {
26841
- const workerPath = fileURLToPath4(workerUrl);
26870
+ const workerPath = fileURLToPath5(workerUrl);
26842
26871
  if (!fs5.existsSync(workerPath)) {
26843
26872
  throw new Error(`Worker script not found: ${workerPath}`);
26844
26873
  }
@@ -26961,12 +26990,12 @@ var init_worker_pool = __esm({
26961
26990
 
26962
26991
  // packages/nexus/src/pipeline/parse-loop.ts
26963
26992
  import fs6 from "node:fs/promises";
26964
- import { fileURLToPath as fileURLToPath5 } from "node:url";
26965
- import { createRequire as createRequire7 } from "node:module";
26993
+ import { fileURLToPath as fileURLToPath6 } from "node:url";
26994
+ import { createRequire as createRequire6 } from "node:module";
26966
26995
  function getParserClass() {
26967
26996
  if (_available2 !== null) return _ParserClass2;
26968
26997
  try {
26969
- const mod = _require7("tree-sitter");
26998
+ const mod = _require6("tree-sitter");
26970
26999
  _ParserClass2 = mod;
26971
27000
  _available2 = true;
26972
27001
  } catch {
@@ -26989,7 +27018,7 @@ function loadGrammar2(langKey) {
26989
27018
  return null;
26990
27019
  }
26991
27020
  try {
26992
- const mod = _require7(spec.pkg);
27021
+ const mod = _require6(spec.pkg);
26993
27022
  const grammar = spec.prop ? mod[spec.prop] : mod;
26994
27023
  _grammarCache2.set(langKey, grammar ?? null);
26995
27024
  return grammar ?? null;
@@ -27058,7 +27087,7 @@ async function runParallelParseLoop(parseableFiles, graph, symbolTable, importCt
27058
27087
  let workerUrl;
27059
27088
  try {
27060
27089
  workerUrl = new URL("./workers/parse-worker.js", import.meta.url);
27061
- const workerPath = fileURLToPath5(workerUrl);
27090
+ const workerPath = fileURLToPath6(workerUrl);
27062
27091
  const { existsSync: existsSync148 } = await import("node:fs");
27063
27092
  if (!existsSync148(workerPath)) {
27064
27093
  return null;
@@ -27367,7 +27396,7 @@ async function runParseLoop(files, graph, symbolTable, importCtx, repoPath, opti
27367
27396
  );
27368
27397
  return { allHeritage, allCalls, barrelMap };
27369
27398
  }
27370
- var WORKER_FILE_THRESHOLD, WORKER_BYTE_THRESHOLD, _require7, _ParserClass2, _parserInstance2, _available2, _grammarCache2, GRAMMAR_SPECS2, TREE_SITTER_MAX_CHARS;
27399
+ var WORKER_FILE_THRESHOLD, WORKER_BYTE_THRESHOLD, _require6, _ParserClass2, _parserInstance2, _available2, _grammarCache2, GRAMMAR_SPECS2, TREE_SITTER_MAX_CHARS;
27371
27400
  var init_parse_loop = __esm({
27372
27401
  "packages/nexus/src/pipeline/parse-loop.ts"() {
27373
27402
  "use strict";
@@ -27380,7 +27409,7 @@ var init_parse_loop = __esm({
27380
27409
  init_worker_pool();
27381
27410
  WORKER_FILE_THRESHOLD = 15;
27382
27411
  WORKER_BYTE_THRESHOLD = 512 * 1024;
27383
- _require7 = createRequire7(import.meta.url);
27412
+ _require6 = createRequire6(import.meta.url);
27384
27413
  _ParserClass2 = null;
27385
27414
  _parserInstance2 = null;
27386
27415
  _available2 = null;
@@ -30084,8 +30113,8 @@ function checkFts5Available(nativeDb) {
30084
30113
  }
30085
30114
  return _fts5Available;
30086
30115
  }
30087
- function execDDL(nativeDb, sql18) {
30088
- nativeDb.prepare(sql18).run();
30116
+ function execDDL(nativeDb, sql19) {
30117
+ nativeDb.prepare(sql19).run();
30089
30118
  }
30090
30119
  function ensureFts5Tables(nativeDb) {
30091
30120
  if (!checkFts5Available(nativeDb)) {
@@ -30703,8 +30732,8 @@ import { execFile as execFile2 } from "node:child_process";
30703
30732
  import { promisify as promisify2 } from "node:util";
30704
30733
  async function computeHandoff(projectRoot, options) {
30705
30734
  const accessor = await getAccessor(projectRoot);
30706
- const sessions2 = await accessor.loadSessions();
30707
- const session = sessions2.find((s3) => s3.id === options.sessionId);
30735
+ const sessions3 = await accessor.loadSessions();
30736
+ const session = sessions3.find((s3) => s3.id === options.sessionId);
30708
30737
  if (!session) {
30709
30738
  throw new CleoError(31 /* SESSION_NOT_FOUND */, `Session '${options.sessionId}' not found`);
30710
30739
  }
@@ -30789,8 +30818,8 @@ function getScopeTaskIds(session, tasks2) {
30789
30818
  }
30790
30819
  async function persistHandoff(projectRoot, sessionId, handoff) {
30791
30820
  const accessor = await getAccessor(projectRoot);
30792
- const sessions2 = await accessor.loadSessions();
30793
- const session = sessions2.find((s3) => s3.id === sessionId);
30821
+ const sessions3 = await accessor.loadSessions();
30822
+ const session = sessions3.find((s3) => s3.id === sessionId);
30794
30823
  if (!session) {
30795
30824
  throw new CleoError(31 /* SESSION_NOT_FOUND */, `Session '${sessionId}' not found`);
30796
30825
  }
@@ -30799,8 +30828,8 @@ async function persistHandoff(projectRoot, sessionId, handoff) {
30799
30828
  }
30800
30829
  async function getHandoff(projectRoot, sessionId) {
30801
30830
  const accessor = await getAccessor(projectRoot);
30802
- const sessions2 = await accessor.loadSessions();
30803
- const session = sessions2.find((s3) => s3.id === sessionId);
30831
+ const sessions3 = await accessor.loadSessions();
30832
+ const session = sessions3.find((s3) => s3.id === sessionId);
30804
30833
  if (!session) return null;
30805
30834
  if (typeof session.handoffJson === "string") {
30806
30835
  try {
@@ -30812,8 +30841,8 @@ async function getHandoff(projectRoot, sessionId) {
30812
30841
  }
30813
30842
  async function getLastHandoff(projectRoot, scope) {
30814
30843
  const accessor = await getAccessor(projectRoot);
30815
- const sessions2 = await accessor.loadSessions();
30816
- let endedSessions = sessions2.filter((s3) => s3.status === "ended" && s3.endedAt);
30844
+ const sessions3 = await accessor.loadSessions();
30845
+ let endedSessions = sessions3.filter((s3) => s3.status === "ended" && s3.endedAt);
30817
30846
  if (scope) {
30818
30847
  endedSessions = endedSessions.filter((s3) => {
30819
30848
  if (scope.type === "global") {
@@ -30903,8 +30932,8 @@ async function captureGitState(projectRoot) {
30903
30932
  async function computeChainPosition(projectRoot, sessionId) {
30904
30933
  try {
30905
30934
  const accessor = await getAccessor(projectRoot);
30906
- const sessions2 = await accessor.loadSessions();
30907
- const sessionMap = new Map(sessions2.map((s3) => [s3.id, s3]));
30935
+ const sessions3 = await accessor.loadSessions();
30936
+ const sessionMap = new Map(sessions3.map((s3) => [s3.id, s3]));
30908
30937
  let current = sessionId;
30909
30938
  let position = 1;
30910
30939
  const visited = /* @__PURE__ */ new Set();
@@ -30967,8 +30996,8 @@ __export(memory_bridge_exports, {
30967
30996
  });
30968
30997
  import { existsSync as existsSync29, mkdirSync as mkdirSync8, readFileSync as readFileSync18, writeFileSync as writeFileSync2 } from "node:fs";
30969
30998
  import { join as join32 } from "node:path";
30970
- function typedAll2(db, sql18, ...params) {
30971
- return db.prepare(sql18).all(...params);
30999
+ function typedAll2(db, sql19, ...params) {
31000
+ return db.prepare(sql19).all(...params);
30972
31001
  }
30973
31002
  async function generateMemoryBridgeContent(projectRoot, config2) {
30974
31003
  const cfg = { ...DEFAULT_CONFIG2, ...config2 };
@@ -31269,7 +31298,7 @@ var init_memory_bridge = __esm({
31269
31298
 
31270
31299
  // packages/core/src/sessions/agent-session-adapter.ts
31271
31300
  import { appendFile, mkdir as mkdir4 } from "node:fs/promises";
31272
- import { dirname as dirname9, resolve as resolvePath } from "node:path";
31301
+ import { dirname as dirname10, resolve as resolvePath } from "node:path";
31273
31302
  function getReceiptsAuditPath(projectRoot) {
31274
31303
  return resolvePath(projectRoot, ".cleo", "audit", "receipts.jsonl");
31275
31304
  }
@@ -31360,7 +31389,7 @@ async function wrapWithAgentSession(options, fn2) {
31360
31389
  }
31361
31390
  async function persistReceipt(projectRoot, receipt) {
31362
31391
  const path15 = getReceiptsAuditPath(projectRoot);
31363
- await mkdir4(dirname9(path15), { recursive: true });
31392
+ await mkdir4(dirname10(path15), { recursive: true });
31364
31393
  const line2 = `${JSON.stringify(receipt)}
31365
31394
  `;
31366
31395
  await appendFile(path15, line2, { encoding: "utf-8" });
@@ -53755,7 +53784,7 @@ __export(graph_memory_bridge_exports, {
53755
53784
  queryMemoriesForCode: () => queryMemoriesForCode
53756
53785
  });
53757
53786
  import { existsSync as existsSync32 } from "node:fs";
53758
- import { createRequire as createRequire8 } from "node:module";
53787
+ import { createRequire as createRequire7 } from "node:module";
53759
53788
  function extractFilePaths(text3) {
53760
53789
  const paths = /* @__PURE__ */ new Set();
53761
53790
  for (const m2 of text3.matchAll(FILE_PATH_PATTERN)) {
@@ -54358,7 +54387,7 @@ async function linkConduitMessagesToSymbols(projectRoot) {
54358
54387
  }
54359
54388
  return result;
54360
54389
  }
54361
- var _require8, DatabaseSync4, FILE_PATH_PATTERN, SYMBOL_PATTERN, SYMBOL_STOP_WORDS2;
54390
+ var _require7, DatabaseSync4, FILE_PATH_PATTERN, SYMBOL_PATTERN, SYMBOL_STOP_WORDS2;
54362
54391
  var init_graph_memory_bridge = __esm({
54363
54392
  "packages/core/src/memory/graph-memory-bridge.ts"() {
54364
54393
  "use strict";
@@ -54367,8 +54396,8 @@ var init_graph_memory_bridge = __esm({
54367
54396
  init_memory_sqlite();
54368
54397
  init_nexus_sqlite();
54369
54398
  init_typed_query();
54370
- _require8 = createRequire8(import.meta.url);
54371
- ({ DatabaseSync: DatabaseSync4 } = _require8("node:sqlite"));
54399
+ _require7 = createRequire7(import.meta.url);
54400
+ ({ DatabaseSync: DatabaseSync4 } = _require7("node:sqlite"));
54372
54401
  FILE_PATH_PATTERN = /(?:^|\s|['"`(])([a-zA-Z0-9_\-./]+\.(?:ts|tsx|js|jsx|rs|go|py|mjs|cjs))(?:$|\s|['"`)])/g;
54373
54402
  SYMBOL_PATTERN = /\b([a-zA-Z_][a-zA-Z0-9_]*(?:[A-Z][a-zA-Z0-9_]*)+|[a-zA-Z_]{4,}[a-zA-Z0-9_]*)\b/g;
54374
54403
  SYMBOL_STOP_WORDS2 = /* @__PURE__ */ new Set([
@@ -58704,14 +58733,14 @@ var init_intelligence_hooks = __esm({
58704
58733
  // packages/core/src/conduit/local-transport.ts
58705
58734
  import { randomUUID as randomUUID2 } from "node:crypto";
58706
58735
  import { existsSync as existsSync33 } from "node:fs";
58707
- import { createRequire as createRequire9 } from "node:module";
58708
- var _require9, DatabaseSyncClass2, LocalTransport;
58736
+ import { createRequire as createRequire8 } from "node:module";
58737
+ var _require8, DatabaseSyncClass, LocalTransport;
58709
58738
  var init_local_transport = __esm({
58710
58739
  "packages/core/src/conduit/local-transport.ts"() {
58711
58740
  "use strict";
58712
58741
  init_conduit_sqlite();
58713
- _require9 = createRequire9(import.meta.url);
58714
- ({ DatabaseSync: DatabaseSyncClass2 } = _require9("node:sqlite"));
58742
+ _require8 = createRequire8(import.meta.url);
58743
+ ({ DatabaseSync: DatabaseSyncClass } = _require8("node:sqlite"));
58715
58744
  LocalTransport = class {
58716
58745
  name = "local";
58717
58746
  state = null;
@@ -58730,7 +58759,7 @@ var init_local_transport = __esm({
58730
58759
  if (!existsSync33(dbPath)) {
58731
58760
  throw new Error(`LocalTransport: conduit.db not found at ${dbPath}. Run: cleo init`);
58732
58761
  }
58733
- const db = new DatabaseSyncClass2(dbPath);
58762
+ const db = new DatabaseSyncClass(dbPath);
58734
58763
  db.exec("PRAGMA journal_mode = WAL");
58735
58764
  db.exec("PRAGMA busy_timeout = 5000");
58736
58765
  db.exec("PRAGMA foreign_keys = ON");
@@ -59556,7 +59585,7 @@ __export(pipeline_exports, {
59556
59585
  listPipelines: () => listPipelines,
59557
59586
  pipelineExists: () => pipelineExists
59558
59587
  });
59559
- import { and as and8, asc as asc3, desc as desc3, eq as eq11, sql as sql9 } from "drizzle-orm";
59588
+ import { and as and8, asc as asc3, desc as desc3, eq as eq11, sql as sql10 } from "drizzle-orm";
59560
59589
  async function initializePipeline(taskId, options = {}) {
59561
59590
  const db = await getDb();
59562
59591
  const now2 = /* @__PURE__ */ new Date();
@@ -59617,7 +59646,7 @@ async function getPipeline(taskId) {
59617
59646
  }
59618
59647
  const row = result[0];
59619
59648
  const isActive = row.status === "active";
59620
- const transitionResult = await db.select({ count: sql9`count(*)` }).from(lifecycleTransitions).where(eq11(lifecycleTransitions.pipelineId, row.id)).all();
59649
+ const transitionResult = await db.select({ count: sql10`count(*)` }).from(lifecycleTransitions).where(eq11(lifecycleTransitions.pipelineId, row.id)).all();
59621
59650
  const transitionCount = Number(transitionResult[0]?.count || 0);
59622
59651
  return {
59623
59652
  id: taskId,
@@ -59748,7 +59777,7 @@ async function listPipelines(options = {}) {
59748
59777
  return Promise.all(
59749
59778
  results.map(async (row) => {
59750
59779
  const isActive = row.status === "active";
59751
- const transitionResult = await db.select({ count: sql9`count(*)` }).from(lifecycleTransitions).where(eq11(lifecycleTransitions.pipelineId, row.id)).all();
59780
+ const transitionResult = await db.select({ count: sql10`count(*)` }).from(lifecycleTransitions).where(eq11(lifecycleTransitions.pipelineId, row.id)).all();
59752
59781
  const transitionCount = Number(transitionResult[0]?.count || 0);
59753
59782
  return {
59754
59783
  id: row.taskId,
@@ -59826,16 +59855,16 @@ async function cancelPipeline(taskId, reason) {
59826
59855
  }
59827
59856
  async function pipelineExists(taskId) {
59828
59857
  const db = await getDb();
59829
- const result = await db.select({ count: sql9`count(*)` }).from(lifecyclePipelines).where(eq11(lifecyclePipelines.taskId, taskId)).all();
59858
+ const result = await db.select({ count: sql10`count(*)` }).from(lifecyclePipelines).where(eq11(lifecyclePipelines.taskId, taskId)).all();
59830
59859
  return (result[0]?.count || 0) > 0;
59831
59860
  }
59832
59861
  async function getPipelineStatistics() {
59833
59862
  const db = await getDb();
59834
- const totalResult = await db.select({ count: sql9`count(*)` }).from(lifecyclePipelines).all();
59863
+ const totalResult = await db.select({ count: sql10`count(*)` }).from(lifecyclePipelines).all();
59835
59864
  const total = Number(totalResult[0]?.count || 0);
59836
59865
  const byStatusResult = await db.select({
59837
59866
  status: lifecyclePipelines.status,
59838
- count: sql9`count(*)`
59867
+ count: sql10`count(*)`
59839
59868
  }).from(lifecyclePipelines).groupBy(lifecyclePipelines.status).all();
59840
59869
  const byStatus = {
59841
59870
  active: 0,
@@ -59853,7 +59882,7 @@ async function getPipelineStatistics() {
59853
59882
  }
59854
59883
  const byStageResult = await db.select({
59855
59884
  stage: lifecyclePipelines.currentStageId,
59856
- count: sql9`count(*)`
59885
+ count: sql10`count(*)`
59857
59886
  }).from(lifecyclePipelines).groupBy(lifecyclePipelines.currentStageId).all();
59858
59887
  const byStage = {};
59859
59888
  for (const row of byStageResult) {
@@ -60191,15 +60220,15 @@ var init_briefing = __esm({
60191
60220
 
60192
60221
  // packages/core/src/sessions/find.ts
60193
60222
  async function findSessions(accessor, params) {
60194
- let sessions2 = await accessor.loadSessions();
60223
+ let sessions3 = await accessor.loadSessions();
60195
60224
  if (params?.status) {
60196
- sessions2 = sessions2.filter((s3) => s3.status === params.status);
60225
+ sessions3 = sessions3.filter((s3) => s3.status === params.status);
60197
60226
  }
60198
60227
  if (params?.scope) {
60199
60228
  const scopeParts = params.scope.split(":");
60200
60229
  const scopeType = scopeParts[0];
60201
60230
  const scopeId = scopeParts[1];
60202
- sessions2 = sessions2.filter((s3) => {
60231
+ sessions3 = sessions3.filter((s3) => {
60203
60232
  if (s3.scope.type !== scopeType) return false;
60204
60233
  if (scopeId && s3.scope.rootTaskId !== scopeId && s3.scope.epicId !== scopeId) return false;
60205
60234
  return true;
@@ -60207,15 +60236,15 @@ async function findSessions(accessor, params) {
60207
60236
  }
60208
60237
  if (params?.query) {
60209
60238
  const q2 = params.query.toLowerCase();
60210
- sessions2 = sessions2.filter(
60239
+ sessions3 = sessions3.filter(
60211
60240
  (s3) => s3.id.toLowerCase().includes(q2) || s3.name.toLowerCase().includes(q2)
60212
60241
  );
60213
60242
  }
60214
- sessions2.sort((a, b2) => new Date(b2.startedAt).getTime() - new Date(a.startedAt).getTime());
60243
+ sessions3.sort((a, b2) => new Date(b2.startedAt).getTime() - new Date(a.startedAt).getTime());
60215
60244
  if (params?.limit && params.limit > 0) {
60216
- sessions2 = sessions2.slice(0, params.limit);
60245
+ sessions3 = sessions3.slice(0, params.limit);
60217
60246
  }
60218
- return sessions2.map(toMinimal);
60247
+ return sessions3.map(toMinimal);
60219
60248
  }
60220
60249
  function toMinimal(s3) {
60221
60250
  return {
@@ -60237,12 +60266,12 @@ var init_find2 = __esm({
60237
60266
  // packages/core/src/sessions/session-archive.ts
60238
60267
  async function archiveSessions(projectRoot, olderThan) {
60239
60268
  const accessor = await getAccessor(projectRoot);
60240
- const sessions2 = await accessor.loadSessions();
60241
- if (!sessions2 || sessions2.length === 0) {
60269
+ const sessions3 = await accessor.loadSessions();
60270
+ if (!sessions3 || sessions3.length === 0) {
60242
60271
  return { archived: [], count: 0 };
60243
60272
  }
60244
60273
  const archivedIds = [];
60245
- for (const session of sessions2) {
60274
+ for (const session of sessions3) {
60246
60275
  if (session.status === "active") continue;
60247
60276
  if (session.status !== "ended" && session.status !== "orphaned" && session.status !== "suspended")
60248
60277
  continue;
@@ -60266,8 +60295,8 @@ var init_session_archive = __esm({
60266
60295
  // packages/core/src/sessions/session-cleanup.ts
60267
60296
  async function cleanupSessions(projectRoot) {
60268
60297
  const accessor = await getAccessor(projectRoot);
60269
- const sessions2 = await accessor.loadSessions();
60270
- if (sessions2.length === 0) {
60298
+ const sessions3 = await accessor.loadSessions();
60299
+ if (sessions3.length === 0) {
60271
60300
  return { removed: [], autoEnded: [], cleaned: false };
60272
60301
  }
60273
60302
  const removed = [];
@@ -60276,7 +60305,7 @@ async function cleanupSessions(projectRoot) {
60276
60305
  const autoEndDays = typeof configDays === "number" && configDays > 0 ? configDays : DEFAULT_AUTO_END_DAYS;
60277
60306
  const autoEndMs = autoEndDays * 24 * 60 * 60 * 1e3;
60278
60307
  const now2 = Date.now();
60279
- for (const session of sessions2) {
60308
+ for (const session of sessions3) {
60280
60309
  if (session.status === "active") {
60281
60310
  const sessionTime = new Date(session.startedAt).getTime();
60282
60311
  if (now2 - sessionTime > autoEndMs) {
@@ -60331,8 +60360,8 @@ async function getContextDrift(projectRoot, params) {
60331
60360
  };
60332
60361
  let session;
60333
60362
  if (params?.sessionId) {
60334
- const sessions2 = await accessor.loadSessions();
60335
- session = sessions2.find((s3) => s3.id === params.sessionId);
60363
+ const sessions3 = await accessor.loadSessions();
60364
+ session = sessions3.find((s3) => s3.id === params.sessionId);
60336
60365
  if (!session) {
60337
60366
  throw new CleoError(31 /* SESSION_NOT_FOUND */, `Session '${params.sessionId}' not found`);
60338
60367
  }
@@ -60471,8 +60500,8 @@ var init_session_memory_bridge = __esm({
60471
60500
  // packages/core/src/sessions/session-show.ts
60472
60501
  async function showSession(projectRoot, sessionId) {
60473
60502
  const accessor = await getAccessor(projectRoot);
60474
- const sessions2 = await accessor.loadSessions();
60475
- const session = sessions2.find((s3) => s3.id === sessionId);
60503
+ const sessions3 = await accessor.loadSessions();
60504
+ const session = sessions3.find((s3) => s3.id === sessionId);
60476
60505
  if (session) {
60477
60506
  return session;
60478
60507
  }
@@ -60555,8 +60584,8 @@ var init_session_stats = __esm({
60555
60584
  // packages/core/src/sessions/session-suspend.ts
60556
60585
  async function suspendSession(projectRoot, sessionId, reason) {
60557
60586
  const accessor = await getAccessor(projectRoot);
60558
- const sessions2 = await accessor.loadSessions();
60559
- const session = sessions2.find((s3) => s3.id === sessionId);
60587
+ const sessions3 = await accessor.loadSessions();
60588
+ const session = sessions3.find((s3) => s3.id === sessionId);
60560
60589
  if (!session) {
60561
60590
  throw new CleoError(31 /* SESSION_NOT_FOUND */, `Session '${sessionId}' not found`);
60562
60591
  }
@@ -60591,8 +60620,8 @@ var init_session_suspend = __esm({
60591
60620
  // packages/core/src/sessions/session-switch.ts
60592
60621
  async function switchSession(projectRoot, sessionId) {
60593
60622
  const accessor = await getAccessor(projectRoot);
60594
- const sessions2 = await accessor.loadSessions();
60595
- const targetSession = sessions2.find((s3) => s3.id === sessionId);
60623
+ const sessions3 = await accessor.loadSessions();
60624
+ const targetSession = sessions3.find((s3) => s3.id === sessionId);
60596
60625
  if (!targetSession) {
60597
60626
  throw new CleoError(31 /* SESSION_NOT_FOUND */, `Session '${sessionId}' not found`);
60598
60627
  }
@@ -60640,12 +60669,12 @@ var init_session_view = __esm({
60640
60669
  "use strict";
60641
60670
  SessionView2 = class _SessionView {
60642
60671
  _sessions;
60643
- constructor(sessions2) {
60644
- this._sessions = sessions2;
60672
+ constructor(sessions3) {
60673
+ this._sessions = sessions3;
60645
60674
  }
60646
60675
  /** Create a SessionView from a Session array. */
60647
- static from(sessions2) {
60648
- return new _SessionView(sessions2);
60676
+ static from(sessions3) {
60677
+ return new _SessionView(sessions3);
60649
60678
  }
60650
60679
  /** All sessions in the view (readonly). */
60651
60680
  get all() {
@@ -60870,14 +60899,14 @@ async function readSessions(cwd, accessor) {
60870
60899
  const acc = accessor ?? await getAccessor(cwd);
60871
60900
  return acc.loadSessions();
60872
60901
  }
60873
- async function saveSessions(sessions2, cwd, accessor) {
60902
+ async function saveSessions(sessions3, cwd, accessor) {
60874
60903
  const acc = accessor ?? await getAccessor(cwd);
60875
- await acc.saveSessions(sessions2);
60904
+ await acc.saveSessions(sessions3);
60876
60905
  }
60877
60906
  async function startSession(options, cwd, accessor) {
60878
60907
  const scope = parseScope2(options.scope);
60879
- const sessions2 = await readSessions(cwd, accessor);
60880
- const activeSessions = sessions2.filter((s3) => s3.status === "active");
60908
+ const sessions3 = await readSessions(cwd, accessor);
60909
+ const activeSessions = sessions3.filter((s3) => s3.status === "active");
60881
60910
  for (const active of activeSessions) {
60882
60911
  if (active.scope.type === scope.type && active.scope.epicId === scope.epicId) {
60883
60912
  throw new CleoError(
@@ -60922,7 +60951,7 @@ async function startSession(options, cwd, accessor) {
60922
60951
  process.env.CLEO_SESSION_ID = session.id;
60923
60952
  process.env.CLEO_SESSION_GRADE_ID = session.id;
60924
60953
  }
60925
- sessions2.push(session);
60954
+ sessions3.push(session);
60926
60955
  const acc = accessor ?? await getAccessor(cwd);
60927
60956
  await acc.upsertSingleSession(session);
60928
60957
  try {
@@ -60959,12 +60988,12 @@ async function startSession(options, cwd, accessor) {
60959
60988
  return session;
60960
60989
  }
60961
60990
  async function endSession(options = {}, cwd, accessor) {
60962
- const sessions2 = await readSessions(cwd, accessor);
60991
+ const sessions3 = await readSessions(cwd, accessor);
60963
60992
  let session;
60964
60993
  if (options.sessionId) {
60965
- session = sessions2.find((s3) => s3.id === options.sessionId);
60994
+ session = sessions3.find((s3) => s3.id === options.sessionId);
60966
60995
  } else {
60967
- session = sessions2.filter((s3) => s3.status === "active").sort(
60996
+ session = sessions3.filter((s3) => s3.status === "active").sort(
60968
60997
  (a, b2) => new Date(b2.startedAt).getTime() - new Date(a.startedAt).getTime()
60969
60998
  )[0];
60970
60999
  }
@@ -61023,15 +61052,15 @@ async function endSession(options = {}, cwd, accessor) {
61023
61052
  return session;
61024
61053
  }
61025
61054
  async function sessionStatus(cwd, accessor) {
61026
- const sessions2 = await readSessions(cwd, accessor);
61027
- const active = sessions2.filter((s3) => s3.status === "active").sort(
61055
+ const sessions3 = await readSessions(cwd, accessor);
61056
+ const active = sessions3.filter((s3) => s3.status === "active").sort(
61028
61057
  (a, b2) => new Date(b2.startedAt).getTime() - new Date(a.startedAt).getTime()
61029
61058
  )[0];
61030
61059
  return active ?? null;
61031
61060
  }
61032
61061
  async function resumeSession(sessionId, cwd, accessor) {
61033
- const sessions2 = await readSessions(cwd, accessor);
61034
- const session = sessions2.find((s3) => s3.id === sessionId);
61062
+ const sessions3 = await readSessions(cwd, accessor);
61063
+ const session = sessions3.find((s3) => s3.id === sessionId);
61035
61064
  if (!session) {
61036
61065
  throw new CleoError(31 /* SESSION_NOT_FOUND */, `Session not found: ${sessionId}`, {
61037
61066
  fix: "Use 'cleo session list' to see available sessions"
@@ -61051,28 +61080,28 @@ async function resumeSession(sessionId, cwd, accessor) {
61051
61080
  return session;
61052
61081
  }
61053
61082
  async function listSessions(options = {}, cwd, accessor) {
61054
- let sessions2 = await readSessions(cwd, accessor);
61083
+ let sessions3 = await readSessions(cwd, accessor);
61055
61084
  if (options.status) {
61056
- sessions2 = sessions2.filter((s3) => s3.status === options.status);
61085
+ sessions3 = sessions3.filter((s3) => s3.status === options.status);
61057
61086
  }
61058
- sessions2.sort(
61087
+ sessions3.sort(
61059
61088
  (a, b2) => new Date(b2.startedAt).getTime() - new Date(a.startedAt).getTime()
61060
61089
  );
61061
61090
  if (options.limit) {
61062
- sessions2 = sessions2.slice(0, options.limit);
61091
+ sessions3 = sessions3.slice(0, options.limit);
61063
61092
  }
61064
- for (const s3 of sessions2) {
61093
+ for (const s3 of sessions3) {
61065
61094
  Object.assign(s3, { _next: sessionListItemNext(s3.id) });
61066
61095
  }
61067
- return sessions2;
61096
+ return sessions3;
61068
61097
  }
61069
61098
  async function gcSessions(maxAgeHours = 24, cwd, accessor) {
61070
- let sessions2 = await readSessions(cwd, accessor);
61099
+ let sessions3 = await readSessions(cwd, accessor);
61071
61100
  const now2 = Date.now();
61072
61101
  const maxAgeMs = maxAgeHours * 60 * 60 * 1e3;
61073
61102
  const orphaned = [];
61074
61103
  const removed = [];
61075
- for (const session of sessions2) {
61104
+ for (const session of sessions3) {
61076
61105
  if (session.status === "active") {
61077
61106
  const age = now2 - new Date(session.startedAt).getTime();
61078
61107
  if (age > maxAgeMs) {
@@ -61083,7 +61112,7 @@ async function gcSessions(maxAgeHours = 24, cwd, accessor) {
61083
61112
  }
61084
61113
  }
61085
61114
  const thirtyDaysMs = 30 * 24 * 60 * 60 * 1e3;
61086
- sessions2 = sessions2.filter((s3) => {
61115
+ sessions3 = sessions3.filter((s3) => {
61087
61116
  if (s3.status === "active") return true;
61088
61117
  const endedAt = s3.endedAt ? new Date(s3.endedAt).getTime() : new Date(s3.startedAt).getTime();
61089
61118
  if (now2 - endedAt > thirtyDaysMs) {
@@ -61093,7 +61122,7 @@ async function gcSessions(maxAgeHours = 24, cwd, accessor) {
61093
61122
  return true;
61094
61123
  });
61095
61124
  const acc = accessor ?? await getAccessor(cwd);
61096
- for (const session of sessions2) {
61125
+ for (const session of sessions3) {
61097
61126
  if (orphaned.includes(session.id)) {
61098
61127
  await acc.upsertSingleSession(session);
61099
61128
  }
@@ -62699,7 +62728,7 @@ var init_codebase_map = __esm({
62699
62728
 
62700
62729
  // packages/core/src/compliance/store.ts
62701
62730
  import { appendFileSync as appendFileSync3, existsSync as existsSync35, mkdirSync as mkdirSync11, readFileSync as readFileSync20 } from "node:fs";
62702
- import { dirname as dirname10, join as join37 } from "node:path";
62731
+ import { dirname as dirname11, join as join37 } from "node:path";
62703
62732
  function getComplianceJsonlPath(projectRoot) {
62704
62733
  return join37(projectRoot, ".cleo", "metrics", "COMPLIANCE.jsonl");
62705
62734
  }
@@ -62935,13 +62964,13 @@ async function getSkillReliability(opts) {
62935
62964
  stats2.passRateSum += c.compliance_pass_rate ?? 0;
62936
62965
  stats2.violations += c.violation_count ?? 0;
62937
62966
  }
62938
- const skills = Object.entries(byAgent).map(([id, stats2]) => ({
62967
+ const skills2 = Object.entries(byAgent).map(([id, stats2]) => ({
62939
62968
  agentId: id,
62940
62969
  totalChecks: stats2.count,
62941
62970
  avgPassRate: stats2.count > 0 ? Math.round(stats2.passRateSum / stats2.count * 1e3) / 1e3 : 0,
62942
62971
  totalViolations: stats2.violations
62943
62972
  }));
62944
- return { skills, total: skills.length };
62973
+ return { skills: skills2, total: skills2.length };
62945
62974
  }
62946
62975
  async function getValueMetrics(days = 7, cwd) {
62947
62976
  const manifestPath = getManifestPath(cwd);
@@ -63636,7 +63665,7 @@ async function checkContextThreshold(opts) {
63636
63665
  }
63637
63666
  async function listContextSessions(cwd) {
63638
63667
  const cleoDir = getCleoDir2(cwd);
63639
- const sessions2 = [];
63668
+ const sessions3 = [];
63640
63669
  const statesDir = join39(cleoDir, "context-states");
63641
63670
  if (existsSync37(statesDir)) {
63642
63671
  for (const file2 of readdirSync16(statesDir)) {
@@ -63644,7 +63673,7 @@ async function listContextSessions(cwd) {
63644
63673
  const filePath = join39(statesDir, file2);
63645
63674
  try {
63646
63675
  const state = JSON.parse(readFileSync22(filePath, "utf-8"));
63647
- sessions2.push({
63676
+ sessions3.push({
63648
63677
  file: basename3(filePath),
63649
63678
  sessionId: state.sessionId ?? null,
63650
63679
  percentage: state.contextWindow?.percentage ?? 0,
@@ -63660,7 +63689,7 @@ async function listContextSessions(cwd) {
63660
63689
  if (existsSync37(singletonFile)) {
63661
63690
  try {
63662
63691
  const state = JSON.parse(readFileSync22(singletonFile, "utf-8"));
63663
- sessions2.push({
63692
+ sessions3.push({
63664
63693
  file: ".context-state.json",
63665
63694
  sessionId: state.sessionId ?? "global",
63666
63695
  percentage: state.contextWindow?.percentage ?? 0,
@@ -63670,7 +63699,7 @@ async function listContextSessions(cwd) {
63670
63699
  } catch {
63671
63700
  }
63672
63701
  }
63673
- return { sessions: sessions2, count: sessions2.length };
63702
+ return { sessions: sessions3, count: sessions3.length };
63674
63703
  }
63675
63704
  var init_context = __esm({
63676
63705
  "packages/core/src/context/index.ts"() {
@@ -63891,7 +63920,7 @@ var init_hooks = __esm({
63891
63920
 
63892
63921
  // packages/core/src/identity/cleo-identity.ts
63893
63922
  import { chmod, constants, mkdir as mkdir6, readFile as readFile6, writeFile as writeFile5 } from "node:fs/promises";
63894
- import { dirname as dirname11, join as join40 } from "node:path";
63923
+ import { dirname as dirname12, join as join40 } from "node:path";
63895
63924
  import { AgentIdentity, identityFromSeed, verifySignature } from "llmtxt/identity";
63896
63925
  function getCleoIdentityPath(cwd) {
63897
63926
  return join40(getCleoDirAbsolute(cwd), KEY_RELATIVE_PATH);
@@ -63952,7 +63981,7 @@ async function generateAndPersistIdentity(keyPath) {
63952
63981
  sk: bytesToHex(seed),
63953
63982
  pk: identity.pubkeyHex
63954
63983
  };
63955
- await mkdir6(dirname11(keyPath), { recursive: true });
63984
+ await mkdir6(dirname12(keyPath), { recursive: true });
63956
63985
  await writeFile5(keyPath, JSON.stringify(file2), { mode: 384 });
63957
63986
  try {
63958
63987
  await chmod(keyPath, constants.S_IRUSR | constants.S_IWUSR);
@@ -66425,10 +66454,10 @@ import { execFile as execFile3 } from "node:child_process";
66425
66454
  import { randomUUID as randomUUID3 } from "node:crypto";
66426
66455
  import { existsSync as existsSync41, constants as fsConstants3, readFileSync as readFileSync26, statSync as statSync8 } from "node:fs";
66427
66456
  import { access as access3, copyFile as copyFile2, mkdir as mkdir8, readdir as readdir3, readFile as readFile8, rm as rm2, writeFile as writeFile7 } from "node:fs/promises";
66428
- import { createRequire as createRequire10 } from "node:module";
66457
+ import { createRequire as createRequire9 } from "node:module";
66429
66458
  import { homedir as getHomedir } from "node:os";
66430
- import { dirname as dirname12, join as join44, resolve as resolve5 } from "node:path";
66431
- import { fileURLToPath as fileURLToPath6 } from "node:url";
66459
+ import { dirname as dirname13, join as join44, resolve as resolve5 } from "node:path";
66460
+ import { fileURLToPath as fileURLToPath7 } from "node:url";
66432
66461
  import { promisify as promisify3 } from "node:util";
66433
66462
  async function fileExists(path15) {
66434
66463
  try {
@@ -66462,8 +66491,8 @@ async function removeCleoFromRootGitignore(projectRoot) {
66462
66491
  return { removed: true };
66463
66492
  }
66464
66493
  function getPackageRoot() {
66465
- const thisFile = fileURLToPath6(import.meta.url);
66466
- return resolve5(dirname12(thisFile), "..");
66494
+ const thisFile = fileURLToPath7(import.meta.url);
66495
+ return resolve5(dirname13(thisFile), "..");
66467
66496
  }
66468
66497
  function getGitignoreContent() {
66469
66498
  try {
@@ -66681,7 +66710,7 @@ async function ensureProjectContext(projectRoot, opts) {
66681
66710
  const context = detectProjectType2(projectRoot);
66682
66711
  try {
66683
66712
  const schemaPath = join44(
66684
- dirname12(fileURLToPath6(import.meta.url)),
66713
+ dirname13(fileURLToPath7(import.meta.url)),
66685
66714
  "../schemas/project-context.schema.json"
66686
66715
  );
66687
66716
  if (existsSync41(schemaPath)) {
@@ -67291,7 +67320,7 @@ function resolveIdentitySourcePath() {
67291
67320
  );
67292
67321
  if (existsSync41(monorepoPath)) return monorepoPath;
67293
67322
  try {
67294
- const require2 = createRequire10(import.meta.url);
67323
+ const require2 = createRequire9(import.meta.url);
67295
67324
  const pkgJson = require2.resolve("@cleocode/cleo-os/package.json");
67296
67325
  const pkgDir = pkgJson.replace(/\/package\.json$/, "");
67297
67326
  const installedPath = join44(pkgDir, "starter-bundle", "CLEOOS-IDENTITY.md");
@@ -68602,7 +68631,7 @@ var init_stages = __esm({
68602
68631
  // packages/core/src/lifecycle/stage-artifacts.ts
68603
68632
  import { existsSync as existsSync44 } from "node:fs";
68604
68633
  import { readFile as readFile9, writeFile as writeFile8 } from "node:fs/promises";
68605
- import { dirname as dirname13, join as join47, relative as relative7 } from "node:path";
68634
+ import { dirname as dirname14, join as join47, relative as relative7 } from "node:path";
68606
68635
  function stageSlug(stage) {
68607
68636
  return stage.replace(/_/g, "-");
68608
68637
  }
@@ -68640,7 +68669,7 @@ function toWorkspaceRelative(path15, cwd) {
68640
68669
  function buildRelatedLinks(epicId, stage, absolutePath, cwd) {
68641
68670
  const prereqs = STAGE_PREREQUISITES[stage] ?? [];
68642
68671
  const related = [{ type: "task", id: epicId }];
68643
- const artifactDir = dirname13(absolutePath);
68672
+ const artifactDir = dirname14(absolutePath);
68644
68673
  for (const prereq of prereqs) {
68645
68674
  const prereqDir = getStagePath(epicId, prereq, cwd);
68646
68675
  const prereqFile = join47(prereqDir, `${epicId}-${stageSlug(prereq)}.md`);
@@ -68898,7 +68927,7 @@ function discoverSkillsInDir(dir) {
68898
68927
  if (!existsSync45(dir)) {
68899
68928
  return [];
68900
68929
  }
68901
- const skills = [];
68930
+ const skills2 = [];
68902
68931
  try {
68903
68932
  const entries = readdirSync20(dir);
68904
68933
  for (const entry of entries) {
@@ -68908,7 +68937,7 @@ function discoverSkillsInDir(dir) {
68908
68937
  if (statSync9(entryPath).isDirectory()) {
68909
68938
  const skill = discoverSkill(entryPath);
68910
68939
  if (skill) {
68911
- skills.push(skill);
68940
+ skills2.push(skill);
68912
68941
  }
68913
68942
  }
68914
68943
  } catch {
@@ -68916,22 +68945,22 @@ function discoverSkillsInDir(dir) {
68916
68945
  }
68917
68946
  } catch {
68918
68947
  }
68919
- return skills;
68948
+ return skills2;
68920
68949
  }
68921
68950
  function discoverAllSkills(cwd) {
68922
68951
  const searchPaths = getSkillSearchPaths(cwd);
68923
68952
  const seen = /* @__PURE__ */ new Set();
68924
- const skills = [];
68953
+ const skills2 = [];
68925
68954
  for (const sp of searchPaths) {
68926
68955
  const found = discoverSkillsInDir(sp.path);
68927
68956
  for (const skill of found) {
68928
68957
  if (!seen.has(skill.dirName)) {
68929
68958
  seen.add(skill.dirName);
68930
- skills.push(skill);
68959
+ skills2.push(skill);
68931
68960
  }
68932
68961
  }
68933
68962
  }
68934
- return skills;
68963
+ return skills2;
68935
68964
  }
68936
68965
  function findSkill(name2, cwd) {
68937
68966
  const { canonical } = mapSkillName(name2);
@@ -68965,15 +68994,15 @@ function toSkillSummary(skill) {
68965
68994
  }
68966
68995
  function generateManifest(cwd) {
68967
68996
  const searchPaths = getSkillSearchPaths(cwd);
68968
- const skills = discoverAllSkills(cwd);
68997
+ const skills2 = discoverAllSkills(cwd);
68969
68998
  return {
68970
68999
  _meta: {
68971
69000
  generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
68972
69001
  ttlSeconds: 300,
68973
- skillCount: skills.length,
69002
+ skillCount: skills2.length,
68974
69003
  searchPaths: searchPaths.map((p2) => p2.path)
68975
69004
  },
68976
- skills: skills.map(toSkillSummary)
69005
+ skills: skills2.map(toSkillSummary)
68977
69006
  };
68978
69007
  }
68979
69008
  function resolveTemplatePath(name2, cwd) {
@@ -69175,11 +69204,11 @@ function getCatalogMatrix() {
69175
69204
  return null;
69176
69205
  }
69177
69206
  }
69178
- function dispatchByLabels(task, skills) {
69207
+ function dispatchByLabels(task, skills2) {
69179
69208
  const labels = task.labels ?? [];
69180
69209
  if (labels.length === 0) return null;
69181
69210
  const labelSet = new Set(labels.map((l) => l.toLowerCase()));
69182
- for (const skill of skills) {
69211
+ for (const skill of skills2) {
69183
69212
  const tags = skill.frontmatter.tags ?? [];
69184
69213
  for (const tag of tags) {
69185
69214
  if (labelSet.has(tag.toLowerCase())) {
@@ -69251,8 +69280,8 @@ function dispatchByKeyword(task) {
69251
69280
  return null;
69252
69281
  }
69253
69282
  function autoDispatch(task, cwd) {
69254
- const skills = discoverAllSkills(cwd);
69255
- const labelResult = dispatchByLabels(task, skills);
69283
+ const skills2 = discoverAllSkills(cwd);
69284
+ const labelResult = dispatchByLabels(task, skills2);
69256
69285
  if (labelResult) return labelResult;
69257
69286
  const catalogResult = dispatchByCatalog(task);
69258
69287
  if (catalogResult) return catalogResult;
@@ -73150,7 +73179,7 @@ function getSkillReliability2(options = {}, cwd) {
73150
73179
  if (!bySkill.has(skill)) bySkill.set(skill, []);
73151
73180
  bySkill.get(skill).push(e);
73152
73181
  }
73153
- const skills = Array.from(bySkill.entries()).map(([skill, group]) => {
73182
+ const skills2 = Array.from(bySkill.entries()).map(([skill, group]) => {
73154
73183
  const avgPassRate = group.reduce((s3, e) => s3 + (e.compliance?.compliance_pass_rate ?? 0), 0) / group.length;
73155
73184
  const avgAdherence = group.reduce((s3, e) => s3 + (e.compliance?.rule_adherence_score ?? 0), 0) / group.length;
73156
73185
  const totalViolations = group.reduce((s3, e) => s3 + (e.compliance?.violation_count ?? 0), 0);
@@ -73164,11 +73193,11 @@ function getSkillReliability2(options = {}, cwd) {
73164
73193
  reliability
73165
73194
  };
73166
73195
  }).sort((a, b2) => b2.reliability - a.reliability);
73167
- const totalSkills = skills.length;
73168
- const avgReliability = totalSkills > 0 ? skills.reduce((s3, sk) => s3 + sk.reliability, 0) / totalSkills : 0;
73196
+ const totalSkills = skills2.length;
73197
+ const avgReliability = totalSkills > 0 ? skills2.reduce((s3, sk) => s3 + sk.reliability, 0) / totalSkills : 0;
73169
73198
  return {
73170
73199
  success: true,
73171
- result: { skills, summary: { totalSkills, avgReliability } }
73200
+ result: { skills: skills2, summary: { totalSkills, avgReliability } }
73172
73201
  };
73173
73202
  }
73174
73203
  async function logSessionMetrics(metricsJson, cwd) {
@@ -73326,7 +73355,7 @@ var init_enums = __esm({
73326
73355
  // packages/core/src/metrics/token-estimation.ts
73327
73356
  import { existsSync as existsSync55, readFileSync as readFileSync36, statSync as statSync12 } from "node:fs";
73328
73357
  import { appendFile as appendFile3, mkdir as mkdir13 } from "node:fs/promises";
73329
- import { dirname as dirname14, join as join59 } from "node:path";
73358
+ import { dirname as dirname15, join as join59 } from "node:path";
73330
73359
  function getTokenFilePath(cwd) {
73331
73360
  return join59(getCleoDir(cwd), "metrics", "TOKEN_USAGE.jsonl");
73332
73361
  }
@@ -73344,7 +73373,7 @@ function estimateTokensFromFile(filePath) {
73344
73373
  async function logTokenEvent(eventType, tokens, source, taskId, context, cwd) {
73345
73374
  if (!isTrackingEnabled()) return;
73346
73375
  const tokenFile = getTokenFilePath(cwd);
73347
- await mkdir13(dirname14(tokenFile), { recursive: true });
73376
+ await mkdir13(dirname15(tokenFile), { recursive: true });
73348
73377
  const entry = {
73349
73378
  timestamp: isoTimestamp(),
73350
73379
  event_type: eventType,
@@ -73867,7 +73896,7 @@ var init_agent_outputs = __esm({
73867
73896
  // packages/core/src/migration/checksum.ts
73868
73897
  import { createHash as createHash12 } from "node:crypto";
73869
73898
  import { readFileSync as readFileSync38 } from "node:fs";
73870
- import { createRequire as createRequire11 } from "node:module";
73899
+ import { createRequire as createRequire10 } from "node:module";
73871
73900
  async function computeChecksum2(filePath) {
73872
73901
  const content = readFileSync38(filePath);
73873
73902
  return createHash12("sha256").update(content).digest("hex");
@@ -73909,12 +73938,12 @@ async function compareChecksums(filePath1, filePath2) {
73909
73938
  const checksum2 = await computeChecksum2(filePath2);
73910
73939
  return checksum1 === checksum2;
73911
73940
  }
73912
- var _require10, DatabaseSync5;
73941
+ var _require9, DatabaseSync5;
73913
73942
  var init_checksum = __esm({
73914
73943
  "packages/core/src/migration/checksum.ts"() {
73915
73944
  "use strict";
73916
- _require10 = createRequire11(import.meta.url);
73917
- ({ DatabaseSync: DatabaseSync5 } = _require10("node:sqlite"));
73945
+ _require9 = createRequire10(import.meta.url);
73946
+ ({ DatabaseSync: DatabaseSync5 } = _require9("node:sqlite"));
73918
73947
  }
73919
73948
  });
73920
73949
 
@@ -73938,7 +73967,7 @@ import {
73938
73967
  statSync as statSync14,
73939
73968
  unlinkSync as unlinkSync3
73940
73969
  } from "node:fs";
73941
- import { dirname as dirname15, join as join61, relative as relative8 } from "node:path";
73970
+ import { dirname as dirname16, join as join61, relative as relative8 } from "node:path";
73942
73971
  function createMigrationLogger(cleoDir, config2) {
73943
73972
  return new MigrationLogger(cleoDir, config2);
73944
73973
  }
@@ -73994,7 +74023,7 @@ var init_logger3 = __esm({
73994
74023
  };
73995
74024
  const timestamp3 = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
73996
74025
  this.logPath = join61(cleoDir, "logs", `migration-${timestamp3}.jsonl`);
73997
- const logsDir = dirname15(this.logPath);
74026
+ const logsDir = dirname16(this.logPath);
73998
74027
  if (!existsSync57(logsDir)) {
73999
74028
  mkdirSync15(logsDir, { recursive: true });
74000
74029
  }
@@ -75071,7 +75100,7 @@ __export(migrate_json_to_sqlite_exports, {
75071
75100
  import { randomUUID as randomUUID4 } from "node:crypto";
75072
75101
  import { existsSync as existsSync61, readFileSync as readFileSync42, renameSync as renameSync4 } from "node:fs";
75073
75102
  import { join as join66 } from "node:path";
75074
- import { sql as sql10 } from "drizzle-orm";
75103
+ import { sql as sql11 } from "drizzle-orm";
75075
75104
  async function migrateJsonToSqlite() {
75076
75105
  const jsonPath = getRegistryPath();
75077
75106
  if (!existsSync61(jsonPath)) return 0;
@@ -75127,9 +75156,9 @@ async function migrateJsonToSqlite() {
75127
75156
  }).onConflictDoUpdate({
75128
75157
  target: projectRegistry.projectHash,
75129
75158
  set: {
75130
- projectPath: sql10`excluded.project_path`,
75131
- name: sql10`excluded.name`,
75132
- lastSeen: sql10`(datetime('now'))`
75159
+ projectPath: sql11`excluded.project_path`,
75160
+ name: sql11`excluded.name`,
75161
+ lastSeen: sql11`(datetime('now'))`
75133
75162
  }
75134
75163
  });
75135
75164
  migrated++;
@@ -76928,7 +76957,7 @@ var init_tasks_bridge = __esm({
76928
76957
 
76929
76958
  // packages/core/src/reconciliation/link-store.ts
76930
76959
  import { randomUUID as randomUUID6 } from "node:crypto";
76931
- import { and as and9, eq as eq13, sql as sql11 } from "drizzle-orm";
76960
+ import { and as and9, eq as eq13, sql as sql12 } from "drizzle-orm";
76932
76961
  async function getLinksByProvider(providerId, cwd) {
76933
76962
  const db = await getDb(cwd);
76934
76963
  const rows = await db.select().from(externalTaskLinks).where(eq13(externalTaskLinks.providerId, providerId));
@@ -76953,7 +76982,7 @@ async function ensureExternalTaskLinksTable(cwd) {
76953
76982
  const db = await getDb(cwd);
76954
76983
  try {
76955
76984
  db.run(
76956
- sql11.raw(`
76985
+ sql12.raw(`
76957
76986
  CREATE TABLE IF NOT EXISTS external_task_links (
76958
76987
  id text PRIMARY KEY NOT NULL,
76959
76988
  task_id text NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
@@ -76970,15 +76999,15 @@ async function ensureExternalTaskLinksTable(cwd) {
76970
76999
  `)
76971
77000
  );
76972
77001
  db.run(
76973
- sql11.raw(
77002
+ sql12.raw(
76974
77003
  `CREATE UNIQUE INDEX IF NOT EXISTS uq_ext_links_task_provider_external ON external_task_links(task_id, provider_id, external_id)`
76975
77004
  )
76976
77005
  );
76977
77006
  db.run(
76978
- sql11.raw(`CREATE INDEX IF NOT EXISTS idx_ext_links_task_id ON external_task_links(task_id)`)
77007
+ sql12.raw(`CREATE INDEX IF NOT EXISTS idx_ext_links_task_id ON external_task_links(task_id)`)
76979
77008
  );
76980
77009
  db.run(
76981
- sql11.raw(
77010
+ sql12.raw(
76982
77011
  `CREATE INDEX IF NOT EXISTS idx_ext_links_provider_id ON external_task_links(provider_id)`
76983
77012
  )
76984
77013
  );
@@ -79282,9 +79311,9 @@ async function loadProjectACL(projectPath) {
79282
79311
  try {
79283
79312
  const { loadConfig: loadConfig4 } = await Promise.resolve().then(() => (init_config(), config_exports));
79284
79313
  const config2 = await loadConfig4(projectPath);
79285
- const agents = config2?.authorizedAgents;
79286
- if (Array.isArray(agents) && agents.length > 0) {
79287
- return { authorizedAgents: agents };
79314
+ const agents2 = config2?.authorizedAgents;
79315
+ if (Array.isArray(agents2) && agents2.length > 0) {
79316
+ return { authorizedAgents: agents2 };
79288
79317
  }
79289
79318
  } catch {
79290
79319
  await logAclFailure(projectPath);
@@ -79502,13 +79531,13 @@ async function workspaceStatus() {
79502
79531
  }
79503
79532
  async function workspaceAgents() {
79504
79533
  const projects = await nexusList();
79505
- const agents = [];
79534
+ const agents2 = [];
79506
79535
  for (const project of projects) {
79507
79536
  try {
79508
79537
  const acc = await getAccessor(project.path);
79509
79538
  const instances = await acc.listAgentInstances();
79510
79539
  for (const inst of instances) {
79511
- agents.push({
79540
+ agents2.push({
79512
79541
  agentId: inst.id,
79513
79542
  agentType: inst.agentType,
79514
79543
  status: inst.status,
@@ -79520,7 +79549,7 @@ async function workspaceAgents() {
79520
79549
  } catch {
79521
79550
  }
79522
79551
  }
79523
- return agents;
79552
+ return agents2;
79524
79553
  }
79525
79554
  var RATE_LIMIT_WINDOW_MS, RATE_LIMIT_MAX_OPS, rateLimitCounters, DEFAULT_ACL, TASK_REF_PATTERN, VERB_TO_OPERATION;
79526
79555
  var init_workspace = __esm({
@@ -80196,12 +80225,12 @@ var init_skill_paths = __esm({
80196
80225
 
80197
80226
  // packages/core/src/orchestration/spawn-prompt.ts
80198
80227
  import { existsSync as existsSync67, readFileSync as readFileSync45 } from "node:fs";
80199
- import { dirname as dirname16, join as join73, resolve as resolve9 } from "node:path";
80200
- import { fileURLToPath as fileURLToPath7 } from "node:url";
80228
+ import { dirname as dirname17, join as join73, resolve as resolve9 } from "node:path";
80229
+ import { fileURLToPath as fileURLToPath8 } from "node:url";
80201
80230
  function locateCleoInjectionTemplate() {
80202
- const thisFile = fileURLToPath7(import.meta.url);
80231
+ const thisFile = fileURLToPath8(import.meta.url);
80203
80232
  const candidates = [];
80204
- let dir = dirname16(thisFile);
80233
+ let dir = dirname17(thisFile);
80205
80234
  for (let i = 0; i < 8; i++) {
80206
80235
  const direct = join73(dir, "templates", "CLEO-INJECTION.md");
80207
80236
  if (existsSync67(direct)) return direct;
@@ -80210,7 +80239,7 @@ function locateCleoInjectionTemplate() {
80210
80239
  if (parent === dir) break;
80211
80240
  dir = parent;
80212
80241
  }
80213
- let baseDir = dirname16(thisFile);
80242
+ let baseDir = dirname17(thisFile);
80214
80243
  for (let i = 0; i < 8; i++) {
80215
80244
  const nm = join73(baseDir, "node_modules", "@cleocode", "core", "templates", "CLEO-INJECTION.md");
80216
80245
  if (existsSync67(nm)) return nm;
@@ -81077,7 +81106,7 @@ var init_context2 = __esm({
81077
81106
 
81078
81107
  // packages/core/src/orchestration/harness-hint.ts
81079
81108
  import { existsSync as existsSync69, mkdirSync as mkdirSync16, readFileSync as readFileSync47, renameSync as renameSync5, writeFileSync as writeFileSync6 } from "node:fs";
81080
- import { dirname as dirname17, join as join74 } from "node:path";
81109
+ import { dirname as dirname18, join as join74 } from "node:path";
81081
81110
  function coerceHarnessHint(value) {
81082
81111
  if (!value) return void 0;
81083
81112
  return HARNESS_HINT_VALUES.has(value) ? value : void 0;
@@ -81142,7 +81171,7 @@ function resolveHarnessHint(options = {}) {
81142
81171
  }
81143
81172
  async function persistHarnessProfile(projectRoot, hint) {
81144
81173
  const finalPath = harnessProfilePath(projectRoot);
81145
- const cleoDir = dirname17(finalPath);
81174
+ const cleoDir = dirname18(finalPath);
81146
81175
  if (!existsSync69(cleoDir)) {
81147
81176
  mkdirSync16(cleoDir, { recursive: true });
81148
81177
  }
@@ -81184,7 +81213,7 @@ var init_harness_hint = __esm({
81184
81213
 
81185
81214
  // packages/core/src/orchestration/hierarchy.ts
81186
81215
  function buildDefaultHierarchy() {
81187
- const agents = {
81216
+ const agents2 = {
81188
81217
  owner: {
81189
81218
  agentId: "owner",
81190
81219
  displayName: "Owner (HITL)",
@@ -81287,7 +81316,7 @@ function buildDefaultHierarchy() {
81287
81316
  }
81288
81317
  };
81289
81318
  return {
81290
- agents,
81319
+ agents: agents2,
81291
81320
  primeId: "cleoos-opus-orchestrator",
81292
81321
  projectIds: ["cleocode", "signaldock"]
81293
81322
  };
@@ -81375,7 +81404,7 @@ var init_api_key_kdf = __esm({
81375
81404
  // packages/core/src/store/agent-registry-accessor.ts
81376
81405
  import { randomBytes as randomBytes13 } from "node:crypto";
81377
81406
  import { existsSync as existsSync70, mkdirSync as mkdirSync17, readFileSync as readFileSync48, statSync as statSync19, writeFileSync as writeFileSync7 } from "node:fs";
81378
- import { createRequire as createRequire12 } from "node:module";
81407
+ import { createRequire as createRequire11 } from "node:module";
81379
81408
  import { join as join75 } from "node:path";
81380
81409
  function readMachineKey() {
81381
81410
  const keyPath = join75(getCleoHome(), "machine-key");
@@ -81456,7 +81485,7 @@ function rowToResolvedAgent(row) {
81456
81485
  if (!extended.cantPath || !extended.cantSha256) {
81457
81486
  return null;
81458
81487
  }
81459
- const skills = JSON.parse(row.skills);
81488
+ const skills2 = JSON.parse(row.skills);
81460
81489
  return {
81461
81490
  agentId: row.agent_id,
81462
81491
  tier: extended.tier,
@@ -81465,7 +81494,7 @@ function rowToResolvedAgent(row) {
81465
81494
  canSpawn: extended.canSpawn,
81466
81495
  orchLevel: extended.orchLevel,
81467
81496
  reportsTo: extended.reportsTo,
81468
- skills,
81497
+ skills: skills2,
81469
81498
  source: extended.tier,
81470
81499
  aliasApplied: false
81471
81500
  };
@@ -81490,10 +81519,10 @@ function openConduitDb(projectRoot) {
81490
81519
  db.exec("PRAGMA journal_mode = WAL");
81491
81520
  return db;
81492
81521
  }
81493
- function syncJunctionTables(db, agentUuid, capabilities, skills) {
81522
+ function syncJunctionTables(db, agentUuid, capabilities2, skills2) {
81494
81523
  db.prepare("DELETE FROM agent_capabilities WHERE agent_id = ?").run(agentUuid);
81495
81524
  db.prepare("DELETE FROM agent_skills WHERE agent_id = ?").run(agentUuid);
81496
- for (const cap of capabilities) {
81525
+ for (const cap of capabilities2) {
81497
81526
  const capRow = db.prepare("SELECT id FROM capabilities WHERE slug = ?").get(cap);
81498
81527
  if (capRow) {
81499
81528
  db.prepare(
@@ -81501,7 +81530,7 @@ function syncJunctionTables(db, agentUuid, capabilities, skills) {
81501
81530
  ).run(agentUuid, capRow.id);
81502
81531
  }
81503
81532
  }
81504
- for (const skill of skills) {
81533
+ for (const skill of skills2) {
81505
81534
  const skillRow = db.prepare("SELECT id FROM skills WHERE slug = ?").get(skill);
81506
81535
  if (skillRow) {
81507
81536
  db.prepare("INSERT OR IGNORE INTO agent_skills (agent_id, skill_id) VALUES (?, ?)").run(
@@ -81695,7 +81724,7 @@ function getProjectAgentRef2(projectRoot, agentId) {
81695
81724
  conduitDb.close();
81696
81725
  }
81697
81726
  }
81698
- var _require11, DatabaseSync6, MACHINE_KEY_LENGTH, AgentRegistryAccessor;
81727
+ var _require10, DatabaseSync6, MACHINE_KEY_LENGTH, AgentRegistryAccessor;
81699
81728
  var init_agent_registry_accessor = __esm({
81700
81729
  "packages/core/src/store/agent-registry-accessor.ts"() {
81701
81730
  "use strict";
@@ -81704,8 +81733,8 @@ var init_agent_registry_accessor = __esm({
81704
81733
  init_conduit_sqlite();
81705
81734
  init_global_salt();
81706
81735
  init_signaldock_sqlite();
81707
- _require11 = createRequire12(import.meta.url);
81708
- ({ DatabaseSync: DatabaseSync6 } = _require11("node:sqlite"));
81736
+ _require10 = createRequire11(import.meta.url);
81737
+ ({ DatabaseSync: DatabaseSync6 } = _require10("node:sqlite"));
81709
81738
  MACHINE_KEY_LENGTH = 32;
81710
81739
  AgentRegistryAccessor = class {
81711
81740
  /**
@@ -82028,9 +82057,9 @@ var init_agent_registry_accessor = __esm({
82028
82057
  // packages/core/src/store/agent-resolver.ts
82029
82058
  import { createHash as createHash15 } from "node:crypto";
82030
82059
  import { accessSync as accessSync2, readFileSync as readFileSync49 } from "node:fs";
82031
- import { createRequire as createRequire13 } from "node:module";
82032
- import { dirname as dirname18, join as join76, resolve as resolve10 } from "node:path";
82033
- import { fileURLToPath as fileURLToPath8 } from "node:url";
82060
+ import { createRequire as createRequire12 } from "node:module";
82061
+ import { dirname as dirname19, join as join76, resolve as resolve10 } from "node:path";
82062
+ import { fileURLToPath as fileURLToPath9 } from "node:url";
82034
82063
  function resolveAgent(db, agentId, options = {}) {
82035
82064
  let effectiveId = agentId;
82036
82065
  let aliasApplied = false;
@@ -82142,7 +82171,7 @@ function tryResolveFallback(agentId, options) {
82142
82171
  };
82143
82172
  }
82144
82173
  function resolveDefaultSeedDir() {
82145
- const here = dirname18(fileURLToPath8(import.meta.url));
82174
+ const here = dirname19(fileURLToPath9(import.meta.url));
82146
82175
  return resolve10(here, "..", "..", "..", "agents", "seed-agents");
82147
82176
  }
82148
82177
  function fileExists2(path15) {
@@ -82158,7 +82187,7 @@ var init_agent_resolver = __esm({
82158
82187
  "packages/core/src/store/agent-resolver.ts"() {
82159
82188
  "use strict";
82160
82189
  init_agent_registry_accessor();
82161
- _resolverRequire = createRequire13(import.meta.url);
82190
+ _resolverRequire = createRequire12(import.meta.url);
82162
82191
  ({ DatabaseSync: _DatabaseSync } = _resolverRequire("node:sqlite"));
82163
82192
  DEPRECATED_ALIASES = Object.freeze({
82164
82193
  "cleoos-opus-orchestrator": "cleo-prime"
@@ -82846,7 +82875,7 @@ async function getOtelSummary() {
82846
82875
  return { message: "No token tracking data yet", events: 0 };
82847
82876
  }
82848
82877
  const totalTokens = entries.reduce((sum, e) => sum + (e.estimated_tokens ?? 0), 0);
82849
- const sessions2 = entries.filter((e) => e.event_type === "session_start");
82878
+ const sessions3 = entries.filter((e) => e.event_type === "session_start");
82850
82879
  const spawns = entries.filter((e) => e.event_type !== "session_start");
82851
82880
  const byType = {};
82852
82881
  for (const e of entries) {
@@ -82859,8 +82888,8 @@ async function getOtelSummary() {
82859
82888
  totalEvents: entries.length,
82860
82889
  totalTokens,
82861
82890
  sessions: {
82862
- count: sessions2.length,
82863
- tokens: sessions2.reduce((s3, e) => s3 + (e.estimated_tokens ?? 0), 0)
82891
+ count: sessions3.length,
82892
+ tokens: sessions3.reduce((s3, e) => s3 + (e.estimated_tokens ?? 0), 0)
82864
82893
  },
82865
82894
  spawns: {
82866
82895
  count: spawns.length,
@@ -82872,17 +82901,17 @@ async function getOtelSummary() {
82872
82901
  }
82873
82902
  async function getOtelSessions(opts) {
82874
82903
  const entries = readJsonlFile3(getTokenFilePath2());
82875
- let sessions2 = entries.filter((e) => e.event_type === "session_start");
82904
+ let sessions3 = entries.filter((e) => e.event_type === "session_start");
82876
82905
  if (opts.session) {
82877
- sessions2 = sessions2.filter((e) => {
82906
+ sessions3 = sessions3.filter((e) => {
82878
82907
  const ctx = e.context ?? {};
82879
82908
  return ctx.session_id === opts.session;
82880
82909
  });
82881
82910
  }
82882
82911
  if (opts.task) {
82883
- sessions2 = sessions2.filter((e) => e.task_id === opts.task);
82912
+ sessions3 = sessions3.filter((e) => e.task_id === opts.task);
82884
82913
  }
82885
- return { sessions: sessions2, count: sessions2.length };
82914
+ return { sessions: sessions3, count: sessions3.length };
82886
82915
  }
82887
82916
  async function getOtelSpawns(opts) {
82888
82917
  const entries = readJsonlFile3(getTokenFilePath2());
@@ -84386,7 +84415,7 @@ var init_release_config = __esm({
84386
84415
 
84387
84416
  // packages/core/src/release/ci.ts
84388
84417
  import { existsSync as existsSync75, mkdirSync as mkdirSync18, readFileSync as readFileSync53, writeFileSync as writeFileSync9 } from "node:fs";
84389
- import { dirname as dirname19, join as join79 } from "node:path";
84418
+ import { dirname as dirname20, join as join79 } from "node:path";
84390
84419
  function getPlatformPath(platform6) {
84391
84420
  return PLATFORM_PATHS[platform6];
84392
84421
  }
@@ -84501,7 +84530,7 @@ function writeCIConfig(platform6, options = {}) {
84501
84530
  if (options.dryRun) {
84502
84531
  return { action: "would_write", path: outputPath, content };
84503
84532
  }
84504
- mkdirSync18(dirname19(outputPath), { recursive: true });
84533
+ mkdirSync18(dirname20(outputPath), { recursive: true });
84505
84534
  writeFileSync9(outputPath, content, "utf-8");
84506
84535
  return { action: "wrote", path: outputPath, content };
84507
84536
  }
@@ -88019,7 +88048,7 @@ var init_input_sanitization = __esm({
88019
88048
  // packages/core/src/security/owner-override-auth.ts
88020
88049
  import { createHmac as createHmac2 } from "node:crypto";
88021
88050
  import { appendFileSync as appendFileSync8, mkdirSync as mkdirSync19 } from "node:fs";
88022
- import { dirname as dirname20 } from "node:path";
88051
+ import { dirname as dirname21 } from "node:path";
88023
88052
  function isAgentRoleForbidden() {
88024
88053
  const currentRole = process.env["CLEO_AGENT_ROLE"];
88025
88054
  if (BOOTSTRAP_AGENT_ROLE && FORBIDDEN_OVERRIDE_ROLES.has(BOOTSTRAP_AGENT_ROLE)) {
@@ -88062,7 +88091,7 @@ function resetOverrideCount(sessionId) {
88062
88091
  function appendOwnerOverrideAudit(projectRoot, record2) {
88063
88092
  const bypassPath = `${projectRoot}/.cleo/audit/force-bypass.jsonl`;
88064
88093
  try {
88065
- mkdirSync19(dirname20(bypassPath), { recursive: true });
88094
+ mkdirSync19(dirname21(bypassPath), { recursive: true });
88066
88095
  appendFileSync8(bypassPath, `${JSON.stringify(record2)}
88067
88096
  `, { encoding: "utf-8" });
88068
88097
  } catch {
@@ -88316,7 +88345,7 @@ var init_install = __esm({
88316
88345
 
88317
88346
  // packages/core/src/skills/agents/registry.ts
88318
88347
  import { existsSync as existsSync81, mkdirSync as mkdirSync21, readdirSync as readdirSync27, readFileSync as readFileSync57, writeFileSync as writeFileSync11 } from "node:fs";
88319
- import { dirname as dirname21, join as join85 } from "node:path";
88348
+ import { dirname as dirname22, join as join85 } from "node:path";
88320
88349
  function getRegistryPath2() {
88321
88350
  return join85(getCleoHome(), "agent-registry.json");
88322
88351
  }
@@ -88339,7 +88368,7 @@ function readRegistry2() {
88339
88368
  }
88340
88369
  function saveRegistry(registry2) {
88341
88370
  const registryPath = getRegistryPath2();
88342
- const dir = dirname21(registryPath);
88371
+ const dir = dirname22(registryPath);
88343
88372
  if (!existsSync81(dir)) {
88344
88373
  mkdirSync21(dir, { recursive: true });
88345
88374
  }
@@ -89276,8 +89305,8 @@ async function sessionInit(epicId, cwd) {
89276
89305
  let activeSessionId = null;
89277
89306
  let activeScope = null;
89278
89307
  try {
89279
- const sessions2 = await acc.loadSessions();
89280
- let active = sessions2.filter((s3) => s3.status === "active");
89308
+ const sessions3 = await acc.loadSessions();
89309
+ let active = sessions3.filter((s3) => s3.status === "active");
89281
89310
  if (epicId && active.length > 0) {
89282
89311
  const epicScoped = active.filter(
89283
89312
  (s3) => s3.scope?.rootTaskId === epicId || s3.scope?.epicId === epicId
@@ -90177,7 +90206,7 @@ __export(snapshot_exports, {
90177
90206
  import { createHash as createHash16 } from "node:crypto";
90178
90207
  import { existsSync as existsSync90 } from "node:fs";
90179
90208
  import { mkdir as mkdir16, readFile as readFile15, writeFile as writeFile11 } from "node:fs/promises";
90180
- import { dirname as dirname22, join as join93 } from "node:path";
90209
+ import { dirname as dirname23, join as join93 } from "node:path";
90181
90210
  function toSnapshotTask(task) {
90182
90211
  return {
90183
90212
  id: task.id,
@@ -90233,7 +90262,7 @@ async function exportSnapshot(cwd) {
90233
90262
  };
90234
90263
  }
90235
90264
  async function writeSnapshot(snapshot, outputPath) {
90236
- const dir = dirname22(outputPath);
90265
+ const dir = dirname23(outputPath);
90237
90266
  if (!existsSync90(dir)) {
90238
90267
  await mkdir16(dir, { recursive: true });
90239
90268
  }
@@ -91733,7 +91762,7 @@ async function convertStickyToSessionNote(stickyId, sessionId, projectRoot) {
91733
91762
  }
91734
91763
  const { readSessions: readSessions2, saveSessions: saveSessions2, sessionStatus: sessionStatus3 } = await Promise.resolve().then(() => (init_sessions2(), sessions_exports2));
91735
91764
  try {
91736
- const sessions2 = await readSessions2(projectRoot);
91765
+ const sessions3 = await readSessions2(projectRoot);
91737
91766
  let targetSessionId = sessionId;
91738
91767
  if (!targetSessionId) {
91739
91768
  const activeSession = await sessionStatus3(projectRoot);
@@ -91750,7 +91779,7 @@ async function convertStickyToSessionNote(stickyId, sessionId, projectRoot) {
91750
91779
  }
91751
91780
  };
91752
91781
  }
91753
- const session = sessions2.find((s3) => s3.id === targetSessionId);
91782
+ const session = sessions3.find((s3) => s3.id === targetSessionId);
91754
91783
  if (!session) {
91755
91784
  return {
91756
91785
  success: false,
@@ -91762,7 +91791,7 @@ async function convertStickyToSessionNote(stickyId, sessionId, projectRoot) {
91762
91791
  }
91763
91792
  const timestampedNote = `${(/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace(/\.\d+Z$/, " UTC")}: ${sticky.content}`;
91764
91793
  session.notes.push(timestampedNote);
91765
- await saveSessions2(sessions2, projectRoot);
91794
+ await saveSessions2(sessions3, projectRoot);
91766
91795
  const convertedTo = { type: "session_note", id: targetSessionId };
91767
91796
  await accessor.updateStickyNote(stickyId, {
91768
91797
  status: "converted",
@@ -92319,9 +92348,9 @@ async function auditData(projectRoot, opts) {
92319
92348
  if (existsSync93(sessPath)) {
92320
92349
  try {
92321
92350
  const data = JSON.parse(readFileSync67(sessPath, "utf-8"));
92322
- const sessions2 = data.sessions ?? [];
92351
+ const sessions3 = data.sessions ?? [];
92323
92352
  const sessionIds = /* @__PURE__ */ new Set();
92324
- for (const s3 of sessions2) {
92353
+ for (const s3 of sessions3) {
92325
92354
  if (sessionIds.has(s3.id)) {
92326
92355
  issues.push({
92327
92356
  severity: "error",
@@ -92331,7 +92360,7 @@ async function auditData(projectRoot, opts) {
92331
92360
  }
92332
92361
  sessionIds.add(s3.id);
92333
92362
  }
92334
- for (const s3 of sessions2) {
92363
+ for (const s3 of sessions3) {
92335
92364
  if (!s3.scope?.rootTaskId) {
92336
92365
  issues.push({
92337
92366
  severity: "warning",
@@ -92398,7 +92427,7 @@ import {
92398
92427
  unlinkSync as unlinkSync6,
92399
92428
  writeFileSync as writeFileSync16
92400
92429
  } from "node:fs";
92401
- import { dirname as dirname23, join as join97 } from "node:path";
92430
+ import { dirname as dirname24, join as join97 } from "node:path";
92402
92431
  function safeSqliteSnapshot(db, destPath) {
92403
92432
  if (!db) return false;
92404
92433
  db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
@@ -92407,7 +92436,7 @@ function safeSqliteSnapshot(db, destPath) {
92407
92436
  return true;
92408
92437
  }
92409
92438
  function atomicWriteSync(destPath, data) {
92410
- mkdirSync25(dirname23(destPath), { recursive: true });
92439
+ mkdirSync25(dirname24(destPath), { recursive: true });
92411
92440
  const tmp = `${destPath}.${process.pid}.${Date.now()}.tmp`;
92412
92441
  try {
92413
92442
  writeFileSync16(tmp, data);
@@ -92669,8 +92698,8 @@ async function cleanupSystem(projectRoot, params) {
92669
92698
  if (existsSync95(sessPath)) {
92670
92699
  try {
92671
92700
  const data = JSON.parse(readFileSync69(sessPath, "utf-8"));
92672
- const sessions2 = data.sessions ?? [];
92673
- const stale = sessions2.filter(
92701
+ const sessions3 = data.sessions ?? [];
92702
+ const stale = sessions3.filter(
92674
92703
  (s3) => {
92675
92704
  if (s3.status !== "active") return false;
92676
92705
  if (params.olderThan && s3.lastActivity) {
@@ -92685,7 +92714,7 @@ async function cleanupSystem(projectRoot, params) {
92685
92714
  }
92686
92715
  if (!dryRun && stale.length > 0) {
92687
92716
  const staleIds = new Set(stale.map((s3) => s3.id));
92688
- data.sessions = sessions2.filter((s3) => !staleIds.has(s3.id));
92717
+ data.sessions = sessions3.filter((s3) => !staleIds.has(s3.id));
92689
92718
  writeFileSync17(sessPath, JSON.stringify(data, null, 2), "utf-8");
92690
92719
  }
92691
92720
  } catch {
@@ -92904,10 +92933,10 @@ import {
92904
92933
  unlinkSync as unlinkSync8,
92905
92934
  writeFileSync as writeFileSync18
92906
92935
  } from "node:fs";
92907
- import { basename as basename14, dirname as dirname24, join as join101 } from "node:path";
92936
+ import { basename as basename14, dirname as dirname25, join as join101 } from "node:path";
92908
92937
  import * as lockfile2 from "proper-lockfile";
92909
92938
  function rotateBackup(filePath) {
92910
- const dir = dirname24(filePath);
92939
+ const dir = dirname25(filePath);
92911
92940
  const name2 = basename14(filePath);
92912
92941
  const backupDir = join101(dir, ".backups");
92913
92942
  if (!existsSync97(backupDir)) {
@@ -92935,7 +92964,7 @@ function rotateBackup(filePath) {
92935
92964
  }
92936
92965
  }
92937
92966
  function writeJsonFileAtomic(filePath, data, indent = 2) {
92938
- const dir = dirname24(filePath);
92967
+ const dir = dirname25(filePath);
92939
92968
  const tempPath = join101(dir, `.${basename14(filePath)}.${randomBytes15(6).toString("hex")}.tmp`);
92940
92969
  const content = JSON.stringify(data, null, indent) + "\n";
92941
92970
  writeFileSync18(tempPath, content, "utf-8");
@@ -94016,11 +94045,11 @@ __export(parser_exports, {
94016
94045
  parseFile: () => parseFile2
94017
94046
  });
94018
94047
  import { readFileSync as readFileSync72 } from "node:fs";
94019
- import { createRequire as createRequire14 } from "node:module";
94048
+ import { createRequire as createRequire13 } from "node:module";
94020
94049
  import { relative as relative11 } from "node:path";
94021
94050
  function tryRequire2(id) {
94022
94051
  try {
94023
- return _require12(id);
94052
+ return _require11(id);
94024
94053
  } catch {
94025
94054
  return null;
94026
94055
  }
@@ -94212,12 +94241,12 @@ function batchParse2(filePaths, projectRoot) {
94212
94241
  const totalSymbols = results.reduce((sum, r) => sum + r.symbols.length, 0);
94213
94242
  return { results, skipped, totalSymbols };
94214
94243
  }
94215
- var _require12, _ParserClass3, _QueryClass2, _parserInstance3, _availabilityChecked2, _available3, _grammarCache3, GRAMMAR_SPECS3, QUERY_PATTERNS2, _queryCache2;
94244
+ var _require11, _ParserClass3, _QueryClass2, _parserInstance3, _availabilityChecked2, _available3, _grammarCache3, GRAMMAR_SPECS3, QUERY_PATTERNS2, _queryCache2;
94216
94245
  var init_parser4 = __esm({
94217
94246
  "packages/core/src/code/parser.ts"() {
94218
94247
  "use strict";
94219
94248
  init_tree_sitter_languages2();
94220
- _require12 = createRequire14(import.meta.url);
94249
+ _require11 = createRequire13(import.meta.url);
94221
94250
  _ParserClass3 = null;
94222
94251
  _QueryClass2 = null;
94223
94252
  _parserInstance3 = null;
@@ -94323,9 +94352,9 @@ __export(dependencies_exports, {
94323
94352
  getDependencySpecs: () => getDependencySpecs
94324
94353
  });
94325
94354
  import { execFileSync as execFileSync12 } from "node:child_process";
94326
- import { createRequire as createRequire15 } from "node:module";
94327
- import { dirname as dirname25 } from "node:path";
94328
- import { fileURLToPath as fileURLToPath9 } from "node:url";
94355
+ import { createRequire as createRequire14 } from "node:module";
94356
+ import { dirname as dirname26 } from "node:path";
94357
+ import { fileURLToPath as fileURLToPath10 } from "node:url";
94329
94358
  function tryExec(cmd, args, timeoutMs = 3e3) {
94330
94359
  try {
94331
94360
  return execFileSync12(cmd, args, {
@@ -94394,7 +94423,7 @@ async function checkTreeSitter() {
94394
94423
  let version2;
94395
94424
  if (available) {
94396
94425
  try {
94397
- const pkgJson = _require13("tree-sitter/package.json");
94426
+ const pkgJson = _require12("tree-sitter/package.json");
94398
94427
  version2 = pkgJson.version;
94399
94428
  } catch {
94400
94429
  version2 = void 0;
@@ -94463,17 +94492,17 @@ function checkSimpleTool(name2, category, errorMsg, fixHint) {
94463
94492
  function checkCantNapi() {
94464
94493
  let available = false;
94465
94494
  try {
94466
- const binary2 = _require13.resolve("../../../cant/napi/cant.linux-x64-gnu.node", {
94495
+ const binary2 = _require12.resolve("../../../cant/napi/cant.linux-x64-gnu.node", {
94467
94496
  paths: [_dirname]
94468
94497
  });
94469
- _require13(binary2);
94498
+ _require12(binary2);
94470
94499
  available = true;
94471
94500
  } catch {
94472
94501
  try {
94473
- const fallback = _require13.resolve("../../../../crates/cant-napi/index.cjs", {
94502
+ const fallback = _require12.resolve("../../../../crates/cant-napi/index.cjs", {
94474
94503
  paths: [_dirname]
94475
94504
  });
94476
- _require13(fallback);
94505
+ _require12(fallback);
94477
94506
  available = true;
94478
94507
  } catch {
94479
94508
  available = false;
@@ -94494,15 +94523,15 @@ function checkCantNapi() {
94494
94523
  function checkLafsNapi() {
94495
94524
  let available = false;
94496
94525
  try {
94497
- _require13.resolve("@cleocode/lafs-native", { paths: [_dirname] });
94498
- _require13("@cleocode/lafs-native");
94526
+ _require12.resolve("@cleocode/lafs-native", { paths: [_dirname] });
94527
+ _require12("@cleocode/lafs-native");
94499
94528
  available = true;
94500
94529
  } catch {
94501
94530
  try {
94502
- const fallback = _require13.resolve("../../../../crates/lafs-napi/index.cjs", {
94531
+ const fallback = _require12.resolve("../../../../crates/lafs-napi/index.cjs", {
94503
94532
  paths: [_dirname]
94504
94533
  });
94505
- _require13(fallback);
94534
+ _require12(fallback);
94506
94535
  available = true;
94507
94536
  } catch {
94508
94537
  available = false;
@@ -94591,13 +94620,13 @@ async function checkAllDependencies() {
94591
94620
  warnings
94592
94621
  };
94593
94622
  }
94594
- var _require13, _dirname, DEPENDENCY_SPECS;
94623
+ var _require12, _dirname, DEPENDENCY_SPECS;
94595
94624
  var init_dependencies = __esm({
94596
94625
  "packages/core/src/system/dependencies.ts"() {
94597
94626
  "use strict";
94598
94627
  init_platform();
94599
- _require13 = createRequire15(import.meta.url);
94600
- _dirname = dirname25(fileURLToPath9(import.meta.url));
94628
+ _require12 = createRequire14(import.meta.url);
94629
+ _dirname = dirname26(fileURLToPath10(import.meta.url));
94601
94630
  DEPENDENCY_SPECS = [
94602
94631
  // ── Required ────────────────────────────────────────────────────────────
94603
94632
  {
@@ -94677,12 +94706,12 @@ __export(project_health_exports, {
94677
94706
  probeDb: () => probeDb
94678
94707
  });
94679
94708
  import { access as fsAccess, readFile as readFile18, stat as stat3 } from "node:fs/promises";
94680
- import { createRequire as createRequire16 } from "node:module";
94681
- import { dirname as dirname26, join as join103 } from "node:path";
94709
+ import { createRequire as createRequire15 } from "node:module";
94710
+ import { dirname as dirname27, join as join103 } from "node:path";
94682
94711
  function getDatabaseSyncCtor() {
94683
94712
  if (_databaseSyncCtor !== void 0) return _databaseSyncCtor;
94684
94713
  try {
94685
- const mod = _require14("node:sqlite");
94714
+ const mod = _require13("node:sqlite");
94686
94715
  _databaseSyncCtor = mod.DatabaseSync;
94687
94716
  } catch {
94688
94717
  _databaseSyncCtor = null;
@@ -95096,15 +95125,15 @@ async function writeHealthBack(reports, log15) {
95096
95125
  }
95097
95126
  }
95098
95127
  function _parentDirOf(dbPath) {
95099
- return dirname26(dbPath);
95128
+ return dirname27(dbPath);
95100
95129
  }
95101
- var _require14, _databaseSyncCtor, TASKS_DB, BRAIN_DB, CONDUIT_DB, NEXUS_DB, SIGNALDOCK_DB, CONFIG_JSON, PROJECT_INFO_JSON, DB_EXPECTED_VERSIONS, JSON_EXPECTED_VERSIONS;
95130
+ var _require13, _databaseSyncCtor, TASKS_DB, BRAIN_DB, CONDUIT_DB, NEXUS_DB, SIGNALDOCK_DB, CONFIG_JSON, PROJECT_INFO_JSON, DB_EXPECTED_VERSIONS, JSON_EXPECTED_VERSIONS;
95102
95131
  var init_project_health = __esm({
95103
95132
  "packages/core/src/system/project-health.ts"() {
95104
95133
  "use strict";
95105
95134
  init_logger();
95106
95135
  init_paths();
95107
- _require14 = createRequire16(import.meta.url);
95136
+ _require13 = createRequire15(import.meta.url);
95108
95137
  TASKS_DB = "tasks.db";
95109
95138
  BRAIN_DB = "brain.db";
95110
95139
  CONDUIT_DB = "conduit.db";
@@ -95129,7 +95158,7 @@ var init_project_health = __esm({
95129
95158
  // packages/core/src/system/health.ts
95130
95159
  import { execFileSync as execFileSync13 } from "node:child_process";
95131
95160
  import { existsSync as existsSync99, readFileSync as readFileSync73, statSync as statSync21 } from "node:fs";
95132
- import { createRequire as createRequire17 } from "node:module";
95161
+ import { createRequire as createRequire16 } from "node:module";
95133
95162
  import { join as join104 } from "node:path";
95134
95163
  function resolveStructuredLogPath(cleoDir) {
95135
95164
  const defaultPath = join104(cleoDir, "logs", "cleo.log");
@@ -95261,7 +95290,7 @@ async function getSystemHealth(projectRoot, opts) {
95261
95290
  const sdDbPath = join104(cleoDir, "signaldock.db");
95262
95291
  if (existsSync99(sdDbPath)) {
95263
95292
  try {
95264
- const { DatabaseSync: SdDb } = _require15("node:sqlite");
95293
+ const { DatabaseSync: SdDb } = _require14("node:sqlite");
95265
95294
  const sdDb = new SdDb(sdDbPath);
95266
95295
  try {
95267
95296
  const tables = sdDb.prepare(
@@ -95417,8 +95446,8 @@ async function getSystemDiagnostics(projectRoot, opts) {
95417
95446
  if (existsSync99(dbPath)) {
95418
95447
  try {
95419
95448
  const accessor = await getAccessor(projectRoot);
95420
- const sessions2 = await accessor.loadSessions();
95421
- const activeSessions = sessions2.filter((s3) => s3.status === "active");
95449
+ const sessions3 = await accessor.loadSessions();
95450
+ const activeSessions = sessions3.filter((s3) => s3.status === "active");
95422
95451
  if (activeSessions.length > 3) {
95423
95452
  diagChecks.push({
95424
95453
  name: "stale_sessions",
@@ -96138,7 +96167,7 @@ async function startupHealthCheck(projectRoot) {
96138
96167
  system
96139
96168
  };
96140
96169
  }
96141
- var _require15, databaseSyncCtor, STALE_JSON_FILES;
96170
+ var _require14, databaseSyncCtor, STALE_JSON_FILES;
96142
96171
  var init_health = __esm({
96143
96172
  "packages/core/src/system/health.ts"() {
96144
96173
  "use strict";
@@ -96152,10 +96181,10 @@ var init_health = __esm({
96152
96181
  init_checks3();
96153
96182
  init_dependencies();
96154
96183
  init_storage_preflight();
96155
- _require15 = createRequire17(import.meta.url);
96184
+ _require14 = createRequire16(import.meta.url);
96156
96185
  databaseSyncCtor = (() => {
96157
96186
  try {
96158
- return _require15("node:sqlite").DatabaseSync;
96187
+ return _require14("node:sqlite").DatabaseSync;
96159
96188
  } catch {
96160
96189
  return null;
96161
96190
  }
@@ -96190,8 +96219,8 @@ async function generateInjection(projectRoot, accessor) {
96190
96219
  activeSessionName = activeSessionMeta;
96191
96220
  }
96192
96221
  try {
96193
- const sessions2 = await acc.loadSessions();
96194
- const active = sessions2.find((s3) => s3.status === "active");
96222
+ const sessions3 = await acc.loadSessions();
96223
+ const active = sessions3.find((s3) => s3.status === "active");
96195
96224
  if (active) {
96196
96225
  activeSessionName = active.name || active.id;
96197
96226
  focusTask = active.taskWork?.taskId ?? focusTask;
@@ -96336,18 +96365,18 @@ async function getSystemMetrics(projectRoot, opts, accessor) {
96336
96365
  let sessionsCompleted = 0;
96337
96366
  try {
96338
96367
  if (accessor) {
96339
- const sessions2 = await accessor.loadSessions();
96340
- sessionsTotal = sessions2.length;
96341
- sessionsActive = sessions2.filter((s3) => s3.status === "active").length;
96342
- sessionsCompleted = sessions2.filter((s3) => s3.status === "ended").length;
96368
+ const sessions3 = await accessor.loadSessions();
96369
+ sessionsTotal = sessions3.length;
96370
+ sessionsActive = sessions3.filter((s3) => s3.status === "active").length;
96371
+ sessionsCompleted = sessions3.filter((s3) => s3.status === "ended").length;
96343
96372
  } else {
96344
96373
  const sessionsPath = join106(cleoDir, "sessions.json");
96345
96374
  if (existsSync101(sessionsPath)) {
96346
96375
  const sessionsData = JSON.parse(readFileSync75(sessionsPath, "utf-8"));
96347
- const sessions2 = sessionsData.sessions ?? [];
96348
- sessionsTotal = sessions2.length;
96349
- sessionsActive = sessions2.filter((s3) => s3.status === "active").length;
96350
- sessionsCompleted = sessions2.filter(
96376
+ const sessions3 = sessionsData.sessions ?? [];
96377
+ sessionsTotal = sessions3.length;
96378
+ sessionsActive = sessions3.filter((s3) => s3.status === "active").length;
96379
+ sessionsCompleted = sessions3.filter(
96351
96380
  (s3) => s3.status === "ended" || s3.status === "ended"
96352
96381
  ).length;
96353
96382
  }
@@ -97686,7 +97715,7 @@ var init_find3 = __esm({
97686
97715
 
97687
97716
  // packages/core/src/tasks/gate-audit.ts
97688
97717
  import { appendFile as appendFile5, mkdir as mkdir18, readFile as readFile21 } from "node:fs/promises";
97689
- import { dirname as dirname27, resolve as resolvePath3 } from "node:path";
97718
+ import { dirname as dirname28, resolve as resolvePath3 } from "node:path";
97690
97719
  function getGateAuditPath(projectRoot) {
97691
97720
  return resolvePath3(projectRoot, ".cleo", "audit", "gates.jsonl");
97692
97721
  }
@@ -97695,14 +97724,14 @@ function getForceBypassPath(projectRoot) {
97695
97724
  }
97696
97725
  async function appendGateAuditLine(projectRoot, record2) {
97697
97726
  const path15 = getGateAuditPath(projectRoot);
97698
- await mkdir18(dirname27(path15), { recursive: true });
97727
+ await mkdir18(dirname28(path15), { recursive: true });
97699
97728
  const line2 = `${JSON.stringify(record2)}
97700
97729
  `;
97701
97730
  await appendFile5(path15, line2, { encoding: "utf-8" });
97702
97731
  }
97703
97732
  async function appendForceBypassLine(projectRoot, record2) {
97704
97733
  const path15 = getForceBypassPath(projectRoot);
97705
- await mkdir18(dirname27(path15), { recursive: true });
97734
+ await mkdir18(dirname28(path15), { recursive: true });
97706
97735
  const line2 = `${JSON.stringify(record2)}
97707
97736
  `;
97708
97737
  await appendFile5(path15, line2, { encoding: "utf-8" });
@@ -97873,7 +97902,7 @@ __export(schema_exports, {
97873
97902
  telemetryEvents: () => telemetryEvents,
97874
97903
  telemetrySchemaMeta: () => telemetrySchemaMeta
97875
97904
  });
97876
- import { sql as sql12 } from "drizzle-orm";
97905
+ import { sql as sql13 } from "drizzle-orm";
97877
97906
  var telemetryEvents, telemetrySchemaMeta;
97878
97907
  var init_schema = __esm({
97879
97908
  "packages/core/src/telemetry/schema.ts"() {
@@ -97901,7 +97930,7 @@ var init_schema = __esm({
97901
97930
  /** Machine-readable error code when exit_code != 0. NULL on success. */
97902
97931
  errorCode: text2("error_code"),
97903
97932
  /** ISO-8601 timestamp of the invocation. */
97904
- timestamp: text2("timestamp").notNull().default(sql12`(datetime('now'))`)
97933
+ timestamp: text2("timestamp").notNull().default(sql13`(datetime('now'))`)
97905
97934
  },
97906
97935
  (table) => [
97907
97936
  index("idx_telemetry_command").on(table.command),
@@ -97922,14 +97951,14 @@ var init_schema = __esm({
97922
97951
 
97923
97952
  // packages/core/src/telemetry/sqlite.ts
97924
97953
  import { mkdirSync as mkdirSync28 } from "node:fs";
97925
- import { dirname as dirname28, join as join110 } from "node:path";
97926
- import { fileURLToPath as fileURLToPath10 } from "node:url";
97954
+ import { dirname as dirname29, join as join110 } from "node:path";
97955
+ import { fileURLToPath as fileURLToPath11 } from "node:url";
97927
97956
  function getTelemetryDbPath() {
97928
97957
  return join110(getCleoHome(), DB_FILENAME4);
97929
97958
  }
97930
97959
  function resolveTelemetryMigrationsFolder() {
97931
- const __filename = fileURLToPath10(import.meta.url);
97932
- const __dir = dirname28(__filename);
97960
+ const __filename = fileURLToPath11(import.meta.url);
97961
+ const __dir = dirname29(__filename);
97933
97962
  const isBundled = __dir.endsWith("/dist") || __dir.endsWith("\\dist");
97934
97963
  const pkgRoot = isBundled ? join110(__dir, "..") : join110(__dir, "..", "..");
97935
97964
  return join110(pkgRoot, "migrations", "drizzle-telemetry");
@@ -97974,7 +98003,7 @@ async function getTelemetryDb() {
97974
98003
  _initPromise3 = (async () => {
97975
98004
  const dbPath = requestedPath;
97976
98005
  _dbPath3 = dbPath;
97977
- mkdirSync28(dirname28(dbPath), { recursive: true });
98006
+ mkdirSync28(dirname29(dbPath), { recursive: true });
97978
98007
  const nativeDb = openNativeDatabase(dbPath);
97979
98008
  _nativeDb3 = nativeDb;
97980
98009
  const db = drizzle({ client: nativeDb, schema: schema_exports });
@@ -98025,7 +98054,7 @@ __export(telemetry_exports, {
98025
98054
  import { randomUUID as randomUUID8 } from "node:crypto";
98026
98055
  import { existsSync as existsSync106, mkdirSync as mkdirSync29, readFileSync as readFileSync76, writeFileSync as writeFileSync19 } from "node:fs";
98027
98056
  import { join as join111 } from "node:path";
98028
- import { and as and11, count as count2, desc as desc5, gt as gt2, sql as sql13 } from "drizzle-orm";
98057
+ import { and as and11, count as count2, desc as desc5, gt as gt2, sql as sql14 } from "drizzle-orm";
98029
98058
  function getTelemetryConfigPath() {
98030
98059
  return join111(getCleoHome(), TELEMETRY_CONFIG_FILENAME);
98031
98060
  }
@@ -98109,15 +98138,15 @@ async function buildDiagnosticsReport(days = 30) {
98109
98138
  const rows = await db.select({
98110
98139
  command: telemetryEvents.command,
98111
98140
  total: count2(telemetryEvents.id),
98112
- failures: sql13`SUM(CASE WHEN ${telemetryEvents.exitCode} != 0 THEN 1 ELSE 0 END)`,
98113
- avgMs: sql13`AVG(${telemetryEvents.durationMs})`,
98114
- maxMs: sql13`MAX(${telemetryEvents.durationMs})`
98141
+ failures: sql14`SUM(CASE WHEN ${telemetryEvents.exitCode} != 0 THEN 1 ELSE 0 END)`,
98142
+ avgMs: sql14`AVG(${telemetryEvents.durationMs})`,
98143
+ maxMs: sql14`MAX(${telemetryEvents.durationMs})`
98115
98144
  }).from(telemetryEvents).where(gt2(telemetryEvents.timestamp, from)).groupBy(telemetryEvents.command).all();
98116
98145
  const errorCodeRows = await db.select({
98117
98146
  command: telemetryEvents.command,
98118
98147
  errorCode: telemetryEvents.errorCode,
98119
98148
  n: count2(telemetryEvents.id)
98120
- }).from(telemetryEvents).where(and11(gt2(telemetryEvents.timestamp, from), sql13`${telemetryEvents.errorCode} IS NOT NULL`)).groupBy(telemetryEvents.command, telemetryEvents.errorCode).orderBy(desc5(count2(telemetryEvents.id))).all();
98149
+ }).from(telemetryEvents).where(and11(gt2(telemetryEvents.timestamp, from), sql14`${telemetryEvents.errorCode} IS NOT NULL`)).groupBy(telemetryEvents.command, telemetryEvents.errorCode).orderBy(desc5(count2(telemetryEvents.id))).all();
98121
98150
  const topErrorMap = /* @__PURE__ */ new Map();
98122
98151
  for (const r of errorCodeRows) {
98123
98152
  if (!topErrorMap.has(r.command)) {
@@ -99427,8 +99456,8 @@ var init_validation_schemas = __esm({
99427
99456
  sessionRefinements = {
99428
99457
  name: (s3) => s3.min(1).max(200)
99429
99458
  };
99430
- insertSessionSchema = createInsertSchema2(sessions, sessionRefinements);
99431
- selectSessionSchema = createSelectSchema2(sessions, sessionRefinements);
99459
+ insertSessionSchema = createInsertSchema2(sessions2, sessionRefinements);
99460
+ selectSessionSchema = createSelectSchema2(sessions2, sessionRefinements);
99432
99461
  insertWorkHistorySchema = createInsertSchema2(taskWorkHistory);
99433
99462
  selectWorkHistorySchema = createSelectSchema2(taskWorkHistory);
99434
99463
  lifecyclePipelineRefinements = {
@@ -99828,7 +99857,7 @@ var init_docs_sync = __esm({
99828
99857
  // packages/core/src/validation/doctor/project-cache.ts
99829
99858
  import { createHash as createHash20 } from "node:crypto";
99830
99859
  import { existsSync as existsSync112, mkdirSync as mkdirSync30, readFileSync as readFileSync82, unlinkSync as unlinkSync9, writeFileSync as writeFileSync22 } from "node:fs";
99831
- import { dirname as dirname29, join as join116 } from "node:path";
99860
+ import { dirname as dirname30, join as join116 } from "node:path";
99832
99861
  function getCacheFilePath(cleoHome) {
99833
99862
  const home = cleoHome ?? getCleoHome();
99834
99863
  return join116(home, CACHE_FILE2);
@@ -99839,7 +99868,7 @@ function initCacheFile(cacheFile) {
99839
99868
  lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
99840
99869
  projects: {}
99841
99870
  };
99842
- const dir = dirname29(cacheFile);
99871
+ const dir = dirname30(cacheFile);
99843
99872
  if (!existsSync112(dir)) {
99844
99873
  mkdirSync30(dir, { recursive: true });
99845
99874
  }
@@ -100939,7 +100968,7 @@ var init_gap_check = __esm({
100939
100968
  // packages/core/src/validation/manifest.ts
100940
100969
  import { existsSync as existsSync113 } from "node:fs";
100941
100970
  import { appendFile as appendFile6, mkdir as mkdir19, readFile as readFile22 } from "node:fs/promises";
100942
- import { dirname as dirname30 } from "node:path";
100971
+ import { dirname as dirname31 } from "node:path";
100943
100972
  async function findManifestEntry(taskId, manifestPath) {
100944
100973
  if (!manifestPath) {
100945
100974
  try {
@@ -101060,7 +101089,7 @@ async function validateManifestEntry(taskId, manifestEntry, manifestPath = DEFAU
101060
101089
  };
101061
101090
  }
101062
101091
  async function logRealCompliance(taskId, validationResult, agentType = "unknown", compliancePath = DEFAULT_COMPLIANCE_PATH) {
101063
- const metricsDir = dirname30(compliancePath);
101092
+ const metricsDir = dirname31(compliancePath);
101064
101093
  await mkdir19(metricsDir, { recursive: true });
101065
101094
  const { score, pass, violations } = validationResult;
101066
101095
  const violationCount = violations.length;
@@ -102224,13 +102253,13 @@ __export(init_exports, {
102224
102253
  import { existsSync as existsSync116, readdirSync as readdirSync37, readFileSync as readFileSync84 } from "node:fs";
102225
102254
  import { copyFile as copyFile4, lstat, mkdir as mkdir20, readFile as readFile23, symlink, unlink as unlink4, writeFile as writeFile12 } from "node:fs/promises";
102226
102255
  import { platform as platform5 } from "node:os";
102227
- import { basename as basename17, dirname as dirname31, join as join118 } from "node:path";
102256
+ import { basename as basename17, dirname as dirname32, join as join118 } from "node:path";
102228
102257
  async function resolveSeedAgentsDir() {
102229
102258
  try {
102230
- const { createRequire: createRequire24 } = await import("node:module");
102231
- const req = createRequire24(import.meta.url);
102259
+ const { createRequire: createRequire23 } = await import("node:module");
102260
+ const req = createRequire23(import.meta.url);
102232
102261
  const agentsPkgMain = req.resolve("@cleocode/agents/package.json");
102233
- const agentsPkgRoot = dirname31(agentsPkgMain);
102262
+ const agentsPkgRoot = dirname32(agentsPkgMain);
102234
102263
  const candidate = join118(agentsPkgRoot, "seed-agents");
102235
102264
  if (existsSync116(candidate)) {
102236
102265
  return candidate;
@@ -102255,10 +102284,10 @@ async function resolveSeedAgentsDir() {
102255
102284
  async function initAgentDefinition(created, warnings) {
102256
102285
  let agentSourceDir = null;
102257
102286
  try {
102258
- const { createRequire: createRequire24 } = await import("node:module");
102259
- const req = createRequire24(import.meta.url);
102287
+ const { createRequire: createRequire23 } = await import("node:module");
102288
+ const req = createRequire23(import.meta.url);
102260
102289
  const agentsPkgMain = req.resolve("@cleocode/agents/package.json");
102261
- const agentsPkgRoot = dirname31(agentsPkgMain);
102290
+ const agentsPkgRoot = dirname32(agentsPkgMain);
102262
102291
  const candidate = join118(agentsPkgRoot, "cleo-subagent");
102263
102292
  if (existsSync116(candidate)) {
102264
102293
  agentSourceDir = candidate;
@@ -102277,7 +102306,7 @@ async function initAgentDefinition(created, warnings) {
102277
102306
  return;
102278
102307
  }
102279
102308
  const globalAgentsDir = join118(getAgentsHome(), "agents", "cleo-subagent");
102280
- await mkdir20(dirname31(globalAgentsDir), { recursive: true });
102309
+ await mkdir20(dirname32(globalAgentsDir), { recursive: true });
102281
102310
  try {
102282
102311
  try {
102283
102312
  const stat8 = await lstat(globalAgentsDir);
@@ -102322,10 +102351,10 @@ async function initCoreSkills(created, warnings) {
102322
102351
  const packageRoot = getPackageRoot();
102323
102352
  let ctSkillsRoot = null;
102324
102353
  try {
102325
- const { createRequire: createRequire24 } = await import("node:module");
102326
- const req = createRequire24(import.meta.url);
102354
+ const { createRequire: createRequire23 } = await import("node:module");
102355
+ const req = createRequire23(import.meta.url);
102327
102356
  const skillsPkgMain = req.resolve("@cleocode/skills/package.json");
102328
- const skillsPkgRoot = dirname31(skillsPkgMain);
102357
+ const skillsPkgRoot = dirname32(skillsPkgMain);
102329
102358
  if (existsSync116(join118(skillsPkgRoot, "skills.json"))) {
102330
102359
  ctSkillsRoot = skillsPkgRoot;
102331
102360
  }
@@ -102356,11 +102385,11 @@ async function initCoreSkills(created, warnings) {
102356
102385
  }
102357
102386
  const catalogPath = join118(ctSkillsRoot, "skills.json");
102358
102387
  const catalog5 = JSON.parse(readFileSync84(catalogPath, "utf-8"));
102359
- const skills = catalog5.skills ?? [];
102360
- const coreSkills = skills.filter((s3) => s3.tier <= 2);
102388
+ const skills2 = catalog5.skills ?? [];
102389
+ const coreSkills = skills2.filter((s3) => s3.tier <= 2);
102361
102390
  const installed = [];
102362
102391
  for (const skill of coreSkills) {
102363
- const skillSourceDir = dirname31(join118(ctSkillsRoot, skill.path));
102392
+ const skillSourceDir = dirname32(join118(ctSkillsRoot, skill.path));
102364
102393
  if (!existsSync116(skillSourceDir)) {
102365
102394
  continue;
102366
102395
  }
@@ -102465,7 +102494,7 @@ async function updateDocs() {
102465
102494
  }
102466
102495
  async function initProject(opts = {}) {
102467
102496
  const cleoDir = getCleoDirAbsolute();
102468
- const projRoot = dirname31(cleoDir);
102497
+ const projRoot = dirname32(cleoDir);
102469
102498
  const alreadyInitialized = existsSync116(cleoDir) && (existsSync116(join118(cleoDir, "tasks.db")) || existsSync116(join118(cleoDir, "config.json")));
102470
102499
  if (alreadyInitialized && !opts.force) {
102471
102500
  throw new CleoError(
@@ -102831,10 +102860,10 @@ async function deployStarterBundle(cleoDir, created, warnings) {
102831
102860
  if (hasCantFiles) return;
102832
102861
  let starterBundleSrc = null;
102833
102862
  try {
102834
- const { createRequire: createRequire24 } = await import("node:module");
102835
- const req = createRequire24(import.meta.url);
102863
+ const { createRequire: createRequire23 } = await import("node:module");
102864
+ const req = createRequire23(import.meta.url);
102836
102865
  const cleoOsPkgMain = req.resolve("@cleocode/cleo-os/package.json");
102837
- const cleoOsPkgRoot = dirname31(cleoOsPkgMain);
102866
+ const cleoOsPkgRoot = dirname32(cleoOsPkgMain);
102838
102867
  const candidate = join118(cleoOsPkgRoot, "starter-bundle");
102839
102868
  if (existsSync116(candidate)) {
102840
102869
  starterBundleSrc = candidate;
@@ -103074,8 +103103,8 @@ async function ensureCleoSymlink(ctx) {
103074
103103
  }
103075
103104
  async function writeTemplateTo(content, destPath, isDryRun) {
103076
103105
  if (isDryRun) return false;
103077
- const { dirname: dirname44 } = await import("node:path");
103078
- await mkdir21(dirname44(destPath), { recursive: true });
103106
+ const { dirname: dirname46 } = await import("node:path");
103107
+ await mkdir21(dirname46(destPath), { recursive: true });
103079
103108
  await writeFile13(destPath, content);
103080
103109
  return true;
103081
103110
  }
@@ -103540,12 +103569,12 @@ async function serializeSession(projectRoot, options = {}, accessor) {
103540
103569
  const acc = accessor ?? await getAccessor(projectRoot);
103541
103570
  const maxObs = options.maxObservations ?? 10;
103542
103571
  const maxDescLen = options.maxDescriptionLength ?? 500;
103543
- const sessions2 = await acc.loadSessions();
103572
+ const sessions3 = await acc.loadSessions();
103544
103573
  let session;
103545
103574
  if (options.sessionId) {
103546
- session = sessions2.find((s3) => s3.id === options.sessionId);
103575
+ session = sessions3.find((s3) => s3.id === options.sessionId);
103547
103576
  } else {
103548
- session = sessions2.filter((s3) => s3.status === "active").sort((a, b2) => new Date(b2.startedAt).getTime() - new Date(a.startedAt).getTime())[0];
103577
+ session = sessions3.filter((s3) => s3.status === "active").sort((a, b2) => new Date(b2.startedAt).getTime() - new Date(a.startedAt).getTime())[0];
103549
103578
  }
103550
103579
  if (!session) {
103551
103580
  throw new CleoError(
@@ -103626,9 +103655,9 @@ async function restoreSession(projectRoot, snapshot, options = {}, accessor) {
103626
103655
  const acc = accessor ?? await getAccessor(projectRoot);
103627
103656
  const activate = options.activate ?? true;
103628
103657
  if (activate) {
103629
- const sessions2 = await acc.loadSessions();
103658
+ const sessions3 = await acc.loadSessions();
103630
103659
  const scope = snapshot.session.scope;
103631
- const activeConflict = sessions2.find(
103660
+ const activeConflict = sessions3.find(
103632
103661
  (s3) => s3.status === "active" && s3.scope.type === scope.type && s3.scope.epicId === scope.epicId && s3.id !== snapshot.session.id
103633
103662
  );
103634
103663
  if (activeConflict) {
@@ -105288,7 +105317,7 @@ __export(attachment_store_exports, {
105288
105317
  import { createHash as createHash21, randomUUID as randomUUID10 } from "node:crypto";
105289
105318
  import { mkdir as mkdir22, readFile as readFile25, rm as rm3, writeFile as writeFile14 } from "node:fs/promises";
105290
105319
  import { join as join121 } from "node:path";
105291
- import { and as and12, eq as eq15, sql as sql14 } from "drizzle-orm";
105320
+ import { and as and12, eq as eq15, sql as sql15 } from "drizzle-orm";
105292
105321
  function extFromMime(mime) {
105293
105322
  const base = mime.split(";")[0]?.trim() ?? mime;
105294
105323
  return MIME_TO_EXT[base] ?? ".bin";
@@ -105396,7 +105425,7 @@ function createAttachmentStore() {
105396
105425
  attachedAt: (/* @__PURE__ */ new Date()).toISOString(),
105397
105426
  attachedBy: attachedBy ?? null
105398
105427
  }).run();
105399
- await db.update(attachments).set({ refCount: sql14`ref_count + 1` }).where(eq15(attachments.id, attachmentId)).run();
105428
+ await db.update(attachments).set({ refCount: sql15`ref_count + 1` }).where(eq15(attachments.id, attachmentId)).run();
105400
105429
  nativeDb.prepare("COMMIT").run();
105401
105430
  if (wasNew) {
105402
105431
  await mkdir22(join121(filePath, ".."), { recursive: true });
@@ -105471,7 +105500,7 @@ function createAttachmentStore() {
105471
105500
  attachedAt: (/* @__PURE__ */ new Date()).toISOString(),
105472
105501
  attachedBy: attachedBy ?? null
105473
105502
  }).run();
105474
- await db.update(attachments).set({ refCount: sql14`ref_count + 1` }).where(eq15(attachments.id, attachmentId)).run();
105503
+ await db.update(attachments).set({ refCount: sql15`ref_count + 1` }).where(eq15(attachments.id, attachmentId)).run();
105475
105504
  nativeDb.prepare("COMMIT").run();
105476
105505
  } catch (err) {
105477
105506
  try {
@@ -105511,7 +105540,7 @@ function createAttachmentStore() {
105511
105540
  }
105512
105541
  return { status: "removed" };
105513
105542
  }
105514
- await db.update(attachments).set({ refCount: sql14`ref_count - 1` }).where(eq15(attachments.id, attachmentId)).run();
105543
+ await db.update(attachments).set({ refCount: sql15`ref_count - 1` }).where(eq15(attachments.id, attachmentId)).run();
105515
105544
  nativeDb.prepare("COMMIT").run();
105516
105545
  return { status: "derefd", refCountAfter: newCount };
105517
105546
  } catch (err) {
@@ -105799,8 +105828,8 @@ var init_llmtxt_blob_adapter = __esm({
105799
105828
  db = this.opts.db;
105800
105829
  } else {
105801
105830
  const { drizzle: drizzle2, NodeSqliteDatabase } = await loadDrizzle();
105802
- const { mkdir: mkdir28 } = await import("node:fs/promises");
105803
- await mkdir28(path6.dirname(manifestDbPath), { recursive: true });
105831
+ const { mkdir: mkdir29 } = await import("node:fs/promises");
105832
+ await mkdir29(path6.dirname(manifestDbPath), { recursive: true });
105804
105833
  const nativeDb = new NodeSqliteDatabase(manifestDbPath);
105805
105834
  this.ownedNativeDb = nativeDb;
105806
105835
  db = drizzle2({ client: nativeDb });
@@ -105947,7 +105976,7 @@ var init_blob_ops = __esm({
105947
105976
  // packages/core/src/docs/docs-ops.ts
105948
105977
  import { createHash as createHash22 } from "node:crypto";
105949
105978
  import { mkdir as mkdir23 } from "node:fs/promises";
105950
- import { dirname as dirname32, isAbsolute as isAbsolute4, join as join122 } from "node:path";
105979
+ import { dirname as dirname33, isAbsolute as isAbsolute4, join as join122 } from "node:path";
105951
105980
  function throwUnavailable(primitive, cause) {
105952
105981
  const msg = `LLMTXT_PRIMITIVE_UNAVAILABLE: cannot import "${primitive}". Requires llmtxt >= ${REQUIRED_LLMTXT_VERSION}. Install with: pnpm add llmtxt@${REQUIRED_LLMTXT_VERSION}`;
105953
105982
  const err = new Error(msg);
@@ -106156,7 +106185,7 @@ async function publishDocs(opts) {
106156
106185
  }
106157
106186
  const publishedPath = isAbsolute4(opts.toPath) ? opts.toPath : join122(root, opts.toPath);
106158
106187
  const tmpPath = `${publishedPath}.cleo-publish-tmp`;
106159
- await mkdir23(dirname32(publishedPath), { recursive: true });
106188
+ await mkdir23(dirname33(publishedPath), { recursive: true });
106160
106189
  const { writeFile: writeFile18, rename: rename3 } = await import("node:fs/promises");
106161
106190
  await writeFile18(tmpPath, bytes);
106162
106191
  await rename3(tmpPath, publishedPath);
@@ -109004,7 +109033,7 @@ var init_brain_export = __esm({
109004
109033
  });
109005
109034
 
109006
109035
  // packages/core/src/memory/brain-purge.ts
109007
- import { inArray as inArray6, ne as ne3, sql as sql15 } from "drizzle-orm";
109036
+ import { inArray as inArray6, ne as ne3, sql as sql16 } from "drizzle-orm";
109008
109037
  function countRowsNative(tableName) {
109009
109038
  const nativeDb = getBrainNativeDb();
109010
109039
  if (!nativeDb) return 0;
@@ -109026,7 +109055,7 @@ async function purgeBrainNoise(projectRoot) {
109026
109055
  console.log(` Learnings: ${beforeLearnings}`);
109027
109056
  console.log(` Decisions: ${beforeDecisions}`);
109028
109057
  console.log(` Observations: ${beforeObservations}`);
109029
- const realDecision = await db.select().from(brainDecisions).where(sql15`id = 'D-mntpeeer'`);
109058
+ const realDecision = await db.select().from(brainDecisions).where(sql16`id = 'D-mntpeeer'`);
109030
109059
  if (realDecision.length === 0) {
109031
109060
  throw new Error(
109032
109061
  "SAFETY ABORT: D-mntpeeer not found in brain_decisions. Backup and restore required."
@@ -109173,9 +109202,9 @@ var init_brain_purge = __esm({
109173
109202
 
109174
109203
  // packages/core/src/memory/claude-mem-migration.ts
109175
109204
  import { existsSync as existsSync119 } from "node:fs";
109176
- import { createRequire as createRequire18 } from "node:module";
109177
- function typedAll3(db, sql18) {
109178
- return db.prepare(sql18).all();
109205
+ import { createRequire as createRequire17 } from "node:module";
109206
+ function typedAll3(db, sql19) {
109207
+ return db.prepare(sql19).all();
109179
109208
  }
109180
109209
  function mapObservationType(type2) {
109181
109210
  if (VALID_OBSERVATION_TYPES.has(type2)) {
@@ -109396,15 +109425,15 @@ Use --source <path> to specify a custom location.`
109396
109425
  }
109397
109426
  return result;
109398
109427
  }
109399
- var _require16, DatabaseSync7, VALID_OBSERVATION_TYPES;
109428
+ var _require15, DatabaseSync7, VALID_OBSERVATION_TYPES;
109400
109429
  var init_claude_mem_migration = __esm({
109401
109430
  "packages/core/src/memory/claude-mem-migration.ts"() {
109402
109431
  "use strict";
109403
109432
  init_paths();
109404
109433
  init_memory_sqlite();
109405
109434
  init_brain_search();
109406
- _require16 = createRequire18(import.meta.url);
109407
- ({ DatabaseSync: DatabaseSync7 } = _require16("node:sqlite"));
109435
+ _require15 = createRequire17(import.meta.url);
109436
+ ({ DatabaseSync: DatabaseSync7 } = _require15("node:sqlite"));
109408
109437
  VALID_OBSERVATION_TYPES = /* @__PURE__ */ new Set([
109409
109438
  "discovery",
109410
109439
  "change",
@@ -112247,7 +112276,7 @@ var init_hooks_augment = __esm({
112247
112276
  });
112248
112277
 
112249
112278
  // packages/core/src/nexus/plasticity-queries.ts
112250
- import { sql as sql16 } from "drizzle-orm";
112279
+ import { sql as sql17 } from "drizzle-orm";
112251
112280
  function emptyResult(key, note) {
112252
112281
  return { [key]: [], count: 0, note };
112253
112282
  }
@@ -112256,7 +112285,7 @@ async function getHotPaths(_projectRoot, limit = 20) {
112256
112285
  if (!db) {
112257
112286
  return emptyResult("paths", "nexus database not initialised");
112258
112287
  }
112259
- const stmt = sql16`
112288
+ const stmt = sql17`
112260
112289
  SELECT source_id AS sourceId,
112261
112290
  target_id AS targetId,
112262
112291
  type AS type,
@@ -112287,7 +112316,7 @@ async function getHotNodes(_projectRoot, limit = 20) {
112287
112316
  if (!db) {
112288
112317
  return emptyResult("nodes", "nexus database not initialised");
112289
112318
  }
112290
- const stmt = sql16`
112319
+ const stmt = sql17`
112291
112320
  SELECT r.source_id AS sourceId,
112292
112321
  COALESCE(n.label, r.source_id) AS label,
112293
112322
  n.file_path AS filePath,
@@ -112322,7 +112351,7 @@ async function getColdSymbols(_projectRoot, thresholdDays = 30) {
112322
112351
  return { symbols: [], count: 0, thresholdDays, note: "nexus database not initialised" };
112323
112352
  }
112324
112353
  const cutoff = new Date(Date.now() - thresholdDays * 864e5).toISOString();
112325
- const stmt = sql16`
112354
+ const stmt = sql17`
112326
112355
  SELECT r.source_id AS sourceId,
112327
112356
  COALESCE(n.label, r.source_id) AS label,
112328
112357
  n.file_path AS filePath,
@@ -115943,7 +115972,7 @@ var init_t310_readiness = __esm({
115943
115972
  // packages/core/src/store/backup-pack.ts
115944
115973
  import crypto5 from "node:crypto";
115945
115974
  import fs9 from "node:fs";
115946
- import { createRequire as createRequire19 } from "node:module";
115975
+ import { createRequire as createRequire18 } from "node:module";
115947
115976
  import os3 from "node:os";
115948
115977
  import path7 from "node:path";
115949
115978
  function resolveContractsSchemasDir() {
@@ -116371,7 +116400,7 @@ async function packBundle(input) {
116371
116400
  }
116372
116401
  }
116373
116402
  }
116374
- var _require17, DatabaseSync8;
116403
+ var _require16, DatabaseSync8;
116375
116404
  var init_backup_pack = __esm({
116376
116405
  "packages/core/src/store/backup-pack.ts"() {
116377
116406
  "use strict";
@@ -116383,8 +116412,8 @@ var init_backup_pack = __esm({
116383
116412
  init_nexus_sqlite();
116384
116413
  init_signaldock_sqlite();
116385
116414
  init_t310_readiness();
116386
- _require17 = createRequire19(import.meta.url);
116387
- ({ DatabaseSync: DatabaseSync8 } = _require17("node:sqlite"));
116415
+ _require16 = createRequire18(import.meta.url);
116416
+ ({ DatabaseSync: DatabaseSync8 } = _require16("node:sqlite"));
116388
116417
  }
116389
116418
  });
116390
116419
 
@@ -116452,7 +116481,7 @@ var init_cleanup_legacy = __esm({
116452
116481
 
116453
116482
  // packages/core/src/store/migrate-signaldock-to-conduit.ts
116454
116483
  import { existsSync as existsSync126, mkdirSync as mkdirSync32, renameSync as renameSync10, unlinkSync as unlinkSync10 } from "node:fs";
116455
- import { createRequire as createRequire20 } from "node:module";
116484
+ import { createRequire as createRequire19 } from "node:module";
116456
116485
  import { join as join129 } from "node:path";
116457
116486
  function needsSignaldockToConduitMigration(projectRoot) {
116458
116487
  const legacyPath = join129(projectRoot, ".cleo", "signaldock.db");
@@ -116783,7 +116812,7 @@ function migrateSignaldockToConduit(projectRoot) {
116783
116812
  result.status = "migrated";
116784
116813
  return result;
116785
116814
  }
116786
- var _require18, DatabaseSync9, PROJECT_TIER_TABLES, GLOBAL_IDENTITY_TABLES;
116815
+ var _require17, DatabaseSync9, PROJECT_TIER_TABLES, GLOBAL_IDENTITY_TABLES;
116787
116816
  var init_migrate_signaldock_to_conduit = __esm({
116788
116817
  "packages/core/src/store/migrate-signaldock-to-conduit.ts"() {
116789
116818
  "use strict";
@@ -116792,8 +116821,8 @@ var init_migrate_signaldock_to_conduit = __esm({
116792
116821
  init_conduit_sqlite();
116793
116822
  init_global_salt();
116794
116823
  init_signaldock_sqlite();
116795
- _require18 = createRequire20(import.meta.url);
116796
- ({ DatabaseSync: DatabaseSync9 } = _require18("node:sqlite"));
116824
+ _require17 = createRequire19(import.meta.url);
116825
+ ({ DatabaseSync: DatabaseSync9 } = _require17("node:sqlite"));
116797
116826
  PROJECT_TIER_TABLES = [
116798
116827
  "messages",
116799
116828
  "conversations",
@@ -116842,7 +116871,7 @@ import { and as and14, desc as desc7, eq as eq18, isNull as isNull4 } from "driz
116842
116871
  async function createSession(session, cwd) {
116843
116872
  const db = await getDb(cwd);
116844
116873
  const tw = session.taskWork;
116845
- db.insert(sessions).values({
116874
+ db.insert(sessions2).values({
116846
116875
  id: session.id,
116847
116876
  name: session.name,
116848
116877
  status: session.status,
@@ -116860,7 +116889,7 @@ async function createSession(session, cwd) {
116860
116889
  }
116861
116890
  async function getSession(sessionId, cwd) {
116862
116891
  const db = await getDb(cwd);
116863
- const rows = await db.select().from(sessions).where(eq18(sessions.id, sessionId)).all();
116892
+ const rows = await db.select().from(sessions2).where(eq18(sessions2.id, sessionId)).all();
116864
116893
  if (rows.length === 0) return null;
116865
116894
  return rowToSession(rows[0]);
116866
116895
  }
@@ -116889,16 +116918,16 @@ async function updateSession(sessionId, updates, cwd) {
116889
116918
  updateRow.handoffConsumedBy = updates.handoffConsumedBy;
116890
116919
  if (updates.debriefJson !== void 0) updateRow.debriefJson = updates.debriefJson;
116891
116920
  if (updates.handoffJson !== void 0) updateRow.handoffJson = updates.handoffJson;
116892
- db.update(sessions).set(updateRow).where(eq18(sessions.id, sessionId)).run();
116921
+ db.update(sessions2).set(updateRow).where(eq18(sessions2.id, sessionId)).run();
116893
116922
  return getSession(sessionId, cwd);
116894
116923
  }
116895
116924
  async function listSessions2(filters, cwd) {
116896
116925
  const db = await getDb(cwd);
116897
116926
  const conditions = [];
116898
116927
  if (filters?.active) {
116899
- conditions.push(eq18(sessions.status, "active"));
116928
+ conditions.push(eq18(sessions2.status, "active"));
116900
116929
  }
116901
- const query = db.select().from(sessions).where(conditions.length > 0 ? and14(...conditions) : void 0).orderBy(desc7(sessions.startedAt));
116930
+ const query = db.select().from(sessions2).where(conditions.length > 0 ? and14(...conditions) : void 0).orderBy(desc7(sessions2.startedAt));
116902
116931
  const rows = filters?.limit ? await query.limit(filters.limit).all() : await query.all();
116903
116932
  return rows.map(rowToSession);
116904
116933
  }
@@ -116926,14 +116955,14 @@ async function startTask2(sessionId, taskId, cwd) {
116926
116955
  )
116927
116956
  ).run();
116928
116957
  db.insert(taskWorkHistory).values({ sessionId, taskId, setAt: now2 }).run();
116929
- db.update(sessions).set({ currentTask: taskId, taskStartedAt: now2 }).where(eq18(sessions.id, sessionId)).run();
116958
+ db.update(sessions2).set({ currentTask: taskId, taskStartedAt: now2 }).where(eq18(sessions2.id, sessionId)).run();
116930
116959
  }
116931
116960
  async function getCurrentTask(sessionId, cwd) {
116932
116961
  const db = await getDb(cwd);
116933
116962
  const rows = await db.select({
116934
- currentTask: sessions.currentTask,
116935
- taskStartedAt: sessions.taskStartedAt
116936
- }).from(sessions).where(eq18(sessions.id, sessionId)).all();
116963
+ currentTask: sessions2.currentTask,
116964
+ taskStartedAt: sessions2.taskStartedAt
116965
+ }).from(sessions2).where(eq18(sessions2.id, sessionId)).all();
116937
116966
  if (rows.length === 0) return { taskId: null, since: null };
116938
116967
  return { taskId: rows[0].currentTask, since: rows[0].taskStartedAt };
116939
116968
  }
@@ -116946,7 +116975,7 @@ async function stopTask2(sessionId, cwd) {
116946
116975
  isNull4(taskWorkHistory.clearedAt)
116947
116976
  )
116948
116977
  ).run();
116949
- db.update(sessions).set({ currentTask: null, taskStartedAt: null }).where(eq18(sessions.id, sessionId)).run();
116978
+ db.update(sessions2).set({ currentTask: null, taskStartedAt: null }).where(eq18(sessions2.id, sessionId)).run();
116950
116979
  }
116951
116980
  async function workHistory(sessionId, limit = 50, cwd) {
116952
116981
  const db = await getDb(cwd);
@@ -116961,16 +116990,16 @@ async function gcSessions2(maxAgeDays = 30, cwd) {
116961
116990
  const db = await getDb(cwd);
116962
116991
  const threshold = /* @__PURE__ */ new Date();
116963
116992
  threshold.setDate(threshold.getDate() - maxAgeDays);
116964
- const before = await db.select({ id: sessions.id }).from(sessions).where(and14(eq18(sessions.status, "ended"))).all();
116993
+ const before = await db.select({ id: sessions2.id }).from(sessions2).where(and14(eq18(sessions2.status, "ended"))).all();
116965
116994
  const toUpdate = before;
116966
116995
  if (toUpdate.length > 0) {
116967
- db.update(sessions).set({ status: "orphaned" }).where(eq18(sessions.status, "ended")).run();
116996
+ db.update(sessions2).set({ status: "orphaned" }).where(eq18(sessions2.status, "ended")).run();
116968
116997
  }
116969
116998
  return toUpdate.length;
116970
116999
  }
116971
117000
  async function getActiveSession(cwd) {
116972
117001
  const db = await getDb(cwd);
116973
- const rows = await db.select().from(sessions).where(eq18(sessions.status, "active")).orderBy(desc7(sessions.startedAt)).limit(1).all();
117002
+ const rows = await db.select().from(sessions2).where(eq18(sessions2.status, "active")).orderBy(desc7(sessions2.startedAt)).limit(1).all();
116974
117003
  if (rows.length === 0) return null;
116975
117004
  return rowToSession(rows[0]);
116976
117005
  }
@@ -117139,7 +117168,7 @@ __export(task_store_exports, {
117139
117168
  updateTask: () => updateTask2,
117140
117169
  updateTaskSafe: () => updateTaskSafe
117141
117170
  });
117142
- import { and as and15, asc as asc4, count as count4, eq as eq20, inArray as inArray7, isNull as isNull5, ne as ne5, sql as sql17 } from "drizzle-orm";
117171
+ import { and as and15, asc as asc4, count as count4, eq as eq20, inArray as inArray7, isNull as isNull5, ne as ne5, sql as sql18 } from "drizzle-orm";
117143
117172
  async function insertTaskRow(task, cwd) {
117144
117173
  const db = await getDb(cwd);
117145
117174
  const row = taskToRow(task);
@@ -117242,7 +117271,7 @@ async function findTasks2(query, limit = 20, cwd) {
117242
117271
  const rows = await db.select().from(tasks).where(
117243
117272
  and15(
117244
117273
  ne5(tasks.status, "archived"),
117245
- sql17`(${tasks.id} LIKE ${pattern} OR ${tasks.title} LIKE ${pattern} OR ${tasks.description} LIKE ${pattern})`
117274
+ sql18`(${tasks.id} LIKE ${pattern} OR ${tasks.title} LIKE ${pattern} OR ${tasks.description} LIKE ${pattern})`
117246
117275
  )
117247
117276
  ).limit(limit).all();
117248
117277
  return rows.map(rowToTask);
@@ -118264,11 +118293,11 @@ async function coreTaskHistory(projectRoot, taskId, limit) {
118264
118293
  try {
118265
118294
  const { getDb: getDb5 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
118266
118295
  const { auditLog: auditLog2 } = await Promise.resolve().then(() => (init_tasks_schema(), tasks_schema_exports));
118267
- const { sql: sql18 } = await import("drizzle-orm");
118296
+ const { sql: sql19 } = await import("drizzle-orm");
118268
118297
  const db = await getDb5(projectRoot);
118269
118298
  const maxRows = limit && limit > 0 ? limit : 100;
118270
118299
  const rows = await db.all(
118271
- sql18`SELECT * FROM ${auditLog2}
118300
+ sql19`SELECT * FROM ${auditLog2}
118272
118301
  WHERE ${auditLog2.taskId} = ${taskId}
118273
118302
  ORDER BY ${auditLog2.timestamp} DESC
118274
118303
  LIMIT ${maxRows}`
@@ -118594,7 +118623,7 @@ __export(migration_sqlite_exports, {
118594
118623
  migrateJsonToSqliteAtomic: () => migrateJsonToSqliteAtomic
118595
118624
  });
118596
118625
  import { existsSync as existsSync127, mkdirSync as mkdirSync33, readFileSync as readFileSync91 } from "node:fs";
118597
- import { dirname as dirname33, join as join130 } from "node:path";
118626
+ import { dirname as dirname34, join as join130 } from "node:path";
118598
118627
  function topoSortTasks(tasks2) {
118599
118628
  const taskMap = new Map(tasks2.map((t) => [t.id, t]));
118600
118629
  const sorted = [];
@@ -118628,7 +118657,7 @@ function topoSortTasks(tasks2) {
118628
118657
  function countJsonRecords(cleoDir) {
118629
118658
  let tasks2 = 0;
118630
118659
  let archived = 0;
118631
- let sessions2 = 0;
118660
+ let sessions3 = 0;
118632
118661
  const todoPath = join130(cleoDir, "todo.json");
118633
118662
  if (existsSync127(todoPath)) {
118634
118663
  try {
@@ -118649,11 +118678,11 @@ function countJsonRecords(cleoDir) {
118649
118678
  if (existsSync127(sessionsPath)) {
118650
118679
  try {
118651
118680
  const data = JSON.parse(readFileSync91(sessionsPath, "utf-8"));
118652
- sessions2 = (data.sessions ?? []).length;
118681
+ sessions3 = (data.sessions ?? []).length;
118653
118682
  } catch {
118654
118683
  }
118655
118684
  }
118656
- return { tasks: tasks2, archived, sessions: sessions2 };
118685
+ return { tasks: tasks2, archived, sessions: sessions3 };
118657
118686
  }
118658
118687
  async function migrateJsonToSqliteAtomic(cwd, tempDbPath, logger) {
118659
118688
  const cleoDir = getCleoDirAbsolute(cwd);
@@ -118672,12 +118701,12 @@ async function migrateJsonToSqliteAtomic(cwd, tempDbPath, logger) {
118672
118701
  closeDb2();
118673
118702
  try {
118674
118703
  logger?.info("import", "init", "Initializing node:sqlite for migration");
118675
- mkdirSync33(dirname33(tempDbPath), { recursive: true });
118704
+ mkdirSync33(dirname34(tempDbPath), { recursive: true });
118676
118705
  const nativeDb = openNativeDatabase(tempDbPath, { enableWal: true });
118677
118706
  const db = drizzle({ client: nativeDb, schema: tasks_schema_exports });
118678
118707
  logger?.info("import", "create-tables", "Running drizzle migrations to create tables");
118679
118708
  const migrationsFolder = resolveMigrationsFolder();
118680
- migrate(db, { migrationsFolder });
118709
+ migrateSanitized(db, { migrationsFolder });
118681
118710
  if (process.env.VITEST) {
118682
118711
  nativeDb.exec("PRAGMA foreign_keys=OFF");
118683
118712
  }
@@ -118873,18 +118902,18 @@ async function runMigrationDataImport(db, cleoDir, result, logger) {
118873
118902
  path: sessionsPath.replace(cleoDir, ".")
118874
118903
  });
118875
118904
  const sessionsData = JSON.parse(readFileSync91(sessionsPath, "utf-8"));
118876
- const sessions2 = sessionsData.sessions ?? [];
118877
- const totalSessions = sessions2.length;
118905
+ const sessions3 = sessionsData.sessions ?? [];
118906
+ const totalSessions = sessions3.length;
118878
118907
  logger?.info("import", "sessions-start", `Starting import of ${totalSessions} sessions`, {
118879
118908
  totalSessions
118880
118909
  });
118881
- for (let i = 0; i < sessions2.length; i++) {
118882
- const session = sessions2[i];
118910
+ for (let i = 0; i < sessions3.length; i++) {
118911
+ const session = sessions3[i];
118883
118912
  try {
118884
118913
  const validStatuses = ["active", "ended", "orphaned", "suspended"];
118885
118914
  const normalizedStatus = validStatuses.includes(session.status) ? session.status : "ended";
118886
118915
  const normalizedName = session.name || `session-${session.id}`;
118887
- await db.insert(sessions).values({
118916
+ await db.insert(sessions2).values({
118888
118917
  id: session.id,
118889
118918
  name: normalizedName,
118890
118919
  status: normalizedStatus,
@@ -118899,7 +118928,7 @@ async function runMigrationDataImport(db, cleoDir, result, logger) {
118899
118928
  endedAt: session.endedAt
118900
118929
  }).onConflictDoNothing().run();
118901
118930
  result.sessionsImported++;
118902
- if ((i + 1) % 10 === 0 || i === sessions2.length - 1) {
118931
+ if ((i + 1) % 10 === 0 || i === sessions3.length - 1) {
118903
118932
  logger?.logImportProgress("import", "sessions", result.sessionsImported, totalSessions);
118904
118933
  }
118905
118934
  } catch (err) {
@@ -118945,7 +118974,7 @@ async function migrateJsonToSqlite2(cwd, options) {
118945
118974
  const db2 = await getDb(cwd);
118946
118975
  const tasksResult = await db2.select({ count: count5() }).from(tasks).where(ne6(tasks.status, "archived")).get();
118947
118976
  const archivedResult = await db2.select({ count: count5() }).from(tasks).where(eq22(tasks.status, "archived")).get();
118948
- const sessionsResult = await db2.select({ count: count5() }).from(sessions).get();
118977
+ const sessionsResult = await db2.select({ count: count5() }).from(sessions2).get();
118949
118978
  const existingCounts = {
118950
118979
  tasks: tasksResult?.count ?? 0,
118951
118980
  archived: archivedResult?.count ?? 0,
@@ -119095,13 +119124,13 @@ async function migrateJsonToSqlite2(cwd, options) {
119095
119124
  if (existsSync127(sessionsPath)) {
119096
119125
  try {
119097
119126
  const sessionsData = JSON.parse(readFileSync91(sessionsPath, "utf-8"));
119098
- const sessions2 = sessionsData.sessions ?? [];
119099
- for (const session of sessions2) {
119127
+ const sessions3 = sessionsData.sessions ?? [];
119128
+ for (const session of sessions3) {
119100
119129
  try {
119101
119130
  const validStatuses = ["active", "ended", "orphaned", "suspended"];
119102
119131
  const normalizedStatus = validStatuses.includes(session.status) ? session.status : "ended";
119103
119132
  const normalizedName = session.name || `session-${session.id}`;
119104
- db.insert(sessions).values({
119133
+ db.insert(sessions2).values({
119105
119134
  id: session.id,
119106
119135
  name: normalizedName,
119107
119136
  status: normalizedStatus,
@@ -119144,15 +119173,15 @@ async function exportToJson(cwd) {
119144
119173
  updatedAt: row.updatedAt,
119145
119174
  completedAt: row.completedAt ?? void 0
119146
119175
  }));
119147
- const sessions2 = await listSessions3(void 0, cwd);
119148
- return { tasks: tasks2, archived, sessions: sessions2 };
119176
+ const sessions3 = await listSessions3(void 0, cwd);
119177
+ return { tasks: tasks2, archived, sessions: sessions3 };
119149
119178
  }
119150
119179
  var init_migration_sqlite = __esm({
119151
119180
  "packages/core/src/store/migration-sqlite.ts"() {
119152
119181
  "use strict";
119153
119182
  init_node_sqlite();
119154
- init_migrator2();
119155
119183
  init_paths();
119184
+ init_migration_manager();
119156
119185
  init_sqlite2();
119157
119186
  init_tasks_schema();
119158
119187
  }
@@ -119196,10 +119225,10 @@ async function repairMissingSizes(cwd, dryRun) {
119196
119225
  async function repairMissingCompletedAt(cwd, dryRun) {
119197
119226
  const { getDb: getDb5 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
119198
119227
  const { tasks: tasks2 } = await Promise.resolve().then(() => (init_tasks_schema(), tasks_schema_exports));
119199
- const { sql: sql18 } = await import("drizzle-orm");
119228
+ const { sql: sql19 } = await import("drizzle-orm");
119200
119229
  const db = await getDb5(cwd);
119201
119230
  const affected = await db.select({ id: tasks2.id }).from(tasks2).where(
119202
- sql18`(${tasks2.status} = 'done' OR ${tasks2.status} = 'cancelled') AND ${tasks2.completedAt} IS NULL`
119231
+ sql19`(${tasks2.status} = 'done' OR ${tasks2.status} = 'cancelled') AND ${tasks2.completedAt} IS NULL`
119203
119232
  );
119204
119233
  if (affected.length === 0) {
119205
119234
  return {
@@ -119217,7 +119246,7 @@ async function repairMissingCompletedAt(cwd, dryRun) {
119217
119246
  }
119218
119247
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
119219
119248
  await db.update(tasks2).set({ completedAt: now2 }).where(
119220
- sql18`(${tasks2.status} = 'done' OR ${tasks2.status} = 'cancelled') AND ${tasks2.completedAt} IS NULL`
119249
+ sql19`(${tasks2.status} = 'done' OR ${tasks2.status} = 'cancelled') AND ${tasks2.completedAt} IS NULL`
119221
119250
  );
119222
119251
  return {
119223
119252
  action: "fix_completed_at",
@@ -119228,8 +119257,8 @@ async function repairMissingCompletedAt(cwd, dryRun) {
119228
119257
  async function repairMissingColumns(cwd, dryRun) {
119229
119258
  const { getDb: getDb5 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
119230
119259
  const db = await getDb5(cwd);
119231
- const { sql: sql18 } = await import("drizzle-orm");
119232
- const columns = db.all(sql18`PRAGMA table_info(tasks)`);
119260
+ const { sql: sql19 } = await import("drizzle-orm");
119261
+ const columns = db.all(sql19`PRAGMA table_info(tasks)`);
119233
119262
  const existingCols = new Set(columns.map((c) => c.name));
119234
119263
  const missingCols = ["pipeline_stage"].filter((c) => !existingCols.has(c));
119235
119264
  if (missingCols.length === 0) {
@@ -119247,7 +119276,7 @@ async function repairMissingColumns(cwd, dryRun) {
119247
119276
  };
119248
119277
  }
119249
119278
  for (const col of missingCols) {
119250
- db.run(sql18.raw(`ALTER TABLE tasks ADD COLUMN ${col} text`));
119279
+ db.run(sql19.raw(`ALTER TABLE tasks ADD COLUMN ${col} text`));
119251
119280
  }
119252
119281
  return {
119253
119282
  action: "fix_missing_columns",
@@ -122003,7 +122032,7 @@ var init_schema_validator = __esm({
122003
122032
  // packages/core/src/validation/validate-ops.ts
122004
122033
  import { execFileSync as execFileSync14 } from "node:child_process";
122005
122034
  import { appendFileSync as appendFileSync11, existsSync as existsSync132, mkdirSync as mkdirSync35, readFileSync as readFileSync97 } from "node:fs";
122006
- import { dirname as dirname34, join as join132, resolve as resolve15 } from "node:path";
122035
+ import { dirname as dirname35, join as join132, resolve as resolve15 } from "node:path";
122007
122036
  function readJsonFile2(filePath) {
122008
122037
  try {
122009
122038
  const raw = readFileSync97(filePath, "utf-8");
@@ -122311,7 +122340,7 @@ function coreComplianceRecord(taskId, result, protocol, violations, projectRoot)
122311
122340
  throw new Error(`Invalid result: ${result}. Valid: ${validResults.join(", ")}`);
122312
122341
  }
122313
122342
  const compliancePath = join132(projectRoot, ".cleo", "metrics", "COMPLIANCE.jsonl");
122314
- const dir = dirname34(compliancePath);
122343
+ const dir = dirname35(compliancePath);
122315
122344
  if (!existsSync132(dir)) {
122316
122345
  mkdirSync35(dir, { recursive: true });
122317
122346
  }
@@ -122611,8 +122640,8 @@ async function buildBrainState(projectRoot, opts, accessor) {
122611
122640
  };
122612
122641
  const acc = accessor ?? await getAccessor(projectRoot);
122613
122642
  try {
122614
- const sessions2 = await acc.loadSessions();
122615
- const activeSession = sessions2.find((s3) => s3.status === "active");
122643
+ const sessions3 = await acc.loadSessions();
122644
+ const activeSession = sessions3.find((s3) => s3.status === "active");
122616
122645
  if (activeSession) {
122617
122646
  brain.session = {
122618
122647
  id: activeSession.id,
@@ -129738,7 +129767,7 @@ var require__ = __commonJS({
129738
129767
  // packages/core/src/store/backup-unpack.ts
129739
129768
  import crypto6 from "node:crypto";
129740
129769
  import fs11 from "node:fs";
129741
- import { createRequire as createRequire21 } from "node:module";
129770
+ import { createRequire as createRequire20 } from "node:module";
129742
129771
  import os4 from "node:os";
129743
129772
  import path9 from "node:path";
129744
129773
  import { default as addFormatsImport2 } from "ajv-formats";
@@ -130000,15 +130029,15 @@ function cleanupStaging(stagingDir) {
130000
130029
  } catch {
130001
130030
  }
130002
130031
  }
130003
- var import__, _require19, DatabaseSync10, ajv2020Mod, Ajv2020, fmtMod2, addFormats3, BundleError, _ajv2020, MANIFEST_SCHEMA_ID;
130032
+ var import__, _require18, DatabaseSync10, ajv2020Mod, Ajv2020, fmtMod2, addFormats3, BundleError, _ajv2020, MANIFEST_SCHEMA_ID;
130004
130033
  var init_backup_unpack = __esm({
130005
130034
  "packages/core/src/store/backup-unpack.ts"() {
130006
130035
  "use strict";
130007
130036
  import__ = __toESM(require__(), 1);
130008
130037
  init_index_min();
130009
130038
  init_backup_crypto();
130010
- _require19 = createRequire21(import.meta.url);
130011
- ({ DatabaseSync: DatabaseSync10 } = _require19("node:sqlite"));
130039
+ _require18 = createRequire20(import.meta.url);
130040
+ ({ DatabaseSync: DatabaseSync10 } = _require18("node:sqlite"));
130012
130041
  ajv2020Mod = import__.default;
130013
130042
  Ajv2020 = typeof ajv2020Mod.default === "function" ? ajv2020Mod.default : import__.default;
130014
130043
  fmtMod2 = addFormatsImport2;
@@ -130485,11 +130514,11 @@ var init_restore_json_merge = __esm({
130485
130514
  // packages/core/src/nexus/nexus-bridge.ts
130486
130515
  import { existsSync as existsSync135, mkdirSync as mkdirSync36, readFileSync as readFileSync100, writeFileSync as writeFileSync26 } from "node:fs";
130487
130516
  import { join as join135 } from "node:path";
130488
- function typedAll4(db, sql18, ...params) {
130489
- return db.prepare(sql18).all(...params);
130517
+ function typedAll4(db, sql19, ...params) {
130518
+ return db.prepare(sql19).all(...params);
130490
130519
  }
130491
- function typedGet2(db, sql18, ...params) {
130492
- return db.prepare(sql18).get(...params);
130520
+ function typedGet2(db, sql19, ...params) {
130521
+ return db.prepare(sql19).get(...params);
130493
130522
  }
130494
130523
  function queryIndexMeta(db, projectId) {
130495
130524
  try {
@@ -131181,7 +131210,7 @@ var init_plan = __esm({
131181
131210
  import { execFileSync as execFileSync15 } from "node:child_process";
131182
131211
  import { createCipheriv, createDecipheriv, createHmac as createHmac3, randomBytes as randomBytes19 } from "node:crypto";
131183
131212
  import { chmod as chmod3, mkdir as mkdir24, readFile as readFile27, stat as stat6, writeFile as writeFile15 } from "node:fs/promises";
131184
- import { dirname as dirname35, join as join136 } from "node:path";
131213
+ import { dirname as dirname36, join as join136 } from "node:path";
131185
131214
  function getMachineKeyPath() {
131186
131215
  if (process.platform === "win32") {
131187
131216
  const appData = process.env["LOCALAPPDATA"] ?? process.env["APPDATA"];
@@ -131232,7 +131261,7 @@ async function getMachineKey() {
131232
131261
  } catch (err) {
131233
131262
  if (err instanceof Error && "code" in err && err.code === "ENOENT") {
131234
131263
  const key = randomBytes19(KEY_LENGTH);
131235
- await mkdir24(dirname35(keyPath), { recursive: true });
131264
+ await mkdir24(dirname36(keyPath), { recursive: true });
131236
131265
  await writeFile15(keyPath, key, { mode: 384 });
131237
131266
  if (process.platform === "win32") {
131238
131267
  try {
@@ -131593,7 +131622,7 @@ function parseCantAgent(source) {
131593
131622
  const lines = body.slice(headerIndex + headerMatch[0].length).split("\n");
131594
131623
  let role = null;
131595
131624
  let parent = null;
131596
- let skills = [];
131625
+ let skills2 = [];
131597
131626
  for (const rawLine of lines) {
131598
131627
  if (/^[a-zA-Z]/.test(rawLine)) break;
131599
131628
  const trimmed = rawLine.trim();
@@ -131607,10 +131636,10 @@ function parseCantAgent(source) {
131607
131636
  } else if (key === "parent") {
131608
131637
  parent = unquote(value) || null;
131609
131638
  } else if (key === "skills") {
131610
- skills = parseSkillsValue(value);
131639
+ skills2 = parseSkillsValue(value);
131611
131640
  }
131612
131641
  }
131613
- return { name: name2, role, parent, skills };
131642
+ return { name: name2, role, parent, skills: skills2 };
131614
131643
  }
131615
131644
  function unquote(raw) {
131616
131645
  if (raw.length >= 2) {
@@ -131844,6 +131873,7 @@ __export(internal_exports, {
131844
131873
  HttpTransport: () => HttpTransport,
131845
131874
  LIFECYCLE_PIPELINE_STATUSES: () => LIFECYCLE_PIPELINE_STATUSES,
131846
131875
  LIFECYCLE_STAGE_STATUSES: () => LIFECYCLE_STAGE_STATUSES,
131876
+ LifecycleScopeDeniedError: () => LifecycleScopeDeniedError,
131847
131877
  MANIFEST_STATUSES: () => MANIFEST_STATUSES,
131848
131878
  MAX_LOOP_BACKS_PER_PHASE: () => MAX_LOOP_BACKS_PER_PHASE,
131849
131879
  MINIMUM_NODE_MAJOR: () => MINIMUM_NODE_MAJOR,
@@ -132630,6 +132660,7 @@ __export(internal_exports, {
132630
132660
  resolvePhasePrompt: () => resolvePhasePrompt,
132631
132661
  resolveProjectPath: () => resolveProjectPath,
132632
132662
  resolveProjectRoot: () => resolveProjectRoot,
132663
+ resolveSignaldockMigrationsFolder: () => resolveSignaldockMigrationsFolder,
132633
132664
  resolveSkillPathsForProvider: () => resolveSkillPathsForProvider,
132634
132665
  resolveStageAlias: () => resolveStageAlias,
132635
132666
  resolveTask: () => resolveTask,
@@ -132679,7 +132710,7 @@ __export(internal_exports, {
132679
132710
  sessionStartNext: () => sessionStartNext,
132680
132711
  sessionStatus: () => sessionStatus,
132681
132712
  sessionStatusSchema: () => sessionStatusSchema,
132682
- sessions: () => sessions,
132713
+ sessions: () => sessions2,
132683
132714
  setConfigValue: () => setConfigValue,
132684
132715
  setPermission: () => setPermission,
132685
132716
  setPhase: () => setPhase,
@@ -133565,12 +133596,12 @@ function renderCurrent(data, quiet) {
133565
133596
  function renderSession(data, quiet) {
133566
133597
  const sessionId = data["sessionId"];
133567
133598
  const status = data["status"];
133568
- const sessions2 = data["sessions"];
133569
- if (sessions2) {
133570
- if (quiet) return sessions2.map((s3) => String(s3["id"])).join("\n");
133599
+ const sessions3 = data["sessions"];
133600
+ if (sessions3) {
133601
+ if (quiet) return sessions3.map((s3) => String(s3["id"])).join("\n");
133571
133602
  const lines2 = [];
133572
- lines2.push(`${BOLD}Sessions (${sessions2.length})${NC}`);
133573
- for (const s3 of sessions2) {
133603
+ lines2.push(`${BOLD}Sessions (${sessions3.length})${NC}`);
133604
+ for (const s3 of sessions3) {
133574
133605
  const active = s3["active"];
133575
133606
  const icon = active ? `${GREEN}\u25CF${NC}` : `${DIM}\u25CB${NC}`;
133576
133607
  lines2.push(` ${icon} ${BOLD}${s3["id"]}${NC}${active ? " (active)" : ""}`);
@@ -140054,6 +140085,10 @@ var init_error3 = __esm({
140054
140085
  E_LIFECYCLE_TRANSITION_INVALID: 83,
140055
140086
  E_IVTR_INCOMPLETE: 83,
140056
140087
  E_PROVENANCE_REQUIRED: 84,
140088
+ // T1162: lifecycle scope guard — maps to ExitCode.TASK_NOT_IN_SCOPE (34)
140089
+ // because a subagent attempting to mutate a parent epic's lifecycle is
140090
+ // operating outside the scope granted by its session.
140091
+ E_LIFECYCLE_SCOPE_DENIED: 34,
140057
140092
  // Artifact Publish (85-89)
140058
140093
  E_ARTIFACT_TYPE_UNKNOWN: 85,
140059
140094
  E_ARTIFACT_VALIDATION_FAILED: 86,
@@ -140344,6 +140379,80 @@ var init_init_engine = __esm({
140344
140379
  });
140345
140380
 
140346
140381
  // packages/cleo/src/dispatch/engines/lifecycle-engine.ts
140382
+ import { appendFile as appendFile7, mkdir as mkdir25 } from "node:fs/promises";
140383
+ import { dirname as dirname37, resolve as resolvePath4 } from "node:path";
140384
+ function getForceBypassPath2(projectRoot) {
140385
+ return resolvePath4(projectRoot, ".cleo", "audit", "force-bypass.jsonl");
140386
+ }
140387
+ async function appendLifecycleScopeBypassLine(projectRoot, epicId, sessionScope, reason) {
140388
+ const path15 = getForceBypassPath2(projectRoot);
140389
+ await mkdir25(dirname37(path15), { recursive: true });
140390
+ const record2 = {
140391
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
140392
+ type: "lifecycle_scope_bypass",
140393
+ epicId,
140394
+ sessionScope,
140395
+ overrideReason: reason,
140396
+ pid: process.pid,
140397
+ command: (process.argv.slice(1).join(" ") || "cleo").slice(0, 512)
140398
+ };
140399
+ await appendFile7(path15, `${JSON.stringify(record2)}
140400
+ `, { encoding: "utf-8" });
140401
+ }
140402
+ async function enforceScopeForLifecycleMutation(epicId, projectRoot) {
140403
+ let session;
140404
+ try {
140405
+ session = await getActiveSession(projectRoot);
140406
+ } catch {
140407
+ return null;
140408
+ }
140409
+ if (!session) {
140410
+ return null;
140411
+ }
140412
+ const scope = session.scope;
140413
+ if (scope.type === "global") {
140414
+ return null;
140415
+ }
140416
+ if (scope.type === "epic") {
140417
+ const rootId = scope.rootTaskId ?? scope.epicId;
140418
+ if (rootId === epicId) {
140419
+ return null;
140420
+ }
140421
+ }
140422
+ const overrideRaw = process.env["CLEO_OWNER_OVERRIDE"];
140423
+ const overrideActive = overrideRaw === "1" || overrideRaw === "true";
140424
+ const agentRole = process.env["CLEO_AGENT_ROLE"];
140425
+ const forbiddenRoles = /* @__PURE__ */ new Set(["worker", "lead", "subagent"]);
140426
+ const overrideAllowed = overrideActive && !(agentRole && forbiddenRoles.has(agentRole));
140427
+ if (overrideAllowed) {
140428
+ const reason = (process.env["CLEO_OWNER_OVERRIDE_REASON"] ?? "").trim() || "unspecified";
140429
+ const scopeStr = scope.epicId ? `epic:${scope.epicId}` : scope.type;
140430
+ try {
140431
+ const root = projectRoot ?? process.cwd();
140432
+ await appendLifecycleScopeBypassLine(root, epicId, scopeStr, reason);
140433
+ } catch {
140434
+ }
140435
+ return null;
140436
+ }
140437
+ const scopeDesc = scope.type === "epic" && scope.epicId ? `epic:${scope.epicId}${scope.rootTaskId && scope.rootTaskId !== scope.epicId ? ` (rootTaskId: ${scope.rootTaskId})` : ""}` : scope.type;
140438
+ return engineError(
140439
+ "E_LIFECYCLE_SCOPE_DENIED",
140440
+ `Lifecycle stage advancement for epic ${epicId} requires a session scoped to that epic or an owner override. Current session scope: ${scopeDesc}. Use CLEO_OWNER_OVERRIDE=1 (with CLEO_OWNER_OVERRIDE_REASON) if this is an authorized operation.`,
140441
+ {
140442
+ fix: `Start a session scoped to the target epic: cleo session start --scope epic:${epicId}`,
140443
+ alternatives: [
140444
+ {
140445
+ action: "Start an epic-scoped session",
140446
+ command: `cleo session start --scope epic:${epicId} --name "Lifecycle work"`
140447
+ },
140448
+ {
140449
+ action: "Emergency override (audited)",
140450
+ command: `CLEO_OWNER_OVERRIDE=1 CLEO_OWNER_OVERRIDE_REASON="..." cleo lifecycle complete ${epicId} <stage>`
140451
+ }
140452
+ ]
140453
+ }
140454
+ );
140455
+ }
140347
140456
  async function lifecycleStatus(epicId, projectRoot) {
140348
140457
  if (!epicId) {
140349
140458
  return engineError("E_INVALID_INPUT", "epicId is required");
@@ -140412,6 +140521,8 @@ async function lifecycleProgress(taskId, stage, status, notes, projectRoot) {
140412
140521
  if (!taskId || !stage || !status) {
140413
140522
  return engineError("E_INVALID_INPUT", "taskId, stage, and status are required");
140414
140523
  }
140524
+ const scopeDenied = await enforceScopeForLifecycleMutation(taskId, projectRoot);
140525
+ if (scopeDenied) return scopeDenied;
140415
140526
  stage = resolveStageAlias(stage);
140416
140527
  try {
140417
140528
  if (status === "in_progress" || status === "completed") {
@@ -140446,6 +140557,8 @@ async function lifecycleSkip(taskId, stage, reason, projectRoot) {
140446
140557
  if (!taskId || !stage || !reason) {
140447
140558
  return engineError("E_INVALID_INPUT", "taskId, stage, and reason are required");
140448
140559
  }
140560
+ const scopeDenied = await enforceScopeForLifecycleMutation(taskId, projectRoot);
140561
+ if (scopeDenied) return scopeDenied;
140449
140562
  try {
140450
140563
  const data = await skipStageWithReason(taskId, stage, reason, projectRoot);
140451
140564
  return engineSuccess({ ...data, skipped: true });
@@ -140460,6 +140573,8 @@ async function lifecycleReset(taskId, stage, reason, projectRoot) {
140460
140573
  if (!taskId || !stage || !reason) {
140461
140574
  return engineError("E_INVALID_INPUT", "taskId, stage, and reason are required");
140462
140575
  }
140576
+ const scopeDenied = await enforceScopeForLifecycleMutation(taskId, projectRoot);
140577
+ if (scopeDenied) return scopeDenied;
140463
140578
  try {
140464
140579
  const data = await resetStage(taskId, stage, reason, projectRoot);
140465
140580
  return engineSuccess({ ...data, reset: "pending" });
@@ -140519,8 +140634,8 @@ async function sessionStatus2(projectRoot) {
140519
140634
  try {
140520
140635
  const accessor = await getAccessor(projectRoot);
140521
140636
  const focusState = await accessor.getMetaValue("focus_state");
140522
- const sessions2 = await accessor.loadSessions();
140523
- const active = sessions2.find((s3) => s3.status === "active");
140637
+ const sessions3 = await accessor.loadSessions();
140638
+ const active = sessions3.find((s3) => s3.status === "active");
140524
140639
  return {
140525
140640
  success: true,
140526
140641
  data: {
@@ -140536,8 +140651,8 @@ async function sessionStatus2(projectRoot) {
140536
140651
  async function sessionList(projectRoot, params) {
140537
140652
  try {
140538
140653
  const accessor = await getAccessor(projectRoot);
140539
- const sessions2 = await accessor.loadSessions();
140540
- let result = sessions2;
140654
+ const sessions3 = await accessor.loadSessions();
140655
+ let result = sessions3;
140541
140656
  if (params?.status) {
140542
140657
  result = result.filter((s3) => s3.status === params.status);
140543
140658
  } else if (params?.active === true) {
@@ -140545,7 +140660,7 @@ async function sessionList(projectRoot, params) {
140545
140660
  } else if (params?.active === false) {
140546
140661
  result = result.filter((s3) => s3.status !== "active");
140547
140662
  }
140548
- const total = sessions2.length;
140663
+ const total = sessions3.length;
140549
140664
  const filtered = result.length;
140550
140665
  const limit = params?.limit && params.limit > 0 ? params.limit : SESSION_LIST_DEFAULT_LIMIT;
140551
140666
  const offset = typeof params?.offset === "number" && params.offset > 0 ? params.offset : 0;
@@ -140663,8 +140778,8 @@ async function sessionStart(projectRoot, params) {
140663
140778
  const sessionId = generateSessionId2();
140664
140779
  let previousSessionId = null;
140665
140780
  {
140666
- const sessions2 = await accessor.loadSessions();
140667
- const sameScope = sessions2.filter(
140781
+ const sessions3 = await accessor.loadSessions();
140782
+ const sameScope = sessions3.filter(
140668
140783
  (s3) => s3.status === "ended" && s3.endedAt && s3.scope?.type === scope.type && (scope.type === "global" || s3.scope?.rootTaskId === scope.rootTaskId)
140669
140784
  ).sort(
140670
140785
  (a, b2) => new Date(b2.endedAt).getTime() - new Date(a.endedAt).getTime()
@@ -140725,8 +140840,8 @@ async function sessionStart(projectRoot, params) {
140725
140840
  }
140726
140841
  await accessor.upsertSingleSession(newSession);
140727
140842
  if (previousSessionId) {
140728
- const sessions2 = await accessor.loadSessions();
140729
- const pred = sessions2.find((s3) => s3.id === previousSessionId);
140843
+ const sessions3 = await accessor.loadSessions();
140844
+ const pred = sessions3.find((s3) => s3.id === previousSessionId);
140730
140845
  if (pred) {
140731
140846
  pred.nextSessionId = sessionId;
140732
140847
  await accessor.upsertSingleSession(pred);
@@ -140746,8 +140861,8 @@ async function sessionStart(projectRoot, params) {
140746
140861
  let previousHandoff = null;
140747
140862
  if (previousSessionId) {
140748
140863
  try {
140749
- const sessions2 = await accessor.loadSessions();
140750
- const pred = sessions2.find((s3) => s3.id === previousSessionId);
140864
+ const sessions22 = await accessor.loadSessions();
140865
+ const pred = sessions22.find((s3) => s3.id === previousSessionId);
140751
140866
  if (pred) {
140752
140867
  if (pred.debriefJson) {
140753
140868
  previousDebrief = JSON.parse(pred.debriefJson);
@@ -140807,8 +140922,8 @@ async function sessionEnd(projectRoot, notes, params) {
140807
140922
  const { loadConfig: loadConfig4 } = await Promise.resolve().then(() => (init_internal(), internal_exports));
140808
140923
  const config2 = await loadConfig4(projectRoot);
140809
140924
  if (config2.brain?.summarization?.enabled) {
140810
- const sessions2 = await accessor.loadSessions();
140811
- const endedSession = sessions2.find(
140925
+ const sessions3 = await accessor.loadSessions();
140926
+ const endedSession = sessions3.find(
140812
140927
  (s3) => s3.id === sessionId
140813
140928
  );
140814
140929
  if (endedSession?.debriefJson) {
@@ -140838,8 +140953,8 @@ async function sessionEnd(projectRoot, notes, params) {
140838
140953
  async function sessionResume(projectRoot, sessionId) {
140839
140954
  try {
140840
140955
  const accessor = await getAccessor(projectRoot);
140841
- const sessions2 = await accessor.loadSessions();
140842
- const session = sessions2.find((s3) => s3.id === sessionId);
140956
+ const sessions3 = await accessor.loadSessions();
140957
+ const session = sessions3.find((s3) => s3.id === sessionId);
140843
140958
  if (!session) {
140844
140959
  return engineError("E_NOT_FOUND", `Session '${sessionId}' not found`);
140845
140960
  }
@@ -140890,13 +141005,13 @@ async function sessionResume(projectRoot, sessionId) {
140890
141005
  async function sessionGc(projectRoot, maxAgeDays = 1) {
140891
141006
  try {
140892
141007
  const accessor = await getAccessor(projectRoot);
140893
- const sessions2 = await accessor.loadSessions();
141008
+ const sessions3 = await accessor.loadSessions();
140894
141009
  const now2 = Date.now();
140895
141010
  const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
140896
141011
  const thirtyDaysMs = 30 * 24 * 60 * 60 * 1e3;
140897
141012
  const orphaned = [];
140898
141013
  const removed = [];
140899
- for (const session of sessions2) {
141014
+ for (const session of sessions3) {
140900
141015
  if (session.status === "active") {
140901
141016
  const lastActive = new Date(session.endedAt || session.startedAt).getTime();
140902
141017
  if (now2 - lastActive > maxAgeMs) {
@@ -140907,7 +141022,7 @@ async function sessionGc(projectRoot, maxAgeDays = 1) {
140907
141022
  }
140908
141023
  }
140909
141024
  }
140910
- for (const s3 of sessions2) {
141025
+ for (const s3 of sessions3) {
140911
141026
  if (s3.status === "active") continue;
140912
141027
  const endedAt = s3.endedAt ? new Date(s3.endedAt).getTime() : new Date(s3.startedAt).getTime();
140913
141028
  if (now2 - endedAt > thirtyDaysMs) {
@@ -141041,8 +141156,8 @@ async function sessionBriefing(projectRoot, options) {
141041
141156
  async function sessionComputeDebrief(projectRoot, sessionId, options) {
141042
141157
  try {
141043
141158
  const accessor = await getAccessor(projectRoot);
141044
- const sessions2 = await accessor.loadSessions();
141045
- const session = sessions2.find((s3) => s3.id === sessionId);
141159
+ const sessions3 = await accessor.loadSessions();
141160
+ const session = sessions3.find((s3) => s3.id === sessionId);
141046
141161
  const debrief = await computeDebrief(projectRoot, {
141047
141162
  sessionId,
141048
141163
  note: options?.note,
@@ -141065,8 +141180,8 @@ async function sessionComputeDebrief(projectRoot, sessionId, options) {
141065
141180
  async function sessionDebriefShow(projectRoot, sessionId) {
141066
141181
  try {
141067
141182
  const accessor = await getAccessor(projectRoot);
141068
- const sessions2 = await accessor.loadSessions();
141069
- const session = sessions2.find((s3) => s3.id === sessionId);
141183
+ const sessions3 = await accessor.loadSessions();
141184
+ const session = sessions3.find((s3) => s3.id === sessionId);
141070
141185
  if (!session) {
141071
141186
  return engineError("E_NOT_FOUND", `Session '${sessionId}' not found`);
141072
141187
  }
@@ -141092,8 +141207,8 @@ async function sessionDebriefShow(projectRoot, sessionId) {
141092
141207
  async function sessionChainShow(projectRoot, sessionId) {
141093
141208
  try {
141094
141209
  const accessor = await getAccessor(projectRoot);
141095
- const sessions2 = await accessor.loadSessions();
141096
- const sessionMap = new Map(sessions2.map((s3) => [s3.id, s3]));
141210
+ const sessions3 = await accessor.loadSessions();
141211
+ const sessionMap = new Map(sessions3.map((s3) => [s3.id, s3]));
141097
141212
  const target = sessionMap.get(sessionId);
141098
141213
  if (!target) {
141099
141214
  return engineError("E_NOT_FOUND", `Session '${sessionId}' not found`);
@@ -141150,7 +141265,7 @@ var init_session_engine = __esm({
141150
141265
 
141151
141266
  // packages/cleo/src/dispatch/engines/orchestrate-engine.ts
141152
141267
  import { createHash as createHash30 } from "node:crypto";
141153
- import { createRequire as createRequire22 } from "node:module";
141268
+ import { createRequire as createRequire21 } from "node:module";
141154
141269
  async function sendConduitEvent(cwd, to2, event) {
141155
141270
  try {
141156
141271
  const { AgentRegistryAccessor: AgentRegistryAccessor2, createConduit: createConduit2 } = await Promise.resolve().then(() => (init_internal(), internal_exports));
@@ -142075,7 +142190,7 @@ var init_orchestrate_engine = __esm({
142075
142190
  init_internal();
142076
142191
  init_error3();
142077
142192
  init_session_engine();
142078
- _engineRequire = createRequire22(import.meta.url);
142193
+ _engineRequire = createRequire21(import.meta.url);
142079
142194
  ({ DatabaseSync: _DatabaseSyncCtor } = _engineRequire("node:sqlite"));
142080
142195
  CLASSIFIER_RULES2 = [
142081
142196
  { test: /^(docs?|doc)[:\s-]/i, agentId: "docs-worker" },
@@ -143293,27 +143408,27 @@ async function queryAuditLogSqlite(projectRoot, filters) {
143293
143408
  }
143294
143409
  const { getDb: getDb5 } = await Promise.resolve().then(() => (init_internal(), internal_exports));
143295
143410
  const { auditLog: auditLog2 } = await Promise.resolve().then(() => (init_internal(), internal_exports));
143296
- const { sql: sql18 } = await import("drizzle-orm");
143411
+ const { sql: sql19 } = await import("drizzle-orm");
143297
143412
  const db = await getDb5(projectRoot);
143298
143413
  try {
143299
143414
  const conditions = [];
143300
143415
  if (filters?.operation) {
143301
143416
  conditions.push(
143302
- sql18`(${auditLog2.action} = ${filters.operation} OR ${auditLog2.operation} = ${filters.operation})`
143417
+ sql19`(${auditLog2.action} = ${filters.operation} OR ${auditLog2.operation} = ${filters.operation})`
143303
143418
  );
143304
143419
  }
143305
143420
  if (filters?.taskId) {
143306
- conditions.push(sql18`${auditLog2.taskId} = ${filters.taskId}`);
143421
+ conditions.push(sql19`${auditLog2.taskId} = ${filters.taskId}`);
143307
143422
  }
143308
143423
  if (filters?.since) {
143309
- conditions.push(sql18`${auditLog2.timestamp} >= ${filters.since}`);
143424
+ conditions.push(sql19`${auditLog2.timestamp} >= ${filters.since}`);
143310
143425
  }
143311
143426
  if (filters?.until) {
143312
- conditions.push(sql18`${auditLog2.timestamp} <= ${filters.until}`);
143427
+ conditions.push(sql19`${auditLog2.timestamp} <= ${filters.until}`);
143313
143428
  }
143314
- const whereClause = conditions.length > 0 ? sql18.join(conditions, sql18` AND `) : sql18`1=1`;
143429
+ const whereClause = conditions.length > 0 ? sql19.join(conditions, sql19` AND `) : sql19`1=1`;
143315
143430
  const countResult = await db.all(
143316
- sql18`SELECT count(*) as cnt FROM ${auditLog2} WHERE ${whereClause}`
143431
+ sql19`SELECT count(*) as cnt FROM ${auditLog2} WHERE ${whereClause}`
143317
143432
  );
143318
143433
  const total = countResult[0]?.cnt ?? 0;
143319
143434
  if (total === 0) {
@@ -143330,7 +143445,7 @@ async function queryAuditLogSqlite(projectRoot, filters) {
143330
143445
  const offset = filters?.offset ?? 0;
143331
143446
  const limit = filters?.limit ?? 20;
143332
143447
  const rows = await db.all(
143333
- sql18`SELECT * FROM ${auditLog2}
143448
+ sql19`SELECT * FROM ${auditLog2}
143334
143449
  WHERE ${whereClause}
143335
143450
  ORDER BY ${auditLog2.timestamp} DESC
143336
143451
  LIMIT ${limit} OFFSET ${offset}`
@@ -143401,14 +143516,14 @@ function systemContext(projectRoot, params) {
143401
143516
  stateFile = join139(cleoDir, ".context-state.json");
143402
143517
  }
143403
143518
  }
143404
- const sessions2 = [];
143519
+ const sessions3 = [];
143405
143520
  const statesDir = join139(cleoDir, "context-states");
143406
143521
  if (existsSync137(statesDir)) {
143407
143522
  for (const file2 of readdirSync42(statesDir)) {
143408
143523
  if (file2.startsWith("context-state-") && file2.endsWith(".json")) {
143409
143524
  try {
143410
143525
  const state = JSON.parse(readFileSync103(join139(statesDir, file2), "utf-8"));
143411
- sessions2.push({
143526
+ sessions3.push({
143412
143527
  file: basename20(file2),
143413
143528
  sessionId: state.sessionId ?? null,
143414
143529
  percentage: state.contextWindow?.percentage ?? 0,
@@ -143424,7 +143539,7 @@ function systemContext(projectRoot, params) {
143424
143539
  if (existsSync137(singletonFile)) {
143425
143540
  try {
143426
143541
  const state = JSON.parse(readFileSync103(singletonFile, "utf-8"));
143427
- sessions2.push({
143542
+ sessions3.push({
143428
143543
  file: ".context-state.json",
143429
143544
  sessionId: state.sessionId ?? "global",
143430
143545
  percentage: state.contextWindow?.percentage ?? 0,
@@ -143445,7 +143560,7 @@ function systemContext(projectRoot, params) {
143445
143560
  maxTokens: 0,
143446
143561
  timestamp: null,
143447
143562
  stale: true,
143448
- sessions: sessions2
143563
+ sessions: sessions3
143449
143564
  }
143450
143565
  };
143451
143566
  }
@@ -143471,7 +143586,7 @@ function systemContext(projectRoot, params) {
143471
143586
  maxTokens: max,
143472
143587
  timestamp: timestamp3,
143473
143588
  stale: status === "stale",
143474
- sessions: sessions2
143589
+ sessions: sessions3
143475
143590
  }
143476
143591
  };
143477
143592
  } catch {
@@ -143485,7 +143600,7 @@ function systemContext(projectRoot, params) {
143485
143600
  maxTokens: 0,
143486
143601
  timestamp: null,
143487
143602
  stale: true,
143488
- sessions: sessions2
143603
+ sessions: sessions3
143489
143604
  }
143490
143605
  };
143491
143606
  }
@@ -151290,7 +151405,7 @@ function handleTopEntriesFromBrain(operation, params, startTime, db, limit) {
151290
151405
  const nodeType = typeof rawNodeType === "string" && rawNodeType.length > 0 ? rawNodeType : null;
151291
151406
  let rows = [];
151292
151407
  try {
151293
- const sql18 = nodeType === null ? `SELECT id, node_type, label, quality_score, last_activity_at, metadata_json
151408
+ const sql19 = nodeType === null ? `SELECT id, node_type, label, quality_score, last_activity_at, metadata_json
151294
151409
  FROM brain_page_nodes
151295
151410
  ORDER BY quality_score DESC
151296
151411
  LIMIT ?` : `SELECT id, node_type, label, quality_score, last_activity_at, metadata_json
@@ -151299,7 +151414,7 @@ function handleTopEntriesFromBrain(operation, params, startTime, db, limit) {
151299
151414
  ORDER BY quality_score DESC
151300
151415
  LIMIT ?`;
151301
151416
  const bindArgs = nodeType === null ? [limit] : [nodeType, limit];
151302
- const rawRows = db.prepare(sql18).all(...bindArgs);
151417
+ const rawRows = db.prepare(sql19).all(...bindArgs);
151303
151418
  rows = rawRows.map((raw) => {
151304
151419
  const r = raw;
151305
151420
  return {
@@ -151335,7 +151450,7 @@ function handleTopEntriesFromNexus(operation, params, startTime, db, limit) {
151335
151450
  const kind = typeof rawKind === "string" && rawKind.length > 0 ? rawKind : null;
151336
151451
  let rows = [];
151337
151452
  try {
151338
- const sql18 = kind === null ? `SELECT r.source_id,
151453
+ const sql19 = kind === null ? `SELECT r.source_id,
151339
151454
  SUM(COALESCE(r.weight, 0)) AS totalWeight,
151340
151455
  COUNT(*) AS edgeCount,
151341
151456
  n.label,
@@ -151358,7 +151473,7 @@ function handleTopEntriesFromNexus(operation, params, startTime, db, limit) {
151358
151473
  ORDER BY totalWeight DESC, edgeCount DESC
151359
151474
  LIMIT ?`;
151360
151475
  const bindArgs = kind === null ? [limit] : [kind, limit];
151361
- const rawRows = db.prepare(sql18).all(...bindArgs);
151476
+ const rawRows = db.prepare(sql19).all(...bindArgs);
151362
151477
  rows = rawRows.map((raw) => {
151363
151478
  const r = raw;
151364
151479
  return {
@@ -156078,8 +156193,8 @@ function listPlaybookRuns(db, opts = {}) {
156078
156193
  const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
156079
156194
  const limitClause = typeof opts.limit === "number" ? "LIMIT ?" : "";
156080
156195
  if (limitClause) values.push(opts.limit ?? 0);
156081
- const sql18 = `SELECT * FROM playbook_runs ${where} ORDER BY started_at DESC ${limitClause}`;
156082
- const rows = db.prepare(sql18).all(...values);
156196
+ const sql19 = `SELECT * FROM playbook_runs ${where} ORDER BY started_at DESC ${limitClause}`;
156197
+ const rows = db.prepare(sql19).all(...values);
156083
156198
  return rows.map(rowToPlaybookRun);
156084
156199
  }
156085
156200
  function deletePlaybookRun(db, runId) {
@@ -156688,8 +156803,8 @@ var init_src4 = __esm({
156688
156803
  // packages/cleo/src/dispatch/domains/playbook.ts
156689
156804
  import { existsSync as existsSync139, readFileSync as readFileSync106 } from "node:fs";
156690
156805
  import { homedir as homedir11 } from "node:os";
156691
- import { dirname as dirname36, join as join142, resolve as resolvePath4 } from "node:path";
156692
- import { fileURLToPath as fileURLToPath11 } from "node:url";
156806
+ import { dirname as dirname38, join as join142, resolve as resolvePath5 } from "node:path";
156807
+ import { fileURLToPath as fileURLToPath12 } from "node:url";
156693
156808
  function normalizeListStatus(raw) {
156694
156809
  if (typeof raw !== "string" || raw.length === 0) return void 0;
156695
156810
  const value = raw.trim().toLowerCase();
@@ -156717,9 +156832,9 @@ function resolvePlaybookDirs() {
156717
156832
  return __playbookRuntimeOverrides.playbookBaseDirs;
156718
156833
  }
156719
156834
  const globalDir = join142(homedir11(), ".local", "share", "cleo", "playbooks");
156720
- const here = dirname36(fileURLToPath11(import.meta.url));
156721
- const sourceStarter = resolvePath4(here, "..", "..", "..", "..", "playbooks", "starter");
156722
- const bundledStarter = resolvePath4(here, "..", "..", "..", "playbooks", "starter");
156835
+ const here = dirname38(fileURLToPath12(import.meta.url));
156836
+ const sourceStarter = resolvePath5(here, "..", "..", "..", "..", "playbooks", "starter");
156837
+ const bundledStarter = resolvePath5(here, "..", "..", "..", "playbooks", "starter");
156723
156838
  return [globalDir, sourceStarter, bundledStarter];
156724
156839
  }
156725
156840
  function loadPlaybookByName(name2) {
@@ -159606,7 +159721,7 @@ function envelopeToEngineResult(envelope) {
159606
159721
  }
159607
159722
  async function storeSessionOwnerAuthToken(projectRoot, sessionId, token) {
159608
159723
  const db = await getDb(projectRoot);
159609
- db.update(sessions).set({ ownerAuthToken: token }).where(eq21(sessions.id, sessionId)).run();
159724
+ db.update(sessions2).set({ ownerAuthToken: token }).where(eq21(sessions2.id, sessionId)).run();
159610
159725
  }
159611
159726
  var _sessionTypedHandler, QUERY_OPS, MUTATE_OPS, SessionHandler;
159612
159727
  var init_session5 = __esm({
@@ -160971,15 +161086,15 @@ function toolsIssueDiagnostics() {
160971
161086
  }
160972
161087
  async function toolsSkillList(limit, offset) {
160973
161088
  try {
160974
- const skills = await discoverSkills(getCanonicalSkillsDir4());
160975
- const page = paginate(skills, limit, offset);
161089
+ const skills2 = await discoverSkills(getCanonicalSkillsDir4());
161090
+ const page = paginate(skills2, limit, offset);
160976
161091
  return {
160977
161092
  success: true,
160978
161093
  data: {
160979
161094
  skills: page.items,
160980
- count: skills.length,
160981
- total: skills.length,
160982
- filtered: skills.length,
161095
+ count: skills2.length,
161096
+ total: skills2.length,
161097
+ filtered: skills2.length,
160983
161098
  page: page.page
160984
161099
  },
160985
161100
  page: page.page
@@ -161002,10 +161117,10 @@ async function toolsSkillShow(name2) {
161002
161117
  async function toolsSkillFind(query) {
161003
161118
  try {
161004
161119
  const q2 = (query ?? "").toLowerCase();
161005
- const skills = await discoverSkills(getCanonicalSkillsDir4());
161006
- const filtered = q2 ? skills.filter(
161120
+ const skills2 = await discoverSkills(getCanonicalSkillsDir4());
161121
+ const filtered = q2 ? skills2.filter(
161007
161122
  (s3) => s3.name.toLowerCase().includes(q2) || s3.metadata.description.toLowerCase().includes(q2)
161008
- ) : skills;
161123
+ ) : skills2;
161009
161124
  return engineSuccess({ skills: filtered, count: filtered.length, query: q2 });
161010
161125
  } catch (error48) {
161011
161126
  return engineError("E_INTERNAL", error48 instanceof Error ? error48.message : String(error48));
@@ -162583,26 +162698,26 @@ __export(cli_exports, {
162583
162698
  });
162584
162699
  import { randomUUID as randomUUID19 } from "node:crypto";
162585
162700
  import { existsSync as existsSync141 } from "node:fs";
162586
- import { createRequire as createRequire23 } from "node:module";
162587
- import { dirname as dirname37, join as join146 } from "node:path";
162588
- import { fileURLToPath as fileURLToPath12 } from "node:url";
162701
+ import { createRequire as createRequire22 } from "node:module";
162702
+ import { dirname as dirname39, join as join146 } from "node:path";
162703
+ import { fileURLToPath as fileURLToPath13 } from "node:url";
162589
162704
  import { catalog as catalog4, registerSkillLibraryFromPath } from "@cleocode/caamp";
162590
162705
  function ensureCaampLibrary() {
162591
162706
  if (catalog4.isCatalogAvailable()) return;
162592
162707
  try {
162593
162708
  let skillsRoot = null;
162594
162709
  try {
162595
- const req = createRequire23(import.meta.url);
162710
+ const req = createRequire22(import.meta.url);
162596
162711
  const skillsPkgJson = req.resolve("@cleocode/skills/package.json");
162597
- const candidate = dirname37(skillsPkgJson);
162712
+ const candidate = dirname39(skillsPkgJson);
162598
162713
  if (existsSync141(join146(candidate, "skills.json"))) {
162599
162714
  skillsRoot = candidate;
162600
162715
  }
162601
162716
  } catch {
162602
162717
  }
162603
162718
  if (!skillsRoot) {
162604
- const thisFile = fileURLToPath12(import.meta.url);
162605
- const packageRoot = join146(dirname37(thisFile), "..", "..", "..", "..", "..");
162719
+ const thisFile = fileURLToPath13(import.meta.url);
162720
+ const packageRoot = join146(dirname39(thisFile), "..", "..", "..", "..", "..");
162606
162721
  const candidate = join146(packageRoot, "packages", "skills");
162607
162722
  if (existsSync141(join146(candidate, "skills.json"))) {
162608
162723
  skillsRoot = candidate;
@@ -162826,8 +162941,8 @@ var init_cli = __esm({
162826
162941
  // packages/cleo/src/cli/index.ts
162827
162942
  init_internal();
162828
162943
  import { readFileSync as readFileSync115 } from "node:fs";
162829
- import { dirname as dirname43, join as join159 } from "node:path";
162830
- import { fileURLToPath as fileURLToPath13 } from "node:url";
162944
+ import { dirname as dirname45, join as join159 } from "node:path";
162945
+ import { fileURLToPath as fileURLToPath14 } from "node:url";
162831
162946
 
162832
162947
  // node_modules/.pnpm/citty@0.2.1/node_modules/citty/dist/_chunks/libs/scule.mjs
162833
162948
  var NUMBER_CHAR_RE = /\d/;
@@ -164812,18 +164927,18 @@ var statusCommand = defineCommand({
164812
164927
  { command: "agent status" }
164813
164928
  );
164814
164929
  } else {
164815
- const agents = await registry2.list();
164930
+ const agents2 = await registry2.list();
164816
164931
  cliOutput(
164817
164932
  {
164818
164933
  success: true,
164819
164934
  data: {
164820
- agents: agents.map((a) => ({
164935
+ agents: agents2.map((a) => ({
164821
164936
  agentId: a.agentId,
164822
164937
  displayName: a.displayName,
164823
164938
  active: a.isActive,
164824
164939
  lastUsedAt: a.lastUsedAt
164825
164940
  })),
164826
- total: agents.length
164941
+ total: agents2.length
164827
164942
  }
164828
164943
  },
164829
164944
  { command: "agent status" }
@@ -165088,9 +165203,9 @@ var stopAllCommand = defineCommand({
165088
165203
  const { AgentRegistryAccessor: AgentRegistryAccessor2, getDb: getDb5 } = await Promise.resolve().then(() => (init_internal(), internal_exports));
165089
165204
  await getDb5();
165090
165205
  const registry2 = new AgentRegistryAccessor2(process.cwd());
165091
- const agents = await registry2.list({ active: true });
165206
+ const agents2 = await registry2.list({ active: true });
165092
165207
  let stopped = 0;
165093
- for (const a of agents) {
165208
+ for (const a of agents2) {
165094
165209
  await registry2.update(a.agentId, { isActive: false });
165095
165210
  try {
165096
165211
  await fetch(`${a.apiBaseUrl}/agents/${a.agentId}/status`, {
@@ -165108,7 +165223,7 @@ var stopAllCommand = defineCommand({
165108
165223
  stopped++;
165109
165224
  }
165110
165225
  cliOutput(
165111
- { success: true, data: { stopped, total: agents.length } },
165226
+ { success: true, data: { stopped, total: agents2.length } },
165112
165227
  { command: "agent stop-all" }
165113
165228
  );
165114
165229
  } catch (err) {
@@ -165317,11 +165432,11 @@ var listCommand3 = defineCommand({
165317
165432
  await getDb5();
165318
165433
  const includeGlobal = args.global === true;
165319
165434
  const includeDisabled = args["include-disabled"] === true;
165320
- const agents = listAgentsForProject2(process.cwd(), {
165435
+ const agents2 = listAgentsForProject2(process.cwd(), {
165321
165436
  includeGlobal,
165322
165437
  includeDisabled
165323
165438
  });
165324
- const filtered = !includeGlobal && args.active ? agents.filter((a) => a.isActive) : agents;
165439
+ const filtered = !includeGlobal && args.active ? agents2.filter((a) => a.isActive) : agents2;
165325
165440
  cliOutput(
165326
165441
  {
165327
165442
  success: true,
@@ -166253,7 +166368,7 @@ var packCommand = defineCommand({
166253
166368
  async run({ args }) {
166254
166369
  try {
166255
166370
  const { existsSync: existsSync148, statSync: statSync23 } = await import("node:fs");
166256
- const { resolve: resolve21, basename: basename21, dirname: dirname44 } = await import("node:path");
166371
+ const { resolve: resolve21, basename: basename21, dirname: dirname46 } = await import("node:path");
166257
166372
  const { execFileSync: execFileSync21 } = await import("node:child_process");
166258
166373
  const resolvedDir = resolve21(args.dir);
166259
166374
  if (!existsSync148(resolvedDir) || !statSync23(resolvedDir).isDirectory()) {
@@ -166289,7 +166404,7 @@ var packCommand = defineCommand({
166289
166404
  const agentName = basename21(resolvedDir);
166290
166405
  const archiveName = `${agentName}.cantz`;
166291
166406
  const archivePath = resolve21(archiveName);
166292
- const parentDir = dirname44(resolvedDir);
166407
+ const parentDir = dirname46(resolvedDir);
166293
166408
  try {
166294
166409
  execFileSync21("zip", ["-r", archivePath, agentName], {
166295
166410
  cwd: parentDir,
@@ -166602,8 +166717,8 @@ var doctorCommand = defineCommand({
166602
166717
  ensureGlobalSignaldockDb: ensureGlobalSignaldockDb2,
166603
166718
  getGlobalSignaldockDbPath: getGlobalSignaldockDbPath2
166604
166719
  } = await Promise.resolve().then(() => (init_internal(), internal_exports));
166605
- const { createRequire: createRequire24 } = await import("node:module");
166606
- const nodeSqlite = createRequire24(import.meta.url)(
166720
+ const { createRequire: createRequire23 } = await import("node:module");
166721
+ const nodeSqlite = createRequire23(import.meta.url)(
166607
166722
  "node:sqlite"
166608
166723
  );
166609
166724
  const { DatabaseSync: DatabaseSync11 } = nodeSqlite;
@@ -168496,8 +168611,8 @@ var briefingCommand = defineCommand({
168496
168611
  // packages/cleo/src/cli/commands/bug.ts
168497
168612
  init_src3();
168498
168613
  import { existsSync as existsSync143 } from "node:fs";
168499
- import { appendFile as appendFile7, mkdir as mkdir25, readFile as readFile30 } from "node:fs/promises";
168500
- import { dirname as dirname38, join as join147 } from "node:path";
168614
+ import { appendFile as appendFile8, mkdir as mkdir26, readFile as readFile30 } from "node:fs/promises";
168615
+ import { dirname as dirname40, join as join147 } from "node:path";
168501
168616
  init_cli();
168502
168617
  var SEVERITY_MAP = {
168503
168618
  P0: { priority: "critical", labels: ["bug", "p0"] },
@@ -168550,8 +168665,8 @@ async function appendSignedBugSeverity(record2) {
168550
168665
  const line2 = `${JSON.stringify({ ...full, _sig: sig })}
168551
168666
  `;
168552
168667
  const auditPath = join147(getCleoDirAbsolute(), "audit", "bug-severity.jsonl");
168553
- await mkdir25(dirname38(auditPath), { recursive: true });
168554
- await appendFile7(auditPath, line2, { encoding: "utf-8" });
168668
+ await mkdir26(dirname40(auditPath), { recursive: true });
168669
+ await appendFile8(auditPath, line2, { encoding: "utf-8" });
168555
168670
  }
168556
168671
  var bugCommand = defineCommand({
168557
168672
  meta: {
@@ -168663,7 +168778,7 @@ var cancelCommand = defineCommand({
168663
168778
 
168664
168779
  // packages/cleo/src/cli/commands/cant.ts
168665
168780
  import { existsSync as existsSync144, mkdirSync as mkdirSync38, readFileSync as readFileSync109, writeFileSync as writeFileSync27 } from "node:fs";
168666
- import { dirname as dirname39, isAbsolute as isAbsolute6, join as join148, resolve as resolve19 } from "node:path";
168781
+ import { dirname as dirname41, isAbsolute as isAbsolute6, join as join148, resolve as resolve19 } from "node:path";
168667
168782
  init_renderers();
168668
168783
  function resolveFilePath(file2) {
168669
168784
  return isAbsolute6(file2) ? file2 : resolve19(process.cwd(), file2);
@@ -168824,7 +168939,7 @@ var cantMigrateCommand = defineCommand({
168824
168939
  let written = 0;
168825
168940
  for (const outputFile of result.outputFiles) {
168826
168941
  const outputPath = isAbsolute6(outputFile.path) ? outputFile.path : join148(projectRoot, outputFile.path);
168827
- mkdirSync38(dirname39(outputPath), { recursive: true });
168942
+ mkdirSync38(dirname41(outputPath), { recursive: true });
168828
168943
  writeFileSync27(outputPath, outputFile.content, "utf-8");
168829
168944
  written++;
168830
168945
  }
@@ -170948,7 +171063,7 @@ var detectCommand2 = defineCommand({
170948
171063
  // packages/cleo/src/cli/commands/detect-drift.ts
170949
171064
  init_src();
170950
171065
  import { existsSync as existsSync145, readdirSync as readdirSync43, readFileSync as readFileSync111 } from "node:fs";
170951
- import { dirname as dirname40, join as join150 } from "node:path";
171066
+ import { dirname as dirname42, join as join150 } from "node:path";
170952
171067
  init_paths2();
170953
171068
  init_renderers();
170954
171069
  function findProjectRoot() {
@@ -170957,7 +171072,7 @@ function findProjectRoot() {
170957
171072
  if (existsSync145(join150(currentDir, "package.json"))) {
170958
171073
  return currentDir;
170959
171074
  }
170960
- const parent = dirname40(currentDir);
171075
+ const parent = dirname42(currentDir);
170961
171076
  if (parent === currentDir) break;
170962
171077
  currentDir = parent;
170963
171078
  }
@@ -171425,8 +171540,8 @@ var diagnosticsCommand = defineCommand({
171425
171540
  // packages/cleo/src/cli/commands/docs.ts
171426
171541
  init_src();
171427
171542
  init_internal();
171428
- import { mkdir as mkdir26, readdir as readdir5, readFile as readFile31, writeFile as writeFile16 } from "node:fs/promises";
171429
- import { dirname as dirname41, isAbsolute as isAbsolute7, join as join151, resolve as resolve20 } from "node:path";
171543
+ import { mkdir as mkdir27, readdir as readdir5, readFile as readFile31, writeFile as writeFile16 } from "node:fs/promises";
171544
+ import { dirname as dirname43, isAbsolute as isAbsolute7, join as join151, resolve as resolve20 } from "node:path";
171430
171545
  init_cli();
171431
171546
  init_renderers();
171432
171547
  async function getScriptNames(projectRoot) {
@@ -171719,7 +171834,7 @@ var exportCommand4 = defineCommand({
171719
171834
  let writtenPath;
171720
171835
  if (typeof args.out === "string" && args.out.length > 0) {
171721
171836
  const outPath = isAbsolute7(args.out) ? args.out : resolve20(projectRoot, args.out);
171722
- await mkdir26(dirname41(outPath), { recursive: true });
171837
+ await mkdir27(dirname43(outPath), { recursive: true });
171723
171838
  await writeFile16(outPath, result.markdown, "utf8");
171724
171839
  writtenPath = outPath;
171725
171840
  }
@@ -171834,7 +171949,7 @@ var mergeCommand = defineCommand({
171834
171949
  });
171835
171950
  if (typeof args.out === "string" && args.out.length > 0) {
171836
171951
  const outPath = isAbsolute7(args.out) ? args.out : resolve20(projectRoot, args.out);
171837
- await mkdir26(dirname41(outPath), { recursive: true });
171952
+ await mkdir27(dirname43(outPath), { recursive: true });
171838
171953
  await writeFile16(outPath, result.merged, "utf8");
171839
171954
  process.stderr.write(`Wrote merged content to ${outPath}
171840
171955
  `);
@@ -171906,7 +172021,7 @@ var graphCommand = defineCommand({
171906
172021
  }
171907
172022
  if (typeof args.out === "string" && args.out.length > 0) {
171908
172023
  const outPath = isAbsolute7(args.out) ? args.out : resolve20(projectRoot, args.out);
171909
- await mkdir26(dirname41(outPath), { recursive: true });
172024
+ await mkdir27(dirname43(outPath), { recursive: true });
171910
172025
  await writeFile16(outPath, output, "utf8");
171911
172026
  process.stderr.write(`Wrote graph to ${outPath}
171912
172027
  `);
@@ -172977,7 +173092,7 @@ init_src();
172977
173092
  init_src3();
172978
173093
  import { execFileSync as execFileSync18 } from "node:child_process";
172979
173094
  import { existsSync as existsSync146, mkdirSync as mkdirSync39, readFileSync as readFileSync112, writeFileSync as writeFileSync28 } from "node:fs";
172980
- import { dirname as dirname42, join as join153 } from "node:path";
173095
+ import { dirname as dirname44, join as join153 } from "node:path";
172981
173096
  init_renderers();
172982
173097
  function getChangelogSource(cwd) {
172983
173098
  const configPath = getConfigPath(cwd);
@@ -173149,7 +173264,7 @@ var generateChangelogCommand = defineCommand({
173149
173264
  const content = generateForPlatform(targetPlatform, sourceContent, repoSlug, limit);
173150
173265
  if (!dryRun) {
173151
173266
  const fullPath = join153(getProjectRoot(), outputPath);
173152
- mkdirSync39(dirname42(fullPath), { recursive: true });
173267
+ mkdirSync39(dirname44(fullPath), { recursive: true });
173153
173268
  writeFileSync28(fullPath, content, "utf-8");
173154
173269
  }
173155
173270
  results.push({ platform: targetPlatform, path: outputPath, written: !dryRun });
@@ -173170,7 +173285,7 @@ var generateChangelogCommand = defineCommand({
173170
173285
  );
173171
173286
  if (!dryRun) {
173172
173287
  const fullPath = join153(getProjectRoot(), platformConfig.path);
173173
- mkdirSync39(dirname42(fullPath), { recursive: true });
173288
+ mkdirSync39(dirname44(fullPath), { recursive: true });
173174
173289
  writeFileSync28(fullPath, content, "utf-8");
173175
173290
  }
173176
173291
  results.push({
@@ -185075,7 +185190,7 @@ async function writeRuntimeVersionMetadata(mode, source, version2) {
185075
185190
  `installed=${(/* @__PURE__ */ new Date()).toISOString()}`
185076
185191
  ];
185077
185192
  await import("node:fs/promises").then(
185078
- ({ writeFile: writeFile18, mkdir: mkdir28 }) => mkdir28(cleoHome, { recursive: true }).then(
185193
+ ({ writeFile: writeFile18, mkdir: mkdir29 }) => mkdir29(cleoHome, { recursive: true }).then(
185079
185194
  () => writeFile18(join155(cleoHome, "VERSION"), `${lines.join("\n")}
185080
185195
  `, "utf-8")
185081
185196
  )
@@ -188154,11 +188269,11 @@ var extractCommand = defineCommand({
188154
188269
  try {
188155
188270
  const { extractTranscript } = await import("@cleocode/core/memory/transcript-extractor.js");
188156
188271
  const { findSessionTranscriptPath: findSessionTranscriptPath2, listAllTranscripts: listAllTranscripts2 } = await import("@cleocode/core/memory/transcript-scanner.js");
188157
- const sessions2 = [];
188272
+ const sessions3 = [];
188158
188273
  if (args["all-warm"]) {
188159
188274
  const allTranscripts = await listAllTranscripts2({ olderThanHours: 1 });
188160
188275
  for (const t of allTranscripts) {
188161
- sessions2.push({ sessionId: t.sessionId, path: t.path });
188276
+ sessions3.push({ sessionId: t.sessionId, path: t.path });
188162
188277
  }
188163
188278
  } else if (args["session-id"]) {
188164
188279
  const path15 = await findSessionTranscriptPath2(args["session-id"]);
@@ -188179,7 +188294,7 @@ var extractCommand = defineCommand({
188179
188294
  process.exit(4);
188180
188295
  return;
188181
188296
  }
188182
- sessions2.push({ sessionId: args["session-id"], path: path15 });
188297
+ sessions3.push({ sessionId: args["session-id"], path: path15 });
188183
188298
  } else {
188184
188299
  process.stderr.write(
188185
188300
  "Provide a session-id or use --all-warm to extract all warm sessions\n"
@@ -188191,7 +188306,7 @@ var extractCommand = defineCommand({
188191
188306
  let totalStored = 0;
188192
188307
  let totalBytesFreed = 0;
188193
188308
  const results = [];
188194
- for (const session of sessions2) {
188309
+ for (const session of sessions3) {
188195
188310
  const result = await extractTranscript({
188196
188311
  transcriptPath: session.path,
188197
188312
  projectRoot,
@@ -188207,7 +188322,7 @@ var extractCommand = defineCommand({
188207
188322
  const envelope = {
188208
188323
  success: true,
188209
188324
  data: {
188210
- sessionsProcessed: sessions2.length,
188325
+ sessionsProcessed: sessions3.length,
188211
188326
  memoriesExtracted: totalExtracted,
188212
188327
  memoriesStored: totalStored,
188213
188328
  bytesFreed: totalBytesFreed,
@@ -188221,7 +188336,7 @@ var extractCommand = defineCommand({
188221
188336
  const dryLabel = dryRun ? " (dry run)" : "";
188222
188337
  process.stdout.write(`Transcript extraction complete${dryLabel}
188223
188338
  `);
188224
- process.stdout.write(`Sessions: ${sessions2.length}
188339
+ process.stdout.write(`Sessions: ${sessions3.length}
188225
188340
  `);
188226
188341
  process.stdout.write(`Extracted: ${totalExtracted} memories
188227
188342
  `);
@@ -188857,7 +188972,7 @@ var verifyCommand2 = defineCommand({
188857
188972
  init_src();
188858
188973
  init_src3();
188859
188974
  import { execFileSync as execFileSync20, spawn as spawn3 } from "node:child_process";
188860
- import { mkdir as mkdir27, open, readFile as readFile33, rm as rm4, stat as stat7, writeFile as writeFile17 } from "node:fs/promises";
188975
+ import { mkdir as mkdir28, open, readFile as readFile33, rm as rm4, stat as stat7, writeFile as writeFile17 } from "node:fs/promises";
188861
188976
  import { join as join158 } from "node:path";
188862
188977
  init_renderers();
188863
188978
  var DEFAULT_PORT = 3456;
@@ -188908,7 +189023,7 @@ async function startWebServer(port, host) {
188908
189023
  }
188909
189024
  const projectRoot = process.env["CLEO_ROOT"] ?? process.cwd();
188910
189025
  const studioDir = process.env["CLEO_STUDIO_DIR"] ?? join158(projectRoot, "packages", "studio", "build");
188911
- await mkdir27(logDir, { recursive: true });
189026
+ await mkdir28(logDir, { recursive: true });
188912
189027
  await writeFile17(
188913
189028
  configFile,
188914
189029
  JSON.stringify({
@@ -189196,7 +189311,7 @@ Or via NodeSource: https://github.com/nodesource/distributions
189196
189311
  }
189197
189312
  }
189198
189313
  function getPackageVersion() {
189199
- const pkgPath = join159(dirname43(fileURLToPath13(import.meta.url)), "../../package.json");
189314
+ const pkgPath = join159(dirname45(fileURLToPath14(import.meta.url)), "../../package.json");
189200
189315
  const pkg = JSON.parse(readFileSync115(pkgPath, "utf-8"));
189201
189316
  return pkg.version;
189202
189317
  }