# How to Troubleshoot "Claude Code Directory Not Found" Error During Analytics Startup

> Fix the 'Claude Code directory not found' error during analytics startup. Learn how to resolve this common issue with your davila7/claude-code-templates repository.

- Repository: [Daniel Avila/claude-code-templates](https://github.com/davila7/claude-code-templates)
- Tags: how-to-guide
- Published: 2026-04-26

---

**The "Claude Code directory not found" error occurs when the CLI cannot locate the `.claude` folder in your home directory, preventing the analytics engine from initializing its data store.**

When launching the analytics dashboard in the davila7/claude-code-templates repository, the CLI performs strict validation of the local `.claude` directory before starting subsystems. If this validation fails, the process exits immediately with an explicit error message to prevent obscure file-system failures later in the pipeline. This guide explains how to resolve the startup failure by ensuring the directory exists, verifying permissions, and configuring environment-specific paths.

## What Triggers the "Claude Code Directory Not Found" Error

The error is raised by three entry points that share the same validation logic: the **analytics engine**, the **plugin dashboard**, and the **health-check utility**. Each component constructs the directory path using `path.join(os.homedir(), '.claude')` and validates existence before proceeding.

### Analytics Engine Validation

In [`cli-tool/src/analytics.js`](https://github.com/davila7/claude-code-templates/blob/main/cli-tool/src/analytics.js), the constructor assigns `this.claudeDir` and immediately checks `fs.pathExists(this.claudeDir)`. If the check returns `false`, the initialization step throws:

```js
throw new Error(`Claude Code directory not found at ${this.claudeDir}`);

```

This early-fail design prevents the conversation analyzer, file watchers, and WebSocket server from operating on a non-existent data store.

### Plugin Dashboard and Health-Check Implications

The **PluginDashboard** class in [`cli-tool/src/plugin-dashboard.js`](https://github.com/davila7/claude-code-templates/blob/main/cli-tool/src/plugin-dashboard.js) replicates the same check during its `initialize()` method, throwing an identical error to maintain UI consistency.

Meanwhile, [`cli-tool/src/health-check.js`](https://github.com/davila7/claude-code-templates/blob/main/cli-tool/src/health-check.js) provides a non-blocking alternative via `checkClaudeDirectory()`, which returns a **warn** status when `fs.existsSync(claudeDir)` is false rather than throwing. This allows CI pipelines to detect the issue without crashing the process.

## Why the .claude Directory May Be Missing

Several scenarios cause the directory validation to fail:

- **First-time execution** – The `.claude` folder is created only after a Claude-enabled command writes settings or data. Starting analytics before any other command leaves the directory uninitialized.
- **Accidental deletion** – Users occasionally remove hidden folders via cleanup scripts or manual maintenance.
- **Permission issues** – The folder exists but the current user lacks read/write access, common on macOS or Linux when the directory is owned by another UID.
- **Non-standard home directories** – In containerized shells or CI environments, `os.homedir()` may point to a location that never receives the `.claude` directory.

## Step-by-Step Resolution Guide

Follow these steps to eliminate the error and restore analytics functionality.

### Confirm the Expected Directory Location

Verify that the CLI's expected path matches your system configuration:

```bash
echo "$(python -c 'import os; print(os.path.expanduser("~"))')/.claude"

```

Compare the output against the path shown in the error message. If they differ, your shell environment may be overriding the home directory.

### Create the Directory Manually

Create the missing directory with restrictive permissions to satisfy the existence check:

```bash
mkdir -p "$HOME/.claude"
chmod 700 "$HOME/.claude"

```

This temporary fix allows the analytics engine to start, though the directory may lack required subfolders.

### Verify Permissions with the Health-Check Utility

Run the built-in diagnostic to confirm read/write access:

```bash
npx claude-code-templates --health

```

A passing status displays `Claude directory permissions OK`. If you see *warn* or *fail*, correct ownership:

```bash
sudo chown -R "$(whoami)":"$(id -gn)" "$HOME/.claude"
chmod -R u+rwX "$HOME/.claude"

```

### Populate the Directory with Required Subfolders

Trigger a normal initialization to create the standard directory structure (`statsig`, `plugins`, etc.):

```bash
npx claude-code-templates --settings init

```

This populates the data store that the analytics engine expects, preventing secondary errors after the initial directory check passes.

### Handle CI and Container Environments

In environments where `os.homedir()` points to a non-writable location, override the home directory temporarily:

```bash
export CLAUDE_HOME="/tmp/claude"
mkdir -p "$CLAUDE_HOME"
export HOME="$CLAUDE_HOME"  # Forces os.homedir() to use the writable path

npx claude-code-templates --analytics

```

Note that the codebase currently only respects `os.homedir()` and does not natively support a `CLAUDE_HOME` environment variable.

## Preventive Measures

Implement these practices to avoid future startup failures:

- **Never delete** `$HOME/.claude` manually; use the `settings` sub-command (`npx claude-code-templates --settings clear`) to purge data while preserving the directory structure.
- **Add a pre-flight hook** in CI pipelines that executes `node cli-tool/src/health-check.js` before launching analytics, ensuring the directory exists and permissions are correct.
- **Backup persistent data** periodically using `tar -czf claude-backup.tgz $HOME/.claude` if you rely on historical analytics data.

## Code Examples

### Minimal Pre-Flight Script

Use this Node.js script to ensure the directory exists before starting analytics:

```js
// ensure-claude-dir.js
const fs = require('fs-extra');
const os = require('os');
const path = require('path');

(async () => {
  const claudeDir = path.join(os.homedir(), '.claude');
  if (!await fs.pathExists(claudeDir)) {
    await fs.mkdirp(claudeDir);
    console.log('Created missing Claude directory at', claudeDir);
  }
  
  const Analytics = require('./cli-tool/src/analytics');
  const analytics = new Analytics({ verbose: true });
  await analytics.initialize();
})();

```

Execute with:

```bash
node ensure-claude-dir.js

```

### CI Environment Wrapper

For automated pipelines, use this bash wrapper to guarantee a writable directory:

```bash
#!/usr/bin/env bash

# ci-claude-setup.sh

set -e

export HOME="${HOME:-/tmp/claude}"
mkdir -p "$HOME/.claude"
chmod 700 "$HOME/.claude"

# Verify health before starting

node ./cli-tool/src/health-check.js | grep '"status":"pass"' || {
  echo "❌ Claude directory not ready"
  exit 1
}

# Launch analytics

npx claude-code-templates --analytics

```

## Summary

- The "Claude Code directory not found" error is a deliberate guard clause in [`cli-tool/src/analytics.js`](https://github.com/davila7/claude-code-templates/blob/main/cli-tool/src/analytics.js) that protects the system from operating on non-existent data stores.
- The CLI expects the directory at `path.join(os.homedir(), '.claude')` and validates it before initializing subsystems like the conversation analyzer and WebSocket server.
- Resolution requires creating the directory manually, verifying permissions with the health-check utility, and populating required subfolders via `--settings init`.
- Container and CI environments may require overriding `HOME` to ensure `os.homedir()` returns a writable path.

## Frequently Asked Questions

### What is the exact path where the CLI looks for the Claude directory?

The CLI constructs the path using `path.join(os.homedir(), '.claude')` as implemented in [`cli-tool/src/analytics.js`](https://github.com/davila7/claude-code-templates/blob/main/cli-tool/src/analytics.js). On most systems, this resolves to `~/.claude` or `/home/<username>/.claude`, but it varies if the `HOME` environment variable is customized.

### Can I change the location of the .claude directory?

Currently, the codebase hardcodes the dependency on `os.homedir()` and does not support a custom `CLAUDE_HOME` environment variable. To use a different location, you must override the `HOME` environment variable before launching the CLI, or modify the source in [`cli-tool/src/analytics.js`](https://github.com/davila7/claude-code-templates/blob/main/cli-tool/src/analytics.js) to accept an alternative path.

### Why does the analytics engine fail immediately instead of creating the directory automatically?

The early-fail design in [`analytics.js`](https://github.com/davila7/claude-code-templates/blob/main/analytics.js) prevents the system from operating on a corrupted or permission-restricted data store. By throwing `new Error(\`Claude Code directory not found at ${this.claudeDir}\`)` immediately, the CLI avoids obscure file-system errors that would occur later when subsystems attempt to write to `statsig` or `plugins` subdirectories.

### How do I fix permission denied errors after creating the directory?

If the health-check reports permission issues despite the directory existing, run `sudo chown -R "$(whoami)":"$(id -gn)" "$HOME/.claude"` followed by `chmod -R u+rwX "$HOME/.claude"`. This ensures the current user owns the directory and has read, write, and execute permissions necessary for the analytics engine to create subfolders and log files.