diffpilot 0.0.1__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.
diffpilot/store.py ADDED
@@ -0,0 +1,315 @@
1
+ """Markdown stores: sections with stable IDs and text-level edit operations."""
2
+
3
+ import hashlib
4
+ import os
5
+ import re
6
+ import tempfile
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ HEADING = re.compile(r'^(#{1,6})\s+(.+?)\s*#*\s*$')
11
+ ANCHOR = re.compile(r'^\s*<!--\s*dp:id=([\w.\-]+)\s*-->\s*$')
12
+ FENCE = re.compile(r'^\s*(```|~~~)')
13
+
14
+
15
+ @dataclass
16
+ class Section:
17
+ id: str | None
18
+ level: int
19
+ heading: str
20
+ start: int # heading line index
21
+ anchor: int | None # anchor line index
22
+ end: int # exclusive: next heading of any level
23
+ subtree_end: int # exclusive: next heading of same or higher level
24
+ parent: int | None # index into the section list
25
+ path: list[str]
26
+
27
+ @property
28
+ def body_start(self) -> int:
29
+ return (self.anchor if self.anchor is not None else self.start) + 1
30
+
31
+ def body(self, lines: list[str]) -> str:
32
+ return '\n'.join(lines[self.body_start : self.end]).strip('\n')
33
+
34
+
35
+ def parse(text: str) -> list[Section]:
36
+ lines = text.split('\n')
37
+ heads: list[tuple[int, int, str, str | None]] = []
38
+ fence: str | None = None
39
+ for i, line in enumerate(lines):
40
+ m = FENCE.match(line)
41
+ if m:
42
+ fence = None if fence == m.group(1) else (fence or m.group(1))
43
+ continue
44
+ if fence:
45
+ continue
46
+ h = HEADING.match(line)
47
+ if h:
48
+ a = ANCHOR.match(lines[i + 1]) if i + 1 < len(lines) else None
49
+ heads.append((i, len(h.group(1)), h.group(2).strip(), a.group(1) if a else None))
50
+
51
+ sections: list[Section] = []
52
+ stack: list[int] = []
53
+ for n, (i, level, heading, sid) in enumerate(heads):
54
+ end = heads[n + 1][0] if n + 1 < len(heads) else len(lines)
55
+ subtree_end = next((h[0] for h in heads[n + 1 :] if h[1] <= level), len(lines))
56
+ while stack and sections[stack[-1]].level >= level:
57
+ stack.pop()
58
+ parent = stack[-1] if stack else None
59
+ path = (sections[parent].path if parent is not None else []) + [heading]
60
+ sections.append(Section(sid, level, heading, i, i + 1 if sid else None, end, subtree_end, parent, path))
61
+ stack.append(n)
62
+ return sections
63
+
64
+
65
+ def slug(text: str) -> str:
66
+ s = re.sub(r'[^\w]+', '-', text.lower(), flags=re.UNICODE).strip('-_').replace('_', '-')
67
+ if len(s) > 48:
68
+ s = s[:49].rsplit('-', 1)[0] # cut at a word boundary
69
+ return s or 'section'
70
+
71
+
72
+ def ensure_ids(text: str) -> tuple[str, bool]:
73
+ """Assign anchors to headings without one (or with a duplicate id)."""
74
+ sections = parse(text)
75
+ seen: set[str] = set()
76
+ missing: list[int] = []
77
+ for n, s in enumerate(sections):
78
+ if s.id and s.id not in seen:
79
+ seen.add(s.id)
80
+ else:
81
+ missing.append(n)
82
+ if not missing:
83
+ return text, False
84
+ lines = text.split('\n')
85
+ inserts: list[tuple[int, str, bool]] = [] # (heading line, id, replace existing anchor)
86
+ for n in missing:
87
+ s = sections[n]
88
+ parent = sections[s.parent] if s.parent is not None else None
89
+ prefix = parent.id if parent is not None and parent.level >= 2 and parent.id else ''
90
+ base = f'{prefix}.{slug(s.heading)}' if prefix else slug(s.heading)
91
+ sid, k = base, 2
92
+ while sid in seen:
93
+ sid, k = f'{base}-{k}', k + 1
94
+ seen.add(sid)
95
+ s.id = sid
96
+ inserts.append((s.start, sid, s.anchor is not None))
97
+ for line_no, sid, has_anchor in sorted(inserts, reverse=True):
98
+ anchor = f'<!-- dp:id={sid} -->'
99
+ if has_anchor:
100
+ lines[line_no + 1] = anchor
101
+ else:
102
+ lines.insert(line_no + 1, anchor)
103
+ return '\n'.join(lines), True
104
+
105
+
106
+ BULLET = re.compile(r'^[-*+]\s+(.*)$')
107
+ NESTED = re.compile(r'^\s+[-*+]\s')
108
+ OUTLINE_MAX = 2000 # a bullet-outline body above this many characters is split into subsections
109
+ HEAD_MAX = 80 # longest bullet text that may become a heading
110
+
111
+
112
+ def _promote(lines: list[str], a: int, b: int, level: int) -> list[str] | None:
113
+ """Turn the top-level bullets with nested bullets in lines[a:b] into level-`level` headings (lossless).
114
+
115
+ Only when, from the first such bullet on, every unindented line is such a bullet: nothing changes owner.
116
+ """
117
+ items: list[int] = [] # unindented lines (outside fences) in the region
118
+ fence = False
119
+ for i in range(a, b):
120
+ if not fence and lines[i].strip() and not lines[i][:1].isspace():
121
+ items.append(i)
122
+ if FENCE.match(lines[i]):
123
+ fence = not fence
124
+ items.append(b)
125
+
126
+ def children(n: int) -> list[str]:
127
+ return lines[items[n] + 1 : items[n + 1]]
128
+
129
+ branch = [
130
+ n for n in range(len(items) - 1) if BULLET.match(lines[items[n]]) and any(NESTED.match(c) for c in children(n))
131
+ ]
132
+ if not branch or branch != list(range(branch[0], len(items) - 1)):
133
+ return None
134
+ out = lines[a : items[branch[0]]]
135
+ for n in branch:
136
+ head, kids = BULLET.match(lines[items[n]]).group(1).strip(), children(n)
137
+ while kids and kids[0].strip() and not NESTED.match(kids[0]): # wrapped item text belongs to the heading
138
+ head += ' ' + kids.pop(0).strip()
139
+ if len(head) > HEAD_MAX: # a paragraph, not a name: this list is prose, not an outline
140
+ return None
141
+ indent = min(len(k) - len(k.lstrip()) for k in kids if k.strip())
142
+ kids = [k[indent:] for k in kids]
143
+ if any(HEADING.match(k) for k in kids): # dedenting would create a heading: leave the outline alone
144
+ return None
145
+ out += [f'{"#" * level} {head}', '', *kids, '']
146
+ return out
147
+
148
+
149
+ def promote_outline(text: str, max_chars: int = OUTLINE_MAX) -> str:
150
+ """Split oversized bullet-outline bodies (docs written as one nested list) into heading sections.
151
+
152
+ Repeats until no oversized body can be split, so a 40 KB bestiary becomes one section per creature.
153
+ """
154
+ changed = False
155
+ while True:
156
+ lines = text.split('\n')
157
+ sections = parse(text)
158
+ first = sections[0].start if sections else len(lines)
159
+ regions = [(0, first, 2)] + [(s.body_start, s.end, s.level + 1) for s in sections if s.level < 6]
160
+ for a, b, level in regions:
161
+ if len('\n'.join(lines[a:b])) > max_chars and (new := _promote(lines, a, b, level)) is not None:
162
+ text, changed = '\n'.join(lines[:a] + new + lines[b:]), True
163
+ break
164
+ else:
165
+ return normalize(text) if changed else text
166
+
167
+
168
+ def section_hash(heading: str, body: str) -> str:
169
+ return hashlib.sha256(f'{heading}\n{body.strip()}'.encode()).hexdigest()[:12]
170
+
171
+
172
+ def tokens(text: str) -> int:
173
+ return len(text) // 4 + 1
174
+
175
+
176
+ def clip(text: str, n: int) -> str:
177
+ """Collapse whitespace and cut to n characters."""
178
+ text = re.sub(r'\s+', ' ', text).strip()
179
+ return text if len(text) <= n else text[:n] + '…'
180
+
181
+
182
+ def clean_body(text: str, heading: str | None = None) -> list[str]:
183
+ """Normalize model-written body text: no anchors, no duplicated heading line."""
184
+ lines = [ln for ln in text.strip('\n').split('\n') if not ANCHOR.match(ln)]
185
+ if lines and heading:
186
+ h = HEADING.match(lines[0])
187
+ if h and h.group(2).strip().lower() == heading.strip().lower():
188
+ lines = lines[1:]
189
+ while lines and not lines[0].strip():
190
+ lines.pop(0)
191
+ return lines
192
+
193
+
194
+ def _find(sections: list[Section], sid: str) -> Section:
195
+ for s in sections:
196
+ if s.id == sid:
197
+ return s
198
+ raise KeyError(sid)
199
+
200
+
201
+ def _trim_trailing_blank(lines: list[str], start: int, end: int) -> int:
202
+ while end > start and not lines[end - 1].strip():
203
+ end -= 1
204
+ return end
205
+
206
+
207
+ def op_replace(text: str, sid: str, body: str, heading: str | None = None) -> str:
208
+ lines = text.split('\n')
209
+ s = _find(parse(text), sid)
210
+ new = clean_body(body, heading or s.heading)
211
+ tail = [''] if s.end < len(lines) else []
212
+ lines[s.body_start : s.end] = new + tail
213
+ if heading and heading.strip() != s.heading:
214
+ lines[s.start] = f'{"#" * s.level} {heading.strip()}'
215
+ return '\n'.join(lines)
216
+
217
+
218
+ def op_append(text: str, sid: str, body: str) -> str:
219
+ lines = text.split('\n')
220
+ s = _find(parse(text), sid)
221
+ at = _trim_trailing_blank(lines, s.body_start, s.end)
222
+ block = clean_body(body)
223
+ if at > s.body_start:
224
+ block = [''] + block
225
+ lines[at:at] = block
226
+ return '\n'.join(lines)
227
+
228
+
229
+ def op_add(text: str, parent: str | None, heading: str, body: str) -> str:
230
+ lines = text.split('\n')
231
+ if parent:
232
+ p = _find(parse(text), parent)
233
+ level, at = min(p.level + 1, 6), p.subtree_end
234
+ else:
235
+ level, at = 2, len(lines)
236
+ at = _trim_trailing_blank(lines, 0, at)
237
+ block = ['', f'{"#" * level} {heading.strip()}', *_nest(clean_body(body, heading), level), '']
238
+ lines[at:at] = block
239
+ return '\n'.join(lines)
240
+
241
+
242
+ def _nest(lines: list[str], level: int) -> list[str]:
243
+ """Shift subheadings in a new section's body so the shallowest sits one level below the section (max 6)."""
244
+ fence = False
245
+ heads = []
246
+ for i, line in enumerate(lines):
247
+ fence = fence != bool(FENCE.match(line))
248
+ if not fence and (h := HEADING.match(line)):
249
+ heads.append((i, len(h.group(1)), h.group(2)))
250
+ if not heads:
251
+ return lines
252
+ shift = level + 1 - min(n for _, n, _ in heads)
253
+ out = list(lines)
254
+ for i, n, title in heads:
255
+ out[i] = f'{"#" * min(max(n + shift, level + 1), 6)} {title.strip()}'
256
+ return out
257
+
258
+
259
+ def op_delete(text: str, sid: str) -> str:
260
+ lines = text.split('\n')
261
+ s = _find(parse(text), sid)
262
+ del lines[s.start : s.subtree_end]
263
+ return '\n'.join(lines)
264
+
265
+
266
+ def normalize(text: str) -> str:
267
+ """Collapse runs of blank lines (outside fences) and end with one newline."""
268
+ out: list[str] = []
269
+ fence = False
270
+ for line in text.split('\n'):
271
+ if FENCE.match(line):
272
+ fence = not fence
273
+ if not fence and not line.strip() and out and not out[-1].strip():
274
+ continue
275
+ out.append(line)
276
+ return '\n'.join(out).strip('\n') + '\n'
277
+
278
+
279
+ def atomic_write(path: Path, text: str) -> None:
280
+ path.parent.mkdir(parents=True, exist_ok=True)
281
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f'.{path.name}.')
282
+ with os.fdopen(fd, 'w', encoding='utf-8') as f:
283
+ f.write(text)
284
+ umask = os.umask(0)
285
+ os.umask(umask)
286
+ os.chmod(tmp, path.stat().st_mode & 0o777 if path.exists() else 0o666 & ~umask)
287
+ os.replace(tmp, path)
288
+
289
+
290
+ if __name__ == '__main__': # self-check: uv run python -m diffpilot.store
291
+ doc = '# Title\n\nIntro\n\n## Shop\n\nShop text\n\n### Cards\n\n4 cards\n\n```\n# not a heading\n```\n\n## Save\n\nsave\n'
292
+ doc, changed = ensure_ids(doc)
293
+ assert changed and '<!-- dp:id=shop.cards -->' in doc and '<!-- dp:id=title -->' in doc, doc
294
+ assert ensure_ids(doc) == (doc, False)
295
+ doc = op_replace(doc, 'shop.cards', '6 cards', 'Shop cards')
296
+ s = {x.id: x for x in parse(doc)}
297
+ assert s['shop.cards'].heading == 'Shop cards' and s['shop.cards'].body(doc.split('\n')).startswith('6 cards')
298
+ doc = op_add(doc, 'shop', 'Currency', 'Gold only')
299
+ assert [x.id for x in parse(ensure_ids(doc)[0])] == ['title', 'shop', 'shop.cards', 'shop.currency', 'save']
300
+ doc = op_add(doc, 'save', 'Sync', '## Cloud\n\nvia S3\n\n### Conflicts\n\nnewest wins\n\n```\n# code\n```')
301
+ assert '### Sync\n' in doc and '#### Cloud\n' in doc and '##### Conflicts\n' in doc and '# code' in doc, doc
302
+ doc = op_append(doc, 'save', 'cloud sync')
303
+ doc = op_delete(ensure_ids(doc)[0], 'shop')
304
+ ids = ['title', 'save', 'save.sync', 'save.sync.cloud', 'save.sync.cloud.conflicts']
305
+ assert [x.id for x in parse(doc)] == ids and 'cloud sync' in doc, [x.id for x in parse(doc)]
306
+ bestiary = '# Mobs\n\n- Rules\n - gold 1\n- Roster\n - Imp\n - fast\n - Ogre: big and\n slow\n - tank\n'
307
+ out = promote_outline(bestiary, max_chars=10)
308
+ assert [x.heading for x in parse(out)] == ['Mobs', 'Rules', 'Roster', 'Imp', 'Ogre: big and slow'], out
309
+ assert '### Imp\n\n- fast\n' in out and '## Rules\n\n- gold 1\n' in out, out
310
+ assert promote_outline(bestiary) == bestiary # small enough: untouched
311
+ prose = '# Log\n\n- ' + 'long sentence ' * 8 + '\n - detail\n' # a paragraph never becomes a heading
312
+ assert promote_outline(prose, max_chars=1) == prose
313
+ flat = '# X\n\n- a\n - b\nprose after\n' # promoting would move the prose under `a`: refused
314
+ assert promote_outline(flat, max_chars=1) == flat
315
+ print('ok')
diffpilot/store.pyi ADDED
@@ -0,0 +1,43 @@
1
+ from _typeshed import Incomplete
2
+ from dataclasses import dataclass
3
+ from pathlib import Path
4
+
5
+ HEADING: Incomplete
6
+ ANCHOR: Incomplete
7
+ FENCE: Incomplete
8
+
9
+ @dataclass
10
+ class Section:
11
+ id: str | None
12
+ level: int
13
+ heading: str
14
+ start: int
15
+ anchor: int | None
16
+ end: int
17
+ subtree_end: int
18
+ parent: int | None
19
+ path: list[str]
20
+ @property
21
+ def body_start(self) -> int: ...
22
+ def body(self, lines: list[str]) -> str: ...
23
+
24
+ def parse(text: str) -> list[Section]: ...
25
+ def slug(text: str) -> str: ...
26
+ def ensure_ids(text: str) -> tuple[str, bool]: ...
27
+
28
+ BULLET: Incomplete
29
+ NESTED: Incomplete
30
+ OUTLINE_MAX: int
31
+ HEAD_MAX: int
32
+
33
+ def promote_outline(text: str, max_chars: int = ...) -> str: ...
34
+ def section_hash(heading: str, body: str) -> str: ...
35
+ def tokens(text: str) -> int: ...
36
+ def clip(text: str, n: int) -> str: ...
37
+ def clean_body(text: str, heading: str | None = None) -> list[str]: ...
38
+ def op_replace(text: str, sid: str, body: str, heading: str | None = None) -> str: ...
39
+ def op_append(text: str, sid: str, body: str) -> str: ...
40
+ def op_add(text: str, parent: str | None, heading: str, body: str) -> str: ...
41
+ def op_delete(text: str, sid: str) -> str: ...
42
+ def normalize(text: str) -> str: ...
43
+ def atomic_write(path: Path, text: str) -> None: ...