@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,83 @@
1
+ /**
2
+ * Shape of the `session.end` event payload written by the `metrics-capture`
3
+ * hook and consumed by the git-side `prepare-commit-msg` encoder.
4
+ *
5
+ * Single producer / single consumer, one schema — the trailer is DERIVED
6
+ * from these log entries, never computed twice (ARCHITECTURE §5).
7
+ * Metrics, never content: no prompt text, no file paths, no names.
8
+ */
9
+ import { z } from 'zod';
10
+ const count = z.number().int().nonnegative();
11
+ export const tokenCountsSchema = z
12
+ .object({
13
+ /** input tokens */ i: count,
14
+ /** output tokens */ o: count,
15
+ /** cache-read tokens */ cr: count,
16
+ /** cache-write (creation) tokens */ cw: count,
17
+ })
18
+ .strict();
19
+ /**
20
+ * `data` of a `session.end` event. `.passthrough()` keeps unknown fields so
21
+ * newer producers do not break older consumers (forward compatibility).
22
+ */
23
+ export const sessionEndDataSchema = z
24
+ .object({
25
+ /**
26
+ * Which hook event produced this entry. `PreCommit` is the snapshot taken
27
+ * on PreToolUse just before the agent runs `git commit`: without it a
28
+ * commit made mid-session found no snapshot yet and shipped no trailer.
29
+ */
30
+ event: z.enum(['SessionEnd', 'SubagentStop', 'PreCommit']),
31
+ /** Claude Code SessionEnd `reason` (e.g. `clear`, `logout`), if any. */
32
+ reason: z.string().max(64).optional(),
33
+ /** Token counts summed over the transcript. */
34
+ t: tokenCountsSchema,
35
+ /** Model mix, percent by short model tag (≤16 chars per tag). */
36
+ m: z.record(z.string().min(1).max(16), z.number().int().min(0).max(100)),
37
+ /** Full id of the dominant model (for the Assisted-by trailer). */
38
+ model: z.string().max(64).optional(),
39
+ /** Agent CLI at `name@version` (e.g. `claude-code@2.1.200`). */
40
+ tool: z
41
+ .string()
42
+ .max(48)
43
+ .regex(/^[A-Za-z0-9@._/-]+$/)
44
+ .optional(),
45
+ /** Estimated cost in integer cents (0 when the transcript has no costUSD). */
46
+ usdCents: count,
47
+ /** User prompts observed in the transcript. */
48
+ prompts: count,
49
+ /** Tool calls observed in the transcript. */
50
+ toolCalls: count,
51
+ /**
52
+ * Edit-tool (Write|Edit|MultiEdit|NotebookEdit) calls that completed —
53
+ * their `tool_use` got a `tool_result` that is not a denial. Optional:
54
+ * entries written by hooks ≤0.2.0 predate the field.
55
+ */
56
+ acc: count.optional(),
57
+ /**
58
+ * Edit-tool calls denied before running: `tool_result` with
59
+ * `is_error: true` carrying a user-rejection / permission-denial text
60
+ * (or a `toolDenialKind` on the transcript line), plus edits killed by
61
+ * an explicit `[Request interrupted by user for tool use]` marker.
62
+ */
63
+ rej: count.optional(),
64
+ /**
65
+ * Active seconds: sum of consecutive transcript-timestamp gaps < 5 min
66
+ * (gaps ≥ 5 min count as idle). Always ≤ durSec. Optional: entries
67
+ * written by hooks ≤0.2.0 predate the field (consumers fall back to
68
+ * durSec — the old `act = dur` behavior).
69
+ */
70
+ actSec: count.optional(),
71
+ /** Wall-clock seconds between the first and last transcript timestamps. */
72
+ durSec: count,
73
+ })
74
+ .passthrough();
75
+ /** Shorten a model id to a trailer-safe tag: strip `claude-`, date suffix, cap 16. */
76
+ export function modelTag(modelId) {
77
+ const tag = modelId
78
+ .replace(/^claude-/, '')
79
+ .replace(/-\d{8}$/, '')
80
+ .slice(0, 16);
81
+ return tag.length > 0 ? tag : 'unknown';
82
+ }
83
+ //# sourceMappingURL=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I,EAAE,CAAC;SACJ,MAAM,EAAE;SACR,GAAG,CAAC,EAAE,CAAC;SACP,KAAK,CAAC,qBAAqB,CAAC;SAC5B,QAAQ,EAAE;IACb,8EAA8E;IAC9E,QAAQ,EAAE,KAAK;IACf,+CAA+C;IAC/C,OAAO,EAAE,KAAK;IACd,6CAA6C;IAC7C,SAAS,EAAE,KAAK;IAChB;;;;OAIG;IACH,GAAG,EAAE,KAAK,CAAC,QAAQ,EAAE;IACrB;;;;;OAKG;IACH,GAAG,EAAE,KAAK,CAAC,QAAQ,EAAE;IACrB;;;;;OAKG;IACH,MAAM,EAAE,KAAK,CAAC,QAAQ,EAAE;IACxB,2EAA2E;IAC3E,MAAM,EAAE,KAAK;CACd,CAAC;KACD,WAAW,EAAE,CAAC;AAIjB,sFAAsF;AACtF,MAAM,UAAU,QAAQ,CAAC,OAAe;IACtC,MAAM,GAAG,GAAG,OAAO;SAChB,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;SACvB,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC;SACtB,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAChB,OAAO,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC;AAC1C,CAAC"}
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Shared helpers for the hook engine and hook modules.
3
+ *
4
+ * Everything here is fail-soft: helpers return null / false instead of
5
+ * throwing wherever a missing file, absent git, or unreadable manifest is a
6
+ * normal condition in a client repo (ARCHITECTURE §7: fail-open in-session).
7
+ */
8
+ import type { EventType, EventLogEntry, HookInput, Manifest } from '@invictus-group-ai/core';
9
+ /**
10
+ * True when the module at `importMetaUrl` is the process entry point.
11
+ *
12
+ * Compares REAL paths. Node resolves symlinks for the main module, so
13
+ * `import.meta.url` names the real file while `process.argv[1]` keeps the path
14
+ * the git dispatcher used — `node_modules/@invictus-group-ai/hooks/...`, which
15
+ * is a symlink under npm workspaces, pnpm and `file:` installs. The raw
16
+ * comparison never matched there, so every git hook exited 0 without running:
17
+ * the kit's own repository never wrote a single trailer.
18
+ */
19
+ export declare function isEntryModule(importMetaUrl: string): boolean;
20
+ /** `$CLAUDE_PROJECT_DIR` wins; then the hook input's `cwd`; then process.cwd(). */
21
+ export declare function resolveProjectDir(input: Pick<HookInput, 'cwd'> | null, env: NodeJS.ProcessEnv): string;
22
+ /**
23
+ * The environment with git's own variables removed, so `cwd` alone decides
24
+ * which repository a command talks to.
25
+ *
26
+ * Inside a git worktree `GIT_DIR` is ABSOLUTE, so `git -C <subdir>` inherits
27
+ * it and reports that subdirectory as its own toplevel. That is how
28
+ * `post-commit` mistook `.invictus/` for a nested state repo and committed
29
+ * the deletion of every file outside it. In a plain clone the same variable
30
+ * is the relative `.git`, which does not resolve from a subdirectory — which
31
+ * is the only reason this never fired outside a worktree.
32
+ */
33
+ export declare function gitEnv(env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
34
+ /** Run git, return trimmed stdout or null on any failure. Never throws. */
35
+ export declare function gitOutput(args: string[], cwd: string, timeoutMs?: number): string | null;
36
+ /** Read + validate `.invictus/manifest.json`, or null when missing/invalid. */
37
+ export declare function readManifestSafe(projectDir: string): Manifest | null;
38
+ export interface ResolveDevIdOptions {
39
+ /**
40
+ * When true (default), fall back to an UNSALTED id derived from the git
41
+ * email (`d_` + sha256(email)[0..8]) if no provisioned id is found. That
42
+ * fallback is acceptable for the LOCAL event log only — never let it reach
43
+ * git history (trailers), where ids must come from the salted client
44
+ * provisioning (manifest / dev.json / env).
45
+ */
46
+ allowUnsalted?: boolean;
47
+ }
48
+ /**
49
+ * Resolve the pseudonymous dev id, in priority order:
50
+ * 1. `INVICTUS_DEV_ID` env var (must match `d_xxxxxxxx`)
51
+ * 2. `.invictus/local/dev.json` → `{ "devId": "d_..." }` (installer-written)
52
+ * 3. manifest `devs[]` matched by sha256 of the local `git config user.email`
53
+ * 4. (allowUnsalted only) `d_` + first 8 hex of sha256(normalized email)
54
+ * Returns null when nothing resolves.
55
+ */
56
+ export declare function resolveDevId(projectDir: string, env: NodeJS.ProcessEnv, opts?: ResolveDevIdOptions): string | null;
57
+ /**
58
+ * Append an event to `.invictus/log/<devId>.jsonl`, resolving the dev id
59
+ * first. Returns the written entry, or null when the id cannot be resolved
60
+ * or the append fails (never throws — hooks must not die on logging).
61
+ */
62
+ export declare function appendInvictusEvent(projectDir: string, env: NodeJS.ProcessEnv, sid: string, type: EventType, data: Record<string, unknown>): EventLogEntry | null;
63
+ export declare function journalDir(projectDir: string): string;
64
+ /** Newest mtime (ms) among `.invictus/journal/*.md`, or null when none exist. */
65
+ export declare function latestJournalMtimeMs(projectDir: string): number | null;
66
+ /** Path of the newest `YYYY-MM-DD.md` daily journal file, or null. */
67
+ export declare function latestDailyJournalPath(projectDir: string): string | null;
68
+ /** First line of a file, reading at most `maxBytes`. Null when unreadable/empty. */
69
+ export declare function readFirstLine(file: string, maxBytes?: number): string | null;
70
+ /** Strip ANSI escape sequences (SessionStart context must be clean markdown). */
71
+ export declare function stripAnsi(s: string): string;
72
+ /** 8-hex short hash of an arbitrary string (session-id short hashes in trailers). */
73
+ export declare function shortHash8(s: string): string;
74
+ /**
75
+ * Walk from `startDir` up to (and including) `stopDir` looking for `name`.
76
+ * Returns the absolute path of the first hit, or null.
77
+ */
78
+ export declare function findUp(name: string, startDir: string, stopDir: string): string | null;
79
+ /** mkdir -p that never throws. Returns true on success. */
80
+ export declare function ensureDir(dir: string): boolean;
81
+ //# sourceMappingURL=shared.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAwBH,OAAO,KAAK,EAAE,SAAS,EAAE,aAAa,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AAE7F;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,aAAa,EAAE,MAAM,GAAG,OAA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;AAMD,oFAAoF;AACpF,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,SAAY,GAAG,MAAM,GAAG,IAAI,CAkB/E;AAID,iFAAiF;AACjF,wBAAgB,SAAS,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAE3C;AAED,qFAAqF;AACrF,wBAAgB,UAAU,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAE5C;AAED;;;GAGG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAWrF;AAED,2DAA2D;AAC3D,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAO9C"}
package/dist/shared.js ADDED
@@ -0,0 +1,276 @@
1
+ /**
2
+ * Shared helpers for the hook engine and hook modules.
3
+ *
4
+ * Everything here is fail-soft: helpers return null / false instead of
5
+ * throwing wherever a missing file, absent git, or unreadable manifest is a
6
+ * normal condition in a client repo (ARCHITECTURE §7: fail-open in-session).
7
+ */
8
+ import { execFileSync } from 'node:child_process';
9
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, statSync, } from 'node:fs';
10
+ import { dirname, join, resolve } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { appendEvent, defaultLogDir, hashGitEmail, isDevId, readManifest, sha256Hex, } from '@invictus-group-ai/core';
13
+ /**
14
+ * True when the module at `importMetaUrl` is the process entry point.
15
+ *
16
+ * Compares REAL paths. Node resolves symlinks for the main module, so
17
+ * `import.meta.url` names the real file while `process.argv[1]` keeps the path
18
+ * the git dispatcher used — `node_modules/@invictus-group-ai/hooks/...`, which
19
+ * is a symlink under npm workspaces, pnpm and `file:` installs. The raw
20
+ * comparison never matched there, so every git hook exited 0 without running:
21
+ * the kit's own repository never wrote a single trailer.
22
+ */
23
+ export function isEntryModule(importMetaUrl) {
24
+ const entry = process.argv[1];
25
+ if (typeof entry !== 'string' || entry === '')
26
+ return false;
27
+ try {
28
+ return realpathSync(fileURLToPath(importMetaUrl)) === realpathSync(resolve(entry));
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ }
34
+ // ---------------------------------------------------------------------------
35
+ // Project / environment resolution
36
+ // ---------------------------------------------------------------------------
37
+ /** `$CLAUDE_PROJECT_DIR` wins; then the hook input's `cwd`; then process.cwd(). */
38
+ export function resolveProjectDir(input, env) {
39
+ const fromEnv = env.CLAUDE_PROJECT_DIR;
40
+ if (typeof fromEnv === 'string' && fromEnv.length > 0)
41
+ return fromEnv;
42
+ if (input && typeof input.cwd === 'string' && input.cwd.length > 0)
43
+ return input.cwd;
44
+ return process.cwd();
45
+ }
46
+ /**
47
+ * Variables git exports to every hook, naming the repository it is working
48
+ * on. A hook that then runs `git` in a DIFFERENT directory inherits them and
49
+ * silently operates on the original repository — or, worse, treats the new
50
+ * directory as a work tree of it.
51
+ */
52
+ const GIT_ENV_VARS = [
53
+ 'GIT_DIR',
54
+ 'GIT_WORK_TREE',
55
+ 'GIT_COMMON_DIR',
56
+ 'GIT_INDEX_FILE',
57
+ 'GIT_PREFIX',
58
+ 'GIT_OBJECT_DIRECTORY',
59
+ 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
60
+ ];
61
+ /**
62
+ * The environment with git's own variables removed, so `cwd` alone decides
63
+ * which repository a command talks to.
64
+ *
65
+ * Inside a git worktree `GIT_DIR` is ABSOLUTE, so `git -C <subdir>` inherits
66
+ * it and reports that subdirectory as its own toplevel. That is how
67
+ * `post-commit` mistook `.invictus/` for a nested state repo and committed
68
+ * the deletion of every file outside it. In a plain clone the same variable
69
+ * is the relative `.git`, which does not resolve from a subdirectory — which
70
+ * is the only reason this never fired outside a worktree.
71
+ */
72
+ export function gitEnv(env = process.env) {
73
+ const clean = { ...env };
74
+ for (const key of GIT_ENV_VARS)
75
+ delete clean[key];
76
+ return clean;
77
+ }
78
+ /** Run git, return trimmed stdout or null on any failure. Never throws. */
79
+ export function gitOutput(args, cwd, timeoutMs = 4000) {
80
+ try {
81
+ return execFileSync('git', args, {
82
+ cwd,
83
+ env: gitEnv(),
84
+ encoding: 'utf8',
85
+ timeout: timeoutMs,
86
+ stdio: ['ignore', 'pipe', 'ignore'],
87
+ maxBuffer: 1024 * 1024,
88
+ }).trim();
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ }
94
+ /** Read + validate `.invictus/manifest.json`, or null when missing/invalid. */
95
+ export function readManifestSafe(projectDir) {
96
+ try {
97
+ return readManifest(projectDir);
98
+ }
99
+ catch {
100
+ return null;
101
+ }
102
+ }
103
+ /**
104
+ * Resolve the pseudonymous dev id, in priority order:
105
+ * 1. `INVICTUS_DEV_ID` env var (must match `d_xxxxxxxx`)
106
+ * 2. `.invictus/local/dev.json` → `{ "devId": "d_..." }` (installer-written)
107
+ * 3. manifest `devs[]` matched by sha256 of the local `git config user.email`
108
+ * 4. (allowUnsalted only) `d_` + first 8 hex of sha256(normalized email)
109
+ * Returns null when nothing resolves.
110
+ */
111
+ export function resolveDevId(projectDir, env, opts = {}) {
112
+ const { allowUnsalted = true } = opts;
113
+ const fromEnv = env.INVICTUS_DEV_ID;
114
+ if (typeof fromEnv === 'string' && isDevId(fromEnv))
115
+ return fromEnv;
116
+ try {
117
+ const raw = readFileSync(join(projectDir, '.invictus', 'local', 'dev.json'), 'utf8');
118
+ const parsed = JSON.parse(raw);
119
+ if (typeof parsed.devId === 'string' && isDevId(parsed.devId))
120
+ return parsed.devId;
121
+ }
122
+ catch {
123
+ /* absent or malformed — keep resolving */
124
+ }
125
+ const email = gitOutput(['config', 'user.email'], projectDir);
126
+ if (!email)
127
+ return null;
128
+ let emailHash;
129
+ try {
130
+ emailHash = hashGitEmail(email);
131
+ }
132
+ catch {
133
+ return null;
134
+ }
135
+ const manifest = readManifestSafe(projectDir);
136
+ const match = manifest?.devs.find((d) => d.gitEmailHash === emailHash);
137
+ if (match)
138
+ return match.id;
139
+ if (allowUnsalted)
140
+ return `d_${emailHash.slice(0, 8)}`;
141
+ return null;
142
+ }
143
+ // ---------------------------------------------------------------------------
144
+ // Event log convenience
145
+ // ---------------------------------------------------------------------------
146
+ /**
147
+ * Append an event to `.invictus/log/<devId>.jsonl`, resolving the dev id
148
+ * first. Returns the written entry, or null when the id cannot be resolved
149
+ * or the append fails (never throws — hooks must not die on logging).
150
+ */
151
+ export function appendInvictusEvent(projectDir, env, sid, type, data) {
152
+ try {
153
+ const devId = resolveDevId(projectDir, env);
154
+ if (!devId)
155
+ return null;
156
+ return appendEvent(defaultLogDir(projectDir), devId, {
157
+ sid: sid.slice(0, 64) || 'unknown',
158
+ type,
159
+ data,
160
+ });
161
+ }
162
+ catch {
163
+ return null;
164
+ }
165
+ }
166
+ // ---------------------------------------------------------------------------
167
+ // Journal paths (§2 layout: .invictus/journal/)
168
+ // ---------------------------------------------------------------------------
169
+ export function journalDir(projectDir) {
170
+ return join(projectDir, '.invictus', 'journal');
171
+ }
172
+ /** Newest mtime (ms) among `.invictus/journal/*.md`, or null when none exist. */
173
+ export function latestJournalMtimeMs(projectDir) {
174
+ const dir = journalDir(projectDir);
175
+ let newest = null;
176
+ let entries;
177
+ try {
178
+ entries = readdirSync(dir);
179
+ }
180
+ catch {
181
+ return null;
182
+ }
183
+ for (const name of entries) {
184
+ if (!name.endsWith('.md'))
185
+ continue;
186
+ try {
187
+ const st = statSync(join(dir, name));
188
+ if (st.isFile() && (newest === null || st.mtimeMs > newest))
189
+ newest = st.mtimeMs;
190
+ }
191
+ catch {
192
+ /* raced deletion — ignore */
193
+ }
194
+ }
195
+ return newest;
196
+ }
197
+ /** Path of the newest `YYYY-MM-DD.md` daily journal file, or null. */
198
+ export function latestDailyJournalPath(projectDir) {
199
+ const dir = journalDir(projectDir);
200
+ let names;
201
+ try {
202
+ names = readdirSync(dir).filter((n) => /^\d{4}-\d{2}-\d{2}\.md$/.test(n));
203
+ }
204
+ catch {
205
+ return null;
206
+ }
207
+ if (names.length === 0)
208
+ return null;
209
+ names.sort(); // ISO dates sort lexicographically
210
+ return join(dir, names[names.length - 1]);
211
+ }
212
+ // ---------------------------------------------------------------------------
213
+ // Small file / text utilities
214
+ // ---------------------------------------------------------------------------
215
+ /** First line of a file, reading at most `maxBytes`. Null when unreadable/empty. */
216
+ export function readFirstLine(file, maxBytes = 64 * 1024) {
217
+ let fd;
218
+ try {
219
+ fd = openSync(file, 'r');
220
+ }
221
+ catch {
222
+ return null;
223
+ }
224
+ try {
225
+ const buf = Buffer.alloc(maxBytes);
226
+ const n = readSync(fd, buf, 0, maxBytes, 0);
227
+ const text = buf.subarray(0, n).toString('utf8');
228
+ const line = text.split('\n').find((l) => l.trim() !== '');
229
+ return line ?? null;
230
+ }
231
+ catch {
232
+ return null;
233
+ }
234
+ finally {
235
+ closeSync(fd);
236
+ }
237
+ }
238
+ const ANSI_RE = new RegExp(String.raw `\x1b\[[0-9;?]*[ -/]*[@-~]`, 'g');
239
+ /** Strip ANSI escape sequences (SessionStart context must be clean markdown). */
240
+ export function stripAnsi(s) {
241
+ return s.replace(ANSI_RE, '');
242
+ }
243
+ /** 8-hex short hash of an arbitrary string (session-id short hashes in trailers). */
244
+ export function shortHash8(s) {
245
+ return sha256Hex(s).slice(0, 8);
246
+ }
247
+ /**
248
+ * Walk from `startDir` up to (and including) `stopDir` looking for `name`.
249
+ * Returns the absolute path of the first hit, or null.
250
+ */
251
+ export function findUp(name, startDir, stopDir) {
252
+ let dir = startDir;
253
+ for (let i = 0; i < 64; i++) {
254
+ const candidate = join(dir, name);
255
+ if (existsSync(candidate))
256
+ return candidate;
257
+ if (dir === stopDir)
258
+ return null;
259
+ const parent = dirname(dir);
260
+ if (parent === dir)
261
+ return null; // filesystem root
262
+ dir = parent;
263
+ }
264
+ return null;
265
+ }
266
+ /** mkdir -p that never throws. Returns true on success. */
267
+ export function ensureDir(dir) {
268
+ try {
269
+ mkdirSync(dir, { recursive: true });
270
+ return true;
271
+ }
272
+ catch {
273
+ return false;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,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAClC,IAAI,UAAU,CAAC,SAAS,CAAC;YAAE,OAAO,SAAS,CAAC;QAC5C,IAAI,GAAG,KAAK,OAAO;YAAE,OAAO,IAAI,CAAC;QACjC,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;QAC5B,IAAI,MAAM,KAAK,GAAG;YAAE,OAAO,IAAI,CAAC,CAAC,kBAAkB;QACnD,GAAG,GAAG,MAAM,CAAC;IACf,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,2DAA2D;AAC3D,MAAM,UAAU,SAAS,CAAC,GAAW;IACnC,IAAI,CAAC;QACH,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACpC,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC"}
@@ -0,0 +1,30 @@
1
+ #!/bin/sh
2
+ # Invictus commit-metrics-encoder shim (POSIX sh).
3
+ #
4
+ # Invokes the Node implementation of the prepare-commit-msg hook. Resolution
5
+ # order for the script:
6
+ # 1. $INVICTUS_HOOKS_DIST/git/prepare-commit-msg.js (explicit override)
7
+ # 2. <this dir>/../dist/git/prepare-commit-msg.js (package-local layout)
8
+ # 3. <this dir>/invictus/prepare-commit-msg.js (installed .githooks/ layout)
9
+ #
10
+ # ALWAYS fails open: a missing Node runtime or script must never block a
11
+ # commit — an absent trailer is a signal (untracked commit), not an error.
12
+ # Set INVICTUS_SKIP_TRAILER=1 to skip explicitly.
13
+
14
+ [ -n "$INVICTUS_SKIP_TRAILER" ] && exit 0
15
+ command -v node >/dev/null 2>&1 || exit 0
16
+
17
+ dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) || exit 0
18
+
19
+ if [ -n "$INVICTUS_HOOKS_DIST" ] && [ -f "$INVICTUS_HOOKS_DIST/git/prepare-commit-msg.js" ]; then
20
+ script="$INVICTUS_HOOKS_DIST/git/prepare-commit-msg.js"
21
+ elif [ -f "$dir/../dist/git/prepare-commit-msg.js" ]; then
22
+ script="$dir/../dist/git/prepare-commit-msg.js"
23
+ elif [ -f "$dir/invictus/prepare-commit-msg.js" ]; then
24
+ script="$dir/invictus/prepare-commit-msg.js"
25
+ else
26
+ exit 0
27
+ fi
28
+
29
+ node "$script" "$@" || exit 0
30
+ exit 0
@@ -0,0 +1,16 @@
1
+ @echo off
2
+ rem Invictus commit-metrics-encoder shim (Windows cmd).
3
+ rem Mirrors the POSIX shim: resolve the Node implementation, always fail open.
4
+
5
+ if defined INVICTUS_SKIP_TRAILER exit /b 0
6
+ where node >nul 2>nul
7
+ if errorlevel 1 exit /b 0
8
+
9
+ set "SCRIPT="
10
+ if defined INVICTUS_HOOKS_DIST if exist "%INVICTUS_HOOKS_DIST%\git\prepare-commit-msg.js" set "SCRIPT=%INVICTUS_HOOKS_DIST%\git\prepare-commit-msg.js"
11
+ if not defined SCRIPT if exist "%~dp0..\dist\git\prepare-commit-msg.js" set "SCRIPT=%~dp0..\dist\git\prepare-commit-msg.js"
12
+ if not defined SCRIPT if exist "%~dp0invictus\prepare-commit-msg.js" set "SCRIPT=%~dp0invictus\prepare-commit-msg.js"
13
+ if not defined SCRIPT exit /b 0
14
+
15
+ node "%SCRIPT%" %*
16
+ exit /b 0
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@invictus-group-ai/hooks",
3
+ "version": "0.5.0",
4
+ "description": "Invictus AI hook engine: the hook set for Claude Code events plus the git-side commit-metrics encoder. Fail-open in-session; the fail-closed net is .githooks/ + CI.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/invictus-group-ai/invictus-orchestra.git",
9
+ "directory": "packages/hooks"
10
+ },
11
+ "homepage": "https://github.com/invictus-group-ai/invictus-orchestra/tree/main/packages/hooks#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/invictus-group-ai/invictus-orchestra/issues"
14
+ },
15
+ "keywords": [
16
+ "invictus",
17
+ "claude-code",
18
+ "hooks",
19
+ "git-hooks",
20
+ "commit-trailer"
21
+ ],
22
+ "type": "module",
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "bin": {
27
+ "invictus-hook": "./dist/bin.js"
28
+ },
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "default": "./dist/index.js"
33
+ },
34
+ "./engine": {
35
+ "types": "./dist/engine.d.ts",
36
+ "default": "./dist/engine.js"
37
+ },
38
+ "./git/prepare-commit-msg": {
39
+ "types": "./dist/git/prepare-commit-msg.d.ts",
40
+ "default": "./dist/git/prepare-commit-msg.js"
41
+ },
42
+ "./settings-template.json": "./settings-template.json"
43
+ },
44
+ "files": [
45
+ "dist",
46
+ "githooks",
47
+ "settings-template.json",
48
+ "README.md"
49
+ ],
50
+ "sideEffects": false,
51
+ "publishConfig": {
52
+ "access": "public",
53
+ "provenance": true
54
+ },
55
+ "scripts": {
56
+ "build": "tsc -p tsconfig.json",
57
+ "typecheck": "tsc --noEmit -p tsconfig.json",
58
+ "prepack": "npm run build",
59
+ "pretest": "npm run build",
60
+ "test": "vitest run"
61
+ },
62
+ "dependencies": {
63
+ "@invictus-group-ai/core": "^0.5.0",
64
+ "zod": "^3.24.1"
65
+ },
66
+ "devDependencies": {
67
+ "@types/node": "^22.10.0",
68
+ "typescript": "^5.7.2",
69
+ "vitest": "^3.0.0"
70
+ }
71
+ }