-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession-state.ts
More file actions
303 lines (266 loc) · 9.91 KB
/
Copy pathsession-state.ts
File metadata and controls
303 lines (266 loc) · 9.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/**
* Session State Management
* Track current session context for auto-injecting into recall calls
* Track surfaced scars for auto-bridging Q6 answers to scar_usage records
*
* Maintains in-memory state of the current active session including:
* - session_id from session_start
* - linear_issue if working on a Linear issue
* - agent identity
* - surfaced scars (accumulated from session_start + recall calls)
*
* This allows recall() to always assign variants even without explicit parameters.
*/
import type { SurfacedScar, ScarConfirmation, ScarReflection, Observation, SessionChild, ThreadObject } from "../types/index.js";
interface SessionContext {
sessionId: string;
linearIssue?: string;
agent?: string;
project?: string; // Thread fix: track active project for list_threads default
startedAt: Date;
surfacedScars: SurfacedScar[]; // Track all scars surfaced during session
confirmations: ScarConfirmation[]; // Refute-or-obey confirmations for recall-surfaced scars
reflections: ScarReflection[]; // End-of-session scar reflections (OBEYED/REFUTED)
observations: Observation[]; // v2 Phase 2: Sub-agent/teammate observations
children: SessionChild[]; // v2 Phase 2: Child agent records
threads: ThreadObject[]; // : Working thread state
}
// Global session state (single active session per MCP server instance)
let currentSession: SessionContext | null = null;
/**
* Set the current active session
* Called by session_start
*/
export function setCurrentSession(context: Omit<SessionContext, 'surfacedScars' | 'confirmations' | 'reflections' | 'observations' | 'children' | 'threads'> & { surfacedScars?: SurfacedScar[]; observations?: Observation[]; children?: SessionChild[]; threads?: ThreadObject[] }): void {
currentSession = {
...context,
surfacedScars: context.surfacedScars || [],
confirmations: [],
reflections: [],
observations: context.observations || [],
children: context.children || [],
threads: context.threads || [],
};
console.error(`[session-state] Active session set: ${context.sessionId}${context.linearIssue ? ` (issue: ${context.linearIssue})` : ''}`);
}
/**
* Get the current active session
* Returns null if no session active
*/
export function getCurrentSession(): SessionContext | null {
return currentSession;
}
/**
* Clear the current session
* Called by session_close
*/
export function clearCurrentSession(): void {
if (currentSession) {
console.error(`[session-state] Clearing session: ${currentSession.sessionId}`);
}
currentSession = null;
}
/**
* Get the active session's project, or null if no session.
* Used by list_threads to inherit the correct project default.
*/
export function getProject(): string | null {
return currentSession?.project || null;
}
/**
* Check if currently working on a Linear issue
*/
export function hasActiveIssue(): boolean {
return !!(currentSession?.linearIssue);
}
/**
* Add surfaced scars to tracking (deduplicates by scar_id)
* Called by session_start and recall when scars are surfaced.
*/
export function addSurfacedScars(scars: SurfacedScar[]): void {
if (!currentSession) {
console.warn("[session-state] Cannot add surfaced scars: no active session");
return;
}
for (const scar of scars) {
const exists = currentSession.surfacedScars.some(s => s.scar_id === scar.scar_id);
if (!exists) {
currentSession.surfacedScars.push(scar);
}
}
console.error(`[session-state] Surfaced scars tracked: ${currentSession.surfacedScars.length} total`);
}
/**
* Get all surfaced scars for the current session
*/
export function getSurfacedScars(): SurfacedScar[] {
return currentSession?.surfacedScars || [];
}
/**
* Add scar confirmations (refute-or-obey) to the current session.
* Called by confirm_scars tool after validation.
*/
export function addConfirmations(confirmations: ScarConfirmation[]): void {
if (!currentSession) {
console.warn("[session-state] Cannot add confirmations: no active session");
return;
}
for (const conf of confirmations) {
// Replace existing confirmation for same scar_id (allow re-confirmation)
const idx = currentSession.confirmations.findIndex(c => c.scar_id === conf.scar_id);
if (idx >= 0) {
currentSession.confirmations[idx] = conf;
} else {
currentSession.confirmations.push(conf);
}
}
console.error(`[session-state] Confirmations tracked: ${currentSession.confirmations.length} total`);
}
/**
* Get all scar confirmations for the current session.
*/
export function getConfirmations(): ScarConfirmation[] {
return currentSession?.confirmations || [];
}
/**
* Add end-of-session scar reflections (OBEYED/REFUTED) to the current session.
* Called by reflect_scars tool after validation.
*/
export function addReflections(reflections: ScarReflection[]): void {
if (!currentSession) {
console.warn("[session-state] Cannot add reflections: no active session");
return;
}
for (const ref of reflections) {
// Replace existing reflection for same scar_id (allow re-reflection)
const idx = currentSession.reflections.findIndex(r => r.scar_id === ref.scar_id);
if (idx >= 0) {
currentSession.reflections[idx] = ref;
} else {
currentSession.reflections.push(ref);
}
}
console.error(`[session-state] Reflections tracked: ${currentSession.reflections.length} total`);
}
/**
* Get all end-of-session scar reflections for the current session.
*/
export function getReflections(): ScarReflection[] {
return currentSession?.reflections || [];
}
/**
* Check if there are recall-surfaced scars that haven't been confirmed.
* Only checks scars with source "recall" — session_start scars don't require confirmation.
*/
export function hasUnconfirmedScars(): boolean {
if (!currentSession) return false;
const recallScars = currentSession.surfacedScars.filter(s => s.source === "recall");
if (recallScars.length === 0) return false;
const confirmedIds = new Set(currentSession.confirmations.map(c => c.scar_id));
return recallScars.some(s => !confirmedIds.has(s.scar_id));
}
// Security: cap unbounded arrays to prevent memory exhaustion in long sessions
const MAX_OBSERVATIONS = 500;
const MAX_CHILDREN = 100;
/**
* v2 Phase 2: Add observations from sub-agents/teammates
*/
export function addObservations(newObs: Observation[]): number {
if (!currentSession) {
console.warn("[session-state] Cannot add observations: no active session");
return 0;
}
const timestamped = newObs.map(o => ({
...o,
absorbed_at: o.absorbed_at || new Date().toISOString(),
}));
currentSession.observations.push(...timestamped);
// Cap to prevent memory exhaustion — keep most recent
if (currentSession.observations.length > MAX_OBSERVATIONS) {
currentSession.observations = currentSession.observations.slice(-MAX_OBSERVATIONS);
}
console.error(`[session-state] Observations tracked: ${currentSession.observations.length} total`);
return timestamped.length;
}
/**
* v2 Phase 2: Get all observations for the current session
*/
export function getObservations(): Observation[] {
return currentSession?.observations || [];
}
/**
* v2 Phase 2: Register a child agent in the current session
*/
export function addChild(child: SessionChild): void {
if (!currentSession) {
console.warn("[session-state] Cannot add child: no active session");
return;
}
// Cap to prevent memory exhaustion — reject silently beyond limit
if (currentSession.children.length >= MAX_CHILDREN) {
console.warn(`[session-state] Children cap reached (${MAX_CHILDREN}), ignoring new child: ${child.role}`);
return;
}
currentSession.children.push(child);
console.error(`[session-state] Child registered: ${child.role} (${child.type}), total: ${currentSession.children.length}`);
}
/**
* v2 Phase 2: Get all children for the current session
*/
export function getChildren(): SessionChild[] {
return currentSession?.children || [];
}
/**
* Compute session activity signals for close type validation.
* Returns null if no active session (e.g., recovered from registry).
*/
export interface SessionActivity {
duration_min: number;
recall_count: number; // Scars from "recall" (excludes session_start auto-scars)
observation_count: number;
children_count: number;
thread_count: number; // Open threads in current session
}
export function getSessionActivity(): SessionActivity | null {
if (!currentSession) return null;
const durationMs = Date.now() - currentSession.startedAt.getTime();
return {
duration_min: durationMs / (1000 * 60),
recall_count: currentSession.surfacedScars.filter(s => s.source === "recall").length,
observation_count: currentSession.observations.length,
children_count: currentSession.children.length,
thread_count: currentSession.threads.filter(t => t.status === "open").length,
};
}
/**
* : Set threads for the current session
*/
export function setThreads(threads: ThreadObject[]): void {
if (!currentSession) {
console.warn("[session-state] Cannot set threads: no active session");
return;
}
currentSession.threads = threads;
console.error(`[session-state] Threads set: ${threads.length} total`);
}
/**
* : Get threads for the current session
*/
export function getThreads(): ThreadObject[] {
return currentSession?.threads || [];
}
/**
* : Resolve a thread in session state by ID.
* Returns the resolved thread or null if not found.
*/
export function resolveThreadInState(threadId: string, resolutionNote?: string): ThreadObject | null {
if (!currentSession) return null;
const thread = currentSession.threads.find((t) => t.id === threadId);
if (!thread || thread.status === "resolved") return thread || null;
thread.status = "resolved";
thread.resolved_at = new Date().toISOString();
thread.resolved_by_session = currentSession.sessionId;
if (resolutionNote) thread.resolution_note = resolutionNote;
console.error(`[session-state] Thread resolved: ${threadId}`);
return thread;
}