pyaisync 0.1.0__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.
pyaisync/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """pyaisync: one source (.ai/) -> native configuration for each AI coding agent."""
2
+
3
+ __version__ = "0.1.0"
pyaisync/cli.py ADDED
@@ -0,0 +1,369 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from dataclasses import replace
6
+ from pathlib import Path
7
+
8
+ from . import __version__
9
+ from .config import AI_DIR, load_config, set_targets
10
+ from .errors import PyAisyncError
11
+ from .importers import import_target
12
+ from .loader import load_model
13
+ from .model import ALL_TARGETS, FEATURES
14
+ from .plugin import PLUGIN_MANIFEST, build_claude_plugin
15
+ from .safefs import atomic_write
16
+ from .targets import REGISTRY, build_plan
17
+ from .writer import Report, apply
18
+
19
+ _TEMPLATES = {
20
+ "rules/project.md": (
21
+ "---\n"
22
+ "description: General project rules\n"
23
+ "always: true\n"
24
+ "---\n"
25
+ "# Example: edit or delete this file\n"
26
+ "- Describe your conventions and the test/lint commands for this project here.\n"
27
+ ),
28
+ "mcp.toml": (
29
+ "# MCP servers. Use ${VAR} for secrets; never write literal keys here.\n"
30
+ "#\n"
31
+ "# [servers.docs]\n"
32
+ '# type = "http" # stdio | http | sse\n'
33
+ '# url = "https://example.com/mcp"\n'
34
+ '# headers = { Authorization = "Bearer ${DOCS_TOKEN}" }\n'
35
+ "#\n"
36
+ "# [servers.local-tool]\n"
37
+ '# type = "stdio"\n'
38
+ '# command = "uvx"\n'
39
+ '# args = ["my-mcp-server"]\n'
40
+ '# env = { API_KEY = "${MY_API_KEY}" }\n'
41
+ ),
42
+ "hooks.toml": (
43
+ "# Hooks run COMMANDS on your machine. Review them like code.\n"
44
+ "# Events: session_start, session_end, pre_tool_use, post_tool_use,\n"
45
+ "# user_prompt_submit, stop, subagent_start, subagent_stop, pre_compact\n"
46
+ "# OpenCode has no declarative hooks (they are skipped for it).\n"
47
+ "#\n"
48
+ "# [[hooks]]\n"
49
+ '# event = "pre_tool_use"\n'
50
+ '# matcher = ["shell"] # tools: read, grep, glob, edit, shell, web\n'
51
+ '# command = "./scripts/guard.sh" # relative to the repository root\n'
52
+ "# timeout = 30 # seconds, optional\n"
53
+ ),
54
+ "permissions.toml": (
55
+ "# Rules are 'tool' or 'tool(pattern)'; tools: read, grep, glob, edit, shell, web.\n"
56
+ "#\n"
57
+ '# allow = ["shell(uv run pytest*)"]\n'
58
+ '# ask = ["shell(git push*)"]\n'
59
+ '# deny = ["read(.env*)", "shell(rm -rf*)"]\n'
60
+ ),
61
+ "commands/example.md": (
62
+ "---\ndescription: Example command\n---\nSummarize the uncommitted changes. $ARGUMENTS\n"
63
+ ),
64
+ }
65
+
66
+
67
+ def detect_targets(root: Path) -> list[str]:
68
+ found = []
69
+ if (root / "CLAUDE.md").exists() or (root / ".claude").exists():
70
+ found.append("claude")
71
+ if (root / ".cursor").exists():
72
+ found.append("cursor")
73
+ if any((root / p).exists() for p in ("opencode.json", "opencode.jsonc", ".opencode")):
74
+ found.append("opencode")
75
+ return found
76
+
77
+
78
+ def _csv(value: str | None, valid: tuple[str, ...], what: str) -> tuple[str, ...] | None:
79
+ if value is None:
80
+ return None
81
+ items = tuple(v.strip() for v in value.split(",") if v.strip())
82
+ bad = [v for v in items if v not in valid]
83
+ if bad:
84
+ raise PyAisyncError(f"unknown {what} {bad}; valid: {list(valid)}")
85
+ return items
86
+
87
+
88
+ def cmd_init(args: argparse.Namespace, root: Path) -> int:
89
+ ai = root / AI_DIR
90
+ if ai.exists():
91
+ raise PyAisyncError(f"{AI_DIR}/ already exists: init never overwrites anything")
92
+ targets = (
93
+ _csv(args.targets, ALL_TARGETS, "targets") or tuple(detect_targets(root)) or ALL_TARGETS
94
+ )
95
+ if args.from_target:
96
+ if args.from_target not in ALL_TARGETS:
97
+ raise PyAisyncError(f"unknown --from: {args.from_target}")
98
+ if args.from_target not in targets:
99
+ targets = (*targets, args.from_target)
100
+ tlist = ", ".join(f'"{t}"' for t in targets)
101
+ feats = "\n".join(f"{f} = true" for f in FEATURES)
102
+ atomic_write(
103
+ ai / "config.toml", f"version = 1\ntargets = [{tlist}]\n\n[features]\n{feats}\n".encode()
104
+ )
105
+ existing = detect_targets(root)
106
+ # A repo that already has AI configuration should import it, not start from the examples.
107
+ examples = not args.from_target and not existing
108
+ (ai / "skills").mkdir(exist_ok=True)
109
+ if examples:
110
+ for rel, content in _TEMPLATES.items():
111
+ atomic_write(ai / rel, content.encode())
112
+ atomic_write(ai / "skills/.gitkeep", b"")
113
+ print(f"Created {AI_DIR}/ with targets: {', '.join(targets)}")
114
+ if len(targets) < len(ALL_TARGETS):
115
+ print(
116
+ f' (chosen from the tools found in this repo; to add others, edit "targets" in '
117
+ f'{AI_DIR}/config.toml, e.g. targets = ["claude", "cursor", "opencode"])'
118
+ )
119
+ if args.from_target:
120
+ _print_import(import_target(root, args.from_target, on_conflict="skip", write=True))
121
+ others = [t for t in existing if t != args.from_target]
122
+ print()
123
+ if args.from_target:
124
+ print("Next steps:")
125
+ print(
126
+ f" 1. Review {AI_DIR}/ and the warnings above (anything not imported stays in your files)."
127
+ )
128
+ for t in others:
129
+ print(f" - Also found {t} configuration: pyaisync import {t}")
130
+ print(" 2. pyaisync generate --dry-run # preview what will be created or replaced")
131
+ print(
132
+ " 3. pyaisync generate --adopt # first time only: take over your existing files"
133
+ )
134
+ print(" 4. pyaisync check # later, in CI: fails if generated files drift")
135
+ elif existing:
136
+ print(f"Existing configuration found for: {', '.join(existing)}. Bring it in first:")
137
+ for t in existing:
138
+ print(f" pyaisync import {t}")
139
+ print("Then: pyaisync generate --dry-run, and pyaisync generate --adopt (first time only).")
140
+ else:
141
+ print("Next steps:")
142
+ print(
143
+ f" 1. Edit the examples in {AI_DIR}/ (rules/, commands/); add agents/, skills/, mcp.toml, ..."
144
+ )
145
+ print(" 2. pyaisync generate --dry-run # preview")
146
+ print(" 3. pyaisync generate # write CLAUDE.md, .cursor/, AGENTS.md, ...")
147
+ print(" 4. pyaisync check # later, in CI: fails if generated files drift")
148
+ return 0
149
+
150
+
151
+ def _print_import(rep) -> None: # type: ignore[no-untyped-def]
152
+ for label in rep.written:
153
+ print(f" imported {label}")
154
+ for label in rep.unchanged:
155
+ print(f" unchanged {label}")
156
+ for msg in rep.skipped:
157
+ print(f" skipped {msg}")
158
+ for msg in rep.warnings:
159
+ print(f" warning {msg}", file=sys.stderr)
160
+
161
+
162
+ def cmd_import(args: argparse.Namespace, root: Path) -> int:
163
+ rep = import_target(root, args.target, on_conflict=args.on_conflict, write=not args.dry_run)
164
+ print("(dry run, nothing was written)" if args.dry_run else "Import:")
165
+ _print_import(rep)
166
+ return 0
167
+
168
+
169
+ def _print_report(rep: Report, *, write: bool) -> None:
170
+ verbs = (
171
+ ("created", "created " if write else "would create"),
172
+ ("updated", "updated " if write else "would update"),
173
+ ("deleted", "deleted " if write else "would delete"),
174
+ )
175
+ for attr, label in verbs:
176
+ for p in getattr(rep, attr):
177
+ print(f" {label} {p}")
178
+ print(f" unchanged: {len(rep.unchanged)}")
179
+ if rep.notices:
180
+ print(" hooks (these run commands on your machine; review them):")
181
+ for n in rep.notices:
182
+ print(f" {n}")
183
+ for w in rep.warnings:
184
+ print(f" warning: {w}", file=sys.stderr)
185
+ for c in rep.conflicts:
186
+ print(f" CONFLICT: {c}", file=sys.stderr)
187
+
188
+
189
+ def _targets_line(targets: tuple[str, ...]) -> str:
190
+ line = f"Targets: {', '.join(targets)}"
191
+ missing = [t for t in ALL_TARGETS if t not in targets]
192
+ if missing:
193
+ line += (
194
+ f' (not enabled: {", ".join(missing)} - add them to "targets" in '
195
+ f"{AI_DIR}/config.toml, or pass --targets)"
196
+ )
197
+ return line
198
+
199
+
200
+ def cmd_generate(args: argparse.Namespace, root: Path, *, check: bool = False) -> int:
201
+ model = load_model(root)
202
+ targets = _csv(args.targets, ALL_TARGETS, "targets") or model.config.targets
203
+ only = _csv(getattr(args, "features", None), FEATURES, "features")
204
+ if only is not None:
205
+ feats = {f: (f in only) and model.config.features[f] for f in FEATURES}
206
+ model = replace(model, config=replace(model.config, features=feats))
207
+ plan = build_plan(model, targets)
208
+ print(_targets_line(targets))
209
+ write = not (check or args.dry_run)
210
+ rep = apply(root, plan, write=write, force=args.force, adopt=args.adopt)
211
+ _print_report(rep, write=write and not rep.conflicts)
212
+ if rep.conflicts:
213
+ print("Nothing was written because of the conflicts above.", file=sys.stderr)
214
+ return 2
215
+ if check:
216
+ if rep.has_changes:
217
+ print(
218
+ "DRIFT: generated files do not match .ai/ (run 'pyaisync generate').",
219
+ file=sys.stderr,
220
+ )
221
+ return 1
222
+ print("OK: no drift.")
223
+ return 0
224
+
225
+
226
+ def cmd_plugin(args: argparse.Namespace, root: Path) -> int:
227
+ model = load_model(root)
228
+ plan = build_claude_plugin(model)
229
+ meta = model.config.plugin
230
+ assert meta is not None
231
+ out = Path(args.out) if args.out else Path("dist") / meta.name
232
+ out = (out if out.is_absolute() else root / out).resolve() # relative to --root
233
+ if out == root or root.is_relative_to(out):
234
+ raise PyAisyncError(f"refusing to write the plugin over the repository itself: {out}")
235
+ write = not args.dry_run
236
+ rep = apply(
237
+ out, plan, write=write, force=args.force, adopt=args.adopt, manifest_rel=PLUGIN_MANIFEST
238
+ )
239
+ print(f"Plugin '{meta.name}' -> {out}")
240
+ _print_report(rep, write=write and not rep.conflicts)
241
+ if rep.conflicts:
242
+ print("Nothing was written because of the conflicts above.", file=sys.stderr)
243
+ return 2
244
+ return 0
245
+
246
+
247
+ def cmd_target(args: argparse.Namespace, root: Path) -> int:
248
+ current = load_config(root).targets
249
+ wanted = tuple(dict.fromkeys(args.names))
250
+ if args.action == "add":
251
+ new = (*current, *[t for t in wanted if t not in current])
252
+ already = [t for t in wanted if t in current]
253
+ else:
254
+ new = tuple(t for t in current if t not in wanted)
255
+ already = [t for t in wanted if t not in current]
256
+ if not new:
257
+ raise PyAisyncError("refusing to disable every target; at least one must stay enabled")
258
+ if already:
259
+ state = "already enabled" if args.action == "add" else "was not enabled"
260
+ print(f" note: {', '.join(already)} {state}")
261
+ if new != current:
262
+ set_targets(root, new)
263
+ changed = [t for t in wanted if t not in already]
264
+ verb = "Enabled" if args.action == "add" else "Disabled"
265
+ print(f"{verb}: {', '.join(changed) or 'nothing to change'}. Targets: {', '.join(new)}")
266
+ if args.action == "add":
267
+ found = [t for t in changed if t in detect_targets(root)]
268
+ for t in found:
269
+ print(
270
+ f" Found existing {t} configuration in this repo: pyaisync import {t} (to bring it into {AI_DIR}/)"
271
+ )
272
+ print("Next: pyaisync generate --dry-run (then pyaisync generate)")
273
+ elif changed:
274
+ print(
275
+ "Next: pyaisync generate (removes the files pyaisync generated for it; your own files stay)"
276
+ )
277
+ return 0
278
+
279
+
280
+ def cmd_list(args: argparse.Namespace, root: Path) -> int:
281
+ try:
282
+ enabled: tuple[str, ...] | None = load_config(root).targets
283
+ except PyAisyncError:
284
+ enabled = None # no .ai/ here: just show what each tool supports
285
+ header = "target " + ("enabled " if enabled is not None else "")
286
+ print(header + " ".join(f"{f:11}" for f in FEATURES))
287
+ for name, tgt in REGISTRY.items():
288
+ mark = "" if enabled is None else f"{('yes' if name in enabled else 'no'):9}"
289
+ print(
290
+ f"{name:10} {mark}"
291
+ + " ".join(f"{('yes' if f in tgt.supported else 'no'):11}" for f in FEATURES)
292
+ )
293
+ if enabled is not None:
294
+ print("\nEnable or disable a tool: pyaisync target add|remove <claude|cursor|opencode>")
295
+ print("Plugins: `pyaisync plugin claude` packages .ai/ as a Claude Code plugin.")
296
+ return 0
297
+
298
+
299
+ def build_parser() -> argparse.ArgumentParser:
300
+ p = argparse.ArgumentParser(
301
+ prog="pyaisync", description="One source (.ai/) for AI coding agent configuration."
302
+ )
303
+ p.add_argument("--version", action="version", version=f"pyaisync {__version__}")
304
+ p.add_argument("--root", default=".", help="repository root (default: .)")
305
+ sub = p.add_subparsers(dest="cmd", required=True)
306
+
307
+ s = sub.add_parser("init", help="create .ai/")
308
+ s.add_argument("--targets")
309
+ s.add_argument(
310
+ "--from", dest="from_target", metavar="TARGET", help="import from claude|cursor|opencode"
311
+ )
312
+ s.set_defaults(fn=cmd_init)
313
+
314
+ for name in ("generate", "check"):
315
+ s = sub.add_parser(
316
+ name,
317
+ help="generate native files"
318
+ if name == "generate"
319
+ else "fail if generated files drifted",
320
+ )
321
+ s.add_argument("--targets")
322
+ s.add_argument("--features")
323
+ s.add_argument(
324
+ "--force", action="store_true", help="overwrite managed files that were edited by hand"
325
+ )
326
+ s.add_argument("--adopt", action="store_true", help="take over existing unmanaged files")
327
+ if name == "generate":
328
+ s.add_argument("--dry-run", action="store_true")
329
+ s.set_defaults(fn=lambda a, r: cmd_generate(a, r))
330
+ else:
331
+ s.set_defaults(fn=lambda a, r: cmd_generate(a, r, check=True), dry_run=True)
332
+
333
+ s = sub.add_parser("import", help="import a target's native config into .ai/")
334
+ s.add_argument("target", choices=ALL_TARGETS)
335
+ s.add_argument("--dry-run", action="store_true")
336
+ s.add_argument("--on-conflict", default="skip", choices=("skip", "rename", "overwrite"))
337
+ s.set_defaults(fn=cmd_import)
338
+
339
+ s = sub.add_parser("plugin", help="package .ai/ as a Claude Code plugin directory")
340
+ s.add_argument("target", choices=("claude",))
341
+ s.add_argument(
342
+ "--out", help="output directory, relative to --root (default: dist/<plugin name>)"
343
+ )
344
+ s.add_argument("--dry-run", action="store_true")
345
+ s.add_argument("--force", action="store_true", help="overwrite managed files edited by hand")
346
+ s.add_argument("--adopt", action="store_true", help="take over existing unmanaged files")
347
+ s.set_defaults(fn=cmd_plugin)
348
+
349
+ s = sub.add_parser("target", help="enable or disable a tool in .ai/config.toml")
350
+ s.add_argument("action", choices=("add", "remove"))
351
+ s.add_argument("names", nargs="+", choices=ALL_TARGETS, metavar="TARGET")
352
+ s.set_defaults(fn=cmd_target)
353
+
354
+ s = sub.add_parser("list", help="support matrix per target")
355
+ s.set_defaults(fn=cmd_list)
356
+ return p
357
+
358
+
359
+ def main(argv: list[str] | None = None) -> int:
360
+ args = build_parser().parse_args(argv)
361
+ try:
362
+ return int(args.fn(args, Path(args.root).resolve()))
363
+ except PyAisyncError as exc:
364
+ print(f"error: {exc}", file=sys.stderr)
365
+ return 2
366
+
367
+
368
+ if __name__ == "__main__":
369
+ sys.exit(main())
pyaisync/config.py ADDED
@@ -0,0 +1,97 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import tomllib
5
+ from pathlib import Path
6
+
7
+ from .errors import PyAisyncError
8
+ from .model import ALL_TARGETS, FEATURES, Config, PluginMeta
9
+ from .safefs import atomic_write
10
+
11
+ AI_DIR = ".ai"
12
+
13
+
14
+ def load_config(root: Path) -> Config:
15
+ path = root / AI_DIR / "config.toml"
16
+ if not path.is_file():
17
+ raise PyAisyncError(f"{AI_DIR}/config.toml not found (did you run 'pyaisync init'?)")
18
+ try:
19
+ data = tomllib.loads(path.read_text(encoding="utf-8"))
20
+ except tomllib.TOMLDecodeError as exc:
21
+ raise PyAisyncError(f"{path}: invalid TOML: {exc}") from exc
22
+ if data.get("version") != 1:
23
+ raise PyAisyncError(f"{path}: 'version' must be 1")
24
+ targets = tuple(data.get("targets", ALL_TARGETS))
25
+ bad = [t for t in targets if t not in ALL_TARGETS]
26
+ if bad:
27
+ raise PyAisyncError(f"{path}: unknown targets {bad}; valid: {list(ALL_TARGETS)}")
28
+ feats = {f: True for f in FEATURES}
29
+ for key, val in data.get("features", {}).items():
30
+ if key not in FEATURES:
31
+ raise PyAisyncError(f"{path}: unknown feature '{key}'; valid: {list(FEATURES)}")
32
+ if not isinstance(val, bool):
33
+ raise PyAisyncError(f"{path}: features.{key} must be true or false")
34
+ feats[key] = val
35
+ return Config(targets=targets, features=feats, plugin=_plugin(data.get("plugin"), path))
36
+
37
+
38
+ _RESERVED_PREFIXES = ("claude-", "anthropic-", "anthropics-", "cc-plugin-")
39
+ _RESERVED_NAMES = {"claude", "anthropic", "anthropics", "claude-code", "claude-mods"}
40
+
41
+
42
+ def _plugin(raw: object, path: Path) -> PluginMeta | None:
43
+ if raw is None:
44
+ return None
45
+ if not isinstance(raw, dict):
46
+ raise PyAisyncError(f"{path}: [plugin] must be a table")
47
+ unknown = set(raw) - {"name", "version", "description", "author", "license"}
48
+ if unknown:
49
+ raise PyAisyncError(f"{path}: unknown [plugin] keys {sorted(unknown)}")
50
+ for key, val in raw.items():
51
+ if not isinstance(val, str):
52
+ raise PyAisyncError(f"{path}: plugin.{key} must be a string")
53
+ name = raw.get("name", "")
54
+ if not re.fullmatch(r"[a-z0-9]+(-[a-z0-9]+)*", name):
55
+ raise PyAisyncError(f"{path}: plugin.name must be kebab-case (a-z, 0-9, '-')")
56
+ if name in _RESERVED_NAMES or name.startswith(_RESERVED_PREFIXES):
57
+ raise PyAisyncError(f"{path}: plugin.name '{name}' is reserved by Claude Code")
58
+ return PluginMeta(
59
+ name=name,
60
+ version=raw.get("version", "0.1.0"),
61
+ description=raw.get("description", ""),
62
+ author=raw.get("author", ""),
63
+ license=raw.get("license", ""),
64
+ )
65
+
66
+
67
+ _VERSION_LINE = re.compile(r"^version\s*=.*$", re.MULTILINE)
68
+ _TARGETS_KEY = re.compile(r"^targets\s*=\s*\[.*?\]", re.MULTILINE | re.DOTALL)
69
+ _FIRST_TABLE = re.compile(r"^\[", re.MULTILINE)
70
+
71
+
72
+ def set_targets(root: Path, targets: tuple[str, ...]) -> None:
73
+ """Rewrite only the top-level `targets` list of `.ai/config.toml`, keeping comments and tables."""
74
+ bad = [t for t in targets if t not in ALL_TARGETS]
75
+ if bad or not targets:
76
+ raise PyAisyncError(f"invalid targets {list(targets)}; valid: {list(ALL_TARGETS)}")
77
+ path = root / AI_DIR / "config.toml"
78
+ if not path.is_file():
79
+ raise PyAisyncError(f"{AI_DIR}/config.toml not found (did you run 'pyaisync init'?)")
80
+ text = path.read_text(encoding="utf-8")
81
+ line = "targets = [" + ", ".join(f'"{t}"' for t in targets) + "]"
82
+ table = _FIRST_TABLE.search(text)
83
+ head, tail = (text[: table.start()], text[table.start() :]) if table else (text, "")
84
+ if _TARGETS_KEY.search(head):
85
+ head = _TARGETS_KEY.sub(lambda _m: line, head, count=1)
86
+ elif _VERSION_LINE.search(head):
87
+ head = _VERSION_LINE.sub(lambda m: m.group(0) + "\n" + line, head, count=1)
88
+ else:
89
+ head = line + "\n" + head
90
+ new_text = head + tail
91
+ try:
92
+ ok = tomllib.loads(new_text).get("targets") == list(targets)
93
+ except tomllib.TOMLDecodeError:
94
+ ok = False
95
+ if not ok: # never write something we could not verify
96
+ raise PyAisyncError(f"could not update 'targets' in {path}; edit it by hand")
97
+ atomic_write(path, new_text.encode("utf-8"))
pyaisync/errors.py ADDED
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class PyAisyncError(Exception):
5
+ """Usage or validation error with a message meant for the user."""
@@ -0,0 +1,42 @@
1
+ """Minimal Markdown + YAML frontmatter parser (yaml.safe_load only)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import yaml
8
+
9
+ from .errors import PyAisyncError
10
+
11
+ _DELIM = "---"
12
+
13
+
14
+ def parse(text: str, source: str = "<text>") -> tuple[dict[str, Any], str]:
15
+ text = text.replace("\r\n", "\n")
16
+ if not text.startswith(_DELIM + "\n"):
17
+ return {}, text
18
+ end = text.find("\n" + _DELIM, len(_DELIM))
19
+ if end == -1:
20
+ raise PyAisyncError(f"{source}: frontmatter is missing its closing '---'")
21
+ raw = text[len(_DELIM) + 1 : end]
22
+ rest = text[end + len(_DELIM) + 1 :]
23
+ rest = rest.removeprefix("\n")
24
+ try:
25
+ data = yaml.safe_load(raw) if raw.strip() else {}
26
+ except yaml.YAMLError as exc:
27
+ raise PyAisyncError(f"{source}: invalid YAML frontmatter: {exc}") from exc
28
+ if data is None:
29
+ data = {}
30
+ if not isinstance(data, dict):
31
+ raise PyAisyncError(f"{source}: frontmatter must be a YAML mapping")
32
+ return data, rest
33
+
34
+
35
+ def dump(meta: dict[str, Any], body: str) -> str:
36
+ """Serialize deterministically (keys keep the caller's order)."""
37
+ body = body.lstrip("\n")
38
+ if not meta:
39
+ return body if body.endswith("\n") or not body else body + "\n"
40
+ head = yaml.safe_dump(meta, sort_keys=False, allow_unicode=True, width=1000).rstrip("\n")
41
+ out = f"{_DELIM}\n{head}\n{_DELIM}\n\n{body}"
42
+ return out if out.endswith("\n") else out + "\n"