@cleocode/core 2026.3.71 → 2026.3.73
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/cleo.d.ts.map +1 -1
- package/dist/hooks/handlers/agent-hooks.d.ts +48 -0
- package/dist/hooks/handlers/agent-hooks.d.ts.map +1 -0
- package/dist/hooks/handlers/context-hooks.d.ts +53 -0
- package/dist/hooks/handlers/context-hooks.d.ts.map +1 -0
- package/dist/hooks/handlers/error-hooks.d.ts +4 -4
- package/dist/hooks/handlers/error-hooks.d.ts.map +1 -1
- package/dist/hooks/handlers/file-hooks.d.ts +3 -3
- package/dist/hooks/handlers/file-hooks.d.ts.map +1 -1
- package/dist/hooks/handlers/index.d.ts +8 -1
- package/dist/hooks/handlers/index.d.ts.map +1 -1
- package/dist/hooks/handlers/mcp-hooks.d.ts +29 -7
- package/dist/hooks/handlers/mcp-hooks.d.ts.map +1 -1
- package/dist/hooks/handlers/session-hooks.d.ts +5 -5
- package/dist/hooks/handlers/session-hooks.d.ts.map +1 -1
- package/dist/hooks/handlers/task-hooks.d.ts +5 -5
- package/dist/hooks/handlers/task-hooks.d.ts.map +1 -1
- package/dist/hooks/handlers/work-capture-hooks.d.ts +7 -7
- package/dist/hooks/handlers/work-capture-hooks.d.ts.map +1 -1
- package/dist/hooks/payload-schemas.d.ts +177 -11
- package/dist/hooks/payload-schemas.d.ts.map +1 -1
- package/dist/hooks/provider-hooks.d.ts +33 -7
- package/dist/hooks/provider-hooks.d.ts.map +1 -1
- package/dist/hooks/registry.d.ts +26 -6
- package/dist/hooks/registry.d.ts.map +1 -1
- package/dist/hooks/types.d.ts +132 -38
- package/dist/hooks/types.d.ts.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +497 -59
- package/dist/index.js.map +4 -4
- package/dist/sessions/snapshot.d.ts +125 -0
- package/dist/sessions/snapshot.d.ts.map +1 -0
- package/package.json +6 -6
- package/src/cleo.ts +12 -0
- package/src/hooks/handlers/__tests__/hook-automation-e2e.test.ts +634 -0
- package/src/hooks/handlers/agent-hooks.ts +148 -0
- package/src/hooks/handlers/context-hooks.ts +156 -0
- package/src/hooks/handlers/error-hooks.ts +8 -5
- package/src/hooks/handlers/file-hooks.ts +6 -4
- package/src/hooks/handlers/index.ts +12 -1
- package/src/hooks/handlers/mcp-hooks.ts +74 -9
- package/src/hooks/handlers/session-hooks.ts +7 -7
- package/src/hooks/handlers/task-hooks.ts +7 -7
- package/src/hooks/handlers/work-capture-hooks.ts +12 -12
- package/src/hooks/payload-schemas.ts +96 -26
- package/src/hooks/provider-hooks.ts +50 -9
- package/src/hooks/registry.ts +86 -23
- package/src/hooks/types.ts +175 -39
- package/src/index.ts +10 -0
- package/src/sessions/index.ts +4 -4
- package/src/sessions/snapshot.ts +343 -0
- package/src/store/json.ts +2 -2
- package/src/task-work/index.ts +4 -4
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session snapshot serialization and restoration.
|
|
3
|
+
*
|
|
4
|
+
* Provides `serializeSession()` and `restoreSession()` for full session
|
|
5
|
+
* state capture and hydration. Designed for CleoOS agent session persistence:
|
|
6
|
+
* when an agent dies, CleoOS serializes the session snapshot, and when a new
|
|
7
|
+
* agent connects, it restores the snapshot to resume seamlessly.
|
|
8
|
+
*
|
|
9
|
+
* The snapshot captures everything needed to resume work:
|
|
10
|
+
* - Full session object (scope, taskWork, notes, stats)
|
|
11
|
+
* - Handoff data (completed tasks, decisions, next suggested)
|
|
12
|
+
* - Brain context (recent observations linked to this session)
|
|
13
|
+
* - Active task state (current focus, blockers)
|
|
14
|
+
*
|
|
15
|
+
* @module sessions/snapshot
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import type { Session } from '@cleocode/contracts';
|
|
19
|
+
import { ExitCode } from '@cleocode/contracts';
|
|
20
|
+
import { CleoError } from '../errors.js';
|
|
21
|
+
import type { DataAccessor } from '../store/data-accessor.js';
|
|
22
|
+
import { getAccessor } from '../store/data-accessor.js';
|
|
23
|
+
import { getDecisionLog } from './decisions.js';
|
|
24
|
+
import { computeHandoff, type HandoffData } from './handoff.js';
|
|
25
|
+
|
|
26
|
+
// ============================================================================
|
|
27
|
+
// Snapshot types
|
|
28
|
+
// ============================================================================
|
|
29
|
+
|
|
30
|
+
/** Version of the snapshot schema. Increment on breaking changes. */
|
|
31
|
+
export const SNAPSHOT_VERSION = 1;
|
|
32
|
+
|
|
33
|
+
/** A decision recorded during the session. */
|
|
34
|
+
export interface SnapshotDecision {
|
|
35
|
+
/** Decision text. */
|
|
36
|
+
decision: string;
|
|
37
|
+
/** Rationale for the decision. */
|
|
38
|
+
rationale: string;
|
|
39
|
+
/** Task ID context. */
|
|
40
|
+
taskId: string;
|
|
41
|
+
/** When the decision was recorded. */
|
|
42
|
+
recordedAt: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Brain observation linked to this session. */
|
|
46
|
+
export interface SnapshotObservation {
|
|
47
|
+
/** Observation ID. */
|
|
48
|
+
id: string;
|
|
49
|
+
/** Observation text. */
|
|
50
|
+
text: string;
|
|
51
|
+
/** Observation type (discovery, change, feature, etc.). */
|
|
52
|
+
type: string;
|
|
53
|
+
/** When the observation was created. */
|
|
54
|
+
createdAt: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Active task context at snapshot time. */
|
|
58
|
+
export interface SnapshotTaskContext {
|
|
59
|
+
/** Task ID currently in focus. */
|
|
60
|
+
taskId: string;
|
|
61
|
+
/** Task title. */
|
|
62
|
+
title: string;
|
|
63
|
+
/** Task status. */
|
|
64
|
+
status: string;
|
|
65
|
+
/** Task priority. */
|
|
66
|
+
priority: string;
|
|
67
|
+
/** Task description (truncated to save space). */
|
|
68
|
+
description: string;
|
|
69
|
+
/** Acceptance criteria if any. */
|
|
70
|
+
acceptance?: string;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Complete session snapshot — everything needed to resume.
|
|
75
|
+
*
|
|
76
|
+
* This is the serialization format. It is JSON-safe and can be stored
|
|
77
|
+
* in a file, database column, or transmitted over the network.
|
|
78
|
+
*/
|
|
79
|
+
export interface SessionSnapshot {
|
|
80
|
+
/** Schema version for forward compatibility. */
|
|
81
|
+
version: number;
|
|
82
|
+
/** When the snapshot was created. */
|
|
83
|
+
capturedAt: string;
|
|
84
|
+
/** The full session object. */
|
|
85
|
+
session: Session;
|
|
86
|
+
/** Computed handoff data. */
|
|
87
|
+
handoff: HandoffData;
|
|
88
|
+
/** Decisions recorded in this session. */
|
|
89
|
+
decisions: SnapshotDecision[];
|
|
90
|
+
/** Recent brain observations linked to this session. */
|
|
91
|
+
observations: SnapshotObservation[];
|
|
92
|
+
/** Current task context (if a task is focused). */
|
|
93
|
+
activeTask: SnapshotTaskContext | null;
|
|
94
|
+
/** Session duration in minutes at snapshot time. */
|
|
95
|
+
durationMinutes: number;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Options for serializing a session. */
|
|
99
|
+
export interface SerializeOptions {
|
|
100
|
+
/** Session ID to serialize. If omitted, uses the active session. */
|
|
101
|
+
sessionId?: string;
|
|
102
|
+
/** Maximum number of brain observations to include. Default: 10. */
|
|
103
|
+
maxObservations?: number;
|
|
104
|
+
/** Maximum description length for active task. Default: 500. */
|
|
105
|
+
maxDescriptionLength?: number;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Options for restoring a session. */
|
|
109
|
+
export interface RestoreOptions {
|
|
110
|
+
/** Agent identifier for the new agent taking over. */
|
|
111
|
+
agent?: string;
|
|
112
|
+
/** Whether to resume the session (set status to active). Default: true. */
|
|
113
|
+
activate?: boolean;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ============================================================================
|
|
117
|
+
// Serialize
|
|
118
|
+
// ============================================================================
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Serialize a session into a complete snapshot.
|
|
122
|
+
*
|
|
123
|
+
* Captures the full session state including handoff data, decisions,
|
|
124
|
+
* brain observations, and active task context. The result is a
|
|
125
|
+
* JSON-serializable object that can be stored and later restored.
|
|
126
|
+
*
|
|
127
|
+
* @param projectRoot - Project root directory
|
|
128
|
+
* @param options - Serialization options
|
|
129
|
+
* @returns Complete session snapshot
|
|
130
|
+
*/
|
|
131
|
+
export async function serializeSession(
|
|
132
|
+
projectRoot: string,
|
|
133
|
+
options: SerializeOptions = {},
|
|
134
|
+
accessor?: DataAccessor,
|
|
135
|
+
): Promise<SessionSnapshot> {
|
|
136
|
+
const acc = accessor ?? (await getAccessor(projectRoot));
|
|
137
|
+
const maxObs = options.maxObservations ?? 10;
|
|
138
|
+
const maxDescLen = options.maxDescriptionLength ?? 500;
|
|
139
|
+
|
|
140
|
+
// Find the session
|
|
141
|
+
const sessions = await acc.loadSessions();
|
|
142
|
+
let session: Session | undefined;
|
|
143
|
+
|
|
144
|
+
if (options.sessionId) {
|
|
145
|
+
session = sessions.find((s) => s.id === options.sessionId);
|
|
146
|
+
} else {
|
|
147
|
+
// Find the active session
|
|
148
|
+
session = sessions
|
|
149
|
+
.filter((s) => s.status === 'active')
|
|
150
|
+
.sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime())[0];
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (!session) {
|
|
154
|
+
throw new CleoError(
|
|
155
|
+
ExitCode.SESSION_NOT_FOUND,
|
|
156
|
+
options.sessionId
|
|
157
|
+
? `Session '${options.sessionId}' not found`
|
|
158
|
+
: 'No active session to serialize',
|
|
159
|
+
{ fix: "Use 'cleo session list' to see available sessions" },
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Compute handoff data
|
|
164
|
+
const handoff = await computeHandoff(projectRoot, { sessionId: session.id });
|
|
165
|
+
|
|
166
|
+
// Get decisions
|
|
167
|
+
const decisionLog = await getDecisionLog(projectRoot, { sessionId: session.id });
|
|
168
|
+
const decisions: SnapshotDecision[] = decisionLog.map((d) => ({
|
|
169
|
+
decision: d.decision,
|
|
170
|
+
rationale: d.rationale,
|
|
171
|
+
taskId: d.taskId,
|
|
172
|
+
recordedAt: d.timestamp ?? new Date().toISOString(),
|
|
173
|
+
}));
|
|
174
|
+
|
|
175
|
+
// Get brain observations linked to this session (best-effort)
|
|
176
|
+
let observations: SnapshotObservation[] = [];
|
|
177
|
+
try {
|
|
178
|
+
const { searchBrainCompact } = await import('../memory/brain-retrieval.js');
|
|
179
|
+
const results = await searchBrainCompact(projectRoot, {
|
|
180
|
+
query: session.id,
|
|
181
|
+
limit: maxObs,
|
|
182
|
+
tables: ['observations'],
|
|
183
|
+
});
|
|
184
|
+
if (Array.isArray(results)) {
|
|
185
|
+
observations = results.map(
|
|
186
|
+
(r: { id: string; text?: string; type?: string; createdAt?: string }) => ({
|
|
187
|
+
id: r.id,
|
|
188
|
+
text: r.text ?? '',
|
|
189
|
+
type: r.type ?? 'discovery',
|
|
190
|
+
createdAt: r.createdAt ?? '',
|
|
191
|
+
}),
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
} catch {
|
|
195
|
+
// Brain search is best-effort — snapshot works without it
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// Get active task context
|
|
199
|
+
let activeTask: SnapshotTaskContext | null = null;
|
|
200
|
+
if (session.taskWork?.taskId) {
|
|
201
|
+
try {
|
|
202
|
+
const { tasks } = await acc.queryTasks({});
|
|
203
|
+
const task = tasks.find((t) => t.id === session.taskWork?.taskId);
|
|
204
|
+
if (task) {
|
|
205
|
+
const desc = task.description ?? '';
|
|
206
|
+
activeTask = {
|
|
207
|
+
taskId: task.id,
|
|
208
|
+
title: task.title,
|
|
209
|
+
status: task.status,
|
|
210
|
+
priority: task.priority ?? 'medium',
|
|
211
|
+
description: desc.length > maxDescLen ? desc.slice(0, maxDescLen) + '...' : desc,
|
|
212
|
+
acceptance: Array.isArray(task.acceptance)
|
|
213
|
+
? task.acceptance.join('\n')
|
|
214
|
+
: (task.acceptance ?? undefined),
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
} catch {
|
|
218
|
+
// Task lookup is best-effort
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Compute duration
|
|
223
|
+
const startTime = new Date(session.startedAt).getTime();
|
|
224
|
+
const now = Date.now();
|
|
225
|
+
const durationMinutes = Math.round((now - startTime) / 60_000);
|
|
226
|
+
|
|
227
|
+
return {
|
|
228
|
+
version: SNAPSHOT_VERSION,
|
|
229
|
+
capturedAt: new Date().toISOString(),
|
|
230
|
+
session,
|
|
231
|
+
handoff,
|
|
232
|
+
decisions,
|
|
233
|
+
observations,
|
|
234
|
+
activeTask,
|
|
235
|
+
durationMinutes,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// ============================================================================
|
|
240
|
+
// Restore
|
|
241
|
+
// ============================================================================
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Restore a session from a snapshot.
|
|
245
|
+
*
|
|
246
|
+
* Hydrates a session from a previously serialized snapshot. The session
|
|
247
|
+
* is re-inserted into the sessions store and optionally activated.
|
|
248
|
+
* Brain observations from the snapshot are NOT re-inserted (they already
|
|
249
|
+
* exist in brain.db) — only the session state is restored.
|
|
250
|
+
*
|
|
251
|
+
* @param projectRoot - Project root directory
|
|
252
|
+
* @param snapshot - The snapshot to restore from
|
|
253
|
+
* @param options - Restoration options
|
|
254
|
+
* @returns The restored session
|
|
255
|
+
*/
|
|
256
|
+
export async function restoreSession(
|
|
257
|
+
projectRoot: string,
|
|
258
|
+
snapshot: SessionSnapshot,
|
|
259
|
+
options: RestoreOptions = {},
|
|
260
|
+
accessor?: DataAccessor,
|
|
261
|
+
): Promise<Session> {
|
|
262
|
+
// Validate snapshot version
|
|
263
|
+
if (snapshot.version > SNAPSHOT_VERSION) {
|
|
264
|
+
throw new CleoError(
|
|
265
|
+
ExitCode.VALIDATION_ERROR,
|
|
266
|
+
`Snapshot version ${snapshot.version} is newer than supported version ${SNAPSHOT_VERSION}`,
|
|
267
|
+
{ fix: 'Upgrade @cleocode/core to a newer version that supports this snapshot format' },
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const acc = accessor ?? (await getAccessor(projectRoot));
|
|
272
|
+
const activate = options.activate ?? true;
|
|
273
|
+
|
|
274
|
+
// Check for active session conflict
|
|
275
|
+
if (activate) {
|
|
276
|
+
const sessions = await acc.loadSessions();
|
|
277
|
+
const scope = snapshot.session.scope;
|
|
278
|
+
const activeConflict = sessions.find(
|
|
279
|
+
(s) =>
|
|
280
|
+
s.status === 'active' &&
|
|
281
|
+
s.scope.type === scope.type &&
|
|
282
|
+
s.scope.epicId === scope.epicId &&
|
|
283
|
+
s.id !== snapshot.session.id,
|
|
284
|
+
);
|
|
285
|
+
if (activeConflict) {
|
|
286
|
+
throw new CleoError(
|
|
287
|
+
ExitCode.SCOPE_CONFLICT,
|
|
288
|
+
`Active session '${activeConflict.id}' already exists for scope ${scope.type}${scope.epicId ? ':' + scope.epicId : ''}`,
|
|
289
|
+
{
|
|
290
|
+
fix: `End the active session first with 'cleo session end' or restore without activating`,
|
|
291
|
+
alternatives: [
|
|
292
|
+
{ action: 'End conflicting session', command: 'cleo session end' },
|
|
293
|
+
{ action: 'Restore without activating', command: 'Restore with activate: false' },
|
|
294
|
+
],
|
|
295
|
+
},
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// Reconstruct the session
|
|
301
|
+
const restoredSession: Session = {
|
|
302
|
+
...snapshot.session,
|
|
303
|
+
status: activate ? 'active' : snapshot.session.status,
|
|
304
|
+
notes: [
|
|
305
|
+
...(snapshot.session.notes ?? []),
|
|
306
|
+
`Restored from snapshot at ${new Date().toISOString()} (captured ${snapshot.capturedAt}, duration ${snapshot.durationMinutes}m)`,
|
|
307
|
+
],
|
|
308
|
+
resumeCount: (snapshot.session.resumeCount ?? 0) + 1,
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
// Update agent if a new one is taking over
|
|
312
|
+
if (options.agent) {
|
|
313
|
+
restoredSession.agent = options.agent;
|
|
314
|
+
restoredSession.notes = [
|
|
315
|
+
...(restoredSession.notes ?? []),
|
|
316
|
+
`Agent handoff: ${snapshot.session.agent ?? 'unknown'} → ${options.agent}`,
|
|
317
|
+
];
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// Store the handoff data for context
|
|
321
|
+
restoredSession.handoffJson = JSON.stringify(snapshot.handoff);
|
|
322
|
+
|
|
323
|
+
// Persist
|
|
324
|
+
await acc.upsertSingleSession(restoredSession);
|
|
325
|
+
|
|
326
|
+
// Dispatch hook (best-effort)
|
|
327
|
+
try {
|
|
328
|
+
const { hooks } = await import('../hooks/registry.js');
|
|
329
|
+
await hooks.dispatch('SessionStart', projectRoot, {
|
|
330
|
+
timestamp: new Date().toISOString(),
|
|
331
|
+
sessionId: restoredSession.id,
|
|
332
|
+
name: restoredSession.name,
|
|
333
|
+
scope: restoredSession.scope,
|
|
334
|
+
agent: restoredSession.agent,
|
|
335
|
+
restored: true,
|
|
336
|
+
snapshotCapturedAt: snapshot.capturedAt,
|
|
337
|
+
});
|
|
338
|
+
} catch {
|
|
339
|
+
// Hooks are best-effort
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
return restoredSession;
|
|
343
|
+
}
|
package/src/store/json.ts
CHANGED
|
@@ -100,10 +100,10 @@ export async function saveJson(
|
|
|
100
100
|
// Atomic write
|
|
101
101
|
await atomicWriteJson(filePath, data, { indent: options?.indent });
|
|
102
102
|
|
|
103
|
-
// Dispatch
|
|
103
|
+
// Dispatch Notification hook (best-effort, fire-and-forget)
|
|
104
104
|
import('../hooks/registry.js')
|
|
105
105
|
.then(({ hooks: h }) =>
|
|
106
|
-
h.dispatch('
|
|
106
|
+
h.dispatch('Notification', process.cwd(), {
|
|
107
107
|
timestamp: new Date().toISOString(),
|
|
108
108
|
filePath,
|
|
109
109
|
changeType: 'write' as const,
|
package/src/task-work/index.ts
CHANGED
|
@@ -123,10 +123,10 @@ export async function startTask(
|
|
|
123
123
|
accessor,
|
|
124
124
|
);
|
|
125
125
|
|
|
126
|
-
// Dispatch
|
|
126
|
+
// Dispatch PreToolUse hook (best-effort, don't await)
|
|
127
127
|
const { hooks } = await import('../hooks/registry.js');
|
|
128
128
|
hooks
|
|
129
|
-
.dispatch('
|
|
129
|
+
.dispatch('PreToolUse', cwd ?? process.cwd(), {
|
|
130
130
|
timestamp: new Date().toISOString(),
|
|
131
131
|
taskId,
|
|
132
132
|
taskTitle: task.title,
|
|
@@ -169,11 +169,11 @@ export async function stopTask(
|
|
|
169
169
|
|
|
170
170
|
const now = new Date().toISOString();
|
|
171
171
|
|
|
172
|
-
// Dispatch
|
|
172
|
+
// Dispatch PostToolUse hook (best-effort, don't await)
|
|
173
173
|
if (taskId && task) {
|
|
174
174
|
const { hooks } = await import('../hooks/registry.js');
|
|
175
175
|
hooks
|
|
176
|
-
.dispatch('
|
|
176
|
+
.dispatch('PostToolUse', cwd ?? process.cwd(), {
|
|
177
177
|
timestamp: now,
|
|
178
178
|
taskId,
|
|
179
179
|
taskTitle: task.title,
|