Skip to content

feat: load .env in hooks for API keys (GIT-94)#58

Merged
TonyCasey merged 3 commits intomainfrom
git-88
Feb 14, 2026
Merged

feat: load .env in hooks for API keys (GIT-94)#58
TonyCasey merged 3 commits intomainfrom
git-88

Conversation

@TonyCasey
Copy link
Copy Markdown
Owner

@TonyCasey TonyCasey commented Feb 14, 2026

Summary

  • Add dotenv dependency to load .env from repository root
  • Hooks now automatically pick up ANTHROPIC_API_KEY for LLM enrichment
  • No manual export required

Test plan

  • Verified LLM enrichment works with .env file
  • AI-Source: llm-enrichment shown in commit trailers
  • Git notes contain LLM-generated content

Closes GIT-94

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Hooks now load environment variables from a repository-root .env file before processing, affecting hook behavior based on repo-level env values.
  • Chores
    • Added a runtime dependency to support loading environment variables from .env.

AI-Agent: Claude-Code/2.1.42
AI-Model: claude-opus-4-5-20251101
AI-Gotcha: Git hooks require explicit loading of .env files to access API keys and other environment variables that are normally available in the main application context.
AI-Confidence: high
AI-Tags: git-hooks, environment-variables, dotenv, api-keys, configuration, execution-context
AI-Lifecycle: project
AI-Memory-Id: a4807174
AI-Source: llm-enrichment
AI-Agent: Claude-Code/2.1.42
AI-Model: claude-opus-4-5-20251101
AI-Decision: The project uses dotenv for loading environment variables from .env files, specifically for hooks functionality.
AI-Confidence: verified
AI-Tags: dotenv, environment-variables, hooks, configuration, cli-tool, package-structure, binary
AI-Lifecycle: project
AI-Memory-Id: 5e159d36
AI-Source: llm-enrichment
Copilot AI review requested due to automatic review settings February 14, 2026 18:55
@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Feb 14, 2026

📝 Walkthrough

Walkthrough

Adds dotenv as a runtime dependency and changes the hook command to resolve the repository root, load a .env from that root, then load hook configuration and proceed with hook processing.

Changes

Cohort / File(s) Summary
Package Dependencies
package.json
Added dotenv (^17.3.1) to dependencies.
Hook Command Initialization
src/commands/hook.ts
Added path and child_process imports, findGitRoot helper; compute repo root, load .env from repo root via dotenv.config() before loading hook config and continuing hook processing.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Input
  participant HookCmd as Hook Command
  participant Git as Git CLI
  participant Env as .env loader
  participant Config as Hook Config
  participant Hook as Hook Executor

  Input->>HookCmd: invoke hook command (with cwd?)
  HookCmd->>Git: git rev-parse --show-toplevel
  Git-->>HookCmd: repo root (or fallback cwd)
  HookCmd->>Env: load .env from repo root
  Env-->>HookCmd: environment variables loaded
  HookCmd->>Config: loadHookConfig(repoRoot)
  Config-->>HookCmd: hook configuration
  HookCmd->>Hook: isEventEnabled & process hooks
  Hook-->>HookCmd: hook results
  HookCmd-->>Input: exit / output
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 3 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: load .env in hooks for API keys (GIT-94)' directly and clearly summarizes the main change: loading environment variables from a .env file in git hooks to support API keys.
Merge Conflict Detection ✅ Passed ✅ No merge conflicts detected when merging into main

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch git-88

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds automatic .env loading to the git-mem hook command so hook executions can pick up API keys (notably ANTHROPIC_API_KEY) for LLM enrichment without requiring users to manually export environment variables.

Changes:

  • Load .env (from cwd) at the start of hookCommand execution.
  • Add dotenv as a runtime dependency.
  • Update package-lock.json accordingly.

Reviewed changes

Copilot reviewed 2 out of 3 changed files in this pull request and generated 2 comments.

File Description
src/commands/hook.ts Loads .env prior to reading hook config / dispatching events.
package.json Adds dotenv dependency.
package-lock.json Locks dotenv dependency resolution.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/commands/hook.ts
Comment on lines +127 to +129
// Load .env from repository root for API keys (e.g., ANTHROPIC_API_KEY)
loadEnv({ path: join(cwd, '.env'), quiet: true });

Copy link

Copilot AI Feb 14, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New behavior: hooks now load .env and mutate process.env before reading config/dispatching. There are existing unit/integration tests for hook behavior, but none assert that .env loading works (or that it doesn’t affect unrelated env vars). Adding an integration test that writes a .env in the temp repo and verifies the hook picks up a value from it would prevent regressions.

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point on test coverage. The existing hook integration tests cover the commit-msg flow but don't specifically test .env loading. Will defer adding that test to a follow-up since we've manually verified the end-to-end flow works.

Comment thread src/commands/hook.ts Outdated
Comment on lines +125 to +130
const cwd = input.cwd ?? process.cwd();

// Load .env from repository root for API keys (e.g., ANTHROPIC_API_KEY)
loadEnv({ path: join(cwd, '.env'), quiet: true });

const config = loadHookConfig(cwd);
Copy link

Copilot AI Feb 14, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment says this loads .env from the repository root, but the path is derived from cwd (stdin-provided working directory). If cwd is a subdirectory or not the repo top-level, this will silently miss the intended .env (and .git-mem.json), leading to hooks not picking up API keys. Consider resolving the git top-level (e.g., via git rev-parse --show-toplevel using cwd as the working dir) and loading .env from there, or adjust the comment/behavior accordingly.

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6abf8ea - now uses git rev-parse --show-toplevel to find the actual repo root, with graceful fallback to cwd if git fails.

AI-Agent: Claude-Code/2.1.42
AI-Model: claude-opus-4-5-20251101
AI-Gotcha: use git root for .env loading, not cwd (GIT-94). AI-Agent: Claude-Code/2.1.42
AI-Confidence: medium
AI-Tags: commands, typescript
AI-Lifecycle: project
AI-Memory-Id: 48348a38
AI-Source: heuristic
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/commands/hook.ts (1)

142-153: 🧹 Nitpick | 🔵 Trivial

Consider loading .env only when event is enabled.

Currently, .env is loaded before checking if the event is enabled (line 150). This means environment loading occurs even for disabled hooks. While the overhead is minimal, you could optimize by moving the isEventEnabled check earlier:

     const cwd = input.cwd ?? process.cwd();
     const repoRoot = findGitRoot(cwd);
+    const config = loadHookConfig(repoRoot);
+
+    if (!isEventEnabled(config.hooks, eventName)) {
+      clearTimeout(timer);
+      return;
+    }

     // Load .env from repository root for API keys (e.g., ANTHROPIC_API_KEY)
     loadEnv({ path: join(repoRoot, '.env'), quiet: true });
-
-    const config = loadHookConfig(repoRoot);
-
-    if (!isEventEnabled(config.hooks, eventName)) {
-      clearTimeout(timer);
-      return;
-    }

This avoids filesystem access for the .env file when the hook is disabled.

@TonyCasey TonyCasey merged commit 8f3e399 into main Feb 14, 2026
3 checks passed
@TonyCasey TonyCasey deleted the git-88 branch February 14, 2026 19:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants