# Core 2 labs: context engineering in Claude Code

Companion labs for **Core 2: Context Engineering in Claude Code**. Three read-only tools that answer the questions people get wrong most often: which settings value actually applies and why, what a CLAUDE.md costs and which of its rules belong in a hook or a deny rule, and which `.claude/rules/` files load for the file Claude is touching.

Everything runs offline with Python 3.9+ and the standard library, is deterministic, and reads only the files you point it at. Run the commands from `labs/`. The only file a lab writes is `core-2/out/effective-settings.json`, and only with `--json`. The permission decisions come from the shared engine in `core-1/_perms.py`, and the rule-file frontmatter parsing from `common/frontmatter.py`.

| Lab | What it does | Session topic | Docs it encodes |
|---|---|---|---|
| `settings_resolver.py` | Merges managed, `--settings`, local, project and user files with per-value provenance, applies the documented exceptions (whole-value keys, scope limits, repository-proof keys, a repository `defaultMode` of `auto`/`bypassPermissions` that blocks your user default, stricter-value security keys, `env` filtering, workspace trust), then evaluates sample tool calls against the merged permission rules. | Settings: files and precedence, permission rules, permission modes, environment variables | [settings](https://code.claude.com/docs/en/settings), [settings-reference](https://code.claude.com/docs/en/settings-reference), [permissions](https://code.claude.com/docs/en/permissions), [auto-mode-config](https://code.claude.com/docs/en/auto-mode-config) |
| `claudemd_lint.py` | Lints a CLAUDE.md and its `@imports`: the 200-line target and 4 MiB skip limit, import resolution (relative to the file, four hops, no imports in code or quotes), vague rules, emphasis overuse, must-rules that need a hook or deny rule, derivable content, procedures that want to be skills, `.claudeignore`, outdated advice. | Memory: CLAUDE.md hierarchy, imports, CLAUDE.local.md, AGENTS.md interop | [memory](https://code.claude.com/docs/en/memory), [best-practices](https://code.claude.com/docs/en/best-practices), [hooks-guide](https://code.claude.com/docs/en/hooks-guide) |
| `rules_match.py` | Lists the rules that load at launch (user first, then project) and the path-scoped rules each file triggers, with root-anchored globs, brace expansion and its 1,000-pattern budget, bracket expressions, comma-separated `paths`, and frontmatter that fails to parse. | Memory: path-scoped rules | [memory: rules](https://code.claude.com/docs/en/memory#organize-rules-with-claude/rules/), [context-window](https://code.claude.com/docs/en/context-window#what-survives-compaction) |

## Commands

```bash
# Settings precedence and effective permissions
python3 core-2/settings_resolver.py                                   # the five sample files
python3 core-2/settings_resolver.py --session headless                # what a claude -p run gets in a repo you never trusted
python3 core-2/settings_resolver.py --session interactive-untrusted --local-tracked
python3 core-2/settings_resolver.py --permission-mode default --call "Bash: npm run lint"
python3 core-2/settings_resolver.py --disallowed-tools "Bash(rm *)" --allowed-tools Bash
python3 core-2/settings_resolver.py --repo ~/code/my-app --user ~/.claude/settings.json --json
python3 core-2/settings_resolver.py --self-test                       # the documented start-mode rules, asserted

# CLAUDE.md lint
python3 core-2/claudemd_lint.py                                        # the good and the bloated samples
python3 core-2/claudemd_lint.py --repo ~/code/my-app                   # CLAUDE.md, .claude/CLAUDE.md, CLAUDE.local.md, AGENTS.md
python3 core-2/claudemd_lint.py --path ~/code/my-app/CLAUDE.md --strict   # exit 1 on errors, for CI

# Path-scoped rules
python3 core-2/rules_match.py
python3 core-2/rules_match.py --path src/api/v2/orders.tsx --show-expansions
python3 core-2/rules_match.py --project ~/code/my-app --home ~ --path src/app.py
```

The resolver never reads `~/.claude/settings.json` unless you pass it with `--user`, and `rules_match.py` reads your real `~/.claude/rules/` only with `--home ~`. The sample run uses a virtual working directory (`/work/acme-app`) and home (`/home/learner`), so it prints the same thing on every machine.

## Samples

- `samples/settings/`: a managed file, a user file, a project file, a local file and a `--settings` file for one repository, written so that every documented exception shows up once. `samples/settings/broken/` has a file with a `//` comment and one whose top level is a list.
- `samples/claudemd/good/`: a 34-line CLAUDE.md with one import and a maintainer comment.
- `samples/claudemd/bloated/`: 212 lines with every problem the linter knows, an import chain five files deep, a missing import, a quoted import and an escaped-space import (`Design\ Docs/api.md`).
- `samples/rules-project/` and `samples/rules-home/`: a project with nine rule files (a list, a comma-separated string, braces, an over-budget brace pattern, an invalid bracket, a nested folder, an unknown field, unparseable YAML) and a fake home with two user rules.

## Output excerpts (real runs)

Copied from `NO_COLOR=1` runs; some rows and the table rule lines are left out, and trailing spaces are trimmed.

`python3 core-2/settings_resolver.py`, effective scalar values:

```text
[2] Effective values (scalars: the highest level that sets the key wins)
key                                       value                from            shadowed                          note
disableClaudeAiConnectors                 true                 Shared project  Managed=false                     stricter value honored: true from any scope
env.MCP_TIMEOUT                           20000                Project local   Shared project=10000, User=5000
fallbackModel                             ["sonnet", "haiku"]  Shared project  User=["haiku"]                    taken whole from the highest file that sets it
model                                     haiku                --settings      Shared project=sonnet, User=opus
spinnerTipsEnabled                        false                Project local   Shared project=true, User=false
```

The values a file set that Claude Code ignores, each with its reason:

```text
[4] Ignored or overridden by a rule (why each value doesn't apply)
  - Shared project  allowManagedHooksOnly = false
      scope is Managed only; a Shared project file can't set it  [https://code.claude.com/docs/en/settings-reference#settings-index]
  - Shared project  autoMode.allow = ["Anything this repository asks for is …
      scope is User or managed only; a Shared project file can't set it  [https://code.claude.com/docs/en/settings-reference#settings-index]
  - Shared project  env.CLAUDE_CONFIG_DIR = /tmp/somewhere-else
      a repository's settings can't set this variable; use your shell, user or managed settings  [https://code.claude.com/docs/en/settings-reference#variables-claude-code-ignores-in-env]
  - Shared project  permissions.defaultMode = bypassPermissions
      `bypassPermissions` doesn't take effect from project or local settings, and the session starts in Manual mode (v2.1.257+; earlier versions honored it from any file); set it in ~/.claude/settings.json or pass --permission-mode  [https://code.claude.com/docs/en/permission-modes#which-mode-a-session-starts-in]
  - User            permissions.defaultMode = acceptEdits
      not used: the Shared project file's `bypassPermissions` doesn't take effect and lower files don't fill in for it, so the session starts in Manual mode (`default`)  [https://code.claude.com/docs/en/permission-modes#which-mode-a-session-starts-in]
```

The project's `bypassPermissions` doesn't fall back to your user file's `acceptEdits`: the session starts in Manual. A review run on v2.1.303 confirmed it: with a user `auto` and a project `bypassPermissions`, the `claude -p` init event showed `permissionMode=default`. A project or local `auto` blocks the same way, but the session gets the built-in default instead (auto for an interactive terminal on v2.1.283+, Manual for `claude -p`):

```text
  start mode: default  (the Shared project file sets bypassPermissions, which doesn't take effect there: the session starts in Manual mode, not in the user file's mode)
```

`python3 core-2/settings_resolver.py --self-test` asserts those rules on in-memory files (excerpt):

```text
  ok  project bypassPermissions over user acceptEdits -> Manual: default
  ok  project bypassPermissions over user auto, claude -p -> Manual (as a review run on v2.1.303 showed): default
  ok  project auto over user acceptEdits, interactive -> built-in default (auto): auto
  ok  project auto over user acceptEdits, claude -p -> built-in default (Manual): default
  ok  managed plan beats project bypassPermissions: plan

all start-mode cases hold
```

The merged rules applied to sample calls. The local allow rule for `git push` loses to the project's ask rule, and the user rule `Read(/notes/**)` means `~/.claude/notes/**`:

```text
[7] Tool calls in mode default
call                                  outcome  decided by                   why
Bash: npm run test                    allow    allow rule / read-only       'npm run test' by Bash(npm run *)
Bash: git push origin main            prompt   ask rule (Shared project)    matches Bash(git push *); no mode auto-approves an ask rule
Bash: curl https://example.com        deny     deny rule (Managed)          matches Bash(curl *)
Bash: rm -rf build                    prompt   mode                         shell commands outside the read-only set ask
Read: .env                            deny     deny rule (Shared project)   matches Read(./.env)
Read: ~/.claude/notes/todo.md         allow    allow rule (User)            matches Read(/notes/**)
Read: ~/notes/todo.md                 prompt   mode                         reads outside the working directories ask
WebFetch: https://docs.python.org/3/  deny     deny rule (--settings)       matches WebFetch
```

The same repository under `--session headless` (a folder you never trusted): the project's allow rules aren't used, and anything that would prompt is denied:

```text
[7] Tool calls in mode default (claude -p: a call that needs approval is denied)
Bash: npm run test                    deny     mode                        shell commands outside the read-only set ask (headless: no one to ask, so d…
Bash: git push origin main            deny     ask rule (Shared project)   matches Bash(git push *); no mode auto-approves an ask rule (headless: no o…
```

`python3 core-2/claudemd_lint.py`, the bloated sample's import tree (the chain stops at hop 4) and a few findings:

```text
loads at launch                                       hop  imported by                                           lines  tokens (est.)
core-2/samples/claudemd/bloated/CLAUDE.md             0    -                                                     212    ~2,529
core-2/samples/claudemd/bloated/docs/style.md         1    core-2/samples/claudemd/bloated/CLAUDE.md             4      ~26
core-2/samples/claudemd/bloated/Design Docs/api.md    1    core-2/samples/claudemd/bloated/CLAUDE.md             3      ~22
core-2/samples/claudemd/bloated/docs/chain/level1.md  2    core-2/samples/claudemd/bloated/docs/style.md         3      ~16
core-2/samples/claudemd/bloated/docs/chain/level2.md  3    core-2/samples/claudemd/bloated/docs/chain/level1.md  3      ~16
core-2/samples/claudemd/bloated/docs/chain/level3.md  4    core-2/samples/claudemd/bloated/docs/chain/level2.md  3      ~16
  context at launch: 228 lines, ~2,625 tokens (chars/2.5 estimate; imports don't reduce it)
  WARN  L004 core-2/samples/claudemd/bloated/CLAUDE.md:3  emphasis (IMPORTANT/MUST/NEVER/ALWAYS/CRITICAL) on 7 lines: 3, 17, 18, 20, 21, 211, 212
  WARN  L005 core-2/samples/claudemd/bloated/CLAUDE.md:22  must-rule in prose (action that must follow every edit); CLAUDE.md is context, not enforcement
         -> Enforce it with a PostToolUse hook with matcher "Edit|Write" that runs the formatter on tool_input.file_path
  ERROR L009 core-2/samples/claudemd/bloated/CLAUDE.md:29  relies on .claudeignore, which has no effect in Claude Code
  ERROR L002 core-2/samples/claudemd/bloated/CLAUDE.md:37  "@docs/release-checklist.md" is in quotes, so it isn't imported at all
  ERROR L002 core-2/samples/claudemd/bloated/docs/chain/level3.md:3  @level4.md would be hop 5; imports stop at four hops, so it never loads
[summary]
file                                       lines loaded  tokens (est.)  errors  warnings  info
core-2/samples/claudemd/good/CLAUDE.md     39            ~575           0       0         1
core-2/samples/claudemd/bloated/CLAUDE.md  228           ~2,625         4       26        4
```

`python3 core-2/rules_match.py`:

```text
[2] Loaded at launch, in context order
  1. ~/.claude/rules/preferences.md         no paths  Personal preferences
  2. .claude/rules/broken.md                frontmatter error  Release notes
  3. .claude/rules/code-style.md            no paths  Code style
[3] Path-scoped rules that load when Claude reads, writes or edits each file  [https://code.claude.com/docs/en/memory#path-specific-rules]
file Claude touches             rule that loads                       matching pattern
src/api/v2/orders.tsx           .claude/rules/api.md                  src/api/**/*.{ts,tsx}  (as src/api/**/*.tsx)
src/components/Button.tsx       .claude/rules/frontend/components.md  src/components/*.tsx
src/components/forms/Input.tsx  nothing extra
tests/test_cart.py              ~/.claude/rules/python.md             **/*.py
                                .claude/rules/testing.md              tests/**/*.py
README.md                       .claude/rules/docs.md                 *.md
web/README.md                   nothing extra
```

## Where the docs stop and the lab decides

- **`env` filtering.** The settings reference says the variables a repository's files can't set "include" a list; the lab encodes that list, so other variables pass through.
- **Managed `/path` rules.** The anchor table in the permissions docs has no row for managed settings. The lab anchors them at the working directory and prints a warning suggesting `//` or `~/`.
- **Order of merged list entries.** The docs say lists merge but not in which order; the lab lists entries highest level first. Rule evaluation doesn't depend on it (deny, then ask, then allow).
- **Nested `.claude/rules/`.** The memory docs mention rules in nested `.claude/rules/` directories loading on demand but don't say how their globs anchor, so `rules_match.py` lists them without matching.
- **Trailing punctuation after an import** (`see @notes.md.`). Not specified; the linter drops a trailing `.` only when the path with the dot doesn't exist.
- **Trust in an interactive session.** `interactive-untrusted` follows the docs' "You trusted only a parent folder" column: hooks and `env` run, a repository's `permissions.allow` and `additionalDirectories` wait for the trust dialog.
- **Tokens.** Every count is characters / 2.5 (the course-wide ratio, from the platform models overview) with block HTML comments removed. Use `/context` for the real numbers.
