Skip to content

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

Open
Lubrsy706 wants to merge 4 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 4 commits into
rohitg00:mainfrom
Lubrsy706:fix/518-internal-worker-auth

Conversation

@Lubrsy706

@Lubrsy706 Lubrsy706 commented May 19, 2026

Copy link
Copy Markdown

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

Release Notes

  • New Features

    • Configuration files can now be read from ~/.agentmemory/.env in addition to environment variables, with process environment variables taking precedence. This enables persistent secret storage for the AgentMemory integration.
    • Centralized authentication header management for improved consistency across API requests.
  • Bug Fixes

    • Improved search normalization logic in memory viewer.

Review Change Stack

@vercel

vercel Bot commented May 19, 2026

Copy link
Copy Markdown

@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

coderabbitai Bot commented May 19, 2026

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b5f54cfc-416d-4c13-a6a2-874690f63f7c

📥 Commits

Reviewing files that changed from the base of the PR and between 6ceb3fd and 2bc5cd0.

📒 Files selected for processing (27)
  • 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/notification.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
  • src/viewer/index.html
💤 Files with no reviewable changes (27)
  • src/hooks/subagent-stop.ts
  • src/hooks/subagent-start.ts
  • plugin/scripts/post-commit.mjs
  • plugin/scripts/post-tool-use.mjs
  • plugin/scripts/prompt-submit.mjs
  • src/hooks/pre-compact.ts
  • src/hooks/notification.ts
  • src/hooks/task-completed.ts
  • plugin/scripts/stop.mjs
  • plugin/scripts/session-end.mjs
  • plugin/scripts/pre-compact.mjs
  • plugin/scripts/post-tool-failure.mjs
  • plugin/scripts/subagent-stop.mjs
  • plugin/scripts/subagent-start.mjs
  • src/hooks/stop.ts
  • plugin/scripts/task-completed.mjs
  • plugin/scripts/notification.mjs
  • plugin/scripts/session-start.mjs
  • src/hooks/prompt-submit.ts
  • src/hooks/post-tool-use.ts
  • src/hooks/session-start.ts
  • src/hooks/post-tool-failure.ts
  • plugin/scripts/pre-tool-use.mjs
  • src/hooks/session-end.ts
  • src/cli.ts
  • src/hooks/pre-tool-use.ts
  • src/viewer/index.html

📝 Walkthrough

Walkthrough

This PR centralizes environment variable resolution across 25+ hook and script files by introducing a shared agentmemoryEnv helper that reads secrets and configuration from process.env first, then falls back to a cached ~/.agentmemory/.env file. It also refactors the CLI to use a centralized auth header helper and adds test coverage for environment precedence.

Changes

Environment Variable Resolution Infrastructure

Layer / File(s) Summary
Shared env helper module
src/hooks/env.ts
New module exports agentmemoryEnv(key) which parses ~/.agentmemory/.env (supporting comments, blank lines, and quoted values), caches results in-memory, and prefers process.env before falling back to file contents or "" when absent.
Plugin scripts migration
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
Each script adds inline agentmemoryEnv helper (bundled separately from TS module) with file-reading and caching, updates imports for path/fs/os utilities, and migrates SECRET and INJECT_CONTEXT from direct process.env reads (with embedded || "" defaults) to agentmemoryEnv calls.
TypeScript hooks migration
src/hooks/post-commit.ts, src/hooks/notification.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
Each hook imports agentmemoryEnv from ./env.js and derives AGENTMEMORY_SECRET and feature flags via the helper instead of direct process.env with hardcoded || "" fallbacks, removing duplicate empty-string defaults.
CLI authentication header centralization
src/cli.ts
Introduces agentmemoryAuthHeaders(base?) helper that reads AGENTMEMORY_SECRET via getEnvVar and conditionally sets Authorization: Bearer header; refactors apiFetch(), postJson(), postJsonStrict(), observation POST, and import-jsonl command to use the helper instead of manual header construction.
Environment precedence and auth tests
test/context-injection.test.ts
Adds test infrastructure (temp directory setup, ephemeral HTTP server helpers) and test cases for pre-tool-use hook reading from ~/.agentmemory/.env, prompt-submit hook using .env secret when AGENTMEMORY_SECRET env is omitted, and explicit empty AGENTMEMORY_SECRET overriding .env to suppress auth headers.
Viewer search normalization fix
src/viewer/index.html
Minor adjustment to normalizedSearch variable computation location within renderMemories filtering logic.

Sequence Diagram(s)

sequenceDiagram
  participant Hook as Hook/Script
  participant AgentmemoryEnv as agentmemoryEnv(key)
  participant ProcessEnv as process.env
  participant EnvFile as ~/.agentmemory/.env
  participant Cache as In-Memory Cache

  Hook->>AgentmemoryEnv: get AGENTMEMORY_SECRET
  AgentmemoryEnv->>ProcessEnv: check process.env[key]
  alt key present in process.env
    ProcessEnv-->>AgentmemoryEnv: return value
  else key absent in process.env
    AgentmemoryEnv->>Cache: check cached contents
    alt cache empty (first call)
      AgentmemoryEnv->>EnvFile: read & parse ~/.agentmemory/.env
      EnvFile-->>Cache: populate cache
    end
    Cache-->>AgentmemoryEnv: return cached value or ""
  end
  AgentmemoryEnv-->>Hook: return secret (for auth header)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • rohitg00

Poem

🐇 Whiskers twitching with delight,
Secrets now can take their flight!
From env files tucked away home,
No more scattered, now they roam!
Centralized, with process first to see,
Then fallback files, wild and free! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.66% 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 clearly and specifically describes the main change: adding environment variable loading from ~/.agentmemory/.env for authentication in hooks and CLI, directly matching the changeset's core objective.
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

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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
…rker-auth

# Conflicts:
#	plugin/scripts/notification.mjs
#	plugin/scripts/post-tool-failure.mjs
#	plugin/scripts/post-tool-use.mjs
#	plugin/scripts/pre-compact.mjs
#	plugin/scripts/prompt-submit.mjs
#	plugin/scripts/session-start.mjs
#	plugin/scripts/subagent-start.mjs
#	plugin/scripts/subagent-stop.mjs
#	plugin/scripts/task-completed.mjs
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