Skip to content

Fix: unified environment behavior#975

Open
SSgumS wants to merge 3 commits into
rohitg00:mainfrom
SSgumS:main
Open

Fix: unified environment behavior#975
SSgumS wants to merge 3 commits into
rohitg00:mainfrom
SSgumS:main

Conversation

@SSgumS

@SSgumS SSgumS commented Jun 25, 2026

Copy link
Copy Markdown

fix(hooks): load ~/.agentmemory/.env before reading process.env

All hook scripts read AGENTMEMORY_* vars at module level (const declarations before main()). If those vars live only in ~/.agentmemory/.env and not in the shell environment or settings.json, they were silently ignored.

Fix:

  • Add src/hooks/_env.ts: synchronous .env parser that populates process.env for keys not already set (explicit env takes priority).
  • Import side-effect in src/hooks/_project.ts (already inlined first by the bundler into every hook that imports _project).
  • Direct import in the four hooks that bypass _project.ts: pre-tool-use, session-end, post-commit, stop.
  • Patch all 14 compiled plugin/scripts/*.mjs with an inline equivalent so the installed plugin works without a rebuild.

Summary by CodeRabbit

  • New Features

    • Hook and script workflows now auto-load user-local environment settings from ~/.agentmemory/.env at startup (quietly), before configuration is read—covering session, tool, stop, and related hooks.
    • Pre-set environment variables still override values from the file.
  • Bug Fixes

    • Improved startup consistency by initializing environment settings earlier across affected scripts/hooks.
    • Normalized end-of-module export formatting to improve reliable ES module behavior.

All hook scripts read AGENTMEMORY_* vars at module level (const
declarations before main()). If those vars live only in
~/.agentmemory/.env and not in the shell environment or
settings.json, they were silently ignored.

Fix:
- Add src/hooks/_env.ts: synchronous .env parser that populates
  process.env for keys not already set (explicit env takes priority).
- Import side-effect in src/hooks/_project.ts (already inlined first
  by the bundler into every hook that imports _project).
- Direct import in the four hooks that bypass _project.ts:
  pre-tool-use, session-end, post-commit, stop.
- Patch all 14 compiled plugin/scripts/*.mjs with an inline equivalent
  so the installed plugin works without a rebuild.
@vercel

vercel Bot commented Jun 25, 2026

Copy link
Copy Markdown

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

A member of the Team first needs to authorize it.

@SSgumS SSgumS changed the title Fix unified environment behavior Fix: unified environment behavior Jun 25, 2026
@coderabbitai

coderabbitai Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 47c72a48-dd27-437d-a4b3-e9d5aa5e4131

📥 Commits

Reviewing files that changed from the base of the PR and between 5fe8d5a and 0f8ede1.

📒 Files selected for processing (14)
  • 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
🚧 Files skipped from review as they are similar to previous changes (14)
  • src/hooks/_env.ts
  • plugin/scripts/session-end.mjs
  • plugin/scripts/post-commit.mjs
  • plugin/scripts/task-completed.mjs
  • plugin/scripts/stop.mjs
  • plugin/scripts/pre-compact.mjs
  • plugin/scripts/post-tool-failure.mjs
  • plugin/scripts/pre-tool-use.mjs
  • plugin/scripts/subagent-start.mjs
  • plugin/scripts/notification.mjs
  • plugin/scripts/post-tool-use.mjs
  • plugin/scripts/prompt-submit.mjs
  • plugin/scripts/subagent-stop.mjs
  • plugin/scripts/session-start.mjs

📝 Walkthrough

Walkthrough

The PR adds startup loading of ~/.agentmemory/.env into process.env across shared hooks and plugin scripts. It also adds a shared _env.ts module, wires it into hook entrypoints, and normalizes several script footers and region markers.

Changes

Environment bootstrap across hooks and scripts

Layer / File(s) Summary
Shared env loader
src/hooks/_env.ts, src/hooks/_project.ts, src/hooks/post-commit.ts, src/hooks/pre-tool-use.ts, src/hooks/session-end.ts, src/hooks/stop.ts
src/hooks/_env.ts loads ~/.agentmemory/.env into process.env, and the hook entrypoints import it for side effects.
Hook lifecycle plugin scripts
plugin/scripts/pre-compact.mjs, plugin/scripts/pre-tool-use.mjs, plugin/scripts/session-start.mjs, plugin/scripts/session-end.mjs, plugin/scripts/stop.mjs
These hook lifecycle scripts now preload ~/.agentmemory/.env at startup and normalize their trailing exports and region markers.
Post-event plugin scripts
plugin/scripts/notification.mjs, plugin/scripts/post-commit.mjs, plugin/scripts/post-tool-failure.mjs, plugin/scripts/post-tool-use.mjs, plugin/scripts/prompt-submit.mjs
These post-event scripts now preload ~/.agentmemory/.env at startup and normalize their trailing exports and region markers.
Subagent and task scripts
plugin/scripts/subagent-start.mjs, plugin/scripts/subagent-stop.mjs, plugin/scripts/task-completed.mjs
These subagent and task scripts now preload ~/.agentmemory/.env at startup and normalize their trailing exports and region markers.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I found a tiny .env in the moonlit grass,
and hopped through hooks as the values pass.
New keys twinkle in every file I see,
soft as clover and quick as can be.
Boing! The burrow hums in harmony. ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.89% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is related to the change, but "unified environment behavior" is too vague to clearly describe the main update. Use a more specific title such as "Load ~/.agentmemory/.env before hook scripts read process.env".
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
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.

@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: 2

🧹 Nitpick comments (1)
src/hooks/_env.ts (1)

8-30: 📐 Maintainability & Code Quality | 🔵 Trivial

Refactor src/hooks/_env.ts to use the existing dotenv library

The custom .env parser in src/hooks/_env.ts duplicates functionality already available via the dotenv dependency. The existing implementation manually handles whitespace, quoting, and comments while strictly avoiding the override of existing environment variables. This behavior matches dotenv.config() defaults exactly.

Replace the manual parsing logic with:

dotenv.config({ path: join(homedir(), ".agentmemory", ".env") });

This change reduces boilerplate and improves maintainability. The custom parser is still needed in src/hooks/_env.mjs (or similar bundled artifacts) if Node.js module resolution prevents dotenv usage, but can be safely removed from the source file where Node.js runtime is available.

🤖 Prompt for 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.

In `@src/hooks/_env.ts` around lines 8 - 30, `src/hooks/_env.ts` reimplements
`.env` loading manually even though `dotenv` already matches the same parsing
and non-override behavior. Update the module’s initialization logic to use
`dotenv.config()` with the existing env path built from `homedir()` and
`join()`, and remove the custom line-by-line parsing/try-catch block. Keep the
unique `envPath` construction and the `dotenv` import in place so the source
hook stays simple and consistent with the existing dependency.

Source: Coding guidelines

🤖 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 `@plugin/scripts/pre-compact.mjs`:
- Around line 6-21: The environment loader block is present in the other hook
scripts but missing from diagnostics.mjs, leaving that script inconsistent with
the shared source of truth. Update diagnostics.mjs to include the same _env
loader behavior used by pre-compact.mjs and notification.mjs, or alternatively
consolidate the loader into a shared strategy so all hook entrypoints, including
diagnostics.mjs, resolve environment variables consistently.

In `@src/hooks/_project.ts`:
- Line 3: The module initialization order in _project.ts is wrong because
"./_env.js" is imported after the node:child_process and node:path imports,
which can delay environment setup. Move the "./_env.js" import to the very top
of src/hooks/_project.ts so it runs before any other module-level imports or
initialization, matching the pattern used in stop.ts and ensuring
AGENTMEMORY_PROJECT_NAME is available immediately.

---

Nitpick comments:
In `@src/hooks/_env.ts`:
- Around line 8-30: `src/hooks/_env.ts` reimplements `.env` loading manually
even though `dotenv` already matches the same parsing and non-override behavior.
Update the module’s initialization logic to use `dotenv.config()` with the
existing env path built from `homedir()` and `join()`, and remove the custom
line-by-line parsing/try-catch block. Keep the unique `envPath` construction and
the `dotenv` import in place so the source hook stays simple and consistent with
the existing dependency.
🪄 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: a5221502-2e88-407e-89b3-8678dc224d20

📥 Commits

Reviewing files that changed from the base of the PR and between f6f9e3c and 124b5d0.

📒 Files selected for processing (19)
  • 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
  • src/hooks/_project.ts
  • src/hooks/post-commit.ts
  • src/hooks/pre-tool-use.ts
  • src/hooks/session-end.ts
  • src/hooks/stop.ts

Comment thread plugin/scripts/pre-compact.mjs
Comment thread src/hooks/_project.ts
dotenv is already a project dependency (^17.4.2) and provides the same
non-override behavior (dotenv.config() does not overwrite existing keys)
with no custom parsing or error handling needed.

@SSgumS SSgumS left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Applied the improvements

@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`:
- Line 8: The dotenv loader in the _env hook is emitting runtime banners on
stdout, which can interfere with hook protocol output. Update the dotenv.config
call in the _env setup to pass quiet: true while keeping the existing
non-override behavior unchanged, and make the same adjustment in the shared
loader path used by the generated plugin/scripts copies so the fix propagates
consistently.
🪄 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: ee0c022e-c674-458e-8ac4-4d5757bce8c5

📥 Commits

Reviewing files that changed from the base of the PR and between 124b5d0 and 5fe8d5a.

📒 Files selected for processing (14)
  • 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
🚧 Files skipped from review as they are similar to previous changes (2)
  • plugin/scripts/stop.mjs
  • plugin/scripts/post-tool-use.mjs

Comment thread src/hooks/_env.ts Outdated
dotenv v17 logs "◇ injected env (N) from ..." to stdout by default.
Hooks use stdout for protocol output (session-start writes context
there), so this banner corrupts the payload. quiet: true silences it.
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