M
Markdown 台账同步 / Markdown Ledger Sync
作者:红叶开发工具v1
安全地把数据库、问题追踪、需求池等外部待办合并进 Markdown 台账,绝不误删手写正文。Safely merge external todos (DB, issue tracker, requirement pool, email) into a human-maintained Markdown ledger without corrupting hand-written content. Use when programmatically rewriting a Markdown checklist, merging remote todos into a local md list, or automating any Markdown auto-section update. 触发词:同步到 md、自动归并、台账同步、md 自动块、ledger sync。
下载量
358
点赞
88
价格
¥0.20
精选
技能文档
---
name: markdown-ledger-sync
display_name: Markdown 台账同步 / Markdown Ledger Sync
description: 安全地把数据库、问题追踪、需求池等外部待办合并进 Markdown 台账,绝不误删手写正文。Safely merge external todos (DB, issue tracker, requirement pool, email) into a human-maintained Markdown ledger without corrupting hand-written content. Use when programmatically rewriting a Markdown checklist, merging remote todos into a local md list, or automating any Markdown auto-section update. 触发词:同步到 md、自动归并、台账同步、md 自动块、ledger sync。
summary_zh: 安全地把数据库、问题追踪、需求池等外部待办合并进一份人工维护的 Markdown 台账,绝不误删手写正文。
summary_en: Safely merge external todos (DB, issue tracker, requirement pool, email) into a human-maintained Markdown ledger without corrupting hand-written content.
version: 1.0.1
category: automation
tags: [markdown, ledger, todo, checklist, sync, automation]
---
# Markdown Ledger Auto-Sync (safe rewrite playbook)
Programmatically rewriting a **human-maintained Markdown ledger** (requirement list, issue tracker, todo board) is a classic way to accidentally swallow large chunks of prose. This playbook gives a ready-to-use skeleton and the red lines that must be respected. **Read the red lines before writing any code.**
## 简介 / Introduction
**中文**:这是一套"安全改写 Markdown 台账"的方法论 + 即拷即用的参数化骨架脚本。核心解决一个高频事故:AI 或脚本定时把远端待办同步进本地 Markdown 清单时,极易把正文整段吞掉(实测曾一次误删 800+ 行)。提供 5 条红线(先备份、显式标记圈定自动区、判重只针对条目行、锚点正则别被勾选框骗、护栏防净删超 20%)+ 可直接套用的骨架。
**English**: A safe-rewrite playbook plus a ready-to-use parameterized skeleton for syncing external todos into a Markdown ledger. It prevents the classic incident where automated merges silently swallow hand-written prose, via five red lines (backup first, explicit markers, item-line-only dedup, correct anchor regex, >20% shrink guard) and a copy-paste skeleton.
A ready-made, parameterized implementation lives in `scripts/sync_ledger_template.py`. Copy it, set your own constants (path, markers, heading), and follow the acceptance checklist in `references/acceptance-checklist.md`.
## 一、Five red lines (violating any of them causes incidents; all field-tested)
1. **Back up before running.** The ledger is the only copy; loss is unrecoverable.
```python
shutil.copy2(MD, f"{MD}.bak_{time:%H%M%S}") # or cp to a safe tmp dir
```
2. **Wrap the auto-section in explicit start/end markers.** Never `find("\n---")` / `find("\n## ")` / regex to guess the boundary. In Markdown, `---` is a section divider and is unrelated to your auto-block — from block start to the next `---` may be hundreds of lines of prose.
```python
START_MARK = "<!-- SYNC:START -->"
END_MARK = "<!-- SYNC:END -->"
```
3. **Insertion point must land between START/END**, never "right after the heading line" — if the marker is one line under the heading, inserting under the heading lands outside the markers and the block structure decays, causing later replacements to silently miss.
Priority: has `END` → insert before it (ensuring it owns its own line); only `START` → insert after it; only a stale heading → add `START`; nothing → create a fresh full block.
4. **Do not duplicate constant assembly.** If the new heading text already ends with `START_MARK`, do not concatenate it again — that produces two START markers.
5. **Deduplicate only on the item lines, never a bare substring over the whole text.** `anchor in text` returns True forever when the id happens to appear in a bug description, code block, or quote — that item then never syncs back.
```python
def anchor_exists(text, anchor):
for line in text.splitlines():
s = line.lstrip()
if s.startswith("- [ ] **") or s.startswith("- [x] **"):
if anchor in s:
return True
return False
```
5b. **Anchor regex must match the BOLD bracketed id `**[ID]**`, not a bare `[ID]`.** A naive
`r"\[([^\]\[]+)\]"` matches the **empty checkbox `[ ]`** first on a line like
`- [ ] **[REQ-001]** ...`, yielding `" "` as the "anchor" — so every new item looks
"already synced" and nothing is ever inserted. Anchor on `\*\*\[([^\]\[]+)\]\*\*`
(field-tested: a first pass shipped this bug and synced nothing).
## 二、Reference skeleton
Minimal core of the merge step (full version in the script):
```python
# 1) Group lines into items; each item's first line starts with "- [ ] **<ANCHOR>** "
# 2) Dedup via anchor_exists() against current file text (red line 5)
# 3) Find insertion point: END present -> insert before it; else START -> after; else stale heading -> add START; else create block
# 4) Guard: if new line count < 80% of original, abort and keep the backup
# 5) Write file, log "merged N items"
```
Never trust the script's own "merged N" count — a log once said +8 yet the file shrank by 815 lines. After every run, diff or compare line counts.
## 三、Rules for other must-know pitfalls
- **Comments must match implementation.** A comment once claimed "replace only between two markers" while the code inserted after the heading — misleading for everyone downstream.
- **Do not place the auto-block directly under a section heading** (it entangles with prose); a standalone section or the file end is safer.
- **Count by item, not by line.** Iterate and match the per-item anchor pattern, otherwise a 4-line item is tallied as 4 items.
- **Join multi-line items with `"\n".join`** — writing `"".join` squashes everything into one line.
- **Concurrent edits**: when several people/sessions touch the same md, first confirm whether another party already changed it to avoid overwrites.
- **`description` must stay free of angle brackets**; `name` must be hyphen-case (lowercase letters/digits/hyphens).
## 四、Suggested workflow
1. Copy `scripts/sync_ledger_template.py` into your project.
2. Set your constants: `MD` (ledger path), `START_MARK`/`END_MARK`, heading text, and the remote-source query that produces your entries.
3. Run the `merge()` function and open `references/acceptance-checklist.md`; execute every row.
4. Run the script twice more to confirm idempotence (no additions, unchanged line count).
使用说明
## 解决什么问题 把数据库、问题追踪、需求池、邮件等外部待办安全合并进一份人工维护的 Markdown 台账(需求清单 / 问题追踪 / 待办板),绝不误删手写正文。 ## 核心保障 - **写入前自动备份**:任何改写前先落备份,出问题可回滚。 - **只改写显式标记区间**:用 `<!-- SYNC:xxx:START -->` / `<!-- SYNC:xxx:END -->` 圈定自动区,标记外的手写正文一字不动。 - **判重只看条目行**:描述里出现相同编号不会误判为"已同步"。 - **内置护栏**:一旦检测到文件将净删超过 20%,立即中止并保留备份。 ## 使用方式 1. 在 Markdown 台账中用 START / END 标记圈出自动区块。 2. 运行同步脚本,传入数据源与台账路径。 3. 脚本只重写标记区间内的内容,其余原样保留;重复执行结果一致(幂等)。 ## 适用场景 从数据库、需求池、邮件把新条目归并进 Markdown 台账,或任何需要 AI 稳定、可回滚地改写一份长 Markdown 的自动化。 ## 自测 含 13 项自动化用例(幂等、正文保护、判重、护栏、prose-id 不误判),全部通过。
支持平台:Qoder · QoderWork · Claude · Codex 等 AI 编程助手