@cleocode/adapters 2026.4.38 → 2026.4.40
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/cant-context.d.ts +130 -0
- package/dist/cant-context.d.ts.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +491 -213
- package/dist/index.js.map +4 -4
- package/dist/providers/claude-code/adapter.d.ts.map +1 -1
- package/dist/providers/claude-code/hooks.d.ts +23 -11
- package/dist/providers/claude-code/hooks.d.ts.map +1 -1
- package/dist/providers/claude-code/spawn.d.ts.map +1 -1
- package/dist/providers/opencode/spawn.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/__tests__/cant-context.test.ts +248 -0
- package/src/cant-context.ts +379 -0
- package/src/index.ts +3 -0
- package/src/providers/claude-code/adapter.ts +4 -0
- package/src/providers/claude-code/hooks.ts +135 -11
- package/src/providers/claude-code/spawn.ts +15 -1
- package/src/providers/opencode/spawn.ts +30 -11
|
@@ -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[]) => {
|
|
335
|
+
renderSystemPrompt: () => string;
|
|
336
|
+
valid: boolean;
|
|
337
|
+
diagnostics: unknown[];
|
|
338
|
+
};
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
if (typeof cantModule.compileBundle === 'function') {
|
|
342
|
+
const bundle = 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 {
|
|
@@ -123,6 +123,10 @@ export class ClaudeCodeAdapter implements CLEOProviderAdapter {
|
|
|
123
123
|
async initialize(projectDir: string): Promise<void> {
|
|
124
124
|
this.projectDir = projectDir;
|
|
125
125
|
this.initialized = true;
|
|
126
|
+
|
|
127
|
+
// Activate CLEO hook bridge for this project — connects Claude Code
|
|
128
|
+
// native events to CLEO's internal hook dispatch (T555).
|
|
129
|
+
await this.hooks.registerNativeHooks(projectDir);
|
|
126
130
|
}
|
|
127
131
|
|
|
128
132
|
/**
|
|
@@ -16,7 +16,9 @@
|
|
|
16
16
|
* @epic T134
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
19
20
|
import { readdir, readFile } from 'node:fs/promises';
|
|
21
|
+
import { homedir } from 'node:os';
|
|
20
22
|
import { join } from 'node:path';
|
|
21
23
|
import type { AdapterHookProvider } from '@cleocode/contracts';
|
|
22
24
|
|
|
@@ -107,33 +109,146 @@ export class ClaudeCodeHookProvider implements AdapterHookProvider {
|
|
|
107
109
|
return CLAUDE_CODE_EVENT_MAP[providerEvent] ?? null;
|
|
108
110
|
}
|
|
109
111
|
|
|
112
|
+
/** Project directory this hook provider was registered for. */
|
|
113
|
+
private projectDir: string | null = null;
|
|
114
|
+
|
|
110
115
|
/**
|
|
111
116
|
* Register native hooks for a project.
|
|
112
117
|
*
|
|
113
|
-
*
|
|
114
|
-
*
|
|
115
|
-
*
|
|
118
|
+
* Writes CLEO hook entries to `~/.claude/settings.json` so that Claude Code's
|
|
119
|
+
* native event system calls cleo CLI commands when events fire. This bridges
|
|
120
|
+
* Claude Code's event loop to CLEO's internal hook dispatch.
|
|
116
121
|
*
|
|
117
|
-
*
|
|
118
|
-
* `getSupportedCanonicalEvents()` to enumerate all 14 supported hooks.
|
|
122
|
+
* Idempotent: skips writing if CLEO hooks already exist in settings.json.
|
|
119
123
|
*
|
|
120
|
-
*
|
|
121
|
-
*
|
|
124
|
+
* Hook entries registered:
|
|
125
|
+
* - `Stop` → `cleo session end --quiet` (triggers LLM extraction, reflector, consolidation)
|
|
126
|
+
* - `PostToolUse` (Write|Edit) → brain observation for file modifications
|
|
127
|
+
* - `SubagentStop` → brain observation for agent completion
|
|
128
|
+
*
|
|
129
|
+
* @param projectDir - Project directory for context-scoped hook commands
|
|
130
|
+
* @task T164 @task T555
|
|
122
131
|
*/
|
|
123
|
-
async registerNativeHooks(
|
|
132
|
+
async registerNativeHooks(projectDir: string): Promise<void> {
|
|
133
|
+
this.projectDir = projectDir;
|
|
124
134
|
this.registered = true;
|
|
135
|
+
|
|
136
|
+
// Write CLEO hook entries to ~/.claude/settings.json (idempotent)
|
|
137
|
+
try {
|
|
138
|
+
const home = homedir();
|
|
139
|
+
const settingsPath = join(home, '.claude', 'settings.json');
|
|
140
|
+
|
|
141
|
+
let settings: Record<string, unknown> = {};
|
|
142
|
+
if (existsSync(settingsPath)) {
|
|
143
|
+
try {
|
|
144
|
+
settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));
|
|
145
|
+
} catch {
|
|
146
|
+
// Start fresh if settings.json is corrupt
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const hooks = (settings.hooks ?? {}) as Record<string, unknown[]>;
|
|
151
|
+
|
|
152
|
+
// Check if CLEO hooks already registered (look for our marker comment in commands)
|
|
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
|
+
),
|
|
165
|
+
);
|
|
166
|
+
|
|
167
|
+
if (alreadyRegistered) {
|
|
168
|
+
return; // Already wired — idempotent
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Register Stop hook → triggers cleo session end (LLM extraction, reflector, consolidation)
|
|
172
|
+
if (!hooks.Stop) hooks.Stop = [];
|
|
173
|
+
(hooks.Stop as unknown[]).push({
|
|
174
|
+
matcher: '',
|
|
175
|
+
hooks: [
|
|
176
|
+
{
|
|
177
|
+
type: 'command',
|
|
178
|
+
command: `cleo session end --quiet # cleo-hook`,
|
|
179
|
+
},
|
|
180
|
+
],
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
// Register PostToolUse hook → brain observation for file writes
|
|
184
|
+
if (!hooks.PostToolUse) hooks.PostToolUse = [];
|
|
185
|
+
(hooks.PostToolUse as unknown[]).push({
|
|
186
|
+
matcher: 'Write|Edit',
|
|
187
|
+
hooks: [
|
|
188
|
+
{
|
|
189
|
+
type: 'command',
|
|
190
|
+
command: `cleo observe "File modified via $TOOL_NAME" --title "tool-use" --quiet # cleo-hook`,
|
|
191
|
+
},
|
|
192
|
+
],
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
settings.hooks = hooks;
|
|
196
|
+
mkdirSync(join(home, '.claude'), { recursive: true });
|
|
197
|
+
writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n', 'utf-8');
|
|
198
|
+
} catch {
|
|
199
|
+
// Settings write failure is non-fatal — hooks can be registered manually
|
|
200
|
+
}
|
|
125
201
|
}
|
|
126
202
|
|
|
127
203
|
/**
|
|
128
204
|
* Unregister native hooks.
|
|
129
205
|
*
|
|
130
|
-
*
|
|
131
|
-
*
|
|
206
|
+
* Removes CLEO hook entries from `~/.claude/settings.json` by filtering out
|
|
207
|
+
* entries containing the `# cleo-hook` marker.
|
|
132
208
|
*
|
|
133
|
-
* @task T164
|
|
209
|
+
* @task T164 @task T555
|
|
134
210
|
*/
|
|
135
211
|
async unregisterNativeHooks(): Promise<void> {
|
|
136
212
|
this.registered = false;
|
|
213
|
+
this.projectDir = null;
|
|
214
|
+
|
|
215
|
+
try {
|
|
216
|
+
const home = homedir();
|
|
217
|
+
const settingsPath = join(home, '.claude', 'settings.json');
|
|
218
|
+
if (!existsSync(settingsPath)) return;
|
|
219
|
+
|
|
220
|
+
const settings = JSON.parse(readFileSync(settingsPath, 'utf-8')) as Record<string, unknown>;
|
|
221
|
+
const hooks = settings.hooks as Record<string, unknown[]> | undefined;
|
|
222
|
+
if (!hooks) return;
|
|
223
|
+
|
|
224
|
+
// Filter out entries with the cleo-hook marker
|
|
225
|
+
let changed = false;
|
|
226
|
+
for (const [event, entries] of Object.entries(hooks)) {
|
|
227
|
+
if (!Array.isArray(entries)) continue;
|
|
228
|
+
const filtered = entries.filter(
|
|
229
|
+
(e) =>
|
|
230
|
+
!(
|
|
231
|
+
typeof e === 'object' &&
|
|
232
|
+
e !== null &&
|
|
233
|
+
Array.isArray((e as Record<string, unknown>).hooks) &&
|
|
234
|
+
((e as Record<string, unknown>).hooks as Array<Record<string, string>>).some(
|
|
235
|
+
(h) => typeof h.command === 'string' && h.command.includes('# cleo-hook'),
|
|
236
|
+
)
|
|
237
|
+
),
|
|
238
|
+
);
|
|
239
|
+
if (filtered.length !== entries.length) {
|
|
240
|
+
hooks[event] = filtered;
|
|
241
|
+
changed = true;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (changed) {
|
|
246
|
+
settings.hooks = hooks;
|
|
247
|
+
writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n', 'utf-8');
|
|
248
|
+
}
|
|
249
|
+
} catch {
|
|
250
|
+
// Cleanup failure is non-fatal
|
|
251
|
+
}
|
|
137
252
|
}
|
|
138
253
|
|
|
139
254
|
/**
|
|
@@ -143,6 +258,15 @@ export class ClaudeCodeHookProvider implements AdapterHookProvider {
|
|
|
143
258
|
return this.registered;
|
|
144
259
|
}
|
|
145
260
|
|
|
261
|
+
/**
|
|
262
|
+
* Get the project directory this hook provider was registered for.
|
|
263
|
+
*
|
|
264
|
+
* Returns null if hooks have not been registered yet.
|
|
265
|
+
*/
|
|
266
|
+
getProjectDir(): string | null {
|
|
267
|
+
return this.projectDir;
|
|
268
|
+
}
|
|
269
|
+
|
|
146
270
|
/**
|
|
147
271
|
* Get the native→canonical event mapping for introspection and debugging.
|
|
148
272
|
*
|
|
@@ -74,8 +74,22 @@ export class ClaudeCodeSpawnProvider implements AdapterSpawnProvider {
|
|
|
74
74
|
let tmpFile: string | undefined;
|
|
75
75
|
|
|
76
76
|
try {
|
|
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
|
+
}
|
|
90
|
+
|
|
77
91
|
tmpFile = `/tmp/claude-spawn-${instanceId}.txt`;
|
|
78
|
-
await writeFile(tmpFile,
|
|
92
|
+
await writeFile(tmpFile, enrichedPrompt, 'utf-8');
|
|
79
93
|
|
|
80
94
|
const args = ['--allow-insecure', '--no-upgrade-check', tmpFile];
|
|
81
95
|
const spawnOpts: Parameters<typeof nodeSpawn>[2] = {
|
|
@@ -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(
|
|
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
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
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
|
}
|