Repository navigation
Expand file tree
/
Copy pathextract.ts
More file actions
2960 lines (2666 loc) · 107 KB
/
Copy pathextract.ts
File metadata and controls
2960 lines (2666 loc) · 107 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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Session event extraction — pure functions, zero side effects.
* Extracts structured events from Claude Code tool calls and user messages.
*
* All 13 event categories as specified in PRD Section 3.
*/
import {
lookupPrice as catalogLookupPrice,
computeCostUsd as catalogComputeCostUsd,
} from "./pricing.js";
// ── Public interfaces ──────────────────────────────────────────────────────
export interface SessionEvent {
/** e.g. "file_read", "file_write", "cwd", "error_tool", "git", "task",
* "decision", "rule", "env", "role", "skill", "subagent", "data", "intent" */
type: string;
/** e.g. "file", "cwd", "error", "git", "task", "decision",
* "rule", "env", "role", "skill", "subagent", "data", "intent" */
category: string;
/** Extracted payload — full data, no truncation */
data: string;
/** 1=critical (rules, files, tasks) … 5=low */
priority: number;
/**
* Optional — bytes context-mode prevented from entering the model context
* window for this event. Currently populated by external_ref when a
* ctx_fetch_and_index tool_response carries the
* `Fetched and indexed N sections (XKB)` preamble.
*/
bytes_avoided?: number;
/**
* Optional — bytes the model PAID to ACCESS kept-out content for this event:
* the tool_response byte length of a `ctx_search` / `ctx_fetch_and_index`
* call. This is the OTHER half of the with/without ratio (bytes_avoided is
* the kept-out half). Sandbox compute (ctx_execute/batch/file) is work-output
* and is excluded. Present only when the call is a retrieval call and its
* tool_response is non-empty.
*/
bytes_retrieved?: number;
/**
* Optional structured cost/usage fields (Wave 2b). Emitted by
* extractAgentUsage alongside the colon-string `data` so the forward
* envelope can spread them to the platform as typed columns instead of an
* opaque blob. Present only when the source signal is present; cost_usd is
* omitted on a price miss or a zero-token turn.
*/
model_id?: string;
input_tokens?: number;
output_tokens?: number;
cache_read_tokens?: number;
cache_creation_tokens?: number;
cost_usd?: number;
/**
* "task_cumulative" on agent_usage events whose tokens are a Task sub-agent's
* usage SUMMED across its whole run (not one turn). The platform buckets these
* as lifetime spend and never prices them per-turn — see
* docs/handoff/cumulative-cost-bug.md.
*/
usage_scope?: string;
}
export interface ToolCall {
toolName: string;
toolInput: Record<string, unknown>;
toolResponse?: string;
isError?: boolean;
}
/**
* Hook input shape as received from Claude Code PostToolUse hook stdin.
* Uses snake_case to match the raw hook JSON.
*/
export interface HookInput {
tool_name: string;
tool_input: Record<string, unknown>;
tool_response?: string;
/** Optional structured output from the tool (may carry isError) */
tool_output?: { isError?: boolean; is_error?: boolean };
}
// ── Internal helpers ───────────────────────────────────────────────────────
/** Null-safe string coercion — no truncation, preserves full data. */
function safeString(value: string | null | undefined): string {
if (value == null) return "";
return String(value);
}
/** Serialise an unknown value to a string — no truncation. */
function safeStringAny(value: unknown): string {
if (value == null) return "";
return typeof value === "string" ? value : JSON.stringify(value);
}
function isToolError(input: HookInput): boolean {
const response = String(input.tool_response ?? "");
// PreToolUse rewrites curl/wget/inline-HTTP/WebFetch commands into
// echo "context-mode: <guidance text including 'retry', 'fails', 'error'>"
// The user-facing copy legitimately mentions failure modes ("retry if it
// fails with a transient DNS error"), but those words must NOT classify
// our OWN guidance message as a tool error or it gets captured into
// session_resume and surfaces as a fake error in the next chat.
// We check BOTH sides because:
// - real shell run → response starts with `context-mode:` (echo stdout)
// - test/captured-output path → response is the raw command itself
// (`echo "context-mode: …"`), so we also match the command shape
const command = String(input.tool_input?.command ?? "");
if (
response.startsWith("context-mode:") ||
command.startsWith('echo "context-mode:') ||
command.startsWith("echo 'context-mode:")
) {
return false;
}
const isErrorFlag = input.tool_output?.isError === true || input.tool_output?.is_error === true;
const isBashError =
input.tool_name === "Bash" &&
/exit code [1-9]|error:|Error:|FAIL|failed/i.test(response);
return isBashError || isErrorFlag;
}
interface ApplyPatchTarget {
path: string;
type: "file_write" | "file_edit";
}
function extractApplyPatchTargets(command: string): ApplyPatchTarget[] {
if (!command) return [];
const targets: ApplyPatchTarget[] = [];
for (const line of command.split(/\r?\n/)) {
if (line.startsWith("*** Add File: ")) {
targets.push({ path: line.slice(14).trim(), type: "file_write" });
continue;
}
if (line.startsWith("*** Update File: ")) {
targets.push({ path: line.slice(17).trim(), type: "file_edit" });
continue;
}
if (line.startsWith("*** Delete File: ")) {
targets.push({ path: line.slice(17).trim(), type: "file_edit" });
continue;
}
if (line.startsWith("*** Move to: ")) {
targets.push({ path: line.slice(13).trim(), type: "file_edit" });
}
}
const seen = new Set<string>();
return targets.filter((target) => {
if (!target.path) return false;
const key = `${target.type}:${target.path}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
function isPlanFilePath(filePath: string): boolean {
return /(?:^|[/\\])\.claude[/\\]plans[/\\]/.test(filePath);
}
// ── Category extractors ────────────────────────────────────────────────────
/**
* Category 1 & 2: rule + file
*
* CLAUDE.md / .claude/ reads → emit both a "rule" event (priority 1) AND a
* "file_read" event (priority 1) because the file is being actively accessed.
*
* Other Edit/Write/Read tool calls → emit a file_edit / file_write / file_read
* event (priority 1).
*/
function extractFileAndRule(input: HookInput): SessionEvent[] {
const { tool_name, tool_input, tool_response } = input;
const events: SessionEvent[] = [];
if (tool_name === "Read") {
const filePath = String(tool_input["file_path"] ?? "");
// Rule detection — covers every supported platform's instruction
// file convention plus per-user memory directories. Hardcoding here
// (instead of dispatching through the adapter) keeps extract.ts
// pure / sync / hot-path-safe — the tradeoff is that adding a new
// platform requires updating this regex.
//
// Filenames: CLAUDE.md, AGENTS.md, AGENTS.override.md, GEMINI.md,
// QWEN.md, KIRO.md, copilot-instructions.md,
// context-mode.mdc
// Directories: .claude/, .codex/memories/, .qwen/memory/,
// .gemini/memory/, .config/<plat>/memory/, .cursor/memory/,
// .github/memory/, .kiro/memory/, etc.
const isRuleFile =
/(?:CLAUDE|AGENTS(?:\.override)?|GEMINI|QWEN|KIRO)\.md$/i.test(filePath)
|| /\/copilot-instructions\.md$/i.test(filePath)
|| /\/context-mode\.mdc$/i.test(filePath)
|| /\.claude[\\/]/i.test(filePath)
|| /[\\/]memor(?:y|ies)[\\/][^\\/]+\.md$/i.test(filePath);
if (isRuleFile) {
events.push({
type: "rule",
category: "rule",
data: safeString(filePath),
priority: 1,
});
// Capture rule content so it survives context compaction
if (tool_response && tool_response.length > 0) {
events.push({
type: "rule_content",
category: "rule",
data: safeString(tool_response),
priority: 1,
});
}
}
// Always emit file_read for any Read call
events.push({
type: "file_read",
category: "file",
data: safeString(filePath),
priority: 1,
});
return events;
}
if (tool_name === "Edit") {
const filePath = String(tool_input["file_path"] ?? "");
events.push({
type: "file_edit",
category: "file",
data: safeString(filePath),
priority: 1,
});
return events;
}
if (tool_name === "NotebookEdit") {
const notebookPath = String(tool_input["notebook_path"] ?? "");
events.push({
type: "file_edit",
category: "file",
data: safeString(notebookPath),
priority: 1,
});
return events;
}
if (tool_name === "Write") {
const filePath = String(tool_input["file_path"] ?? "");
events.push({
type: "file_write",
category: "file",
data: safeString(filePath),
priority: 1,
});
return events;
}
if (tool_name === "apply_patch") {
if (isToolError(input)) return [];
const patchTargets = extractApplyPatchTargets(
String(tool_input["command"] ?? tool_input["patch"] ?? ""),
);
for (const target of patchTargets) {
events.push({
type: target.type,
category: "file",
data: safeString(target.path),
priority: 1,
});
}
return events;
}
// Glob — file pattern exploration
if (tool_name === "Glob") {
const pattern = String(tool_input["pattern"] ?? "");
events.push({
type: "file_glob",
category: "file",
data: safeString(pattern),
priority: 3,
});
return events;
}
// Grep — code search
if (tool_name === "Grep") {
const searchPattern = String(tool_input["pattern"] ?? "");
const searchPath = String(tool_input["path"] ?? "");
events.push({
type: "file_search",
category: "file",
data: safeString(`${searchPattern} in ${searchPath}`),
priority: 3,
});
return events;
}
return events;
}
/**
* Category 4: cwd
* Matches the first `cd <path>` in a Bash command (handles quoted paths).
*/
function extractCwd(input: HookInput): SessionEvent[] {
if (input.tool_name !== "Bash") return [];
const cmd = String(input.tool_input["command"] ?? "");
// Match: cd "path" | cd 'path' | cd path
const cdMatch = cmd.match(/\bcd\s+("([^"]+)"|'([^']+)'|(\S+))/);
if (!cdMatch) return [];
const dir = cdMatch[2] ?? cdMatch[3] ?? cdMatch[4] ?? "";
return [{
type: "cwd",
category: "cwd",
data: safeString(dir),
priority: 2,
}];
}
/**
* Category 5: error
* Detects failures from bash exit codes / error patterns, or an explicit
* isError flag in tool_output.
*/
function extractError(input: HookInput): SessionEvent[] {
const { tool_response } = input;
const response = String(tool_response ?? "");
if (!isToolError(input)) return [];
return [{
type: "error_tool",
category: "error",
data: safeString(response),
priority: 2,
}];
}
/**
* Category 11: git
* Matches common git operations from Bash commands.
*/
const GIT_PATTERNS: Array<{ pattern: RegExp; operation: string }> = [
{ pattern: /\bgit\s+checkout\b/, operation: "branch" },
{ pattern: /\bgit\s+commit\b/, operation: "commit" },
{ pattern: /\bgit\s+merge\s+\S+/, operation: "merge" },
{ pattern: /\bgit\s+rebase\b/, operation: "rebase" },
{ pattern: /\bgit\s+stash\b/, operation: "stash" },
{ pattern: /\bgit\s+push\b/, operation: "push" },
{ pattern: /\bgit\s+pull\b/, operation: "pull" },
{ pattern: /\bgit\s+log\b/, operation: "log" },
{ pattern: /\bgit\s+diff\b/, operation: "diff" },
{ pattern: /\bgit\s+status\b/, operation: "status" },
{ pattern: /\bgit\s+branch\b/, operation: "branch" },
{ pattern: /\bgit\s+reset\b/, operation: "reset" },
{ pattern: /\bgit\s+add\b/, operation: "add" },
{ pattern: /\bgit\s+cherry-pick\b/, operation: "cherry-pick" },
{ pattern: /\bgit\s+tag\b/, operation: "tag" },
{ pattern: /\bgit\s+fetch\b/, operation: "fetch" },
{ pattern: /\bgit\s+clone\b/, operation: "clone" },
{ pattern: /\bgit\s+worktree\b/, operation: "worktree" },
];
function extractGit(input: HookInput): SessionEvent[] {
if (input.tool_name !== "Bash") return [];
const cmd = String(input.tool_input["command"] ?? "");
// Bug 8 (v1.0.162) — parse the git invocation algorithmically so flags
// between `git` and the operation token are tolerated (`git -C /path
// status`, `git --no-pager log`, etc.). Falls back to the legacy regex
// pattern scan when the algorithmic parse cannot locate a `git` token —
// preserves backward compat for commands like `cd /repo && git status`
// where the algorithmic parse sees `cd` as the first token instead.
const parsed = parseGitInvocation(cmd);
let match: { pattern: RegExp; operation: string } | undefined;
if (parsed && parsed.operation) {
match = GIT_PATTERNS.find(p => p.operation === parsed.operation);
}
if (!match) {
match = GIT_PATTERNS.find(p => p.pattern.test(cmd));
}
if (!match) return [];
// Bug 1 (v1.0.161) — for `git commit` operations, parse -m / -am / --message=
// from the Bash command via shell-like argv tokenization so downstream
// consumers receive the actual commit subject in `data`. Falls back to the
// operation name when no message argument is present (--amend / --no-edit /
// -F file / interactive editor flow). Tokenizer is hand-rolled char-by-char
// (no regex) to mirror real shell quoting/cluster-flag semantics.
//
// When a message is captured, the event surfaces as type='git_commit' so the
// rollup aggregator can distinguish ACTUAL commits from other git operations
// (status/diff/log were inflating has_commit on every event — see
// session-loaders.mjs rollup stamp + Bug 2).
// Bug 8 cwd hint — when `-C <dir>` is present in the git invocation, emit
// a leading cwd event so the attribution carry-forward (LAST_SEEN source)
// routes downstream events in the same batch to the scoped directory's
// project. Without the hint, `git -C /projB status` while cwd=/projA
// misattributes to /projA.
const out: SessionEvent[] = [];
if (parsed?.scopedDir) {
out.push({
type: "cwd",
category: "cwd",
data: safeString(parsed.scopedDir),
priority: 2,
});
}
if (match.operation === "commit") {
const msg = extractCommitMessageFromCommand(cmd);
if (msg) {
out.push({
type: "git_commit",
category: "git",
data: safeString(msg),
priority: 2,
});
return out;
}
}
out.push({
type: "git",
category: "git",
data: safeString(match.operation),
priority: 2,
});
return out;
}
// Algorithmic git invocation parser — tokenizes the Bash command and walks
// argv to extract the `-C <dir>` scope hint and the operation subcommand.
// Tolerates env-prefix assignments and any number of flags between `git`
// and the operation. Returns null when no `git` token is found (caller
// falls back to the legacy regex pattern scan).
interface ParsedGit {
scopedDir: string | null;
operation: string | null;
}
/**
* Gap #2 (16-oss-verify-gap-prd) — expand leading `~` / `~/` to homedir.
* Does NOT support `~user/path` (no current-user resolution at bridge
* layer; that requires a passwd lookup). Returns input unchanged when
* there is no tilde or the path starts with `~<otheruser>`.
*/
function expandHomeTilde(path: string): string {
if (typeof path !== "string" || path.length === 0) return path;
if (path === "~") return getHomedirSafe();
if (path.startsWith("~/")) return getHomedirSafe() + path.slice(1);
return path;
}
/**
* Lazily-resolved homedir — avoids a require/import at module init time.
* Falls back to "~" (no-op expansion) when the environment is sandboxed
* without HOME / USERPROFILE.
*/
function getHomedirSafe(): string {
try {
const home = process.env.HOME
|| process.env.USERPROFILE
|| (process.env.HOMEDRIVE && process.env.HOMEPATH
? process.env.HOMEDRIVE + process.env.HOMEPATH
: "");
return home || "~";
} catch {
return "~";
}
}
function parseGitInvocation(cmd: string): ParsedGit | null {
const tokens = tokenizeCommand(cmd);
let i = 0;
// Skip env-style assignments at the head (FOO=bar git ...)
while (i < tokens.length && isEnvAssignment(tokens[i])) i++;
// Locate the `git` token (allow common runners like `sudo git ...`)
while (i < tokens.length && tokens[i] !== "git" && !tokens[i].endsWith("/git")) {
// Stop runner-skipping at the first non-assignment, non-runner token
if (!isCommonRunner(tokens[i])) break;
i++;
}
if (i >= tokens.length) return null;
if (tokens[i] !== "git" && !tokens[i].endsWith("/git")) return null;
i++; // consume `git`
let scopedDir: string | null = null;
let operation: string | null = null;
while (i < tokens.length) {
const t = tokens[i];
if (t === "-C" || t === "--directory") {
scopedDir = tokens[i + 1] ?? null;
i += 2;
continue;
}
// Gap #2 — `--directory=/path` equals-form (tokenizer keeps it as one)
if (t.startsWith("--directory=")) {
scopedDir = t.slice("--directory=".length);
i++;
continue;
}
if (t.length > 0 && t[0] === "-") {
// Generic flag — skip the flag itself. We do NOT consume the next
// token as its value generically because git's per-flag arg shape
// varies; the dedicated extractCommitMessageFromCommand handles -m
// separately.
i++;
continue;
}
// First bare (non-flag) token after `git` = operation
operation = t;
break;
}
if (scopedDir) scopedDir = expandHomeTilde(scopedDir);
return { scopedDir, operation };
}
function isEnvAssignment(token: string): boolean {
if (token.length === 0) return false;
// FOO=bar shape: starts with an uppercase letter, contains an `=`
let sawEq = false;
for (let j = 0; j < token.length; j++) {
const c = token.charCodeAt(j);
if (j === 0) {
// First char must be A-Z or underscore
if (!((c >= 65 && c <= 90) || c === 95)) return false;
} else if (c === 61 /* = */) {
sawEq = true;
break;
} else if (!((c >= 65 && c <= 90) || (c >= 48 && c <= 57) || c === 95)) {
// Body chars must be A-Z, 0-9, or _
return false;
}
}
return sawEq;
}
function isCommonRunner(token: string): boolean {
// Runners that wrap real commands. We skip them when locating `git`
// so `sudo git status` works the same as `git status`.
switch (token) {
case "sudo":
case "doas":
case "env":
case "exec":
case "time":
return true;
default:
return false;
}
}
// Shell-like argv tokenizer — handles single/double quotes, backslash escapes,
// and merges adjacent quoted/unquoted segments per POSIX shell behavior
// (`echo a"b c"d` → ["ab cd"]). Pure char loop; no regex.
function tokenizeCommand(cmd: string): string[] {
const tokens: string[] = [];
const n = cmd.length;
let i = 0;
while (i < n) {
while (i < n && (cmd[i] === " " || cmd[i] === "\t")) i++;
if (i >= n) break;
let buf = "";
while (i < n && cmd[i] !== " " && cmd[i] !== "\t") {
const ch = cmd[i];
if (ch === '"' || ch === "'") {
const quote = ch;
i++;
while (i < n && cmd[i] !== quote) {
if (cmd[i] === "\\" && i + 1 < n) {
buf += cmd[i + 1];
i += 2;
} else {
buf += cmd[i];
i++;
}
}
if (i < n) i++; // consume closing quote
} else if (ch === "\\" && i + 1 < n) {
buf += cmd[i + 1];
i += 2;
} else {
buf += ch;
i++;
}
}
tokens.push(buf);
}
return tokens;
}
// Linear scan over argv looking for a commit-message-bearing flag:
// --message=<value> long form, attached value
// --message <value> long form, separate token
// -m / -am / -cm ... short cluster ending in 'm', value in next token
// Returns null when no message arg is present — caller falls back to
// operation name. Pure char checks; no regex.
function extractCommitMessageFromCommand(cmd: string): string | null {
const argv = tokenizeCommand(cmd);
const longPrefix = "--message=";
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
// Long form: --message=VALUE
if (arg.length > longPrefix.length && arg.startsWith(longPrefix)) {
const v = arg.slice(longPrefix.length);
return v.length > 0 ? v : null;
}
// Long form: --message VALUE
if (arg === "--message") {
const v = argv[i + 1];
return v && v.length > 0 ? v : null;
}
// Short cluster ending in 'm' (e.g. -m, -am, -cm). Cluster must be
// single-dash followed by only lowercase letters, last letter 'm'.
if (
arg.length >= 2 &&
arg[0] === "-" &&
arg[1] !== "-" &&
arg[arg.length - 1] === "m" &&
isLowerAlphaRun(arg, 1)
) {
const v = argv[i + 1];
return v && v.length > 0 ? v : null;
}
}
return null;
}
function isLowerAlphaRun(s: string, start: number): boolean {
if (start >= s.length) return false;
for (let i = start; i < s.length; i++) {
const c = s.charCodeAt(i);
if (c < 97 || c > 122) return false; // not a-z
}
return true;
}
/**
* Category 3: task
* TodoWrite / TaskCreate / TaskUpdate tool calls.
*/
function extractTask(input: HookInput): SessionEvent[] {
const TASK_TOOLS = new Set(["TodoWrite", "TaskCreate", "TaskUpdate"]);
if (!TASK_TOOLS.has(input.tool_name)) return [];
// Store tool name as type so create vs update can be reliably distinguished
const type = input.tool_name === "TaskUpdate" ? "task_update"
: input.tool_name === "TaskCreate" ? "task_create"
: "task"; // TodoWrite fallback
return [{
type,
category: "task",
data: safeString(JSON.stringify(input.tool_input)),
priority: 1,
}];
}
/**
* Category 15: plan
* Tracks the full plan mode lifecycle:
* - EnterPlanMode → plan_enter
* - Write/Edit to ~/.claude/plans/ → plan_file_write
* - ExitPlanMode → plan_exit (with allowedPrompts)
* - ExitPlanMode tool_response → plan_approved / plan_rejected
*
* Note: Shift+Tab and /plan command do NOT fire PostToolUse hooks
* (Claude Code bug #15660). Only programmatic EnterPlanMode is tracked.
*/
/**
* FNV-1a 32-bit hash → 8-char lowercase hex. Stable across runs/platforms.
* Used for plan_hash so identical plans dedupe at the platform side.
*/
function fnv1a32Hex(s: string): string {
let hash = 0x811c9dc5;
for (let i = 0; i < s.length; i++) {
hash ^= s.charCodeAt(i);
hash = Math.imul(hash, 0x01000193);
}
return (hash >>> 0).toString(16).padStart(8, "0");
}
/**
* Read the plan text from the ExitPlanMode envelope. SDK carries it on
* the OUTPUT (ExitPlanModeOutput @ :2222), but the PRD body cites input.
* Try both so we are spec-flexible.
*/
function extractExitPlanText(input: HookInput): string | null {
const inputPlan = input.tool_input["plan"];
if (typeof inputPlan === "string" && inputPlan.length > 0) return inputPlan;
const resp = input.tool_response;
if (typeof resp === "string" && resp.length > 0) {
try {
const parsed = JSON.parse(resp);
if (parsed && typeof parsed === "object" && typeof (parsed as Record<string, unknown>).plan === "string") {
return (parsed as Record<string, unknown>).plan as string;
}
} catch { /* fall through */ }
}
return null;
}
function extractPlan(input: HookInput): SessionEvent[] {
if (input.tool_name === "EnterPlanMode") {
return [{
type: "plan_enter",
category: "plan",
data: "entered plan mode",
priority: 2,
}];
}
if (input.tool_name === "ExitPlanMode") {
const events: SessionEvent[] = [];
// Plan exit event with allowedPrompts detail
const prompts = input.tool_input["allowedPrompts"];
let detail = Array.isArray(prompts) && prompts.length > 0
? `exited plan mode (allowed: ${safeStringAny(prompts.map((p: unknown) => {
if (typeof p === "object" && p !== null && "prompt" in p) return String((p as Record<string, unknown>).prompt);
return String(p);
}).join(", "))})`
: "exited plan mode";
// §11 / PRD #6 — append plan_bytes + plan_hash so the platform can
// dedupe identical plans across sessions and JOIN plan_mode_authorized
// writes against a stable plan id. Plan source: tool_input.plan first
// (per PRD), fall back to tool_response.plan (SDK actually carries it
// there per ExitPlanModeOutput @ sdk-tools.d.ts:2222).
const plan = extractExitPlanText(input);
if (typeof plan === "string" && plan.length > 0) {
detail += ` plan_bytes:${plan.length} plan_hash:${fnv1a32Hex(plan)}`;
}
events.push({
type: "plan_exit",
category: "plan",
data: safeString(detail),
priority: 2,
});
// Detect approval/rejection from tool_response
const response = String(input.tool_response ?? "").toLowerCase();
if (response.includes("approved") || response.includes("approve")) {
events.push({
type: "plan_approved",
category: "plan",
data: "plan approved by user",
priority: 1,
});
} else if (response.includes("rejected") || response.includes("decline") || response.includes("denied")) {
events.push({
type: "plan_rejected",
category: "plan",
data: safeString(`plan rejected: ${input.tool_response ?? ""}`),
priority: 2,
});
}
return events;
}
// Detect plan file writes (Write/Edit to ~/.claude/plans/)
if (input.tool_name === "Write" || input.tool_name === "Edit") {
const filePath = String(input.tool_input["file_path"] ?? "");
if (isPlanFilePath(filePath)) {
return [{
type: "plan_file_write",
category: "plan",
data: safeString(`plan file: ${filePath.split(/[/\\]/).pop() ?? filePath}`),
priority: 2,
}];
}
}
if (input.tool_name === "apply_patch") {
if (isToolError(input)) return [];
const patchTargets = extractApplyPatchTargets(
String(input.tool_input["command"] ?? input.tool_input["patch"] ?? ""),
);
return patchTargets
.filter((target) => isPlanFilePath(target.path))
.map((target) => ({
type: "plan_file_write",
category: "plan",
data: safeString(`plan file: ${target.path.split(/[/\\]/).pop() ?? target.path}`),
priority: 2,
}));
}
return [];
}
/**
* Category 8: env
* Environment setup commands in Bash: venv, export, nvm, pyenv, conda, rbenv.
*/
const ENV_PATTERNS: RegExp[] = [
/\bsource\s+\S*activate\b/,
/\bexport\s+\w+=/,
/\bnvm\s+use\b/,
/\bpyenv\s+(shell|local|global)\b/,
/\bconda\s+activate\b/,
/\brbenv\s+(shell|local|global)\b/,
/\bnpm\s+install\b/,
/\bnpm\s+ci\b/,
/\bpip\s+install\b/,
/\bbun\s+install\b/,
/\byarn\s+(add|install)\b/,
/\bpnpm\s+(add|install)\b/,
/\bcargo\s+(install|add)\b/,
/\bgo\s+(install|get)\b/,
/\brustup\b/,
/\basdf\b/,
/\bvolta\b/,
/\bdeno\s+install\b/,
];
function extractEnv(input: HookInput): SessionEvent[] {
if (input.tool_name !== "Bash") return [];
const cmd = String(input.tool_input["command"] ?? "");
const isEnvCmd = ENV_PATTERNS.some(p => p.test(cmd));
if (!isEnvCmd) return [];
// Sanitize export commands to prevent secret leakage
const sanitized = cmd.replace(/\bexport\s+(\w+)=\S*/g, "export $1=***");
return [{
type: "env",
category: "env",
data: safeString(sanitized),
priority: 2,
}];
}
/**
* Category 10: skill
* Skill tool invocations.
*/
function extractSkill(input: HookInput): SessionEvent[] {
if (input.tool_name !== "Skill") return [];
const skillName = String(input.tool_input["skill"] ?? "");
return [{
type: "skill",
category: "skill",
data: safeString(skillName),
priority: 2,
}];
}
/**
* Category 16: constraint
* Constraints discovered through error events — tool failures reveal
* platform/environment limitations worth remembering.
*/
function extractConstraint(input: HookInput): SessionEvent[] {
// Only fire on error events — constraints are discovered through failures
if (!input.tool_response?.includes("Error") && !input.tool_output?.isError) return [];
const response = String(input.tool_response || "");
const patterns = [/not supported/i, /cannot/i, /does not support/i, /FAIL/i, /refused/i, /permission denied/i, /incompatible/i];
for (const pattern of patterns) {
const match = response.match(pattern);
if (match) {
// Extract context around the match
const idx = response.toLowerCase().indexOf(match[0].toLowerCase());
const context = response.slice(Math.max(0, idx - 50), Math.min(response.length, idx + 200)).trim();
return [{
type: "constraint_discovered",
category: "constraint",
data: safeString(context),
priority: 2,
}];
}
}
return [];
}
/**
* Category 9: subagent
* Agent tool calls — tracks both launch and completion.
* When tool_response is present, the agent has completed and the result
* is captured at higher priority (P2) so it survives budget trimming.
*/
function extractSubagent(input: HookInput): SessionEvent[] {
if (input.tool_name !== "Agent") return [];
const prompt = safeString(String(input.tool_input["prompt"] ?? input.tool_input["description"] ?? ""));
const response = input.tool_response ? safeString(String(input.tool_response)) : "";
const isCompleted = response.length > 0;
return [{
type: isCompleted ? "subagent_completed" : "subagent_launched",
category: "subagent",
data: isCompleted
? safeString(`[completed] ${prompt} → ${response}`)
: safeString(`[launched] ${prompt}`),
priority: isCompleted ? 2 : 3,
}];
}
/**
* Category 14: mcp
* MCP tool calls (context7, playwright, claude-mem, ctx-stats, etc.).
*/
function extractMcp(input: HookInput): SessionEvent[] {
const { tool_name, tool_input, tool_response } = input;
if (!tool_name.startsWith("mcp__")) return [];
// Extract readable tool name: last segment after __
const parts = tool_name.split("__");
const toolShort = parts[parts.length - 1] || tool_name;
// Extract first string argument for context
const firstArg = Object.values(tool_input).find((v): v is string => typeof v === "string");
const argStr = firstArg ? `: ${safeString(String(firstArg))}` : "";
// Append tool_response so ctx_search can find what the MCP returned — not
// just the call shape. Without this, bodies from external MCPs (jira tickets,
// grafana loki lines, sentry issues, context7 docs) are invisible to search.
// No truncation: matches the rule_content precedent above — SQLite TEXT is
// unbounded and large responses are the ones a cache most wants to preserve.
const responseStr = tool_response && tool_response.length > 0
? `\nresponse: ${safeString(tool_response)}`
: "";
return [{
type: "mcp",
category: "mcp",
data: safeString(`${toolShort}${argStr}${responseStr}`),
priority: 3,
}];
}
/**
* Category 27: mcp_tool_call
* Records the raw MCP call shape (tool_name + tool_input) so analytics
* can compute usage patterns like batch concurrency.
*
* Distinct from `extractMcp` (category "mcp"), which captures the textual
* call+response for FTS5 search. This emits a structured JSON payload
* keyed by tool_name + params, capped to ~2KB to keep SQLite rows small.
*
* Priority 4 (informational) — should not crowd out high-signal events
* during FIFO eviction.
*/
const MCP_PARAMS_BUDGET_BYTES = 2048;
/**
* UTF-8-aware string truncation. Returns the longest prefix of `s` whose
* UTF-8 byte length is <= `maxBytes`, never landing mid-multibyte-codepoint.
*
* Naive `s.slice(0, N)` operates on UTF-16 code units, so a 2KB cap could
* either over-shoot (multi-byte codepoints occupy fewer code units than
* bytes — e.g. a chunk of CJK / emoji-heavy JSON would silently exceed
* the byte budget) or land mid surrogate pair (corrupt JSON downstream).
*/
function truncateToBytes(s: string, maxBytes: number): { value: string; truncated: boolean } {
if (Buffer.byteLength(s, "utf8") <= maxBytes) return { value: s, truncated: false };
const buf = Buffer.from(s, "utf8");
// Walk back from maxBytes until the byte starts a fresh codepoint:
// 0xxxxxxx → ASCII (start)
// 11xxxxxx → start of multi-byte
// 10xxxxxx → continuation; keep walking
let cut = maxBytes;
while (cut > 0 && (buf[cut] & 0xc0) === 0x80) cut--;
return { value: buf.subarray(0, cut).toString("utf8"), truncated: true };
}
/**
* Keys whose VALUES must be redacted before persisting tool_input — secrets,
* tokens, credentials, signatures. Match is on the LAST path segment of the
* key (case-insensitive substring), so `headers.Authorization`, `auth.token`,
* `apiKey`, `API_KEY`, `password`, `secret`, `cookie`, `set-cookie`, `signature`,
* `private_key`, etc. all redact. False-positive risk acceptable — we'd rather
* over-redact than ship a Bearer token to SQLite.
*/
const SECRET_KEY_PATTERN =
/(authorization|auth_token|access_token|refresh_token|bearer|token|secret|password|passwd|pwd|api[-_]?key|apikey|cookie|set-cookie|signature|private[-_]?key|client[-_]?secret|x[-_]?api[-_]?key)/i;
const REDACTED = "[REDACTED]";
/**
* Walk an arbitrary JSON-serializable value and return a clone with values
* redacted under any key matching SECRET_KEY_PATTERN. Cycle-safe.