Skip to content

fix(auth): load agentmemory env for hooks and CLI#535

Open
Lubrsy706 wants to merge 3 commits into
rohitg00:mainfrom
Lubrsy706:fix/518-internal-worker-auth
Open

fix(auth): load agentmemory env for hooks and CLI#535
Lubrsy706 wants to merge 3 commits into
rohitg00:mainfrom
Lubrsy706:fix/518-internal-worker-auth

Conversation

@Lubrsy706
Copy link
Copy Markdown

@Lubrsy706 Lubrsy706 commented May 19, 2026

Summary

  • add a shared hook env reader that keeps process env precedence but falls back to ~/.agentmemory/.env
  • use that reader for hook Bearer auth and the context-injection flag, so installed hooks match the daemon's config
  • use the same merged env source for CLI REST calls such as status, demo, and JSONL import
  • rebuild the packaged plugin/scripts/*.mjs hook outputs

Why

When AGENTMEMORY_SECRET is set in ~/.agentmemory/.env, the daemon enables API auth, but hook and CLI processes often do not inherit that shell variable. That makes hook calls to /session/start, /observe, /session/end, /consolidate-pipeline, etc. send no Bearer token even though the server requires one, which can silently break capture and downstream consolidation.

This keeps explicit shell env overrides working while making the default ~/.agentmemory/.env configuration usable end-to-end.

Addresses #518.

Validation

  • npm run build
  • npm test -- test/context-injection.test.ts test/cli-connect.test.ts test/codex-plugin.test.ts test/stop-hook-recursion-guard.test.ts
  • npm test

Summary by CodeRabbit

  • New Features

    • Centralized environment resolution added: the app now reads and caches ~/.agentmemory/.env (supports comments, quoted values, inline comment stripping); process env vars still take precedence.
    • Authentication headers are now consistently sourced from the central env resolution, improving request auth behavior across commands and hooks.
  • Tests

    • Added integration tests for context injection and env-based auth precedence.

Review Change Stack

@vercel
Copy link
Copy Markdown

vercel Bot commented May 19, 2026

@Lubrsy706 is attempting to deploy a commit to the rohitg00's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 19, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 688893c3-595d-4250-9f60-bfeb8f23cdaf

📥 Commits

Reviewing files that changed from the base of the PR and between 492c772 and 6ceb3fd.

📒 Files selected for processing (1)
  • test/context-injection.test.ts

📝 Walkthrough

Walkthrough

Adds a cached ~/.agentmemory/.env reader (agentmemoryEnv) and migrates plugin scripts, TypeScript hooks, and the CLI to use it for AGENTMEMORY_* configuration and centralized Authorization header construction; tests added to validate file-backed secret precedence and suppression.

Changes

Environment Variable Resolution and Hook Configuration Migration

Layer / File(s) Summary
Environment variable resolution infrastructure
src/hooks/env.ts, plugin/scripts/env-B0rzso6b.mjs
Adds .env file parsing with caching and exports agentmemoryEnv(key) that prefers process.env and falls back to cached ~/.agentmemory/.env values.
Plugin scripts migration
plugin/scripts/*.mjs
All plugin scripts import the generated env helper and derive AGENTMEMORY_SECRET/AGENTMEMORY_INJECT_CONTEXT via agentmemoryEnv(...) instead of direct process.env access.
TypeScript hooks migration
src/hooks/*.ts
All TS hook entrypoints import agentmemoryEnv and use it to source AGENTMEMORY_SECRET, AGENTMEMORY_INJECT_CONTEXT, and related config, removing previous `
CLI authentication header centralization
src/cli.ts
Introduces agentmemoryAuthHeaders() (uses env helper) and applies it across apiFetch, postJson/postJsonStrict, observation POSTs, and import-jsonl.
Test coverage for .env fallback mechanism
test/context-injection.test.ts
Adds fixtures to create a temp ~/.agentmemory/.env, spin up local HTTP servers, and tests verifying hooks use file-backed secrets and that an explicit empty env value suppresses Authorization.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 In a burrow where secrets softly hide,
A little .env keeps them safe inside,
Hooks now ask kindly where their tokens dwell,
From shell or file the truth they tell,
Headers sing "Bearer" when the key is bright.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix(auth): load agentmemory env for hooks and CLI' accurately describes the main change: adding environment variable loading from ~/.agentmemory/.env for authentication across hooks and CLI components.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/hooks/env.ts`:
- Around line 39-43: The agentmemoryEnv function currently treats empty-string
process.env values as absent and uses || when returning cachedEnv, so update
agentmemoryEnv to treat an explicitly set empty string as a valid override:
check for process.env[key] !== undefined (or use
Object.prototype.hasOwnProperty.call(process.env, key)) instead of a truthy
check to decide precedence, keep the existing cachedEnv lazy-init via
readAgentmemoryEnvFile(), and return cachedEnv[key] using the nullish coalescing
operator (??) so that an actual empty string from the cache is preserved rather
than coerced to "". Reference the agentmemoryEnv function and
cachedEnv/readAgentmemoryEnvFile usage when making the change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b6296165-d2f8-46a3-864a-03e20d79b24d

📥 Commits

Reviewing files that changed from the base of the PR and between 68fddd4 and 159f612.

📒 Files selected for processing (30)
  • plugin/scripts/env-DODO3jxN.mjs
  • plugin/scripts/notification.mjs
  • plugin/scripts/post-commit.mjs
  • plugin/scripts/post-tool-failure.mjs
  • plugin/scripts/post-tool-use.mjs
  • plugin/scripts/pre-compact.mjs
  • plugin/scripts/pre-tool-use.mjs
  • plugin/scripts/prompt-submit.mjs
  • plugin/scripts/session-end.mjs
  • plugin/scripts/session-start.mjs
  • plugin/scripts/stop.mjs
  • plugin/scripts/subagent-start.mjs
  • plugin/scripts/subagent-stop.mjs
  • plugin/scripts/task-completed.mjs
  • src/cli.ts
  • src/hooks/env.ts
  • src/hooks/notification.ts
  • src/hooks/post-commit.ts
  • src/hooks/post-tool-failure.ts
  • src/hooks/post-tool-use.ts
  • src/hooks/pre-compact.ts
  • src/hooks/pre-tool-use.ts
  • src/hooks/prompt-submit.ts
  • src/hooks/session-end.ts
  • src/hooks/session-start.ts
  • src/hooks/stop.ts
  • src/hooks/subagent-start.ts
  • src/hooks/subagent-stop.ts
  • src/hooks/task-completed.ts
  • test/context-injection.test.ts

Comment thread src/hooks/env.ts Outdated
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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/context-injection.test.ts`:
- Around line 224-246: The test currently treats authHeader === undefined as
proof no Authorization was sent but that could also mean the server never
received the request; modify the server handler in the createServer callback to
set a requestReceived flag (e.g., requestReceived = true) when invoked, keep
assigning authHeader there, and after runHook add an assertion
expect(requestReceived).toBe(true) (in addition to
expect(authHeader).toBeUndefined()) so the test only passes if the hook actually
hit the mock server; update references to authHeader, createServer, runHook and
expect accordingly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a1c1792d-4282-44d0-b49c-be52962e341d

📥 Commits

Reviewing files that changed from the base of the PR and between 159f612 and 492c772.

📒 Files selected for processing (16)
  • plugin/scripts/env-B0rzso6b.mjs
  • plugin/scripts/notification.mjs
  • plugin/scripts/post-commit.mjs
  • plugin/scripts/post-tool-failure.mjs
  • plugin/scripts/post-tool-use.mjs
  • plugin/scripts/pre-compact.mjs
  • plugin/scripts/pre-tool-use.mjs
  • plugin/scripts/prompt-submit.mjs
  • plugin/scripts/session-end.mjs
  • plugin/scripts/session-start.mjs
  • plugin/scripts/stop.mjs
  • plugin/scripts/subagent-start.mjs
  • plugin/scripts/subagent-stop.mjs
  • plugin/scripts/task-completed.mjs
  • src/hooks/env.ts
  • test/context-injection.test.ts

Comment thread test/context-injection.test.ts
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.

1 participant