@haystackeditor/cli 0.25.1 → 0.27.0

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.
Files changed (109) hide show
  1. package/README.md +39 -463
  2. package/dist/capture/app-config.js +30 -6
  3. package/dist/commands/capture-brief.js +45 -35
  4. package/dist/commands/capture-contract.js +4 -4
  5. package/dist/commands/crawl-report.js +196 -0
  6. package/dist/commands/db-profile-upload.js +3 -3
  7. package/dist/commands/feedback.js +66 -0
  8. package/dist/commands/init-telemetry.js +55 -9
  9. package/dist/commands/init.js +8 -3
  10. package/dist/commands/lockfile-pin.js +307 -0
  11. package/dist/commands/telemetry-token.js +3 -3
  12. package/dist/commands/tokens.js +4 -4
  13. package/dist/commands/verify-explore.js +3 -3
  14. package/dist/commands/verify-history.js +2 -2
  15. package/dist/commands/verify-onboarding.js +13 -16
  16. package/dist/commands/verify-precompute.js +3 -4
  17. package/dist/commands/verify.js +31 -118
  18. package/dist/index.js +55 -968
  19. package/dist/schema.js +4 -10
  20. package/dist/utils/haystack-api.js +8 -36
  21. package/package.json +1 -5
  22. package/schemas/feedback.v1.json +13 -0
  23. package/schemas/pre-verify.v2.json +240 -0
  24. package/schemas/verify-raw.v1.json +1132 -0
  25. package/schemas/verify.v2.json +655 -0
  26. package/dist/assets/hooks/agent-context/detect.ts +0 -316
  27. package/dist/assets/hooks/agent-context/format.ts +0 -100
  28. package/dist/assets/hooks/agent-context/index.ts +0 -41
  29. package/dist/assets/hooks/agent-context/parsers/claude.ts +0 -262
  30. package/dist/assets/hooks/agent-context/parsers/codex.ts +0 -416
  31. package/dist/assets/hooks/agent-context/parsers/gemini.ts +0 -155
  32. package/dist/assets/hooks/agent-context/parsers/opencode.ts +0 -174
  33. package/dist/assets/hooks/agent-context/tsconfig.json +0 -14
  34. package/dist/assets/hooks/agent-context/types.ts +0 -58
  35. package/dist/assets/hooks/llm-rules-template.md +0 -59
  36. package/dist/assets/hooks/package-lock.json +0 -598
  37. package/dist/assets/hooks/package.json +0 -12
  38. package/dist/assets/hooks/scripts/commit-msg.sh +0 -5
  39. package/dist/assets/hooks/scripts/post-commit.sh +0 -5
  40. package/dist/assets/hooks/scripts/pre-commit.sh +0 -175
  41. package/dist/assets/hooks/scripts/pre-push.sh +0 -25
  42. package/dist/assets/hooks/scripts/prepare-commit-msg.sh +0 -5
  43. package/dist/assets/hooks/truncation-checker/ast-analyzer.ts +0 -528
  44. package/dist/assets/hooks/truncation-checker/index.ts +0 -595
  45. package/dist/assets/hooks/truncation-checker/tsconfig.json +0 -13
  46. package/dist/assets/skills/map-cloud-verifier-universe/SKILL.md +0 -2051
  47. package/dist/assets/skills/map-cloud-verifier-universe/agents/openai.yaml +0 -4
  48. package/dist/assets/skills/map-cloud-verifier-universe/references/output-contract.md +0 -3411
  49. package/dist/assets/skills/map-your-system.md +0 -143
  50. package/dist/assets/skills/submit.md +0 -200
  51. package/dist/commands/ask.js +0 -20
  52. package/dist/commands/cloud-verifier-behaviors.js +0 -218
  53. package/dist/commands/cloud-verifier-data-store-census.js +0 -539
  54. package/dist/commands/cloud-verifier-data-store-drift.js +0 -158
  55. package/dist/commands/cloud-verifier-identity-census.js +0 -4060
  56. package/dist/commands/cloud-verifier-materialization.js +0 -704
  57. package/dist/commands/cloud-verifier-pascal-selector-census.js +0 -1382
  58. package/dist/commands/cloud-verifier-python-manifest-selector-census.js +0 -2015
  59. package/dist/commands/cloud-verifier-specialized-operational-census.js +0 -11432
  60. package/dist/commands/cloud-verifier-universe.js +0 -10178
  61. package/dist/commands/config.js +0 -549
  62. package/dist/commands/design-verify.js +0 -311
  63. package/dist/commands/dismiss.js +0 -159
  64. package/dist/commands/hooks.js +0 -226
  65. package/dist/commands/inbox.js +0 -137
  66. package/dist/commands/mcp.js +0 -201
  67. package/dist/commands/policy.js +0 -371
  68. package/dist/commands/pr-status.js +0 -207
  69. package/dist/commands/pr.js +0 -105
  70. package/dist/commands/prepare-universe-review.js +0 -1092
  71. package/dist/commands/production-source-deny-policy.js +0 -100
  72. package/dist/commands/request-review.js +0 -74
  73. package/dist/commands/review.js +0 -191
  74. package/dist/commands/rules.js +0 -98
  75. package/dist/commands/scaffold-provisional-universe.js +0 -806
  76. package/dist/commands/setup.js +0 -1170
  77. package/dist/commands/skills.js +0 -447
  78. package/dist/commands/status.js +0 -35
  79. package/dist/commands/submit.js +0 -745
  80. package/dist/commands/system-map.js +0 -228
  81. package/dist/commands/triage.js +0 -598
  82. package/dist/commands/webhooks.js +0 -241
  83. package/dist/states.js +0 -46
  84. package/dist/tools/detect.js +0 -832
  85. package/dist/triage/astra.js +0 -202
  86. package/dist/triage/prompts.js +0 -188
  87. package/dist/triage/runner.js +0 -200
  88. package/dist/triage/types.js +0 -7
  89. package/dist/types.js +0 -326
  90. package/dist/utils/action-output.js +0 -26
  91. package/dist/utils/analysis-api.js +0 -416
  92. package/dist/utils/config.js +0 -54
  93. package/dist/utils/design-verifier-api.js +0 -294
  94. package/dist/utils/design-verifier-history.js +0 -79
  95. package/dist/utils/design-verifier-result.js +0 -424
  96. package/dist/utils/github-api.js +0 -324
  97. package/dist/utils/pending-state.js +0 -86
  98. package/dist/utils/pr-ref.js +0 -56
  99. package/dist/utils/prompter.js +0 -328
  100. package/schemas/action.v1.json +0 -22
  101. package/schemas/ask.v1.json +0 -40
  102. package/schemas/inbox.v1.json +0 -27
  103. package/schemas/pr-status.v1.json +0 -61
  104. package/schemas/pr.v1.json +0 -97
  105. package/schemas/pr.v3.json +0 -45
  106. package/schemas/setup.v1.json +0 -75
  107. package/schemas/submit.v1.json +0 -90
  108. package/schemas/triage.v1.json +0 -103
  109. package/schemas/triage.v2.json +0 -64
@@ -1,316 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
3
- import * as os from 'os';
4
- import * as crypto from 'crypto';
5
- import type { DetectionResult, AgentType } from './types.js';
6
-
7
- const STALENESS_MINUTES = parseInt(
8
- process.env.AGENT_CONTEXT_STALENESS_MINUTES ?? '5',
9
- 10,
10
- );
11
-
12
- export function sanitizePath(absPath: string): string {
13
- return absPath.replace(/[^a-zA-Z0-9]/g, '-');
14
- }
15
-
16
- function sha256(input: string): string {
17
- return crypto.createHash('sha256').update(input).digest('hex');
18
- }
19
-
20
- function isRecent(filePath: string): boolean {
21
- try {
22
- const stat = fs.statSync(filePath);
23
- const ageMs = Date.now() - stat.mtimeMs;
24
- return ageMs < STALENESS_MINUTES * 60 * 1000;
25
- } catch {
26
- return false;
27
- }
28
- }
29
-
30
- function findMostRecentFile(dir: string, pattern: RegExp): string | null {
31
- if (!fs.existsSync(dir)) return null;
32
-
33
- let entries: fs.Dirent[];
34
- try {
35
- entries = fs.readdirSync(dir, { withFileTypes: true });
36
- } catch {
37
- return null;
38
- }
39
-
40
- let bestPath: string | null = null;
41
- let bestMtime = 0;
42
-
43
- for (const entry of entries) {
44
- if (!entry.isFile() || !pattern.test(entry.name)) continue;
45
- const fullPath = path.join(dir, entry.name);
46
- try {
47
- const stat = fs.statSync(fullPath);
48
- if (stat.mtimeMs > bestMtime) {
49
- bestMtime = stat.mtimeMs;
50
- bestPath = fullPath;
51
- }
52
- } catch {
53
- continue;
54
- }
55
- }
56
-
57
- return bestPath;
58
- }
59
-
60
- function extractSessionId(filePath: string, ext: string): string {
61
- return path.basename(filePath, ext);
62
- }
63
-
64
- function findMostRecentFileRecursive(
65
- dir: string,
66
- matches: (filePath: string) => boolean,
67
- ): string | null {
68
- if (!fs.existsSync(dir)) return null;
69
-
70
- const stack = [dir];
71
- let bestPath: string | null = null;
72
- let bestMtime = 0;
73
-
74
- while (stack.length > 0) {
75
- const currentDir = stack.pop();
76
- if (!currentDir) continue;
77
-
78
- let entries: fs.Dirent[];
79
- try {
80
- entries = fs.readdirSync(currentDir, { withFileTypes: true });
81
- } catch {
82
- continue;
83
- }
84
-
85
- for (const entry of entries) {
86
- const fullPath = path.join(currentDir, entry.name);
87
- if (entry.isDirectory()) {
88
- stack.push(fullPath);
89
- continue;
90
- }
91
- if (!entry.isFile() || !matches(fullPath)) continue;
92
-
93
- try {
94
- const stat = fs.statSync(fullPath);
95
- if (stat.mtimeMs > bestMtime) {
96
- bestMtime = stat.mtimeMs;
97
- bestPath = fullPath;
98
- }
99
- } catch {
100
- continue;
101
- }
102
- }
103
- }
104
-
105
- return bestPath;
106
- }
107
-
108
- function readCodexSessionRepoPath(filePath: string): string | null {
109
- let fd: number | undefined;
110
-
111
- try {
112
- fd = fs.openSync(filePath, 'r');
113
- const buffer = Buffer.alloc(32 * 1024);
114
- const bytesRead = fs.readSync(fd, buffer, 0, buffer.length, 0);
115
- const header = buffer.toString('utf8', 0, bytesRead);
116
-
117
- for (const line of header.split('\n')) {
118
- const trimmed = line.trim();
119
- if (!trimmed) continue;
120
-
121
- try {
122
- const parsed = JSON.parse(trimmed) as {
123
- type?: string;
124
- payload?: { cwd?: string };
125
- };
126
- if (
127
- (parsed.type === 'session_meta' || parsed.type === 'turn_context') &&
128
- typeof parsed.payload?.cwd === 'string'
129
- ) {
130
- return parsed.payload.cwd;
131
- }
132
- } catch {
133
- continue;
134
- }
135
- }
136
- } catch {
137
- return null;
138
- } finally {
139
- if (fd !== undefined) {
140
- fs.closeSync(fd);
141
- }
142
- }
143
-
144
- return null;
145
- }
146
-
147
- function codexSessionMatchesRepo(
148
- sessionFilePath: string,
149
- repoPath: string,
150
- ): boolean {
151
- const sessionRepoPath = readCodexSessionRepoPath(sessionFilePath);
152
- return !sessionRepoPath || sessionRepoPath === repoPath;
153
- }
154
-
155
- function getCodexSessionRoots(): string[] {
156
- const overrideDir = process.env.HAYSTACK_TEST_CODEX_SESSION_DIR;
157
- if (overrideDir) return [overrideDir];
158
-
159
- const codexHome =
160
- process.env.HAYSTACK_TEST_CODEX_HOME ||
161
- process.env.CODEX_HOME ||
162
- path.join(os.homedir(), '.codex');
163
-
164
- return [
165
- path.join(codexHome, 'sessions'),
166
- path.join(codexHome, 'archived_sessions'),
167
- ];
168
- }
169
-
170
- function extractCodexSessionId(filePath: string): string {
171
- const basename = path.basename(filePath);
172
- const match = basename.match(
173
- /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i,
174
- );
175
- return match ? match[1] : extractSessionId(filePath, '.jsonl');
176
- }
177
-
178
- function detectClaude(repoPath: string): DetectionResult {
179
- const overrideDir = process.env.HAYSTACK_TEST_CLAUDE_PROJECT_DIR;
180
- const sessionDir =
181
- overrideDir ||
182
- path.join(os.homedir(), '.claude', 'projects', sanitizePath(repoPath));
183
-
184
- const sessionFile = findMostRecentFile(sessionDir, /\.jsonl$/);
185
- if (!sessionFile || !isRecent(sessionFile)) {
186
- return { detected: false };
187
- }
188
-
189
- return {
190
- detected: true,
191
- agent: 'claude-code',
192
- sessionFilePath: sessionFile,
193
- sessionId: extractSessionId(sessionFile, '.jsonl'),
194
- };
195
- }
196
-
197
- function detectGemini(repoPath: string): DetectionResult {
198
- const overrideDir = process.env.HAYSTACK_TEST_GEMINI_PROJECT_DIR;
199
- const projectHash = sha256(repoPath);
200
- const sessionDir =
201
- overrideDir ||
202
- path.join(os.homedir(), '.gemini', 'tmp', projectHash, 'chats');
203
-
204
- const sessionFile = findMostRecentFile(sessionDir, /^session-.*\.json$/);
205
- if (!sessionFile || !isRecent(sessionFile)) {
206
- return { detected: false };
207
- }
208
-
209
- return {
210
- detected: true,
211
- agent: 'gemini-cli',
212
- sessionFilePath: sessionFile,
213
- sessionId: extractSessionId(sessionFile, '.json'),
214
- };
215
- }
216
-
217
- function detectOpenCode(repoPath: string): DetectionResult {
218
- const overrideDir = process.env.HAYSTACK_TEST_OPENCODE_PROJECT_DIR;
219
- const sessionDir =
220
- overrideDir ||
221
- path.join(os.tmpdir(), 'haystack-opencode', sanitizePath(repoPath));
222
-
223
- const sessionFile = findMostRecentFile(sessionDir, /\.json$/);
224
- if (!sessionFile || !isRecent(sessionFile)) {
225
- return { detected: false };
226
- }
227
-
228
- return {
229
- detected: true,
230
- agent: 'opencode',
231
- sessionFilePath: sessionFile,
232
- sessionId: extractSessionId(sessionFile, '.json'),
233
- };
234
- }
235
-
236
- function detectCodex(repoPath: string): DetectionResult {
237
- const overrideFile = process.env.HAYSTACK_TEST_CODEX_SESSION_FILE;
238
- if (
239
- overrideFile &&
240
- isRecent(overrideFile) &&
241
- codexSessionMatchesRepo(overrideFile, repoPath)
242
- ) {
243
- return {
244
- detected: true,
245
- agent: 'codex',
246
- sessionFilePath: overrideFile,
247
- sessionId: extractCodexSessionId(overrideFile),
248
- };
249
- }
250
-
251
- const sessionRoots = getCodexSessionRoots();
252
- const threadId = process.env.CODEX_THREAD_ID;
253
-
254
- if (threadId) {
255
- for (const sessionRoot of sessionRoots) {
256
- const sessionFile = findMostRecentFileRecursive(
257
- sessionRoot,
258
- (filePath) =>
259
- filePath.endsWith(`${threadId}.jsonl`) &&
260
- path.basename(filePath).startsWith('rollout-'),
261
- );
262
-
263
- if (
264
- sessionFile &&
265
- isRecent(sessionFile) &&
266
- codexSessionMatchesRepo(sessionFile, repoPath)
267
- ) {
268
- return {
269
- detected: true,
270
- agent: 'codex',
271
- sessionFilePath: sessionFile,
272
- sessionId: extractCodexSessionId(sessionFile),
273
- };
274
- }
275
- }
276
- }
277
-
278
- for (const sessionRoot of sessionRoots) {
279
- const sessionFile = findMostRecentFileRecursive(
280
- sessionRoot,
281
- (filePath) =>
282
- filePath.endsWith('.jsonl') &&
283
- path.basename(filePath).startsWith('rollout-') &&
284
- isRecent(filePath) &&
285
- codexSessionMatchesRepo(filePath, repoPath),
286
- );
287
-
288
- if (sessionFile) {
289
- return {
290
- detected: true,
291
- agent: 'codex',
292
- sessionFilePath: sessionFile,
293
- sessionId: extractCodexSessionId(sessionFile),
294
- };
295
- }
296
- }
297
-
298
- return { detected: false };
299
- }
300
-
301
- const detectors: Array<(repoPath: string) => DetectionResult> = [
302
- detectClaude,
303
- detectCodex,
304
- detectGemini,
305
- detectOpenCode,
306
- ];
307
-
308
- export async function detectAgent(
309
- repoPath: string,
310
- ): Promise<DetectionResult> {
311
- for (const detect of detectors) {
312
- const result = detect(repoPath);
313
- if (result.detected) return result;
314
- }
315
- return { detected: false };
316
- }
@@ -1,100 +0,0 @@
1
- import type { AgentContext, InteractionTurn } from './types.js';
2
-
3
- const AGENT_DISPLAY_NAMES: Record<string, string> = {
4
- 'claude-code': 'Claude Code',
5
- 'gemini-cli': 'Gemini CLI',
6
- codex: 'Codex',
7
- opencode: 'OpenCode',
8
- };
9
-
10
- // intentional: truncation for display formatting in hook output, not LLM context
11
- function truncate(text: string, maxLen: number): string {
12
- if (text.length <= maxLen) return text;
13
- return text.slice(0, maxLen) + '...';
14
- }
15
-
16
- function formatNumber(n: number): string {
17
- return n.toLocaleString('en-US');
18
- }
19
-
20
- function formatTurnSummary(turn: InteractionTurn): string {
21
- const role = turn.role.toUpperCase();
22
- const content = truncate(turn.content.replace(/\n/g, ' '), 200);
23
- const toolNames = turn.toolUses.map((t) => t.toolName);
24
- const toolSuffix = toolNames.length > 0 ? ` [tools: ${toolNames.join(', ')}]` : '';
25
- return ` [${turn.turnIndex + 1}] ${role}: ${content}${toolSuffix}`;
26
- }
27
-
28
- function formatHuman(ctx: AgentContext): string {
29
- const lines: string[] = [];
30
-
31
- lines.push('========================================');
32
- lines.push(' AGENT CONTEXT DETECTED');
33
- lines.push('========================================');
34
- lines.push(`Agent: ${AGENT_DISPLAY_NAMES[ctx.agent] || ctx.agent}`);
35
- lines.push(`Session ID: ${ctx.sessionId}`);
36
-
37
- if (ctx.metadata.model) {
38
- lines.push(`Model: ${ctx.metadata.model}`);
39
- }
40
- if (ctx.metadata.version) {
41
- lines.push(`Version: ${ctx.metadata.version}`);
42
- }
43
- if (ctx.metadata.gitBranch) {
44
- lines.push(`Git Branch: ${ctx.metadata.gitBranch}`);
45
- }
46
- if (ctx.metadata.startedAt) {
47
- lines.push(`Started At: ${ctx.metadata.startedAt}`);
48
- }
49
-
50
- lines.push('');
51
- lines.push('Task Prompt:');
52
- lines.push(` ${truncate(ctx.taskPrompt.replace(/\n/g, ' '), 500)}`);
53
-
54
- lines.push('');
55
- lines.push(`Modified Files (${ctx.modifiedFiles.length}):`);
56
- if (ctx.modifiedFiles.length === 0) {
57
- lines.push(' (none)');
58
- } else {
59
- for (const f of ctx.modifiedFiles) {
60
- // Find which tools modified this file
61
- const tools = new Set<string>();
62
- for (const turn of ctx.transcript) {
63
- for (const mf of turn.modifiedFiles) {
64
- if (mf.filePath === f) tools.add(mf.toolName);
65
- }
66
- }
67
- lines.push(` - ${f} (${Array.from(tools).join(', ')})`);
68
- }
69
- }
70
-
71
- lines.push('');
72
- lines.push('Token Usage:');
73
- lines.push(
74
- ` Input: ${formatNumber(ctx.tokenUsage.inputTokens)} Output: ${formatNumber(ctx.tokenUsage.outputTokens)}`,
75
- );
76
- if (ctx.tokenUsage.cacheCreationTokens || ctx.tokenUsage.cacheReadTokens) {
77
- lines.push(
78
- ` Cache Creation: ${formatNumber(ctx.tokenUsage.cacheCreationTokens || 0)} Cache Read: ${formatNumber(ctx.tokenUsage.cacheReadTokens || 0)}`,
79
- );
80
- }
81
-
82
- lines.push('');
83
- lines.push(`Transcript (${ctx.transcript.length} turns):`);
84
- for (const turn of ctx.transcript) {
85
- lines.push(formatTurnSummary(turn));
86
- }
87
-
88
- lines.push('========================================');
89
- return lines.join('\n');
90
- }
91
-
92
- function formatJson(ctx: AgentContext): string {
93
- return JSON.stringify(ctx, null, 2);
94
- }
95
-
96
- export function formatContext(ctx: AgentContext): string {
97
- const mode = process.env.AGENT_CONTEXT_FORMAT || 'human';
98
- if (mode === 'json') return formatJson(ctx);
99
- return formatHuman(ctx);
100
- }
@@ -1,41 +0,0 @@
1
- import { detectAgent } from './detect.js';
2
- import { ClaudeParser } from './parsers/claude.js';
3
- import { CodexParser } from './parsers/codex.js';
4
- import { GeminiParser } from './parsers/gemini.js';
5
- import { OpenCodeParser } from './parsers/opencode.js';
6
- import { formatContext } from './format.js';
7
- import type { AgentParser } from './types.js';
8
-
9
- const PARSERS: Record<string, AgentParser> = {
10
- 'claude-code': new ClaudeParser(),
11
- codex: new CodexParser(),
12
- 'gemini-cli': new GeminiParser(),
13
- opencode: new OpenCodeParser(),
14
- };
15
-
16
- async function main() {
17
- const repoRoot = process.argv[2] || process.cwd();
18
-
19
- const detection = await detectAgent(repoRoot);
20
-
21
- if (!detection.detected || !detection.agent || !detection.sessionFilePath) {
22
- if (process.env.AGENT_CONTEXT_VERBOSE) {
23
- console.error('[agent-context] No AI agent session detected.');
24
- }
25
- return;
26
- }
27
-
28
- const parser = PARSERS[detection.agent];
29
- if (!parser) {
30
- console.error(`[agent-context] No parser for agent: ${detection.agent}`);
31
- return;
32
- }
33
-
34
- const context = await parser.parse(detection.sessionFilePath, repoRoot);
35
- const output = formatContext(context);
36
- console.error(output);
37
- }
38
-
39
- main().catch((err) => {
40
- console.error(`[agent-context] Error: ${err.message}`);
41
- });
@@ -1,262 +0,0 @@
1
- import * as fs from 'fs';
2
- import type {
3
- AgentContext,
4
- AgentParser,
5
- DetectionResult,
6
- InteractionTurn,
7
- ModifiedFile,
8
- TokenUsage,
9
- ToolUseInfo,
10
- } from '../types.js';
11
- import { detectAgent } from '../detect.js';
12
-
13
- const FILE_MOD_TOOLS = new Set([
14
- 'Write',
15
- 'Edit',
16
- 'NotebookEdit',
17
- 'mcp__acp__Write',
18
- 'mcp__acp__Edit',
19
- ]);
20
-
21
- interface ClaudeLine {
22
- type?: string;
23
- sessionId?: string;
24
- version?: string;
25
- gitBranch?: string;
26
- uuid?: string;
27
- timestamp?: string;
28
- // Old format: message wrapper with role/content/usage
29
- message?: {
30
- id?: string;
31
- model?: string;
32
- role?: string;
33
- content?: unknown;
34
- usage?: {
35
- input_tokens?: number;
36
- output_tokens?: number;
37
- cache_creation_input_tokens?: number;
38
- cache_read_input_tokens?: number;
39
- };
40
- };
41
- // Alternate format: id/content at top level (type is the role)
42
- id?: string;
43
- content?: unknown;
44
- }
45
-
46
- interface ContentBlock {
47
- type?: string; // Optional: new format blocks may omit type
48
- text?: string;
49
- thinking?: string;
50
- name?: string;
51
- id?: string;
52
- input?: Record<string, unknown>;
53
- }
54
-
55
- function parseLines(raw: string): ClaudeLine[] {
56
- const lines: ClaudeLine[] = [];
57
- for (const line of raw.split('\n')) {
58
- const trimmed = line.trim();
59
- if (!trimmed) continue;
60
- try {
61
- lines.push(JSON.parse(trimmed));
62
- } catch {
63
- // Skip unparseable lines (e.g. partial write from concurrent agent)
64
- }
65
- }
66
- return lines;
67
- }
68
-
69
- function extractTextContent(content: unknown): string {
70
- if (typeof content === 'string') return content;
71
- if (!Array.isArray(content)) return '';
72
-
73
- const parts: string[] = [];
74
- for (const block of content as ContentBlock[]) {
75
- // Support both old ({type: "text", text}) and new ({id, text}) content blocks
76
- if (block.text && (block.type === 'text' || !block.type)) {
77
- parts.push(block.text);
78
- }
79
- }
80
- return parts.join('\n');
81
- }
82
-
83
- function extractModifiedFiles(content: unknown): ModifiedFile[] {
84
- if (!Array.isArray(content)) return [];
85
- const files: ModifiedFile[] = [];
86
-
87
- for (const block of content as ContentBlock[]) {
88
- if (block.type !== 'tool_use' || !block.name) continue;
89
- if (!FILE_MOD_TOOLS.has(block.name)) continue;
90
-
91
- const filePath =
92
- (block.input?.file_path as string) ||
93
- (block.input?.path as string) ||
94
- (block.input?.notebook_path as string);
95
- if (filePath) {
96
- files.push({
97
- filePath,
98
- toolName: block.name,
99
- toolUseId: block.id,
100
- });
101
- }
102
- }
103
- return files;
104
- }
105
-
106
- function extractToolUses(content: unknown): ToolUseInfo[] {
107
- if (!Array.isArray(content)) return [];
108
- const tools: ToolUseInfo[] = [];
109
-
110
- for (const block of content as ContentBlock[]) {
111
- if (block.type !== 'tool_use' || !block.name) continue;
112
- tools.push({
113
- toolName: block.name,
114
- toolUseId: block.id || '',
115
- input: sanitizeInput(block.input || {}),
116
- });
117
- }
118
- return tools;
119
- }
120
-
121
- // intentional: sanitize tool input for display in hook output, not LLM context
122
- function sanitizeInput(input: Record<string, unknown>): Record<string, unknown> {
123
- const sanitized: Record<string, unknown> = {};
124
- for (const [key, value] of Object.entries(input)) {
125
- if (typeof value === 'string' && value.length > 200) {
126
- sanitized[key] = value.slice(0, 200) + '... (truncated)';
127
- } else {
128
- sanitized[key] = value;
129
- }
130
- }
131
- return sanitized;
132
- }
133
-
134
- export class ClaudeParser implements AgentParser {
135
- async detect(repoPath: string): Promise<DetectionResult> {
136
- return detectAgent(repoPath);
137
- }
138
-
139
- async parse(
140
- sessionFilePath: string,
141
- _repoPath: string,
142
- ): Promise<AgentContext> {
143
- const raw = fs.readFileSync(sessionFilePath, 'utf-8');
144
- const allLines = parseLines(raw);
145
-
146
- // Filter to user and assistant lines only
147
- const userLines = allLines.filter((l) => l.type === 'user');
148
- const assistantLines = allLines.filter((l) => l.type === 'assistant');
149
-
150
- // Deduplicate assistant messages by message.id (streaming produces duplicates)
151
- // Support both old format (line.message.id) and new format (line.id)
152
- const dedupedAssistant = new Map<string, ClaudeLine>();
153
- for (const line of assistantLines) {
154
- const msgId = line.message?.id || line.id;
155
- if (msgId) {
156
- dedupedAssistant.set(msgId, line);
157
- }
158
- }
159
- const uniqueAssistant = Array.from(dedupedAssistant.values());
160
-
161
- // Build transcript turns
162
- const transcript: InteractionTurn[] = [];
163
- let turnIndex = 0;
164
-
165
- // Interleave user and assistant messages by position
166
- // User messages appear at even indices, assistant at odd
167
- const maxTurns = Math.max(userLines.length, uniqueAssistant.length);
168
- for (let i = 0; i < maxTurns; i++) {
169
- if (i < userLines.length) {
170
- const user = userLines[i];
171
- // Support both old ({message: {content}}) and new ({content}) formats
172
- const userContent = user.message?.content ?? user.content;
173
- transcript.push({
174
- turnIndex: turnIndex++,
175
- role: 'user',
176
- content: extractTextContent(userContent),
177
- modifiedFiles: [],
178
- toolUses: [],
179
- });
180
- }
181
- if (i < uniqueAssistant.length) {
182
- const asst = uniqueAssistant[i];
183
- // Support both old ({message: {content, usage}}) and new ({content}) formats
184
- const content = asst.message?.content ?? asst.content;
185
- const usage = asst.message?.usage;
186
- transcript.push({
187
- turnIndex: turnIndex++,
188
- role: 'assistant',
189
- content: extractTextContent(content),
190
- modifiedFiles: extractModifiedFiles(content),
191
- tokenUsage: usage
192
- ? {
193
- inputTokens: usage.input_tokens || 0,
194
- outputTokens: usage.output_tokens || 0,
195
- cacheCreationTokens: usage.cache_creation_input_tokens,
196
- cacheReadTokens: usage.cache_read_input_tokens,
197
- }
198
- : undefined,
199
- toolUses: extractToolUses(content),
200
- });
201
- }
202
- }
203
-
204
- // Task prompt: first user message where content is a plain string
205
- // (not a tool_result array) and not a system instruction injected by the host
206
- let taskPrompt = '';
207
- for (const user of userLines) {
208
- const content = user.message?.content;
209
- if (typeof content !== 'string') continue;
210
- if (content.startsWith('<system_instruction>') || content.startsWith('<system-')) continue;
211
- taskPrompt = content;
212
- break;
213
- }
214
-
215
- // Aggregate token usage
216
- const totalUsage: TokenUsage = {
217
- inputTokens: 0,
218
- outputTokens: 0,
219
- cacheCreationTokens: 0,
220
- cacheReadTokens: 0,
221
- };
222
- for (const asst of uniqueAssistant) {
223
- const usage = asst.message?.usage;
224
- if (usage) {
225
- totalUsage.inputTokens += usage.input_tokens || 0;
226
- totalUsage.outputTokens += usage.output_tokens || 0;
227
- totalUsage.cacheCreationTokens! += usage.cache_creation_input_tokens || 0;
228
- totalUsage.cacheReadTokens! += usage.cache_read_input_tokens || 0;
229
- }
230
- }
231
-
232
- // Collect all modified files (deduplicated)
233
- const allModifiedFiles = new Set<string>();
234
- for (const turn of transcript) {
235
- for (const f of turn.modifiedFiles) {
236
- allModifiedFiles.add(f.filePath);
237
- }
238
- }
239
-
240
- // Metadata from first lines
241
- const firstUser = userLines[0];
242
- const firstAssistant = uniqueAssistant[0];
243
- const stat = fs.statSync(sessionFilePath);
244
-
245
- return {
246
- agent: 'claude-code',
247
- sessionId: firstUser?.sessionId || '',
248
- sessionFilePath,
249
- taskPrompt,
250
- modifiedFiles: Array.from(allModifiedFiles),
251
- tokenUsage: totalUsage,
252
- transcript,
253
- metadata: {
254
- model: firstAssistant?.message?.model,
255
- version: firstUser?.version,
256
- gitBranch: firstUser?.gitBranch,
257
- startedAt: firstUser?.timestamp,
258
- sessionFileModifiedAt: stat.mtime.toISOString(),
259
- },
260
- };
261
- }
262
- }