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/core.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
"""Async pipelines: write (record/prd/impl/instruct, finish), read (ask/brief) and the AGENTS.md resume."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from diffpilot import agents, agentsmd, events, prompts, store
|
|
9
|
+
from diffpilot.agents import Deps
|
|
10
|
+
from diffpilot.config import Config, DPError
|
|
11
|
+
from diffpilot.gitdiff import compressed_diff
|
|
12
|
+
from diffpilot.index import Index, Locked, now
|
|
13
|
+
from diffpilot.jev import rank, routing_hint
|
|
14
|
+
from diffpilot.llm import Engine
|
|
15
|
+
from diffpilot.ops import Applied, apply_ops, open_index
|
|
16
|
+
from diffpilot.schemas import AnswerResult, BriefResult, EditResult
|
|
17
|
+
from diffpilot.store import clip
|
|
18
|
+
|
|
19
|
+
log = logging.getLogger('diffpilot')
|
|
20
|
+
CITED = ('records', 'requirements', 'decisions', 'instructions')
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
# --- shared ----------------------------------------------------------------
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def ensure_stores(cfg: Config) -> list[str]:
|
|
27
|
+
created = []
|
|
28
|
+
for st in cfg.stores:
|
|
29
|
+
p = cfg.store_path(st)
|
|
30
|
+
if not p.exists():
|
|
31
|
+
store.atomic_write(p, f'# {cfg.store_title(st)}\n')
|
|
32
|
+
created.append(cfg.rel(p))
|
|
33
|
+
return created
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def code_paths(cfg: Config, files: list[str]) -> list[str]:
|
|
37
|
+
paths = (Path(f).resolve() for f in files)
|
|
38
|
+
return [cfg.rel(p) if p.is_relative_to(cfg.root) else str(p) for p in paths]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def detail(cfg: Config) -> str:
|
|
42
|
+
return prompts.DETAIL.get(cfg.behavior.detail, prompts.DETAIL['normal'])
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def files_note(files: list[str]) -> str:
|
|
46
|
+
return f'\nRelated code files (read with read_code if useful): {", ".join(files)}\n' if files else ''
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
async def refresh_summaries(cfg: Config, idx: Index, engine: Engine) -> None:
|
|
50
|
+
"""Fill missing section summaries (fast model, batched); tiny sections use their first sentence."""
|
|
51
|
+
results: dict[str, tuple[str, list[str]]] = {}
|
|
52
|
+
batches: list[list[str]] = [[]]
|
|
53
|
+
size = 0
|
|
54
|
+
for ref in idx.stale():
|
|
55
|
+
v = idx.views[ref]
|
|
56
|
+
if v.tokens < 40:
|
|
57
|
+
results[ref] = (idx.summary(ref), [])
|
|
58
|
+
continue
|
|
59
|
+
if size + v.tokens > cfg.behavior.context_budget and batches[-1]:
|
|
60
|
+
batches.append([])
|
|
61
|
+
size = 0
|
|
62
|
+
batches[-1].append(ref)
|
|
63
|
+
size += min(v.tokens, 1000)
|
|
64
|
+
for batch in filter(None, batches):
|
|
65
|
+
text = '\n\n'.join(f'[{r}] {idx.views[r].path}\n{clip(idx.views[r].body, 4000)}' for r in batch)
|
|
66
|
+
res = await engine.run(agents.summarizer, prompts.SUMMARIZE.format(sections=text), fast=True)
|
|
67
|
+
for it in res.items:
|
|
68
|
+
if it.ref in batch:
|
|
69
|
+
results[it.ref] = (it.summary.strip(), [k.lower() for k in it.keywords][:8])
|
|
70
|
+
if not results:
|
|
71
|
+
return
|
|
72
|
+
with Locked(cfg):
|
|
73
|
+
fresh = Index(cfg)
|
|
74
|
+
for ref, (summary, kw) in results.items():
|
|
75
|
+
if ref in fresh.sections and fresh.sections[ref].get('hash') == idx.views[ref].hash:
|
|
76
|
+
fresh.sections[ref].update(summary=summary, keywords=kw)
|
|
77
|
+
fresh.save()
|
|
78
|
+
idx.data = fresh.data
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
async def prefetch(deps: Deps, query: str) -> str:
|
|
82
|
+
"""Show the most relevant sections up front (BM25, reranked by Jev if configured) to save tool turns."""
|
|
83
|
+
cfg = deps.cfg
|
|
84
|
+
budget = cfg.behavior.context_budget // 3
|
|
85
|
+
hits = await rank(deps.jev, deps.idx, query, 6, cfg.stores, cfg.jev.threshold)
|
|
86
|
+
out: list[str] = []
|
|
87
|
+
used = 0
|
|
88
|
+
for ref, _ in hits:
|
|
89
|
+
t = deps.idx.views[ref].tokens
|
|
90
|
+
if used + t > budget and out:
|
|
91
|
+
break
|
|
92
|
+
out.append(deps.mark(ref))
|
|
93
|
+
used += t
|
|
94
|
+
return '\n\n'.join(out) or '(no matching sections)'
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def result_lines(applied: Applied, result: EditResult) -> list[str]:
|
|
98
|
+
summary = result.summary.strip()
|
|
99
|
+
tail = f'Event {applied.event_id} · {summary}' if applied.event_id else f'No changes: {summary}'
|
|
100
|
+
return [*applied.lines, tail]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# --- write -----------------------------------------------------------------
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
async def record(
|
|
107
|
+
cfg: Config, text: str, store_name: str | None, files: list[str], command: str, inbox_id: str | None = None
|
|
108
|
+
) -> dict:
|
|
109
|
+
text = text.strip()
|
|
110
|
+
if not text:
|
|
111
|
+
raise DPError('empty input')
|
|
112
|
+
ensure_stores(cfg)
|
|
113
|
+
idx = open_index(cfg)
|
|
114
|
+
ih = events.input_hash(f'{command}\n{text}')
|
|
115
|
+
last = next((e for e in reversed(events.events(cfg)) if e.get('command') != 'manual'), None)
|
|
116
|
+
if last and last.get('input_hash') == ih:
|
|
117
|
+
if inbox_id:
|
|
118
|
+
events.inbox_remove(cfg, inbox_id)
|
|
119
|
+
return {'ok': True, 'duplicate': True, 'event_id': last['id'], 'lines': [f'Already recorded as {last["id"]}']}
|
|
120
|
+
allowed = cfg.family(store_name) if store_name else cfg.stores
|
|
121
|
+
iid = inbox_id or events.inbox_add(cfg, command, text, {'files': files})
|
|
122
|
+
async with Engine(cfg, command) as engine:
|
|
123
|
+
deps = Deps(cfg=cfg, idx=idx, jev=engine.jev, allowed=allowed, mode='edit', request=text)
|
|
124
|
+
await refresh_summaries(cfg, idx, engine)
|
|
125
|
+
prompt = prompts.EDIT_TASK.format(
|
|
126
|
+
stores=', '.join(allowed),
|
|
127
|
+
language=cfg.behavior.language,
|
|
128
|
+
detail=detail(cfg),
|
|
129
|
+
outline=idx.outline(),
|
|
130
|
+
shown=await prefetch(deps, text),
|
|
131
|
+
route=await routing_hint(engine.jev, cfg, text, allowed),
|
|
132
|
+
files=files_note(files),
|
|
133
|
+
input=text,
|
|
134
|
+
)
|
|
135
|
+
result = await engine.run(agents.editor, prompt, deps)
|
|
136
|
+
event = {
|
|
137
|
+
'command': command,
|
|
138
|
+
'input': text,
|
|
139
|
+
'input_hash': ih,
|
|
140
|
+
'summary': result.summary.strip(),
|
|
141
|
+
'reason': result.reason,
|
|
142
|
+
'change_type': result.change_type,
|
|
143
|
+
}
|
|
144
|
+
applied = apply_ops(cfg, idx, result.ops, deps.shown, command, allowed, event, files=files)
|
|
145
|
+
events.inbox_remove(cfg, iid)
|
|
146
|
+
return {
|
|
147
|
+
'ok': True,
|
|
148
|
+
'event_id': applied.event_id,
|
|
149
|
+
'summary': result.summary,
|
|
150
|
+
'ops': applied.ops,
|
|
151
|
+
'lines': result_lines(applied, result),
|
|
152
|
+
'warnings': result.warnings + applied.warnings,
|
|
153
|
+
'code_comments': [result.code_comment] if result.code_comment else [],
|
|
154
|
+
'usage': engine.usage_dict(),
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _batches(rows: list[dict], budget_chars: int) -> list[list[dict]]:
|
|
159
|
+
out: list[list[dict]] = [[]]
|
|
160
|
+
size = 0
|
|
161
|
+
for r in rows:
|
|
162
|
+
if out[-1] and size + len(r['text']) > budget_chars:
|
|
163
|
+
out.append([])
|
|
164
|
+
size = 0
|
|
165
|
+
out[-1].append(r)
|
|
166
|
+
size += len(r['text'])
|
|
167
|
+
return out
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _notes_text(batch: list[dict]) -> str:
|
|
171
|
+
return '\n'.join(
|
|
172
|
+
f'{i}. [{n["ts"][:16].replace("T", " ")}] {n["text"]}'
|
|
173
|
+
+ (f' (files: {", ".join(n["files"])})' if n.get('files') else '')
|
|
174
|
+
for i, n in enumerate(batch, 1)
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
async def finish(cfg: Config, text: str, files: list[str], use_diff: bool = True) -> dict:
|
|
179
|
+
"""Integrate all pending notes (+ the task's git diff as evidence, unless use_diff is off) into the stores."""
|
|
180
|
+
if text.strip():
|
|
181
|
+
events.note(cfg, text, files) # persisted first, so nothing is lost if finish fails
|
|
182
|
+
pending = events.notes(cfg)
|
|
183
|
+
if not pending:
|
|
184
|
+
return {'ok': True, 'lines': ['No pending notes.']}
|
|
185
|
+
ensure_stores(cfg)
|
|
186
|
+
idx = open_index(cfg)
|
|
187
|
+
base = next((n['git_head'] for n in pending if n.get('git_head')), None)
|
|
188
|
+
if not use_diff or not cfg.behavior.git:
|
|
189
|
+
listed = sorted({f for n in pending for f in n.get('files', [])} | set(files))
|
|
190
|
+
diff = '(no diff: --no-diff; read these files if needed)\n\n' + ('\n'.join(listed) or '(no files given)')
|
|
191
|
+
elif base:
|
|
192
|
+
diff = compressed_diff(cfg, [base], cfg.behavior.context_budget * 2)
|
|
193
|
+
else:
|
|
194
|
+
diff = '(not a git repository)'
|
|
195
|
+
files_changed = diff.split('\n\n', 1)[0]
|
|
196
|
+
out: dict = {'ok': True, 'lines': [f'Processed {len(pending)} note(s)'], 'warnings': [], 'code_comments': []}
|
|
197
|
+
out['events'] = []
|
|
198
|
+
async with Engine(cfg, 'finish') as engine:
|
|
199
|
+
await refresh_summaries(cfg, idx, engine)
|
|
200
|
+
for batch in _batches(pending, cfg.behavior.context_budget * 2):
|
|
201
|
+
notes = _notes_text(batch)
|
|
202
|
+
request = f'Work notes:\n{notes}\n\nTask diff summary:\n{files_changed}'
|
|
203
|
+
deps = Deps(cfg=cfg, idx=idx, jev=engine.jev, mode='edit', request=request)
|
|
204
|
+
prompt = prompts.FINISH_TASK.format(
|
|
205
|
+
language=cfg.behavior.language,
|
|
206
|
+
detail=detail(cfg),
|
|
207
|
+
outline=idx.outline(),
|
|
208
|
+
shown=await prefetch(deps, notes),
|
|
209
|
+
route=await routing_hint(engine.jev, cfg, notes, cfg.stores),
|
|
210
|
+
notes=notes,
|
|
211
|
+
diff=diff,
|
|
212
|
+
)
|
|
213
|
+
result = await engine.run(agents.editor, prompt, deps)
|
|
214
|
+
event = {
|
|
215
|
+
'command': 'finish',
|
|
216
|
+
'input': notes,
|
|
217
|
+
'input_hash': events.input_hash(notes),
|
|
218
|
+
'note_ids': [n['id'] for n in batch],
|
|
219
|
+
'summary': result.summary.strip(),
|
|
220
|
+
'reason': result.reason,
|
|
221
|
+
'change_type': result.change_type,
|
|
222
|
+
}
|
|
223
|
+
note_files = sorted({f for n in batch for f in n.get('files', [])})
|
|
224
|
+
applied = apply_ops(cfg, idx, result.ops, deps.shown, 'finish', cfg.stores, event, files=note_files)
|
|
225
|
+
with Locked(cfg):
|
|
226
|
+
events.notes_remove(cfg, {n['id'] for n in batch}) # only after the batch is written
|
|
227
|
+
out['lines'] += result_lines(applied, result)
|
|
228
|
+
out['warnings'] += result.warnings + applied.warnings
|
|
229
|
+
out['code_comments'] += [result.code_comment] if result.code_comment else []
|
|
230
|
+
out['events'] += [applied.event_id] if applied.event_id else []
|
|
231
|
+
out['usage'] = engine.usage_dict()
|
|
232
|
+
return out
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# --- read ------------------------------------------------------------------
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
async def query(cfg: Config, mode: str, text: str, files: list[str], use_cache: bool = True) -> dict:
|
|
239
|
+
text = text.strip()
|
|
240
|
+
if not text:
|
|
241
|
+
raise DPError('empty input')
|
|
242
|
+
idx = open_index(cfg)
|
|
243
|
+
key = hashlib.sha256(json.dumps([mode, text, files, prompts.PROMPT_VERSION]).encode()).hexdigest()[:20]
|
|
244
|
+
cache_path = cfg.state / 'cache' / 'answers.json'
|
|
245
|
+
cache = json.loads(cache_path.read_text()) if cache_path.exists() else {}
|
|
246
|
+
structure = hashlib.sha256('\n'.join(sorted(idx.views)).encode()).hexdigest()[:12]
|
|
247
|
+
hit = cache.get(key) if use_cache else None
|
|
248
|
+
if (
|
|
249
|
+
hit
|
|
250
|
+
and hit['structure'] == structure
|
|
251
|
+
and all(r in idx.views and idx.views[r].hash == h for r, h in hit['deps'].items())
|
|
252
|
+
):
|
|
253
|
+
return {**hit['result'], 'cached': True}
|
|
254
|
+
|
|
255
|
+
async with Engine(cfg, mode) as engine:
|
|
256
|
+
deps = Deps(cfg=cfg, idx=idx, jev=engine.jev, mode=mode, request=text)
|
|
257
|
+
await refresh_summaries(cfg, idx, engine)
|
|
258
|
+
common = {
|
|
259
|
+
'budget': cfg.behavior.answer_budget,
|
|
260
|
+
'outline': idx.outline(),
|
|
261
|
+
'shown': await prefetch(deps, text),
|
|
262
|
+
'files': files_note(files),
|
|
263
|
+
}
|
|
264
|
+
res: AnswerResult | BriefResult
|
|
265
|
+
if mode == 'ask':
|
|
266
|
+
code = ' (and source code via read_code when the stores do not answer it)' * cfg.behavior.code_access
|
|
267
|
+
res = await engine.run(agents.answerer, prompts.ASK_TASK.format(code=code, question=text, **common), deps)
|
|
268
|
+
else:
|
|
269
|
+
res = await engine.run(agents.briefer, prompts.BRIEF_TASK.format(task=text, **common), deps)
|
|
270
|
+
|
|
271
|
+
out = res.model_dump()
|
|
272
|
+
for k in CITED:
|
|
273
|
+
if k not in out:
|
|
274
|
+
continue
|
|
275
|
+
keep = [c for c in out[k] if agents.valid_ref(cfg, idx, c['ref'])]
|
|
276
|
+
if dropped := [c['ref'] for c in out[k] if c not in keep]:
|
|
277
|
+
log.info('dropped unverifiable citations: %s', dropped)
|
|
278
|
+
for c in keep:
|
|
279
|
+
c['ref'] = c['ref'].strip().strip('`')
|
|
280
|
+
c['updated'] = idx.sections.get(c['ref'], {}).get('updated_at', '')[:10] or None
|
|
281
|
+
out[k] = keep
|
|
282
|
+
cited = {c['ref'] for k in CITED for c in out.get(k, []) if c['ref'] in idx.views}
|
|
283
|
+
cache[key] = {'result': out, 'deps': {r: idx.views[r].hash for r in cited}, 'structure': structure, 'ts': now()}
|
|
284
|
+
store.atomic_write(cache_path, json.dumps(cache, ensure_ascii=False))
|
|
285
|
+
return {**out, 'usage': engine.usage_dict()}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
# --- AGENTS.md -------------------------------------------------------------
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
async def update_agentsmd(cfg: Config, force: bool = False) -> dict:
|
|
292
|
+
"""Refresh both diffpilot sections of AGENTS.md; the resume is rewritten only when its inputs changed."""
|
|
293
|
+
text = agentsmd.read(cfg)
|
|
294
|
+
rest, _, current = agentsmd.split(text)
|
|
295
|
+
others = agentsmd.outside(text)
|
|
296
|
+
idx = open_index(cfg)
|
|
297
|
+
|
|
298
|
+
def key(resume: str | None) -> str:
|
|
299
|
+
stores = '\n'.join(f'{r}={v.hash}' for r, v in sorted(idx.views.items()))
|
|
300
|
+
raw = f'{others}\x00{resume}\x00{stores}\x00{cfg.behavior.agents_md_lines}\x00{prompts.PROMPT_VERSION}'
|
|
301
|
+
return hashlib.sha256(raw.encode()).hexdigest()[:16]
|
|
302
|
+
|
|
303
|
+
lines: list[str] = []
|
|
304
|
+
resume = current
|
|
305
|
+
if not idx.views:
|
|
306
|
+
lines.append('Stores are empty: wrote the tool section only (run `diffpilot init --bootstrap` to seed them).')
|
|
307
|
+
elif force or idx.meta.get('agents_md_key') != key(current):
|
|
308
|
+
instructions = '\n\n'.join(idx.show(r) for r, v in idx.views.items() if v.store == 'instructions')
|
|
309
|
+
budget = cfg.behavior.context_budget * 2
|
|
310
|
+
prompt = prompts.RESUME_TASK.format(
|
|
311
|
+
lines=cfg.behavior.agents_md_lines,
|
|
312
|
+
language=cfg.behavior.language,
|
|
313
|
+
agents_md=others[:budget] or '(empty)',
|
|
314
|
+
current=current or '(none yet)',
|
|
315
|
+
outline=idx.outline(),
|
|
316
|
+
instructions=instructions[:budget] or '(empty)',
|
|
317
|
+
)
|
|
318
|
+
async with Engine(cfg, 'update_agentsmd') as engine:
|
|
319
|
+
deps = Deps(cfg=cfg, idx=idx, jev=engine.jev, mode='resume', request=others[:budget], current=current or '')
|
|
320
|
+
await refresh_summaries(cfg, idx, engine)
|
|
321
|
+
res = await engine.run(agents.resume_writer, prompt, deps)
|
|
322
|
+
resume = res.markdown.strip()
|
|
323
|
+
lines += [f'- {c}' for c in res.changes]
|
|
324
|
+
new = agentsmd.compose(rest, agentsmd.tool_section(cfg), resume)
|
|
325
|
+
changed = new != text
|
|
326
|
+
with Locked(cfg):
|
|
327
|
+
if changed:
|
|
328
|
+
store.atomic_write(cfg.root / cfg.paths.agents_md, new)
|
|
329
|
+
fresh = Index(cfg)
|
|
330
|
+
fresh.meta['agents_md_key'] = key(resume)
|
|
331
|
+
fresh.save()
|
|
332
|
+
head = f'Updated {cfg.paths.agents_md}' if changed else f'{cfg.paths.agents_md} is up to date'
|
|
333
|
+
return {'ok': True, 'changed': changed, 'resume': resume, 'lines': [head, *lines]}
|
diffpilot/core.pyi
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from _typeshed import Incomplete
|
|
2
|
+
from diffpilot import agents as agents, agentsmd as agentsmd, events as events, prompts as prompts, store as store
|
|
3
|
+
from diffpilot.agents import Deps as Deps
|
|
4
|
+
from diffpilot.config import Config as Config, DPError as DPError
|
|
5
|
+
from diffpilot.gitdiff import compressed_diff as compressed_diff
|
|
6
|
+
from diffpilot.index import Index as Index, Locked as Locked, now as now
|
|
7
|
+
from diffpilot.jev import rank as rank, routing_hint as routing_hint
|
|
8
|
+
from diffpilot.llm import Engine as Engine
|
|
9
|
+
from diffpilot.ops import Applied as Applied, apply_ops as apply_ops, open_index as open_index
|
|
10
|
+
from diffpilot.schemas import AnswerResult as AnswerResult, BriefResult as BriefResult, EditResult as EditResult
|
|
11
|
+
from diffpilot.store import clip as clip
|
|
12
|
+
|
|
13
|
+
log: Incomplete
|
|
14
|
+
CITED: Incomplete
|
|
15
|
+
|
|
16
|
+
def ensure_stores(cfg: Config) -> list[str]: ...
|
|
17
|
+
def code_paths(cfg: Config, files: list[str]) -> list[str]: ...
|
|
18
|
+
def detail(cfg: Config) -> str: ...
|
|
19
|
+
def files_note(files: list[str]) -> str: ...
|
|
20
|
+
async def refresh_summaries(cfg: Config, idx: Index, engine: Engine) -> None: ...
|
|
21
|
+
async def prefetch(deps: Deps, query: str) -> str: ...
|
|
22
|
+
def result_lines(applied: Applied, result: EditResult) -> list[str]: ...
|
|
23
|
+
async def record(cfg: Config, text: str, store_name: str | None, files: list[str], command: str, inbox_id: str | None = None) -> dict: ...
|
|
24
|
+
async def finish(cfg: Config, text: str, files: list[str], use_diff: bool = True) -> dict: ...
|
|
25
|
+
async def query(cfg: Config, mode: str, text: str, files: list[str], use_cache: bool = True) -> dict: ...
|
|
26
|
+
async def update_agentsmd(cfg: Config, force: bool = False) -> dict: ...
|
diffpilot/events.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""Change events (.diffpilot/changes.jsonl), CHANGELOG.md rendering, inbox."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import secrets
|
|
6
|
+
import subprocess
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from diffpilot import store
|
|
11
|
+
from diffpilot.config import Config, DPError
|
|
12
|
+
from diffpilot.index import Locked, now
|
|
13
|
+
|
|
14
|
+
CHANGE_TYPES = ('added', 'changed', 'deprecated', 'removed', 'fixed', 'security')
|
|
15
|
+
START, END = '<!-- diffpilot:unreleased:start -->', '<!-- diffpilot:unreleased:end -->'
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def new_id(prefix: str = 'c') -> str:
|
|
19
|
+
return f'{prefix}_{datetime.now(UTC).strftime("%Y%m%d_%H%M%S")}_{secrets.token_hex(2)}'
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def input_hash(text: str) -> str:
|
|
23
|
+
return hashlib.sha256(text.strip().encode()).hexdigest()[:16]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _read_jsonl(path: Path) -> list[dict]:
|
|
27
|
+
if not path.exists():
|
|
28
|
+
return []
|
|
29
|
+
return [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines() if line.strip()]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _write_jsonl(path: Path, rows: list[dict]) -> None:
|
|
33
|
+
store.atomic_write(path, ''.join(json.dumps(r, ensure_ascii=False) + '\n' for r in rows))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _append_jsonl(path: Path, row: dict) -> None:
|
|
37
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
38
|
+
with path.open('a', encoding='utf-8') as f:
|
|
39
|
+
f.write(json.dumps(row, ensure_ascii=False) + '\n')
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def events(cfg: Config) -> list[dict]:
|
|
43
|
+
return _read_jsonl(cfg.state / 'changes.jsonl')
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def append(cfg: Config, event: dict) -> None:
|
|
47
|
+
_append_jsonl(cfg.state / 'changes.jsonl', event)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def mark_released(cfg: Config, ids: set[str]) -> None:
|
|
51
|
+
rows = events(cfg)
|
|
52
|
+
for r in rows:
|
|
53
|
+
if r['id'] in ids:
|
|
54
|
+
r['released'] = True
|
|
55
|
+
_write_jsonl(cfg.state / 'changes.jsonl', rows)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def unreleased(cfg: Config) -> list[dict]:
|
|
59
|
+
return [e for e in events(cfg) if not e.get('released') and e.get('changelog', True)]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def history(cfg: Config, ref: str) -> list[dict]:
|
|
63
|
+
return [e for e in events(cfg) if any(ref in (o.get('target'), o.get('ref')) for o in e.get('ops', []))]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# --- CHANGELOG.md ----------------------------------------------------------
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _changelog_text(cfg: Config) -> str:
|
|
70
|
+
p = cfg.store_path('changelog')
|
|
71
|
+
text = p.read_text(encoding='utf-8') if p.exists() else '# Changelog\n'
|
|
72
|
+
if START in text and END in text:
|
|
73
|
+
return text
|
|
74
|
+
lines = text.split('\n')
|
|
75
|
+
for i, line in enumerate(lines):
|
|
76
|
+
if line.strip().lower().startswith('## [unreleased]'):
|
|
77
|
+
lines[i + 1 : i + 1] = [START, END]
|
|
78
|
+
return '\n'.join(lines)
|
|
79
|
+
at = next((i + 1 for i, ln in enumerate(lines) if ln.startswith('# ')), 0)
|
|
80
|
+
lines[at:at] = ['', '## [Unreleased]', START, END, '']
|
|
81
|
+
return '\n'.join(lines)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def render_groups(groups: dict[str, list[str]]) -> list[str]:
|
|
85
|
+
out: list[str] = []
|
|
86
|
+
for t in CHANGE_TYPES:
|
|
87
|
+
items = groups.get(t) or []
|
|
88
|
+
if items:
|
|
89
|
+
out += ['', f'### {t.capitalize()}', *[f'- {i}' for i in items]]
|
|
90
|
+
return out
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def refresh_unreleased(cfg: Config) -> None:
|
|
94
|
+
groups: dict[str, list[str]] = {}
|
|
95
|
+
for e in unreleased(cfg):
|
|
96
|
+
refs = sorted({o['ref'] for o in e.get('ops', []) if o.get('ref')})
|
|
97
|
+
tail = f' ({", ".join(refs[:3])})' if refs else ''
|
|
98
|
+
groups.setdefault(e.get('change_type', 'changed'), []).append(f'{e["summary"]}{tail}')
|
|
99
|
+
text = _changelog_text(cfg)
|
|
100
|
+
head, rest = text.split(START, 1)
|
|
101
|
+
_, tail = rest.split(END, 1)
|
|
102
|
+
body = render_groups(groups)
|
|
103
|
+
new = head + START + ('\n'.join(body) + '\n' if body else '\n') + END + tail
|
|
104
|
+
store.atomic_write(cfg.store_path('changelog'), store.normalize(new))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def write_release(cfg: Config, title: str, groups: dict[str, list[str]]) -> None:
|
|
108
|
+
text = _changelog_text(cfg)
|
|
109
|
+
head, rest = text.split(END, 1)
|
|
110
|
+
entry = '\n'.join(['', '', f'## {title}', *render_groups(groups), ''])
|
|
111
|
+
store.atomic_write(cfg.store_path('changelog'), store.normalize(head + END + entry + rest))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# --- inbox (inputs saved before an LLM call) -------------------------------
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def inbox(cfg: Config) -> list[dict]:
|
|
118
|
+
return _read_jsonl(cfg.state / 'inbox.jsonl')
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def inbox_add(cfg: Config, command: str, text: str, args: dict) -> str:
|
|
122
|
+
iid = new_id('i')
|
|
123
|
+
_append_jsonl(cfg.state / 'inbox.jsonl', {'id': iid, 'command': command, 'input': text, 'args': args})
|
|
124
|
+
return iid
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def inbox_remove(cfg: Config, iid: str) -> None:
|
|
128
|
+
rows = inbox(cfg)
|
|
129
|
+
_write_jsonl(cfg.state / 'inbox.jsonl', [r for r in rows if r['id'] != iid])
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# --- notes journal (note -> finish) -------------------------------------------
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def git_head(cfg: Config) -> str | None:
|
|
136
|
+
if not cfg.behavior.git:
|
|
137
|
+
return None
|
|
138
|
+
r = subprocess.run(['git', 'rev-parse', '--short', 'HEAD'], cwd=cfg.root, capture_output=True, text=True)
|
|
139
|
+
return r.stdout.strip() or None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def note(cfg: Config, text: str, files: list[str]) -> dict:
|
|
143
|
+
"""Append to the notes journal. No LLM: instant, so it can be called at every decision."""
|
|
144
|
+
text = text.strip()
|
|
145
|
+
if not text:
|
|
146
|
+
raise DPError('empty note')
|
|
147
|
+
nid = new_id('n')
|
|
148
|
+
with Locked(cfg):
|
|
149
|
+
note_add(cfg, {'id': nid, 'ts': now(), 'text': text, 'files': files, 'git_head': git_head(cfg)})
|
|
150
|
+
pending = len(notes(cfg))
|
|
151
|
+
return {
|
|
152
|
+
'ok': True,
|
|
153
|
+
'note_id': nid,
|
|
154
|
+
'pending': pending,
|
|
155
|
+
'lines': [f'Noted {nid} ({pending} pending; run `diffpilot finish` at the end of the task)'],
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def notes(cfg: Config) -> list[dict]:
|
|
160
|
+
return _read_jsonl(cfg.state / 'notes.jsonl')
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def note_add(cfg: Config, row: dict) -> None:
|
|
164
|
+
_append_jsonl(cfg.state / 'notes.jsonl', row)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def notes_remove(cfg: Config, ids: set[str]) -> None:
|
|
168
|
+
_write_jsonl(cfg.state / 'notes.jsonl', [n for n in notes(cfg) if n['id'] not in ids])
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def log_run(cfg: Config, row: dict) -> None:
|
|
172
|
+
_append_jsonl(cfg.state / 'runs.jsonl', row)
|
diffpilot/events.pyi
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from _typeshed import Incomplete
|
|
2
|
+
from diffpilot import store as store
|
|
3
|
+
from diffpilot.config import Config as Config, DPError as DPError
|
|
4
|
+
from diffpilot.index import Locked as Locked, now as now
|
|
5
|
+
|
|
6
|
+
CHANGE_TYPES: Incomplete
|
|
7
|
+
START: Incomplete
|
|
8
|
+
END: Incomplete
|
|
9
|
+
|
|
10
|
+
def new_id(prefix: str = 'c') -> str: ...
|
|
11
|
+
def input_hash(text: str) -> str: ...
|
|
12
|
+
def events(cfg: Config) -> list[dict]: ...
|
|
13
|
+
def append(cfg: Config, event: dict) -> None: ...
|
|
14
|
+
def mark_released(cfg: Config, ids: set[str]) -> None: ...
|
|
15
|
+
def unreleased(cfg: Config) -> list[dict]: ...
|
|
16
|
+
def history(cfg: Config, ref: str) -> list[dict]: ...
|
|
17
|
+
def render_groups(groups: dict[str, list[str]]) -> list[str]: ...
|
|
18
|
+
def refresh_unreleased(cfg: Config) -> None: ...
|
|
19
|
+
def write_release(cfg: Config, title: str, groups: dict[str, list[str]]) -> None: ...
|
|
20
|
+
def inbox(cfg: Config) -> list[dict]: ...
|
|
21
|
+
def inbox_add(cfg: Config, command: str, text: str, args: dict) -> str: ...
|
|
22
|
+
def inbox_remove(cfg: Config, iid: str) -> None: ...
|
|
23
|
+
def git_head(cfg: Config) -> str | None: ...
|
|
24
|
+
def note(cfg: Config, text: str, files: list[str]) -> dict: ...
|
|
25
|
+
def notes(cfg: Config) -> list[dict]: ...
|
|
26
|
+
def note_add(cfg: Config, row: dict) -> None: ...
|
|
27
|
+
def notes_remove(cfg: Config, ids: set[str]) -> None: ...
|
|
28
|
+
def log_run(cfg: Config, row: dict) -> None: ...
|