|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import os |
| 4 | +import glob |
| 5 | +from datetime import datetime, timezone |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +from palinode.core.config import config |
| 9 | +from palinode.core import parser |
| 10 | + |
| 11 | +def run_lint_pass() -> dict[str, Any]: |
| 12 | + """Scan PALINODE_DIR for memory health issues. |
| 13 | + |
| 14 | + Checks for: |
| 15 | + - Orphaned files (no entities, no references from other files) |
| 16 | + - Stale files (not updated in 90+ days, still marked status: active) |
| 17 | + - Missing fields (missing 'type', 'id', 'category') |
| 18 | + - Contradictions (potential contradictions, heuristic check) |
| 19 | + """ |
| 20 | + base_dir = getattr(config, 'memory_dir', config.palinode_dir) |
| 21 | + pattern = os.path.join(base_dir, "**/*.md") |
| 22 | + |
| 23 | + orphaned_files = [] |
| 24 | + stale_files = [] |
| 25 | + missing_fields = [] |
| 26 | + contradictions = [] # Heuristic placeholder |
| 27 | + |
| 28 | + now = datetime.now(timezone.utc) |
| 29 | + |
| 30 | + entity_references: dict[str, int] = {} |
| 31 | + all_files = [] |
| 32 | + |
| 33 | + skip_dirs = {"archive", "logs", ".obsidian"} |
| 34 | + |
| 35 | + for filepath in glob.glob(pattern, recursive=True): |
| 36 | + rel_path = os.path.relpath(filepath, base_dir) |
| 37 | + parts = rel_path.split(os.sep) |
| 38 | + if parts[0] in skip_dirs: |
| 39 | + continue |
| 40 | + |
| 41 | + try: |
| 42 | + with open(filepath, "r") as f: |
| 43 | + content = f.read() |
| 44 | + metadata, _ = parser.parse_markdown(content) |
| 45 | + |
| 46 | + entities = metadata.get("entities", []) |
| 47 | + for e in entities: |
| 48 | + entity_references[e] = entity_references.get(e, 0) + 1 |
| 49 | + |
| 50 | + all_files.append({ |
| 51 | + "path": rel_path, |
| 52 | + "metadata": metadata, |
| 53 | + }) |
| 54 | + except Exception: |
| 55 | + pass |
| 56 | + |
| 57 | + for f in all_files: |
| 58 | + path = f["path"] |
| 59 | + meta = f["metadata"] |
| 60 | + |
| 61 | + # 1. Missing fields |
| 62 | + missing = [] |
| 63 | + if not meta.get("id"): missing.append("id") |
| 64 | + if not meta.get("type"): missing.append("type") |
| 65 | + if not meta.get("category"): missing.append("category") |
| 66 | + if missing: |
| 67 | + missing_fields.append({"file": path, "missing": missing}) |
| 68 | + |
| 69 | + # 2. Orphans |
| 70 | + category = meta.get("category", "") |
| 71 | + if category and not path.startswith("daily/"): |
| 72 | + slug = path.split(os.sep)[-1].replace(".md", "") |
| 73 | + # Removing any layer suffixes like -status or -history |
| 74 | + if slug.endswith("-status"): slug = slug[:-7] |
| 75 | + if slug.endswith("-history"): slug = slug[:-8] |
| 76 | + |
| 77 | + own_entity_ref = f"{category}/{slug}" |
| 78 | + has_entities = len(meta.get("entities", [])) > 0 |
| 79 | + is_referenced = entity_references.get(own_entity_ref, 0) > 0 |
| 80 | + |
| 81 | + # An orphan has NO entities AND is not referenced by anything else |
| 82 | + if not has_entities and not is_referenced: |
| 83 | + orphaned_files.append(path) |
| 84 | + |
| 85 | + # 3. Stale |
| 86 | + if meta.get("status") == "active": |
| 87 | + last_updated = meta.get("last_updated") or meta.get("created_at") |
| 88 | + if last_updated: |
| 89 | + try: |
| 90 | + if isinstance(last_updated, str): |
| 91 | + dt = datetime.fromisoformat(last_updated.replace('Z', '+00:00')) |
| 92 | + else: |
| 93 | + dt = last_updated |
| 94 | + if dt.tzinfo is None: |
| 95 | + dt = dt.replace(tzinfo=timezone.utc) |
| 96 | + |
| 97 | + days_old = (now - dt).days |
| 98 | + if days_old > 90: |
| 99 | + stale_files.append({"file": path, "days_old": days_old}) |
| 100 | + except Exception: |
| 101 | + pass |
| 102 | + |
| 103 | + # 4. Contradictions heuristics |
| 104 | + # Simple check: Any entity that has multiple active files |
| 105 | + file_statuses = {} |
| 106 | + for f in all_files: |
| 107 | + cat = f["metadata"].get("category", "") |
| 108 | + if not cat or f["path"].startswith("daily/"): continue |
| 109 | + slug = f["path"].split(os.sep)[-1].replace(".md", "") |
| 110 | + if slug.endswith("-status"): slug = slug[:-7] |
| 111 | + if slug.endswith("-history"): slug = slug[:-8] |
| 112 | + ent = f"{cat}/{slug}" |
| 113 | + |
| 114 | + status = f["metadata"].get("status", "active") |
| 115 | + if status == "active": |
| 116 | + file_statuses[ent] = file_statuses.get(ent, 0) + 1 |
| 117 | + if file_statuses[ent] > 1: |
| 118 | + contradictions.append({ |
| 119 | + "entity": ent, |
| 120 | + "issue": "Multiple 'active' files detected for the same entity." |
| 121 | + }) |
| 122 | + |
| 123 | + # Deduplicate contradictions |
| 124 | + unique_contradictions = [dict(t) for t in {tuple(d.items()) for d in contradictions}] |
| 125 | + |
| 126 | + return { |
| 127 | + "orphaned_files": orphaned_files, |
| 128 | + "stale_files": stale_files, |
| 129 | + "missing_fields": missing_fields, |
| 130 | + "contradictions": unique_contradictions |
| 131 | + } |
0 commit comments