Skip to content

Conversation

@pec1985
Copy link
Contributor

@pec1985 pec1985 commented Sep 1, 2025

Local development files (.env.development, .env.local, etc.) should never be synced to the production database. This was causing the CLI to prompt users to sync development-only environment variables to their cloud project.

The fix adds a conditional check to only call HandleMissingProjectEnvs when not in local development mode (isLocalDev = false).

Fixes issue where users were getting prompted to sync env vars from .env.development files to production.

Amp-Thread-ID: https://ampcode.com/threads/T-94a6a673-ef07-4dbd-95a8-8437d17bdd21

Summary by CodeRabbit

  • Bug Fixes
    • Prevents syncing missing project environment variables to production when running in local development, reducing risk of unintended production changes.
  • New Features
    • Improved user prompts: environment file names are shown, messages correctly pluralize variables, and a muted note clarifies opting out won’t affect local development.

Local development files (.env.development, .env.local, etc.) should never
be synced to the production database. This was causing the CLI to prompt
users to sync development-only environment variables to their cloud project.

The fix adds a conditional check to only call HandleMissingProjectEnvs
when not in local development mode (isLocalDev = false).

Fixes issue where users were getting prompted to sync env vars from
.env.development files to production.

Co-authored-by: Amp <amp@ampcode.com>
Amp-Thread-ID: https://ampcode.com/threads/T-94a6a673-ef07-4dbd-95a8-8437d17bdd21
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 1, 2025

Walkthrough

ProcessEnvFiles now accepts an isLocalDev flag and only calls HandleMissingProjectEnvs when not in local development. HandleMissingProjectEnvs signature was extended to receive envFilename; user-facing messages were updated to reference the actual env file name and adjusted wording for singular/plural cases and muted-notes.

Changes

Cohort / File(s) Summary
Env handling & prompts
internal/envutil/envutil.go
Added isLocalDev parameter to ProcessEnvFiles to skip project sync when local; updated HandleMissingProjectEnvs signature to accept envFilename; compute envFileDisplayName; update user-facing messages (singular/plural text, prompt phrasing, muted note) and pass envFilename into prompts.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant CLI as CLI
  participant EnvUtil as envutil.ProcessEnvFiles
  participant Handler as envutil.HandleMissingProjectEnvs
  participant ProjectAPI as Project API

  CLI->>EnvUtil: call ProcessEnvFiles(..., isLocalDev, envFilename)
  EnvUtil->>EnvUtil: load local env lines
  EnvUtil->>EnvUtil: compute envFileDisplayName from envFilename

  alt isLocalDev == false
    EnvUtil->>Handler: HandleMissingProjectEnvs(..., envFilename)
    Handler->>ProjectAPI: query/set project envs (prompt user)
    ProjectAPI-->>Handler: result
  else isLocalDev == true
    note over EnvUtil: Skip calling HandleMissingProjectEnvs (no project sync)
  end

  EnvUtil-->>CLI: return env file & project data
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Prevent syncing/setting project (production) env vars during local development [AGENT-628]
Clarify environment labeling/counts (e.g., .env vs .env.development.local) in CLI outputs [AGENT-628]
Clarify prompt wording (“set them where?”) to specify target environment [AGENT-628]
Confirm local env vars remain functional when declining to set project vars [AGENT-628] Behavior implied (skip sync) but no explicit tests or runtime confirmation added.

Out-of-scope changes

(None identified)

Possibly related PRs

Suggested reviewers

  • potofpie
  • jhaynie

Poem

I nibbled notes beside the burrow door,
“Keep local safe — don’t push to more.”
Carrots named clear, no prod surprise,
I hop away with bright-eyed sighs. 🥕

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch AGENT-628

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai bot requested a review from potofpie September 1, 2025 15:27
Copy link
Contributor

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

Caution

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

⚠️ Outside diff range comments (1)
internal/envutil/envutil.go (1)

185-185: Fix grammar in user-facing text

“are not been set” ➜ “are not set”.

-        title = fmt.Sprintf("The environment variables %s from %s are not been set in the project.", strings.Join(colorized, ", "), tui.Bold(".env"))
+        title = fmt.Sprintf("The environment variables %s from %s are not set in the project.", strings.Join(colorized, ", "), tui.Bold(".env"))
🧹 Nitpick comments (3)
internal/envutil/envutil.go (3)

69-73: Good guard; add a debug trace when skipping

Add a small debug log so operators can confirm why project env syncing was skipped.

-        // Only sync env vars to production when not in local development mode
-        // Local development files (.env.development, .env.local, etc.) should never be synced to production
-        if !isLocalDev {
-            projectData = HandleMissingProjectEnvs(ctx, logger, le, projectData, theproject, apiUrl, token, force)
-        }
+        // Only sync env vars to the project (cloud/production) when not in local development mode.
+        if isLocalDev {
+            logger.Debug("Skipping project env sync from local env file to production (isLocalDev=true)")
+        } else {
+            projectData = HandleMissingProjectEnvs(ctx, logger, le, projectData, theproject, apiUrl, token, force)
+        }

106-117: Make messages reflect the actual env file in use

These prompts always say “.env” even when operating on .env.development. Use the provided envfilename to avoid confusion.

-          para = append(para, fmt.Sprintf("The variable %s was found in %s but not in your %s file:\n", tui.Bold(ev.Key), tui.Bold(filename), tui.Bold(".env")))
+          para = append(para, fmt.Sprintf(
+            "The variable %s was found in %s but not in your %s file:\n",
+            tui.Bold(ev.Key), tui.Bold(filename), tui.Bold(filepath.Base(envfilename)),
+          ))
...
-          if !tui.Ask(logger, "Would you like to add it to your .env file?", true) {
+          if !tui.Ask(logger, fmt.Sprintf(
+            "Would you like to add it to your %s file?",
+            filepath.Base(envfilename),
+          ), true) {

199-199: Clarify destination to match PR objective

Make it explicit that acceptance sets values in the cloud/production project, not the local env file.

-      force = tui.Ask(logger, "Would you like to set "+suffix+" now?", true)
+      force = tui.Ask(logger, "Would you like to set "+suffix+" in the project (cloud/production) now?", true)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 697720d and 4bc9efc.

📒 Files selected for processing (1)
  • internal/envutil/envutil.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Test Install Script (macos-latest)
  • GitHub Check: Build and Test (macos-latest)
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
internal/envutil/envutil.go (1)

69-73: isLocalDev usage verified
All callers of ProcessEnvFiles pass isLocalDev correctly (true in cmd/dev.go, false in cmd/project.go and cmd/cloud.go), so no changes required.

@pec1985 pec1985 changed the title fix: prevent local development env files from syncing to production [AGENT-628] prevent local development env files from syncing to production Sep 1, 2025
@coderabbitai coderabbitai bot requested a review from jhaynie September 1, 2025 15:44
Copy link
Contributor

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

Caution

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

⚠️ Outside diff range comments (2)
internal/envutil/envutil.go (2)

41-49: Create .env.development with 0600 perms and handle write/close errors.

Env files can contain secrets; ensure strict perms and check errors.

Apply:

-			of, err := os.Create(f)
+			of, err := os.OpenFile(f, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
 			if err != nil {
 				errsystem.New(errsystem.ErrInvalidConfiguration, err, errsystem.WithContextMessage("Failed to create .env.development file")).ShowErrorAndExit()
 			}
-			defer of.Close()
-			of.WriteString("# This file is used to store development environment variables\n")
+			defer func() { _ = of.Close() }()
+			if _, werr := of.WriteString("# This file is used to store development environment variables\n"); werr != nil {
+				errsystem.New(errsystem.ErrInvalidConfiguration, werr, errsystem.WithContextMessage("Failed to write to .env.development file")).ShowErrorAndExit()
+			}

106-110: Use the active env file name in messages (not hard-coded “.env”).

Aligns with PR objective to clarify which file is being referenced.

Apply:

-					para = append(para, fmt.Sprintf("The variable %s was found in %s but not in your %s file:\n", tui.Bold(ev.Key), tui.Bold(filename), tui.Bold(".env")))
+					envFileDisplayName := tui.Bold(filepath.Base(envfilename))
+					para = append(para, fmt.Sprintf("The variable %s was found in %s but not in your %s file:\n", tui.Bold(ev.Key), tui.Bold(filename), envFileDisplayName))
-			tui.ShowSuccess("added %s to your .env file", util.Pluralize(len(addtoenvfile), "environment variable", "environment variables"))
+			envFileDisplayName := tui.Bold(filepath.Base(envfilename))
+			tui.ShowSuccess("added %s to your %s file", util.Pluralize(len(addtoenvfile), "environment variable", "environment variables"), envFileDisplayName)

Also applies to: 148-150

🧹 Nitpick comments (3)
internal/envutil/envutil.go (3)

156-203: Deterministic ordering for multi-key display.

Map iteration order is random; sort keys to avoid UI flicker.

Apply:

-				var colorized []string
-				for key := range keyvalue {
-					colorized = append(colorized, tui.Bold(key))
-				}
+				keys := make([]string, 0, len(keyvalue))
+				for k := range keyvalue {
+					keys = append(keys, k)
+				}
+				sort.Strings(keys)
+				colorized := make([]string, 0, len(keys))
+				for _, k := range keys {
+					colorized = append(colorized, tui.Bold(k))
+				}

And add import:

// at top imports
import "sort"

175-207: Avoid reusing “force” for user consent.

Use a new var to keep semantics clear (force=automation, consent=prompt).

Apply:

-			force = tui.Ask(logger, question, true)
+			consent := tui.Ask(logger, question, true)
+			force = consent

35-50: Consider broader local env precedence (.env.development.local, .env.local).

If relevant to your workflow, prefer a small precedence chain for local files.

Example:

-	if isLocalDev {
-		f := filepath.Join(dir, ".env.development")
-		if util.Exists(f) {
-			envfilename = f
+	if isLocalDev {
+		for _, name := range []string{".env.development.local", ".env.local", ".env.development"} {
+			f := filepath.Join(dir, name)
+			if util.Exists(f) {
+				envfilename = f
+				break
+			}
+		}
+		if envfilename == filepath.Join(dir, ".env") {
+			// create .env.development if none of the above exist
+			f := filepath.Join(dir, ".env.development")
+			// (creation as per secure 0600 version suggested above)
 			} else {
 				// create it but don't load it -- this is required because uv expects a .env.development file to exist from the template
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 4bc9efc and 1c1d569.

📒 Files selected for processing (1)
  • internal/envutil/envutil.go (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
internal/envutil/envutil.go (1)
internal/project/project.go (1)
  • ProjectData (44-53)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Build and Test (macos-latest)
  • GitHub Check: Analyze (go)
🔇 Additional comments (2)
internal/envutil/envutil.go (2)

205-207: Nice touch on the muted opt-out note.

Clear UX that declining won’t affect local dev.


69-73: Production-sync guard LGTM — all ProcessEnvFiles callers pass isLocalDev correctly (false in project/cloud commands, true in dev).

@pec1985 pec1985 requested a review from robindiddams September 1, 2025 20:00
@pec1985 pec1985 merged commit dff9460 into main Sep 1, 2025
14 checks passed
@pec1985 pec1985 deleted the AGENT-628 branch September 1, 2025 21:02
@coderabbitai coderabbitai bot mentioned this pull request Sep 1, 2025
devin-ai-integration bot added a commit that referenced this pull request Sep 24, 2025
- Added: [AGENT-684] Check if zsh is installed before adding autocomplete in the CLI (#450)
- Added: [AGENT-628] Unit tests (#441)
- Added: feat: automatically add AGENTUITY_SDK_KEY and AGENTUITY_PROJECT_KEY to .env file when running dev command (#442)
- Changed: Dont sort releases by commit msg (#447)
- Changed: [AGENT-628] prevent local development env files from syncing to production (#440)
- Fixed: Fix npm workspaces (#451)
- Fixed: Fix 'Press any key to continue' to accept any key, not just Enter (#445)

Co-Authored-By: unknown <>
jhaynie pushed a commit that referenced this pull request Sep 24, 2025
- Added: [AGENT-684] Check if zsh is installed before adding autocomplete in the CLI (#450)
- Added: [AGENT-628] Unit tests (#441)
- Added: feat: automatically add AGENTUITY_SDK_KEY and AGENTUITY_PROJECT_KEY to .env file when running dev command (#442)
- Changed: Dont sort releases by commit msg (#447)
- Changed: [AGENT-628] prevent local development env files from syncing to production (#440)
- Fixed: Fix npm workspaces (#451)
- Fixed: Fix 'Press any key to continue' to accept any key, not just Enter (#445)

Co-Authored-By: unknown <>

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
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.

3 participants