@cleocode/adapters 2026.4.39 → 2026.4.41

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.
@@ -0,0 +1,379 @@
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
+
22
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
23
+ import { homedir } from 'node:os';
24
+ import { basename, join } from 'node:path';
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // Types
28
+ // ---------------------------------------------------------------------------
29
+
30
+ /** Per-tier file counts for diagnostic reporting. */
31
+ export interface TierDiscoveryStats {
32
+ global: number;
33
+ user: number;
34
+ project: number;
35
+ overrides: number;
36
+ merged: number;
37
+ }
38
+
39
+ /** Minimal observation shape returned by memoryFind / searchBrainCompact. */
40
+ export interface MentalModelObservation {
41
+ id: string;
42
+ type: string;
43
+ title: string;
44
+ date?: string;
45
+ }
46
+
47
+ /** Options for the main enrichment function. */
48
+ export interface BuildCantEnrichedPromptOptions {
49
+ /** Project root directory for .cleo/cant/ discovery and brain.db access. */
50
+ projectDir: string;
51
+ /** The raw prompt to enrich. Returned unchanged if no CANT context is available. */
52
+ basePrompt: string;
53
+ /** Agent name for mental model injection. Omit to skip mental model fetch. */
54
+ agentName?: string;
55
+ }
56
+
57
+ // ---------------------------------------------------------------------------
58
+ // Constants
59
+ // ---------------------------------------------------------------------------
60
+
61
+ /**
62
+ * Preamble text injected when an agent has mental model observations.
63
+ * The agent MUST re-evaluate each observation against current project state.
64
+ */
65
+ const VALIDATE_ON_LOAD_PREAMBLE =
66
+ '===== MENTAL MODEL (validate-on-load) =====\n' +
67
+ 'These are your prior observations, patterns, and learnings for this project.\n' +
68
+ 'Before acting, you MUST re-evaluate each entry against current project state.\n' +
69
+ 'If an entry is stale, note it and proceed with fresh understanding.';
70
+
71
+ // ---------------------------------------------------------------------------
72
+ // Discovery functions (ported from cleo-cant-bridge.ts lines 418-526)
73
+ // ---------------------------------------------------------------------------
74
+
75
+ /**
76
+ * Recursively discover `.cant` files in a directory.
77
+ *
78
+ * @param dir - The directory to scan recursively.
79
+ * @returns An array of absolute paths to `.cant` files found.
80
+ */
81
+ export function discoverCantFiles(dir: string): string[] {
82
+ try {
83
+ const entries = readdirSync(dir, { recursive: true, withFileTypes: true });
84
+ const files: string[] = [];
85
+ for (const entry of entries) {
86
+ if (entry.isFile() && entry.name.endsWith('.cant')) {
87
+ const parent = (entry as unknown as { parentPath?: string }).parentPath ?? dir;
88
+ files.push(join(parent, entry.name));
89
+ }
90
+ }
91
+ return files;
92
+ } catch {
93
+ return [];
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Resolve XDG-compliant paths for the 3-tier CANT hierarchy.
99
+ *
100
+ * Respects `XDG_DATA_HOME` and `XDG_CONFIG_HOME` environment variables.
101
+ * Falls back to XDG defaults (`~/.local/share/` and `~/.config/`).
102
+ *
103
+ * @param projectDir - The project root directory (for the project tier).
104
+ * @returns An object with `global`, `user`, and `project` CANT directory paths.
105
+ */
106
+ export function resolveThreeTierPaths(projectDir: string): {
107
+ global: string;
108
+ user: string;
109
+ project: string;
110
+ } {
111
+ const home = homedir();
112
+ const xdgData = process.env['XDG_DATA_HOME'] ?? join(home, '.local', 'share');
113
+ const xdgConfig = process.env['XDG_CONFIG_HOME'] ?? join(home, '.config');
114
+
115
+ return {
116
+ global: join(xdgData, 'cleo', 'cant'),
117
+ user: join(xdgConfig, 'cleo', 'cant'),
118
+ project: join(projectDir, '.cleo', 'cant'),
119
+ };
120
+ }
121
+
122
+ /**
123
+ * Discover `.cant` files across all three tiers with override semantics.
124
+ *
125
+ * Scans global, user, and project tiers. Files in higher-precedence tiers
126
+ * override files in lower-precedence tiers that share the same basename.
127
+ * The precedence order is: project > user > global.
128
+ *
129
+ * @param projectDir - The project root directory.
130
+ * @returns An object containing the merged file list and per-tier statistics.
131
+ */
132
+ export function discoverCantFilesMultiTier(projectDir: string): {
133
+ files: string[];
134
+ stats: TierDiscoveryStats;
135
+ } {
136
+ const paths = resolveThreeTierPaths(projectDir);
137
+
138
+ const globalFiles = discoverCantFiles(paths.global);
139
+ const userFiles = discoverCantFiles(paths.user);
140
+ const projectFiles = discoverCantFiles(paths.project);
141
+
142
+ // Build basename-keyed map; lowest precedence first so higher tiers override
143
+ const fileMap = new Map<string, string>();
144
+
145
+ for (const file of globalFiles) {
146
+ fileMap.set(basename(file), file);
147
+ }
148
+
149
+ for (const file of userFiles) {
150
+ fileMap.set(basename(file), file);
151
+ }
152
+
153
+ for (const file of projectFiles) {
154
+ fileMap.set(basename(file), file);
155
+ }
156
+
157
+ const totalUniqueInputs = globalFiles.length + userFiles.length + projectFiles.length;
158
+ const overrides = totalUniqueInputs - fileMap.size;
159
+
160
+ return {
161
+ files: Array.from(fileMap.values()),
162
+ stats: {
163
+ global: globalFiles.length,
164
+ user: userFiles.length,
165
+ project: projectFiles.length,
166
+ overrides,
167
+ merged: fileMap.size,
168
+ },
169
+ };
170
+ }
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // Memory bridge (ported from cleo-cant-bridge.ts lines 376-404)
174
+ // ---------------------------------------------------------------------------
175
+
176
+ /**
177
+ * Read the memory bridge file from a project's .cleo/ directory.
178
+ *
179
+ * @param projectDir - The project root directory.
180
+ * @returns The memory bridge content, or null if not found or empty.
181
+ */
182
+ export function readMemoryBridge(projectDir: string): string | null {
183
+ try {
184
+ const bridgePath = join(projectDir, '.cleo', 'memory-bridge.md');
185
+ if (!existsSync(bridgePath)) return null;
186
+ const content = readFileSync(bridgePath, 'utf-8');
187
+ return content.length > 0 ? content : null;
188
+ } catch {
189
+ return null;
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Build the memory-bridge system-prompt block appended to every agent.
195
+ *
196
+ * Wraps the raw memory-bridge.md content in a clearly labeled section
197
+ * so the agent knows this is the CLEO project memory context.
198
+ *
199
+ * @param content - The raw memory-bridge.md content.
200
+ * @returns The formatted memory-bridge block for system prompt injection.
201
+ */
202
+ export function buildMemoryBridgeBlock(content: string): string {
203
+ return (
204
+ '\n\n===== CLEO MEMORY BRIDGE =====\n' +
205
+ 'This is your project memory context from .cleo/memory-bridge.md.\n' +
206
+ 'Use it to understand recent decisions, handoff notes, and key patterns.\n\n' +
207
+ content.trim() +
208
+ '\n===== END MEMORY BRIDGE ====='
209
+ );
210
+ }
211
+
212
+ // ---------------------------------------------------------------------------
213
+ // Mental model injection (ported from cleo-cant-bridge.ts lines 113-135, 543-589)
214
+ // ---------------------------------------------------------------------------
215
+
216
+ /**
217
+ * Build the validate-on-load mental-model injection string.
218
+ *
219
+ * Pure function — no I/O, safe to call in tests without a real DB.
220
+ *
221
+ * @param agentName - Name of the spawned agent (used in the header line).
222
+ * @param observations - Prior mental-model observations to list.
223
+ * @returns System-prompt block with preamble and numbered observations,
224
+ * or empty string when `observations` is empty.
225
+ */
226
+ export function buildMentalModelInjection(
227
+ agentName: string,
228
+ observations: MentalModelObservation[],
229
+ ): string {
230
+ if (observations.length === 0) return '';
231
+
232
+ const lines: string[] = ['', `// Agent: ${agentName}`, VALIDATE_ON_LOAD_PREAMBLE, ''];
233
+
234
+ for (let i = 0; i < observations.length; i++) {
235
+ const obs = observations[i];
236
+ const datePart = obs.date ? ` [${obs.date}]` : '';
237
+ lines.push(`${i + 1}. [${obs.id}] (${obs.type})${datePart}: ${obs.title}`);
238
+ }
239
+
240
+ lines.push('===== END MENTAL MODEL =====');
241
+ return lines.join('\n');
242
+ }
243
+
244
+ /**
245
+ * Fetch mental model observations for an agent from brain.db.
246
+ *
247
+ * Uses dynamic import of `@cleocode/core` to avoid circular dependencies.
248
+ * Returns empty string on any failure (best-effort, never throws).
249
+ *
250
+ * @param agentName - The agent's name for scoped observation lookup.
251
+ * @param projectRoot - Project root directory for brain.db access.
252
+ * @returns The validate-on-load system-prompt block, or "" on failure/empty.
253
+ */
254
+ async function fetchMentalModelInjection(agentName: string, projectRoot: string): Promise<string> {
255
+ try {
256
+ // Dynamic import — @cleocode/core is NOT a compile-time dependency of adapters.
257
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
258
+ const coreModule = (await import(/* webpackIgnore: true */ '@cleocode/core' as string)) as {
259
+ memoryFind?: (
260
+ params: {
261
+ query: string;
262
+ agent?: string;
263
+ limit?: number;
264
+ tables?: string[];
265
+ },
266
+ projectRoot?: string,
267
+ ) => Promise<{
268
+ success: boolean;
269
+ data?: {
270
+ results?: MentalModelObservation[];
271
+ };
272
+ }>;
273
+ };
274
+
275
+ if (typeof coreModule.memoryFind !== 'function') return '';
276
+
277
+ const result = await coreModule.memoryFind(
278
+ {
279
+ query: agentName,
280
+ agent: agentName,
281
+ limit: 10,
282
+ tables: ['observations'],
283
+ },
284
+ projectRoot,
285
+ );
286
+
287
+ if (!result.success || !result.data?.results?.length) return '';
288
+
289
+ return buildMentalModelInjection(agentName, result.data.results);
290
+ } catch {
291
+ return '';
292
+ }
293
+ }
294
+
295
+ // ---------------------------------------------------------------------------
296
+ // Main entry point
297
+ // ---------------------------------------------------------------------------
298
+
299
+ /**
300
+ * Build an enriched prompt with CANT context, memory bridge, and mental model.
301
+ *
302
+ * This is the universal entry point for all spawn providers. It performs the
303
+ * same operations as the Pi bridge (cleo-cant-bridge.ts) but returns a string
304
+ * rather than hooking into Pi events:
305
+ *
306
+ * 1. Discovers `.cant` files across 3 tiers (global → user → project)
307
+ * 2. Compiles the CANT bundle via `@cleocode/cant`'s `compileBundle()`
308
+ * 3. Renders the compiled system prompt
309
+ * 4. Reads the memory bridge from `.cleo/memory-bridge.md`
310
+ * 5. Fetches mental model observations for the named agent
311
+ * 6. Concatenates: basePrompt + CANT bundle + memory bridge + mental model
312
+ *
313
+ * All operations are best-effort. If any step fails, the base prompt is
314
+ * returned unchanged. CANT context is an enrichment, not a gate — agents
315
+ * always spawn regardless of CANT availability.
316
+ *
317
+ * @param options - Project dir, base prompt, and optional agent name.
318
+ * @returns The enriched prompt string, or basePrompt unchanged on failure.
319
+ */
320
+ export async function buildCantEnrichedPrompt(
321
+ options: BuildCantEnrichedPromptOptions,
322
+ ): Promise<string> {
323
+ const { projectDir, basePrompt, agentName } = options;
324
+ let appendix = '';
325
+
326
+ // Step 1-3: Discover and compile CANT bundle
327
+ 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
+ };
340
+
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}`;
347
+ }
348
+ }
349
+ }
350
+ }
351
+ } catch {
352
+ // CANT compilation failure — continue without bundle context
353
+ }
354
+
355
+ // Step 4: Append memory bridge
356
+ try {
357
+ const bridge = readMemoryBridge(projectDir);
358
+ if (bridge) {
359
+ appendix += buildMemoryBridgeBlock(bridge);
360
+ }
361
+ } catch {
362
+ // Memory bridge read failure — non-fatal
363
+ }
364
+
365
+ // Step 5: Append mental model for named agent
366
+ if (agentName) {
367
+ try {
368
+ const mentalModel = await fetchMentalModelInjection(agentName, projectDir);
369
+ if (mentalModel) {
370
+ appendix += `\n\n${mentalModel}`;
371
+ }
372
+ } catch {
373
+ // Mental model fetch failure — non-fatal
374
+ }
375
+ }
376
+
377
+ // Step 6: Return enriched prompt (or unchanged basePrompt if no context found)
378
+ return appendix ? basePrompt + appendix : basePrompt;
379
+ }
package/src/index.ts CHANGED
@@ -13,6 +13,9 @@
13
13
  * registry enable dynamic adapter loading by AdapterManager.
14
14
  */
15
15
 
16
+ export type { BuildCantEnrichedPromptOptions, TierDiscoveryStats } from './cant-context.js';
17
+ // Shared CANT context builder — used by all spawn providers
18
+ export { buildCantEnrichedPrompt } from './cant-context.js';
16
19
  // Re-export adapter classes for direct use
17
20
  // Per-provider factory functions (renamed to avoid collisions)
18
21
  export {
@@ -150,17 +150,18 @@ export class ClaudeCodeHookProvider implements AdapterHookProvider {
150
150
  const hooks = (settings.hooks ?? {}) as Record<string, unknown[]>;
151
151
 
152
152
  // Check if CLEO hooks already registered (look for our marker comment in commands)
153
- const alreadyRegistered = Object.values(hooks).some((entries) =>
154
- Array.isArray(entries) &&
155
- entries.some(
156
- (e) =>
157
- typeof e === 'object' &&
158
- e !== null &&
159
- Array.isArray((e as Record<string, unknown>).hooks) &&
160
- ((e as Record<string, unknown>).hooks as Array<Record<string, string>>).some(
161
- (h) => typeof h.command === 'string' && h.command.includes('# cleo-hook'),
162
- ),
163
- ),
153
+ const alreadyRegistered = Object.values(hooks).some(
154
+ (entries) =>
155
+ Array.isArray(entries) &&
156
+ entries.some(
157
+ (e) =>
158
+ typeof e === 'object' &&
159
+ e !== null &&
160
+ Array.isArray((e as Record<string, unknown>).hooks) &&
161
+ ((e as Record<string, unknown>).hooks as Array<Record<string, string>>).some(
162
+ (h) => typeof h.command === 'string' && h.command.includes('# cleo-hook'),
163
+ ),
164
+ ),
164
165
  );
165
166
 
166
167
  if (alreadyRegistered) {
@@ -74,13 +74,36 @@ export class ClaudeCodeSpawnProvider implements AdapterSpawnProvider {
74
74
  let tmpFile: string | undefined;
75
75
 
76
76
  try {
77
- tmpFile = `/tmp/claude-spawn-${instanceId}.txt`;
78
- await writeFile(tmpFile, context.prompt, 'utf-8');
77
+ // Enrich prompt with CANT bundle, memory bridge, and mental model (T555).
78
+ // Best-effort: if CANT context is unavailable, the raw prompt is used.
79
+ let enrichedPrompt = context.prompt;
80
+ try {
81
+ const { buildCantEnrichedPrompt } = await import('../../cant-context.js');
82
+ enrichedPrompt = await buildCantEnrichedPrompt({
83
+ projectDir: context.workingDirectory ?? process.cwd(),
84
+ basePrompt: context.prompt,
85
+ agentName: (context.options?.agentName as string) ?? undefined,
86
+ });
87
+ } catch {
88
+ // CANT enrichment unavailable — use raw prompt
89
+ }
79
90
 
80
- const args = ['--allow-insecure', '--no-upgrade-check', tmpFile];
91
+ tmpFile = `/tmp/claude-spawn-${instanceId}.txt`;
92
+ await writeFile(tmpFile, enrichedPrompt, 'utf-8');
93
+
94
+ // --print: non-interactive batch mode (process prompt, output response, exit)
95
+ // --dangerously-skip-permissions: allow all tool calls without human approval
96
+ // --output-format json: structured output for parsing
97
+ const args = [
98
+ '--print',
99
+ '--dangerously-skip-permissions',
100
+ '--output-format',
101
+ 'json',
102
+ tmpFile,
103
+ ];
81
104
  const spawnOpts: Parameters<typeof nodeSpawn>[2] = {
82
105
  detached: true,
83
- stdio: 'ignore',
106
+ stdio: ['ignore', 'pipe', 'pipe'],
84
107
  };
85
108
 
86
109
  if (context.workingDirectory) {
@@ -80,18 +80,23 @@ export function buildOpenCodeAgentMarkdown(description: string, instructions: st
80
80
  * @param workingDirectory - Project root directory
81
81
  * @returns The agent name to use for spawning
82
82
  */
83
- async function ensureSubagentDefinition(workingDirectory: string): Promise<string> {
83
+ async function ensureSubagentDefinition(
84
+ workingDirectory: string,
85
+ enrichedInstructions?: string,
86
+ ): Promise<string> {
84
87
  const agentDir = join(workingDirectory, '.opencode', 'agent');
85
88
  const agentPath = join(agentDir, `${OPENCODE_SUBAGENT_NAME}.md`);
86
- const description = 'CLEO task executor with protocol compliance.';
87
- const instructions = [
88
- '# CLEO Subagent',
89
- '',
90
- 'You are a CLEO subagent executing a delegated task.',
91
- 'Follow the CLEO protocol and complete the assigned work.',
92
- '',
93
- '@~/.cleo/templates/CLEO-INJECTION.md',
94
- ].join('\n');
89
+ const description = 'CLEO task executor with protocol compliance and CANT context.';
90
+ const instructions =
91
+ enrichedInstructions ??
92
+ [
93
+ '# CLEO Subagent',
94
+ '',
95
+ 'You are a CLEO subagent executing a delegated task.',
96
+ 'Follow the CLEO protocol and complete the assigned work.',
97
+ '',
98
+ '@~/.cleo/templates/CLEO-INJECTION.md',
99
+ ].join('\n');
95
100
 
96
101
  const content = buildOpenCodeAgentMarkdown(description, instructions);
97
102
 
@@ -160,9 +165,23 @@ export class OpenCodeSpawnProvider implements AdapterSpawnProvider {
160
165
  const workingDirectory = context.workingDirectory ?? process.cwd();
161
166
 
162
167
  try {
168
+ // Enrich prompt with CANT bundle, memory bridge, and mental model (T555).
169
+ // Best-effort: if CANT context is unavailable, the raw prompt is used.
170
+ let enrichedInstructions: string | undefined;
171
+ try {
172
+ const { buildCantEnrichedPrompt } = await import('../../cant-context.js');
173
+ enrichedInstructions = await buildCantEnrichedPrompt({
174
+ projectDir: workingDirectory,
175
+ basePrompt: context.prompt,
176
+ agentName: (context.options?.agentName as string) ?? undefined,
177
+ });
178
+ } catch {
179
+ // CANT enrichment unavailable — use raw prompt
180
+ }
181
+
163
182
  let agentName: string;
164
183
  try {
165
- agentName = await ensureSubagentDefinition(workingDirectory);
184
+ agentName = await ensureSubagentDefinition(workingDirectory, enrichedInstructions);
166
185
  } catch {
167
186
  agentName = OPENCODE_FALLBACK_AGENT;
168
187
  }