|
#!/usr/bin/env python3 |
|
"""Outils déterministes pour un vault Obsidian tenu par un agent IA (Claude Code…). |
|
|
|
Exemple à adapter : tout ce qui est propre à votre vault vit dans vocab.json. |
|
|
|
vault.py status état d'Obsidian (ouvert/fermé) et chemin du vault |
|
vault.py check <note>... | --all | --recent N |
|
vérifie les conventions (tags, nommage, liens, secrets…) |
|
vault.py move <source> <destination> [--dry-run] |
|
renomme/déplace une note et met à jour tous les liens |
|
vault.py find [--tag T] [--type T] [--projet P] [--links-to NOM] [--text REGEX] [--recent N] [--folder D] |
|
liste des notes (chemin relatif + date + titre) |
|
vault.py info <nom de note> chemin, propriétés, liens sortants et rétroliens |
|
vault.py entities notes d'entité (organisations, projets) et leurs tags |
|
vault.py vocab list vocabulaire de tags actuel |
|
vault.py vocab add <famille/tag> [--entity "Nom de la note"] [--parent org/x] |
|
ajoute un tag au vocabulaire (et l'associe à une note d'entité) |
|
vault.py vocab usage nombre de notes par tag + tags utilisés hors vocabulaire |
|
|
|
Lancer depuis la racine du vault : python3 .claude/obsidian-kit/scripts/vault.py <commande>. |
|
Les chemins de notes sont relatifs à la racine du vault. |
|
""" |
|
import json, os, re, subprocess, sys, time |
|
from pathlib import Path |
|
|
|
KIT = Path(__file__).resolve().parent.parent |
|
# OBSIDIAN_VAULT / OBSIDIAN_VOCAB : surcharges pour tester sur une copie du vault |
|
VOCAB_PATH = Path(os.environ.get("OBSIDIAN_VOCAB", KIT / "vocab.json")) |
|
VOCAB = json.loads(VOCAB_PATH.read_text(encoding="utf-8")) |
|
VAULT = Path(os.environ.get("OBSIDIAN_VAULT", KIT.parent.parent)) # <vault>/.claude/obsidian-kit → <vault> |
|
ALLOWED_TAGS = {(f"{k}/{v}" if k else v) for k, vs in VOCAB["tags"].items() for v in vs} |
|
# Notes d'entrée (hubs) : dispensées de tags ; ROOT_NOTES : seules notes autorisées à la racine |
|
HUBS = set(VOCAB.get("hubs", ["Accueil", "CLAUDE"])) |
|
ROOT_NOTES = set(VOCAB.get("root_notes", ["Accueil", "CLAUDE"])) |
|
INBOX = VOCAB.get("inbox", "00 Inbox") |
|
SKIP_DIRS = {".obsidian", ".claude", ".trash", "_Templates"} |
|
FORBIDDEN_NAMES = {"sans titre", "untitled", "infos", "liste", "nouvelle note", "note", "temp", "divers"} |
|
SECRET_PATTERNS = [ |
|
("clé/mot de passe/token", r"(?i)\b(api[_-]?key|secret|password|passwd|mot de passe|token|access[_-]?key)\b\s*[:=]\s*[`'\"]?[^\s`'\"]{8,}"), |
|
("clé OpenAI/Anthropic", r"\bsk-(?:proj-|ant-)?[A-Za-z0-9_-]{20,}"), |
|
("clé AWS/Scaleway", r"\b(AKIA|SCW)[A-Z0-9]{14,}\b"), # ajoutez vos fournisseurs |
|
("n° de Sécurité sociale", r"\b[12]\s?\d{2}\s?(0[1-9]|1[0-2])\s?\d{2}\s?\d{3}\s?\d{3}(\s?\d{2})?\b"), |
|
("IBAN", r"\bFR\d{2}(\s?\d{4}){5}\s?\d{3}\b"), |
|
("URL pré-signée", r"X-Amz-Signature=|[?&]sig=[A-Za-z0-9%]{20,}"), |
|
] |
|
|
|
|
|
def rel(p): return str(Path(p).resolve().relative_to(VAULT)) |
|
|
|
|
|
def iter_files(ext=None): |
|
for root, dirs, files in os.walk(VAULT): |
|
dirs[:] = [d for d in dirs if d not in SKIP_DIRS] |
|
for f in files: |
|
if f == ".DS_Store": continue |
|
if ext and not f.endswith(ext): continue |
|
yield Path(root) / f |
|
|
|
|
|
def notes(): return list(iter_files(".md")) |
|
|
|
|
|
def resolve(arg): |
|
p = Path(arg) |
|
if not p.is_absolute(): p = VAULT / p |
|
if p.exists(): return p |
|
if not str(p).endswith(".md") and Path(str(p) + ".md").exists(): return Path(str(p) + ".md") |
|
# recherche par nom de note |
|
name = Path(arg).name.removesuffix(".md") |
|
hits = [n for n in notes() if n.stem == name] |
|
if len(hits) == 1: return hits[0] |
|
if len(hits) > 1: sys.exit(f"Nom ambigu « {name} » : " + ", ".join(rel(h) for h in hits)) |
|
sys.exit(f"Note introuvable : {arg}") |
|
|
|
|
|
def split_fm(text): |
|
if not text.startswith("---\n"): return None, text |
|
end = text.find("\n---", 4) |
|
if end == -1: return None, text |
|
return text[4:end], text[end + 4:].lstrip("\n") |
|
|
|
|
|
def parse_fm(fm): |
|
"""Parseur YAML minimal (clé: valeur, listes en ligne ou à tirets).""" |
|
data, key = {}, None |
|
for line in (fm or "").split("\n"): |
|
if not line.strip(): continue |
|
m = re.match(r"^([\w\-À-ÿ]+):\s*(.*)$", line) |
|
if m: |
|
key, val = m.group(1), m.group(2).strip() |
|
if val.startswith("[") and val.endswith("]"): |
|
data[key] = [v.strip().strip("\"'") for v in val[1:-1].split(",") if v.strip()] |
|
elif val == "": |
|
data[key] = [] |
|
else: |
|
data[key] = val.strip("\"'") |
|
elif key and re.match(r"^\s+-\s*", line): |
|
if not isinstance(data.get(key), list): data[key] = [] |
|
data[key].append(re.sub(r"^\s+-\s*", "", line).strip().strip("\"'")) |
|
return data |
|
|
|
|
|
def strip_code(body): return re.sub(r"```.*?```|`[^`\n]*`", "", body, flags=re.S) |
|
|
|
|
|
def wikilinks(text): |
|
return [m.group(1).strip() for m in re.finditer(r"!?\[\[([^\]|#^]+)(?:[#^|][^\]]*)?\]\]", strip_code(text))] |
|
|
|
|
|
def names_index(): |
|
idx = {} |
|
for f in iter_files(): |
|
idx.setdefault(f.stem if f.suffix == ".md" else f.name, []).append(f) |
|
if f.suffix != ".md": idx.setdefault(f.stem, []).append(f) |
|
return idx |
|
|
|
|
|
def link_ok(target, idx): |
|
base = target.split("/")[-1] |
|
return base in idx or base.removesuffix(".md") in idx |
|
|
|
|
|
# ---------------------------------------------------------------- check |
|
def check_note(p, idx, stem_count): |
|
issues, warns = [], [] |
|
r = rel(p); stem = p.stem |
|
text = p.read_text(encoding="utf-8") |
|
fm_raw, body = split_fm(text) |
|
fm = parse_fm(fm_raw) |
|
is_hub = stem in HUBS and r in (f"{stem}.md", f"{stem}/{stem}.md") |
|
# nommage / emplacement |
|
if "/" not in r and stem not in ROOT_NOTES: |
|
issues.append(f"note à la racine du vault : la ranger dans un dossier ({INBOX}/ en cas de doute)") |
|
if stem.lower().rstrip(" 0123456789") in FORBIDDEN_NAMES: |
|
issues.append(f"titre non explicite « {stem} »") |
|
if re.search(r"\d{1,2}[-/.]\d{1,2}[-/.]\d{4}|\b\d{8}\b", stem) or \ |
|
(re.search(r"\d{4}-\d{2}-\d{2}", stem) and not re.match(r"^\d{4}-\d{2}-\d{2}( |$)", stem)): |
|
issues.append("date dans le titre hors format « AAAA-MM-JJ Sujet »") |
|
if stem_count.get(stem, 0) > 1: |
|
issues.append(f"nom de note en double dans le vault ({stem_count[stem]} fichiers « {stem} »)") |
|
# frontmatter |
|
if fm_raw is None and not is_hub: |
|
issues.append("pas de frontmatter (propriétés/tags manquants)") |
|
tags = fm.get("tags", []) |
|
if isinstance(tags, str): tags = [tags] |
|
tags = [t.lstrip("#") for t in tags] |
|
if not is_hub: |
|
bad = [t for t in tags if t not in ALLOWED_TAGS] |
|
if bad: issues.append("tags hors vocabulaire : " + ", ".join(bad) + " (voir vocab.json)") |
|
if not tags: issues.append("aucun tag") |
|
elif len(tags) > 5: warns.append(f"{len(tags)} tags : viser 2 à 4") |
|
inline = set(re.findall(r"(?:^|\s)#([A-Za-zÀ-ÿ][\w/À-ÿ-]*)", strip_code(body))) |
|
inline = {t for t in inline if not re.fullmatch(r"[0-9A-Fa-f]{3,8}", t)} |
|
if inline - ALLOWED_TAGS and not stem.endswith(".excalidraw"): |
|
warns.append("tags inline hors vocabulaire : " + ", ".join(sorted(inline - ALLOWED_TAGS))) |
|
# type et propriétés requises |
|
typ = fm.get("type") |
|
if typ: |
|
if typ not in VOCAB["types"] and not r.startswith("_Archives/"): warns.append(f"type inconnu « {typ} »") |
|
for k in VOCAB["types"].get(typ, []): |
|
if not fm.get(k): issues.append(f"propriété « {k} » manquante pour type: {typ}") |
|
st = fm.get("statut") |
|
if st and typ in VOCAB["statuts"] and st not in VOCAB["statuts"][typ]: |
|
issues.append(f"statut « {st} » invalide pour {typ} ({'/'.join(VOCAB['statuts'][typ])})") |
|
if typ == "réunion" and fm.get("projet") and "[[" not in str(fm.get("projet")): |
|
warns.append("projet devrait être un lien : projet: \"[[Entité]]\"") |
|
if fm.get("date") and not re.fullmatch(r"\d{4}-\d{2}-\d{2}", str(fm["date"])): |
|
issues.append(f"date « {fm['date']} » hors format AAAA-MM-JJ") |
|
# liens vers les entités |
|
links = set(wikilinks(text)) |
|
link_bases = {l.split("/")[-1] for l in links} |
|
covered = {VOCAB.get("parents", {}).get(t) for t in tags if VOCAB["entities"].get(t) in link_bases} |
|
for t in tags: |
|
ent = VOCAB["entities"].get(t) |
|
if t in covered: continue # déjà relié via l'entité enfant (ex. [[Atlas]] → [[Acme]]) |
|
if ent and ent != stem and ent not in link_bases: |
|
issues.append(f"tag {t} sans lien vers l'entité [[{ent}]] (ajouter dans liens:)") |
|
# liens cassés |
|
broken = sorted({l for l in links if not link_ok(l, idx)}) |
|
if broken: issues.append("liens cassés : " + ", ".join(f"[[{b}]]" for b in broken)) |
|
# secrets |
|
for label, rx in SECRET_PATTERNS: |
|
if re.search(rx, text): |
|
(warns if "sensible" in tags else issues).append(f"secret probable ({label}) : ne pas le stocker, renvoyer au gestionnaire de mots de passe") |
|
return issues, warns |
|
|
|
|
|
def cmd_check(args): |
|
idx = names_index() |
|
stem_count = {} |
|
for n in notes(): stem_count[n.stem] = stem_count.get(n.stem, 0) + 1 |
|
if "--all" in args: |
|
targets = notes() |
|
elif "--recent" in args: |
|
days = float(args[args.index("--recent") + 1]) |
|
targets = [n for n in notes() if time.time() - n.stat().st_mtime < days * 86400] |
|
else: |
|
targets = [resolve(a) for a in args] |
|
total = 0 |
|
for p in sorted(targets): |
|
issues, warns = check_note(p, idx, stem_count) |
|
if issues or warns: |
|
print(f"\n{rel(p)}") |
|
for i in issues: print(f" ✗ {i}") |
|
for w in warns: print(f" ~ {w}") |
|
total += len(issues) |
|
print(f"\n{len(targets)} note(s) vérifiée(s), {total} problème(s) bloquant(s).") |
|
sys.exit(1 if total else 0) |
|
|
|
|
|
# ---------------------------------------------------------------- move |
|
def cmd_move(args): |
|
dry = "--dry-run" in args |
|
args = [a for a in args if a != "--dry-run"] |
|
if len(args) != 2: sys.exit("usage: vault.py move <source> <destination> [--dry-run]") |
|
src = resolve(args[0]) |
|
dst = Path(args[1]); dst = dst if dst.is_absolute() else VAULT / dst |
|
if dst.suffix != ".md" and src.suffix == ".md": dst = dst.with_suffix(dst.suffix + ".md") if dst.suffix else Path(str(dst) + ".md") |
|
if dst.exists(): sys.exit(f"Destination déjà existante : {rel(dst)}") |
|
old, new = src.stem, dst.stem |
|
if old != new and any(n.stem == new for n in notes()): |
|
sys.exit(f"Une autre note s'appelle déjà « {new} » : choisir un nom unique") |
|
changed = [] |
|
if old != new: |
|
rx = re.compile(r"(!?\[\[)([^\]|#^]+)([#^|][^\]]*)?(\]\])") |
|
for n in notes(): |
|
t = n.read_text(encoding="utf-8") |
|
def sub(m): |
|
target = m.group(2) |
|
if target.split("/")[-1].removesuffix(".md") == old: |
|
return f"{m.group(1)}{new}{m.group(3) or ''}{m.group(4)}" |
|
return m.group(0) |
|
t2 = rx.sub(sub, t) |
|
if t2 != t: |
|
changed.append(rel(n)) |
|
if not dry: n.write_text(t2, encoding="utf-8") |
|
if not dry: |
|
dst.parent.mkdir(parents=True, exist_ok=True) |
|
src.rename(dst) |
|
try: src.parent.rmdir() # retire le dossier s'il est devenu vide |
|
except OSError: pass |
|
print(("[simulation] " if dry else "") + f"{rel(src) if not dry else args[0]} → {rel(dst) if not dry else args[1]}") |
|
print(f"liens mis à jour dans {len(changed)} note(s)" + (": " + ", ".join(changed) if changed else "")) |
|
|
|
|
|
# ---------------------------------------------------------------- find / info |
|
def meta(p): |
|
fm_raw, body = split_fm(p.read_text(encoding="utf-8")) |
|
return parse_fm(fm_raw), body |
|
|
|
|
|
def cmd_find(args): |
|
opts = {} |
|
it = iter(args) |
|
for a in it: |
|
if a.startswith("--"): opts[a[2:]] = next(it, "") |
|
res = [] |
|
for p in notes(): |
|
fm, body = meta(p) |
|
tags = [t.lstrip("#") for t in (fm.get("tags") or [])] if isinstance(fm.get("tags"), list) else [str(fm.get("tags", "")).lstrip("#")] |
|
if "tag" in opts and not any(t == opts["tag"] or t.startswith(opts["tag"] + "/") for t in tags): continue |
|
if "type" in opts and fm.get("type") != opts["type"]: continue |
|
if "projet" in opts and opts["projet"].lower() not in str(fm.get("projet", "")).lower(): continue |
|
if "folder" in opts and not rel(p).startswith(opts["folder"].rstrip("/") + "/"): continue |
|
if "recent" in opts and time.time() - p.stat().st_mtime > float(opts["recent"]) * 86400: continue |
|
text = p.read_text(encoding="utf-8") |
|
if "links-to" in opts and opts["links-to"] not in {l.split("/")[-1] for l in wikilinks(text)}: continue |
|
if "text" in opts and not re.search(opts["text"], text, re.I): continue |
|
date = fm.get("date") or time.strftime("%Y-%m-%d", time.localtime(p.stat().st_mtime)) |
|
res.append((str(date), rel(p))) |
|
for d, r in sorted(res, reverse=True): print(f"{d} {r}") |
|
print(f"{len(res)} note(s)") |
|
|
|
|
|
def cmd_info(args): |
|
p = resolve(" ".join(args)) |
|
fm, body = meta(p) |
|
text = p.read_text(encoding="utf-8") |
|
print(f"chemin : {rel(p)}") |
|
print("propriétés : " + json.dumps(fm, ensure_ascii=False)) |
|
print("liens sortants : " + ", ".join(sorted(set(wikilinks(text)))) ) |
|
back = [rel(n) for n in notes() if n != p and p.stem in {l.split('/')[-1] for l in wikilinks(n.read_text(encoding='utf-8'))}] |
|
print(f"rétroliens ({len(back)}) :") |
|
for b in sorted(back): print(f" - {b}") |
|
|
|
|
|
def cmd_entities(_): |
|
rev = {v: k for k, v in VOCAB["entities"].items()} |
|
for n in sorted(notes()): |
|
fm, _b = meta(n) |
|
if fm.get("type") in ("organisation", "projet") or n.stem in rev: |
|
print(f"{n.stem:20} {rev.get(n.stem, '-'):28} {rel(n)}") |
|
|
|
|
|
def cmd_vocab(args): |
|
if not args or args[0] == "list": |
|
for fam, vs in VOCAB["tags"].items(): print(f"{fam or '(racine)'}: " + ", ".join(vs)) |
|
print("entités: " + ", ".join(f"{k} → [[{v}]]" for k, v in VOCAB["entities"].items())) |
|
return |
|
if args[0] == "add": |
|
# option --parent org/x : la note d'entité enfant suffit à relier le parent |
|
if len(args) < 2: sys.exit("usage: vault.py vocab add <famille/tag> [--entity \"Nom\"]") |
|
if args[1].startswith("-"): |
|
sys.exit("usage: vault.py vocab add <famille/tag> [--entity \"Nom\"] [--parent org/x]") |
|
tag = args[1].lstrip("#").strip().lower() |
|
if not re.fullmatch(r"[a-zà-ÿ0-9][a-zà-ÿ0-9-]*/[a-zà-ÿ0-9][a-zà-ÿ0-9-]*", tag): |
|
sys.exit("format attendu : famille/tag en minuscules, mots séparés par des tirets (ex. org/sncf, tech/rust)") |
|
fam, _, name = tag.rpartition("/") |
|
if not fam or fam not in VOCAB["tags"]: |
|
sys.exit(f"famille « {fam} » inconnue ({', '.join(f for f in VOCAB['tags'] if f)}) : ne créer une famille que sur demande explicite") |
|
if name not in VOCAB["tags"][fam]: VOCAB["tags"][fam].append(name) |
|
if "--entity" in args: |
|
VOCAB["entities"][tag] = args[args.index("--entity") + 1] |
|
if "--parent" in args: |
|
VOCAB.setdefault("parents", {})[tag] = args[args.index("--parent") + 1] |
|
if fam in ("org", "projet") and tag not in VOCAB["entities"]: |
|
print(f"attention : {tag} n'est associé à aucune note d'entité (--entity \"Nom\")") |
|
VOCAB_PATH.write_text(json.dumps(VOCAB, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") |
|
print(f"ajouté au vocabulaire : {tag}" + (f" → [[{VOCAB['entities'][tag]}]]" if tag in VOCAB["entities"] else "")) |
|
return |
|
if args[0] == "usage": |
|
from collections import Counter |
|
c, out = Counter(), Counter() |
|
for n in notes(): |
|
fm, _b = meta(n) |
|
tags = fm.get("tags") or [] |
|
for t in ([tags] if isinstance(tags, str) else tags): |
|
t = t.lstrip("#"); c[t] += 1 |
|
if t not in ALLOWED_TAGS: out[t] += 1 |
|
for t in sorted(ALLOWED_TAGS, key=lambda x: -c[x]): print(f"{c[t]:4} {t}") |
|
if out: print("hors vocabulaire : " + ", ".join(f"{t}({n})" for t, n in out.most_common())) |
|
unused = [t for t in ALLOWED_TAGS if not c[t]] |
|
if unused: print("jamais utilisés : " + ", ".join(sorted(unused))) |
|
return |
|
sys.exit("usage: vault.py vocab list|add|usage") |
|
|
|
|
|
def cmd_status(_): |
|
running = subprocess.run(["pgrep", "-ix", "obsidian"], capture_output=True).returncode == 0 |
|
print(f"vault : {VAULT}") |
|
print(f"Obsidian : {'OUVERT (ne pas modifier .obsidian/)' if running else 'fermé'}") |
|
print(f"date du jour : {time.strftime('%Y-%m-%d')}") |
|
|
|
|
|
if __name__ == "__main__": |
|
if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"): print(__doc__); sys.exit(0) |
|
cmds = {"check": cmd_check, "move": cmd_move, "find": cmd_find, "info": cmd_info, "entities": cmd_entities, "status": cmd_status, "vocab": cmd_vocab} |
|
if sys.argv[1] not in cmds or "-h" in sys.argv[2:] or "--help" in sys.argv[2:]: print(__doc__); sys.exit(0) |
|
cmds[sys.argv[1]](sys.argv[2:]) |