@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,166 @@
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
+ import { execFileSync } from 'node:child_process';
33
+ import { existsSync } from 'node:fs';
34
+ import { join, resolve } from 'node:path';
35
+ import { gitEnv, gitOutput, isEntryModule } from '../shared.js';
36
+ /** Absolute git toplevel for a directory, or null when it is not in a repo. */
37
+ function toplevel(dir) {
38
+ const out = gitOutput(['rev-parse', '--show-toplevel'], dir);
39
+ return out === null || out === '' ? null : resolve(out);
40
+ }
41
+ /**
42
+ * The state directory when it is a repository of its own, else null.
43
+ * Null covers both "no `.invictus/`" and "`.invictus/` belongs to the product
44
+ * repo" — in the latter the state is already committed alongside the code and
45
+ * this hook has no work to do.
46
+ */
47
+ function nestedStateRepo(productRoot) {
48
+ const stateDir = join(productRoot, '.invictus');
49
+ // A repository of its own HAS a .git entry. Without this check the answer
50
+ // depended on what `git rev-parse` reported from inside the directory —
51
+ // and under an inherited GIT_DIR (git worktrees export it as an absolute
52
+ // path) it reported `.invictus/` itself, so the hook staged the whole
53
+ // product repo as deleted and committed that.
54
+ if (!existsSync(join(stateDir, '.git')))
55
+ return null;
56
+ const inner = toplevel(stateDir);
57
+ if (inner === null)
58
+ return null;
59
+ const outer = toplevel(productRoot);
60
+ if (outer !== null && inner === outer)
61
+ return null;
62
+ return inner;
63
+ }
64
+ /** Subject + short sha of the commit that just landed, for the state message. */
65
+ function productCommitRef(productRoot) {
66
+ return {
67
+ sha: gitOutput(['rev-parse', '--short', 'HEAD'], productRoot) ?? 'unknown',
68
+ subject: gitOutput(['log', '-1', '--pretty=%s'], productRoot) ?? '',
69
+ };
70
+ }
71
+ /** Porcelain status lines of the state repo (empty array = clean). */
72
+ function pendingChanges(stateRoot) {
73
+ const out = gitOutput(['status', '--porcelain'], stateRoot);
74
+ if (out === null || out === '')
75
+ return [];
76
+ return out.split('\n').filter((l) => l.trim() !== '');
77
+ }
78
+ /**
79
+ * Refuse to proceed when a staged path sits under `local/`. Reached only when
80
+ * the state repo's own gitignore rule is missing or was overridden with
81
+ * `git add -f`; the salt reverses pseudonymous dev ids back to git emails, so
82
+ * an accidental push of it defeats the whole privacy model.
83
+ */
84
+ function stagedSecrets(stateRoot) {
85
+ const out = gitOutput(['diff', '--cached', '--name-only'], stateRoot);
86
+ if (out === null || out === '')
87
+ return [];
88
+ return out
89
+ .split('\n')
90
+ .map((l) => l.trim())
91
+ .filter((l) => l === 'local' || l.startsWith('local/'));
92
+ }
93
+ function run(args, cwd, timeoutMs = 15_000) {
94
+ try {
95
+ execFileSync('git', args, {
96
+ cwd,
97
+ env: gitEnv(),
98
+ timeout: timeoutMs,
99
+ stdio: ['ignore', 'ignore', 'ignore'],
100
+ });
101
+ return true;
102
+ }
103
+ catch {
104
+ return false;
105
+ }
106
+ }
107
+ export function runPostCommit(options = {}) {
108
+ const env = options.env ?? process.env;
109
+ if (env['INVICTUS_SKIP_STATE_COMMIT']) {
110
+ return { action: 'skipped', message: null };
111
+ }
112
+ const productRoot = toplevel(options.cwd ?? process.cwd());
113
+ if (productRoot === null)
114
+ return { action: 'no-nested-state', message: null };
115
+ const stateRoot = nestedStateRepo(productRoot);
116
+ if (stateRoot === null)
117
+ return { action: 'no-nested-state', message: null };
118
+ if (pendingChanges(stateRoot).length === 0) {
119
+ return { action: 'nothing-to-commit', message: null };
120
+ }
121
+ if (!run(['add', '-A'], stateRoot)) {
122
+ return { action: 'nothing-to-commit', message: 'invictus: could not stage the state repo — state not committed' };
123
+ }
124
+ const secrets = stagedSecrets(stateRoot);
125
+ if (secrets.length > 0) {
126
+ run(['reset'], stateRoot);
127
+ return {
128
+ action: 'nothing-to-commit',
129
+ message: `invictus: REFUSING to commit the project state — ${secrets.join(', ')} is staged under .invictus/local/, ` +
130
+ 'which holds the dev-id salt and the signing key. Add `local/` to .invictus/.gitignore and run `invi doctor`.',
131
+ };
132
+ }
133
+ const { sha, subject } = productCommitRef(productRoot);
134
+ const message = subject === '' ? `chore(state): ${sha}` : `chore(state): ${subject} [${sha}]`;
135
+ if (!run(['commit', '-m', message], stateRoot)) {
136
+ return { action: 'nothing-to-commit', message: 'invictus: state commit failed — the product commit is unaffected' };
137
+ }
138
+ const upstream = gitOutput(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], stateRoot);
139
+ if (upstream === null) {
140
+ return {
141
+ action: 'committed-not-pushed',
142
+ message: 'invictus: project state committed locally (no upstream on .invictus/ — run `git -C .invictus push -u origin main` once)',
143
+ };
144
+ }
145
+ if (!run(['push'], stateRoot, 30_000)) {
146
+ return {
147
+ action: 'committed-not-pushed',
148
+ message: 'invictus: project state committed but NOT pushed (offline or no credentials) — it will go with the next commit',
149
+ };
150
+ }
151
+ return { action: 'committed', message: null };
152
+ }
153
+ // Direct execution: `node dist/git/post-commit.js` (also through a symlinked package)
154
+ if (isEntryModule(import.meta.url)) {
155
+ let result;
156
+ try {
157
+ result = runPostCommit();
158
+ }
159
+ catch {
160
+ result = { action: 'skipped', message: null }; // the commit already landed
161
+ }
162
+ if (result.message !== null)
163
+ process.stderr.write(result.message + '\n');
164
+ process.exitCode = 0;
165
+ }
166
+ //# sourceMappingURL=post-commit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"post-commit.js","sourceRoot":"","sources":["../../src/git/post-commit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAchE,+EAA+E;AAC/E,SAAS,QAAQ,CAAC,GAAW;IAC3B,MAAM,GAAG,GAAG,SAAS,CAAC,CAAC,WAAW,EAAE,iBAAiB,CAAC,EAAE,GAAG,CAAC,CAA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
2
+ * metrics-pusher — the git-side hook (`pre-push`).
3
+ *
4
+ * Runs `invi sync` on every push — event log and commit trailers — and never blocks the push.
5
+ *
6
+ * WHY THIS EXISTS. `invi sync` was a manual step in the onboarding, and a
7
+ * manual step in an onboarding is a step that does not happen. The metrics are
8
+ * worth exactly what gets sent, so leaving the send to human discipline meant
9
+ * leaving it to chance — a dashboard that is empty because nobody ran a command
10
+ * is indistinguishable, to whoever is looking at it, from a product that does
11
+ * not work.
12
+ *
13
+ * WHY `pre-push` AND NOT `post-commit`. Three reasons, in order of weight:
14
+ *
15
+ * 1. The developer is already going to the network and already expects to wait
16
+ * a moment. A commit is supposed to be instant; spending a network round
17
+ * trip on it would make the kit feel like a tax on every save.
18
+ * 2. A push batches. Ten commits become one request instead of ten.
19
+ * 3. Nothing is lost by waiting: the event log is on disk, the watermark
20
+ * tracks what the server accepted, and ingestion is idempotent — so a
21
+ * missed sync is a delay, never a gap.
22
+ *
23
+ * IT NEVER BLOCKS THE PUSH. Every failure path exits 0. A developer whose push
24
+ * is refused because a metrics server is unreachable will, correctly, rip the
25
+ * hook out — and then the honest failure (no data) is replaced by a dishonest
26
+ * one (no kit). Offline, unconfigured, server down, credentials rejected: all
27
+ * of them are quiet, and the entries go with the next push.
28
+ *
29
+ * Escape hatch: INVICTUS_SKIP_SYNC=1.
30
+ */
31
+ /** How long a push may spend on telemetry before we give up on it. */
32
+ export declare const SYNC_TIMEOUT_MS = 15000;
33
+ export type PrePushAction = 'skipped' | 'not-configured' | 'no-cli' | 'synced' | 'sync-failed';
34
+ export interface PrePushResult {
35
+ action: PrePushAction;
36
+ /** Written to stderr when present. Null means: say nothing at all. */
37
+ message: string | null;
38
+ }
39
+ export declare function runPrePush(opts: {
40
+ cwd: string;
41
+ env: NodeJS.ProcessEnv;
42
+ }): PrePushResult;
43
+ //# sourceMappingURL=pre-push.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pre-push.d.ts","sourceRoot":"","sources":["../../src/git/pre-push.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAMH,sEAAsE;AACtE,eAAO,MAAM,eAAe,QAAS,CAAC;AAEtC,MAAM,MAAM,aAAa,GACrB,SAAS,GACT,gBAAgB,GAChB,QAAQ,GACR,QAAQ,GACR,aAAa,CAAC;AAElB,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,aAAa,CAAC;IACtB,sEAAsE;IACtE,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB;AAeD,wBAAgB,UAAU,CAAC,IAAI,EAAE;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC,UAAU,CAAA;CAAE,GAAG,aAAa,CA0CvF"}
@@ -0,0 +1,102 @@
1
+ /**
2
+ * metrics-pusher — the git-side hook (`pre-push`).
3
+ *
4
+ * Runs `invi sync` on every push — event log and commit trailers — and never blocks the push.
5
+ *
6
+ * WHY THIS EXISTS. `invi sync` was a manual step in the onboarding, and a
7
+ * manual step in an onboarding is a step that does not happen. The metrics are
8
+ * worth exactly what gets sent, so leaving the send to human discipline meant
9
+ * leaving it to chance — a dashboard that is empty because nobody ran a command
10
+ * is indistinguishable, to whoever is looking at it, from a product that does
11
+ * not work.
12
+ *
13
+ * WHY `pre-push` AND NOT `post-commit`. Three reasons, in order of weight:
14
+ *
15
+ * 1. The developer is already going to the network and already expects to wait
16
+ * a moment. A commit is supposed to be instant; spending a network round
17
+ * trip on it would make the kit feel like a tax on every save.
18
+ * 2. A push batches. Ten commits become one request instead of ten.
19
+ * 3. Nothing is lost by waiting: the event log is on disk, the watermark
20
+ * tracks what the server accepted, and ingestion is idempotent — so a
21
+ * missed sync is a delay, never a gap.
22
+ *
23
+ * IT NEVER BLOCKS THE PUSH. Every failure path exits 0. A developer whose push
24
+ * is refused because a metrics server is unreachable will, correctly, rip the
25
+ * hook out — and then the honest failure (no data) is replaced by a dishonest
26
+ * one (no kit). Offline, unconfigured, server down, credentials rejected: all
27
+ * of them are quiet, and the entries go with the next push.
28
+ *
29
+ * Escape hatch: INVICTUS_SKIP_SYNC=1.
30
+ */
31
+ import { execFileSync, spawnSync } from 'node:child_process';
32
+ import { findKitCli, isProvisioned } from '../kit-cli.js';
33
+ import { gitEnv, isEntryModule } from '../shared.js';
34
+ /** How long a push may spend on telemetry before we give up on it. */
35
+ export const SYNC_TIMEOUT_MS = 15_000;
36
+ function gitToplevel(cwd) {
37
+ try {
38
+ return execFileSync('git', ['rev-parse', '--show-toplevel'], {
39
+ cwd,
40
+ env: gitEnv(),
41
+ encoding: 'utf8',
42
+ stdio: ['ignore', 'pipe', 'ignore'],
43
+ }).trim();
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ }
49
+ export function runPrePush(opts) {
50
+ if (opts.env.INVICTUS_SKIP_SYNC)
51
+ return { action: 'skipped', message: null };
52
+ const root = gitToplevel(opts.cwd);
53
+ if (root === null)
54
+ return { action: 'not-configured', message: null };
55
+ // No client.json means this machine was never provisioned against a platform.
56
+ // That is the normal state of a repo using the kit offline, and it is not a
57
+ // problem to report on every push.
58
+ if (!isProvisioned(root)) {
59
+ return { action: 'not-configured', message: null };
60
+ }
61
+ const cli = findKitCli(root);
62
+ if (cli === null)
63
+ return { action: 'no-cli', message: null };
64
+ const run = spawnSync(process.execPath, [cli, 'sync'], {
65
+ cwd: root,
66
+ encoding: 'utf8',
67
+ timeout: SYNC_TIMEOUT_MS,
68
+ env: opts.env,
69
+ });
70
+ if (run.status === 0) {
71
+ // One line, only when something actually moved: a hook that talks on every
72
+ // push teaches people to stop reading hooks.
73
+ const out = `${run.stdout ?? ''}`.trim();
74
+ const first = out.split('\n')[0] ?? '';
75
+ // Only speak when a non-zero count appears: "sincronizados 0 eventos" is
76
+ // the normal case and does not deserve a line on every push.
77
+ const moved = /\b[1-9]\d*\b/.test(first);
78
+ return { action: 'synced', message: moved ? first : null };
79
+ }
80
+ const why = run.error?.message ??
81
+ `${run.stderr ?? ''}`.trim().split('\n')[0] ??
82
+ `exit ${String(run.status)}`;
83
+ return {
84
+ action: 'sync-failed',
85
+ message: `invictus: métricas não enviadas (${why}) — vão no próximo push`,
86
+ };
87
+ }
88
+ // Direct execution: `node dist/git/pre-push.js` (also through a symlinked package)
89
+ if (isEntryModule(import.meta.url)) {
90
+ let result;
91
+ try {
92
+ result = runPrePush({ cwd: process.cwd(), env: process.env });
93
+ }
94
+ catch {
95
+ result = { action: 'sync-failed', message: null }; // never stand in the way
96
+ }
97
+ if (result.message !== null)
98
+ process.stderr.write(result.message + '\n');
99
+ // ALWAYS 0. Telemetry must never stand between a developer and their push.
100
+ process.exitCode = 0;
101
+ }
102
+ //# sourceMappingURL=pre-push.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pre-push.js","sourceRoot":"","sources":["../../src/git/pre-push.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAErD,sEAAsE;AACtE,MAAM,CAAC,MAAM,eAAe,GAAG,MAAM,CAAC;AAetC,SAAS,WAAW,CAAC,GAAW;IAC9B,IAAI,CAAC;QACH,OAAO,YAAY,CAAC,KAAK,EAAE,CAAC,WAAW,EAAE,iBAAiB,CAAC,EAAE;YAC3D,GAAG;YACH,GAAG,EAAE,MAAM,EAAE;YACb,QAAQ,EAAE,MAAM;YAChB,KAAK,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,CAAC;SACpC,CAAC,CAAC,IAAI,EAAE,CAAC;IACZ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,IAA6C;IACtE,IAAI,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E,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAC7D,CAAC;IAED,MAAM,GAAG,GACP,GAAG,CAAC,KAAK,EAAE,OAAO;QAClB,GAAG,GAAG,CAAC,MAAM,IAAI,EAAE,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAC3C,QAAQ,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;IAC/B,OAAO;QACL,MAAM,EAAE,aAAa;QACrB,OAAO,EAAE,oCAAoC,GAAG,yBAAyB;KAC1E,CAAC;AACJ,CAAC;AAED,mFAAmF;AACnF,IAAI,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;IACnC,IAAI,MAAqB,CAAC;IAC1B,IAAI,CAAC;QACH,MAAM,GAAG,UAAU,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;IAChE,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,GAAG,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,yBAAyB;IAC9E,CAAC;IACD,IAAI,MAAM,CAAC,OAAO,KAAK,IAAI;QAAE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;IACzE,2EAA2E;IAC3E,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC"}
@@ -0,0 +1,97 @@
1
+ /**
2
+ * commit-metrics-encoder — the git-side hook (`prepare-commit-msg`).
3
+ * Works on every CLI, not only Claude Code.
4
+ *
5
+ * Reads the metrics accumulated in the event log since the last trailer
6
+ * (session.end entries), appends ONE `task.commit` summary entry, builds a
7
+ * TrailerPayload from it (the trailer is DERIVED from the log entry —
8
+ * ARCHITECTURE §5), encodes via the core codec, and appends
9
+ *
10
+ * Assisted-by: <model> via Invictus Kit
11
+ * Invictus: v1.<base64url(deflate(cbor))>.<hmac16>
12
+ *
13
+ * to the commit message — unless the trailers are already present or this
14
+ * is a merge/squash/fixup/amend commit.
15
+ *
16
+ * HMAC key: `.invictus/local/dev.key` (git-ignored, per-dev, derived from
17
+ * the client master key at provisioning). ABSENT KEY → SKIP SILENTLY: an
18
+ * absent trailer is a signal (the "untracked commit" metric), never an
19
+ * error, and this hook must never break `git commit`.
20
+ */
21
+ import type { EventLogEntry, TrailerLocCounts } from '@invictus-group-ai/core';
22
+ import type { AgentLocEntry } from '../hooks/loc-recorder.js';
23
+ export interface PrepareCommitMsgOptions {
24
+ cwd?: string;
25
+ env?: NodeJS.ProcessEnv;
26
+ }
27
+ /**
28
+ * A `task.commit` is written while the commit message is being prepared —
29
+ * before the commit exists. When that commit is then amended with a new
30
+ * message, reset away, or rejected by a later hook, the entry had already
31
+ * claimed the window and the commit that replaced it shipped with no trailer
32
+ * (seen in a client repo: the commit that carried the trailer was amended
33
+ * away, and the one that survived had none).
34
+ *
35
+ * The fix: an entry only counts as credited if some ref still carries a
36
+ * trailer derived from it. Otherwise its window is handed to the next commit.
37
+ */
38
+ /** A `task.commit` older than this is never re-credited, carried or not. */
39
+ export declare const ORPHAN_MAX_AGE_SEC: number;
40
+ /**
41
+ * True when a commit reachable from any ref (branches, tags, remotes — not the
42
+ * reflog) carries a trailer whose `j` is this entry. When git cannot answer,
43
+ * the answer is yes: re-crediting work that did land would double-count it,
44
+ * which is worse than leaving one commit without a trailer.
45
+ */
46
+ export declare function carriedByAnyRef(projectDir: string, entry: EventLogEntry): boolean;
47
+ export interface Superseded {
48
+ /** `task.commit` hashes whose window this commit takes over. */
49
+ hashes: Set<string>;
50
+ /** The newest of them (recorded as `re` on the replacing entry), or null. */
51
+ head: EventLogEntry | null;
52
+ }
53
+ /**
54
+ * Which `task.commit` entries never landed. Only the newest entry is checked:
55
+ * any older one was already judged when the entry after it was written, and
56
+ * if it was taken over, that entry names it in `re` — so the chain is followed
57
+ * instead of asking git again.
58
+ */
59
+ export declare function supersededCommits(entries: EventLogEntry[], isCarried: (entry: EventLogEntry) => boolean, nowSec: number): Superseded;
60
+ /** Recorded agent line counts for one file, summed over scratch entries. */
61
+ export interface AgentFileTotals {
62
+ la: number;
63
+ ld: number;
64
+ }
65
+ /**
66
+ * Sum the scratch entries per file — multiple edits AND multiple sessions
67
+ * since the last commit accumulate into one added/removed total per file.
68
+ */
69
+ export declare function aggregateAgentLoc(entries: AgentLocEntry[]): Map<string, AgentFileTotals>;
70
+ /**
71
+ * Staged additions/deletions, split by attribution. Per staged file:
72
+ * `min(recorded agent lines, staged numstat lines)` counts as assisted
73
+ * (`aa`/`ad`) and the remainder as human (`ha`/`hd`) — a per-file
74
+ * line-count BOUND (loc-recorder header has the full semantics):
75
+ *
76
+ * - agent added 10 lines, human added 5 more → aa=10, ha=5;
77
+ * - agent edits reverted by the human before staging → capped by staged
78
+ * reality (recorded counts in excess of the numstat never count);
79
+ * - renamed files (numstat `old => new`) carry attribution recorded under
80
+ * the pre-rename path.
81
+ *
82
+ * Binary files (numstat `-`) carry no line counts and are skipped.
83
+ * `stagedFiles` contains every staged path (pre- AND post-rename) so the
84
+ * caller can consume the matching scratch entries.
85
+ */
86
+ export declare function splitStagedLoc(numstat: string | null, agentTotals: ReadonlyMap<string, AgentFileTotals>): {
87
+ loc: TrailerLocCounts;
88
+ stagedFiles: Set<string>;
89
+ };
90
+ /** Insert trailer lines after the last content line (before git's comment block). */
91
+ export declare function insertTrailers(message: string, trailerLines: string[]): string | null;
92
+ /**
93
+ * `prepare-commit-msg` implementation. argv: [msgFile, source?, sha?].
94
+ * Always returns 0 — metrics encoding must never break a commit.
95
+ */
96
+ export declare function runPrepareCommitMsg(argv: string[], opts?: PrepareCommitMsgOptions): Promise<number>;
97
+ //# sourceMappingURL=prepare-commit-msg.d.ts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