-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathsession-analysis.mjs
More file actions
347 lines (319 loc) · 12.1 KB
/
Copy pathsession-analysis.mjs
File metadata and controls
347 lines (319 loc) · 12.1 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
#!/usr/bin/env node
import path from "node:path";
import { fileURLToPath } from "node:url";
import { analyzeClaudeStyleSessions } from "./session-analysis/claude-facets.mjs";
import { parseArgs } from "./session-analysis/cli.mjs";
import { createCodexCliJsonModelClient } from "./session-analysis/codex-json-model.mjs";
// Minimal AI-facing usage:
// const analyzer = await createAnalyzer("qoder");
// const result = await analyzer.analyze({ workspace: "/path/to/repo", command: "facets" });
// // result => { scope, sources, sessions, facets, warnings }
// CLI workflow for AI agents:
// node scripts/session-analysis.mjs sources --platform qoder --workspace /path/to/repo
// node scripts/session-analysis.mjs facets --platform qoder --workspace /path/to/repo --limit 5
// node scripts/session-analysis.mjs insights --platform qoder --workspace /path/to/repo --limit 5
// node scripts/session-analysis.mjs facts --platform qoder --workspace /path/to/repo --limit 3
// node scripts/session-analysis.mjs facts --platform qoder --workspace /path/to/repo --limit 3 --debug
// node scripts/session-analysis.mjs claude-facets --platform qoder --workspace /path/to/repo --limit 5
// node scripts/session-analysis.mjs file-reads --platform qoder --workspace /path/to/repo --limit 5
// node scripts/session-analysis.mjs show --platform qoder --workspace /path/to/repo --session-id <id> --include-events
// This module returns evidence and compact insight packs; the caller synthesizes
// any final narrative/report.
export class SessionAnalyzer {
async resolveScope(_options = {}) {
throw new Error("resolveScope() must be implemented by a platform analyzer");
}
async discoverSourceRoots(_scope) {
throw new Error("discoverSourceRoots() must be implemented by a platform analyzer");
}
async discoverSessions(_scope, _roots) {
throw new Error("discoverSessions() must be implemented by a platform analyzer");
}
async readSession(_session, _scope, _options = {}) {
throw new Error("readSession() must be implemented by a platform analyzer");
}
normalizeEvent(_raw, _sourceRef, _options = {}) {
throw new Error("normalizeEvent() must be implemented by a platform analyzer");
}
normalizeEvents(raw, sourceRef, options = {}) {
const event = this.normalizeEvent(raw, sourceRef, options);
return event ? [event] : [];
}
mergeSession(events, session) {
const summary = summarizeEvents(events);
return {
...session,
firstSeen: summary.timeRange.firstSeen ?? session.firstSeen,
lastSeen: summary.timeRange.lastSeen ?? session.lastSeen,
eventCounts: summary.eventCounts,
messageCounts: summary.messageCounts,
};
}
async analyze(options = {}) {
const scope = await this.resolveScope(options);
const roots = await this.discoverSourceRoots(scope);
const sessions = Array.isArray(options.sessionInventory)
? [...options.sessionInventory]
: await this.discoverSessions(scope, roots);
const filteredSessions = filterSessionsByScope(sessions, scope);
return {
scope: publicScope(scope),
sources: roots.map(toPublicSource),
sessions: filteredSessions,
facets: null,
warnings: rootWarnings(roots),
};
}
}
function timestampMillis(value) {
if (!value) {
return 0;
}
const time = new Date(value).getTime();
return Number.isNaN(time) ? null : time;
}
function mergeTimeRange(target, timestamp) {
if (!timestamp) {
return;
}
if (!target.firstSeen || timestampMillis(timestamp) < timestampMillis(target.firstSeen)) {
target.firstSeen = timestamp;
}
if (!target.lastSeen || timestampMillis(timestamp) > timestampMillis(target.lastSeen)) {
target.lastSeen = timestamp;
}
}
function countBy(items, keyFn) {
const counts = new Map();
for (const item of items) {
const key = keyFn(item);
if (!key) {
continue;
}
counts.set(key, (counts.get(key) ?? 0) + 1);
}
return Object.fromEntries([...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])));
}
function summarizeEvents(events) {
const timeRange = { firstSeen: null, lastSeen: null };
for (const event of events) {
mergeTimeRange(timeRange, event.timestamp);
}
return {
eventCounts: countBy(events, (event) => event.type),
messageCounts: countBy(events, (event) =>
event.type === "user" || event.type === "assistant" || event.type === "last-prompt" || event.type === "message"
? event.type
: null,
),
sourceCounts: countBy(events, (event) => event.sourceKind),
timeRange,
};
}
function filterSessionsByScope(sessions, scope) {
return sessions.filter((session) => {
if (scope.sessionId && session.sessionId !== scope.sessionId) {
return false;
}
if (scope.sinceTime !== null && session.lastSeen && timestampMillis(session.lastSeen) < scope.sinceTime) {
return false;
}
if (scope.untilTime !== null && session.firstSeen && timestampMillis(session.firstSeen) > scope.untilTime) {
return false;
}
return true;
});
}
function publicScope(scope) {
return Object.fromEntries(
Object.entries(scope).filter(([key]) => !key.endsWith("Time") && key !== "raw" && !key.startsWith("_")),
);
}
function toPublicSource(root) {
return {
id: root.id,
kind: root.kind,
role: root.role,
path: root.path,
exists: root.exists,
enabled: root.enabled,
optional: root.optional,
workspaceScoped: root.workspaceScoped,
};
}
function rootWarnings(roots) {
return [
...roots
.filter((root) => root.enabled && root.optional && !root.exists)
.map((root) => ({
code: "missing-optional-root",
message: `${root.kind} root does not exist: ${root.path}`,
source: root.id,
})),
...roots
.filter((root) => !root.enabled)
.map((root) => ({
code: "disabled-source-root",
message: root.disabledHint ? `${root.kind} root is disabled; ${root.disabledHint}` : `${root.kind} root is disabled`,
source: root.id,
})),
];
}
function platformFromArgs(argv) {
const index = argv.indexOf("--platform");
if (index !== -1 && argv[index + 1]) {
return argv[index + 1];
}
const withEquals = argv.find((arg) => arg.startsWith("--platform="));
if (withEquals) {
return withEquals.slice("--platform=".length);
}
return "qoder";
}
async function loadPlatform(platform = "qoder") {
if (platform === "qoder") {
const module = await import("./session-analysis/platforms/qoder.mjs");
return {
Analyzer: module.QoderSessionAnalyzer,
main: module.main,
};
}
if (platform === "codex") {
const module = await import("./session-analysis/platforms/codex.mjs");
return {
Analyzer: module.CodexSessionAnalyzer,
main: module.main,
};
}
if (platform === "claude") {
const module = await import("./session-analysis/platforms/claude.mjs");
return {
Analyzer: module.ClaudeSessionAnalyzer,
main: module.main,
};
}
if (platform === "cursor") {
const module = await import("./session-analysis/platforms/cursor.mjs");
return {
Analyzer: module.CursorSessionAnalyzer,
main: module.main,
};
}
if (platform === "qwen") {
const module = await import("./session-analysis/platforms/qwen.mjs");
return {
Analyzer: module.QwenSessionAnalyzer,
main: module.main,
};
}
if (platform === "copilot") {
const module = await import("./session-analysis/platforms/copilot.mjs");
return {
Analyzer: module.CopilotSessionAnalyzer,
main: module.main,
};
}
if (platform === "pi") {
const module = await import("./session-analysis/platforms/pi.mjs");
return {
Analyzer: module.PiSessionAnalyzer,
main: module.main,
};
}
if (platform === "workbuddy") {
const module = await import("./session-analysis/platforms/workbuddy.mjs");
return {
Analyzer: module.WorkbuddySessionAnalyzer,
main: module.main,
};
}
throw new Error(`Unsupported platform: ${platform}. Supported platforms: qoder, codex, claude, cursor, qwen, copilot, pi, workbuddy.`);
}
export async function createAnalyzer(platform = "qoder") {
const { Analyzer } = await loadPlatform(platform);
return new Analyzer();
}
export async function main(argv = process.argv.slice(2)) {
const { command, options } = parseArgs(argv);
if (options.help === true) {
const factsOptions = command === "facts"
? [
"",
"Facts options:",
" --limit <1-5> Maximum emitted task candidates (default: 5)",
" --selection <strategy> stratified, latest-n, or all-eligible",
" --since <date> --until <date> Freeze the provider-specific review window",
" --debug Add local-only candidate-to-session-id locators",
" --output <path> Write local diagnostic output to a file",
]
: [];
const eventOptions = command === "show" || command === "events"
? [
"",
"Event inspection options:",
" --session-id <id> Raw session id from local facts --debug output",
" --include-events Include normalized events in show output",
" --include-command-text Include command text for local diagnosis",
" --include-user-text Include user text for local diagnosis",
" --include-content Include provider content for local diagnosis",
" --type <event-type> Filter events output by normalized type",
]
: [];
const claudeOptions = command === "claude-facets"
? [
"",
"Claude facets options:",
" --limit <1-5> Maximum semantic facets (default: 5)",
" --selection <strategy> Existing bounded session selection strategy",
" --since <date> --until <date> Freeze an explicit time window",
" --analysis-model codex-cli JSON model route",
" --model-concurrency <1-4> Concurrent per-session model calls (default: 2)",
"",
"Privacy: compact redacted session semantics are sent to the configured Codex service;",
"raw prompts, commands, tool output, paths, ids, and secrets are excluded.",
"This experiment does not change findings, reports, scores, or caches.",
]
: [];
process.stdout.write([
`Usage: session-analysis${command ? ` ${command}` : " <command>"} --platform <qoder|codex|claude|cursor|qwen|copilot|pi|workbuddy> --workspace <path> [options]`,
"",
"Commands: sources, sessions, facets, insights, facts, file-reads, show, events, claude-facets",
...factsOptions,
...eventOptions,
...claudeOptions,
"",
"Options: --workbuddy-home <dir> overrides the WorkBuddy data root (default: ~/.workbuddy).",
"",
"Use facts --debug only for local diagnosis; it exposes raw session ids and must not be passed to report agents.",
].join("\n") + "\n");
return null;
}
if (command === "claude-facets") {
const platform = options.platform ?? "qoder";
const analysisModel = options["analysis-model"] ?? "codex-cli";
const format = options.format ?? "json";
if (analysisModel !== "codex-cli") {
throw new Error(`Unsupported analysis model: ${analysisModel}. Supported models: codex-cli.`);
}
if (format !== "json") throw new Error(`claude-facets supports only JSON output, not ${format}`);
const analyzer = await createAnalyzer(platform);
const result = await analyzeClaudeStyleSessions({
analyzer,
platform,
options,
modelClient: createCodexCliJsonModelClient(),
});
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
return result;
}
const platform = platformFromArgs(argv);
const { main: platformMain } = await loadPlatform(platform);
return platformMain(argv);
}
const isCli = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (isCli) {
main().catch((error) => {
process.stderr.write(`session-analysis failed: ${error.stack ?? error.message}\n`);
process.exitCode = 1;
});
}