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/__init__.py +11 -0
- diffpilot/__init__.pyi +3 -0
- diffpilot/__main__.py +3 -0
- diffpilot/__main__.pyi +1 -0
- diffpilot/agents.py +438 -0
- diffpilot/agents.pyi +81 -0
- diffpilot/agentsmd.py +97 -0
- diffpilot/agentsmd.pyi +12 -0
- diffpilot/bootstrap.py +456 -0
- diffpilot/bootstrap.pyi +49 -0
- diffpilot/cli.py +731 -0
- diffpilot/cli.pyi +62 -0
- diffpilot/config.py +342 -0
- diffpilot/config.pyi +109 -0
- diffpilot/core.py +333 -0
- diffpilot/core.pyi +26 -0
- diffpilot/events.py +172 -0
- diffpilot/events.pyi +28 -0
- diffpilot/gitdiff.py +170 -0
- diffpilot/gitdiff.pyi +14 -0
- diffpilot/index.py +242 -0
- diffpilot/index.pyi +60 -0
- diffpilot/jev.py +203 -0
- diffpilot/jev.pyi +33 -0
- diffpilot/llm.py +141 -0
- diffpilot/llm.pyi +28 -0
- diffpilot/ops.py +285 -0
- diffpilot/ops.pyi +31 -0
- diffpilot/prompts.py +432 -0
- diffpilot/prompts.pyi +28 -0
- diffpilot/py.typed +0 -0
- diffpilot/schemas.py +110 -0
- diffpilot/schemas.pyi +88 -0
- diffpilot/store.py +315 -0
- diffpilot/store.pyi +43 -0
- diffpilot/verify.py +352 -0
- diffpilot/verify.pyi +58 -0
- diffpilot-0.0.1.dist-info/METADATA +80 -0
- diffpilot-0.0.1.dist-info/RECORD +42 -0
- diffpilot-0.0.1.dist-info/WHEEL +5 -0
- diffpilot-0.0.1.dist-info/entry_points.txt +2 -0
- diffpilot-0.0.1.dist-info/top_level.txt +1 -0
diffpilot/bootstrap.py
ADDED
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
"""init --bootstrap and coverage: seed the stores from existing project docs and measure what they hold."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import fnmatch
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import re
|
|
9
|
+
import subprocess
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from diffpilot import agents, prompts, store
|
|
14
|
+
from diffpilot.agents import Deps
|
|
15
|
+
from diffpilot.agentsmd import outside
|
|
16
|
+
from diffpilot.config import Config, DPError, git_ignored
|
|
17
|
+
from diffpilot.core import refresh_summaries
|
|
18
|
+
from diffpilot.index import Index, now
|
|
19
|
+
from diffpilot.jev import chunk_value, covered, rank
|
|
20
|
+
from diffpilot.llm import Engine
|
|
21
|
+
from diffpilot.ops import apply_ops, open_index
|
|
22
|
+
from diffpilot.schemas import Fact
|
|
23
|
+
|
|
24
|
+
log = logging.getLogger('diffpilot')
|
|
25
|
+
|
|
26
|
+
DOC_EXT = {'.md', '.mdx', '.markdown', '.rst'}
|
|
27
|
+
SKIP_DIRS = {
|
|
28
|
+
'node_modules',
|
|
29
|
+
'.git',
|
|
30
|
+
'.venv',
|
|
31
|
+
'venv',
|
|
32
|
+
'dist',
|
|
33
|
+
'build',
|
|
34
|
+
'vendor',
|
|
35
|
+
'__pycache__',
|
|
36
|
+
'.pytest_cache',
|
|
37
|
+
'htmlcov',
|
|
38
|
+
'site-packages',
|
|
39
|
+
}
|
|
40
|
+
SKIP_NAMES = re.compile(r'^(license|licence|copying|notice)(\.|$)', re.I)
|
|
41
|
+
CHUNK_MAX = 6000
|
|
42
|
+
EXTRACT_PARALLEL = 4 # concurrent extraction requests (fast model)
|
|
43
|
+
TRIAGE_THRESHOLD = 0.2 # Jev P(durable knowledge) below this: chunk skipped (conservative)
|
|
44
|
+
COVERED_THRESHOLD = 0.6 # Jev P(fact already recorded) at or above this: not merged again
|
|
45
|
+
|
|
46
|
+
type Found = tuple[Fact, Chunk]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class Chunk:
|
|
51
|
+
file: str
|
|
52
|
+
start: int
|
|
53
|
+
end: int
|
|
54
|
+
text: str
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def hash(self) -> str:
|
|
58
|
+
return hashlib.sha256(' '.join(self.text.split()).encode()).hexdigest()[:16]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def inventory(cfg: Config, include: list[str], exclude: list[str], max_files: int) -> list[str]:
|
|
62
|
+
try:
|
|
63
|
+
if not cfg.behavior.git:
|
|
64
|
+
raise OSError
|
|
65
|
+
out = subprocess.run(
|
|
66
|
+
['git', 'ls-files', '-co', '--exclude-standard'], cwd=cfg.root, capture_output=True, text=True, check=True
|
|
67
|
+
).stdout.splitlines()
|
|
68
|
+
except (OSError, subprocess.CalledProcessError):
|
|
69
|
+
found = [cfg.rel(p) for p in cfg.root.rglob('*') if p.is_file() and '.git' not in p.parts]
|
|
70
|
+
out = sorted(set(found) - git_ignored(cfg, found))
|
|
71
|
+
files = []
|
|
72
|
+
for rel in out:
|
|
73
|
+
parts = rel.split('/')
|
|
74
|
+
if any(p in SKIP_DIRS for p in parts) or SKIP_NAMES.match(parts[-1]):
|
|
75
|
+
continue
|
|
76
|
+
if Path(rel).suffix.lower() not in DOC_EXT or cfg.is_own(rel): # feedback-loop guard
|
|
77
|
+
continue
|
|
78
|
+
if include and not any(fnmatch.fnmatch(rel, g) for g in include):
|
|
79
|
+
continue
|
|
80
|
+
if any(fnmatch.fnmatch(rel, g) for g in exclude):
|
|
81
|
+
continue
|
|
82
|
+
if (cfg.root / rel).is_file():
|
|
83
|
+
files.append(rel)
|
|
84
|
+
files.sort(key=lambda r: (not Path(r).name.lower().startswith('readme'), r.count('/'), r))
|
|
85
|
+
return files[:max_files]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def read_source(cfg: Config, rel: str) -> str:
|
|
89
|
+
text = (cfg.root / rel).read_text(encoding='utf-8', errors='replace')
|
|
90
|
+
if rel == cfg.paths.agents_md:
|
|
91
|
+
text = outside(text) # never read diffpilot's own sections
|
|
92
|
+
return text
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def chunk(rel: str, text: str) -> list[Chunk]:
|
|
96
|
+
lines = text.split('\n')
|
|
97
|
+
starts = [i for i, ln in enumerate(lines) if re.match(r'^#{1,3}\s', ln)]
|
|
98
|
+
bounds = sorted({0, *starts, len(lines)})
|
|
99
|
+
pieces = [(a, b) for a, b in zip(bounds, bounds[1:], strict=False) if '\n'.join(lines[a:b]).strip()]
|
|
100
|
+
out: list[Chunk] = []
|
|
101
|
+
cur: tuple[int, int] | None = None
|
|
102
|
+
for a, b in pieces:
|
|
103
|
+
while b - a > 0 and len('\n'.join(lines[a:b])) > CHUNK_MAX: # split oversized sections by lines
|
|
104
|
+
n = a
|
|
105
|
+
while n < b and len('\n'.join(lines[a : n + 1])) <= CHUNK_MAX:
|
|
106
|
+
n += 1
|
|
107
|
+
n = max(n, a + 1)
|
|
108
|
+
if cur:
|
|
109
|
+
out.append(Chunk(rel, cur[0], cur[1], '\n'.join(lines[cur[0] : cur[1]])))
|
|
110
|
+
cur = None
|
|
111
|
+
out.append(Chunk(rel, a, n, '\n'.join(lines[a:n])))
|
|
112
|
+
a = n
|
|
113
|
+
if a >= b:
|
|
114
|
+
continue
|
|
115
|
+
if cur and len('\n'.join(lines[cur[0] : b])) <= CHUNK_MAX:
|
|
116
|
+
cur = (cur[0], b)
|
|
117
|
+
else:
|
|
118
|
+
if cur:
|
|
119
|
+
out.append(Chunk(rel, cur[0], cur[1], '\n'.join(lines[cur[0] : cur[1]])))
|
|
120
|
+
cur = (a, b)
|
|
121
|
+
if cur:
|
|
122
|
+
out.append(Chunk(rel, cur[0], cur[1], '\n'.join(lines[cur[0] : cur[1]])))
|
|
123
|
+
return out
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _norm(text: str) -> str:
|
|
127
|
+
return re.sub(r'[\s*_`>#|]+', ' ', text).strip().lower()
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def skeleton(cfg: Config) -> str:
|
|
131
|
+
entries = sorted(p.name + ('/' if p.is_dir() else '') for p in cfg.root.iterdir() if not p.name.startswith('.'))
|
|
132
|
+
return ' '.join(e for e in entries if e.rstrip('/') not in SKIP_DIRS)[:1500]
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class Manifest:
|
|
136
|
+
def __init__(self, cfg: Config) -> None:
|
|
137
|
+
self.path = cfg.state / 'bootstrap.json'
|
|
138
|
+
self.data: dict = json.loads(self.path.read_text()) if self.path.exists() else {'files': {}}
|
|
139
|
+
|
|
140
|
+
def save(self) -> None:
|
|
141
|
+
store.atomic_write(self.path, json.dumps(self.data, indent=1, ensure_ascii=False, sort_keys=True) + '\n')
|
|
142
|
+
|
|
143
|
+
def chunks(self, rel: str) -> dict:
|
|
144
|
+
return self.data['files'].setdefault(rel, {'chunks': {}})['chunks']
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
async def run(cfg: Config, include: list[str], exclude: list[str], max_files: int, force: bool) -> dict:
|
|
148
|
+
report: dict = {
|
|
149
|
+
'sources': 0,
|
|
150
|
+
'skipped_unchanged': 0,
|
|
151
|
+
'chunks': 0,
|
|
152
|
+
'facts': 0,
|
|
153
|
+
'dropped': 0,
|
|
154
|
+
'triaged': 0,
|
|
155
|
+
'recorded': 0,
|
|
156
|
+
'lines': [],
|
|
157
|
+
'conflicts': [],
|
|
158
|
+
'orphaned': [],
|
|
159
|
+
'warnings': [],
|
|
160
|
+
'events': [],
|
|
161
|
+
}
|
|
162
|
+
idx = open_index(cfg)
|
|
163
|
+
man = Manifest(cfg)
|
|
164
|
+
files = inventory(cfg, include, exclude, max_files)
|
|
165
|
+
report['sources'] = len(files)
|
|
166
|
+
pending, stale_refs = _changed(cfg, man, files, force, report)
|
|
167
|
+
deleted = [rel for rel in man.data['files'] if not (cfg.root / rel).exists()]
|
|
168
|
+
report['orphaned'] = sorted({
|
|
169
|
+
r
|
|
170
|
+
for rel in deleted
|
|
171
|
+
for c in man.data['files'][rel]['chunks'].values()
|
|
172
|
+
for r in c.get('refs', [])
|
|
173
|
+
if r in idx.views
|
|
174
|
+
})
|
|
175
|
+
for rel in deleted: # reported once; the sections keep their `sources` provenance in the index
|
|
176
|
+
del man.data['files'][rel]
|
|
177
|
+
report['chunks'] = len(pending)
|
|
178
|
+
man.save()
|
|
179
|
+
if not pending:
|
|
180
|
+
return report
|
|
181
|
+
|
|
182
|
+
async with Engine(cfg, 'bootstrap') as engine:
|
|
183
|
+
pending = await _triage(engine, man, pending, report)
|
|
184
|
+
found = await _extract(cfg, engine, pending, report)
|
|
185
|
+
found = await _drop_recorded(cfg, idx, engine, found, report)
|
|
186
|
+
with_facts = {c.hash for _, c in found}
|
|
187
|
+
for c in pending: # chunks without facts are done now
|
|
188
|
+
if c.hash not in with_facts:
|
|
189
|
+
man.chunks(c.file)[c.hash] = {'lines': [c.start + 1, c.end], 'refs': []}
|
|
190
|
+
man.save()
|
|
191
|
+
if found:
|
|
192
|
+
await refresh_summaries(cfg, idx, engine) # once: later batches see first-sentence summaries
|
|
193
|
+
groups = _merge_groups(found, cfg.behavior.context_budget * 2)
|
|
194
|
+
log.warning('bootstrap: %d facts from %d chunks, %d merge batch(es)', len(found), len(pending), len(groups))
|
|
195
|
+
for group in groups:
|
|
196
|
+
await _merge(cfg, idx, engine, man, group, stale_refs, report)
|
|
197
|
+
return report
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _changed(
|
|
201
|
+
cfg: Config, man: Manifest, files: list[str], force: bool, report: dict
|
|
202
|
+
) -> tuple[list[Chunk], dict[str, list[str]]]:
|
|
203
|
+
"""Return new or changed chunks, and per file the refs derived from chunks that no longer exist."""
|
|
204
|
+
pending: list[Chunk] = []
|
|
205
|
+
stale_refs: dict[str, list[str]] = {}
|
|
206
|
+
for rel in files:
|
|
207
|
+
chunks = chunk(rel, read_source(cfg, rel))
|
|
208
|
+
known = man.chunks(rel)
|
|
209
|
+
current = {c.hash for c in chunks}
|
|
210
|
+
for h in [h for h in known if h not in current]:
|
|
211
|
+
stale_refs.setdefault(rel, []).extend(known.pop(h).get('refs', []))
|
|
212
|
+
new = [c for c in chunks if force or c.hash not in known]
|
|
213
|
+
report['skipped_unchanged'] += not new
|
|
214
|
+
pending += new
|
|
215
|
+
return pending, stale_refs
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _batches(chunks: list[Chunk], budget_chars: int) -> list[list[Chunk]]:
|
|
219
|
+
out: list[list[Chunk]] = [[]]
|
|
220
|
+
size = 0
|
|
221
|
+
for c in chunks:
|
|
222
|
+
if out[-1] and size + len(c.text) > budget_chars:
|
|
223
|
+
out.append([])
|
|
224
|
+
size = 0
|
|
225
|
+
out[-1].append(c)
|
|
226
|
+
size += len(c.text)
|
|
227
|
+
return [b for b in out if b]
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
async def _triage(engine: Engine, man: Manifest, chunks: list[Chunk], report: dict) -> list[Chunk]:
|
|
231
|
+
"""Drop chunks Jev rates as holding no durable knowledge (badges, install steps, history). Skipped without Jev."""
|
|
232
|
+
probs = await chunk_value(engine.jev, {c.hash: f'{c.file}\n{c.text}' for c in chunks})
|
|
233
|
+
if probs is None:
|
|
234
|
+
return chunks
|
|
235
|
+
keep = [c for c in chunks if probs.get(c.hash, 1.0) >= TRIAGE_THRESHOLD]
|
|
236
|
+
for c in chunks:
|
|
237
|
+
if c not in keep:
|
|
238
|
+
man.chunks(c.file)[c.hash] = {'lines': [c.start + 1, c.end], 'refs': [], 'skipped': 'no durable knowledge'}
|
|
239
|
+
report['triaged'] = len(chunks) - len(keep)
|
|
240
|
+
return keep
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
async def _extract(cfg: Config, engine: Engine, chunks: list[Chunk], report: dict) -> list[Found]:
|
|
244
|
+
"""Extract quote-verified facts from all chunks: large batches, several requests in parallel."""
|
|
245
|
+
batches = _batches(chunks, cfg.behavior.context_budget * 2) # smaller = better recall; same tokens, parallel
|
|
246
|
+
log.warning('bootstrap: extracting from %d chunks in %d batch(es)', len(chunks), len(batches))
|
|
247
|
+
limit = asyncio.Semaphore(EXTRACT_PARALLEL)
|
|
248
|
+
sk = skeleton(cfg)
|
|
249
|
+
cats = ', '.join(f'{st} ({cfg.store_title(st)})' for st in cfg.stores if '.' in st)
|
|
250
|
+
categories = f'PRD category stores (use for details of their area): {cats}' if cats else ''
|
|
251
|
+
|
|
252
|
+
async def one(batch: list[Chunk]) -> list[Found]:
|
|
253
|
+
text = '\n\n'.join(f'[chunk {i}] {c.file}:{c.start + 1}-{c.end}\n{c.text}' for i, c in enumerate(batch))
|
|
254
|
+
async with limit:
|
|
255
|
+
ext = await engine.run(
|
|
256
|
+
agents.extractor, prompts.EXTRACT.format(skeleton=sk, chunks=text, categories=categories), fast=True
|
|
257
|
+
)
|
|
258
|
+
found = []
|
|
259
|
+
for f in ext.facts:
|
|
260
|
+
c = batch[f.chunk] if 0 <= f.chunk < len(batch) else None
|
|
261
|
+
if c and len(_norm(f.quote)) >= 8 and _norm(f.quote) in _norm(c.text):
|
|
262
|
+
found.append((f, c))
|
|
263
|
+
else:
|
|
264
|
+
report['dropped'] += 1
|
|
265
|
+
return found
|
|
266
|
+
|
|
267
|
+
found = [x for part in await asyncio.gather(*(one(b) for b in batches)) for x in part]
|
|
268
|
+
report['facts'] += len(found)
|
|
269
|
+
return found
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
async def _drop_recorded(cfg: Config, idx: Index, engine: Engine, found: list[Found], report: dict) -> list[Found]:
|
|
273
|
+
"""Keep only facts Jev does not find in the stores (saves merge tokens). Without Jev, keep all."""
|
|
274
|
+
probs = await covered(engine.jev, idx, [f.text for f, _ in found], cfg.stores)
|
|
275
|
+
if probs is None:
|
|
276
|
+
return found
|
|
277
|
+
keep = [x for x, p in zip(found, probs, strict=True) if p < COVERED_THRESHOLD]
|
|
278
|
+
report['recorded'] = len(found) - len(keep)
|
|
279
|
+
return keep
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
JUDGE_BATCH = 12 # uncertain facts per judge request
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
async def _judge(cfg: Config, idx: Index, engine: Engine, facts: list[Found]) -> list[tuple[str, str | None]]:
|
|
286
|
+
"""Fast-model verdict (status, missing specifics) per fact against its best-ranked sections."""
|
|
287
|
+
limit = asyncio.Semaphore(EXTRACT_PARALLEL)
|
|
288
|
+
|
|
289
|
+
async def batch(part: list[Found]) -> list[tuple[str, str | None]]:
|
|
290
|
+
refs: dict[str, None] = {}
|
|
291
|
+
for f, _ in part:
|
|
292
|
+
refs |= dict.fromkeys(r for r, _ in await rank(engine.jev, idx, f.text, 3, cfg.stores, 0.0))
|
|
293
|
+
sections = '\n\n'.join(idx.show(r) for r in refs)[: cfg.behavior.context_budget * 3]
|
|
294
|
+
facts = '\n'.join(f'{n}. {f.text}' for n, (f, _) in enumerate(part))
|
|
295
|
+
async with limit:
|
|
296
|
+
res = await engine.run(agents.judge, prompts.JUDGE.format(facts=facts, sections=sections), fast=True)
|
|
297
|
+
verdicts = {it.n: (it.status, it.missing) for it in res.items}
|
|
298
|
+
return [verdicts.get(n, ('missing', None)) for n in range(len(part))]
|
|
299
|
+
|
|
300
|
+
parts = [facts[i : i + JUDGE_BATCH] for i in range(0, len(facts), JUDGE_BATCH)]
|
|
301
|
+
return [v for part in await asyncio.gather(*(batch(p) for p in parts)) for v in part]
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
async def coverage(cfg: Config, paths: list[str], fix: bool = False, into: str | None = None) -> dict:
|
|
305
|
+
"""Measure how much of the durable knowledge in documents the stores hold; with fix, merge the gaps.
|
|
306
|
+
|
|
307
|
+
Cascade: the fast model extracts facts, Jev confirms the clearly recorded ones, the fast model judges the rest
|
|
308
|
+
(stated / partial / missing, with the missing specifics). `into` pins the merge to one store (and its categories).
|
|
309
|
+
"""
|
|
310
|
+
allowed = cfg.family(into) if into else cfg.stores
|
|
311
|
+
if not allowed:
|
|
312
|
+
raise DPError(f'unknown store {into!r}; stores: {", ".join(cfg.stores)}')
|
|
313
|
+
for rel in paths:
|
|
314
|
+
if not (cfg.root / rel).is_file():
|
|
315
|
+
raise DPError(f'{rel}: not a file in the repository')
|
|
316
|
+
idx = open_index(cfg)
|
|
317
|
+
chunks = [c for rel in paths for c in chunk(rel, read_source(cfg, rel))]
|
|
318
|
+
report: dict = {'facts': 0, 'dropped': 0, 'lines': [], 'warnings': [], 'conflicts': [], 'events': []}
|
|
319
|
+
async with Engine(cfg, 'coverage') as engine:
|
|
320
|
+
if not engine.jev.available:
|
|
321
|
+
raise DPError(
|
|
322
|
+
'coverage needs Jev: set [auth].openrouter_api_key in diffpilot.toml (or $OPENROUTER_API_KEY)'
|
|
323
|
+
)
|
|
324
|
+
found = await _extract(cfg, engine, chunks, report)
|
|
325
|
+
probs = await covered(engine.jev, idx, [f.text for f, _ in found], cfg.stores) or []
|
|
326
|
+
unsure = [x for x, p in zip(found, probs, strict=True) if p < COVERED_THRESHOLD]
|
|
327
|
+
gaps = [
|
|
328
|
+
(x, st, miss)
|
|
329
|
+
for x, (st, miss) in zip(unsure, await _judge(cfg, idx, engine, unsure), strict=False)
|
|
330
|
+
if st != 'stated'
|
|
331
|
+
]
|
|
332
|
+
if fix and gaps:
|
|
333
|
+
todo = [
|
|
334
|
+
(
|
|
335
|
+
f.model_copy(
|
|
336
|
+
update={
|
|
337
|
+
'text': f'{f.text} (the stores lack: {miss})' if miss else f.text,
|
|
338
|
+
'store': f.store if f.store in allowed else allowed[0],
|
|
339
|
+
}
|
|
340
|
+
),
|
|
341
|
+
c,
|
|
342
|
+
)
|
|
343
|
+
for (f, c), _, miss in gaps
|
|
344
|
+
]
|
|
345
|
+
man = Manifest(cfg)
|
|
346
|
+
for group in _merge_groups(todo, cfg.behavior.context_budget * 2):
|
|
347
|
+
await _merge(cfg, idx, engine, man, group, {}, report, allowed)
|
|
348
|
+
total = len(found)
|
|
349
|
+
rows = [
|
|
350
|
+
{'source': f'{c.file}:{c.start + 1}-{c.end}', 'store': f.store, 'status': st, 'text': f.text, 'lacks': miss}
|
|
351
|
+
for (f, c), st, miss in gaps
|
|
352
|
+
]
|
|
353
|
+
partial = sum(r['status'] == 'partial' for r in rows)
|
|
354
|
+
ratio = (total - len(rows) + partial / 2) / total if total else 1.0
|
|
355
|
+
lines = [
|
|
356
|
+
f'Coverage of {", ".join(paths)}: {total - len(rows)}/{total} facts fully recorded, {partial} partial, '
|
|
357
|
+
f'{len(rows) - partial} missing ({ratio:.0%})'
|
|
358
|
+
]
|
|
359
|
+
lines += [
|
|
360
|
+
f'- {r["status"]:<7} [{r["source"]}] {r["text"]}' + (f' — lacks: {r["lacks"]}' if r['lacks'] else '')
|
|
361
|
+
for r in rows
|
|
362
|
+
]
|
|
363
|
+
man = Manifest(cfg) # last result per document: doctor counts a measured document as covered
|
|
364
|
+
for rel in paths:
|
|
365
|
+
n = sum(c.file == rel for _, c in found)
|
|
366
|
+
part = [st for (_, c), st, _ in gaps if c.file == rel]
|
|
367
|
+
r = (n - len(part) + part.count('partial') / 2) / n if n else 1.0
|
|
368
|
+
man.data.setdefault('coverage', {})[rel] = {'facts': n, 'ratio': round(r, 3), 'at': now()}
|
|
369
|
+
man.save()
|
|
370
|
+
if fix:
|
|
371
|
+
lines += ['', f'Merged the gaps: {len(report["events"])} event(s)', *report['lines']]
|
|
372
|
+
lines += [f'Conflict (not written): {c}' for c in report['conflicts']]
|
|
373
|
+
return {
|
|
374
|
+
'ok': True,
|
|
375
|
+
'facts': total,
|
|
376
|
+
'gaps': rows,
|
|
377
|
+
'ratio': round(ratio, 3),
|
|
378
|
+
'lines': lines,
|
|
379
|
+
'warnings': report['warnings'],
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _merge_groups(found: list[Found], budget_chars: int) -> list[list[Found]]:
|
|
384
|
+
"""Large merge batches; all facts of one chunk stay together so its manifest entry is written once."""
|
|
385
|
+
by_chunk: dict[str, list[Found]] = {}
|
|
386
|
+
for x in found:
|
|
387
|
+
by_chunk.setdefault(x[1].hash, []).append(x)
|
|
388
|
+
groups: list[list[Found]] = [[]]
|
|
389
|
+
size = 0
|
|
390
|
+
for items in by_chunk.values():
|
|
391
|
+
n = sum(len(f.text) + 80 for f, _ in items)
|
|
392
|
+
if groups[-1] and size + n > budget_chars:
|
|
393
|
+
groups.append([])
|
|
394
|
+
size = 0
|
|
395
|
+
groups[-1] += items
|
|
396
|
+
size += n
|
|
397
|
+
return groups
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
async def _merge(
|
|
401
|
+
cfg: Config,
|
|
402
|
+
idx: Index,
|
|
403
|
+
engine: Engine,
|
|
404
|
+
man: Manifest,
|
|
405
|
+
facts: list[Found],
|
|
406
|
+
stale_refs: dict,
|
|
407
|
+
report: dict,
|
|
408
|
+
allowed: tuple[str, ...] = (),
|
|
409
|
+
) -> None:
|
|
410
|
+
chunks = list({c.hash: c for _, c in facts}.values())
|
|
411
|
+
files = sorted({c.file for c in chunks})
|
|
412
|
+
stale = [r for f in files for r in stale_refs.get(f, []) if r in idx.views]
|
|
413
|
+
fact_text = '\n'.join(
|
|
414
|
+
f'{n}. [{f.store}/{f.kind}] {f.text} (source: {c.file}:{c.start + 1}-{c.end})'
|
|
415
|
+
for n, (f, c) in enumerate(facts)
|
|
416
|
+
)
|
|
417
|
+
deps = Deps(cfg=cfg, idx=idx, jev=engine.jev, code=False, owner_only=True, mode='merge', request=fact_text)
|
|
418
|
+
deps.facts = [f.text for f, _ in facts]
|
|
419
|
+
for r in stale:
|
|
420
|
+
deps.mark(r)
|
|
421
|
+
prompt = prompts.MERGE_TASK.format(
|
|
422
|
+
language=cfg.behavior.language,
|
|
423
|
+
detail=prompts.DETAIL.get(cfg.behavior.detail, prompts.DETAIL['normal']),
|
|
424
|
+
outline=idx.outline(),
|
|
425
|
+
stale='\n'.join(idx.show(r) for r in stale) or '(none)',
|
|
426
|
+
facts=fact_text,
|
|
427
|
+
)
|
|
428
|
+
res = await engine.run(agents.merger, prompt, deps)
|
|
429
|
+
event = {
|
|
430
|
+
'command': 'bootstrap',
|
|
431
|
+
'summary': f'Bootstrap from {", ".join(files)[:200]}',
|
|
432
|
+
'change_type': 'added',
|
|
433
|
+
'changelog': False,
|
|
434
|
+
}
|
|
435
|
+
allowed = allowed or cfg.stores
|
|
436
|
+
applied = apply_ops(cfg, idx, list(res.ops), deps.shown, 'bootstrap', allowed, event, owner_only=True)
|
|
437
|
+
report['lines'] += applied.lines
|
|
438
|
+
report['warnings'] += applied.warnings
|
|
439
|
+
report['conflicts'] += [f'{c.description} ({", ".join(c.sources)})' for c in res.conflicts]
|
|
440
|
+
if applied.event_id:
|
|
441
|
+
report['events'].append(applied.event_id)
|
|
442
|
+
refs_by_chunk: dict[str, set[str]] = {c.hash: set() for c in chunks}
|
|
443
|
+
for o in applied.ops: # provenance: which chunks produced which sections
|
|
444
|
+
op, ref = res.ops[o['n']], o.get('ref')
|
|
445
|
+
if not ref or ref not in idx.sections:
|
|
446
|
+
continue
|
|
447
|
+
srcs = [facts[n][1] for n in op.facts if 0 <= n < len(facts)]
|
|
448
|
+
e = idx.sections[ref]
|
|
449
|
+
e['sources'] = sorted({*e.get('sources', []), *(f'{c.file}:{c.start + 1}-{c.end}' for c in srcs)})
|
|
450
|
+
for c in srcs:
|
|
451
|
+
refs_by_chunk[c.hash].add(ref)
|
|
452
|
+
idx.save()
|
|
453
|
+
for c in chunks: # manifest updated only after the batch is applied (resume-safe); provenance accumulates
|
|
454
|
+
refs = refs_by_chunk[c.hash] | set(man.chunks(c.file).get(c.hash, {}).get('refs', []))
|
|
455
|
+
man.chunks(c.file)[c.hash] = {'lines': [c.start + 1, c.end], 'refs': sorted(refs)}
|
|
456
|
+
man.save()
|
diffpilot/bootstrap.pyi
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from _typeshed import Incomplete
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from diffpilot import agents as agents, prompts as prompts, store as store
|
|
4
|
+
from diffpilot.agents import Deps as Deps
|
|
5
|
+
from diffpilot.agentsmd import outside as outside
|
|
6
|
+
from diffpilot.config import Config as Config, DPError as DPError, git_ignored as git_ignored
|
|
7
|
+
from diffpilot.core import refresh_summaries as refresh_summaries
|
|
8
|
+
from diffpilot.index import Index as Index, now as now
|
|
9
|
+
from diffpilot.jev import chunk_value as chunk_value, covered as covered, rank as rank
|
|
10
|
+
from diffpilot.llm import Engine as Engine
|
|
11
|
+
from diffpilot.ops import apply_ops as apply_ops, open_index as open_index
|
|
12
|
+
from diffpilot.schemas import Fact as Fact
|
|
13
|
+
|
|
14
|
+
log: Incomplete
|
|
15
|
+
DOC_EXT: Incomplete
|
|
16
|
+
SKIP_DIRS: Incomplete
|
|
17
|
+
SKIP_NAMES: Incomplete
|
|
18
|
+
CHUNK_MAX: int
|
|
19
|
+
EXTRACT_PARALLEL: int
|
|
20
|
+
TRIAGE_THRESHOLD: float
|
|
21
|
+
COVERED_THRESHOLD: float
|
|
22
|
+
type Found = tuple[Fact, Chunk]
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Chunk:
|
|
26
|
+
file: str
|
|
27
|
+
start: int
|
|
28
|
+
end: int
|
|
29
|
+
text: str
|
|
30
|
+
@property
|
|
31
|
+
def hash(self) -> str: ...
|
|
32
|
+
|
|
33
|
+
def inventory(cfg: Config, include: list[str], exclude: list[str], max_files: int) -> list[str]: ...
|
|
34
|
+
def read_source(cfg: Config, rel: str) -> str: ...
|
|
35
|
+
def chunk(rel: str, text: str) -> list[Chunk]: ...
|
|
36
|
+
def skeleton(cfg: Config) -> str: ...
|
|
37
|
+
|
|
38
|
+
class Manifest:
|
|
39
|
+
path: Incomplete
|
|
40
|
+
data: dict
|
|
41
|
+
def __init__(self, cfg: Config) -> None: ...
|
|
42
|
+
def save(self) -> None: ...
|
|
43
|
+
def chunks(self, rel: str) -> dict: ...
|
|
44
|
+
|
|
45
|
+
async def run(cfg: Config, include: list[str], exclude: list[str], max_files: int, force: bool) -> dict: ...
|
|
46
|
+
|
|
47
|
+
JUDGE_BATCH: int
|
|
48
|
+
|
|
49
|
+
async def coverage(cfg: Config, paths: list[str], fix: bool = False, into: str | None = None) -> dict: ...
|