Claude Code Regex Checks for an Obsidian Vault
You can put three regex checks between Claude Code and an Obsidian vault by routing file changes through a small validation script. The checks can block writes that contain unwanted paths, unsafe Markdown content, or text that breaks your vault’s conventions. Claude Code’s hooks are the practical place to enforce this; first make a backup and test against a disposable vault.
What You’ll Need
- Claude Code installed and working in a project directory.
- An Obsidian vault folder and permission to edit the Claude Code project’s settings.
- Node.js available in your terminal, so you can run a small script without adding a package.
- A backup or test copy of the vault. Regex checks are not a substitute for a backup or a security boundary against a user who can edit the script.
Step-by-Step
- Decide exactly what each check should reject. Keep the checks narrow and write down examples that should pass and fail. This guide uses three illustrative rules: block writes to files outside the vault, reject a Markdown file containing a prohibited marker such as
[DO NOT SAVE], and reject a file containing a line longer than 500 characters. Change these examples to match your own workflow. A regex can identify text patterns; it cannot reliably validate every Markdown structure or determine whether content is appropriate. - Make a test vault and note its absolute path. Copy a few representative notes into a separate folder, such as
/home/sam/ObsidianTeston Linux or macOS, orC:\Users\Sam\ObsidianTeston Windows. Use the real absolute path in the script. Do not start by pointing an untested hook at your only copy of the vault. - Create a validation script in the Claude Code project. Make a file named
check-vault-write.mjsin the project’s trusted configuration or scripts folder. Claude Code PreToolUse hooks receive tool details on standard input; the script below reads the hook event, checks Write and Edit destinations, and exits with a blocking response when a rule fails. Replace the example path before use. - Add the three regex checks. This example assumes Claude Code’s hook input includes a JSON object with a
tool_nameandtool_input; it safely allows unrelated tools and blocks a write if it cannot parse a relevant event. Check the current Claude Code hook documentation for the exact event schema supported by your installed version.
#!/usr/bin/env node
import fs from 'node:fs';
import path from 'node:path';
const VAULT = '/home/sam/ObsidianTest'; // Replace with your absolute vault path
const input = JSON.parse(fs.readFileSync(0, 'utf8'));
const tool = input.tool_name;
if (tool !== 'Write' && tool !== 'Edit') process.exit(0);
const args = input.tool_input ?? {};
const file = args.file_path;
if (typeof file !== 'string') {
console.error('Blocked: could not identify the target file.');
process.exit(2);
}
const root = path.resolve(VAULT);
const target = path.resolve(file);
if (target !== root && !target.startsWith(root + path.sep)) {
console.error('Blocked: target is outside the approved vault.');
process.exit(2);
}
// Checks 2 and 3 inspect text supplied by Write or the replacement in Edit.
const text = typeof args.content === 'string' ? args.content :
typeof args.new_string === 'string' ? args.new_string : '';
const checks = [
{ re: /\[DO NOT SAVE\]/i, message: 'Blocked marker found.' },
{ re: /^.{501,}$/m, message: 'A line exceeds 500 characters.' }
];
for (const check of checks) {
if (check.re.test(text)) {
console.error(`Blocked: ${check.message}`);
process.exit(2);
}
}
process.exit(0);
- Adjust the script for Edit behavior. The example checks the replacement string passed to Edit, not necessarily the entire resulting note. If your hook event does not supply enough text to assess the final file, do not assume the content checks are complete. Use a hook stage and documented input that provides the resulting content, or validate the file after the change with a separate process. Keep the path check in place either way.
- Register a PreToolUse hook. In the Claude Code project, create or edit
.claude/settings.jsonand add a hook for thePreToolUseevent. Configure its matcher for the file-writing tools you want to cover, typicallyWrite|Edit, and runnode /absolute/path/to/check-vault-write.mjs. Follow the current settings schema for the hook command and matcher; preserve existing settings rather than replacing the whole file. Use an absolute script path and ensure the command works from Claude Code’s launch context. - Test every check before relying on it. Ask Claude Code to write a harmless test note inside the test vault, then try a path outside it, the prohibited marker, and a line over the limit. Confirm allowed content proceeds and each rejected case produces a clear message. Test both Write and Edit, since their inputs differ. Remove test notes afterward.
- Point the checks at your real vault only after verification. Change
VAULTto the intended absolute path, review the hook configuration, and confirm normal note edits still work. Keep the script and configuration under version control or make a separate backup so you can restore them if a change blocks legitimate work.
Common Mistakes
- Using a broad path prefix. A simple check such as
target.startsWith(root)can mistakenly accept a sibling folder whose name begins with the vault name. The example adds a path separator to avoid that case. - Assuming Edit provides the full note. Edit may send only the replacement text and search string. A content regex against the replacement alone cannot guarantee the finished file passes.
- Putting regex in the wrong layer. A setting’s matcher selects tool names; it is not a general-purpose content filter. Put content validation in a script and verify the hook’s documented input.
- Forgetting platform path differences. Windows paths, drive letters, and separators differ from Unix-style paths. Use Node’s path utilities and test on the same operating system where Claude Code runs.
- Treating hooks as a complete security boundary. Hooks can be changed or bypassed by someone with access to the project or machine. Restrict filesystem permissions separately if access control matters.
Tips
- Give each check a specific error message, and keep an example of a passing and failing input beside the script.
- Use anchored patterns where appropriate. For example,
^and$make a rule apply to a whole line rather than matching an arbitrary substring. - Consider false positives before blocking. A phrase that is unsafe in one context may be valid in code examples, quoted text, or a note about the rule itself.
- Keep validation fast and local. A small script that fails closed on malformed hook input is easier to maintain than a complicated chain of shell commands.
Troubleshooting
The hook does not run: Check that Claude Code is opened in the project containing .claude/settings.json, that the JSON is valid, and that the event and tool matcher follow the current hook schema. Confirm Node runs from a terminal and use an absolute script path.
Every write is blocked: Print a temporary diagnostic to standard error showing the received tool name and target path. Check the vault path, path separators, and whether Claude Code sends a relative or absolute file path. Remove diagnostics once fixed; do not print note contents.
The marker check misses text: Inspect the documented event payload and verify which field contains content for each tool. An Edit operation may not include the full resulting note. Change the validation design rather than assuming an absent field means the note is safe.
Valid notes are rejected: Make the regex more specific, test it against representative Markdown, and decide whether code blocks or quoted examples should be excluded. Temporarily disable the hook only for controlled debugging in the test vault, then restore it before working with real notes.
Frequently Asked Questions
Can I use three regex checks without writing a script?
No. A hook matcher can choose which tool calls trigger, but checking file paths and content generally requires a command or script to inspect the hook input.
Do these checks run when I edit a note directly in Obsidian?
No. They apply to Claude Code actions that invoke the configured hook. They do not monitor manual edits or other applications.
Can regex validate all Markdown links and frontmatter?
Not reliably in every case. Regex is useful for simple, clearly defined patterns; use a Markdown-aware parser or dedicated validator for structural rules.
What if my vault is on Windows?
Use the full Windows vault path in the script and test the hook from the same Windows environment. Node’s path functions handle platform-specific separators when run on that system.
Will the hook protect my vault from every unwanted change?
No. It checks only the operations and data you configure it to inspect. Back up the vault, review permissions, and test the actual hook behavior rather than treating it as guaranteed protection.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.