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/gitdiff.py ADDED
@@ -0,0 +1,170 @@
1
+ """git_diff_changelog_summary: one changelog entry from git diff + unreleased events."""
2
+
3
+ import fnmatch
4
+ import logging
5
+ import re
6
+ import subprocess
7
+ from datetime import date
8
+
9
+ from diffpilot import agents, events, prompts
10
+ from diffpilot.config import Config, DPError
11
+ from diffpilot.events import git_head
12
+ from diffpilot.index import Locked, now
13
+ from diffpilot.llm import Engine
14
+
15
+ log = logging.getLogger('diffpilot')
16
+
17
+ NOISE = [
18
+ '*.lock',
19
+ '*-lock.json',
20
+ '*.min.js',
21
+ '*.map',
22
+ '*.svg',
23
+ '*.png',
24
+ '*.jpg',
25
+ '*.gif',
26
+ '*.ico',
27
+ '*.pdf',
28
+ 'dist/*',
29
+ 'build/*',
30
+ '.gitignore',
31
+ '*/.gitignore',
32
+ 'LICENSE*',
33
+ '*.egg-info/*',
34
+ ]
35
+ STRUCTURE = re.compile(
36
+ r'^[+]?\s*(async def |def |class |function |export |interface |type |struct |fn |pub |func |#{1,3} |\[[\w.-]+\]\s*$|[A-Z_]{3,}\s*=)'
37
+ )
38
+
39
+
40
+ def _git(cfg: Config, *args: str) -> str:
41
+ r = subprocess.run(['git', *args], cwd=cfg.root, capture_output=True, text=True)
42
+ if r.returncode != 0:
43
+ raise DPError(f'git {" ".join(args)} failed: {r.stderr.strip()}')
44
+ return r.stdout
45
+
46
+
47
+ def resolve_base(cfg: Config, base: str | None, rng: str | None, staged: bool) -> tuple[list[str], str]:
48
+ if rng:
49
+ return [rng], rng
50
+ if staged:
51
+ return ['--cached'], 'staged changes'
52
+ if base:
53
+ return [base], f'{base}..working tree'
54
+ released = [e for e in events.events(cfg) if e.get('command') == 'release' and e.get('git_head')]
55
+ if released:
56
+ h = released[-1]['git_head']
57
+ return [h], f'{h} (last release)..working tree'
58
+ tag = subprocess.run(['git', 'describe', '--tags', '--abbrev=0'], cwd=cfg.root, capture_output=True, text=True)
59
+ if tag.returncode == 0:
60
+ t = tag.stdout.strip()
61
+ return [t], f'{t} (last tag)..working tree'
62
+ if _git(cfg, 'status', '--porcelain').strip():
63
+ return ['HEAD'], 'uncommitted changes'
64
+ return ['HEAD~1', 'HEAD'], 'last commit'
65
+
66
+
67
+ def _fit(lines: list[str], limit: int) -> list[str]:
68
+ """Drop blank lines; if still too long, keep only structural lines (defs, classes, headings)."""
69
+ lines = [ln for ln in lines if ln.strip('+- ')]
70
+ if sum(len(ln) + 1 for ln in lines) <= limit:
71
+ return lines
72
+ keep = [ln for ln in lines if ln.startswith('@@') or STRUCTURE.match(ln)]
73
+ out: list[str] = []
74
+ size = 0
75
+ for ln in keep:
76
+ if size + len(ln) > limit:
77
+ out.append(f'... ({len(keep) - len(out)} more structural lines)')
78
+ break
79
+ out.append(ln)
80
+ size += len(ln) + 1
81
+ return out + [f'... ({len(lines)} lines total, structure only)']
82
+
83
+
84
+ def compressed_diff(cfg: Config, args: list[str], budget_chars: int) -> str:
85
+ """Deterministic compression: file list with counts, then a fair per-file share of each patch.
86
+
87
+ diffpilot's own files (stores, changelog, state) are skipped: their changes arrive as events, with reasons.
88
+ """
89
+
90
+ def skip(path: str) -> bool:
91
+ return cfg.is_own(path) or any(fnmatch.fnmatch(path, g) for g in NOISE)
92
+
93
+ numstat = _git(cfg, 'diff', '--numstat', *args)
94
+ untracked = (
95
+ []
96
+ if '--cached' in args or '..' in ''.join(args)
97
+ else _git(cfg, 'ls-files', '--others', '--exclude-standard').split()
98
+ )
99
+ lines, items = ['Files:'], []
100
+ for row in numstat.splitlines():
101
+ add, rem, path = row.split('\t', 2)
102
+ lines.append(f' {path} +{add} -{rem}')
103
+ if add != '-' and not skip(path):
104
+ items.append((path, True))
105
+ for p in untracked:
106
+ lines.append(f' {p} (new, untracked)')
107
+ if not skip(p) and (cfg.root / p).is_file():
108
+ items.append((p, False))
109
+ out = '\n'.join(lines) + '\n'
110
+ share = max(1200, (budget_chars - len(out)) // max(len(items), 1))
111
+ for path, tracked in items:
112
+ if tracked:
113
+ patch = _git(cfg, 'diff', '-U1', *args, '--', path).splitlines()
114
+ body = [ln for ln in patch if ln.startswith(('@@', '+', '-')) and not ln.startswith(('+++', '---'))]
115
+ else:
116
+ try:
117
+ body = ['+' + x for x in (cfg.root / path).read_text(encoding='utf-8').splitlines()]
118
+ except UnicodeDecodeError:
119
+ continue
120
+ block = f'\n--- {path}{"" if tracked else " (new file)"}\n' + '\n'.join(_fit(body, share))
121
+ if len(out) + len(block) > budget_chars:
122
+ out += f'\n--- {path}: omitted (budget)'
123
+ continue
124
+ out += block
125
+ return out
126
+
127
+
128
+ async def summarize(
129
+ cfg: Config, base: str | None, rng: str | None, staged: bool, write: bool, version: str | None
130
+ ) -> dict:
131
+ if not cfg.behavior.git:
132
+ raise DPError('git_diff_changelog_summary needs git: [behavior].git is false')
133
+ args, label = resolve_base(cfg, base, rng, staged)
134
+ diff = compressed_diff(cfg, args, cfg.behavior.context_budget * 3)
135
+ pending = events.unreleased(cfg)
136
+ ev_text = '\n'.join(
137
+ f'- [{e.get("change_type", "changed")}] {e["summary"]}' + (f' — why: {e["reason"]}' if e.get('reason') else '')
138
+ for e in pending
139
+ )
140
+ if not diff.strip('Files:\n ') and not pending:
141
+ return {'ok': True, 'empty': True, 'base': label, 'entry': {}, 'lines': ['No changes to summarize.']}
142
+ async with Engine(cfg, 'changelog') as engine:
143
+ entry = await engine.run(
144
+ agents.changelog_writer,
145
+ prompts.CHANGELOG.format(language=cfg.behavior.language, events=ev_text or '(none)', base=label, diff=diff),
146
+ )
147
+ usage = engine.usage_dict()
148
+ groups = entry.model_dump()
149
+ title = f'[{version}] - {date.today().isoformat()}' if version else date.today().isoformat()
150
+ lines = [f'## {title}', *events.render_groups(groups)]
151
+ if write:
152
+ with Locked(cfg):
153
+ events.write_release(cfg, title, groups)
154
+ events.mark_released(cfg, {e['id'] for e in pending})
155
+ events.append(
156
+ cfg,
157
+ {
158
+ 'id': events.new_id(),
159
+ 'ts': now(),
160
+ 'command': 'release',
161
+ 'summary': title,
162
+ 'git_head': git_head(cfg),
163
+ 'changelog': False,
164
+ 'released': True,
165
+ 'ops': [],
166
+ },
167
+ )
168
+ events.refresh_unreleased(cfg)
169
+ lines.append(f'\nWritten to {cfg.paths.changelog}; {len(pending)} event(s) marked released.')
170
+ return {'ok': True, 'base': label, 'entry': groups, 'title': title, 'lines': lines, 'usage': usage}
diffpilot/gitdiff.pyi ADDED
@@ -0,0 +1,14 @@
1
+ from _typeshed import Incomplete
2
+ from diffpilot import agents as agents, events as events, prompts as prompts
3
+ from diffpilot.config import Config as Config, DPError as DPError
4
+ from diffpilot.events import git_head as git_head
5
+ from diffpilot.index import Locked as Locked, now as now
6
+ from diffpilot.llm import Engine as Engine
7
+
8
+ log: Incomplete
9
+ NOISE: Incomplete
10
+ STRUCTURE: Incomplete
11
+
12
+ def resolve_base(cfg: Config, base: str | None, rng: str | None, staged: bool) -> tuple[list[str], str]: ...
13
+ def compressed_diff(cfg: Config, args: list[str], budget_chars: int) -> str: ...
14
+ async def summarize(cfg: Config, base: str | None, rng: str | None, staged: bool, write: bool, version: str | None) -> dict: ...
diffpilot/index.py ADDED
@@ -0,0 +1,242 @@
1
+ """Section index (.diffpilot/index.json): hashes, summaries, links, search, outline."""
2
+
3
+ import fnmatch
4
+ import json
5
+ import math
6
+ import re
7
+ from collections import Counter
8
+ from dataclasses import dataclass
9
+ from datetime import UTC, datetime
10
+
11
+ from filelock import FileLock, Timeout
12
+
13
+ from diffpilot import store
14
+ from diffpilot.config import Config, DPError
15
+
16
+ HISTORY = re.compile(r'\b\d{4}-\d{2}(-\d{2})?\b|\b(history|historical|archive|archived|changelog|log)\b', re.I)
17
+
18
+
19
+ def now() -> str:
20
+ return datetime.now(UTC).strftime('%Y-%m-%dT%H:%M:%SZ')
21
+
22
+
23
+ @dataclass
24
+ class View:
25
+ ref: str
26
+ store: str
27
+ file: str
28
+ heading: str
29
+ path: str
30
+ body: str
31
+ hash: str
32
+ lines: tuple[int, int]
33
+ tokens: int
34
+ children: list[str]
35
+ level: int
36
+
37
+
38
+ def load_views(cfg: Config) -> dict[str, View]:
39
+ views: dict[str, View] = {}
40
+ for st in cfg.stores:
41
+ p = cfg.store_path(st)
42
+ if not p.exists():
43
+ continue
44
+ text = p.read_text(encoding='utf-8')
45
+ lines = text.split('\n')
46
+ sections = store.parse(text)
47
+ for s in sections:
48
+ if not s.id:
49
+ continue
50
+ body = s.body(lines)
51
+ children = [f'{st}:{c.id}' for c in sections if c.parent is not None and sections[c.parent] is s and c.id]
52
+ views[f'{st}:{s.id}'] = View(
53
+ ref=f'{st}:{s.id}',
54
+ store=st,
55
+ file=cfg.rel(p),
56
+ heading=s.heading,
57
+ path=' > '.join(s.path),
58
+ body=body,
59
+ hash=store.section_hash(s.heading, body),
60
+ lines=(s.start + 1, s.end),
61
+ tokens=store.tokens(body),
62
+ children=children,
63
+ level=s.level,
64
+ )
65
+ return views
66
+
67
+
68
+ def lock(cfg: Config) -> FileLock:
69
+ cfg.state.mkdir(parents=True, exist_ok=True)
70
+ return FileLock(str(cfg.state / 'lock'), timeout=60)
71
+
72
+
73
+ class Locked:
74
+ def __init__(self, cfg: Config) -> None:
75
+ self.lock = lock(cfg)
76
+
77
+ def __enter__(self) -> None:
78
+ try:
79
+ self.lock.acquire()
80
+ except Timeout as e:
81
+ raise DPError('another diffpilot process holds the lock', 5) from e
82
+
83
+ def __exit__(self, *exc: object) -> None:
84
+ self.lock.release()
85
+
86
+
87
+ @dataclass
88
+ class SyncResult:
89
+ added: list[str]
90
+ changed: list[str]
91
+ removed: list[str]
92
+
93
+ @property
94
+ def any(self) -> bool:
95
+ return bool(self.added or self.changed or self.removed)
96
+
97
+
98
+ class Index:
99
+ def __init__(self, cfg: Config) -> None:
100
+ self.cfg = cfg
101
+ self.path = cfg.state / 'index.json'
102
+ self.data: dict = {'version': 1, 'sections': {}, 'meta': {}}
103
+ if self.path.exists():
104
+ self.data = json.loads(self.path.read_text(encoding='utf-8'))
105
+ self.views: dict[str, View] = {}
106
+
107
+ @property
108
+ def sections(self) -> dict[str, dict]:
109
+ return self.data['sections']
110
+
111
+ @property
112
+ def meta(self) -> dict:
113
+ return self.data.setdefault('meta', {})
114
+
115
+ def save(self) -> None:
116
+ store.atomic_write(self.path, json.dumps(self.data, indent=1, ensure_ascii=False, sort_keys=True) + '\n')
117
+
118
+ def sync(self, origin: str | None = None, change: str | None = None) -> SyncResult:
119
+ """Re-parse stores. Sections changed since the last sync get `origin` (default: 'manual')."""
120
+ for st in self.cfg.stores:
121
+ p = self.cfg.store_path(st)
122
+ if p.exists():
123
+ raw = p.read_text(encoding='utf-8')
124
+ text = store.ensure_ids(store.promote_outline(raw))[0]
125
+ if text != raw:
126
+ store.atomic_write(p, text)
127
+ self.views = load_views(self.cfg)
128
+ res = SyncResult([], [], [])
129
+ ts = now()
130
+ for ref, v in self.views.items():
131
+ e = self.sections.get(ref)
132
+ if e is None:
133
+ e = self.sections[ref] = {'summary': '', 'keywords': [], 'links': [], 'code_refs': [], 'sources': []}
134
+ res.added.append(ref)
135
+ elif e['hash'] != v.hash:
136
+ res.changed.append(ref)
137
+ e['summary'], e['keywords'] = '', []
138
+ else:
139
+ e.update(file=v.file, heading=v.path, lines=list(v.lines), tokens=v.tokens)
140
+ continue
141
+ e.update(file=v.file, heading=v.path, lines=list(v.lines), tokens=v.tokens, hash=v.hash)
142
+ e.update(origin=origin or 'manual', updated_at=ts, last_change=change)
143
+ for ref in [r for r in self.sections if r not in self.views]:
144
+ del self.sections[ref]
145
+ res.removed.append(ref)
146
+ for e in self.sections.values():
147
+ e['links'] = [x for x in e.get('links', []) if x in self.views]
148
+ self.save()
149
+ return res
150
+
151
+ # --- retrieval -------------------------------------------------------
152
+
153
+ def summary(self, ref: str) -> str:
154
+ s = self.sections.get(ref, {}).get('summary')
155
+ if s:
156
+ return s
157
+ body = re.sub(r'\s+', ' ', self.views[ref].body).strip()
158
+ first = re.split(r'(?<=[.!?])\s', body, maxsplit=1)[0]
159
+ return (first[:140] + '…') if len(first) > 140 else first
160
+
161
+ def resolve(self, query: str) -> list[str]:
162
+ """Refs matching an exact ref, else a ref prefix (store optional), else a heading (case-insensitive)."""
163
+ if query in self.views:
164
+ return [query]
165
+ refs = [r for r in self.views if r.startswith(query) or r.split(':', 1)[1].startswith(query)]
166
+ top = [r for r in refs if all(o == r or o.startswith(r + '.') for o in refs)]
167
+ refs = top or refs # a prefix that matches a section and its descendants means the section
168
+ return refs or [r for r, v in self.views.items() if v.heading.lower() == query.strip().lower()]
169
+
170
+ def is_history(self, ref: str) -> bool:
171
+ """Dated or archive sections (by heading path or [behavior].history ref globs): past, not current state."""
172
+ if any(fnmatch.fnmatch(ref, g) for g in self.cfg.behavior.history):
173
+ return True
174
+ return bool(HISTORY.search(self.views[ref].path))
175
+
176
+ def outline(self, stores: tuple[str, ...] = (), depth: int = 0, grep: str = '') -> str:
177
+ """depth: heading levels below the store title (0 = all); grep: case-insensitive ref/heading/summary filter."""
178
+ out: list[str] = []
179
+ for st in stores or self.cfg.stores:
180
+ refs = [
181
+ v
182
+ for v in self.views.values()
183
+ if v.store == st
184
+ and not (depth and v.level > depth + 1)
185
+ and grep.lower() in f'{v.ref} {v.path} {self.summary(v.ref)}'.lower()
186
+ ]
187
+ out.append(f'## {st} ({self.cfg.rel(self.cfg.store_path(st))}) — {self.cfg.store_title(st)}')
188
+ if grep and not refs:
189
+ out.pop() # filtered: stores without a match are left out
190
+ elif not refs:
191
+ out.append('(empty)')
192
+ for v in refs:
193
+ indent = ' ' * max(v.level - 2, 0)
194
+ out.append(f'{indent}- {v.ref} | {v.heading} | ~{v.tokens}t | {self.summary(v.ref)}')
195
+ return '\n'.join(out)
196
+
197
+ def show(self, ref: str) -> str:
198
+ v = self.views.get(ref)
199
+ if v is None:
200
+ return f'[{ref}] not found'
201
+ e = self.sections.get(ref, {})
202
+ meta = f'{v.file}:{v.lines[0]}-{v.lines[1]}, origin: {e.get("origin", "?")}, updated {e.get("updated_at", "?")[:10]}'
203
+ parts = [f'[{ref}] {v.path} ({meta})', v.body or '(no body)']
204
+ if v.children:
205
+ parts.append('children: ' + ', '.join(v.children))
206
+ if e.get('links'):
207
+ parts.append('related: ' + ', '.join(e['links']))
208
+ if e.get('code_refs'):
209
+ parts.append('code: ' + ', '.join(e['code_refs']))
210
+ return '\n'.join(parts)
211
+
212
+ def search(self, query: str, limit: int = 8, stores: tuple[str, ...] = ()) -> list[tuple[str, float]]:
213
+ """BM25 over heading + body + keywords."""
214
+ stores = stores or self.cfg.stores
215
+ docs = {
216
+ r: _terms(f'{v.path} {v.path} {v.body} {" ".join(self.sections.get(r, {}).get("keywords", []))}')
217
+ for r, v in self.views.items()
218
+ if v.store in stores
219
+ }
220
+ q = set(_terms(query))
221
+ if not docs or not q:
222
+ return []
223
+ avg = sum(len(d) for d in docs.values()) / len(docs)
224
+ df = Counter(t for d in docs.values() for t in set(d))
225
+ scores = []
226
+ for ref, d in docs.items():
227
+ tf = Counter(d)
228
+ score = 0.0
229
+ for t in q & tf.keys():
230
+ idf = math.log(1 + (len(docs) - df[t] + 0.5) / (df[t] + 0.5))
231
+ score += idf * tf[t] * 2.2 / (tf[t] + 1.2 * (0.25 + 0.75 * len(d) / avg))
232
+ if score > 0:
233
+ scores.append((ref, score))
234
+ return sorted(scores, key=lambda x: -x[1])[:limit]
235
+
236
+ def stale(self, stores: tuple[str, ...] = ()) -> list[str]:
237
+ stores = stores or self.cfg.stores
238
+ return [r for r, v in self.views.items() if v.store in stores and not self.sections[r].get('summary')]
239
+
240
+
241
+ def _terms(text: str) -> list[str]:
242
+ return [t for t in re.findall(r'\w+', text.lower()) if len(t) > 1]
diffpilot/index.pyi ADDED
@@ -0,0 +1,60 @@
1
+ from _typeshed import Incomplete
2
+ from dataclasses import dataclass
3
+ from diffpilot import store as store
4
+ from diffpilot.config import Config as Config, DPError as DPError
5
+ from filelock import FileLock
6
+
7
+ HISTORY: Incomplete
8
+
9
+ def now() -> str: ...
10
+
11
+ @dataclass
12
+ class View:
13
+ ref: str
14
+ store: str
15
+ file: str
16
+ heading: str
17
+ path: str
18
+ body: str
19
+ hash: str
20
+ lines: tuple[int, int]
21
+ tokens: int
22
+ children: list[str]
23
+ level: int
24
+
25
+ def load_views(cfg: Config) -> dict[str, View]: ...
26
+ def lock(cfg: Config) -> FileLock: ...
27
+
28
+ class Locked:
29
+ lock: Incomplete
30
+ def __init__(self, cfg: Config) -> None: ...
31
+ def __enter__(self) -> None: ...
32
+ def __exit__(self, *exc: object) -> None: ...
33
+
34
+ @dataclass
35
+ class SyncResult:
36
+ added: list[str]
37
+ changed: list[str]
38
+ removed: list[str]
39
+ @property
40
+ def any(self) -> bool: ...
41
+
42
+ class Index:
43
+ cfg: Incomplete
44
+ path: Incomplete
45
+ data: dict
46
+ views: dict[str, View]
47
+ def __init__(self, cfg: Config) -> None: ...
48
+ @property
49
+ def sections(self) -> dict[str, dict]: ...
50
+ @property
51
+ def meta(self) -> dict: ...
52
+ def save(self) -> None: ...
53
+ def sync(self, origin: str | None = None, change: str | None = None) -> SyncResult: ...
54
+ def summary(self, ref: str) -> str: ...
55
+ def resolve(self, query: str) -> list[str]: ...
56
+ def is_history(self, ref: str) -> bool: ...
57
+ def outline(self, stores: tuple[str, ...] = (), depth: int = 0, grep: str = '') -> str: ...
58
+ def show(self, ref: str) -> str: ...
59
+ def search(self, query: str, limit: int = 8, stores: tuple[str, ...] = ()) -> list[tuple[str, float]]: ...
60
+ def stale(self, stores: tuple[str, ...] = ()) -> list[str]: ...
diffpilot/jev.py ADDED
@@ -0,0 +1,203 @@
1
+ """TypeSafe Jev (via OpenRouter) on Pydantic AI's TypeSafeModel: fast, cheap typed decisions.
2
+
3
+ Used where diffpilot classifies rather than writes: reranking retrieval candidates by relevance and routing input to
4
+ stores. Jev is an optimization, never a requirement: without an OpenRouter key, or on any Jev failure, callers get
5
+ None and fall back to BM25 / the LLM agent.
6
+ """
7
+
8
+ import asyncio
9
+ import logging
10
+ from typing import Any
11
+
12
+ from pydantic import BaseModel, Field, create_model
13
+ from pydantic_ai import Agent
14
+ from pydantic_ai.models import Model
15
+ from pydantic_ai.models.typesafe import TypeSafeModel
16
+ from pydantic_ai.providers.typesafe import TypeSafeProvider
17
+
18
+ from diffpilot.config import Config
19
+ from diffpilot.index import Index
20
+ from diffpilot.store import clip
21
+
22
+ log = logging.getLogger('diffpilot')
23
+ OPENROUTER_BASE = 'https://openrouter.ai/api' # the SDK appends /v1/systemone
24
+ SECTION_CHARS = 1500 # per candidate in a rerank request
25
+ EVIDENCE_CHARS = 8000 # per section when checking whether a fact is stated (clipping hides facts)
26
+ POOL = 40 # max candidates (questions) per request
27
+ CHUNK_CHARS = 6000 # per doc chunk in a triage request (= bootstrap CHUNK_MAX)
28
+ PARALLEL = 8 # concurrent Jev requests
29
+
30
+ SCOPES = {
31
+ 'prd': 'the current product vision: what the product does and must do',
32
+ 'impl': 'how things are built and why: trade-offs, workarounds, gotchas, limitations',
33
+ 'instructions': 'standing rules for working on the project: tooling, conventions, process',
34
+ }
35
+
36
+
37
+ class Jev:
38
+ """One per command. `available` turns False after the first failure so a broken key costs one request."""
39
+
40
+ def __init__(self, cfg: Config) -> None:
41
+ self.cfg = cfg
42
+ self.calls = 0
43
+ self.model: Model | None = None
44
+ if cfg.jev.enabled and cfg.openrouter_key:
45
+ self.model = TypeSafeModel(
46
+ cfg.jev.model,
47
+ provider=TypeSafeProvider(api_key=cfg.openrouter_key, base_url=OPENROUTER_BASE),
48
+ settings={'timeout': cfg.jev.timeout_s},
49
+ )
50
+
51
+ @property
52
+ def available(self) -> bool:
53
+ return self.model is not None
54
+
55
+ async def probabilities(self, state: str, questions: dict[str, str]) -> dict[str, float] | None:
56
+ """P(yes) for each {key: yes/no question} about `state`, in one request."""
57
+ if not self.available or not questions:
58
+ return None
59
+ keys = list(questions)
60
+ fields: dict[str, Any] = {
61
+ f'q{i}': (float, Field(ge=0, le=1, description=questions[k])) for i, k in enumerate(keys)
62
+ }
63
+ out_type: type[BaseModel] = create_model('Decision', **fields)
64
+ try:
65
+ res = await Agent(self.model, output_type=out_type).run(state)
66
+ except Exception as e: # noqa: BLE001 - Jev is optional: any failure means "fall back"
67
+ log.warning('jev unavailable, falling back to keyword search: %s', e)
68
+ self.model = None
69
+ return None
70
+ self.calls += 1
71
+ return {k: float(getattr(res.output, f'q{i}')) for i, k in enumerate(keys)}
72
+
73
+ async def relevance(self, request: str, candidates: dict[str, str]) -> dict[str, float] | None:
74
+ """P(section is relevant to the request) for each {ref: text}."""
75
+ sections = '\n\n'.join(f'[{r}] {clip(t, SECTION_CHARS)}' for r, t in candidates.items())
76
+ state = f'Request:\n{request[:4000]}\n\nDocumentation sections:\n{sections}'
77
+ return await self.probabilities(
78
+ state,
79
+ {
80
+ r: f'Is section [{r}] relevant to the request: does it state facts, rules or decisions the request '
81
+ 'is about, asks about, or would change (not merely sharing a few words)?'
82
+ for r in candidates
83
+ },
84
+ )
85
+
86
+ async def route(self, text: str, scopes: dict[str, str]) -> dict[str, float] | None:
87
+ """P(input contains knowledge for the store) for each {store: scope description}."""
88
+ return await self.probabilities(
89
+ f'Input:\n{text[:8000]}',
90
+ {
91
+ st: f'Does the input contain knowledge that belongs in the "{st}" store: {d}?'
92
+ for st, d in scopes.items()
93
+ },
94
+ )
95
+
96
+
97
+ async def rank(
98
+ j: Jev | None, idx: Index, query: str, limit: int, stores: tuple[str, ...], threshold: float
99
+ ) -> list[tuple[str, float]]:
100
+ """BM25 candidates (padded with other sections for vocabulary mismatches), reranked by Jev when available."""
101
+ hits = idx.search(query, limit=max(limit, 20), stores=stores)
102
+ if j is None or not j.available:
103
+ return hits[:limit]
104
+ pool = [r for r, _ in hits if idx.views[r].body] # heading-only sections carry no facts
105
+ pool += [r for r, v in idx.views.items() if v.store in stores and v.body and r not in pool][: POOL - len(pool)]
106
+ if not pool:
107
+ return []
108
+ probs = await j.relevance(query, {r: f'{idx.views[r].path}\n{idx.views[r].body}' for r in pool})
109
+ if probs is None:
110
+ return hits[:limit]
111
+ ranked = sorted(((r, p) for r, p in probs.items() if p >= threshold), key=lambda x: -x[1])
112
+ return ranked[:limit]
113
+
114
+
115
+ async def chunk_value(j: Jev | None, chunks: dict[str, str]) -> dict[str, float] | None:
116
+ """P(chunk states durable project knowledge) for {key: text}.
117
+
118
+ One request per chunk, run in parallel: with several chunks in one state Jev mixes them up (measured: scores of
119
+ 0.2-0.4 for chunks that score 0.8-0.95 alone).
120
+ """
121
+ if j is None or not j.available or not chunks:
122
+ return None
123
+ question = (
124
+ 'Does this documentation chunk state durable project knowledge (requirements, product behavior, design '
125
+ 'decisions and their reasons, gotchas, working rules), rather than only badges, install or usage boilerplate, '
126
+ 'marketing, changelog history, TODOs or links?'
127
+ )
128
+ limit = asyncio.Semaphore(PARALLEL)
129
+
130
+ async def one(key: str) -> float | None:
131
+ async with limit:
132
+ probs = await j.probabilities(f'Documentation chunk:\n{clip(chunks[key], CHUNK_CHARS)}', {'v': question})
133
+ return probs['v'] if probs else None
134
+
135
+ values = await asyncio.gather(*(one(k) for k in chunks))
136
+ if any(v is None for v in values):
137
+ return None
138
+ return dict(zip(chunks, values, strict=True)) # type: ignore[arg-type]
139
+
140
+
141
+ async def covered(j: Jev | None, idx: Index, facts: list[str], stores: tuple[str, ...]) -> list[float] | None:
142
+ """P(fact is already stated in the stores) per fact: its best-ranked sections, then one yes/no question.
143
+
144
+ Atomic facts are judged reliably (measured: recorded 0.8-0.9, missing 0.15-0.35, contradicted ~0.05); whole
145
+ chunks are not, so callers check facts, never chunks.
146
+ """
147
+ if j is None or not j.available:
148
+ return None
149
+ limit = asyncio.Semaphore(PARALLEL)
150
+ question = 'Is this fact stated in the documentation sections (same meaning; wording may differ)?'
151
+
152
+ async def one(fact: str) -> float | None:
153
+ async with limit:
154
+ hits = await rank(j, idx, fact, 5, stores, 0.0)
155
+ if not hits:
156
+ return 0.0
157
+ docs = '\n\n'.join(f'[{r}]\n{clip(idx.views[r].body, EVIDENCE_CHARS)}' for r, _ in hits)
158
+ probs = await j.probabilities(f'Fact:\n{fact}\n\nDocumentation sections:\n{docs}', {'c': question})
159
+ return probs['c'] if probs else None
160
+
161
+ values = await asyncio.gather(*(one(f) for f in facts))
162
+ return None if any(v is None for v in values) else values # type: ignore[return-value]
163
+
164
+
165
+ async def stated(j: Jev | None, facts: list[tuple[str, str]]) -> list[float] | None:
166
+ """P(fact is stated in its text) for each (fact, text) pair, in parallel."""
167
+ if j is None or not j.available:
168
+ return None
169
+ limit = asyncio.Semaphore(PARALLEL)
170
+ question = 'Does the text state this fact with all its specifics (names, numbers, values, reasons)?'
171
+
172
+ async def one(fact: str, text: str) -> float | None:
173
+ async with limit:
174
+ probs = await j.probabilities(f'Fact:\n{fact}\n\nText:\n{text}', {'c': question})
175
+ return probs['c'] if probs else None
176
+
177
+ values = await asyncio.gather(*(one(f, t) for f, t in facts))
178
+ return None if any(v is None for v in values) else values # type: ignore[return-value]
179
+
180
+
181
+ def scopes(cfg: Config, stores: tuple[str, ...]) -> dict[str, str]:
182
+ out = {}
183
+ for st in stores:
184
+ base, _, cat = st.partition('.')
185
+ out[st] = f'product requirements, details of: {cfg.prd_categories[cat]}' if cat else SCOPES[base]
186
+ if 'prd' in out and any('.' in s for s in stores):
187
+ out['prd'] = 'the general product vision and overview; details of specific areas belong elsewhere'
188
+ return out
189
+
190
+
191
+ async def routing_hint(j: Jev | None, cfg: Config, text: str, stores: tuple[str, ...]) -> str:
192
+ """One prompt line with the likely target stores, or '' when Jev is unavailable or there is no choice."""
193
+ if j is None or not j.available or len(stores) < 2:
194
+ return ''
195
+ probs = await j.route(text, scopes(cfg, stores))
196
+ if not probs:
197
+ return ''
198
+ likely = [f'{st} ({p:.2f})' for st, p in sorted(probs.items(), key=lambda x: -x[1]) if p >= 0.5]
199
+ return (
200
+ 'Routing hint from a fast classifier (may be wrong; verify against the input): likely target stores: '
201
+ + (', '.join(likely) or 'none is clear')
202
+ + '\n'
203
+ )