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/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from importlib import metadata as _metadata
|
|
3
|
+
|
|
4
|
+
os.environ.setdefault('PYDANTIC_AI_NO_BANNER', '1') # before any pydantic_ai import in the package
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
__version__ = _metadata.version('diffpilot')
|
|
8
|
+
except _metadata.PackageNotFoundError: # pragma: no cover
|
|
9
|
+
__version__ = '0.0.0'
|
|
10
|
+
|
|
11
|
+
__all__: list[str] = []
|
diffpilot/__init__.pyi
ADDED
diffpilot/__main__.py
ADDED
diffpilot/__main__.pyi
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from diffpilot.cli import main as main
|
diffpilot/agents.py
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
"""Pydantic AI agents: the read-only docs toolset, output validators and the reviewer sub-agent."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import re
|
|
5
|
+
import unicodedata
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any, cast
|
|
8
|
+
|
|
9
|
+
from pydantic_ai import Agent, ModelRetry, RunContext
|
|
10
|
+
from pydantic_ai.exceptions import UsageLimitExceeded
|
|
11
|
+
from pydantic_ai.toolsets import FunctionToolset
|
|
12
|
+
from pydantic_ai.usage import UsageLimits
|
|
13
|
+
|
|
14
|
+
from diffpilot import events, prompts
|
|
15
|
+
from diffpilot.agentsmd import outside
|
|
16
|
+
from diffpilot.config import Config, git_ignored
|
|
17
|
+
from diffpilot.index import Index
|
|
18
|
+
from diffpilot.jev import Jev, covered, rank, stated
|
|
19
|
+
from diffpilot.ops import plan_ops, preview
|
|
20
|
+
from diffpilot.schemas import (
|
|
21
|
+
AnswerResult,
|
|
22
|
+
BriefResult,
|
|
23
|
+
ChangelogEntry,
|
|
24
|
+
Cited,
|
|
25
|
+
EditResult,
|
|
26
|
+
ExtractResult,
|
|
27
|
+
JudgeResult,
|
|
28
|
+
MergeResult,
|
|
29
|
+
ResumeResult,
|
|
30
|
+
SummaryResult,
|
|
31
|
+
Verdict,
|
|
32
|
+
)
|
|
33
|
+
from diffpilot.store import clip
|
|
34
|
+
|
|
35
|
+
log = logging.getLogger('diffpilot')
|
|
36
|
+
|
|
37
|
+
MAX_FIXES = 2 # retries for problems found by automatic checks
|
|
38
|
+
MAX_REVIEWS = 2 # reviewer rounds (the second only after a rejection)
|
|
39
|
+
REVIEW_REQUESTS = 6 # request budget of one reviewer run
|
|
40
|
+
|
|
41
|
+
SECRET_NAMES = re.compile(r'(^\.env|\.pem$|\.key$|^id_[a-z0-9]+$|^auth\.json$|secret|credential)', re.I)
|
|
42
|
+
DIRECTIVE = re.compile(
|
|
43
|
+
r'\b(you|the caller)\s+(must|should|need to|have to|are required to|ought to)\b'
|
|
44
|
+
r'|(?:^|[.!?]\s+)(make sure|ensure|do not|don\'t)\b',
|
|
45
|
+
re.I,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# --- deps & tools --------------------------------------------------------------
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class Deps:
|
|
54
|
+
cfg: Config
|
|
55
|
+
idx: Index
|
|
56
|
+
code: bool = True
|
|
57
|
+
allowed: tuple[str, ...] = () # empty = all stores
|
|
58
|
+
owner_only: bool = False
|
|
59
|
+
mode: str = '' # edit | merge | ask | brief
|
|
60
|
+
request: str = '' # what the reviewer checks against: input, question, task, fact list or AGENTS.md text
|
|
61
|
+
current: str = '' # resume mode: the current resume section
|
|
62
|
+
jev: Jev | None = None # fast relevance reranking for search, when configured
|
|
63
|
+
facts: list[str] = field(default_factory=list) # merge mode: fact texts, by number
|
|
64
|
+
shown: dict[str, str] = field(default_factory=dict) # ref -> hash at the time the model read it
|
|
65
|
+
calls: list[str] = field(default_factory=list)
|
|
66
|
+
fixes: int = 0
|
|
67
|
+
reviews: int = 0
|
|
68
|
+
|
|
69
|
+
def __post_init__(self) -> None:
|
|
70
|
+
self.allowed = self.allowed or self.cfg.stores
|
|
71
|
+
|
|
72
|
+
def mark(self, ref: str) -> str:
|
|
73
|
+
if ref in self.idx.views:
|
|
74
|
+
self.shown[ref] = self.idx.views[ref].hash
|
|
75
|
+
return self.idx.show(ref)
|
|
76
|
+
|
|
77
|
+
def calls_text(self) -> str:
|
|
78
|
+
return ', '.join(self.calls) or 'none (only the prefetched sections)'
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
docs: FunctionToolset[Deps] = FunctionToolset()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@docs.tool
|
|
85
|
+
def outline(ctx: RunContext[Deps], store: str = '') -> str: # noqa: D417 - ctx is injected
|
|
86
|
+
"""Section tree with refs, sizes and one-line summaries.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
store: prd, impl, instructions or a PRD category (prd.<name>; `prd` includes its categories); empty for all.
|
|
90
|
+
|
|
91
|
+
"""
|
|
92
|
+
ctx.deps.calls.append(f'outline({store})')
|
|
93
|
+
cfg = ctx.deps.cfg
|
|
94
|
+
return ctx.deps.idx.outline(cfg.family(store.strip().rstrip(':')) or cfg.stores)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@docs.tool
|
|
98
|
+
async def search(ctx: RunContext[Deps], terms: str) -> str:
|
|
99
|
+
"""Search all sections by meaning and keywords (headings, bodies, keywords). Returns refs with summaries.
|
|
100
|
+
|
|
101
|
+
Describe what you are looking for in a short phrase or sentence; the most relevant sections come first.
|
|
102
|
+
"""
|
|
103
|
+
ctx.deps.calls.append(f'search({clip(terms, 60)})')
|
|
104
|
+
d = ctx.deps
|
|
105
|
+
idx = d.idx
|
|
106
|
+
hits = await rank(d.jev, idx, terms, 8, d.cfg.stores, d.cfg.jev.threshold)
|
|
107
|
+
return '\n'.join(f'- {r} | {idx.views[r].path} | {idx.summary(r)}' for r, _ in hits) or 'no hits'
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@docs.tool
|
|
111
|
+
def show(ctx: RunContext[Deps], refs: list[str]) -> str: # noqa: D417 - ctx is injected
|
|
112
|
+
"""Exact text of sections, with origin, update date, children and related sections.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
refs: section refs like 'prd:shop.cards'.
|
|
116
|
+
|
|
117
|
+
"""
|
|
118
|
+
ctx.deps.calls.append(f'show({", ".join(refs)})')
|
|
119
|
+
return '\n\n'.join(ctx.deps.mark(r.strip().strip('`')) for r in refs)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@docs.tool
|
|
123
|
+
def history(ctx: RunContext[Deps], ref: str) -> str:
|
|
124
|
+
"""Past recorded changes of a section, with reasons and previous text."""
|
|
125
|
+
ctx.deps.calls.append(f'history({ref})')
|
|
126
|
+
out = []
|
|
127
|
+
for e in events.history(ctx.deps.cfg, ref)[-8:]:
|
|
128
|
+
out.append(
|
|
129
|
+
f'- {e["ts"][:10]} {e["id"]}: {e["summary"]}' + (f' — why: {e["reason"]}' if e.get('reason') else '')
|
|
130
|
+
)
|
|
131
|
+
for o in e.get('ops', []):
|
|
132
|
+
if o.get('before') and ref in (o.get('target'), o.get('ref')):
|
|
133
|
+
out.append(f' before: {clip(o["before"], 300)}')
|
|
134
|
+
return '\n'.join(out) or 'no recorded history'
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@docs.tool
|
|
138
|
+
def read_code(ctx: RunContext[Deps], path: str, start: int | None = None, end: int | None = None) -> str: # noqa: D417 - ctx is injected
|
|
139
|
+
"""Read a repository file (with line numbers) or list a directory. Read-only, repository-confined.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
path: path relative to the repository root.
|
|
143
|
+
start: first line (1-based), optional.
|
|
144
|
+
end: last line, optional (at most 400 lines are returned).
|
|
145
|
+
|
|
146
|
+
"""
|
|
147
|
+
ctx.deps.calls.append(f'read_code({path})')
|
|
148
|
+
if not (ctx.deps.code and ctx.deps.cfg.behavior.code_access):
|
|
149
|
+
return 'code access is disabled for this request'
|
|
150
|
+
return read_file(ctx.deps.cfg, path, start, end)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def read_file(cfg: Config, rel: str, start: int | None, end: int | None) -> str:
|
|
154
|
+
root = cfg.root.resolve()
|
|
155
|
+
p = (root / rel).resolve()
|
|
156
|
+
if not p.is_relative_to(root) or not p.exists():
|
|
157
|
+
return f'{rel}: not found in repository'
|
|
158
|
+
if any(SECRET_NAMES.search(part) for part in p.relative_to(root).parts) or '.git' in p.parts:
|
|
159
|
+
return f'{rel}: access denied (sensitive path)'
|
|
160
|
+
if git_ignored(cfg, [p.relative_to(root).as_posix()]):
|
|
161
|
+
return f'{rel}: ignored by .gitignore'
|
|
162
|
+
if p.is_dir():
|
|
163
|
+
return '\n'.join(
|
|
164
|
+
sorted(x.name + ('/' if x.is_dir() else '') for x in p.iterdir() if not x.name.startswith('.'))[:200]
|
|
165
|
+
)
|
|
166
|
+
try:
|
|
167
|
+
text = p.read_text(encoding='utf-8')
|
|
168
|
+
except UnicodeDecodeError:
|
|
169
|
+
return f'{rel}: binary file'
|
|
170
|
+
if p == (root / cfg.paths.agents_md).resolve():
|
|
171
|
+
text = outside(text) # diffpilot's own sections are its output, never evidence
|
|
172
|
+
lines = text.split('\n')
|
|
173
|
+
first = max(1, start or 1)
|
|
174
|
+
last = min(end or first + 399, first + 399, len(lines))
|
|
175
|
+
text = '\n'.join(f'{i}: {ln}' for i, ln in enumerate(lines[first - 1 : last], first))
|
|
176
|
+
return text[:24000] + (f'\n… ({len(lines)} lines total)' if last < len(lines) else '')
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
# --- validation helpers --------------------------------------------------------
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def valid_ref(cfg: Config, idx: Index, ref: str) -> bool:
|
|
183
|
+
ref = ref.strip().strip('`')
|
|
184
|
+
st, sep, _ = ref.partition(':')
|
|
185
|
+
if sep and st in cfg.stores:
|
|
186
|
+
return ref in idx.views
|
|
187
|
+
path = re.split(r'[:#]', ref, maxsplit=1)[0]
|
|
188
|
+
p = (cfg.root / path).resolve()
|
|
189
|
+
return bool(path) and p.is_relative_to(cfg.root.resolve()) and p.exists()
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def directives(texts: list[str]) -> list[str]:
|
|
193
|
+
hits = []
|
|
194
|
+
for t in texts:
|
|
195
|
+
for sentence in re.split(r'(?<=[.!?])\s+', t):
|
|
196
|
+
if DIRECTIVE.search(sentence) and 'recorded' not in sentence.lower():
|
|
197
|
+
hits.append(sentence.strip())
|
|
198
|
+
return hits
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def cited(res: AnswerResult | BriefResult) -> list[Cited]:
|
|
202
|
+
return res.records if isinstance(res, AnswerResult) else res.requirements + res.decisions + res.instructions
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def prose(res: AnswerResult | BriefResult) -> list[str]:
|
|
206
|
+
if isinstance(res, AnswerResult):
|
|
207
|
+
return [res.answer, *[c.text for c in res.records]]
|
|
208
|
+
return [*[c.text for c in res.requirements + res.decisions], *res.tensions]
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def scripts(text: str) -> set[str]:
|
|
212
|
+
"""Return the writing systems of non-ASCII letters, e.g. {'CYRILLIC'}."""
|
|
213
|
+
return {unicodedata.name(ch, 'UNKNOWN').split()[0] for ch in text if ch.isalpha() and not ch.isascii()} - {'LATIN'}
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def stray_scripts(written: list[str], context: str) -> list[str]:
|
|
217
|
+
"""Model glitches: words in a writing system that appears neither in the request nor in the docs context."""
|
|
218
|
+
extra = scripts(' '.join(written)) - scripts(context)
|
|
219
|
+
return (
|
|
220
|
+
[f'text contains characters in an unexpected script ({", ".join(sorted(extra))}); remove them'] if extra else []
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _bullets(items: list[str]) -> str:
|
|
225
|
+
return '\n'.join(f'- {i}' for i in items)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
async def _review(ctx: RunContext[Deps], prompt: str) -> Verdict:
|
|
229
|
+
"""Independent reviewer sub-agent: fresh context, own read-only tool state, same model."""
|
|
230
|
+
d = ctx.deps
|
|
231
|
+
try:
|
|
232
|
+
res = await reviewer.run(
|
|
233
|
+
prompt,
|
|
234
|
+
model=cast(Any, ctx.model),
|
|
235
|
+
deps=Deps(cfg=d.cfg, idx=d.idx, code=d.code, jev=d.jev),
|
|
236
|
+
usage=ctx.usage,
|
|
237
|
+
usage_limits=UsageLimits(request_limit=ctx.usage.requests + REVIEW_REQUESTS),
|
|
238
|
+
)
|
|
239
|
+
except UsageLimitExceeded:
|
|
240
|
+
log.info('reviewer ran out of its request budget; draft accepted unreviewed')
|
|
241
|
+
return Verdict(approved=True)
|
|
242
|
+
v = res.output
|
|
243
|
+
log.info('reviewer %s %s', 'approved' if v.approved else 'rejected', '; '.join(v.problems))
|
|
244
|
+
return v
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
LOST_THRESHOLD = 0.5 # Jev P(fact stated) below this: the merge lost it
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
async def lost_facts(d: Deps, out: Any) -> list[str]:
|
|
251
|
+
"""Merge-mode check with Jev: every fact must be stated in the ops that cite it, or already be in the stores."""
|
|
252
|
+
cited = {
|
|
253
|
+
n: '\n\n'.join(f'{o.heading or ""}\n{o.text or ""}' for o in out.ops if n in o.facts)
|
|
254
|
+
for n in range(len(d.facts))
|
|
255
|
+
}
|
|
256
|
+
in_ops = [n for n, t in cited.items() if t.strip()]
|
|
257
|
+
skipped = [n for n in cited if n not in in_ops]
|
|
258
|
+
p_ops = await stated(d.jev, [(d.facts[n], cited[n]) for n in in_ops]) if in_ops else []
|
|
259
|
+
p_skip = await covered(d.jev, d.idx, [d.facts[n] for n in skipped], d.cfg.stores) if skipped else []
|
|
260
|
+
if p_ops is None or p_skip is None:
|
|
261
|
+
return []
|
|
262
|
+
lost = [n for n, p in zip(in_ops, p_ops, strict=True) if p < LOST_THRESHOLD]
|
|
263
|
+
lost += [n for n, p in zip(skipped, p_skip, strict=True) if p < LOST_THRESHOLD]
|
|
264
|
+
if lost:
|
|
265
|
+
log.info('merge lost %d of %d facts', len(lost), len(d.facts))
|
|
266
|
+
return [
|
|
267
|
+
f'fact {n} is not fully stated by the ops citing it, nor recorded elsewhere: "{clip(d.facts[n], 300)}" — '
|
|
268
|
+
'write all its specifics (append them to the matching section, or add a section)'
|
|
269
|
+
for n in sorted(lost)
|
|
270
|
+
]
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
async def check_edit(ctx: RunContext[Deps], out: Any) -> Any:
|
|
274
|
+
d = ctx.deps
|
|
275
|
+
plan = plan_ops(d.cfg, d.idx, out.ops, d.shown, d.allowed, d.owner_only, strict=False)
|
|
276
|
+
issues = [w for w in plan.warnings if not w.startswith('conflict (not written)')]
|
|
277
|
+
written = [o.text or '' for o in out.ops] + [o.heading or '' for o in out.ops]
|
|
278
|
+
written += [out.summary, *out.warnings] if hasattr(out, 'summary') else [c.description for c in out.conflicts]
|
|
279
|
+
issues += stray_scripts(written, d.request + ''.join(plan.orig.values()))
|
|
280
|
+
if d.mode == 'merge' and not issues and d.fixes < MAX_FIXES:
|
|
281
|
+
issues += await lost_facts(d, out)
|
|
282
|
+
if issues and d.fixes < MAX_FIXES:
|
|
283
|
+
d.fixes += 1
|
|
284
|
+
log.info('automatic checks: %s', '; '.join(issues))
|
|
285
|
+
raise ModelRetry(prompts.FIX.format(issues=_bullets(issues)))
|
|
286
|
+
# bootstrap merges are not reviewed: facts are quote-verified, ops are owner-only and checked above
|
|
287
|
+
if d.cfg.behavior.verify and d.mode != 'merge' and d.reviews < MAX_REVIEWS:
|
|
288
|
+
d.reviews += 1
|
|
289
|
+
diff = preview(d.cfg, plan, d.cfg.behavior.context_budget * 2)
|
|
290
|
+
prompt = prompts.REVIEW_EDIT_TASK.format(
|
|
291
|
+
input=d.request,
|
|
292
|
+
summary=out.summary,
|
|
293
|
+
warnings='; '.join(out.warnings) or 'none',
|
|
294
|
+
calls=d.calls_text(),
|
|
295
|
+
diff=diff,
|
|
296
|
+
)
|
|
297
|
+
verdict = await _review(ctx, prompt)
|
|
298
|
+
if not verdict.approved and verdict.problems:
|
|
299
|
+
raise ModelRetry(prompts.REVISE.format(problems=_bullets(verdict.problems)))
|
|
300
|
+
return out
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
REF = re.compile(r'\b(?:prd(?:\.[\w-]+)?|impl|instructions):[\w.\-]*\w')
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
async def check_resume(ctx: RunContext[Deps], out: ResumeResult) -> ResumeResult:
|
|
307
|
+
"""Automatic checks (no ## headings, length, valid refs, scripts), then the reviewer against the rest of AGENTS.md."""
|
|
308
|
+
d = ctx.deps
|
|
309
|
+
md = out.markdown.strip()
|
|
310
|
+
issues = [
|
|
311
|
+
f'heading level too high, use ### or lower: "{ln}"' for ln in md.split('\n') if re.match(r'^#{1,2}\s', ln)
|
|
312
|
+
]
|
|
313
|
+
limit = d.cfg.behavior.agents_md_lines
|
|
314
|
+
if md.count('\n') + 1 > limit * 1.3:
|
|
315
|
+
issues.append(f'too long: {md.count(chr(10)) + 1} lines, aim for at most {limit}')
|
|
316
|
+
issues += [f'store ref does not exist: {r}' for r in dict.fromkeys(REF.findall(md)) if r not in d.idx.views]
|
|
317
|
+
issues += stray_scripts([md], d.request + ''.join(v.body for v in d.idx.views.values()))
|
|
318
|
+
if issues and d.fixes < MAX_FIXES:
|
|
319
|
+
d.fixes += 1
|
|
320
|
+
log.info('automatic checks: %s', '; '.join(issues))
|
|
321
|
+
raise ModelRetry(prompts.FIX.format(issues=_bullets(issues)))
|
|
322
|
+
if d.cfg.behavior.verify and d.reviews < MAX_REVIEWS:
|
|
323
|
+
d.reviews += 1
|
|
324
|
+
prompt = prompts.REVIEW_RESUME_TASK.format(
|
|
325
|
+
contract=prompts.CONTRACT['resume'],
|
|
326
|
+
agents_md=d.request,
|
|
327
|
+
current=d.current or '(none)',
|
|
328
|
+
draft=out.model_dump_json(indent=1),
|
|
329
|
+
)
|
|
330
|
+
verdict = await _review(ctx, prompt)
|
|
331
|
+
if not verdict.approved and verdict.problems:
|
|
332
|
+
raise ModelRetry(prompts.REVISE.format(problems=_bullets(verdict.problems)))
|
|
333
|
+
return out
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
async def check_answer(ctx: RunContext[Deps], out: Any) -> Any:
|
|
337
|
+
d = ctx.deps
|
|
338
|
+
issues = []
|
|
339
|
+
for c in cited(out):
|
|
340
|
+
ref = c.ref.strip().strip('`')
|
|
341
|
+
if not valid_ref(d.cfg, d.idx, ref):
|
|
342
|
+
issues.append(f'cited ref does not exist: {ref}')
|
|
343
|
+
elif ref.partition(':')[0] in d.cfg.stores and ref not in d.shown:
|
|
344
|
+
issues.append(f'cited without reading it: {ref} (show it and verify the claim)')
|
|
345
|
+
issues += [f'directive to the caller, restate as a fact about the record: "{h}"' for h in directives(prose(out))]
|
|
346
|
+
issues += stray_scripts(
|
|
347
|
+
prose(out) + list(getattr(out, 'gaps', [])), d.request + ''.join(d.idx.show(r) for r in d.shown)
|
|
348
|
+
)
|
|
349
|
+
if issues and d.fixes < MAX_FIXES:
|
|
350
|
+
d.fixes += 1
|
|
351
|
+
log.info('automatic checks: %s', '; '.join(issues))
|
|
352
|
+
raise ModelRetry(prompts.FIX.format(issues=_bullets(issues)))
|
|
353
|
+
if d.cfg.behavior.verify and d.reviews < MAX_REVIEWS:
|
|
354
|
+
d.reviews += 1
|
|
355
|
+
refs = dict.fromkeys(c.ref.strip().strip('`') for c in cited(out))
|
|
356
|
+
evidence = '\n\n'.join(d.idx.show(r) for r in refs if r in d.idx.views)
|
|
357
|
+
prompt = prompts.REVIEW_ANSWER_TASK.format(
|
|
358
|
+
mode=d.mode,
|
|
359
|
+
contract=prompts.CONTRACT[d.mode],
|
|
360
|
+
label='Question' if d.mode == 'ask' else 'Task',
|
|
361
|
+
request=d.request,
|
|
362
|
+
draft=out.model_dump_json(indent=1),
|
|
363
|
+
evidence=evidence[: d.cfg.behavior.context_budget * 2] or '(no store sections cited)',
|
|
364
|
+
)
|
|
365
|
+
verdict = await _review(ctx, prompt)
|
|
366
|
+
if not verdict.approved and verdict.problems:
|
|
367
|
+
raise ModelRetry(prompts.REVISE.format(problems=_bullets(verdict.problems)))
|
|
368
|
+
return out
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
# --- agents (model is chosen per run by the Engine) ----------------------------
|
|
372
|
+
|
|
373
|
+
_RETRIES: Any = {'tools': 2, 'output': MAX_FIXES + MAX_REVIEWS + 1}
|
|
374
|
+
|
|
375
|
+
editor: Agent[Deps, EditResult] = Agent(
|
|
376
|
+
output_type=EditResult,
|
|
377
|
+
deps_type=Deps,
|
|
378
|
+
instructions=prompts.EDITOR,
|
|
379
|
+
toolsets=[docs],
|
|
380
|
+
retries=_RETRIES,
|
|
381
|
+
name='editor',
|
|
382
|
+
)
|
|
383
|
+
editor.output_validator(check_edit)
|
|
384
|
+
|
|
385
|
+
merger: Agent[Deps, MergeResult] = Agent(
|
|
386
|
+
output_type=MergeResult,
|
|
387
|
+
deps_type=Deps,
|
|
388
|
+
instructions=prompts.MERGER,
|
|
389
|
+
toolsets=[docs],
|
|
390
|
+
retries=_RETRIES,
|
|
391
|
+
name='merger',
|
|
392
|
+
)
|
|
393
|
+
merger.output_validator(check_edit)
|
|
394
|
+
|
|
395
|
+
answerer: Agent[Deps, AnswerResult] = Agent(
|
|
396
|
+
output_type=AnswerResult,
|
|
397
|
+
deps_type=Deps,
|
|
398
|
+
instructions=prompts.ANSWERER,
|
|
399
|
+
toolsets=[docs],
|
|
400
|
+
retries=_RETRIES,
|
|
401
|
+
name='answerer',
|
|
402
|
+
)
|
|
403
|
+
answerer.output_validator(check_answer)
|
|
404
|
+
|
|
405
|
+
briefer: Agent[Deps, BriefResult] = Agent(
|
|
406
|
+
output_type=BriefResult,
|
|
407
|
+
deps_type=Deps,
|
|
408
|
+
instructions=prompts.ANSWERER,
|
|
409
|
+
toolsets=[docs],
|
|
410
|
+
retries=_RETRIES,
|
|
411
|
+
name='briefer',
|
|
412
|
+
)
|
|
413
|
+
briefer.output_validator(check_answer)
|
|
414
|
+
|
|
415
|
+
reviewer: Agent[Deps, Verdict] = Agent(
|
|
416
|
+
output_type=Verdict, deps_type=Deps, instructions=prompts.REVIEWER, toolsets=[docs], retries=2, name='reviewer'
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
resume_writer: Agent[Deps, ResumeResult] = Agent(
|
|
420
|
+
output_type=ResumeResult,
|
|
421
|
+
deps_type=Deps,
|
|
422
|
+
instructions=prompts.RESUME,
|
|
423
|
+
toolsets=[docs],
|
|
424
|
+
retries=_RETRIES,
|
|
425
|
+
name='resume',
|
|
426
|
+
)
|
|
427
|
+
resume_writer.output_validator(check_resume)
|
|
428
|
+
|
|
429
|
+
summarizer: Agent[None, SummaryResult] = Agent(
|
|
430
|
+
output_type=SummaryResult, instructions=prompts.BASE, retries=2, name='summarizer'
|
|
431
|
+
)
|
|
432
|
+
extractor: Agent[None, ExtractResult] = Agent(
|
|
433
|
+
output_type=ExtractResult, instructions=prompts.BASE, retries=2, name='extractor'
|
|
434
|
+
)
|
|
435
|
+
judge: Agent[None, JudgeResult] = Agent(output_type=JudgeResult, instructions=prompts.BASE, retries=2, name='judge')
|
|
436
|
+
changelog_writer: Agent[None, ChangelogEntry] = Agent(
|
|
437
|
+
output_type=ChangelogEntry, instructions=prompts.BASE, retries=2, name='changelog'
|
|
438
|
+
)
|
diffpilot/agents.pyi
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
from _typeshed import Incomplete
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from diffpilot import events as events, prompts as prompts
|
|
4
|
+
from diffpilot.agentsmd import outside as outside
|
|
5
|
+
from diffpilot.config import Config as Config, git_ignored as git_ignored
|
|
6
|
+
from diffpilot.index import Index as Index
|
|
7
|
+
from diffpilot.jev import Jev as Jev, covered as covered, rank as rank, stated as stated
|
|
8
|
+
from diffpilot.ops import plan_ops as plan_ops, preview as preview
|
|
9
|
+
from diffpilot.schemas import AnswerResult as AnswerResult, BriefResult as BriefResult, ChangelogEntry as ChangelogEntry, Cited as Cited, EditResult as EditResult, ExtractResult as ExtractResult, JudgeResult as JudgeResult, MergeResult as MergeResult, ResumeResult as ResumeResult, SummaryResult as SummaryResult, Verdict as Verdict
|
|
10
|
+
from diffpilot.store import clip as clip
|
|
11
|
+
from pydantic_ai import Agent, RunContext as RunContext
|
|
12
|
+
from pydantic_ai.toolsets import FunctionToolset
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
log: Incomplete
|
|
16
|
+
MAX_FIXES: int
|
|
17
|
+
MAX_REVIEWS: int
|
|
18
|
+
REVIEW_REQUESTS: int
|
|
19
|
+
SECRET_NAMES: Incomplete
|
|
20
|
+
DIRECTIVE: Incomplete
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Deps:
|
|
24
|
+
cfg: Config
|
|
25
|
+
idx: Index
|
|
26
|
+
code: bool = ...
|
|
27
|
+
allowed: tuple[str, ...] = ...
|
|
28
|
+
owner_only: bool = ...
|
|
29
|
+
mode: str = ...
|
|
30
|
+
request: str = ...
|
|
31
|
+
current: str = ...
|
|
32
|
+
jev: Jev | None = ...
|
|
33
|
+
facts: list[str] = field(default_factory=list)
|
|
34
|
+
shown: dict[str, str] = field(default_factory=dict)
|
|
35
|
+
calls: list[str] = field(default_factory=list)
|
|
36
|
+
fixes: int = ...
|
|
37
|
+
reviews: int = ...
|
|
38
|
+
def __post_init__(self) -> None: ...
|
|
39
|
+
def mark(self, ref: str) -> str: ...
|
|
40
|
+
def calls_text(self) -> str: ...
|
|
41
|
+
|
|
42
|
+
docs: FunctionToolset[Deps]
|
|
43
|
+
|
|
44
|
+
@docs.tool
|
|
45
|
+
def outline(ctx: RunContext[Deps], store: str = '') -> str: ...
|
|
46
|
+
@docs.tool
|
|
47
|
+
async def search(ctx: RunContext[Deps], terms: str) -> str: ...
|
|
48
|
+
@docs.tool
|
|
49
|
+
def show(ctx: RunContext[Deps], refs: list[str]) -> str: ...
|
|
50
|
+
@docs.tool
|
|
51
|
+
def history(ctx: RunContext[Deps], ref: str) -> str: ...
|
|
52
|
+
@docs.tool
|
|
53
|
+
def read_code(ctx: RunContext[Deps], path: str, start: int | None = None, end: int | None = None) -> str: ...
|
|
54
|
+
def read_file(cfg: Config, rel: str, start: int | None, end: int | None) -> str: ...
|
|
55
|
+
def valid_ref(cfg: Config, idx: Index, ref: str) -> bool: ...
|
|
56
|
+
def directives(texts: list[str]) -> list[str]: ...
|
|
57
|
+
def cited(res: AnswerResult | BriefResult) -> list[Cited]: ...
|
|
58
|
+
def prose(res: AnswerResult | BriefResult) -> list[str]: ...
|
|
59
|
+
def scripts(text: str) -> set[str]: ...
|
|
60
|
+
def stray_scripts(written: list[str], context: str) -> list[str]: ...
|
|
61
|
+
|
|
62
|
+
LOST_THRESHOLD: float
|
|
63
|
+
|
|
64
|
+
async def lost_facts(d: Deps, out: Any) -> list[str]: ...
|
|
65
|
+
async def check_edit(ctx: RunContext[Deps], out: Any) -> Any: ...
|
|
66
|
+
|
|
67
|
+
REF: Incomplete
|
|
68
|
+
|
|
69
|
+
async def check_resume(ctx: RunContext[Deps], out: ResumeResult) -> ResumeResult: ...
|
|
70
|
+
async def check_answer(ctx: RunContext[Deps], out: Any) -> Any: ...
|
|
71
|
+
|
|
72
|
+
editor: Agent[Deps, EditResult]
|
|
73
|
+
merger: Agent[Deps, MergeResult]
|
|
74
|
+
answerer: Agent[Deps, AnswerResult]
|
|
75
|
+
briefer: Agent[Deps, BriefResult]
|
|
76
|
+
reviewer: Agent[Deps, Verdict]
|
|
77
|
+
resume_writer: Agent[Deps, ResumeResult]
|
|
78
|
+
summarizer: Agent[None, SummaryResult]
|
|
79
|
+
extractor: Agent[None, ExtractResult]
|
|
80
|
+
judge: Agent[None, JudgeResult]
|
|
81
|
+
changelog_writer: Agent[None, ChangelogEntry]
|
diffpilot/agentsmd.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""AGENTS.md: the `## diffpilot` section (how to use the tool) and `## diffpilot - resume` (project essentials).
|
|
2
|
+
|
|
3
|
+
The headings themselves are the anchors — no hidden markers that people or agents might delete by accident.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
from diffpilot import prompts, store
|
|
9
|
+
from diffpilot.config import Config
|
|
10
|
+
|
|
11
|
+
TOOL_HEADING = '## diffpilot'
|
|
12
|
+
RESUME_HEADING = '## diffpilot - resume'
|
|
13
|
+
_TOOL = re.compile(r'^##\s+diffpilot\s*$', re.I)
|
|
14
|
+
_RESUME = re.compile(r'^##\s+diffpilot\s*[-–—:]\s*resume\s*$', re.I)
|
|
15
|
+
_LEGACY = re.compile(r'\n*<!-- diffpilot:start -->.*?<!-- diffpilot:end -->\n*', re.S) # pre-1.0 block
|
|
16
|
+
_SLOT = '\x00diffpilot\x00'
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def split(text: str) -> tuple[str, str | None, str | None]:
|
|
20
|
+
"""Return (AGENTS.md without the diffpilot sections, tool section body, resume section body).
|
|
21
|
+
|
|
22
|
+
A section runs until the next `#`/`##` heading; the rest keeps a slot where the sections were.
|
|
23
|
+
"""
|
|
24
|
+
text = _LEGACY.sub('\n\n', text)
|
|
25
|
+
rest: list[str] = []
|
|
26
|
+
bodies: dict[str, list[str]] = {}
|
|
27
|
+
current: str | None = None
|
|
28
|
+
fence = False
|
|
29
|
+
for line in text.split('\n'):
|
|
30
|
+
if store.FENCE.match(line):
|
|
31
|
+
fence = not fence
|
|
32
|
+
if not fence and re.match(r'^#{1,2}\s', line):
|
|
33
|
+
current = 'tool' if _TOOL.match(line) else 'resume' if _RESUME.match(line) else None
|
|
34
|
+
if current:
|
|
35
|
+
if not bodies and _SLOT not in rest:
|
|
36
|
+
rest.append(_SLOT)
|
|
37
|
+
bodies[current] = []
|
|
38
|
+
continue
|
|
39
|
+
if current:
|
|
40
|
+
bodies[current].append(line)
|
|
41
|
+
else:
|
|
42
|
+
rest.append(line)
|
|
43
|
+
tool, resume = ('\n'.join(bodies[k]).strip('\n') if k in bodies else None for k in ('tool', 'resume'))
|
|
44
|
+
return '\n'.join(rest), tool, resume
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def outside(text: str) -> str:
|
|
48
|
+
"""AGENTS.md content written by others (what agents already read), without the diffpilot sections."""
|
|
49
|
+
return re.sub(r'\n{3,}', '\n\n', split(text)[0].replace(_SLOT, '')).strip('\n')
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def compose(rest: str, tool: str, resume: str | None) -> str:
|
|
53
|
+
block = f'{TOOL_HEADING}\n\n{tool.strip()}\n'
|
|
54
|
+
if resume:
|
|
55
|
+
block += f'\n{RESUME_HEADING}\n\n{resume.strip()}\n'
|
|
56
|
+
if _SLOT in rest:
|
|
57
|
+
head, tail = rest.split(_SLOT, 1)
|
|
58
|
+
out = head.rstrip('\n') + '\n\n' + block + ('\n' + tail.lstrip('\n') if tail.strip() else '')
|
|
59
|
+
else:
|
|
60
|
+
out = rest.rstrip('\n') + '\n\n' + block
|
|
61
|
+
return store.normalize(out.lstrip('\n'))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def tool_section(cfg: Config) -> str:
|
|
65
|
+
files = [f'`{cfg.rel(cfg.store_path(s))}`' for s in (*cfg.stores, 'changelog')]
|
|
66
|
+
return prompts.TOOL_SECTION.format(files=', '.join(files[:-1]) + ' and ' + files[-1]).strip()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def read(cfg: Config) -> str:
|
|
70
|
+
p = cfg.root / cfg.paths.agents_md
|
|
71
|
+
return p.read_text(encoding='utf-8') if p.exists() else '# AGENTS.md\n'
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def write_tool_section(cfg: Config) -> bool:
|
|
75
|
+
"""Create or refresh only the `## diffpilot` section (no LLM). Used by init."""
|
|
76
|
+
text = read(cfg)
|
|
77
|
+
rest, _, resume = split(text)
|
|
78
|
+
new = compose(rest, tool_section(cfg), resume)
|
|
79
|
+
if new == text:
|
|
80
|
+
return False
|
|
81
|
+
store.atomic_write(cfg.root / cfg.paths.agents_md, new)
|
|
82
|
+
return True
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
if __name__ == '__main__': # self-check: uv run python -m diffpilot.agentsmd
|
|
86
|
+
doc = '# AGENTS.md\n\nRules.\n\n<!-- diffpilot:start -->\n## diffpilot\nold\n<!-- diffpilot:end -->\n\n## Other\n\nx\n'
|
|
87
|
+
rest, tool, resume = split(doc)
|
|
88
|
+
assert tool is None and resume is None and 'old' not in rest # legacy block removed
|
|
89
|
+
out = compose(rest, 'TOOL', 'RESUME\n\n### Sub\n\ny')
|
|
90
|
+
assert out.index('## diffpilot\n') > out.index('Rules.') and out.endswith('y\n'), out
|
|
91
|
+
rest2, tool2, resume2 = split(out + '\n## Other\n\nx\n')
|
|
92
|
+
assert tool2 == 'TOOL' and resume2 == 'RESUME\n\n### Sub\n\ny' and '## Other' in rest2
|
|
93
|
+
moved = '# T\n\n## diffpilot\n\nTOOL\n\n## diffpilot - resume\n\nR\n\n## Tail\n\nz\n'
|
|
94
|
+
expected = '# T\n\n## diffpilot\n\nTOOL\n\n## diffpilot - resume\n\nR2\n\n## Tail\n\nz\n'
|
|
95
|
+
assert compose(split(moved)[0], 'TOOL', 'R2') == expected, compose(split(moved)[0], 'TOOL', 'R2')
|
|
96
|
+
assert outside(moved) == '# T\n\n## Tail\n\nz'
|
|
97
|
+
print('ok')
|
diffpilot/agentsmd.pyi
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from diffpilot import prompts as prompts, store as store
|
|
2
|
+
from diffpilot.config import Config as Config
|
|
3
|
+
|
|
4
|
+
TOOL_HEADING: str
|
|
5
|
+
RESUME_HEADING: str
|
|
6
|
+
|
|
7
|
+
def split(text: str) -> tuple[str, str | None, str | None]: ...
|
|
8
|
+
def outside(text: str) -> str: ...
|
|
9
|
+
def compose(rest: str, tool: str, resume: str | None) -> str: ...
|
|
10
|
+
def tool_section(cfg: Config) -> str: ...
|
|
11
|
+
def read(cfg: Config) -> str: ...
|
|
12
|
+
def write_tool_section(cfg: Config) -> bool: ...
|