@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.
- package/LICENSE +21 -0
- package/README.md +130 -0
- package/dist/bin.d.ts +11 -0
- package/dist/bin.d.ts.map +1 -0
- package/dist/bin.js +37 -0
- package/dist/bin.js.map +1 -0
- package/dist/engine.d.ts +53 -0
- package/dist/engine.d.ts.map +1 -0
- package/dist/engine.js +182 -0
- package/dist/engine.js.map +1 -0
- package/dist/git/post-commit.d.ts +43 -0
- package/dist/git/post-commit.d.ts.map +1 -0
- package/dist/git/post-commit.js +166 -0
- package/dist/git/post-commit.js.map +1 -0
- package/dist/git/pre-push.d.ts +43 -0
- package/dist/git/pre-push.d.ts.map +1 -0
- package/dist/git/pre-push.js +102 -0
- package/dist/git/pre-push.js.map +1 -0
- package/dist/git/prepare-commit-msg.d.ts +97 -0
- package/dist/git/prepare-commit-msg.d.ts.map +1 -0
- package/dist/git/prepare-commit-msg.js +623 -0
- package/dist/git/prepare-commit-msg.js.map +1 -0
- package/dist/git-activate.d.ts +25 -0
- package/dist/git-activate.d.ts.map +1 -0
- package/dist/git-activate.js +75 -0
- package/dist/git-activate.js.map +1 -0
- package/dist/hooks/db-guard.d.ts +31 -0
- package/dist/hooks/db-guard.d.ts.map +1 -0
- package/dist/hooks/db-guard.js +290 -0
- package/dist/hooks/db-guard.js.map +1 -0
- package/dist/hooks/index.d.ts +16 -0
- package/dist/hooks/index.d.ts.map +1 -0
- package/dist/hooks/index.js +24 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/hooks/journal-nudge.d.ts +14 -0
- package/dist/hooks/journal-nudge.d.ts.map +1 -0
- package/dist/hooks/journal-nudge.js +60 -0
- package/dist/hooks/journal-nudge.js.map +1 -0
- package/dist/hooks/loc-recorder.d.ts +79 -0
- package/dist/hooks/loc-recorder.d.ts.map +1 -0
- package/dist/hooks/loc-recorder.js +183 -0
- package/dist/hooks/loc-recorder.js.map +1 -0
- package/dist/hooks/metrics-capture.d.ts +34 -0
- package/dist/hooks/metrics-capture.d.ts.map +1 -0
- package/dist/hooks/metrics-capture.js +275 -0
- package/dist/hooks/metrics-capture.js.map +1 -0
- package/dist/hooks/secret-guard.d.ts +19 -0
- package/dist/hooks/secret-guard.d.ts.map +1 -0
- package/dist/hooks/secret-guard.js +163 -0
- package/dist/hooks/secret-guard.js.map +1 -0
- package/dist/hooks/session-boot.d.ts +17 -0
- package/dist/hooks/session-boot.d.ts.map +1 -0
- package/dist/hooks/session-boot.js +123 -0
- package/dist/hooks/session-boot.js.map +1 -0
- package/dist/hooks/stop-gate.d.ts +17 -0
- package/dist/hooks/stop-gate.d.ts.map +1 -0
- package/dist/hooks/stop-gate.js +97 -0
- package/dist/hooks/stop-gate.js.map +1 -0
- package/dist/hooks/typecheck-on-edit.d.ts +18 -0
- package/dist/hooks/typecheck-on-edit.d.ts.map +1 -0
- package/dist/hooks/typecheck-on-edit.js +110 -0
- package/dist/hooks/typecheck-on-edit.js.map +1 -0
- package/dist/i18n/en.d.ts +45 -0
- package/dist/i18n/en.d.ts.map +1 -0
- package/dist/i18n/en.js +53 -0
- package/dist/i18n/en.js.map +1 -0
- package/dist/i18n/index.d.ts +35 -0
- package/dist/i18n/index.d.ts.map +1 -0
- package/dist/i18n/index.js +56 -0
- package/dist/i18n/index.js.map +1 -0
- package/dist/i18n/pt-BR.d.ts +12 -0
- package/dist/i18n/pt-BR.d.ts.map +1 -0
- package/dist/i18n/pt-BR.js +50 -0
- package/dist/i18n/pt-BR.js.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -0
- package/dist/kit-cli.d.ts +36 -0
- package/dist/kit-cli.d.ts.map +1 -0
- package/dist/kit-cli.js +68 -0
- package/dist/kit-cli.js.map +1 -0
- package/dist/metrics-schema.d.ts +215 -0
- package/dist/metrics-schema.d.ts.map +1 -0
- package/dist/metrics-schema.js +83 -0
- package/dist/metrics-schema.js.map +1 -0
- package/dist/shared.d.ts +81 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +276 -0
- package/dist/shared.js.map +1 -0
- package/githooks/prepare-commit-msg +30 -0
- package/githooks/prepare-commit-msg.cmd +16 -0
- package/package.json +71 -0
- package/settings-template.json +97 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Invictus AI (invictusai.com.br)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# @invictus-group-ai/hooks
|
|
2
|
+
|
|
3
|
+
> **Installing the kit?** This package is the engine, not the entry point. Install it together with the CLI in the root of your repository — `npm install -D @invictus-group-ai/orchestra @invictus-group-ai/hooks`, then `npx invi init`, which registers every hook for you. Start at [`@invictus-group-ai/orchestra`](https://www.npmjs.com/package/@invictus-group-ai/orchestra). Node ≥ 20 and git required.
|
|
4
|
+
|
|
5
|
+
The Invictus hook engine: **8 Claude Code hooks + 1 git-side hook** (the hook set of ARCHITECTURE §7). One Node runtime, one thin bin, every hook a module `(input, ctx) => HookOutput`, every hook fixture-tested with both allow and block paths.
|
|
6
|
+
|
|
7
|
+
Design rules (each one is a shipped bug in the legacy kit that must not recur):
|
|
8
|
+
|
|
9
|
+
- `Stop` fires **every assistant turn** — only `stop-gate` uses it, and it short-circuits on `stop_hook_active` before anything else.
|
|
10
|
+
- Session metrics live on `SessionEnd` (+ `SubagentStop`), never on `Stop`.
|
|
11
|
+
- Context injection goes to **stdout** (SessionStart, clean markdown, no ANSI). Blocking reasons go to **stderr + exit 2**. Agent-visible advice on PostToolUse goes through JSON `additionalContext` — the only channel the model actually sees there.
|
|
12
|
+
- Secret scanning covers `command`, `content`, `new_string`, **and `edits[].new_string`**.
|
|
13
|
+
- `db-guard` triggers only on DB-client/migration binaries + write keywords — never on `git`/`grep`/`cat`/`echo`, never on files written under `db/migrations/`.
|
|
14
|
+
- **Fail-open in-session**: any internal engine error (unknown hook, bad stdin, hook exception, hard timeout) is appended to the event log and the engine exits 0. The fail-closed net is `.githooks/` + CI.
|
|
15
|
+
|
|
16
|
+
## Dispatch
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
echo '<hook JSON>' | invictus-hook <hook-name> [<hook-name>…]
|
|
20
|
+
# equivalently:
|
|
21
|
+
node dist/bin.js <hook-name> [<hook-name>…]
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
The engine reads the hook JSON from stdin **once**, validates it (zod, via `@invictus-group-ai/core`), dispatches every named module **in this one process** (multi-module dispatch: one registration, one spawn, N modules — how `typecheck-on-edit loc-recorder` share the single PostToolUse edit registration), enforces a per-hook **hard internal timeout**, and renders each module's `HookOutput`:
|
|
25
|
+
|
|
26
|
+
| Module returns | Engine emits |
|
|
27
|
+
|---|---|
|
|
28
|
+
| `{ mode: 'exit', exitCode, stdout?, stderr? }` | streams as-is + that exit code |
|
|
29
|
+
| `{ mode: 'json', json }` | `JSON.stringify(json)` on stdout, exit 0 |
|
|
30
|
+
|
|
31
|
+
Multi-module merge (deterministic, argv order): any block (exit 2) wins, then any warn (exit 1) — streams of exit-mode outputs joined; else a single JSON output on stdout (first JSON as base, `additionalContext` concatenated across JSON outputs); else exit 0 with the stdouts joined (multi-module context injection). A broken module fails open **individually** — its siblings still run.
|
|
32
|
+
|
|
33
|
+
Internal errors are recorded as a first-class `hook.error` event in `.invictus/log/<devId>.jsonl` (core >=0.2.0; entries written by kit <=0.1.x used `gate` + `data.kind: 'hook.error'` and remain valid), then exit 0.
|
|
34
|
+
|
|
35
|
+
## The hooks
|
|
36
|
+
|
|
37
|
+
| Hook | Event(s) | Mode | What it does |
|
|
38
|
+
|---|---|---|---|
|
|
39
|
+
| `secret-guard` | PreToolUse: `Bash\|Write\|Edit\|MultiEdit` | block (exit 2) | Scans `command`, `content`, `new_string`, `edits[].new_string` against 12 secret patterns (Anthropic/OpenAI/AWS/GitHub/Slack/Stripe/Google keys, private-key blocks, JWTs, generic credential assignments). Matches are redacted in the block message. Allowlist: `.invictus/secretsignore` (one regex or literal per line, `#` comments). Writing to `.env*` files is allowed — that IS the taught workflow. Env-var references (`$KEY`, `${KEY}`) and masked placeholders never trigger. |
|
|
40
|
+
| `db-guard` | PreToolUse: `Bash` | block (exit 2) | Quote-aware command parsing; blocks only when a segment invokes a DB binary (`psql mysql mariadb sqlite3 mongosh mongo redis-cli prisma alembic supabase drizzle-kit flyway liquibase rails/rake db:* manage.py`) through any wrapper (`sudo`, `npx`, `pnpm exec`, `bundle exec`, `python`, env prefixes) AND carries a write keyword for that dialect. Read-only use (`SELECT`, `EXPLAIN`, `migrate status`, `db:migrate:status`, `makemigrations`) passes. The block message teaches the `db/migrations/<ts>_<desc>.sql` UP/DOWN workflow. |
|
|
41
|
+
| `typecheck-on-edit` | PostToolUse: `Write\|Edit\|MultiEdit` (`.ts/.tsx/.mts/.cts`, not `.d.ts`) | warn (exit 2) | Project-scoped `tsc --noEmit -p <nearest tsconfig.json>` — never file-arg tsc. Off unless the manifest lists `typecheck-on-edit` in `hooks[]` (per-stack toggle at init); `INVICTUS_TYPECHECK=1/0` forces/kills. Missing tsconfig/tsc or tsc timeout ⇒ silent exit 0. Errors mentioning the edited file are shown first, capped at 30 lines. |
|
|
42
|
+
| `session-boot` | SessionStart | context (stdout) | ≤60 lines of clean markdown, no ANSI: `MEMORY.md` head + latest `.invictus/journal/YYYY-MM-DD.md` head + git summary (branch, working-tree counts, last 5 commits) + open `- [ ]` TODOs from CLAUDE.md and the latest journal. |
|
|
43
|
+
| `metrics-capture` | SessionEnd + SubagentStop | silent | Parses the transcript JSONL (`usage` blocks, tool_use counts, prompts, timestamps, `costUSD` when present) and appends one `session.end` event via `@invictus-group-ai/core` — including edit-tool **accept/reject** counts and **active seconds** derived from the transcript (see "Metrics fidelity" below). No output ever. Metrics, never content. |
|
|
44
|
+
| `loc-recorder` | PostToolUse: `Write\|Edit\|MultiEdit\|NotebookEdit` (same registration and process as typecheck-on-edit) | silent | Appends `{ts, f, la, ld, sid}` (repo-relative file + added/removed line counts derived from the tool_input) to the local scratch `.invictus/metrics/agent-loc.jsonl` for every agent edit. The commit encoder sums the counts per file and attributes `min(recorded, staged numstat)` as assisted LoC, the remainder as human. Paths stay in the local scratch only — never in the event log or trailer. |
|
|
45
|
+
| `journal-nudge` | PostToolUse: `Bash` matching `git … commit` (non-amend, non-fixup) | JSON `additionalContext` | If no `.invictus/journal/*.md` was touched in the last 5 minutes, injects an instruction to run the `invi-journal` skill. Silent otherwise. |
|
|
46
|
+
| `stop-gate` | Stop | block ONCE (exit 2) | (1) `stop_hook_active` ⇒ exit 0, first check, always. (2) Single gate: commits made this session (last commit ≥ first transcript timestamp) with no journal entry since the last commit ⇒ block once with the reason on stderr; a marker under `.invictus/local/stop-gate/` guarantees "once per session". Anything unreadable ⇒ exit 0. |
|
|
47
|
+
| `commit-metrics-encoder` | git `prepare-commit-msg` | silent | See below. Works on every CLI, not only Claude Code. |
|
|
48
|
+
|
|
49
|
+
## Git-side: `githooks/prepare-commit-msg`
|
|
50
|
+
|
|
51
|
+
Portable shims (`prepare-commit-msg` POSIX sh + `prepare-commit-msg.cmd` Windows) invoke `node dist/git/prepare-commit-msg.js`. The implementation:
|
|
52
|
+
|
|
53
|
+
1. Skips merge/squash/amend sources, `fixup!`/`squash!` messages, and messages that already carry `Assisted-by:`/`Invictus:` trailers.
|
|
54
|
+
2. Reads the HMAC key from `.invictus/local/dev.key` (git-ignored; hex or utf-8). **Absent key ⇒ skip silently** — an absent trailer is a signal (untracked commit), never an error.
|
|
55
|
+
3. Aggregates `session.end` events from `.invictus/log/<devId>.jsonl` **since the last `task.commit` entry** (SubagentStop entries are attribution detail and are not double-counted): tokens, cost, prompts, tool calls, `acc`/`rej` (edit-tool accepts/rejects) and `act` (active seconds, capped at wall clock).
|
|
56
|
+
4. Splits `git diff --cached --numstat` into `loc.aa/ad` vs `loc.ha/hd`: per staged file, `min(lines recorded by loc-recorder, staged numstat lines)` counts as assisted and the remainder as human (renamed files carry the attribution recorded under their pre-rename path), then consumes the scratch entries for staged files (entries for not-yet-staged files stay for a later commit; entries older than 14 days are pruned).
|
|
57
|
+
5. Appends one `task.commit` summary event; the trailer payload is derived from it (`j` = its hash — single source, ARCHITECTURE §5). `prev` chains to the previous trailer's payload hash via `.invictus/metrics/last-trailer.json`.
|
|
58
|
+
6. Encodes with the core codec and appends, before git's comment block:
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
Assisted-by: <dominant model> via Invictus Kit
|
|
62
|
+
Invictus: v1.<base64url(deflateRaw(cbor(payload)))>.<hmac-sha256-trunc16>
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Only a **provisioned** dev id (env `INVICTUS_DEV_ID`, `.invictus/local/dev.json`, or a manifest `devs[]` email-hash match) may reach git history; the unsalted local fallback id is used for the local log only. Every path in this hook fails open — it can never break `git commit`. `INVICTUS_SKIP_TRAILER=1` skips explicitly.
|
|
66
|
+
|
|
67
|
+
## Language (D-003)
|
|
68
|
+
|
|
69
|
+
Block/warn messages and injected context (secret-guard, db-guard, typecheck-on-edit header/footer, stop-gate, journal-nudge `additionalContext`, session-boot headers) render from a message catalog (`src/i18n/`, same pattern as the kit's): EN canonical, resolved from the client repo's `manifest.language.render`, **falling back to pt-BR** when the manifest is absent (`INVICTUS_LANG` overrides, for tests/debugging). The content the agent must obey — the `db/migrations/…` path, `-- UP`/`-- DOWN` sections, the `invi-journal` skill name, the `$VAR` guidance — is identical in meaning across languages (translated, never paraphrased) and byte-identical for machine tokens. Diagnostics stay EN: db-guard's per-segment reasons (binary + keyword), raw tsc output lines, engine `hook.error` log entries. Missing-translation safety is compile-time (`MessageKey = keyof typeof en`; pt-BR is declared `Record<MessageKey, string>`, so `tsc` fails on drift); per-hook message assertions run in both languages (`test/i18n.test.ts`).
|
|
70
|
+
|
|
71
|
+
## Registration
|
|
72
|
+
|
|
73
|
+
`settings-template.json` is the block the installer JSON-merges into `.claude/settings.json` (never clobbering existing hooks): `$CLAUDE_PROJECT_DIR`-anchored commands, exact matchers, and a `timeout` (seconds) per hook. The engine additionally enforces its own internal timeout (ms; override with `INVICTUS_HOOK_TIMEOUT_MS`).
|
|
74
|
+
|
|
75
|
+
## Files this package reads/writes in a client repo
|
|
76
|
+
|
|
77
|
+
| Path | Role |
|
|
78
|
+
|---|---|
|
|
79
|
+
| `.invictus/log/<devId>.jsonl` | append-only event log (source of truth) |
|
|
80
|
+
| `.invictus/journal/*.md` | journal read by session-boot / freshness checks |
|
|
81
|
+
| `.invictus/secretsignore` | secret-guard allowlist |
|
|
82
|
+
| `.invictus/manifest.json` | hook toggles (`hooks[]`), dev id mapping |
|
|
83
|
+
| `.invictus/local/dev.key`, `dev.json` | per-dev HMAC key + id (git-ignored) |
|
|
84
|
+
| `.invictus/local/stop-gate/` | stop-gate once-per-session markers (git-ignored) |
|
|
85
|
+
| `.invictus/metrics/last-trailer.json` | trailer hash chain scratch |
|
|
86
|
+
| `.invictus/metrics/agent-loc.jsonl` | loc-recorder scratch: per-edit agent line counts per file, consumed per commit |
|
|
87
|
+
|
|
88
|
+
## Metrics fidelity — how acc/rej, act, and the LoC split are derived
|
|
89
|
+
|
|
90
|
+
### `acc`/`rej` (edit-tool accepts/rejects)
|
|
91
|
+
|
|
92
|
+
Derived by `metrics-capture` at SessionEnd from the transcript JSONL — one pass, no per-tool-call process spawns. What we established by reading real transcripts under `~/.claude/projects/` (156 files, CLI 2.0–2.1, 3454 `tool_use` / 3453 `tool_result` blocks):
|
|
93
|
+
|
|
94
|
+
- **A denied tool call still gets a `tool_result`**, matched by `tool_use_id`, with `is_error: true` and one of two stable texts: `"The user doesn't want to proceed with this tool use."` (explicit user rejection) or `"Permission for this action was denied by the Claude Code auto mode classifier."` (policy denial).
|
|
95
|
+
- Newer CLIs additionally stamp **`toolDenialKind`** (`"user-rejected"` | `"automode-blocked"`) on the transcript line — but only a minority of observed denials carried it (1 of 4 user rejections), so the **text is the load-bearing signal** and the field is honored as a bonus.
|
|
96
|
+
- A user ESC during a running tool appears as a user text line `"[Request interrupted by user for tool use]"`; the in-flight `tool_use` gets no `tool_result` — counted as rejected.
|
|
97
|
+
- Ordinary tool **failures** (`Exit code 1`, `<tool_use_error>File has not been read yet…`) also carry `is_error: true` but none of the denial texts: the tool RAN, so the decision was an accept — failures never count as rejections.
|
|
98
|
+
|
|
99
|
+
Per the trailer spec (observability.md §3) only **edit tools** (`Write|Edit|MultiEdit|NotebookEdit`) feed `acc`/`rej`. Documented approximations: an edit still pending at transcript end without an interrupt marker gets no verdict (neither `acc` nor `rej`); denial texts are the CLI's EN literals — a future CLI localizing them would degrade rejections to that no-verdict bucket (the `toolDenialKind` field then picks them up).
|
|
100
|
+
|
|
101
|
+
### `act` (active seconds)
|
|
102
|
+
|
|
103
|
+
From transcript timestamps at SessionEnd: sort all line timestamps, sum consecutive gaps `< 5 min`; gaps ≥ 5 min count as idle. Always ≤ `dur` (wall clock, first→last timestamp); the encoder additionally caps the accumulated `act` at `dur`. The 5-minute idle threshold is the usual git-hours-style heuristic — a documented approximation, not a measurement of attention. `session.end` entries written by hooks ≤0.2.0 have no `actSec`; the encoder falls back to `durSec` for those (the old `act = dur` behavior).
|
|
104
|
+
|
|
105
|
+
### `loc.aa/ad` vs `loc.ha/hd` (assisted vs human lines)
|
|
106
|
+
|
|
107
|
+
`loc-recorder` (silent, same PostToolUse process as typecheck-on-edit) records, per agent edit, the file AND the added/removed line counts derived from the tool_input — `Write`: full content line count as added; `Edit`: line-diff of `old_string` vs `new_string` (common prefix/suffix strip + LCS, so shared context lines don't count); `MultiEdit`: sum of the per-edit diffs; `NotebookEdit`: `new_source` line count — into `.invictus/metrics/agent-loc.jsonl`. At commit time the encoder sums the entries per file (multiple edits and **multiple sessions since the last commit accumulate**) and, per staged file, attributes `min(recorded agent lines, staged numstat lines)` as assisted (`aa`/`ad`) and the remainder as human (`ha`/`hd`). Renamed files (numstat `old => new` detection) carry the attribution recorded under their pre-rename path. Consumed entries are removed per commit; unstaged files keep theirs for the next commit; 14-day expiry prevents stale attribution.
|
|
108
|
+
|
|
109
|
+
**This is a per-file line-count BOUND, not per-line identity tracking.** The kit knows *how many* lines the agent added/removed in a file, not *which* staged lines are the agent's:
|
|
110
|
+
|
|
111
|
+
- agent adds 10 lines, human adds 5 more → `aa=10, ha=5` (correct);
|
|
112
|
+
- agent adds 10 lines, human rewrites 3 of them in place before staging → numstat still shows ~10 added, all 10 count assisted (over-attribution within the bound);
|
|
113
|
+
- agent work reverted by the human before staging is capped by staged reality and never counts (`min` against the numstat);
|
|
114
|
+
- `Write` carries no old content in its tool_input, so lines a rewrite deletes are recorded as 0 and surface as human deletions;
|
|
115
|
+
- `Edit` with `replace_all` is counted once — the occurrence count is not in the tool_input.
|
|
116
|
+
|
|
117
|
+
True per-line identity (git-ai-style checkpointing) remains future work, and the reason is structural: **no hook fires on human edits.** Humans change files in their editors, outside any Claude Code event, so the human side of the diff is only observable at commit time — attributing individual lines would require content snapshots of every agent edit (a checkpoint store) diffed against the staged blob, which this scratch deliberately does not keep (metrics, never content).
|
|
118
|
+
|
|
119
|
+
## Honest limitations
|
|
120
|
+
|
|
121
|
+
- All three derivations above are documented approximations of transcript/scratch data; OTel `tool_decision` / active-time events remain the authoritative source when a client runs a collector.
|
|
122
|
+
- Metrics reach the trailer only after a `SessionEnd` has fired — a commit mid-session carries the previous sessions' aggregate (or none). Transcript-derived token counts are approximate by upstream design.
|
|
123
|
+
- If a commit is aborted after `prepare-commit-msg` ran, the `task.commit` log entry and hash chain still advance (detectable via `j`, self-heals on the next commit) and the agent-loc scratch entries for the staged files are already consumed — that commit's assisted lines would count as human if re-staged later.
|
|
124
|
+
|
|
125
|
+
## Develop
|
|
126
|
+
|
|
127
|
+
```bash
|
|
128
|
+
npm install # from the monorepo root (workspace links @invictus-group-ai/core)
|
|
129
|
+
npm test # builds (pretest) then runs vitest fixtures, incl. the compiled bin end-to-end
|
|
130
|
+
```
|
package/dist/bin.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Thin dispatcher: `invictus-hook <hook-name> [<hook-name>…]` reads the
|
|
4
|
+
* Claude Code hook JSON from stdin once and runs every named hook in THIS
|
|
5
|
+
* process via the engine (multi-module dispatch — one registration, one
|
|
6
|
+
* spawn, N modules). The engine fails open on every internal error, so this
|
|
7
|
+
* bin can only exit non-zero when a hook DECIDED to block (exit 2) or warn
|
|
8
|
+
* (exit 1).
|
|
9
|
+
*/
|
|
10
|
+
export {};
|
|
11
|
+
//# sourceMappingURL=bin.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bin.d.ts","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":";AACA;;;;;;;GAOG"}
|
package/dist/bin.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Thin dispatcher: `invictus-hook <hook-name> [<hook-name>…]` reads the
|
|
4
|
+
* Claude Code hook JSON from stdin once and runs every named hook in THIS
|
|
5
|
+
* process via the engine (multi-module dispatch — one registration, one
|
|
6
|
+
* spawn, N modules). The engine fails open on every internal error, so this
|
|
7
|
+
* bin can only exit non-zero when a hook DECIDED to block (exit 2) or warn
|
|
8
|
+
* (exit 1).
|
|
9
|
+
*/
|
|
10
|
+
import { runEngine } from './engine.js';
|
|
11
|
+
const STDIN_TIMEOUT_MS = 10_000;
|
|
12
|
+
async function readStdin() {
|
|
13
|
+
if (process.stdin.isTTY)
|
|
14
|
+
return '';
|
|
15
|
+
const chunks = [];
|
|
16
|
+
const read = (async () => {
|
|
17
|
+
for await (const chunk of process.stdin) {
|
|
18
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
19
|
+
}
|
|
20
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
21
|
+
})();
|
|
22
|
+
const timeout = new Promise((resolve) => {
|
|
23
|
+
const t = setTimeout(() => resolve(Buffer.concat(chunks).toString('utf8')), STDIN_TIMEOUT_MS);
|
|
24
|
+
t.unref?.();
|
|
25
|
+
});
|
|
26
|
+
return Promise.race([read, timeout]);
|
|
27
|
+
}
|
|
28
|
+
const stdinText = await readStdin();
|
|
29
|
+
const result = await runEngine(process.argv.slice(2), stdinText);
|
|
30
|
+
if (result.stdout !== '')
|
|
31
|
+
process.stdout.write(result.stdout);
|
|
32
|
+
if (result.stderr !== '')
|
|
33
|
+
process.stderr.write(result.stderr);
|
|
34
|
+
process.exitCode = result.exitCode;
|
|
35
|
+
// Safety valve: if a hook leaked an open handle, still exit within 2s.
|
|
36
|
+
setTimeout(() => process.exit(result.exitCode), 2000).unref();
|
|
37
|
+
//# sourceMappingURL=bin.js.map
|
package/dist/bin.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bin.js","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":";AACA;;;;;;;GAOG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEhC,KAAK,UAAU,SAAS;IACtB,IAAI,OAAO,CAAC,KAAK,CAAC,KAAK;QAAE,OAAO,EAAE,CAAC;IACnC,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,MAAM,IAAI,GAAG,CAAC,KAAK,IAAI,EAAE;QACvB,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;YACxC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;QACnE,CAAC;QACD,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IAChD,CAAC,CAAC,EAAE,CAAC;IACL,MAAM,OAAO,GAAG,IAAI,OAAO,CAAS,CAAC,OAAO,EAAE,EAAE;QAC9C,MAAM,CAAC,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,EAAE,gBAAgB,CAAC,CAAC;QAC9F,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;IACd,CAAC,CAAC,CAAC;IACH,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;AACvC,CAAC;AAED,MAAM,SAAS,GAAG,MAAM,SAAS,EAAE,CAAC;AACpC,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;AAEjE,IAAI,MAAM,CAAC,MAAM,KAAK,EAAE;IAAE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;AAC9D,IAAI,MAAM,CAAC,MAAM,KAAK,EAAE;IAAE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;AAE9D,OAAO,CAAC,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;AACnC,uEAAuE;AACvE,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAC,KAAK,EAAE,CAAC"}
|
package/dist/engine.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hook engine (ARCHITECTURE §7).
|
|
3
|
+
*
|
|
4
|
+
* Single Node runtime; each hook is a module `(input, ctx) => HookOutput`;
|
|
5
|
+
* the thin bin dispatches by argv name — MULTIPLE names run in this ONE
|
|
6
|
+
* process, in argv order (e.g. `invictus-hook typecheck-on-edit
|
|
7
|
+
* loc-recorder` on the single PostToolUse Write|Edit registration; no
|
|
8
|
+
* per-module spawn). Output contract per module:
|
|
9
|
+
* - `mode: 'exit'` → raw streams + exit code (stdout context on
|
|
10
|
+
* SessionStart/UserPromptSubmit; stderr + exit 2 to block)
|
|
11
|
+
* - `mode: 'json'` → JSON printed on stdout, exit 0 (PostToolUse
|
|
12
|
+
* `additionalContext` etc.)
|
|
13
|
+
*
|
|
14
|
+
* Multi-module merge (deterministic, in argv order):
|
|
15
|
+
* 1. any block (exit 2) → exit 2, streams of all exit-mode outputs joined;
|
|
16
|
+
* 2. else any warn (exit 1) → exit 1, same joining;
|
|
17
|
+
* 3. else any JSON output → ONE JSON on stdout (first as base,
|
|
18
|
+
* `additionalContext` concatenated across all JSON outputs);
|
|
19
|
+
* 4. else exit 0 with the stdouts joined (multi-module context injection).
|
|
20
|
+
*
|
|
21
|
+
* Hard internal timeout per hook. FAILS OPEN on any internal error: the
|
|
22
|
+
* error is appended to the event log and the engine exits 0 — a broken hook
|
|
23
|
+
* must never take the session down (one broken module never stops its
|
|
24
|
+
* siblings). The fail-closed net is `.githooks/` + CI.
|
|
25
|
+
*/
|
|
26
|
+
import type { HookInput, HookOutput } from '@invictus-group-ai/core';
|
|
27
|
+
export interface HookContext {
|
|
28
|
+
/** `$CLAUDE_PROJECT_DIR`, falling back to the hook input's `cwd`. */
|
|
29
|
+
projectDir: string;
|
|
30
|
+
env: NodeJS.ProcessEnv;
|
|
31
|
+
}
|
|
32
|
+
export interface HookModule {
|
|
33
|
+
/** Dispatch name (the engine's argv[0]), e.g. `secret-guard`. */
|
|
34
|
+
name: string;
|
|
35
|
+
/** Events this hook is valid for; other events resolve to a silent exit 0. */
|
|
36
|
+
events: string[];
|
|
37
|
+
/** Hard internal timeout enforced by the engine (ms). */
|
|
38
|
+
timeoutMs: number;
|
|
39
|
+
run(input: HookInput, ctx: HookContext): HookOutput | Promise<HookOutput>;
|
|
40
|
+
}
|
|
41
|
+
export interface EngineResult {
|
|
42
|
+
exitCode: number;
|
|
43
|
+
stdout: string;
|
|
44
|
+
stderr: string;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Dispatch one hook invocation — one or more module names, ONE process.
|
|
48
|
+
* Never throws; never returns a non-zero exit for internal failures (fail
|
|
49
|
+
* open, per module: a broken module is logged and skipped, its siblings
|
|
50
|
+
* still run). `registry` is injectable for tests.
|
|
51
|
+
*/
|
|
52
|
+
export declare function runEngine(hookNames: string | readonly string[] | undefined, stdinText: string, env?: NodeJS.ProcessEnv, registry?: Record<string, HookModule>): Promise<EngineResult>;
|
|
53
|
+
//# sourceMappingURL=engine.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../src/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAGH,OAAO,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAIrE,MAAM,WAAW,WAAW;IAC1B,qEAAqE;IACrE,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC,UAAU,CAAC;CACxB;AAED,MAAM,WAAW,UAAU;IACzB,iEAAiE;IACjE,IAAI,EAAE,MAAM,CAAC;IACb,8EAA8E;IAC9E,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,yDAAyD;IACzD,SAAS,EAAE,MAAM,CAAC;IAClB,GAAG,CAAC,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,WAAW,GAAG,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CAC3E;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AA+HD;;;;;GAKG;AACH,wBAAsB,SAAS,CAC7B,SAAS,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,GAAG,SAAS,EACjD,SAAS,EAAE,MAAM,EACjB,GAAG,GAAE,MAAM,CAAC,UAAwB,EACpC,QAAQ,GAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAS,GAC3C,OAAO,CAAC,YAAY,CAAC,CAyCvB"}
|
package/dist/engine.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hook engine (ARCHITECTURE §7).
|
|
3
|
+
*
|
|
4
|
+
* Single Node runtime; each hook is a module `(input, ctx) => HookOutput`;
|
|
5
|
+
* the thin bin dispatches by argv name — MULTIPLE names run in this ONE
|
|
6
|
+
* process, in argv order (e.g. `invictus-hook typecheck-on-edit
|
|
7
|
+
* loc-recorder` on the single PostToolUse Write|Edit registration; no
|
|
8
|
+
* per-module spawn). Output contract per module:
|
|
9
|
+
* - `mode: 'exit'` → raw streams + exit code (stdout context on
|
|
10
|
+
* SessionStart/UserPromptSubmit; stderr + exit 2 to block)
|
|
11
|
+
* - `mode: 'json'` → JSON printed on stdout, exit 0 (PostToolUse
|
|
12
|
+
* `additionalContext` etc.)
|
|
13
|
+
*
|
|
14
|
+
* Multi-module merge (deterministic, in argv order):
|
|
15
|
+
* 1. any block (exit 2) → exit 2, streams of all exit-mode outputs joined;
|
|
16
|
+
* 2. else any warn (exit 1) → exit 1, same joining;
|
|
17
|
+
* 3. else any JSON output → ONE JSON on stdout (first as base,
|
|
18
|
+
* `additionalContext` concatenated across all JSON outputs);
|
|
19
|
+
* 4. else exit 0 with the stdouts joined (multi-module context injection).
|
|
20
|
+
*
|
|
21
|
+
* Hard internal timeout per hook. FAILS OPEN on any internal error: the
|
|
22
|
+
* error is appended to the event log and the engine exits 0 — a broken hook
|
|
23
|
+
* must never take the session down (one broken module never stops its
|
|
24
|
+
* siblings). The fail-closed net is `.githooks/` + CI.
|
|
25
|
+
*/
|
|
26
|
+
import { parseHookInput, parseHookOutput } from '@invictus-group-ai/core';
|
|
27
|
+
import { appendInvictusEvent, resolveProjectDir } from './shared.js';
|
|
28
|
+
import { HOOKS } from './hooks/index.js';
|
|
29
|
+
const OK = { exitCode: 0, stdout: '', stderr: '' };
|
|
30
|
+
class HookTimeoutError extends Error {
|
|
31
|
+
constructor(name, ms) {
|
|
32
|
+
super(`hook ${name} exceeded its internal timeout of ${ms}ms`);
|
|
33
|
+
this.name = 'HookTimeoutError';
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Record an engine-internal failure in the event log, then fail open.
|
|
38
|
+
*
|
|
39
|
+
* Written as the first-class `hook.error` event type (core ≥0.2.0). Entries
|
|
40
|
+
* appended by kit ≤0.1.x used `type: 'gate'` with `data.kind = 'hook.error'`;
|
|
41
|
+
* they stay schema-valid, so readers scanning for hook failures must accept
|
|
42
|
+
* both forms.
|
|
43
|
+
*/
|
|
44
|
+
function failOpen(hookName, input, env, error) {
|
|
45
|
+
try {
|
|
46
|
+
const projectDir = resolveProjectDir(input?.cwd ? { cwd: input.cwd } : null, env);
|
|
47
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
48
|
+
appendInvictusEvent(projectDir, env, String(input?.session_id ?? 'unknown'), 'hook.error', {
|
|
49
|
+
hook: hookName,
|
|
50
|
+
event: typeof input?.hook_event_name === 'string' ? input.hook_event_name : null,
|
|
51
|
+
error: message.slice(0, 300),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
/* even the error log failing must not block the session */
|
|
56
|
+
}
|
|
57
|
+
return OK;
|
|
58
|
+
}
|
|
59
|
+
function renderOutput(output) {
|
|
60
|
+
if (output.mode === 'json') {
|
|
61
|
+
return { exitCode: 0, stdout: JSON.stringify(output.json), stderr: '' };
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
exitCode: output.exitCode,
|
|
65
|
+
stdout: output.stdout ?? '',
|
|
66
|
+
stderr: output.stderr ?? '',
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function resolveTimeoutMs(module, env) {
|
|
70
|
+
const raw = env.INVICTUS_HOOK_TIMEOUT_MS;
|
|
71
|
+
if (typeof raw === 'string' && raw.length > 0) {
|
|
72
|
+
const parsed = Number.parseInt(raw, 10);
|
|
73
|
+
if (Number.isFinite(parsed) && parsed > 0)
|
|
74
|
+
return parsed;
|
|
75
|
+
}
|
|
76
|
+
return module.timeoutMs;
|
|
77
|
+
}
|
|
78
|
+
async function runWithTimeout(module, input, ctx, timeoutMs) {
|
|
79
|
+
let timer;
|
|
80
|
+
try {
|
|
81
|
+
return await Promise.race([
|
|
82
|
+
Promise.resolve(module.run(input, ctx)),
|
|
83
|
+
new Promise((_, reject) => {
|
|
84
|
+
timer = setTimeout(() => reject(new HookTimeoutError(module.name, timeoutMs)), timeoutMs);
|
|
85
|
+
timer.unref?.();
|
|
86
|
+
}),
|
|
87
|
+
]);
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
if (timer !== undefined)
|
|
91
|
+
clearTimeout(timer);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/** Join non-empty stream fragments with a newline seam. */
|
|
95
|
+
function joinStreams(parts) {
|
|
96
|
+
return parts
|
|
97
|
+
.filter((p) => typeof p === 'string' && p !== '')
|
|
98
|
+
.map((p) => (p.endsWith('\n') ? p.slice(0, -1) : p))
|
|
99
|
+
.join('\n');
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Merge the outputs of the modules that ran (argv order preserved) into one
|
|
103
|
+
* engine result — semantics documented in the file header.
|
|
104
|
+
*/
|
|
105
|
+
function mergeOutputs(outputs) {
|
|
106
|
+
if (outputs.length === 0)
|
|
107
|
+
return OK;
|
|
108
|
+
if (outputs.length === 1)
|
|
109
|
+
return renderOutput(outputs[0]);
|
|
110
|
+
const exits = outputs.filter((o) => o.mode === 'exit');
|
|
111
|
+
const jsons = outputs.filter((o) => o.mode === 'json');
|
|
112
|
+
const maxExit = exits.reduce((max, o) => Math.max(max, o.exitCode), 0);
|
|
113
|
+
if (maxExit > 0) {
|
|
114
|
+
return {
|
|
115
|
+
exitCode: maxExit,
|
|
116
|
+
stdout: joinStreams(exits.map((o) => o.stdout)),
|
|
117
|
+
stderr: joinStreams(exits.map((o) => o.stderr)),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
if (jsons.length === 1)
|
|
121
|
+
return renderOutput(jsons[0]);
|
|
122
|
+
if (jsons.length > 1) {
|
|
123
|
+
const base = jsons[0].json;
|
|
124
|
+
const contexts = jsons
|
|
125
|
+
.map((o) => o.json.hookSpecificOutput?.additionalContext)
|
|
126
|
+
.filter((c) => typeof c === 'string' && c !== '');
|
|
127
|
+
const firstSpecific = jsons.find((o) => o.json.hookSpecificOutput)?.json.hookSpecificOutput;
|
|
128
|
+
const merged = contexts.length > 0 && firstSpecific
|
|
129
|
+
? {
|
|
130
|
+
...base,
|
|
131
|
+
hookSpecificOutput: { ...firstSpecific, additionalContext: contexts.join('\n\n') },
|
|
132
|
+
}
|
|
133
|
+
: base;
|
|
134
|
+
return renderOutput({ mode: 'json', json: merged });
|
|
135
|
+
}
|
|
136
|
+
return { exitCode: 0, stdout: joinStreams(exits.map((o) => o.stdout)), stderr: '' };
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Dispatch one hook invocation — one or more module names, ONE process.
|
|
140
|
+
* Never throws; never returns a non-zero exit for internal failures (fail
|
|
141
|
+
* open, per module: a broken module is logged and skipped, its siblings
|
|
142
|
+
* still run). `registry` is injectable for tests.
|
|
143
|
+
*/
|
|
144
|
+
export async function runEngine(hookNames, stdinText, env = process.env, registry = HOOKS) {
|
|
145
|
+
const names = (typeof hookNames === 'string' ? [hookNames] : (hookNames ?? [])).filter((n) => n !== '');
|
|
146
|
+
if (names.length === 0) {
|
|
147
|
+
return failOpen('(none)', null, env, new Error('no hook name given on argv'));
|
|
148
|
+
}
|
|
149
|
+
let rawInput = null;
|
|
150
|
+
let input;
|
|
151
|
+
try {
|
|
152
|
+
const parsedJson = JSON.parse(stdinText === '' ? '{}' : stdinText);
|
|
153
|
+
rawInput = parsedJson;
|
|
154
|
+
input = parseHookInput(parsedJson);
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
return failOpen(names.join('+'), rawInput, env, err);
|
|
158
|
+
}
|
|
159
|
+
const ctx = { projectDir: resolveProjectDir(input, env), env };
|
|
160
|
+
const outputs = [];
|
|
161
|
+
for (const name of names) {
|
|
162
|
+
const module = registry[name];
|
|
163
|
+
if (!module) {
|
|
164
|
+
failOpen(name, input, env, new Error(`unknown hook: ${name}`));
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
// A hook registered for the wrong event is a settings bug, not a reason
|
|
168
|
+
// to punish the session: silent skip.
|
|
169
|
+
if (module.events.length > 0 && !module.events.includes(input.hook_event_name)) {
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
const output = await runWithTimeout(module, input, ctx, resolveTimeoutMs(module, env));
|
|
174
|
+
outputs.push(parseHookOutput(output));
|
|
175
|
+
}
|
|
176
|
+
catch (err) {
|
|
177
|
+
failOpen(name, input, env, err);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return mergeOutputs(outputs);
|
|
181
|
+
}
|
|
182
|
+
//# sourceMappingURL=engine.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"engine.js","sourceRoot":"","sources":["../src/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAE1E,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACrE,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAwBzC,MAAM,EAAE,GAAiB,EAAE,QAAQ,EAAE,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC;AAEjE,MAAM,gBAAiB,SAAQ,KAAK;IAClC,YAAY,IAAY,EAAE,EAAU;QAClC,KAAK,CAAC,QAAQ,IAAI,qCAAqC,EAAE,IAAI,CAAC,CAAC;QAC/D,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAC;IACjC,CAAC;CACF;AAED;;;;;;;GAOG;AACH,SAAS,QAAQ,CACf,QAAgB,EAChB,KAAgC,EAChC,GAAsB,EACtB,KAAc;IAEd,IAAI,CAAC;QACH,MAAM,UAAU,GAAG,iBAAiB,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,GAAG,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eAAe,CAAC,EAAE,CAAC;YAC/E,SAAS;QACX,CAAC;QACD,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,EAAE,gBAAgB,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;YACvF,OAAO,CAAC,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC;QACxC,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;QAClC,CAAC;IACH,CAAC;IAED,OAAO,YAAY,CAAC,OAAO,CAAC,CAAC;AAC/B,CAAC"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* state-repo-committer — the git-side hook (`post-commit`).
|
|
3
|
+
*
|
|
4
|
+
* Only does anything under the **nested state repo** layout: `.invictus/` is a
|
|
5
|
+
* clone of the client's `repo-orchestra`, gitignored in the product repo, so
|
|
6
|
+
* code and project state live in two different repositories on one working
|
|
7
|
+
* tree. That layout buys real privacy — the platform reads state without ever
|
|
8
|
+
* cloning the client's source — and costs one thing: two commits per unit of
|
|
9
|
+
* work. This hook pays that cost so the developer never sees the bill.
|
|
10
|
+
*
|
|
11
|
+
* After each product commit it stages the state directory, commits it with a
|
|
12
|
+
* message naming the product commit it belongs to, and pushes when an upstream
|
|
13
|
+
* exists. Everything is best-effort and silent-by-default:
|
|
14
|
+
*
|
|
15
|
+
* - not a nested state repo (today's single-repo layout) → no-op, exit 0
|
|
16
|
+
* - nothing changed in the state repo → no-op, exit 0
|
|
17
|
+
* - no upstream, or the push fails (offline, no credentials) → commit stands,
|
|
18
|
+
* one line to stderr, exit 0
|
|
19
|
+
*
|
|
20
|
+
* It must never fail a commit that already succeeded. `git` ignores this hook's
|
|
21
|
+
* exit code, but a noisy hook trains people to ignore hooks, which is worse.
|
|
22
|
+
*
|
|
23
|
+
* Secrets are not a special case here: `local/` is gitignored inside the state
|
|
24
|
+
* repo by `ensureLocalGitignored` (kit-side), so `git add -A` cannot pick up
|
|
25
|
+
* the salt or the signing key. This hook additionally refuses to stage
|
|
26
|
+
* anything under `local/` even if that rule were missing — a belt-and-braces
|
|
27
|
+
* check on the one directory that must never be pushed to a repo the vendor
|
|
28
|
+
* administers.
|
|
29
|
+
*
|
|
30
|
+
* Escape hatch: `INVICTUS_SKIP_STATE_COMMIT=1`.
|
|
31
|
+
*/
|
|
32
|
+
export interface PostCommitOptions {
|
|
33
|
+
cwd?: string;
|
|
34
|
+
env?: NodeJS.ProcessEnv;
|
|
35
|
+
}
|
|
36
|
+
export interface PostCommitResult {
|
|
37
|
+
/** What the hook did — the vocabulary tests assert on. */
|
|
38
|
+
action: 'skipped' | 'no-nested-state' | 'nothing-to-commit' | 'committed' | 'committed-not-pushed';
|
|
39
|
+
/** Message for stderr, or null when the hook stays silent. */
|
|
40
|
+
message: string | null;
|
|
41
|
+
}
|
|
42
|
+
export declare function runPostCommit(options?: PostCommitOptions): PostCommitResult;
|
|
43
|
+
//# sourceMappingURL=post-commit.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"post-commit.d.ts","sourceRoot":"","sources":["../../src/git/post-commit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAOH,MAAM,WAAW,iBAAiB;IAChC,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;CACzB;AAED,MAAM,WAAW,gBAAgB;IAC/B,0DAA0D;IAC1D,MAAM,EAAE,SAAS,GAAG,iBAAiB,GAAG,mBAAmB,GAAG,WAAW,GAAG,sBAAsB,CAAC;IACnG,8DAA8D;IAC9D,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB;AAyED,wBAAgB,aAAa,CAAC,OAAO,GAAE,iBAAsB,GAAG,gBAAgB,CAmD/E"}
|