@cleocode/adapters 2026.4.42 → 2026.4.44

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.
Files changed (88) hide show
  1. package/dist/cant-context.d.ts +35 -0
  2. package/dist/cant-context.d.ts.map +1 -1
  3. package/dist/index.js +153 -37
  4. package/dist/index.js.map +3 -3
  5. package/dist/providers/claude-code/install.d.ts.map +1 -1
  6. package/package.json +7 -5
  7. package/src/cant-context.ts +210 -20
  8. package/src/providers/claude-code/install.ts +1 -5
  9. package/dist/cant-context.js +0 -284
  10. package/dist/cant-context.js.map +0 -1
  11. package/dist/providers/claude-code/adapter.js +0 -187
  12. package/dist/providers/claude-code/adapter.js.map +0 -1
  13. package/dist/providers/claude-code/context-monitor.js +0 -159
  14. package/dist/providers/claude-code/context-monitor.js.map +0 -1
  15. package/dist/providers/claude-code/hooks.js +0 -389
  16. package/dist/providers/claude-code/hooks.js.map +0 -1
  17. package/dist/providers/claude-code/index.js +0 -41
  18. package/dist/providers/claude-code/index.js.map +0 -1
  19. package/dist/providers/claude-code/install.js +0 -199
  20. package/dist/providers/claude-code/install.js.map +0 -1
  21. package/dist/providers/claude-code/paths.js +0 -41
  22. package/dist/providers/claude-code/paths.js.map +0 -1
  23. package/dist/providers/claude-code/spawn.js +0 -185
  24. package/dist/providers/claude-code/spawn.js.map +0 -1
  25. package/dist/providers/claude-code/statusline.js +0 -130
  26. package/dist/providers/claude-code/statusline.js.map +0 -1
  27. package/dist/providers/claude-code/task-sync.js +0 -119
  28. package/dist/providers/claude-code/task-sync.js.map +0 -1
  29. package/dist/providers/claude-code/transport.js +0 -29
  30. package/dist/providers/claude-code/transport.js.map +0 -1
  31. package/dist/providers/codex/adapter.js +0 -146
  32. package/dist/providers/codex/adapter.js.map +0 -1
  33. package/dist/providers/codex/hooks.js +0 -113
  34. package/dist/providers/codex/hooks.js.map +0 -1
  35. package/dist/providers/codex/index.js +0 -39
  36. package/dist/providers/codex/index.js.map +0 -1
  37. package/dist/providers/codex/install.js +0 -124
  38. package/dist/providers/codex/install.js.map +0 -1
  39. package/dist/providers/cursor/adapter.js +0 -151
  40. package/dist/providers/cursor/adapter.js.map +0 -1
  41. package/dist/providers/cursor/hooks.js +0 -208
  42. package/dist/providers/cursor/hooks.js.map +0 -1
  43. package/dist/providers/cursor/index.js +0 -36
  44. package/dist/providers/cursor/index.js.map +0 -1
  45. package/dist/providers/cursor/install.js +0 -180
  46. package/dist/providers/cursor/install.js.map +0 -1
  47. package/dist/providers/cursor/spawn.js +0 -59
  48. package/dist/providers/cursor/spawn.js.map +0 -1
  49. package/dist/providers/gemini-cli/adapter.js +0 -158
  50. package/dist/providers/gemini-cli/adapter.js.map +0 -1
  51. package/dist/providers/gemini-cli/hooks.js +0 -128
  52. package/dist/providers/gemini-cli/hooks.js.map +0 -1
  53. package/dist/providers/gemini-cli/index.js +0 -39
  54. package/dist/providers/gemini-cli/index.js.map +0 -1
  55. package/dist/providers/gemini-cli/install.js +0 -124
  56. package/dist/providers/gemini-cli/install.js.map +0 -1
  57. package/dist/providers/kimi/adapter.js +0 -145
  58. package/dist/providers/kimi/adapter.js.map +0 -1
  59. package/dist/providers/kimi/hooks.js +0 -79
  60. package/dist/providers/kimi/hooks.js.map +0 -1
  61. package/dist/providers/kimi/index.js +0 -39
  62. package/dist/providers/kimi/index.js.map +0 -1
  63. package/dist/providers/kimi/install.js +0 -124
  64. package/dist/providers/kimi/install.js.map +0 -1
  65. package/dist/providers/opencode/adapter.js +0 -166
  66. package/dist/providers/opencode/adapter.js.map +0 -1
  67. package/dist/providers/opencode/hooks.js +0 -206
  68. package/dist/providers/opencode/hooks.js.map +0 -1
  69. package/dist/providers/opencode/index.js +0 -37
  70. package/dist/providers/opencode/index.js.map +0 -1
  71. package/dist/providers/opencode/install.js +0 -115
  72. package/dist/providers/opencode/install.js.map +0 -1
  73. package/dist/providers/opencode/spawn.js +0 -256
  74. package/dist/providers/opencode/spawn.js.map +0 -1
  75. package/dist/providers/pi/adapter.js +0 -220
  76. package/dist/providers/pi/adapter.js.map +0 -1
  77. package/dist/providers/pi/hooks.js +0 -223
  78. package/dist/providers/pi/hooks.js.map +0 -1
  79. package/dist/providers/pi/index.js +0 -38
  80. package/dist/providers/pi/index.js.map +0 -1
  81. package/dist/providers/pi/install.js +0 -175
  82. package/dist/providers/pi/install.js.map +0 -1
  83. package/dist/providers/pi/spawn.js +0 -187
  84. package/dist/providers/pi/spawn.js.map +0 -1
  85. package/dist/providers/shared/transcript-reader.js +0 -124
  86. package/dist/providers/shared/transcript-reader.js.map +0 -1
  87. package/dist/registry.js +0 -92
  88. package/dist/registry.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"install.d.ts","sourceRoot":"","sources":["../../../src/providers/claude-code/install.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAaH,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAgBjG;;;;;;;;;;;;;GAaG;AACH,qBAAa,yBAA0B,YAAW,sBAAsB;IACtE;;;;;OAKG;IACG,OAAO,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,aAAa,CAAC;IAgC9D;;;;OAIG;IACG,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;IAEhC;;;;OAIG;IACG,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;IAkBrC;;;;;;OAMG;IACG,2BAA2B,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIpE;;;;OAIG;IACH,OAAO,CAAC,qBAAqB;IA+B7B;;;;;;;;OAQG;IACH,OAAO,CAAC,eAAe;IAsBvB;;;;OAIG;IACH,OAAO,CAAC,cAAc;CAiCvB"}
1
+ {"version":3,"file":"install.d.ts","sourceRoot":"","sources":["../../../src/providers/claude-code/install.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAaH,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAYjG;;;;;;;;;;;;;GAaG;AACH,qBAAa,yBAA0B,YAAW,sBAAsB;IACtE;;;;;OAKG;IACG,OAAO,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,aAAa,CAAC;IAgC9D;;;;OAIG;IACG,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;IAEhC;;;;OAIG;IACG,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;IAkBrC;;;;;;OAMG;IACG,2BAA2B,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIpE;;;;OAIG;IACH,OAAO,CAAC,qBAAqB;IA+B7B;;;;;;;;OAQG;IACH,OAAO,CAAC,eAAe;IAsBvB;;;;OAIG;IACH,OAAO,CAAC,cAAc;CAiCvB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cleocode/adapters",
3
- "version": "2026.4.42",
3
+ "version": "2026.4.44",
4
4
  "description": "Unified provider adapters for CLEO (Claude Code, OpenCode, Cursor)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -12,8 +12,8 @@
12
12
  }
13
13
  },
14
14
  "dependencies": {
15
- "@cleocode/contracts": "2026.4.42",
16
- "@cleocode/caamp": "2026.4.42"
15
+ "@cleocode/caamp": "2026.4.44",
16
+ "@cleocode/contracts": "2026.4.44"
17
17
  },
18
18
  "license": "MIT",
19
19
  "engines": {
@@ -24,7 +24,8 @@
24
24
  "src"
25
25
  ],
26
26
  "devDependencies": {
27
- "@types/node": "^22.19.15"
27
+ "@types/node": "^22.19.15",
28
+ "vitest": "^4.1.4"
28
29
  },
29
30
  "repository": {
30
31
  "type": "git",
@@ -33,6 +34,7 @@
33
34
  },
34
35
  "scripts": {
35
36
  "build": "tsc",
36
- "build:check": "tsc --noEmit"
37
+ "build:check": "tsc --noEmit",
38
+ "test": "vitest run"
37
39
  }
38
40
  }
@@ -19,9 +19,13 @@
19
19
  * @task T555
20
20
  */
21
21
 
22
+ import { execFile } from 'node:child_process';
22
23
  import { existsSync, readdirSync, readFileSync } from 'node:fs';
23
24
  import { homedir } from 'node:os';
24
25
  import { basename, join } from 'node:path';
26
+ import { promisify } from 'node:util';
27
+
28
+ const execFileAsync = promisify(execFile);
25
29
 
26
30
  // ---------------------------------------------------------------------------
27
31
  // Types
@@ -52,6 +56,17 @@ export interface BuildCantEnrichedPromptOptions {
52
56
  basePrompt: string;
53
57
  /** Agent name for mental model injection. Omit to skip mental model fetch. */
54
58
  agentName?: string;
59
+ /**
60
+ * When true, prepend the CleoOS identity bootstrap from CLEOOS-IDENTITY.md.
61
+ * Intended for the main session agent only — sub-agents get identity via CANT bundle.
62
+ */
63
+ isMainAgent?: boolean;
64
+ /**
65
+ * Pre-compiled CANT bundle string (from a session-level cache).
66
+ * When provided, steps 1–3 (discovery + compile + render) are skipped.
67
+ * Use this to avoid double-compilation when the Pi bridge already compiled the bundle.
68
+ */
69
+ compiledBundle?: string;
55
70
  }
56
71
 
57
72
  // ---------------------------------------------------------------------------
@@ -292,6 +307,161 @@ async function fetchMentalModelInjection(agentName: string, projectRoot: string)
292
307
  }
293
308
  }
294
309
 
310
+ // ---------------------------------------------------------------------------
311
+ // Identity bootstrap (ported from cleo-cant-bridge.ts lines 858-964)
312
+ // ---------------------------------------------------------------------------
313
+
314
+ /**
315
+ * Read CLEOOS-IDENTITY.md from the project or global XDG location.
316
+ *
317
+ * Search order:
318
+ * 1. `<projectDir>/.cleo/CLEOOS-IDENTITY.md` (project-level, deployed by init)
319
+ * 2. `$XDG_DATA_HOME/cleo/CLEOOS-IDENTITY.md` (global XDG default)
320
+ *
321
+ * @param projectDir - The project root directory.
322
+ * @returns The identity file content, or null if not found.
323
+ */
324
+ export function readIdentityFile(projectDir: string): string | null {
325
+ const projectPath = join(projectDir, '.cleo', 'CLEOOS-IDENTITY.md');
326
+ if (existsSync(projectPath)) {
327
+ try {
328
+ const content = readFileSync(projectPath, 'utf-8');
329
+ return content.length > 0 ? content : null;
330
+ } catch {
331
+ // Fall through to global path
332
+ }
333
+ }
334
+
335
+ const home = homedir();
336
+ const xdgData = process.env['XDG_DATA_HOME'] ?? join(home, '.local', 'share');
337
+ const globalPath = join(xdgData, 'cleo', 'CLEOOS-IDENTITY.md');
338
+ if (existsSync(globalPath)) {
339
+ try {
340
+ const content = readFileSync(globalPath, 'utf-8');
341
+ return content.length > 0 ? content : null;
342
+ } catch {
343
+ return null;
344
+ }
345
+ }
346
+
347
+ return null;
348
+ }
349
+
350
+ /**
351
+ * Build the CleoOS identity bootstrap block for the main session agent.
352
+ *
353
+ * Reads CLEOOS-IDENTITY.md from disk and appends live operational context
354
+ * (current session briefing, next tasks, recent brain decisions) gathered
355
+ * via best-effort CLI calls with an 8-second timeout each.
356
+ *
357
+ * Returns an empty string on any failure — never throws.
358
+ *
359
+ * @param projectDir - The project root directory (used for CWD and file lookup).
360
+ * @returns The fully assembled identity block, or "" if unavailable.
361
+ */
362
+ export async function buildIdentityBootstrap(projectDir: string): Promise<string> {
363
+ const identityContent = readIdentityFile(projectDir);
364
+ if (!identityContent) return '';
365
+
366
+ // Gather live operational context in parallel (best-effort, 8s timeout each)
367
+ const [briefingResult, nextResult, memoryResult] = await Promise.allSettled([
368
+ execFileAsync('cleo', ['session', 'briefing', '--json'], {
369
+ timeout: 8_000,
370
+ cwd: projectDir || undefined,
371
+ }),
372
+ execFileAsync('cleo', ['next', '--json', '--limit', '3'], {
373
+ timeout: 8_000,
374
+ cwd: projectDir || undefined,
375
+ }),
376
+ execFileAsync('cleo', ['memory', 'find', 'decision', '--json', '--limit', '5'], {
377
+ timeout: 8_000,
378
+ cwd: projectDir || undefined,
379
+ }),
380
+ ]);
381
+
382
+ const dynamicLines: string[] = [];
383
+
384
+ // Append briefing data if available
385
+ if (briefingResult.status === 'fulfilled') {
386
+ try {
387
+ const briefing = JSON.parse(briefingResult.value.stdout) as {
388
+ data?: {
389
+ currentTask?: { id: string; title: string; status: string };
390
+ handoff?: { note: string };
391
+ };
392
+ };
393
+ const data = briefing?.data ?? (briefing as (typeof briefing)['data']);
394
+ if (data?.currentTask) {
395
+ dynamicLines.push('## Current Task');
396
+ dynamicLines.push(
397
+ `- **${data.currentTask.id}**: ${data.currentTask.title} (${data.currentTask.status})`,
398
+ );
399
+ dynamicLines.push('');
400
+ }
401
+ if (data?.handoff?.note) {
402
+ dynamicLines.push('## Last Session Handoff');
403
+ dynamicLines.push(data.handoff.note);
404
+ dynamicLines.push('');
405
+ }
406
+ } catch {
407
+ /* parse failure — skip briefing data */
408
+ }
409
+ }
410
+
411
+ // Append next tasks
412
+ if (nextResult.status === 'fulfilled') {
413
+ try {
414
+ const next = JSON.parse(nextResult.value.stdout) as {
415
+ data?: { tasks?: Array<{ id: string; title: string; priority?: string }> };
416
+ };
417
+ const tasks = next?.data?.tasks ?? [];
418
+ if (Array.isArray(tasks) && tasks.length > 0) {
419
+ dynamicLines.push('## Next Tasks');
420
+ for (const t of tasks.slice(0, 3)) {
421
+ dynamicLines.push(`- **${t.id}**: ${t.title} (${t.priority ?? 'medium'})`);
422
+ }
423
+ dynamicLines.push('');
424
+ }
425
+ } catch {
426
+ /* parse failure — skip */
427
+ }
428
+ }
429
+
430
+ // Append recent brain decisions
431
+ if (memoryResult.status === 'fulfilled') {
432
+ try {
433
+ const mem = JSON.parse(memoryResult.value.stdout) as {
434
+ data?: { results?: Array<{ id: string; title: string; date?: string }> };
435
+ };
436
+ const results = mem?.data?.results ?? [];
437
+ if (Array.isArray(results) && results.length > 0) {
438
+ dynamicLines.push('## Recent Brain Context');
439
+ for (const r of results.slice(0, 5)) {
440
+ dynamicLines.push(`- [${r.id}] ${r.title} (${r.date ?? ''})`);
441
+ }
442
+ dynamicLines.push('');
443
+ }
444
+ } catch {
445
+ /* parse failure — skip */
446
+ }
447
+ }
448
+
449
+ const sections: string[] = [
450
+ '',
451
+ '===== CLEOOS IDENTITY BOOTSTRAP =====',
452
+ '',
453
+ identityContent.trim(),
454
+ ];
455
+
456
+ if (dynamicLines.length > 0) {
457
+ sections.push('');
458
+ sections.push(...dynamicLines);
459
+ }
460
+
461
+ sections.push('===== END IDENTITY BOOTSTRAP =====');
462
+ return sections.join('\n');
463
+ }
464
+
295
465
  // ---------------------------------------------------------------------------
296
466
  // Main entry point
297
467
  // ---------------------------------------------------------------------------
@@ -320,30 +490,50 @@ async function fetchMentalModelInjection(agentName: string, projectRoot: string)
320
490
  export async function buildCantEnrichedPrompt(
321
491
  options: BuildCantEnrichedPromptOptions,
322
492
  ): Promise<string> {
323
- const { projectDir, basePrompt, agentName } = options;
493
+ const { projectDir, basePrompt, agentName, isMainAgent, compiledBundle } = options;
324
494
  let appendix = '';
325
495
 
326
- // Step 1-3: Discover and compile CANT bundle
496
+ // Step 0: Identity bootstrap for the main session agent.
497
+ // Sub-agents receive identity via the CANT bundle + mental model below.
498
+ if (isMainAgent) {
499
+ try {
500
+ const identityBlock = await buildIdentityBootstrap(projectDir);
501
+ if (identityBlock) {
502
+ appendix += identityBlock;
503
+ }
504
+ } catch {
505
+ // Identity bootstrap failure — non-fatal, continue enrichment
506
+ }
507
+ }
508
+
509
+ // Step 1-3: Discover and compile CANT bundle (or use pre-compiled bundle).
510
+ // When `compiledBundle` is provided (e.g. Pi session cache), skip
511
+ // discovery + compilation to avoid redundant work.
327
512
  try {
328
- const { files } = discoverCantFilesMultiTier(projectDir);
329
-
330
- if (files.length > 0) {
331
- // Dynamic import — @cleocode/cant is NOT a compile-time dependency of adapters.
332
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
333
- const cantModule = (await import(/* webpackIgnore: true */ '@cleocode/cant' as string)) as {
334
- compileBundle?: (paths: string[]) => Promise<{
335
- renderSystemPrompt: () => string;
336
- valid: boolean;
337
- diagnostics: unknown[];
338
- }>;
339
- };
513
+ if (compiledBundle) {
514
+ // Use pre-compiled bundle directly
515
+ appendix += `\n\n${compiledBundle}`;
516
+ } else {
517
+ const { files } = discoverCantFilesMultiTier(projectDir);
518
+
519
+ if (files.length > 0) {
520
+ // Dynamic import — @cleocode/cant is NOT a compile-time dependency of adapters.
521
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
522
+ const cantModule = (await import(/* webpackIgnore: true */ '@cleocode/cant' as string)) as {
523
+ compileBundle?: (paths: string[]) => Promise<{
524
+ renderSystemPrompt: () => string;
525
+ valid: boolean;
526
+ diagnostics: unknown[];
527
+ }>;
528
+ };
340
529
 
341
- if (typeof cantModule.compileBundle === 'function') {
342
- const bundle = await cantModule.compileBundle(files);
343
- if (bundle.valid) {
344
- const rendered = bundle.renderSystemPrompt();
345
- if (rendered) {
346
- appendix += `\n\n${rendered}`;
530
+ if (typeof cantModule.compileBundle === 'function') {
531
+ const bundle = await cantModule.compileBundle(files);
532
+ if (bundle.valid) {
533
+ const rendered = bundle.renderSystemPrompt();
534
+ if (rendered) {
535
+ appendix += `\n\n${rendered}`;
536
+ }
347
537
  }
348
538
  }
349
539
  }
@@ -24,11 +24,7 @@ import { fileURLToPath } from 'node:url';
24
24
  import type { AdapterInstallProvider, InstallOptions, InstallResult } from '@cleocode/contracts';
25
25
 
26
26
  /** Lines that should appear in CLAUDE.md to reference CLEO. */
27
- const INSTRUCTION_REFERENCES = [
28
- '@.cleo/CLEOOS-IDENTITY.md',
29
- '@~/.cleo/templates/CLEO-INJECTION.md',
30
- '@.cleo/memory-bridge.md',
31
- ];
27
+ const INSTRUCTION_REFERENCES = ['@~/.cleo/templates/CLEO-INJECTION.md', '@.cleo/memory-bridge.md'];
32
28
 
33
29
  /** Resolve the commands directory bundled with this adapter. */
34
30
  function getAdapterCommandsDir(): string {
@@ -1,284 +0,0 @@
1
- /**
2
- * Shared CANT context builder for all spawn providers.
3
- *
4
- * Extracts the Pi bridge's CANT discovery/compile/inject logic into a reusable
5
- * module that any spawn provider (Claude Code, OpenCode, Cursor, etc.) can call
6
- * to enrich agent prompts with:
7
- *
8
- * 1. Compiled CANT bundle (team topology, agent personas, tool ACLs)
9
- * 2. Memory bridge (recent decisions, handoff notes, key patterns)
10
- * 3. Mental model injection (validate-on-load agent-specific observations)
11
- *
12
- * All operations are best-effort: if any step fails (missing packages, empty
13
- * directories, compilation errors), the base prompt is returned unchanged.
14
- * This guarantees agents always spawn — CANT context is an enrichment, not a gate.
15
- *
16
- * Reference implementation: packages/cleo-os/extensions/cleo-cant-bridge.ts
17
- * (Pi-only; this module generalizes the same logic for all providers)
18
- *
19
- * @task T555
20
- */
21
- import { existsSync, readdirSync, readFileSync } from 'node:fs';
22
- import { homedir } from 'node:os';
23
- import { basename, join } from 'node:path';
24
- // ---------------------------------------------------------------------------
25
- // Constants
26
- // ---------------------------------------------------------------------------
27
- /**
28
- * Preamble text injected when an agent has mental model observations.
29
- * The agent MUST re-evaluate each observation against current project state.
30
- */
31
- const VALIDATE_ON_LOAD_PREAMBLE = '===== MENTAL MODEL (validate-on-load) =====\n' +
32
- 'These are your prior observations, patterns, and learnings for this project.\n' +
33
- 'Before acting, you MUST re-evaluate each entry against current project state.\n' +
34
- 'If an entry is stale, note it and proceed with fresh understanding.';
35
- // ---------------------------------------------------------------------------
36
- // Discovery functions (ported from cleo-cant-bridge.ts lines 418-526)
37
- // ---------------------------------------------------------------------------
38
- /**
39
- * Recursively discover `.cant` files in a directory.
40
- *
41
- * @param dir - The directory to scan recursively.
42
- * @returns An array of absolute paths to `.cant` files found.
43
- */
44
- export function discoverCantFiles(dir) {
45
- try {
46
- const entries = readdirSync(dir, { recursive: true, withFileTypes: true });
47
- const files = [];
48
- for (const entry of entries) {
49
- if (entry.isFile() && entry.name.endsWith('.cant')) {
50
- const parent = entry.parentPath ?? dir;
51
- files.push(join(parent, entry.name));
52
- }
53
- }
54
- return files;
55
- }
56
- catch {
57
- return [];
58
- }
59
- }
60
- /**
61
- * Resolve XDG-compliant paths for the 3-tier CANT hierarchy.
62
- *
63
- * Respects `XDG_DATA_HOME` and `XDG_CONFIG_HOME` environment variables.
64
- * Falls back to XDG defaults (`~/.local/share/` and `~/.config/`).
65
- *
66
- * @param projectDir - The project root directory (for the project tier).
67
- * @returns An object with `global`, `user`, and `project` CANT directory paths.
68
- */
69
- export function resolveThreeTierPaths(projectDir) {
70
- const home = homedir();
71
- const xdgData = process.env['XDG_DATA_HOME'] ?? join(home, '.local', 'share');
72
- const xdgConfig = process.env['XDG_CONFIG_HOME'] ?? join(home, '.config');
73
- return {
74
- global: join(xdgData, 'cleo', 'cant'),
75
- user: join(xdgConfig, 'cleo', 'cant'),
76
- project: join(projectDir, '.cleo', 'cant'),
77
- };
78
- }
79
- /**
80
- * Discover `.cant` files across all three tiers with override semantics.
81
- *
82
- * Scans global, user, and project tiers. Files in higher-precedence tiers
83
- * override files in lower-precedence tiers that share the same basename.
84
- * The precedence order is: project > user > global.
85
- *
86
- * @param projectDir - The project root directory.
87
- * @returns An object containing the merged file list and per-tier statistics.
88
- */
89
- export function discoverCantFilesMultiTier(projectDir) {
90
- const paths = resolveThreeTierPaths(projectDir);
91
- const globalFiles = discoverCantFiles(paths.global);
92
- const userFiles = discoverCantFiles(paths.user);
93
- const projectFiles = discoverCantFiles(paths.project);
94
- // Build basename-keyed map; lowest precedence first so higher tiers override
95
- const fileMap = new Map();
96
- for (const file of globalFiles) {
97
- fileMap.set(basename(file), file);
98
- }
99
- for (const file of userFiles) {
100
- fileMap.set(basename(file), file);
101
- }
102
- for (const file of projectFiles) {
103
- fileMap.set(basename(file), file);
104
- }
105
- const totalUniqueInputs = globalFiles.length + userFiles.length + projectFiles.length;
106
- const overrides = totalUniqueInputs - fileMap.size;
107
- return {
108
- files: Array.from(fileMap.values()),
109
- stats: {
110
- global: globalFiles.length,
111
- user: userFiles.length,
112
- project: projectFiles.length,
113
- overrides,
114
- merged: fileMap.size,
115
- },
116
- };
117
- }
118
- // ---------------------------------------------------------------------------
119
- // Memory bridge (ported from cleo-cant-bridge.ts lines 376-404)
120
- // ---------------------------------------------------------------------------
121
- /**
122
- * Read the memory bridge file from a project's .cleo/ directory.
123
- *
124
- * @param projectDir - The project root directory.
125
- * @returns The memory bridge content, or null if not found or empty.
126
- */
127
- export function readMemoryBridge(projectDir) {
128
- try {
129
- const bridgePath = join(projectDir, '.cleo', 'memory-bridge.md');
130
- if (!existsSync(bridgePath))
131
- return null;
132
- const content = readFileSync(bridgePath, 'utf-8');
133
- return content.length > 0 ? content : null;
134
- }
135
- catch {
136
- return null;
137
- }
138
- }
139
- /**
140
- * Build the memory-bridge system-prompt block appended to every agent.
141
- *
142
- * Wraps the raw memory-bridge.md content in a clearly labeled section
143
- * so the agent knows this is the CLEO project memory context.
144
- *
145
- * @param content - The raw memory-bridge.md content.
146
- * @returns The formatted memory-bridge block for system prompt injection.
147
- */
148
- export function buildMemoryBridgeBlock(content) {
149
- return ('\n\n===== CLEO MEMORY BRIDGE =====\n' +
150
- 'This is your project memory context from .cleo/memory-bridge.md.\n' +
151
- 'Use it to understand recent decisions, handoff notes, and key patterns.\n\n' +
152
- content.trim() +
153
- '\n===== END MEMORY BRIDGE =====');
154
- }
155
- // ---------------------------------------------------------------------------
156
- // Mental model injection (ported from cleo-cant-bridge.ts lines 113-135, 543-589)
157
- // ---------------------------------------------------------------------------
158
- /**
159
- * Build the validate-on-load mental-model injection string.
160
- *
161
- * Pure function — no I/O, safe to call in tests without a real DB.
162
- *
163
- * @param agentName - Name of the spawned agent (used in the header line).
164
- * @param observations - Prior mental-model observations to list.
165
- * @returns System-prompt block with preamble and numbered observations,
166
- * or empty string when `observations` is empty.
167
- */
168
- export function buildMentalModelInjection(agentName, observations) {
169
- if (observations.length === 0)
170
- return '';
171
- const lines = ['', `// Agent: ${agentName}`, VALIDATE_ON_LOAD_PREAMBLE, ''];
172
- for (let i = 0; i < observations.length; i++) {
173
- const obs = observations[i];
174
- const datePart = obs.date ? ` [${obs.date}]` : '';
175
- lines.push(`${i + 1}. [${obs.id}] (${obs.type})${datePart}: ${obs.title}`);
176
- }
177
- lines.push('===== END MENTAL MODEL =====');
178
- return lines.join('\n');
179
- }
180
- /**
181
- * Fetch mental model observations for an agent from brain.db.
182
- *
183
- * Uses dynamic import of `@cleocode/core` to avoid circular dependencies.
184
- * Returns empty string on any failure (best-effort, never throws).
185
- *
186
- * @param agentName - The agent's name for scoped observation lookup.
187
- * @param projectRoot - Project root directory for brain.db access.
188
- * @returns The validate-on-load system-prompt block, or "" on failure/empty.
189
- */
190
- async function fetchMentalModelInjection(agentName, projectRoot) {
191
- try {
192
- // Dynamic import — @cleocode/core is NOT a compile-time dependency of adapters.
193
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
194
- const coreModule = (await import(/* webpackIgnore: true */ '@cleocode/core'));
195
- if (typeof coreModule.memoryFind !== 'function')
196
- return '';
197
- const result = await coreModule.memoryFind({
198
- query: agentName,
199
- agent: agentName,
200
- limit: 10,
201
- tables: ['observations'],
202
- }, projectRoot);
203
- if (!result.success || !result.data?.results?.length)
204
- return '';
205
- return buildMentalModelInjection(agentName, result.data.results);
206
- }
207
- catch {
208
- return '';
209
- }
210
- }
211
- // ---------------------------------------------------------------------------
212
- // Main entry point
213
- // ---------------------------------------------------------------------------
214
- /**
215
- * Build an enriched prompt with CANT context, memory bridge, and mental model.
216
- *
217
- * This is the universal entry point for all spawn providers. It performs the
218
- * same operations as the Pi bridge (cleo-cant-bridge.ts) but returns a string
219
- * rather than hooking into Pi events:
220
- *
221
- * 1. Discovers `.cant` files across 3 tiers (global → user → project)
222
- * 2. Compiles the CANT bundle via `@cleocode/cant`'s `compileBundle()`
223
- * 3. Renders the compiled system prompt
224
- * 4. Reads the memory bridge from `.cleo/memory-bridge.md`
225
- * 5. Fetches mental model observations for the named agent
226
- * 6. Concatenates: basePrompt + CANT bundle + memory bridge + mental model
227
- *
228
- * All operations are best-effort. If any step fails, the base prompt is
229
- * returned unchanged. CANT context is an enrichment, not a gate — agents
230
- * always spawn regardless of CANT availability.
231
- *
232
- * @param options - Project dir, base prompt, and optional agent name.
233
- * @returns The enriched prompt string, or basePrompt unchanged on failure.
234
- */
235
- export async function buildCantEnrichedPrompt(options) {
236
- const { projectDir, basePrompt, agentName } = options;
237
- let appendix = '';
238
- // Step 1-3: Discover and compile CANT bundle
239
- try {
240
- const { files } = discoverCantFilesMultiTier(projectDir);
241
- if (files.length > 0) {
242
- // Dynamic import — @cleocode/cant is NOT a compile-time dependency of adapters.
243
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
244
- const cantModule = (await import(/* webpackIgnore: true */ '@cleocode/cant'));
245
- if (typeof cantModule.compileBundle === 'function') {
246
- const bundle = await cantModule.compileBundle(files);
247
- if (bundle.valid) {
248
- const rendered = bundle.renderSystemPrompt();
249
- if (rendered) {
250
- appendix += `\n\n${rendered}`;
251
- }
252
- }
253
- }
254
- }
255
- }
256
- catch {
257
- // CANT compilation failure — continue without bundle context
258
- }
259
- // Step 4: Append memory bridge
260
- try {
261
- const bridge = readMemoryBridge(projectDir);
262
- if (bridge) {
263
- appendix += buildMemoryBridgeBlock(bridge);
264
- }
265
- }
266
- catch {
267
- // Memory bridge read failure — non-fatal
268
- }
269
- // Step 5: Append mental model for named agent
270
- if (agentName) {
271
- try {
272
- const mentalModel = await fetchMentalModelInjection(agentName, projectDir);
273
- if (mentalModel) {
274
- appendix += `\n\n${mentalModel}`;
275
- }
276
- }
277
- catch {
278
- // Mental model fetch failure — non-fatal
279
- }
280
- }
281
- // Step 6: Return enriched prompt (or unchanged basePrompt if no context found)
282
- return appendix ? basePrompt + appendix : basePrompt;
283
- }
284
- //# sourceMappingURL=cant-context.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cant-context.js","sourceRoot":"","sources":["../src/cant-context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAChE,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAiC3C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