@cleocode/core 2026.4.51 → 2026.4.53

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/internal.js CHANGED
@@ -9598,11 +9598,14 @@ var init_brain_schema = __esm({
9598
9598
  source: text("source").notNull(),
9599
9599
  /** Estimated tokens consumed by this retrieval. */
9600
9600
  tokensUsed: integer("tokens_used"),
9601
+ /** Session ID (soft FK to tasks.db sessions). Enables grouping retrievals by session for STDP analysis. */
9602
+ sessionId: text("session_id"),
9601
9603
  createdAt: text("created_at").notNull().default(sql2`(datetime('now'))`)
9602
9604
  },
9603
9605
  (table) => [
9604
9606
  index("idx_retrieval_log_created").on(table.createdAt),
9605
- index("idx_retrieval_log_source").on(table.source)
9607
+ index("idx_retrieval_log_source").on(table.source),
9608
+ index("idx_retrieval_log_session").on(table.sessionId)
9606
9609
  ]
9607
9610
  );
9608
9611
  brainPlasticityEvents = sqliteTable(
@@ -11137,44 +11140,6 @@ var init_platform_paths = __esm({
11137
11140
  });
11138
11141
 
11139
11142
  // packages/core/src/paths.ts
11140
- var paths_exports = {};
11141
- __export(paths_exports, {
11142
- getAgentOutputsAbsolute: () => getAgentOutputsAbsolute,
11143
- getAgentOutputsDir: () => getAgentOutputsDir,
11144
- getAgentsHome: () => getAgentsHome,
11145
- getArchivePath: () => getArchivePath,
11146
- getBackupDir: () => getBackupDir,
11147
- getClaudeAgentsDir: () => getClaudeAgentsDir,
11148
- getClaudeMemDbPath: () => getClaudeMemDbPath,
11149
- getCleoCacheDir: () => getCleoCacheDir,
11150
- getCleoCantWorkflowsDir: () => getCleoCantWorkflowsDir,
11151
- getCleoConfigDir: () => getCleoConfigDir,
11152
- getCleoDir: () => getCleoDir,
11153
- getCleoDirAbsolute: () => getCleoDirAbsolute,
11154
- getCleoDocsDir: () => getCleoDocsDir,
11155
- getCleoGlobalAgentsDir: () => getCleoGlobalAgentsDir,
11156
- getCleoGlobalJustfilePath: () => getCleoGlobalJustfilePath,
11157
- getCleoGlobalRecipesDir: () => getCleoGlobalRecipesDir,
11158
- getCleoHome: () => getCleoHome,
11159
- getCleoLogDir: () => getCleoLogDir,
11160
- getCleoPiExtensionsDir: () => getCleoPiExtensionsDir,
11161
- getCleoSchemasDir: () => getCleoSchemasDir,
11162
- getCleoTempDir: () => getCleoTempDir,
11163
- getCleoTemplatesDir: () => getCleoTemplatesDir,
11164
- getCleoTemplatesTildePath: () => getCleoTemplatesTildePath,
11165
- getConfigPath: () => getConfigPath,
11166
- getGlobalConfigPath: () => getGlobalConfigPath,
11167
- getLogPath: () => getLogPath,
11168
- getManifestArchivePath: () => getManifestArchivePath,
11169
- getManifestPath: () => getManifestPath,
11170
- getProjectRoot: () => getProjectRoot,
11171
- getSessionsPath: () => getSessionsPath,
11172
- getTaskPath: () => getTaskPath,
11173
- isAbsolutePath: () => isAbsolutePath,
11174
- isProjectInitialized: () => isProjectInitialized,
11175
- resolveProjectPath: () => resolveProjectPath,
11176
- worktreeScope: () => worktreeScope
11177
- });
11178
11143
  import { AsyncLocalStorage } from "node:async_hooks";
11179
11144
  import { existsSync as existsSync3, readFileSync as readFileSync2 } from "node:fs";
11180
11145
  import { homedir } from "node:os";
@@ -11193,9 +11158,6 @@ function getCleoTemplatesDir() {
11193
11158
  function getCleoSchemasDir() {
11194
11159
  return join4(getCleoHome(), "schemas");
11195
11160
  }
11196
- function getCleoDocsDir() {
11197
- return join4(getCleoHome(), "docs");
11198
- }
11199
11161
  function getCleoDir(cwd) {
11200
11162
  if (cwd) {
11201
11163
  return getCleoDirAbsolute(cwd);
@@ -11267,15 +11229,6 @@ function getTaskPath(cwd) {
11267
11229
  function getConfigPath(cwd) {
11268
11230
  return join4(getCleoDirAbsolute(cwd), "config.json");
11269
11231
  }
11270
- function getSessionsPath(cwd) {
11271
- return join4(getCleoDirAbsolute(cwd), "sessions.json");
11272
- }
11273
- function getArchivePath(cwd) {
11274
- return join4(getCleoDirAbsolute(cwd), "tasks-archive.json");
11275
- }
11276
- function getLogPath(cwd) {
11277
- return join4(getCleoDirAbsolute(cwd), "logs", "cleo.log");
11278
- }
11279
11232
  function getBackupDir(cwd) {
11280
11233
  return join4(getCleoDirAbsolute(cwd), "backups", "operational");
11281
11234
  }
@@ -14328,8 +14281,8 @@ async function cleanupMigrationArtifacts(backupPath) {
14328
14281
  }
14329
14282
  async function validateSqliteDatabase(dbPath) {
14330
14283
  try {
14331
- const { createRequire: createRequire15 } = await import("node:module");
14332
- const _req = createRequire15(import.meta.url);
14284
+ const { createRequire: createRequire16 } = await import("node:module");
14285
+ const _req = createRequire16(import.meta.url);
14333
14286
  const { DatabaseSync: DatabaseSync10 } = _req("node:sqlite");
14334
14287
  const db = new DatabaseSync10(dbPath, { readOnly: true });
14335
14288
  const integrityRow = db.prepare("PRAGMA integrity_check").get();
@@ -14950,7 +14903,7 @@ function clearEmbeddingProvider() {
14950
14903
  currentProvider = null;
14951
14904
  }
14952
14905
  async function embedText(text3) {
14953
- if (!currentProvider || !currentProvider.isAvailable()) return null;
14906
+ if (!currentProvider?.isAvailable()) return null;
14954
14907
  return currentProvider.embed(text3);
14955
14908
  }
14956
14909
  function isEmbeddingAvailable() {
@@ -20100,7 +20053,7 @@ function parseIdPrefix(id) {
20100
20053
  return null;
20101
20054
  }
20102
20055
  async function searchSimilar(query, projectRoot, limit) {
20103
- if (!query || !query.trim()) return [];
20056
+ if (!query?.trim()) return [];
20104
20057
  if (!isEmbeddingAvailable()) return [];
20105
20058
  const maxResults = limit ?? 10;
20106
20059
  const queryVector = await embedText(query);
@@ -47647,7 +47600,7 @@ async function computeLastSession(projectRoot, scopeFilter) {
47647
47600
  const accessor = await getAccessor(projectRoot);
47648
47601
  const allSessions = await accessor.loadSessions();
47649
47602
  const session = allSessions.find((s3) => s3.id === sessionId);
47650
- if (!session || !session.endedAt) return null;
47603
+ if (!session?.endedAt) return null;
47651
47604
  let duration3 = 0;
47652
47605
  if (session.startedAt) {
47653
47606
  duration3 = Math.round(
@@ -48834,10 +48787,17 @@ async function searchBrainCompact(projectRoot, params) {
48834
48787
  setImmediate(() => {
48835
48788
  incrementCitationCounts(projectRoot, returnedIds).catch(() => {
48836
48789
  });
48837
- logRetrieval(projectRoot, query, returnedIds, "find-rrf", results2.length * 50).catch(
48838
- () => {
48839
- }
48840
- );
48790
+ getCurrentSessionId(projectRoot).then((sessionId) => {
48791
+ return logRetrieval(
48792
+ projectRoot,
48793
+ query,
48794
+ returnedIds,
48795
+ "find-rrf",
48796
+ results2.length * 50,
48797
+ sessionId
48798
+ );
48799
+ }).catch(() => {
48800
+ });
48841
48801
  });
48842
48802
  }
48843
48803
  return { results: results2, total: results2.length, tokensEstimated: results2.length * 50 };
@@ -48900,7 +48860,16 @@ async function searchBrainCompact(projectRoot, params) {
48900
48860
  setImmediate(() => {
48901
48861
  incrementCitationCounts(projectRoot, returnedIds).catch(() => {
48902
48862
  });
48903
- logRetrieval(projectRoot, query, returnedIds, "find", results.length * 50).catch(() => {
48863
+ getCurrentSessionId(projectRoot).then((sessionId) => {
48864
+ return logRetrieval(
48865
+ projectRoot,
48866
+ query,
48867
+ returnedIds,
48868
+ "find",
48869
+ results.length * 50,
48870
+ sessionId
48871
+ );
48872
+ }).catch(() => {
48904
48873
  });
48905
48874
  });
48906
48875
  }
@@ -49088,13 +49057,16 @@ async function fetchBrainEntries(projectRoot, params) {
49088
49057
  setImmediate(() => {
49089
49058
  incrementCitationCounts(projectRoot, fetchedIds).catch(() => {
49090
49059
  });
49091
- logRetrieval(
49092
- projectRoot,
49093
- fetchedIds.join(","),
49094
- fetchedIds,
49095
- "fetch",
49096
- results.length * 500
49097
- ).catch(() => {
49060
+ getCurrentSessionId(projectRoot).then((sessionId) => {
49061
+ return logRetrieval(
49062
+ projectRoot,
49063
+ fetchedIds.join(","),
49064
+ fetchedIds,
49065
+ "fetch",
49066
+ results.length * 500,
49067
+ sessionId
49068
+ );
49069
+ }).catch(() => {
49098
49070
  });
49099
49071
  });
49100
49072
  }
@@ -49512,6 +49484,15 @@ async function retrieveWithBudget(projectRoot, query, tokenBudget = 500, options
49512
49484
  excluded
49513
49485
  };
49514
49486
  }
49487
+ async function getCurrentSessionId(projectRoot) {
49488
+ try {
49489
+ const { sessionStatus: sessionStatus2 } = await Promise.resolve().then(() => (init_sessions2(), sessions_exports2));
49490
+ const session = await sessionStatus2(projectRoot);
49491
+ return session?.id;
49492
+ } catch {
49493
+ return void 0;
49494
+ }
49495
+ }
49515
49496
  async function incrementCitationCounts(projectRoot, ids) {
49516
49497
  if (ids.length === 0) return;
49517
49498
  const { getBrainDb: getBrainDb2, getBrainNativeDb: getBrainNativeDb2 } = await Promise.resolve().then(() => (init_brain_sqlite(), brain_sqlite_exports));
@@ -49538,13 +49519,13 @@ async function incrementCitationCounts(projectRoot, ids) {
49538
49519
  }
49539
49520
  }
49540
49521
  }
49541
- async function logRetrieval(projectRoot, query, entryIds, source, tokensUsed) {
49522
+ async function logRetrieval(projectRoot, query, entryIds, source, tokensUsed, sessionId) {
49542
49523
  if (entryIds.length === 0) return;
49543
49524
  const { getBrainDb: getBrainDb2, getBrainNativeDb: getBrainNativeDb2 } = await Promise.resolve().then(() => (init_brain_sqlite(), brain_sqlite_exports));
49544
49525
  await getBrainDb2(projectRoot);
49545
49526
  const nativeDb = getBrainNativeDb2();
49546
49527
  if (!nativeDb) return;
49547
- const createSql = "CREATE TABLE IF NOT EXISTS brain_retrieval_log (id INTEGER PRIMARY KEY AUTOINCREMENT,query TEXT NOT NULL,entry_ids TEXT NOT NULL,entry_count INTEGER NOT NULL,source TEXT NOT NULL,tokens_used INTEGER,created_at TEXT NOT NULL DEFAULT (datetime('now')))";
49528
+ const createSql = "CREATE TABLE IF NOT EXISTS brain_retrieval_log (id INTEGER PRIMARY KEY AUTOINCREMENT,query TEXT NOT NULL,entry_ids TEXT NOT NULL,entry_count INTEGER NOT NULL,source TEXT NOT NULL,tokens_used INTEGER,session_id TEXT,created_at TEXT NOT NULL DEFAULT (datetime('now')))";
49548
49529
  try {
49549
49530
  nativeDb.prepare(createSql).run();
49550
49531
  } catch {
@@ -49552,8 +49533,15 @@ async function logRetrieval(projectRoot, query, entryIds, source, tokensUsed) {
49552
49533
  }
49553
49534
  try {
49554
49535
  nativeDb.prepare(
49555
- "INSERT INTO brain_retrieval_log (query, entry_ids, entry_count, source, tokens_used) VALUES (?, ?, ?, ?, ?)"
49556
- ).run(query, entryIds.join(","), entryIds.length, source, tokensUsed ?? null);
49536
+ "INSERT INTO brain_retrieval_log (query, entry_ids, entry_count, source, tokens_used, session_id) VALUES (?, ?, ?, ?, ?, ?)"
49537
+ ).run(
49538
+ query,
49539
+ entryIds.join(","),
49540
+ entryIds.length,
49541
+ source,
49542
+ tokensUsed ?? null,
49543
+ sessionId ?? null
49544
+ );
49557
49545
  } catch {
49558
49546
  }
49559
49547
  }
@@ -50670,6 +50658,7 @@ __export(scaffold_exports, {
50670
50658
  checkConfig: () => checkConfig,
50671
50659
  checkGitignore: () => checkGitignore,
50672
50660
  checkGlobalHome: () => checkGlobalHome,
50661
+ checkGlobalIdentity: () => checkGlobalIdentity,
50673
50662
  checkGlobalTemplates: () => checkGlobalTemplates,
50674
50663
  checkLogDir: () => checkLogDir,
50675
50664
  checkMemoryBridge: () => checkMemoryBridge,
@@ -50686,6 +50675,7 @@ __export(scaffold_exports, {
50686
50675
  ensureContributorMcp: () => ensureContributorMcp,
50687
50676
  ensureGitignore: () => ensureGitignore,
50688
50677
  ensureGlobalHome: () => ensureGlobalHome,
50678
+ ensureGlobalIdentity: () => ensureGlobalIdentity,
50689
50679
  ensureGlobalScaffold: () => ensureGlobalScaffold,
50690
50680
  ensureGlobalTemplates: () => ensureGlobalTemplates,
50691
50681
  ensureProjectContext: () => ensureProjectContext,
@@ -50703,6 +50693,7 @@ import { execFile as execFile3 } from "node:child_process";
50703
50693
  import { randomUUID as randomUUID2 } from "node:crypto";
50704
50694
  import { existsSync as existsSync40, constants as fsConstants3, readFileSync as readFileSync23, statSync as statSync8 } from "node:fs";
50705
50695
  import { access as access3, copyFile as copyFile2, mkdir as mkdir6, readdir as readdir2, readFile as readFile7, rm as rm2, writeFile as writeFile6 } from "node:fs/promises";
50696
+ import { createRequire as createRequire6 } from "node:module";
50706
50697
  import { homedir as getHomedir } from "node:os";
50707
50698
  import { dirname as dirname10, join as join41, resolve as resolve5 } from "node:path";
50708
50699
  import { fileURLToPath as fileURLToPath4 } from "node:url";
@@ -51558,6 +51549,102 @@ async function ensureCleoOsHub() {
51558
51549
  details: `pi-extensions: ${piResult.copied} created/${piResult.kept} kept, global-recipes: ${recipesResult.copied} created/${recipesResult.kept} kept`
51559
51550
  };
51560
51551
  }
51552
+ function resolveIdentitySourcePath() {
51553
+ const monorepoPath = join41(
51554
+ process.cwd(),
51555
+ "packages",
51556
+ "cleo-os",
51557
+ "starter-bundle",
51558
+ "CLEOOS-IDENTITY.md"
51559
+ );
51560
+ if (existsSync40(monorepoPath)) return monorepoPath;
51561
+ try {
51562
+ const require2 = createRequire6(import.meta.url);
51563
+ const pkgJson = require2.resolve("@cleocode/cleo-os/package.json");
51564
+ const pkgDir = pkgJson.replace(/\/package\.json$/, "");
51565
+ const installedPath = join41(pkgDir, "starter-bundle", "CLEOOS-IDENTITY.md");
51566
+ if (existsSync40(installedPath)) return installedPath;
51567
+ } catch {
51568
+ }
51569
+ return null;
51570
+ }
51571
+ async function ensureGlobalIdentity(forceRefresh = false) {
51572
+ const sourcePath = resolveIdentitySourcePath();
51573
+ if (!sourcePath) {
51574
+ return {
51575
+ action: "skipped",
51576
+ path: "",
51577
+ details: "CLEOOS-IDENTITY.md source not found in monorepo or installed package"
51578
+ };
51579
+ }
51580
+ const cleoHome = getCleoHome();
51581
+ const dst = join41(cleoHome, "CLEOOS-IDENTITY.md");
51582
+ try {
51583
+ await mkdir6(cleoHome, { recursive: true });
51584
+ } catch (err) {
51585
+ return {
51586
+ action: "skipped",
51587
+ path: dst,
51588
+ details: `Failed to create global cleo home: ${err instanceof Error ? err.message : String(err)}`
51589
+ };
51590
+ }
51591
+ if (existsSync40(dst) && !forceRefresh) {
51592
+ return { action: "skipped", path: dst, details: "identity already present" };
51593
+ }
51594
+ const existedBefore = existsSync40(dst);
51595
+ try {
51596
+ const content = readFileSync23(sourcePath, "utf-8");
51597
+ await writeFile6(dst, content);
51598
+ return {
51599
+ action: existedBefore ? "repaired" : "created",
51600
+ path: dst,
51601
+ details: `from ${sourcePath}`
51602
+ };
51603
+ } catch (err) {
51604
+ return {
51605
+ action: "skipped",
51606
+ path: dst,
51607
+ details: `Failed to write identity: ${err instanceof Error ? err.message : String(err)}`
51608
+ };
51609
+ }
51610
+ }
51611
+ function checkGlobalIdentity() {
51612
+ const cleoHome = getCleoHome();
51613
+ const identityPath = join41(cleoHome, "CLEOOS-IDENTITY.md");
51614
+ if (!existsSync40(identityPath)) {
51615
+ return {
51616
+ id: "global_identity",
51617
+ category: "global",
51618
+ status: "failed",
51619
+ message: "Global CLEOOS-IDENTITY.md not found \u2014 orchestrator persona missing",
51620
+ details: { path: identityPath, exists: false },
51621
+ fix: "cleo upgrade (auto-deploys identity)"
51622
+ };
51623
+ }
51624
+ let size = 0;
51625
+ try {
51626
+ size = statSync8(identityPath).size;
51627
+ } catch {
51628
+ }
51629
+ if (size === 0) {
51630
+ return {
51631
+ id: "global_identity",
51632
+ category: "global",
51633
+ status: "failed",
51634
+ message: "Global CLEOOS-IDENTITY.md exists but is empty",
51635
+ details: { path: identityPath, exists: true, size: 0 },
51636
+ fix: "cleo upgrade --refresh-identity"
51637
+ };
51638
+ }
51639
+ return {
51640
+ id: "global_identity",
51641
+ category: "global",
51642
+ status: "passed",
51643
+ message: "Global CLEOOS-IDENTITY.md present",
51644
+ details: { path: identityPath, exists: true, size },
51645
+ fix: ""
51646
+ };
51647
+ }
51561
51648
  function checkGlobalHome() {
51562
51649
  const cleoHome = getCleoHome();
51563
51650
  if (!existsSync40(cleoHome)) {
@@ -55657,7 +55744,7 @@ __export(parser_exports, {
55657
55744
  parseFile: () => parseFile2
55658
55745
  });
55659
55746
  import { readFileSync as readFileSync64 } from "node:fs";
55660
- import { createRequire as createRequire7 } from "node:module";
55747
+ import { createRequire as createRequire8 } from "node:module";
55661
55748
  import { relative as relative7 } from "node:path";
55662
55749
  function tryRequire(id) {
55663
55750
  try {
@@ -55858,7 +55945,7 @@ var init_parser3 = __esm({
55858
55945
  "packages/core/src/code/parser.ts"() {
55859
55946
  "use strict";
55860
55947
  init_tree_sitter_languages();
55861
- _require7 = createRequire7(import.meta.url);
55948
+ _require7 = createRequire8(import.meta.url);
55862
55949
  _ParserClass = null;
55863
55950
  _QueryClass = null;
55864
55951
  _parserInstance = null;
@@ -55964,7 +56051,7 @@ __export(dependencies_exports, {
55964
56051
  getDependencySpecs: () => getDependencySpecs
55965
56052
  });
55966
56053
  import { execFileSync as execFileSync10 } from "node:child_process";
55967
- import { createRequire as createRequire8 } from "node:module";
56054
+ import { createRequire as createRequire9 } from "node:module";
55968
56055
  import { dirname as dirname19 } from "node:path";
55969
56056
  import { fileURLToPath as fileURLToPath5 } from "node:url";
55970
56057
  function tryExec(cmd, args, timeoutMs = 3e3) {
@@ -56237,7 +56324,7 @@ var init_dependencies = __esm({
56237
56324
  "packages/core/src/system/dependencies.ts"() {
56238
56325
  "use strict";
56239
56326
  init_platform();
56240
- _require8 = createRequire8(import.meta.url);
56327
+ _require8 = createRequire9(import.meta.url);
56241
56328
  _dirname = dirname19(fileURLToPath5(import.meta.url));
56242
56329
  DEPENDENCY_SPECS = [
56243
56330
  // ── Required ────────────────────────────────────────────────────────────
@@ -57540,8 +57627,8 @@ import { platform as platform4 } from "node:os";
57540
57627
  import { basename as basename17, dirname as dirname23, join as join107 } from "node:path";
57541
57628
  async function resolveSeedAgentsDir() {
57542
57629
  try {
57543
- const { createRequire: createRequire15 } = await import("node:module");
57544
- const req = createRequire15(import.meta.url);
57630
+ const { createRequire: createRequire16 } = await import("node:module");
57631
+ const req = createRequire16(import.meta.url);
57545
57632
  const agentsPkgMain = req.resolve("@cleocode/agents/package.json");
57546
57633
  const agentsPkgRoot = dirname23(agentsPkgMain);
57547
57634
  const candidate = join107(agentsPkgRoot, "seed-agents");
@@ -57568,8 +57655,8 @@ async function resolveSeedAgentsDir() {
57568
57655
  async function initAgentDefinition(created, warnings) {
57569
57656
  let agentSourceDir = null;
57570
57657
  try {
57571
- const { createRequire: createRequire15 } = await import("node:module");
57572
- const req = createRequire15(import.meta.url);
57658
+ const { createRequire: createRequire16 } = await import("node:module");
57659
+ const req = createRequire16(import.meta.url);
57573
57660
  const agentsPkgMain = req.resolve("@cleocode/agents/package.json");
57574
57661
  const agentsPkgRoot = dirname23(agentsPkgMain);
57575
57662
  const candidate = join107(agentsPkgRoot, "cleo-subagent");
@@ -57635,8 +57722,8 @@ async function initCoreSkills(created, warnings) {
57635
57722
  const packageRoot = getPackageRoot();
57636
57723
  let ctSkillsRoot = null;
57637
57724
  try {
57638
- const { createRequire: createRequire15 } = await import("node:module");
57639
- const req = createRequire15(import.meta.url);
57725
+ const { createRequire: createRequire16 } = await import("node:module");
57726
+ const req = createRequire16(import.meta.url);
57640
57727
  const skillsPkgMain = req.resolve("@cleocode/skills/package.json");
57641
57728
  const skillsPkgRoot = dirname23(skillsPkgMain);
57642
57729
  if (existsSync108(join107(skillsPkgRoot, "skills.json"))) {
@@ -58144,8 +58231,8 @@ async function deployStarterBundle(cleoDir, created, warnings) {
58144
58231
  if (hasCantFiles) return;
58145
58232
  let starterBundleSrc = null;
58146
58233
  try {
58147
- const { createRequire: createRequire15 } = await import("node:module");
58148
- const req = createRequire15(import.meta.url);
58234
+ const { createRequire: createRequire16 } = await import("node:module");
58235
+ const req = createRequire16(import.meta.url);
58149
58236
  const cleoOsPkgMain = req.resolve("@cleocode/cleo-os/package.json");
58150
58237
  const cleoOsPkgRoot = dirname23(cleoOsPkgMain);
58151
58238
  const candidate = join107(cleoOsPkgRoot, "starter-bundle");
@@ -58185,20 +58272,20 @@ async function deployStarterBundle(cleoDir, created, warnings) {
58185
58272
  }
58186
58273
  }
58187
58274
  }
58188
- const identitySrc = join107(starterBundleSrc, "CLEOOS-IDENTITY.md");
58189
- const identityDst = join107(cleoDir, "CLEOOS-IDENTITY.md");
58190
- if (existsSync108(identitySrc) && !existsSync108(identityDst)) {
58191
- await copyFile4(identitySrc, identityDst);
58192
- }
58193
58275
  try {
58194
- const { getCleoHome: getCleoHome2 } = await Promise.resolve().then(() => (init_paths(), paths_exports));
58195
- const globalIdentityDst = join107(getCleoHome2(), "CLEOOS-IDENTITY.md");
58196
- if (existsSync108(identitySrc) && !existsSync108(globalIdentityDst)) {
58197
- await copyFile4(identitySrc, globalIdentityDst);
58276
+ const { ensureGlobalIdentity: ensureGlobalIdentity2 } = await Promise.resolve().then(() => (init_scaffold(), scaffold_exports));
58277
+ const identityResult = await ensureGlobalIdentity2();
58278
+ if (identityResult.action === "created") {
58279
+ created.push(`identity: ${identityResult.path}`);
58280
+ } else if (identityResult.action === "skipped" && identityResult.details) {
58281
+ warnings.push(`identity skipped: ${identityResult.details}`);
58198
58282
  }
58199
- } catch {
58283
+ } catch (err) {
58284
+ warnings.push(`identity deploy failed: ${err instanceof Error ? err.message : String(err)}`);
58200
58285
  }
58201
- created.push("starter-bundle: team + agent .cant files + identity deployed to .cleo/");
58286
+ created.push(
58287
+ "starter-bundle: team + agent .cant files deployed to .cleo/ (identity at global XDG)"
58288
+ );
58202
58289
  }
58203
58290
  var DIR_SYMLINK_TYPE2;
58204
58291
  var init_init = __esm({
@@ -72837,7 +72924,7 @@ function prepareSpawnMulti(skillNames, tokenValues, cwd) {
72837
72924
  const skillName = skillNames[i];
72838
72925
  const isPrimary = i === 0;
72839
72926
  const skill = findSkill(skillName, cwd);
72840
- if (!skill || !skill.content) {
72927
+ if (!skill?.content) {
72841
72928
  continue;
72842
72929
  }
72843
72930
  let content = isPrimary ? skill.content : loadProgressive(skill.content);
@@ -75798,8 +75885,8 @@ init_agent_outputs();
75798
75885
  // packages/core/src/migration/checksum.ts
75799
75886
  import { createHash as createHash8 } from "node:crypto";
75800
75887
  import { readFileSync as readFileSync34 } from "node:fs";
75801
- import { createRequire as createRequire6 } from "node:module";
75802
- var _require6 = createRequire6(import.meta.url);
75888
+ import { createRequire as createRequire7 } from "node:module";
75889
+ var _require6 = createRequire7(import.meta.url);
75803
75890
  var { DatabaseSync: DatabaseSync4 } = _require6("node:sqlite");
75804
75891
  async function computeChecksum2(filePath) {
75805
75892
  const content = readFileSync34(filePath);
@@ -84499,7 +84586,7 @@ async function injectProtocol(skillContent, taskId, tokenValues, cwd, tier) {
84499
84586
  }
84500
84587
  async function orchestratorSpawnSkill(taskId, skillName, tokenValues, cwd, tier) {
84501
84588
  const skill = findSkill(skillName, cwd);
84502
- if (!skill || !skill.content) {
84589
+ if (!skill?.content) {
84503
84590
  throw new CleoError(4 /* NOT_FOUND */, `Skill not found: ${skillName}`, {
84504
84591
  fix: `Check skills directory for ${skillName}/SKILL.md`
84505
84592
  });
@@ -85035,7 +85122,7 @@ async function buildPrompt(taskId, templateName = "TASK-EXECUTOR", cwd, tier) {
85035
85122
  throw new CleoError(4 /* NOT_FOUND */, `Task ${taskId} not found`);
85036
85123
  }
85037
85124
  const skill = findSkill(templateName, cwd);
85038
- if (!skill || !skill.content) {
85125
+ if (!skill?.content) {
85039
85126
  const { canonical } = mapSkillName(templateName);
85040
85127
  throw new CleoError(4 /* NOT_FOUND */, `Skill template ${templateName} not found`, {
85041
85128
  fix: `Expected at skills/${canonical}/SKILL.md`
@@ -87535,7 +87622,7 @@ async function analyzeArchive(opts, accessor) {
87535
87622
  const acc = accessor ?? await getAccessor(opts.cwd);
87536
87623
  const data = await acc.loadArchive();
87537
87624
  const reportType = opts.report ?? "summary";
87538
- if (!data || !data.archivedTasks?.length) {
87625
+ if (!data?.archivedTasks?.length) {
87539
87626
  return {
87540
87627
  report: reportType,
87541
87628
  filters: null,
@@ -88150,7 +88237,7 @@ init_schema_management();
88150
88237
  init_data_accessor();
88151
88238
  import { execFileSync as execFileSync11 } from "node:child_process";
88152
88239
  import { existsSync as existsSync92, readFileSync as readFileSync65, statSync as statSync19 } from "node:fs";
88153
- import { createRequire as createRequire9 } from "node:module";
88240
+ import { createRequire as createRequire10 } from "node:module";
88154
88241
  import { join as join93 } from "node:path";
88155
88242
 
88156
88243
  // packages/core/src/validation/doctor/checks.ts
@@ -88964,7 +89051,7 @@ function calculateHealthStatus(checks) {
88964
89051
 
88965
89052
  // packages/core/src/system/health.ts
88966
89053
  init_dependencies();
88967
- var _require9 = createRequire9(import.meta.url);
89054
+ var _require9 = createRequire10(import.meta.url);
88968
89055
  var databaseSyncCtor = (() => {
88969
89056
  try {
88970
89057
  return _require9("node:sqlite").DatabaseSync;
@@ -89512,6 +89599,7 @@ async function coreDoctorReport(projectRoot) {
89512
89599
  });
89513
89600
  checks.push(mapCheckResult(checkGlobalHome()));
89514
89601
  checks.push(mapCheckResult(checkGlobalTemplates()));
89602
+ checks.push(mapCheckResult(checkGlobalIdentity()));
89515
89603
  checks.push(mapSchemaCheckResult(checkGlobalSchemas()));
89516
89604
  checks.push(mapCheckResult(checkLogDir(projectRoot)));
89517
89605
  const hookResults = await checkGitHooks(projectRoot);
@@ -93466,16 +93554,12 @@ function allEpicChildrenVerified(epicId, tasks2) {
93466
93554
  if (children.length === 0) return false;
93467
93555
  const incomplete = children.filter((t) => t.status !== "done");
93468
93556
  if (incomplete.length > 0) return false;
93469
- const unverified = children.filter(
93470
- (t) => t.status === "done" && (!t.verification || !t.verification.passed)
93471
- );
93557
+ const unverified = children.filter((t) => t.status === "done" && !t.verification?.passed);
93472
93558
  return unverified.length === 0;
93473
93559
  }
93474
93560
  function allSiblingsVerified(parentId, tasks2) {
93475
93561
  const siblings = tasks2.filter((t) => t.parentId === parentId);
93476
- const unverifiedDone = siblings.filter(
93477
- (t) => t.status === "done" && (!t.verification || !t.verification.passed)
93478
- );
93562
+ const unverifiedDone = siblings.filter((t) => t.status === "done" && !t.verification?.passed);
93479
93563
  const incomplete = siblings.filter(
93480
93564
  (t) => t.status === "pending" || t.status === "active" || t.status === "blocked"
93481
93565
  );
@@ -93853,7 +93937,7 @@ import { randomUUID as randomUUID8 } from "node:crypto";
93853
93937
  init_paths();
93854
93938
  import { existsSync as existsSync109, readFileSync as readFileSync77, writeFileSync as writeFileSync20 } from "node:fs";
93855
93939
  import { join as join108 } from "node:path";
93856
- function getCurrentSessionId(cwd) {
93940
+ function getCurrentSessionId2(cwd) {
93857
93941
  if (process.env.CLEO_SESSION) return process.env.CLEO_SESSION;
93858
93942
  const sessionFile = join108(getCleoDir(cwd), ".current-session");
93859
93943
  if (existsSync109(sessionFile)) {
@@ -93881,7 +93965,7 @@ function createCliMeta(operation, duration_ms = 0) {
93881
93965
  duration_ms,
93882
93966
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
93883
93967
  };
93884
- const sessionId = getCurrentSessionId();
93968
+ const sessionId = getCurrentSessionId2();
93885
93969
  if (sessionId) {
93886
93970
  meta3["sessionId"] = sessionId;
93887
93971
  }
@@ -97383,6 +97467,155 @@ async function backfillBrainGraph(projectRoot) {
97383
97467
  };
97384
97468
  }
97385
97469
 
97470
+ // packages/core/src/memory/brain-export.ts
97471
+ init_brain_schema();
97472
+ init_brain_sqlite();
97473
+ async function exportBrainAsGexf(projectRoot) {
97474
+ const db = await getBrainDb(projectRoot);
97475
+ let nodes = [];
97476
+ let edges = [];
97477
+ try {
97478
+ nodes = await db.select({
97479
+ id: brainPageNodes.id,
97480
+ nodeType: brainPageNodes.nodeType,
97481
+ label: brainPageNodes.label,
97482
+ qualityScore: brainPageNodes.qualityScore,
97483
+ contentHash: brainPageNodes.contentHash,
97484
+ lastActivityAt: brainPageNodes.lastActivityAt,
97485
+ metadataJson: brainPageNodes.metadataJson,
97486
+ createdAt: brainPageNodes.createdAt,
97487
+ updatedAt: brainPageNodes.updatedAt
97488
+ }).from(brainPageNodes);
97489
+ } catch {
97490
+ nodes = [];
97491
+ }
97492
+ try {
97493
+ const rawEdges = await db.select({
97494
+ fromId: brainPageEdges.fromId,
97495
+ toId: brainPageEdges.toId,
97496
+ edgeType: brainPageEdges.edgeType,
97497
+ weight: brainPageEdges.weight,
97498
+ createdAt: brainPageEdges.createdAt
97499
+ }).from(brainPageEdges);
97500
+ edges = rawEdges.map((e) => ({ ...e, provenance: null }));
97501
+ } catch {
97502
+ edges = [];
97503
+ }
97504
+ const gexf = buildGexfDocument(nodes, edges);
97505
+ return {
97506
+ success: true,
97507
+ format: "gexf",
97508
+ nodeCount: nodes.length,
97509
+ edgeCount: edges.length,
97510
+ content: gexf,
97511
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString()
97512
+ };
97513
+ }
97514
+ async function exportBrainAsJson(projectRoot) {
97515
+ const db = await getBrainDb(projectRoot);
97516
+ let nodes = [];
97517
+ let edges = [];
97518
+ try {
97519
+ nodes = await db.select({
97520
+ id: brainPageNodes.id,
97521
+ nodeType: brainPageNodes.nodeType,
97522
+ label: brainPageNodes.label,
97523
+ qualityScore: brainPageNodes.qualityScore,
97524
+ contentHash: brainPageNodes.contentHash,
97525
+ lastActivityAt: brainPageNodes.lastActivityAt,
97526
+ metadataJson: brainPageNodes.metadataJson,
97527
+ createdAt: brainPageNodes.createdAt,
97528
+ updatedAt: brainPageNodes.updatedAt
97529
+ }).from(brainPageNodes);
97530
+ } catch {
97531
+ nodes = [];
97532
+ }
97533
+ try {
97534
+ const rawEdges = await db.select({
97535
+ fromId: brainPageEdges.fromId,
97536
+ toId: brainPageEdges.toId,
97537
+ edgeType: brainPageEdges.edgeType,
97538
+ weight: brainPageEdges.weight,
97539
+ createdAt: brainPageEdges.createdAt
97540
+ }).from(brainPageEdges);
97541
+ edges = rawEdges.map((e) => ({ ...e, provenance: null }));
97542
+ } catch {
97543
+ edges = [];
97544
+ }
97545
+ return {
97546
+ success: true,
97547
+ format: "json",
97548
+ nodeCount: nodes.length,
97549
+ edgeCount: edges.length,
97550
+ nodes,
97551
+ edges,
97552
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString()
97553
+ };
97554
+ }
97555
+ function buildGexfDocument(nodes, edges) {
97556
+ const lines = [
97557
+ '<?xml version="1.0" encoding="UTF-8"?>',
97558
+ '<gexf xmlns="http://www.gexf.net/1.3draft" version="1.3">',
97559
+ ' <meta lastmodifieddate="' + (/* @__PURE__ */ new Date()).toISOString() + '">',
97560
+ " <creator>CLEO Brain Export (T626-M6)</creator>",
97561
+ " <description>Living brain knowledge graph (brain_page_nodes + brain_page_edges)</description>",
97562
+ " </meta>",
97563
+ ' <graph mode="static" defaultedgetype="directed">'
97564
+ ];
97565
+ lines.push(' <attributes class="node">');
97566
+ lines.push(' <attribute id="node_type" title="Node Type" type="string"/>');
97567
+ lines.push(' <attribute id="quality_score" title="Quality Score" type="double"/>');
97568
+ lines.push(' <attribute id="content_hash" title="Content Hash" type="string"/>');
97569
+ lines.push(' <attribute id="last_activity_at" title="Last Activity" type="string"/>');
97570
+ lines.push(' <attribute id="created_at" title="Created At" type="string"/>');
97571
+ lines.push(" </attributes>");
97572
+ lines.push(' <attributes class="edge">');
97573
+ lines.push(' <attribute id="edge_type" title="Edge Type" type="string"/>');
97574
+ lines.push(' <attribute id="provenance" title="Provenance" type="string"/>');
97575
+ lines.push(' <attribute id="created_at" title="Created At" type="string"/>');
97576
+ lines.push(" </attributes>");
97577
+ lines.push(" <nodes>");
97578
+ for (const node of nodes) {
97579
+ lines.push(` <node id="${escapeXml(node.id)}" label="${escapeXml(node.label)}">`);
97580
+ lines.push(" <attvalues>");
97581
+ lines.push(` <attvalue for="node_type" value="${escapeXml(node.nodeType)}"/>`);
97582
+ lines.push(` <attvalue for="quality_score" value="${node.qualityScore ?? 0.5}"/>`);
97583
+ if (node.contentHash) {
97584
+ lines.push(` <attvalue for="content_hash" value="${escapeXml(node.contentHash)}"/>`);
97585
+ }
97586
+ lines.push(
97587
+ ` <attvalue for="last_activity_at" value="${escapeXml(node.lastActivityAt)}"/>`
97588
+ );
97589
+ lines.push(` <attvalue for="created_at" value="${escapeXml(node.createdAt)}"/>`);
97590
+ lines.push(" </attvalues>");
97591
+ lines.push(" </node>");
97592
+ }
97593
+ lines.push(" </nodes>");
97594
+ lines.push(" <edges>");
97595
+ for (let i = 0; i < edges.length; i++) {
97596
+ const edge = edges[i];
97597
+ const weight = edge.weight ?? 1;
97598
+ lines.push(
97599
+ ` <edge id="${i}" source="${escapeXml(edge.fromId)}" target="${escapeXml(edge.toId)}" weight="${weight}">`
97600
+ );
97601
+ lines.push(" <attvalues>");
97602
+ lines.push(` <attvalue for="edge_type" value="${escapeXml(edge.edgeType)}"/>`);
97603
+ if (edge.provenance) {
97604
+ lines.push(` <attvalue for="provenance" value="${escapeXml(edge.provenance)}"/>`);
97605
+ }
97606
+ lines.push(` <attvalue for="created_at" value="${escapeXml(edge.createdAt)}"/>`);
97607
+ lines.push(" </attvalues>");
97608
+ lines.push(" </edge>");
97609
+ }
97610
+ lines.push(" </edges>");
97611
+ lines.push(" </graph>");
97612
+ lines.push("</gexf>");
97613
+ return lines.join("\n");
97614
+ }
97615
+ function escapeXml(text3) {
97616
+ return text3.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
97617
+ }
97618
+
97386
97619
  // packages/core/src/internal.ts
97387
97620
  init_brain_lifecycle();
97388
97621
 
@@ -97633,11 +97866,11 @@ init_paths();
97633
97866
  init_brain_sqlite();
97634
97867
  init_brain_search();
97635
97868
  import { existsSync as existsSync111 } from "node:fs";
97636
- import { createRequire as createRequire10 } from "node:module";
97869
+ import { createRequire as createRequire11 } from "node:module";
97637
97870
  function typedAll3(db, sql16) {
97638
97871
  return db.prepare(sql16).all();
97639
97872
  }
97640
- var _require10 = createRequire10(import.meta.url);
97873
+ var _require10 = createRequire11(import.meta.url);
97641
97874
  var { DatabaseSync: DatabaseSync5 } = _require10("node:sqlite");
97642
97875
  var VALID_OBSERVATION_TYPES = /* @__PURE__ */ new Set([
97643
97876
  "discovery",
@@ -97802,7 +98035,7 @@ Use --source <path> to specify a custom location.`
97802
98035
  }
97803
98036
  try {
97804
98037
  for (const row of batch) {
97805
- if (!row.learned || !row.learned.trim()) {
98038
+ if (!row.learned?.trim()) {
97806
98039
  continue;
97807
98040
  }
97808
98041
  const learnId = `CML-${row.id}`;
@@ -100208,7 +100441,7 @@ init_backup();
100208
100441
  // packages/core/src/store/backup-pack.ts
100209
100442
  import crypto5 from "node:crypto";
100210
100443
  import fs4 from "node:fs";
100211
- import { createRequire as createRequire11 } from "node:module";
100444
+ import { createRequire as createRequire12 } from "node:module";
100212
100445
  import os2 from "node:os";
100213
100446
  import path4 from "node:path";
100214
100447
 
@@ -103214,7 +103447,7 @@ function assertT310Ready(projectRoot) {
103214
103447
  }
103215
103448
 
103216
103449
  // packages/core/src/store/backup-pack.ts
103217
- var _require11 = createRequire11(import.meta.url);
103450
+ var _require11 = createRequire12(import.meta.url);
103218
103451
  var { DatabaseSync: DatabaseSync6 } = _require11("node:sqlite");
103219
103452
  function resolveContractsSchemasDir() {
103220
103453
  const candidates = [
@@ -103713,9 +103946,9 @@ init_conduit_sqlite();
103713
103946
  init_global_salt();
103714
103947
  init_signaldock_sqlite();
103715
103948
  import { existsSync as existsSync117, mkdirSync as mkdirSync27, renameSync as renameSync9, unlinkSync as unlinkSync9 } from "node:fs";
103716
- import { createRequire as createRequire12 } from "node:module";
103949
+ import { createRequire as createRequire13 } from "node:module";
103717
103950
  import { join as join114 } from "node:path";
103718
- var _require12 = createRequire12(import.meta.url);
103951
+ var _require12 = createRequire13(import.meta.url);
103719
103952
  var { DatabaseSync: DatabaseSync7 } = _require12("node:sqlite");
103720
103953
  var PROJECT_TIER_TABLES = [
103721
103954
  "messages",
@@ -104160,7 +104393,7 @@ function measureDependencyDepth(taskId, taskMap, visited = /* @__PURE__ */ new S
104160
104393
  if (visited.has(taskId)) return 0;
104161
104394
  visited.add(taskId);
104162
104395
  const task = taskMap.get(taskId);
104163
- if (!task || !task.depends || task.depends.length === 0) return 0;
104396
+ if (!task?.depends || task.depends.length === 0) return 0;
104164
104397
  let maxDepth = 0;
104165
104398
  for (const depId of task.depends) {
104166
104399
  const depth = 1 + measureDependencyDepth(depId, taskMap, visited);
@@ -104514,7 +104747,7 @@ async function coreTaskUnarchive(projectRoot, taskId, params) {
104514
104747
  throw new Error(`Task '${taskId}' already exists in active tasks`);
104515
104748
  }
104516
104749
  const archive = await accessor.loadArchive();
104517
- if (!archive || !archive.archivedTasks) {
104750
+ if (!archive?.archivedTasks) {
104518
104751
  throw new Error("No archive file found");
104519
104752
  }
104520
104753
  const taskIndex = archive.archivedTasks.findIndex((t) => t.id === taskId);
@@ -105875,6 +106108,16 @@ async function runUpgrade(options = {}) {
105875
106108
  }
105876
106109
  } catch {
105877
106110
  }
106111
+ try {
106112
+ const { ensureGlobalIdentity: ensureGlobalIdentity2 } = await Promise.resolve().then(() => (init_scaffold(), scaffold_exports));
106113
+ const identityResult = await ensureGlobalIdentity2();
106114
+ actions.push({
106115
+ action: "global_identity",
106116
+ status: identityResult.action === "created" || identityResult.action === "repaired" ? "applied" : "skipped",
106117
+ details: `${identityResult.path} (${identityResult.details ?? identityResult.action})`
106118
+ });
106119
+ } catch {
106120
+ }
105878
106121
  try {
105879
106122
  const skillsCreated = [];
105880
106123
  const skillsWarnings = [];
@@ -108516,11 +108759,11 @@ init_tasks_schema();
108516
108759
  var import__ = __toESM(require__(), 1);
108517
108760
  import crypto6 from "node:crypto";
108518
108761
  import fs6 from "node:fs";
108519
- import { createRequire as createRequire13 } from "node:module";
108762
+ import { createRequire as createRequire14 } from "node:module";
108520
108763
  import os3 from "node:os";
108521
108764
  import path6 from "node:path";
108522
108765
  import { default as addFormatsImport2 } from "ajv-formats";
108523
- var _require13 = createRequire13(import.meta.url);
108766
+ var _require13 = createRequire14(import.meta.url);
108524
108767
  var { DatabaseSync: DatabaseSync8 } = _require13("node:sqlite");
108525
108768
  var ajv2020Mod = import__.default;
108526
108769
  var Ajv2020 = typeof ajv2020Mod.default === "function" ? ajv2020Mod.default : import__.default;
@@ -110021,7 +110264,7 @@ async function decrypt(ciphertext, projectPath) {
110021
110264
  init_paths();
110022
110265
  import { randomBytes as randomBytes17 } from "node:crypto";
110023
110266
  import { existsSync as existsSync127, mkdirSync as mkdirSync32, readFileSync as readFileSync93, statSync as statSync21, writeFileSync as writeFileSync23 } from "node:fs";
110024
- import { createRequire as createRequire14 } from "node:module";
110267
+ import { createRequire as createRequire15 } from "node:module";
110025
110268
  import { join as join122 } from "node:path";
110026
110269
 
110027
110270
  // packages/core/src/store/api-key-kdf.ts
@@ -110048,7 +110291,7 @@ function deriveApiKey(input) {
110048
110291
  init_conduit_sqlite();
110049
110292
  init_global_salt();
110050
110293
  init_signaldock_sqlite();
110051
- var _require14 = createRequire14(import.meta.url);
110294
+ var _require14 = createRequire15(import.meta.url);
110052
110295
  var { DatabaseSync: DatabaseSync9 } = _require14("node:sqlite");
110053
110296
  var MACHINE_KEY_LENGTH = 32;
110054
110297
  function readMachineKey() {
@@ -110960,6 +111203,8 @@ export {
110960
111203
  ensureSqliteDb,
110961
111204
  estimateContext,
110962
111205
  executeTransfer,
111206
+ exportBrainAsGexf,
111207
+ exportBrainAsJson,
110963
111208
  exportSnapshot,
110964
111209
  exportTasks,
110965
111210
  exportTasksPackage,
@@ -111029,7 +111274,7 @@ export {
111029
111274
  getConfigValue,
111030
111275
  getContextDrift,
111031
111276
  getCriticalPath,
111032
- getCurrentSessionId,
111277
+ getCurrentSessionId2 as getCurrentSessionId,
111033
111278
  getDashboard,
111034
111279
  getDb,
111035
111280
  getDecisionLog,