@invictus-group-ai/hooks 0.5.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 (94) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +130 -0
  3. package/dist/bin.d.ts +11 -0
  4. package/dist/bin.d.ts.map +1 -0
  5. package/dist/bin.js +37 -0
  6. package/dist/bin.js.map +1 -0
  7. package/dist/engine.d.ts +53 -0
  8. package/dist/engine.d.ts.map +1 -0
  9. package/dist/engine.js +182 -0
  10. package/dist/engine.js.map +1 -0
  11. package/dist/git/post-commit.d.ts +43 -0
  12. package/dist/git/post-commit.d.ts.map +1 -0
  13. package/dist/git/post-commit.js +166 -0
  14. package/dist/git/post-commit.js.map +1 -0
  15. package/dist/git/pre-push.d.ts +43 -0
  16. package/dist/git/pre-push.d.ts.map +1 -0
  17. package/dist/git/pre-push.js +102 -0
  18. package/dist/git/pre-push.js.map +1 -0
  19. package/dist/git/prepare-commit-msg.d.ts +97 -0
  20. package/dist/git/prepare-commit-msg.d.ts.map +1 -0
  21. package/dist/git/prepare-commit-msg.js +623 -0
  22. package/dist/git/prepare-commit-msg.js.map +1 -0
  23. package/dist/git-activate.d.ts +25 -0
  24. package/dist/git-activate.d.ts.map +1 -0
  25. package/dist/git-activate.js +75 -0
  26. package/dist/git-activate.js.map +1 -0
  27. package/dist/hooks/db-guard.d.ts +31 -0
  28. package/dist/hooks/db-guard.d.ts.map +1 -0
  29. package/dist/hooks/db-guard.js +290 -0
  30. package/dist/hooks/db-guard.js.map +1 -0
  31. package/dist/hooks/index.d.ts +16 -0
  32. package/dist/hooks/index.d.ts.map +1 -0
  33. package/dist/hooks/index.js +24 -0
  34. package/dist/hooks/index.js.map +1 -0
  35. package/dist/hooks/journal-nudge.d.ts +14 -0
  36. package/dist/hooks/journal-nudge.d.ts.map +1 -0
  37. package/dist/hooks/journal-nudge.js +60 -0
  38. package/dist/hooks/journal-nudge.js.map +1 -0
  39. package/dist/hooks/loc-recorder.d.ts +79 -0
  40. package/dist/hooks/loc-recorder.d.ts.map +1 -0
  41. package/dist/hooks/loc-recorder.js +183 -0
  42. package/dist/hooks/loc-recorder.js.map +1 -0
  43. package/dist/hooks/metrics-capture.d.ts +34 -0
  44. package/dist/hooks/metrics-capture.d.ts.map +1 -0
  45. package/dist/hooks/metrics-capture.js +275 -0
  46. package/dist/hooks/metrics-capture.js.map +1 -0
  47. package/dist/hooks/secret-guard.d.ts +19 -0
  48. package/dist/hooks/secret-guard.d.ts.map +1 -0
  49. package/dist/hooks/secret-guard.js +163 -0
  50. package/dist/hooks/secret-guard.js.map +1 -0
  51. package/dist/hooks/session-boot.d.ts +17 -0
  52. package/dist/hooks/session-boot.d.ts.map +1 -0
  53. package/dist/hooks/session-boot.js +123 -0
  54. package/dist/hooks/session-boot.js.map +1 -0
  55. package/dist/hooks/stop-gate.d.ts +17 -0
  56. package/dist/hooks/stop-gate.d.ts.map +1 -0
  57. package/dist/hooks/stop-gate.js +97 -0
  58. package/dist/hooks/stop-gate.js.map +1 -0
  59. package/dist/hooks/typecheck-on-edit.d.ts +18 -0
  60. package/dist/hooks/typecheck-on-edit.d.ts.map +1 -0
  61. package/dist/hooks/typecheck-on-edit.js +110 -0
  62. package/dist/hooks/typecheck-on-edit.js.map +1 -0
  63. package/dist/i18n/en.d.ts +45 -0
  64. package/dist/i18n/en.d.ts.map +1 -0
  65. package/dist/i18n/en.js +53 -0
  66. package/dist/i18n/en.js.map +1 -0
  67. package/dist/i18n/index.d.ts +35 -0
  68. package/dist/i18n/index.d.ts.map +1 -0
  69. package/dist/i18n/index.js +56 -0
  70. package/dist/i18n/index.js.map +1 -0
  71. package/dist/i18n/pt-BR.d.ts +12 -0
  72. package/dist/i18n/pt-BR.d.ts.map +1 -0
  73. package/dist/i18n/pt-BR.js +50 -0
  74. package/dist/i18n/pt-BR.js.map +1 -0
  75. package/dist/index.d.ts +17 -0
  76. package/dist/index.d.ts.map +1 -0
  77. package/dist/index.js +12 -0
  78. package/dist/index.js.map +1 -0
  79. package/dist/kit-cli.d.ts +36 -0
  80. package/dist/kit-cli.d.ts.map +1 -0
  81. package/dist/kit-cli.js +68 -0
  82. package/dist/kit-cli.js.map +1 -0
  83. package/dist/metrics-schema.d.ts +215 -0
  84. package/dist/metrics-schema.d.ts.map +1 -0
  85. package/dist/metrics-schema.js +83 -0
  86. package/dist/metrics-schema.js.map +1 -0
  87. package/dist/shared.d.ts +81 -0
  88. package/dist/shared.d.ts.map +1 -0
  89. package/dist/shared.js +276 -0
  90. package/dist/shared.js.map +1 -0
  91. package/githooks/prepare-commit-msg +30 -0
  92. package/githooks/prepare-commit-msg.cmd +16 -0
  93. package/package.json +71 -0
  94. package/settings-template.json +97 -0
@@ -0,0 +1,79 @@
1
+ /**
2
+ * loc-recorder — PostToolUse on Write | Edit | MultiEdit | NotebookEdit.
3
+ * SILENT (no stdout/stderr, never blocks). Runs in the SAME engine process
4
+ * as typecheck-on-edit (multi-module dispatch) — no extra spawn per edit.
5
+ *
6
+ * v2 (line-level bound): per agent edit it records the file AND the
7
+ * added/removed LINE COUNTS derived from the tool_input — Write: full
8
+ * content line count as added; Edit: line-diff of old_string vs new_string
9
+ * (common prefix/suffix strip + LCS, so shared context lines don't count);
10
+ * MultiEdit: sum over edits[]. Entries accumulate per file per session in
11
+ * the local scratch `.invictus/metrics/agent-loc.jsonl` (one line per edit;
12
+ * the commit encoder sums them per file across sessions).
13
+ *
14
+ * At commit time the `prepare-commit-msg` encoder attributes, per staged
15
+ * file, `min(recorded agent lines, staged numstat lines)` as assisted
16
+ * (trailer `loc.aa/ad`) and the remainder as human (`loc.ha/hd`), then
17
+ * consumes the entries for the files it attributed.
18
+ *
19
+ * This is a per-file line-count BOUND, not per-line identity tracking:
20
+ * we know HOW MANY lines the agent added/removed in a file, not WHICH
21
+ * staged lines are the agent's. True per-line identity (git-ai-style
22
+ * checkpointing) needs content snapshots of every agent edit diffed against
23
+ * the staged blob — future work, because no hook fires on human edits:
24
+ * humans change files in their editors outside any Claude Code event, so
25
+ * their side of the diff is only observable at commit time.
26
+ *
27
+ * Documented estimate limits: Edit with `replace_all` is counted once (the
28
+ * occurrence count isn't in the tool_input); Write carries no old content,
29
+ * so lines it deletes are recorded as 0 (they surface as human deletions).
30
+ * Both directions are capped by staged reality at commit time.
31
+ *
32
+ * Scope note: file PATHS stay in this local scratch only — the event log
33
+ * and the trailer carry counts, never paths (metrics, never content).
34
+ * PostToolUse fires only after a tool ran, so rejected edits (see
35
+ * metrics-capture acc/rej) never land here.
36
+ */
37
+ import type { HookModule } from '../engine.js';
38
+ /**
39
+ * One scratch line: unix seconds, repo-relative file, lines added/deleted
40
+ * (tool_input-derived counts), session id (absent in entries written by
41
+ * hooks ≤0.2.0). Entries for the same file accumulate — the encoder sums.
42
+ */
43
+ export interface AgentLocEntry {
44
+ ts: number;
45
+ f: string;
46
+ la: number;
47
+ ld: number;
48
+ sid?: string;
49
+ /**
50
+ * Hash of the `task.commit` that consumed this entry. Consumed entries are
51
+ * kept until a later commit proves that one landed: if it was amended away
52
+ * or reset, its attribution is handed back to the commit that replaces it.
53
+ */
54
+ c?: string;
55
+ }
56
+ export declare function agentLocPath(projectDir: string): string;
57
+ /**
58
+ * Line-diff counts between two strings: lines added / removed, with common
59
+ * prefix/suffix lines stripped first and an LCS over the middle (so shared
60
+ * context lines in an Edit's old/new strings don't inflate the counts).
61
+ */
62
+ export declare function diffLineCounts(oldStr: unknown, newStr: unknown): {
63
+ la: number;
64
+ ld: number;
65
+ };
66
+ /**
67
+ * Lines added/deleted derived from the tool input (v2, per the trailer
68
+ * spec): Write = full content line count as added (no old content in the
69
+ * input, so deletions are 0 — they surface as human deletions at commit
70
+ * time); Edit = line-diff old_string vs new_string; MultiEdit = sum of the
71
+ * per-edit diffs; NotebookEdit = new_source line count. These are BOUNDS —
72
+ * the commit encoder caps each file at its staged numstat.
73
+ */
74
+ export declare function estimateLoc(toolName: string, toolInput: Record<string, unknown>): {
75
+ la: number;
76
+ ld: number;
77
+ };
78
+ export declare const locRecorder: HookModule;
79
+ //# sourceMappingURL=loc-recorder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loc-recorder.d.ts","sourceRoot":"","sources":["../../src/hooks/loc-recorder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAMH,OAAO,KAAK,EAAe,UAAU,EAAE,MAAM,cAAc,CAAC;AAK5D;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,MAAM,CAAC;IACX,CAAC,EAAE,MAAM,CAAC;IACV,EAAE,EAAE,MAAM,CAAC;IACX,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;;OAIG;IACH,CAAC,CAAC,EAAE,MAAM,CAAC;CACZ;AAED,wBAAgB,YAAY,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAEvD;AAiCD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAsB3F;AAED;;;;;;;GAOG;AACH,wBAAgB,WAAW,CACzB,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACjC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAyB5B;AAeD,eAAO,MAAM,WAAW,EAAE,UAiCzB,CAAC"}
@@ -0,0 +1,183 @@
1
+ /**
2
+ * loc-recorder — PostToolUse on Write | Edit | MultiEdit | NotebookEdit.
3
+ * SILENT (no stdout/stderr, never blocks). Runs in the SAME engine process
4
+ * as typecheck-on-edit (multi-module dispatch) — no extra spawn per edit.
5
+ *
6
+ * v2 (line-level bound): per agent edit it records the file AND the
7
+ * added/removed LINE COUNTS derived from the tool_input — Write: full
8
+ * content line count as added; Edit: line-diff of old_string vs new_string
9
+ * (common prefix/suffix strip + LCS, so shared context lines don't count);
10
+ * MultiEdit: sum over edits[]. Entries accumulate per file per session in
11
+ * the local scratch `.invictus/metrics/agent-loc.jsonl` (one line per edit;
12
+ * the commit encoder sums them per file across sessions).
13
+ *
14
+ * At commit time the `prepare-commit-msg` encoder attributes, per staged
15
+ * file, `min(recorded agent lines, staged numstat lines)` as assisted
16
+ * (trailer `loc.aa/ad`) and the remainder as human (`loc.ha/hd`), then
17
+ * consumes the entries for the files it attributed.
18
+ *
19
+ * This is a per-file line-count BOUND, not per-line identity tracking:
20
+ * we know HOW MANY lines the agent added/removed in a file, not WHICH
21
+ * staged lines are the agent's. True per-line identity (git-ai-style
22
+ * checkpointing) needs content snapshots of every agent edit diffed against
23
+ * the staged blob — future work, because no hook fires on human edits:
24
+ * humans change files in their editors outside any Claude Code event, so
25
+ * their side of the diff is only observable at commit time.
26
+ *
27
+ * Documented estimate limits: Edit with `replace_all` is counted once (the
28
+ * occurrence count isn't in the tool_input); Write carries no old content,
29
+ * so lines it deletes are recorded as 0 (they surface as human deletions).
30
+ * Both directions are capped by staged reality at commit time.
31
+ *
32
+ * Scope note: file PATHS stay in this local scratch only — the event log
33
+ * and the trailer carry counts, never paths (metrics, never content).
34
+ * PostToolUse fires only after a tool ran, so rejected edits (see
35
+ * metrics-capture acc/rej) never land here.
36
+ */
37
+ import { appendFileSync, existsSync } from 'node:fs';
38
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
39
+ import { HOOK_EXIT } from '@invictus-group-ai/core';
40
+ import { ensureDir, gitOutput } from '../shared.js';
41
+ const EDIT_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit']);
42
+ export function agentLocPath(projectDir) {
43
+ return join(projectDir, '.invictus', 'metrics', 'agent-loc.jsonl');
44
+ }
45
+ /**
46
+ * String → lines, git-style: a trailing newline terminates the last line
47
+ * rather than opening an empty one ('a\nb\n' is 2 lines, not 3).
48
+ */
49
+ function toLines(s) {
50
+ if (typeof s !== 'string' || s === '')
51
+ return [];
52
+ const lines = s.split('\n');
53
+ if (lines[lines.length - 1] === '')
54
+ lines.pop();
55
+ return lines;
56
+ }
57
+ /** LCS length via two-row DP — counts only, no backtrack. */
58
+ function lcsLength(a, b) {
59
+ let prev = new Uint32Array(b.length + 1);
60
+ let cur = new Uint32Array(b.length + 1);
61
+ for (let i = 1; i <= a.length; i++) {
62
+ for (let j = 1; j <= b.length; j++) {
63
+ cur[j] = a[i - 1] === b[j - 1] ? prev[j - 1] + 1 : Math.max(prev[j], cur[j - 1]);
64
+ }
65
+ [prev, cur] = [cur, prev];
66
+ }
67
+ return prev[b.length];
68
+ }
69
+ /**
70
+ * Above this many DP cells the LCS is skipped and the full remainders count
71
+ * as added/removed — a valid upper bound (min-capped at commit time).
72
+ * 1M cells of Uint32 DP is a few ms; typical Edit strings never get there.
73
+ */
74
+ const LCS_MAX_CELLS = 1_000_000;
75
+ /**
76
+ * Line-diff counts between two strings: lines added / removed, with common
77
+ * prefix/suffix lines stripped first and an LCS over the middle (so shared
78
+ * context lines in an Edit's old/new strings don't inflate the counts).
79
+ */
80
+ export function diffLineCounts(oldStr, newStr) {
81
+ const oldLines = toLines(oldStr);
82
+ const newLines = toLines(newStr);
83
+ let start = 0;
84
+ const minLen = Math.min(oldLines.length, newLines.length);
85
+ while (start < minLen && oldLines[start] === newLines[start])
86
+ start++;
87
+ let oldEnd = oldLines.length;
88
+ let newEnd = newLines.length;
89
+ while (oldEnd > start && newEnd > start && oldLines[oldEnd - 1] === newLines[newEnd - 1]) {
90
+ oldEnd--;
91
+ newEnd--;
92
+ }
93
+ const removed = oldEnd - start;
94
+ const added = newEnd - start;
95
+ if (removed === 0 || added === 0 || removed * added > LCS_MAX_CELLS) {
96
+ return { la: added, ld: removed };
97
+ }
98
+ const common = lcsLength(oldLines.slice(start, oldEnd), newLines.slice(start, newEnd));
99
+ return { la: added - common, ld: removed - common };
100
+ }
101
+ /**
102
+ * Lines added/deleted derived from the tool input (v2, per the trailer
103
+ * spec): Write = full content line count as added (no old content in the
104
+ * input, so deletions are 0 — they surface as human deletions at commit
105
+ * time); Edit = line-diff old_string vs new_string; MultiEdit = sum of the
106
+ * per-edit diffs; NotebookEdit = new_source line count. These are BOUNDS —
107
+ * the commit encoder caps each file at its staged numstat.
108
+ */
109
+ export function estimateLoc(toolName, toolInput) {
110
+ switch (toolName) {
111
+ case 'Write':
112
+ return { la: toLines(toolInput.content).length, ld: 0 };
113
+ case 'Edit':
114
+ return diffLineCounts(toolInput.old_string, toolInput.new_string);
115
+ case 'MultiEdit': {
116
+ let la = 0;
117
+ let ld = 0;
118
+ if (Array.isArray(toolInput.edits)) {
119
+ for (const edit of toolInput.edits) {
120
+ if (!edit || typeof edit !== 'object')
121
+ continue;
122
+ const e = edit;
123
+ const counts = diffLineCounts(e.old_string, e.new_string);
124
+ la += counts.la;
125
+ ld += counts.ld;
126
+ }
127
+ }
128
+ return { la, ld };
129
+ }
130
+ case 'NotebookEdit':
131
+ return { la: toLines(toolInput.new_source).length, ld: 0 };
132
+ default:
133
+ return { la: 0, ld: 0 };
134
+ }
135
+ }
136
+ /** Repo-relative path of the edited file, or null when outside the repo. */
137
+ function repoRelativePath(input, ctx) {
138
+ const toolInput = input.tool_input ?? {};
139
+ const raw = toolInput.file_path ?? toolInput.notebook_path;
140
+ if (typeof raw !== 'string' || raw === '')
141
+ return null;
142
+ const repoRoot = gitOutput(['rev-parse', '--show-toplevel'], ctx.projectDir) ?? ctx.projectDir;
143
+ const abs = isAbsolute(raw) ? raw : resolve(input.cwd || ctx.projectDir, raw);
144
+ const rel = relative(repoRoot, abs);
145
+ if (rel === '' || rel.startsWith('..') || isAbsolute(rel))
146
+ return null; // outside the repo
147
+ return rel.split(sep).join('/'); // normalize to git's forward slashes
148
+ }
149
+ export const locRecorder = {
150
+ name: 'loc-recorder',
151
+ events: ['PostToolUse'],
152
+ timeoutMs: 5_000,
153
+ run(input, ctx) {
154
+ const silent = { mode: 'exit', exitCode: HOOK_EXIT.SUCCESS };
155
+ if (typeof input.tool_name !== 'string' || !EDIT_TOOLS.has(input.tool_name))
156
+ return silent;
157
+ // Only record for REAL sessions: fixture invocations (kit verify/doctor,
158
+ // CI smoke tests) use a nonexistent transcript_path by convention, and
159
+ // recording them would misattribute human files as agent-touched.
160
+ if (typeof input.transcript_path !== 'string' || !existsSync(input.transcript_path)) {
161
+ return silent;
162
+ }
163
+ const file = repoRelativePath(input, ctx);
164
+ if (file === null)
165
+ return silent;
166
+ const { la, ld } = estimateLoc(input.tool_name, input.tool_input ?? {});
167
+ const entry = { ts: Math.floor(Date.now() / 1000), f: file, la, ld };
168
+ if (typeof input.session_id === 'string' && input.session_id !== '') {
169
+ entry.sid = input.session_id;
170
+ }
171
+ const path = agentLocPath(ctx.projectDir);
172
+ if (!ensureDir(dirname(path)))
173
+ return silent;
174
+ try {
175
+ appendFileSync(path, JSON.stringify(entry) + '\n', 'utf8');
176
+ }
177
+ catch {
178
+ /* fail-soft: recording LoC must never disturb the session */
179
+ }
180
+ return silent;
181
+ },
182
+ };
183
+ //# sourceMappingURL=loc-recorder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loc-recorder.js","sourceRoot":"","sources":["../../src/hooks/loc-recorder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC9E,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAGpD,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEpD,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,MAAM,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C;YACH,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,IAAI,EAAE,MAAM,CAAC,CAAC;QAC7D,CAAC;QAAC,MAAM,CAAC;YACP,6DAA6D;QAC/D,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF,CAAC"}
@@ -0,0 +1,34 @@
1
+ /**
2
+ * metrics-capture — SessionEnd + SubagentStop, and PreToolUse when Bash runs
3
+ * `git commit`. SILENT (no stdout/stderr).
4
+ *
5
+ * Parses the transcript JSONL at `transcript_path` (usage blocks on
6
+ * assistant messages) and appends ONE `session.end` event to the event log
7
+ * via @invictus-group-ai/core. This is the observability pillar's data source;
8
+ * the git-side trailer encoder derives commit trailers from these entries
9
+ * (single source — ARCHITECTURE §5).
10
+ *
11
+ * Session summaries belong HERE, not on Stop — the legacy kit ran its
12
+ * "session end" work on every assistant turn (audit defect #1).
13
+ *
14
+ * Metrics, never content: token counts, model mix, tool-call and prompt
15
+ * COUNTS, edit-tool accept/reject counts, active vs wall-clock duration.
16
+ * No prompt text, no file paths, no output.
17
+ *
18
+ * Honest caveat: local JSONL usage is approximate (streaming placeholders
19
+ * are a documented upstream issue); OTel api_request events are the
20
+ * authoritative source when a client runs a collector.
21
+ */
22
+ import type { HookModule } from '../engine.js';
23
+ import type { SessionEndData } from '../metrics-schema.js';
24
+ /**
25
+ * `git commit` in a Bash command, with global options before the verb
26
+ * (`git -C dir commit`, `cd x && git commit -m …`). `commit-tree` and
27
+ * `git log --grep commit` do not match. A false positive only costs one
28
+ * extra snapshot — snapshots are cumulative and the encoder deltas them.
29
+ */
30
+ export declare const GIT_COMMIT_RE: RegExp;
31
+ /** Parse a transcript JSONL text into a session.end data payload. */
32
+ export declare function summarizeTranscript(text: string, event: 'SessionEnd' | 'SubagentStop' | 'PreCommit', reason?: string): SessionEndData | null;
33
+ export declare const metricsCapture: HookModule;
34
+ //# sourceMappingURL=metrics-capture.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metrics-capture.d.ts","sourceRoot":"","sources":["../../src/hooks/metrics-capture.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAKH,OAAO,KAAK,EAAe,UAAU,EAAE,MAAM,cAAc,CAAC;AAE5D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AA4F3D;;;;;GAKG;AACH,eAAO,MAAM,aAAa,QACuD,CAAC;AAElF,qEAAqE;AACrE,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,YAAY,GAAG,cAAc,GAAG,WAAW,EAClD,MAAM,CAAC,EAAE,MAAM,GACd,cAAc,GAAG,IAAI,CAyJvB;AAED,eAAO,MAAM,cAAc,EAAE,UAoC5B,CAAC"}
@@ -0,0 +1,275 @@
1
+ /**
2
+ * metrics-capture — SessionEnd + SubagentStop, and PreToolUse when Bash runs
3
+ * `git commit`. SILENT (no stdout/stderr).
4
+ *
5
+ * Parses the transcript JSONL at `transcript_path` (usage blocks on
6
+ * assistant messages) and appends ONE `session.end` event to the event log
7
+ * via @invictus-group-ai/core. This is the observability pillar's data source;
8
+ * the git-side trailer encoder derives commit trailers from these entries
9
+ * (single source — ARCHITECTURE §5).
10
+ *
11
+ * Session summaries belong HERE, not on Stop — the legacy kit ran its
12
+ * "session end" work on every assistant turn (audit defect #1).
13
+ *
14
+ * Metrics, never content: token counts, model mix, tool-call and prompt
15
+ * COUNTS, edit-tool accept/reject counts, active vs wall-clock duration.
16
+ * No prompt text, no file paths, no output.
17
+ *
18
+ * Honest caveat: local JSONL usage is approximate (streaming placeholders
19
+ * are a documented upstream issue); OTel api_request events are the
20
+ * authoritative source when a client runs a collector.
21
+ */
22
+ import { readFileSync } from 'node:fs';
23
+ import { HOOK_EXIT } from '@invictus-group-ai/core';
24
+ import { modelTag, sessionEndDataSchema } from '../metrics-schema.js';
25
+ import { appendInvictusEvent } from '../shared.js';
26
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : 0);
27
+ // ---------------------------------------------------------------------------
28
+ // Edit-tool accept/reject (trailer acc/rej) — derived from the transcript.
29
+ //
30
+ // Evidence (real transcripts under ~/.claude/projects/, CLI 2.0–2.1):
31
+ // - Every tool_use normally gets a tool_result matched by `tool_use_id`
32
+ // (3454 uses / 3453 results across 156 local transcripts).
33
+ // - A DENIED call still gets a tool_result, with `is_error: true` and one
34
+ // of two stable texts: "The user doesn't want to proceed with this tool
35
+ // use." (explicit user rejection) or "Permission for this action was
36
+ // denied by the Claude Code auto mode classifier." (policy denial).
37
+ // Newer CLIs additionally stamp `toolDenialKind` on the transcript line
38
+ // ("user-rejected" | "automode-blocked") — present on only a minority of
39
+ // observed denials, so the text is the load-bearing signal.
40
+ // - A user ESC during a running tool appears as a user text line
41
+ // "[Request interrupted by user for tool use]"; the in-flight tool_use
42
+ // then has no tool_result.
43
+ // - Ordinary tool FAILURES (non-zero exit, "File has not been read yet",
44
+ // …) also carry `is_error: true` but none of the denial texts — the tool
45
+ // RAN, so the edit was accepted; failures never count as rejections.
46
+ // ---------------------------------------------------------------------------
47
+ /** Tools whose accept/reject decisions feed the trailer `acc`/`rej` (§3: edit-tool). */
48
+ const EDIT_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit']);
49
+ const DENIAL_TEXTS = [
50
+ "The user doesn't want to proceed with this tool use",
51
+ 'was denied by the Claude Code auto mode classifier',
52
+ ];
53
+ const INTERRUPT_FOR_TOOL_TEXT = '[Request interrupted by user for tool use]';
54
+ /** Gaps between consecutive transcript timestamps ≥ this are idle (act vs dur). */
55
+ const IDLE_GAP_MS = 5 * 60 * 1000;
56
+ /** Flatten a tool_result `content` (string or content-block list) to text. */
57
+ function toolResultText(content) {
58
+ if (typeof content === 'string')
59
+ return content;
60
+ if (Array.isArray(content)) {
61
+ return content
62
+ .map((item) => !!item && typeof item === 'object' && typeof item.text === 'string'
63
+ ? item.text
64
+ : '')
65
+ .join('\n');
66
+ }
67
+ return '';
68
+ }
69
+ /** True when a tool_result records a DENIAL (not a mere tool failure). */
70
+ function isDenialResult(item, line) {
71
+ if (item.is_error !== true)
72
+ return false;
73
+ if (typeof line.toolDenialKind === 'string' && line.toolDenialKind !== '')
74
+ return true;
75
+ const text = toolResultText(item.content);
76
+ return DENIAL_TEXTS.some((t) => text.includes(t));
77
+ }
78
+ /**
79
+ * `git commit` in a Bash command, with global options before the verb
80
+ * (`git -C dir commit`, `cd x && git commit -m …`). `commit-tree` and
81
+ * `git log --grep commit` do not match. A false positive only costs one
82
+ * extra snapshot — snapshots are cumulative and the encoder deltas them.
83
+ */
84
+ export const GIT_COMMIT_RE = /(?:^|[\s;&|()`])git(?:\s+(?:-[Cc]\s+\S+|--[\w-]+(?:=\S+)?))*\s+commit(?=\s|$)/;
85
+ /** Parse a transcript JSONL text into a session.end data payload. */
86
+ export function summarizeTranscript(text, event, reason) {
87
+ const t = { i: 0, o: 0, cr: 0, cw: 0 };
88
+ const modelWeights = new Map();
89
+ let usd = 0;
90
+ let prompts = 0;
91
+ let toolCalls = 0;
92
+ let acc = 0;
93
+ let rej = 0;
94
+ /** Edit tool_use ids awaiting a tool_result (in-flight). */
95
+ const pendingEdits = new Set();
96
+ const timestamps = [];
97
+ let firstTs = null;
98
+ let lastTs = null;
99
+ let cliVersion = null;
100
+ let sawAnyLine = false;
101
+ for (const rawLine of text.split('\n')) {
102
+ if (rawLine.trim() === '')
103
+ continue;
104
+ let line;
105
+ try {
106
+ line = JSON.parse(rawLine);
107
+ }
108
+ catch {
109
+ continue; // partial/corrupt line — skip, keep counting the rest
110
+ }
111
+ sawAnyLine = true;
112
+ if (typeof line.timestamp === 'string') {
113
+ const ts = Date.parse(line.timestamp);
114
+ if (Number.isFinite(ts)) {
115
+ timestamps.push(ts);
116
+ if (firstTs === null || ts < firstTs)
117
+ firstTs = ts;
118
+ if (lastTs === null || ts > lastTs)
119
+ lastTs = ts;
120
+ }
121
+ }
122
+ if (typeof line.version === 'string' && line.version !== '')
123
+ cliVersion = line.version;
124
+ if (typeof line.costUSD === 'number' && Number.isFinite(line.costUSD))
125
+ usd += line.costUSD;
126
+ const message = line.message;
127
+ if (!message)
128
+ continue;
129
+ if (line.type === 'assistant' || message.role === 'assistant') {
130
+ const usage = message.usage;
131
+ if (usage) {
132
+ const i = num(usage.input_tokens);
133
+ const o = num(usage.output_tokens);
134
+ t.i += i;
135
+ t.o += o;
136
+ t.cr += num(usage.cache_read_input_tokens);
137
+ t.cw += num(usage.cache_creation_input_tokens);
138
+ if (typeof message.model === 'string' && message.model !== '') {
139
+ modelWeights.set(message.model, (modelWeights.get(message.model) ?? 0) + i + o + 1);
140
+ }
141
+ }
142
+ if (Array.isArray(message.content)) {
143
+ for (const item of message.content) {
144
+ if (!item || typeof item !== 'object')
145
+ continue;
146
+ const block = item;
147
+ if (block.type !== 'tool_use')
148
+ continue;
149
+ toolCalls += 1;
150
+ if (typeof block.name === 'string' && EDIT_TOOLS.has(block.name) && typeof block.id === 'string') {
151
+ pendingEdits.add(block.id);
152
+ }
153
+ }
154
+ }
155
+ continue;
156
+ }
157
+ if (line.type === 'user') {
158
+ const content = message.content;
159
+ // tool_results ride user lines (meta or not) — resolve pending edits first.
160
+ let sawToolResult = false;
161
+ if (Array.isArray(content)) {
162
+ for (const item of content) {
163
+ if (!item || typeof item !== 'object')
164
+ continue;
165
+ const block = item;
166
+ if (block.type === 'tool_result') {
167
+ sawToolResult = true;
168
+ const tid = block.tool_use_id;
169
+ if (typeof tid === 'string' && pendingEdits.delete(tid)) {
170
+ if (isDenialResult(block, line))
171
+ rej += 1;
172
+ else
173
+ acc += 1;
174
+ }
175
+ }
176
+ else if (block.type === 'text' &&
177
+ typeof block.text === 'string' &&
178
+ block.text.includes(INTERRUPT_FOR_TOOL_TEXT)) {
179
+ // ESC during a running tool: the in-flight edit(s) never resolve.
180
+ rej += pendingEdits.size;
181
+ pendingEdits.clear();
182
+ }
183
+ }
184
+ }
185
+ if (!line.isMeta) {
186
+ if (typeof content === 'string')
187
+ prompts += 1;
188
+ else if (Array.isArray(content) && !sawToolResult)
189
+ prompts += 1;
190
+ }
191
+ }
192
+ }
193
+ if (!sawAnyLine)
194
+ return null;
195
+ // Edits still pending at transcript end have no verdict in the data
196
+ // (session ended mid-tool) — counted neither accepted nor rejected.
197
+ // Active seconds: sum consecutive timestamp gaps < 5 min over the sorted
198
+ // timeline; larger gaps are idle. Always ≤ durSec by construction.
199
+ timestamps.sort((a, b) => a - b);
200
+ let activeMs = 0;
201
+ for (let i = 1; i < timestamps.length; i++) {
202
+ const gap = timestamps[i] - timestamps[i - 1];
203
+ if (gap > 0 && gap < IDLE_GAP_MS)
204
+ activeMs += gap;
205
+ }
206
+ // Model mix as integer percentages weighted by (input+output) tokens.
207
+ const totalWeight = [...modelWeights.values()].reduce((a, b) => a + b, 0);
208
+ const m = {};
209
+ let dominant;
210
+ let dominantWeight = -1;
211
+ for (const [model, weight] of modelWeights) {
212
+ const tag = modelTag(model);
213
+ m[tag] = Math.min(100, Math.max(0, Math.round((weight / totalWeight) * 100)));
214
+ if (weight > dominantWeight) {
215
+ dominantWeight = weight;
216
+ dominant = model;
217
+ }
218
+ }
219
+ const durSec = firstTs !== null && lastTs !== null ? Math.max(0, Math.round((lastTs - firstTs) / 1000)) : 0;
220
+ const data = {
221
+ event,
222
+ ...(reason ? { reason: reason.slice(0, 64) } : {}),
223
+ t,
224
+ m,
225
+ ...(dominant ? { model: dominant.slice(0, 64) } : {}),
226
+ ...(cliVersion && /^[A-Za-z0-9._-]+$/.test(cliVersion)
227
+ ? { tool: `claude-code@${cliVersion}`.slice(0, 48) }
228
+ : {}),
229
+ usdCents: Math.round(usd * 100),
230
+ prompts,
231
+ toolCalls,
232
+ acc,
233
+ rej,
234
+ actSec: Math.round(activeMs / 1000),
235
+ durSec,
236
+ };
237
+ // Validate against the shared schema so the producer can never write an
238
+ // entry the git-side consumer would reject.
239
+ const parsed = sessionEndDataSchema.safeParse(data);
240
+ return parsed.success ? parsed.data : null;
241
+ }
242
+ export const metricsCapture = {
243
+ name: 'metrics-capture',
244
+ // PreToolUse: a snapshot right before the agent commits, so the commit
245
+ // carries this session's work instead of waiting for the session to end.
246
+ events: ['SessionEnd', 'SubagentStop', 'PreToolUse'],
247
+ timeoutMs: 30_000,
248
+ run(input, ctx) {
249
+ const silent = { mode: 'exit', exitCode: HOOK_EXIT.SUCCESS };
250
+ if (input.hook_event_name === 'PreToolUse') {
251
+ const command = input.tool_input?.['command'];
252
+ if (input.tool_name !== 'Bash' || typeof command !== 'string' || !GIT_COMMIT_RE.test(command)) {
253
+ return silent; // every other Bash call: nothing to do, not even a read
254
+ }
255
+ }
256
+ let text;
257
+ try {
258
+ text = readFileSync(input.transcript_path, 'utf8');
259
+ }
260
+ catch {
261
+ return silent; // no transcript, nothing to record
262
+ }
263
+ const event = input.hook_event_name === 'SubagentStop'
264
+ ? 'SubagentStop'
265
+ : input.hook_event_name === 'PreToolUse'
266
+ ? 'PreCommit'
267
+ : 'SessionEnd';
268
+ const data = summarizeTranscript(text, event, input.reason);
269
+ if (data === null)
270
+ return silent;
271
+ appendInvictusEvent(ctx.projectDir, ctx.env, input.session_id, 'session.end', data);
272
+ return silent;
273
+ },
274
+ };
275
+ //# sourceMappingURL=metrics-capture.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metrics-capture.js","sourceRoot":"","sources":["../../src/hooks/metrics-capture.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAGpD,OAAO,EAAE,QAAQ,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAEtE,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAyBnD,MAAM,GAAG,GAAG,CAAC,CAAU,EAAU,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QA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,CAAC;QAC5D,IAAI,IAAI,KAAK,IAAI;YAAE,OAAO,MAAM,CAAC;QAEjC,mBAAmB,CAAC,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,UAAU,EAAE,aAAa,EAAE,IAAI,CAAC,CAAC;QACpF,OAAO,MAAM,CAAC;IAChB,CAAC;CACF,CAAC"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * secret-guard — PreToolUse on Bash | Write | Edit | MultiEdit.
3
+ *
4
+ * Scans EVERY writable field of the tool call: `command`, `content`,
5
+ * `new_string`, and `edits[].new_string` (the legacy kit's secret scanner
6
+ * missed Edit payloads entirely — that hole must never recur).
7
+ *
8
+ * Findings block with exit 2; matches are REDACTED in the block message
9
+ * (first 4 chars + length — never the secret itself). Allowlist:
10
+ * `.invictus/secretsignore` — one regex (or literal substring) per line,
11
+ * `#` comments; a candidate matching any line is suppressed.
12
+ *
13
+ * Deliberately NOT skipped: lines containing `$VAR` references — the legacy
14
+ * scanner skipped any line with an uppercase var on it, so a real key next
15
+ * to `$URL` sailed through (audit §1, defect b).
16
+ */
17
+ import type { HookModule } from '../engine.js';
18
+ export declare const secretGuard: HookModule;
19
+ //# sourceMappingURL=secret-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secret-guard.d.ts","sourceRoot":"","sources":["../../src/hooks/secret-guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAMH,OAAO,KAAK,EAAe,UAAU,EAAE,MAAM,cAAc,CAAC;AAoH5D,eAAO,MAAM,WAAW,EAAE,UA6CzB,CAAC"}