diffpilot 0.0.1__tar.gz

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.
Files changed (51) hide show
  1. diffpilot-0.0.1/PKG-INFO +80 -0
  2. diffpilot-0.0.1/diffpilot/__init__.py +11 -0
  3. diffpilot-0.0.1/diffpilot/__init__.pyi +3 -0
  4. diffpilot-0.0.1/diffpilot/__main__.py +3 -0
  5. diffpilot-0.0.1/diffpilot/__main__.pyi +1 -0
  6. diffpilot-0.0.1/diffpilot/agents.py +438 -0
  7. diffpilot-0.0.1/diffpilot/agents.pyi +81 -0
  8. diffpilot-0.0.1/diffpilot/agentsmd.py +97 -0
  9. diffpilot-0.0.1/diffpilot/agentsmd.pyi +12 -0
  10. diffpilot-0.0.1/diffpilot/bootstrap.py +456 -0
  11. diffpilot-0.0.1/diffpilot/bootstrap.pyi +49 -0
  12. diffpilot-0.0.1/diffpilot/cli.py +731 -0
  13. diffpilot-0.0.1/diffpilot/cli.pyi +62 -0
  14. diffpilot-0.0.1/diffpilot/config.py +342 -0
  15. diffpilot-0.0.1/diffpilot/config.pyi +109 -0
  16. diffpilot-0.0.1/diffpilot/core.py +333 -0
  17. diffpilot-0.0.1/diffpilot/core.pyi +26 -0
  18. diffpilot-0.0.1/diffpilot/events.py +172 -0
  19. diffpilot-0.0.1/diffpilot/events.pyi +28 -0
  20. diffpilot-0.0.1/diffpilot/gitdiff.py +170 -0
  21. diffpilot-0.0.1/diffpilot/gitdiff.pyi +14 -0
  22. diffpilot-0.0.1/diffpilot/index.py +242 -0
  23. diffpilot-0.0.1/diffpilot/index.pyi +60 -0
  24. diffpilot-0.0.1/diffpilot/jev.py +203 -0
  25. diffpilot-0.0.1/diffpilot/jev.pyi +33 -0
  26. diffpilot-0.0.1/diffpilot/llm.py +141 -0
  27. diffpilot-0.0.1/diffpilot/llm.pyi +28 -0
  28. diffpilot-0.0.1/diffpilot/ops.py +285 -0
  29. diffpilot-0.0.1/diffpilot/ops.pyi +31 -0
  30. diffpilot-0.0.1/diffpilot/prompts.py +432 -0
  31. diffpilot-0.0.1/diffpilot/prompts.pyi +28 -0
  32. diffpilot-0.0.1/diffpilot/py.typed +0 -0
  33. diffpilot-0.0.1/diffpilot/schemas.py +110 -0
  34. diffpilot-0.0.1/diffpilot/schemas.pyi +88 -0
  35. diffpilot-0.0.1/diffpilot/store.py +315 -0
  36. diffpilot-0.0.1/diffpilot/store.pyi +43 -0
  37. diffpilot-0.0.1/diffpilot/verify.py +352 -0
  38. diffpilot-0.0.1/diffpilot/verify.pyi +58 -0
  39. diffpilot-0.0.1/diffpilot.egg-info/PKG-INFO +80 -0
  40. diffpilot-0.0.1/diffpilot.egg-info/SOURCES.txt +49 -0
  41. diffpilot-0.0.1/diffpilot.egg-info/dependency_links.txt +1 -0
  42. diffpilot-0.0.1/diffpilot.egg-info/entry_points.txt +2 -0
  43. diffpilot-0.0.1/diffpilot.egg-info/requires.txt +5 -0
  44. diffpilot-0.0.1/diffpilot.egg-info/top_level.txt +1 -0
  45. diffpilot-0.0.1/pyproject.toml +120 -0
  46. diffpilot-0.0.1/readme.md +63 -0
  47. diffpilot-0.0.1/setup.cfg +4 -0
  48. diffpilot-0.0.1/tests/test_bootstrap.py +88 -0
  49. diffpilot-0.0.1/tests/test_cli.py +202 -0
  50. diffpilot-0.0.1/tests/test_config_stores.py +155 -0
  51. diffpilot-0.0.1/tests/test_init.py +4 -0
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: diffpilot
3
+ Version: 0.0.1
4
+ Summary: Project memory CLI for coding agents: requirements, rationale, instructions and changelog, powered by Codex
5
+ Author-email: Aleksei Marusich <aleksei.marusich@rocshers.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://projects.rocshers.com/open-source/diffpilot
8
+ Project-URL: Repository, https://gitlab.com/rocshers/python/diffpilot
9
+ Keywords: ai,development
10
+ Requires-Python: >=3.14
11
+ Description-Content-Type: text/markdown
12
+ Requires-Dist: filelock>=3.16.1
13
+ Requires-Dist: pydantic>=2.14.3
14
+ Requires-Dist: pydantic-ai-slim[openai,typesafe]>=2.68.0
15
+ Requires-Dist: rich>=15.0.0
16
+ Requires-Dist: typer>=0.29.1
17
+
18
+ # diffpilot - project memory for coding agents
19
+
20
+ [![PyPI](https://img.shields.io/pypi/v/diffpilot)](https://pypi.org/project/diffpilot/)
21
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/diffpilot)](https://pypi.org/project/diffpilot/)
22
+
23
+ [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=rocshers_diffpilot&metric=coverage)](https://sonarcloud.io/summary/new_code?id=rocshers_diffpilot)
24
+ [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=rocshers_diffpilot&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=rocshers_diffpilot)
25
+
26
+ [![Downloads](https://pypi.rocshers.com/badges/svg/packages/diffpilot/downloads/total)](https://clickpy.clickhouse.com/dashboard/diffpilot)
27
+ [![GitLab stars](https://img.shields.io/gitlab/stars/rocshers/python/diffpilot)](https://gitlab.com/rocshers/python/diffpilot)
28
+ [![GitLab last commit](https://img.shields.io/gitlab/last-commit/rocshers/python/diffpilot)](https://gitlab.com/rocshers/python/diffpilot)
29
+
30
+ Project memory for coding agents. The agent says *what changed and why*; diffpilot (its own small agent on a Codex
31
+ subscription) finds where it belongs in the docs, edits surgically, logs the change and keeps the changelog — and
32
+ answers questions about requirements and past decisions with citations, without bossing the calling agent around.
33
+
34
+ ## Features
35
+
36
+ - Three Markdown stores with stable section IDs: `docs/PRD.md` (current product vision), `docs/implementation.md`
37
+ (how and why), `docs/instructions.md` (project rules), plus `docs/CHANGELOG.md`.
38
+ - Optional PRD categories: `[prd_categories] mobs = "..."` keeps the details of an area in `docs/prd/mobs.md`, while
39
+ `PRD.md` holds the overview. An existing spec (a bestiary, a tower roster) is adopted in place, losslessly and
40
+ without bootstrap extraction: `mobs = { scope = "...", path = "docs/mobs.md" }`. A spec written as one big nested
41
+ bullet list is split into heading sections (one per top-level item with sub-items, recursively, while a section
42
+ is over 2000 characters), so each creature gets its own section and ID.
43
+ - Optional [Jev](https://openrouter.ai/typesafe) (TypeSafe's decision model, via OpenRouter) reranks retrieval and
44
+ routes input to stores: better context for fewer tokens. Falls back to BM25 without a key.
45
+ - `note` captures decisions instantly during work; `finish` integrates them (plus the git diff) at the end of the task.
46
+ - `record` writes immediately, routed to the right store(s); `prd` / `impl` / `instruct` force one. Edits are validated ops, never
47
+ free-form rewrites; every write becomes a change event with before/after text and the reason.
48
+ - `ask` and `brief` answer from the stores (and code) with citations; records are presented as context, not orders.
49
+ - `init --bootstrap` seeds the stores from existing docs, with quote verification and safe, incremental re-runs.
50
+ - `git_diff_changelog_summary` turns git diff + recorded changes into one clean changelog entry.
51
+ - `AGENTS.md` gets a `## diffpilot` section (how to use the tool) and, via `update_agentsmd`, a `## diffpilot - resume`
52
+ of project essentials that never repeats what the file already says.
53
+ - Free, instant lookups without an LLM: `outline`, `show`, `search`, `log`.
54
+
55
+ ## Quick start
56
+
57
+ Requires a Codex login (`codex login`, ChatGPT subscription) — credentials are read from `$CODEX_HOME/auth.json`.
58
+
59
+ ```bash
60
+ uvx diffpilot init --bootstrap # global + project config, stores (seeded from existing docs), ## diffpilot in AGENTS.md
61
+ uvx diffpilot brief "Add 6 cards to the shop"
62
+ uvx diffpilot note "Shop shows 6 cards instead of 4; 2 slots are seasonal offers (user request)." # instant
63
+ uvx diffpilot finish # end of task: notes + git diff → docs, reviewed
64
+ uvx diffpilot ask "What are the shop requirements?"
65
+ uvx diffpilot git_diff_changelog_summary --write --version 1.2.0
66
+ uvx diffpilot update_agentsmd
67
+ ```
68
+
69
+ Configuration: global `~/.diffpilot/diffpilot.toml` (auth — Codex home, OpenRouter key —, models, Jev; shared by all
70
+ projects) overridden key by key by the project's `diffpilot.toml` (paths, PRD categories, behavior).
71
+ Every command supports `--json`. Exit codes: 0 ok, 1 usage/config, 2 Codex auth, 3 LLM failure (input kept in the
72
+ inbox, retry with `diffpilot inbox --process`), 4 invalid model output (nothing written), 5 lock busy.
73
+
74
+ diffpilot documents itself: requirements, design rationale and project rules live in [docs/](docs/) and are
75
+ maintained with diffpilot.
76
+
77
+ ## Contribute
78
+
79
+ Issue Tracker: <https://gitlab.com/rocshers/python/diffpilot/-/issues>
80
+ Source Code: <https://gitlab.com/rocshers/python/diffpilot>
@@ -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] = []
@@ -0,0 +1,3 @@
1
+ from _typeshed import Incomplete
2
+
3
+ __version__: Incomplete
@@ -0,0 +1,3 @@
1
+ from diffpilot.cli import main
2
+
3
+ main()
@@ -0,0 +1 @@
1
+ from diffpilot.cli import main as main
@@ -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
+ )
@@ -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]