neurokeeper 0.3.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ """neurokeeper: portable-core harness (deterministic engines + prompts + thin adapters)."""
2
+ __version__ = "0.3.3"
@@ -0,0 +1,280 @@
1
+ #!/usr/bin/env python3
2
+ # @capability: backend-contract
3
+ # @compute: deterministic
4
+ # @effect: read-only
5
+ # @engine: scripts/_backend.py
6
+ # @prompt: (none)
7
+ # @adapters: import (shared helper)
8
+ # @portability: L1a-generic
9
+ # @forbidden: n/a
10
+ # @audit: none
11
+ # @status: experimental
12
+ # @doc: docs/pattern-portable-core-and-adapters.md
13
+ r"""Backend contract: the small, documented seam that makes the vault engines backend-agnostic.
14
+
15
+ PROOF-FIRST. This module abstracts the FIVE places where the deterministic engines were coupled to
16
+ Obsidian, so the same engines can run over a different note store (plain-markdown / Foam tomorrow) by
17
+ swapping ONE object. It is deliberately tiny -- a proof that the coupling is real and isolable, not a
18
+ framework.
19
+
20
+ The five coupling seams (the interface):
21
+ 1. LINK -- parse/emit internal links. find_links(text) -> [(span, Link)]; render_link(Link) -> str;
22
+ make_link_rewriter(rename_map) -> callable(text) -> (new_text, n) for the rename use-case.
23
+ 2. METADATA -- read_frontmatter(text) -> dict|None ; split(text) -> (fm_text, body). YAML `---` default,
24
+ with the 64KB alias-bomb cap (delegated to _vault_lib).
25
+ 3. TAGS -- find_tags(text) -> set[str] (frontmatter tags + inline #tags).
26
+ 4. STORE -- iter_notes() / read(path) / write(path, text) / rename(src, dst). Filesystem-markdown
27
+ default; write() routes through the existing safe_write (symlink/out-of-vault guard).
28
+ 5. GUARD -- assert_safe_to_write(force=False) -- the editor-write preflight capability.
29
+
30
+ Two reference adapters, dispatched by `get_backend(name=None)` on env VAULT_BACKEND (default "obsidian"):
31
+ * ObsidianBackend ("obsidian", DEFAULT) -- the REFERENCE adapter. WRAPS the existing _vault_lib regexes
32
+ / md_files / safe_write and _vault_guard.assert_obsidian_closed so behaviour is byte-identical to the
33
+ pre-contract engines. It does NOT rewrite that logic; it adapts it.
34
+ * MarkdownBackend ("markdown") -- plain-markdown links `[alias](target.md#anchor)` / `![alt](img.png)`,
35
+ YAML frontmatter, filesystem store, NO editor guard (files-on-disk are always safe to write).
36
+
37
+ NB the canonical Link model is intentionally lossy (target/anchor/alias/embed only). Obsidian's escaped-pipe
38
+ table syntax `[[t\|a]]` cannot survive a parse-and-reemit round-trip through it, so ObsidianBackend OVERRIDES
39
+ make_link_rewriter with a target-only substring rewrite (the hardened verbatim regex moved here from the
40
+ engine) -- that is what preserves byte-identity + the table-link / slash-decoy / clobber regressions. The
41
+ generic find_links/render_link splice (base class) is used by stores where parse-and-reemit is safe.
42
+ """
43
+ import os
44
+ import re
45
+ from collections import namedtuple
46
+
47
+ from _vault_lib import ( # the shared deterministic core -- the Obsidian adapter wraps these
48
+ VAULT,
49
+ md_files,
50
+ safe_write,
51
+ parse_frontmatter,
52
+ split_frontmatter,
53
+ folder_suffixes,
54
+ )
55
+
56
+ try:
57
+ from _vault_guard import assert_obsidian_closed
58
+ except Exception: # pragma: no cover -- guard helper optional (mirrors the engines' own fallback)
59
+ def assert_obsidian_closed(force=False):
60
+ pass
61
+
62
+ # Canonical internal link model. Exactly the four fields named in the contract; deliberately lossy
63
+ # (it does NOT capture Obsidian's escaped-pipe backslash -- see module docstring).
64
+ Link = namedtuple("Link", ["target", "anchor", "alias", "embed"])
65
+
66
+ # Tag grammar (shared default; mirrors vault-tag-reconcile's inline-tag + code-fence handling).
67
+ _INLINE_TAG = re.compile(r"(?:^|\s)#([A-Za-z][\w/\-]+)")
68
+ _FENCE = re.compile(r"```.*?```", re.S)
69
+
70
+ # Extensions the GENERIC (markdown) rename rewriter treats as a NOTE link. Markdown internal links carry
71
+ # an explicit ext `[a](foo.md)`, so we REQUIRE one -- extension-less/bare targets and external URLs are
72
+ # NOT repointed (the `""` here was the external-URL-corruption bug the red-team found). An image
73
+ # `Foo Bar.png` sharing a renamed note's stem is excluded by the same rule. (Obsidian's extension-less
74
+ # wikilinks are handled by ObsidianBackend's verbatim override, which does not use this set.)
75
+ _NOTE_EXTS = {".md", ".markdown"}
76
+ # A target carrying a URI scheme (http:, https:, mailto:, obsidian:, ...) is external -- never repoint it.
77
+ _URI_SCHEME = re.compile(r"^[a-z][a-z0-9+.\-]*:", re.I)
78
+
79
+
80
+ class Backend:
81
+ """Base backend: filesystem-markdown STORE + YAML METADATA + #tag TAGS + a no-op write GUARD.
82
+
83
+ Link grammar (seam 1) is abstract -- a concrete adapter MUST provide find_links + render_link
84
+ (or override make_link_rewriter). Everything else has a working default both adapters share.
85
+ """
86
+
87
+ name = "base"
88
+ #: capability flag (seam 5): True iff this store needs an editor-write preflight before bulk writes.
89
+ requires_write_guard = False
90
+
91
+ def __init__(self, vault=None):
92
+ self.vault = vault or VAULT
93
+
94
+ # --- seam 1: LINK -------------------------------------------------------------------------------
95
+ def find_links(self, text):
96
+ """Return [((start, end), Link), ...] for every internal link in `text`."""
97
+ raise NotImplementedError
98
+
99
+ def render_link(self, link):
100
+ """Emit the backend's surface syntax for `link`."""
101
+ raise NotImplementedError
102
+
103
+ def make_link_rewriter(self, rename_map):
104
+ """Build a closure(text) -> (new_text, changed_int) that repoints any link whose target BASENAME
105
+ stem is a key of `rename_map` to the mapped stem. Generic parse-and-reemit via find_links /
106
+ render_link; splices in reverse so spans stay valid. ObsidianBackend overrides this for byte
107
+ identity. `changed_int` is 1 if the file changed (the engine counts files, not links)."""
108
+ def rewrite(text):
109
+ # Do not rewrite links inside fenced code blocks (doc examples / dataview queries).
110
+ fences = [(m.start(), m.end()) for m in _FENCE.finditer(text)]
111
+ changed = False
112
+ for (start, end), link in sorted(self.find_links(text), key=lambda x: x[0][0], reverse=True):
113
+ if any(a <= start < b for a, b in fences):
114
+ continue # inside a code fence -- leave it
115
+ tgt = link.target
116
+ if not tgt or tgt.startswith("#") or _URI_SCHEME.match(tgt):
117
+ continue # anchor-only / external URL / non-target -- never repoint
118
+ base = os.path.basename(tgt)
119
+ stem, ext = os.path.splitext(base)
120
+ new_stem = rename_map.get(stem)
121
+ if new_stem is None or ext.lower() not in _NOTE_EXTS:
122
+ continue # only repoint .md NOTE links (skip images/assets/extension-less targets)
123
+ dirpart = tgt[: len(tgt) - len(base)]
124
+ new_link = link._replace(target=dirpart + new_stem + ext)
125
+ text = text[:start] + self.render_link(new_link) + text[end:]
126
+ changed = True
127
+ return text, (1 if changed else 0)
128
+ return rewrite
129
+
130
+ # --- seam 2: METADATA ---------------------------------------------------------------------------
131
+ def split(self, text):
132
+ """(frontmatter_text, body) -- YAML `---` default. body includes the closing fence
133
+ (the existing split_frontmatter semantics). (None, text) when there is no frontmatter."""
134
+ return split_frontmatter(text)
135
+
136
+ def read_frontmatter(self, text):
137
+ """Parsed frontmatter dict, None if absent, {'__parse_error__': True} on YAML error / >64KB
138
+ (the alias-bomb cap is enforced inside parse_frontmatter)."""
139
+ return parse_frontmatter(text)
140
+
141
+ # --- seam 3: TAGS -------------------------------------------------------------------------------
142
+ def find_tags(self, text):
143
+ """Set of tags: frontmatter `tags:` (str or list) + inline `#tags` outside code fences."""
144
+ tags = set()
145
+ fm = parse_frontmatter(text)
146
+ if fm and not fm.get("__parse_error__"):
147
+ t = fm.get("tags")
148
+ if isinstance(t, list):
149
+ tags.update(str(x) for x in t)
150
+ elif isinstance(t, str):
151
+ tags.update(x for x in re.split(r"[,\s]+", t) if x)
152
+ body = text.split("\n---", 1)[-1] if text.startswith("---") else text
153
+ for m in _INLINE_TAG.finditer(_FENCE.sub("", body)):
154
+ tags.add(m.group(1))
155
+ return tags
156
+
157
+ # --- seam 4: STORE ------------------------------------------------------------------------------
158
+ def iter_notes(self):
159
+ """Yield (abspath, reldir) for every note (the md_files walk, env-driven exclusions)."""
160
+ return md_files(self.vault)
161
+
162
+ def read(self, path):
163
+ """Read a note. newline='' preserves the file's existing CRLF/LF (no reflow on rewrite)."""
164
+ return open(path, encoding="utf-8", newline="").read()
165
+
166
+ def write(self, path, text):
167
+ """Write a note through the vault-confined safe_write (raises VaultWriteError on symlink /
168
+ out-of-vault). Preserves CRLF/LF."""
169
+ return safe_write(path, text)
170
+
171
+ def rename(self, src, dst):
172
+ """Rename a note file. Vault-confinement / symlink / two-step policy stays in the caller."""
173
+ return os.rename(src, dst)
174
+
175
+ # --- seam 5: GUARD ------------------------------------------------------------------------------
176
+ def assert_safe_to_write(self, force=False):
177
+ """Preflight before a bulk write. Base = no-op (files-on-disk are always safe)."""
178
+ return None
179
+
180
+
181
+ class ObsidianBackend(Backend):
182
+ """REFERENCE adapter (DEFAULT). Wraps the existing Obsidian-coupled logic verbatim so refactored
183
+ engines stay byte-identical: wikilinks, the hardened rename regex, and assert_obsidian_closed."""
184
+
185
+ name = "obsidian"
186
+ requires_write_guard = True
187
+
188
+ # [[t]] | [[t|a]] | [[t#h]] | [[t\|a]] | ![[t]] | [[folder/t]] (inner is non-greedy, no nested brackets)
189
+ _WIKILINK = re.compile(r"(!?)\[\[([^\[\]]+?)\]\]")
190
+
191
+ def find_links(self, text):
192
+ out = []
193
+ for m in self._WIKILINK.finditer(text):
194
+ inner = m.group(2)
195
+ alias = None
196
+ am = re.search(r"\\?\|", inner) # alias after an optionally-escaped pipe
197
+ if am:
198
+ alias = inner[am.end():]
199
+ inner = inner[:am.start()]
200
+ anchor = None
201
+ if "#" in inner:
202
+ inner, anchor = inner.split("#", 1)
203
+ out.append(((m.start(), m.end()),
204
+ Link(target=inner, anchor=anchor, alias=alias, embed=(m.group(1) == "!"))))
205
+ return out
206
+
207
+ def render_link(self, link):
208
+ s = link.target
209
+ if link.anchor:
210
+ s += "#" + link.anchor
211
+ if link.alias is not None: # NB plain pipe -- lossy vs escaped-pipe \| (see docstring)
212
+ s += "|" + link.alias
213
+ return ("!" if link.embed else "") + "[[" + s + "]]"
214
+
215
+ def make_link_rewriter(self, rename_map):
216
+ """OVERRIDE: the hardened verbatim rename regex (moved out of vault-name-reconcile unchanged).
217
+ A target-only substring rewrite -- byte-identical to the pre-contract engine, which is what keeps
218
+ the escaped-pipe table link, the TCP/IP slash-decoy, the folder-suffix match and the clobber gap
219
+ all behaving exactly as the regression suite locks them.
220
+
221
+ path-prefix may ONLY be a REAL vault folder (folder_suffixes), never arbitrary text-before-'/'
222
+ (the 2026-06-27 TCP/IP corruption bug). Lookahead includes '\\' so escaped-pipe links
223
+ [[stem\\|alias]] (common in tables) are rewritten too."""
224
+ folders = folder_suffixes(self.vault)
225
+ PATH = ("(?:" + "|".join(re.escape(f) for f in sorted(folders, key=len, reverse=True)) + ")?") \
226
+ if folders else ""
227
+ stems_alt = "|".join(re.escape(s) for s in sorted(rename_map, key=len, reverse=True))
228
+ big = re.compile(r"(!?\[\[" + PATH + r")(" + stems_alt + r")(?=[\]|#\\])")
229
+
230
+ def rewrite(text):
231
+ nt = big.sub(lambda m: m.group(1) + rename_map[m.group(2)], text)
232
+ return nt, (1 if nt != text else 0)
233
+ return rewrite
234
+
235
+ def assert_safe_to_write(self, force=False):
236
+ """Refuse a bulk write while Obsidian is running (the Linter corrupts frontmatter wikilinks on
237
+ live external writes -- the 2026-06-27 incident). Exits 2 unless force."""
238
+ return assert_obsidian_closed(force)
239
+
240
+
241
+ class MarkdownBackend(Backend):
242
+ """Plain-markdown adapter. Links are `[alias](target.md#anchor)` / `![alt](img.png)`; YAML frontmatter
243
+ and filesystem store are inherited; NO editor guard (a files-on-disk store is always safe to write).
244
+ Inherits the generic find_links-based make_link_rewriter (markdown has no escaped-pipe lossiness)."""
245
+
246
+ name = "markdown"
247
+ requires_write_guard = False
248
+
249
+ # [alias](target) or ![alt](target) ; target captured up to the closing paren (may contain spaces).
250
+ _MDLINK = re.compile(r"(!?)\[([^\]]*)\]\(([^)]+)\)")
251
+
252
+ def find_links(self, text):
253
+ out = []
254
+ for m in self._MDLINK.finditer(text):
255
+ tgt = m.group(3).strip()
256
+ anchor = None
257
+ if "#" in tgt:
258
+ tgt, anchor = tgt.split("#", 1)
259
+ out.append(((m.start(), m.end()),
260
+ Link(target=tgt, anchor=anchor, alias=m.group(2), embed=(m.group(1) == "!"))))
261
+ return out
262
+
263
+ def render_link(self, link):
264
+ tgt = link.target + ("#" + link.anchor if link.anchor else "")
265
+ return ("!" if link.embed else "") + "[" + (link.alias or "") + "](" + tgt + ")"
266
+
267
+
268
+ _BACKENDS = {"obsidian": ObsidianBackend, "markdown": MarkdownBackend}
269
+
270
+
271
+ def get_backend(name=None, vault=None):
272
+ """Factory: return a backend instance. `name` overrides env VAULT_BACKEND (default 'obsidian')."""
273
+ key = (name or os.environ.get("VAULT_BACKEND") or "obsidian").strip().lower()
274
+ cls = _BACKENDS.get(key)
275
+ if cls is None:
276
+ raise ValueError(f"unknown VAULT_BACKEND {key!r}; known: {', '.join(sorted(_BACKENDS))}")
277
+ return cls(vault=vault)
278
+
279
+
280
+ __all__ = ["Link", "Backend", "ObsidianBackend", "MarkdownBackend", "get_backend"]
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env python3
2
+ # @capability: vault-write-guard
3
+ # @compute: deterministic
4
+ # @effect: read-only
5
+ # @engine: scripts/_vault_guard.py
6
+ # @prompt: (none)
7
+ # @adapters: import (shared helper)
8
+ # @portability: L1a-generic
9
+ # @forbidden: n/a
10
+ # @audit: none
11
+ # @status: active
12
+ # @doc: docs/pattern-portable-core-and-adapters.md
13
+ """Shared preflight for bulk vault-write capabilities: refuse to write while Obsidian is running.
14
+
15
+ The Obsidian Linter reformats/corrupts frontmatter wikilinks on live EXTERNAL bulk writes (2026-06-27
16
+ incident: `parent: [[X]]` mangled into a blanked nested list across ~400 files). Pattern doc section 6
17
+ mandates this preflight for every mutating-vault capability. Usage:
18
+
19
+ from _vault_guard import assert_obsidian_closed
20
+ if apply: assert_obsidian_closed("--force" in sys.argv)
21
+ """
22
+ import os, subprocess, sys
23
+
24
+ def obsidian_running():
25
+ """True / False / None(undeterminable)."""
26
+ try:
27
+ if os.name == "nt":
28
+ out = subprocess.run(["tasklist", "/FI", "IMAGENAME eq Obsidian.exe"],
29
+ capture_output=True, text=True, encoding="utf-8",
30
+ errors="replace", timeout=10).stdout
31
+ return "Obsidian.exe" in out
32
+ r = subprocess.run(["pgrep", "-x", "obsidian"], capture_output=True, timeout=10)
33
+ return r.returncode == 0
34
+ except Exception:
35
+ return None
36
+
37
+ def assert_obsidian_closed(force=False):
38
+ state = obsidian_running()
39
+ if state is True and not force:
40
+ sys.stderr.write(
41
+ "REFUSING bulk vault write: Obsidian is running. Its Linter corrupts frontmatter "
42
+ "wikilinks on live external writes (2026-06-27 incident). Close Obsidian and retry "
43
+ "(or pass --force to override).\n")
44
+ sys.exit(2)
45
+ if state is None:
46
+ sys.stderr.write("WARN: could not determine whether Obsidian is running; proceeding. "
47
+ "Ensure Obsidian is closed before bulk vault writes.\n")
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env python3
2
+ # @capability: vault-lib
3
+ # @compute: deterministic
4
+ # @effect: read-only
5
+ # @engine: scripts/_vault_lib.py
6
+ # @prompt: (none)
7
+ # @adapters: import (shared helper)
8
+ # @portability: L1a-generic
9
+ # @forbidden: n/a
10
+ # @audit: none
11
+ # @status: active
12
+ # @doc: docs/pattern-portable-core-and-adapters.md
13
+ """Shared helpers for the vault-taxonomy engines (the DRY core they all import).
14
+
15
+ Vault path + scan-exclusions come from the environment so the engines are vault-agnostic:
16
+ VAULT_ROOT - the vault directory (default: cwd)
17
+ VAULT_SCAN_EXCLUDE - comma-separated dir prefixes to skip (default: .obsidian,.claude,.git,.trash)
18
+
19
+ Provides: md_files() walk, split_frontmatter()/parse_frontmatter(), folder_suffixes() (for link-aware
20
+ path matching), kebabify() (code/acronym-preserving slug), within_vault()/safe_write() (the symlink +
21
+ path-traversal write guard), force_utf8_stdout() (cross-platform UTF-8 stdout). One definition, imported
22
+ by every engine.
23
+ """
24
+ import os, re, sys
25
+
26
+ VAULT = os.environ.get("VAULT_ROOT") or os.getcwd()
27
+ SCAN_EXCLUDE = tuple(x for x in (os.environ.get("VAULT_SCAN_EXCLUDE")
28
+ or ".obsidian,.claude,.git,.trash").split(",") if x)
29
+
30
+ # Soft cap on a frontmatter block before YAML parsing -- guards yaml.safe_load against alias-bomb /
31
+ # billion-laughs style amplification on hostile note content (the parser is bounded, not the input).
32
+ FM_MAX_BYTES = 64 * 1024
33
+
34
+ # OPTIONAL forbidden-zones enforcement for the mutators. Comma-separated reldir prefixes; when set, a
35
+ # mutator SKIPS writing any file whose reldir matches. Default UNSET => no skipping (the current
36
+ # attended-exemption behaviour: an operator watching the run + git audit is the control).
37
+ FORBIDDEN_ZONES = tuple(z.strip() for z in (os.environ.get("VAULT_FORBIDDEN_ZONES") or "").split(",")
38
+ if z.strip())
39
+
40
+
41
+ def in_forbidden_zone(reldir, zones=None):
42
+ """True iff reldir is, or sits under, a VAULT_FORBIDDEN_ZONES prefix. UNSET zones => always False."""
43
+ zones = FORBIDDEN_ZONES if zones is None else zones
44
+ if not zones or not reldir:
45
+ return False
46
+ rel = reldir.replace(os.sep, "/").strip("/")
47
+ for z in zones:
48
+ z = z.replace(os.sep, "/").strip("/")
49
+ if z and (rel == z or rel.startswith(z + "/")):
50
+ return True
51
+ return False
52
+
53
+
54
+ def force_utf8_stdout():
55
+ """Best-effort: make stdout/stderr emit UTF-8 on every platform. Windows consoles default to a
56
+ legacy codepage (cp1252), which corrupts non-ASCII when `--json` output is redirected to a file.
57
+ Guarded: a no-op on streams that lack reconfigure() (older Pythons) or are already wrapped."""
58
+ for stream in (sys.stdout, sys.stderr):
59
+ try:
60
+ stream.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
61
+ except Exception:
62
+ pass
63
+
64
+
65
+ class VaultWriteError(Exception):
66
+ """A write/rename was refused because it would escape the vault (symlink or out-of-vault path)."""
67
+
68
+
69
+ def within_vault(path, vault=None):
70
+ """True iff realpath(path) is the vault root or inside it (case-insensitive on Windows)."""
71
+ root = os.path.normcase(os.path.realpath(vault or VAULT))
72
+ real = os.path.normcase(os.path.realpath(path))
73
+ return real == root or real.startswith(root + os.sep)
74
+
75
+
76
+ def safe_write(path, text, newline=""):
77
+ """Write `text` to a REAL file confined to the vault. Refuses (raises VaultWriteError) if `path`
78
+ is a symlink, or if it resolves outside realpath(VAULT) -- a symlink-escape / path-traversal guard
79
+ for the bulk mutators. newline='' preserves the file's existing CRLF/LF. Returns the path written."""
80
+ if os.path.islink(path):
81
+ raise VaultWriteError(f"refusing to write through symlink: {path}")
82
+ if not within_vault(path):
83
+ raise VaultWriteError(f"refusing to write outside vault: {path}")
84
+ with open(path, "w", encoding="utf-8", newline=newline) as f:
85
+ f.write(text)
86
+ return path
87
+
88
+ def md_files(vault=None, exclude=None):
89
+ """Yield (abspath, reldir) for every .md under vault, skipping excluded dir prefixes."""
90
+ vault = vault or VAULT
91
+ exclude = SCAN_EXCLUDE if exclude is None else exclude
92
+ for root, dirs, files in os.walk(vault):
93
+ rel = os.path.relpath(root, vault); rel = "" if rel == "." else rel
94
+ if any(rel == e or rel.startswith(e + os.sep) for e in exclude):
95
+ dirs[:] = []; continue
96
+ dirs[:] = [d for d in dirs if not d.startswith(".")] # Obsidian ignores dot-dirs (tool caches, .obsidian, .git, ...) (issue #3)
97
+ for f in files:
98
+ if f.endswith(".md"):
99
+ yield os.path.join(root, f), rel
100
+
101
+ def split_frontmatter(text):
102
+ """Return (frontmatter_body, rest_including_closing_fence) or (None, text) if no frontmatter."""
103
+ if not text.startswith("---"):
104
+ return None, text
105
+ end = text.find("\n---", 3)
106
+ return (text[3:end], text[end:]) if end != -1 else (None, text)
107
+
108
+ def parse_frontmatter(text):
109
+ """Parsed frontmatter dict, None if absent, or {'__parse_error__': True} on YAML error / oversize."""
110
+ fm, _ = split_frontmatter(text)
111
+ if fm is None:
112
+ return None
113
+ if len(fm.encode("utf-8", "replace")) > FM_MAX_BYTES:
114
+ sys.stderr.write(f"WARN: frontmatter block > {FM_MAX_BYTES} bytes; skipping YAML parse "
115
+ "(alias-bomb guard)\n")
116
+ return {"__parse_error__": True}
117
+ try:
118
+ import yaml
119
+ return yaml.safe_load(fm) or {}
120
+ except Exception:
121
+ return {"__parse_error__": True}
122
+
123
+ def folder_suffixes(vault=None, exclude=(".git", ".trash")):
124
+ """All real-folder path-SUFFIXES ('a/b/c/','b/c/','c/') for link-aware path matching
125
+ (Obsidian links use shortest unique paths). Rejects '/'-in-title false folders."""
126
+ vault = vault or VAULT
127
+ out = set()
128
+ for root, dirs, _ in os.walk(vault):
129
+ rel = os.path.relpath(root, vault).replace(os.sep, "/")
130
+ if rel == "." or rel.split("/")[0] in exclude:
131
+ continue
132
+ segs = rel.split("/")
133
+ for i in range(len(segs)):
134
+ out.add("/".join(segs[i:]) + "/")
135
+ return out
136
+
137
+ DASH = re.compile(r"\s*(?:--|[—–])\s*")
138
+ _SPLIT = re.compile(r"[\s_/\-–—]+")
139
+ CODE_RE = re.compile(r"^[A-Z]{1,4}[0-9][A-Z0-9]*$") # code-like stems: AB12 CD345 EF6 A10 Q4 (uppercase+digit, preserved verbatim)
140
+
141
+ def kebabify(stem):
142
+ """Full kebab, preserving uppercase dossier-codes + all-caps acronyms (>=2)."""
143
+ toks = []
144
+ for tok in _SPLIT.split(stem):
145
+ c = re.sub(r"[^A-Za-z0-9]", "", tok)
146
+ if c:
147
+ toks.append(c if (CODE_RE.match(c) or (c.isupper() and len(c) >= 2)) else c.lower())
148
+ return "-".join(toks)
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env python3
2
+ # @capability: check-release
3
+ # @compute: deterministic
4
+ # @effect: read-only
5
+ # @engine: scripts/check-release.py
6
+ # @prompt: (none)
7
+ # @adapters: cli, ci
8
+ # @portability: L1a-generic
9
+ # @forbidden: n/a
10
+ # @audit: none
11
+ # @status: active
12
+ # @doc: RELEASING.md
13
+ """check-release.py -- deterministic pre-release gate. Exit 1 on any violation; run in CI.
14
+
15
+ Asserts (no auth, no network -- unlike `claude plugin validate`):
16
+ 1. version sync : pyproject.toml == neurokeeper/__init__.py == .claude-plugin/plugin.json
17
+ 2. plugin.json : kebab-case name, non-empty version + description
18
+ 3. marketplace.json: kebab-case name, owner.name, >=1 plugin each with a kebab name + a source
19
+
20
+ This is the cheap, offline half of release validation; the richer `claude plugin validate --strict`
21
+ (which may need auth) stays a documented manual/pre-publish step in RELEASING.md.
22
+ """
23
+ import json
24
+ import os
25
+ import re
26
+ import sys
27
+
28
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
29
+ KEBAB = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")
30
+
31
+
32
+ def _read(rel):
33
+ with open(os.path.join(ROOT, rel), encoding="utf-8") as fh:
34
+ return fh.read()
35
+
36
+
37
+ def main():
38
+ errors = []
39
+
40
+ # 1. version sync
41
+ try:
42
+ vers = {
43
+ "pyproject.toml": re.search(r'(?m)^version\s*=\s*"([^"]+)"', _read("pyproject.toml")).group(1),
44
+ "__init__.py": re.search(r'__version__\s*=\s*"([^"]+)"', _read("neurokeeper/__init__.py")).group(1),
45
+ "plugin.json": json.loads(_read(".claude-plugin/plugin.json")).get("version"),
46
+ }
47
+ except (OSError, AttributeError) as e:
48
+ print(f"check-release FAIL: cannot read a version ({e})")
49
+ sys.exit(1)
50
+ if None in vers.values() or len(set(vers.values())) != 1:
51
+ errors.append(f"version drift: {vers}")
52
+
53
+ # 2. plugin.json
54
+ pj = json.loads(_read(".claude-plugin/plugin.json"))
55
+ if not KEBAB.match(pj.get("name", "")):
56
+ errors.append(f"plugin.json name not kebab-case: {pj.get('name')!r}")
57
+ for field in ("version", "description"):
58
+ if not pj.get(field):
59
+ errors.append(f"plugin.json missing {field}")
60
+
61
+ # 3. marketplace.json
62
+ mk = json.loads(_read(".claude-plugin/marketplace.json"))
63
+ if not KEBAB.match(mk.get("name", "")):
64
+ errors.append(f"marketplace.json name not kebab-case: {mk.get('name')!r}")
65
+ if not (mk.get("owner") or {}).get("name"):
66
+ errors.append("marketplace.json missing owner.name")
67
+ plugins = mk.get("plugins") or []
68
+ if not plugins:
69
+ errors.append("marketplace.json has no plugins[]")
70
+ for p in plugins:
71
+ if not KEBAB.match(p.get("name", "")):
72
+ errors.append(f"marketplace plugin name not kebab-case: {p.get('name')!r}")
73
+ if not p.get("source"):
74
+ errors.append(f"marketplace plugin {p.get('name')!r} missing source")
75
+
76
+ if errors:
77
+ print("check-release FAIL:")
78
+ for e in errors:
79
+ print(" - " + e)
80
+ sys.exit(1)
81
+ print(f"check-release OK: version {vers['pyproject.toml']} synced; plugin + marketplace manifests valid")
82
+
83
+
84
+ if __name__ == "__main__":
85
+ main()