ticket-precedent 0.2.0__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.
@@ -0,0 +1,3 @@
1
+ from importlib.metadata import version
2
+
3
+ __version__ = version("ticket-precedent")
@@ -0,0 +1,75 @@
1
+ from __future__ import annotations
2
+
3
+ import fcntl
4
+ import logging
5
+ import threading
6
+ from collections.abc import Iterator, Sequence
7
+ from contextlib import contextmanager
8
+ from datetime import UTC, datetime, timedelta
9
+ from pathlib import Path
10
+
11
+ from .config import Config, SourceConfig, build_connector, build_embedder
12
+ from .ingest import sync
13
+ from .store import Store
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ def due_sources(
19
+ store: Store, sources: Sequence[SourceConfig], max_age: timedelta
20
+ ) -> list[SourceConfig]:
21
+ now = datetime.now(UTC)
22
+ return [
23
+ source
24
+ for source in sources
25
+ if (synced := store.synced_at(source.name)) is None or now - synced >= max_age
26
+ ]
27
+
28
+
29
+ @contextmanager
30
+ def sync_lock(index_path: Path) -> Iterator[bool]:
31
+ """Yield True when this process may write to the index, False if another one is syncing."""
32
+ lock_path = index_path.with_name(index_path.name + ".sync.lock")
33
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
34
+ with lock_path.open("w") as lock:
35
+ try:
36
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
37
+ except BlockingIOError:
38
+ yield False
39
+ return
40
+ yield True
41
+
42
+
43
+ def run_due_syncs(config: Config) -> None:
44
+ if not config.auto_sync_hours:
45
+ return
46
+ with sync_lock(config.index_path) as acquired:
47
+ if not acquired:
48
+ logger.info("another process is already syncing %s", config.index_path)
49
+ return
50
+ _sync_due(config, timedelta(hours=config.auto_sync_hours))
51
+
52
+
53
+ def _sync_due(config: Config, max_age: timedelta) -> None:
54
+ store = Store(config.index_path)
55
+ try:
56
+ embedder = build_embedder(config.embedding)
57
+ for source in due_sources(store, config.sources, max_age):
58
+ try:
59
+ stats = sync(store, embedder, build_connector(source), source.name, source.chunking)
60
+ except Exception:
61
+ logger.exception("auto-sync of %s failed", source.name)
62
+ continue
63
+ logger.info(
64
+ "auto-sync %s: %d tickets, %d chunks", source.name, stats.tickets, stats.embedded
65
+ )
66
+ finally:
67
+ store.close()
68
+
69
+
70
+ def start_background_sync(config: Config) -> threading.Thread | None:
71
+ if not config.auto_sync_hours or not config.sources:
72
+ return None
73
+ thread = threading.Thread(target=run_due_syncs, args=(config,), name="auto-sync", daemon=True)
74
+ thread.start()
75
+ return thread
@@ -0,0 +1,51 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+
5
+ from .models import Chunk, Ticket
6
+ from .text import clean, windows
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class ChunkingConfig:
11
+ max_chars: int = 1500
12
+ overlap: int = 200
13
+ max_body_chunks: int = 8
14
+ index_comments: bool = True
15
+ max_comment_chunks: int = 20
16
+ min_comment_chars: int = 40
17
+ skip_comment_authors: frozenset[str] = field(default_factory=frozenset)
18
+
19
+
20
+ def chunk_ticket(ticket: Ticket, config: ChunkingConfig) -> list[Chunk]:
21
+ title = ticket.title.strip()
22
+ body_windows = windows(clean(ticket.description), config.max_chars, config.overlap)
23
+ chunks = [
24
+ Chunk("body", i, _with_title(title, window))
25
+ for i, window in enumerate(body_windows[: config.max_body_chunks])
26
+ ]
27
+ if not chunks:
28
+ chunks.append(Chunk("body", 0, title))
29
+ if not config.index_comments:
30
+ return chunks
31
+ return chunks + _comment_chunks(ticket, title, config)
32
+
33
+
34
+ def _comment_chunks(ticket: Ticket, title: str, config: ChunkingConfig) -> list[Chunk]:
35
+ skip = {author.lower() for author in config.skip_comment_authors}
36
+ result: list[Chunk] = []
37
+ for comment in ticket.comments:
38
+ if comment.author.lower() in skip:
39
+ continue
40
+ body = clean(comment.body)
41
+ if len(body) < config.min_comment_chars:
42
+ continue
43
+ for window in windows(body, config.max_chars, config.overlap):
44
+ if len(result) >= config.max_comment_chunks:
45
+ return result
46
+ result.append(Chunk("comment", len(result), _with_title(title, window)))
47
+ return result
48
+
49
+
50
+ def _with_title(title: str, text: str) -> str:
51
+ return f"{title}\n\n{text}" if title else text
@@ -0,0 +1,372 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import re
6
+ import sys
7
+ from collections.abc import Callable
8
+ from dataclasses import asdict
9
+ from pathlib import Path
10
+
11
+ import httpx
12
+
13
+ from .autosync import sync_lock
14
+ from .chunking import ChunkingConfig
15
+ from .config import (
16
+ Config,
17
+ ConfigError,
18
+ EmbeddingConfig,
19
+ SourceConfig,
20
+ build_connector,
21
+ build_embedder,
22
+ build_searcher,
23
+ config_dir,
24
+ data_dir,
25
+ load_config,
26
+ )
27
+ from .connectors.http import RateLimitError
28
+ from .connectors.jira import JiraConnector
29
+ from .demo import APACHE_BOTS, APACHE_JIRA, ZOOKEEPER, DemoError, download, write_config
30
+ from .effort import reference_for_ticket
31
+ from .embeddings import EmbeddingError
32
+ from .evaluation.dataset import duplicate_queries
33
+ from .evaluation.metrics import markdown_table
34
+ from .evaluation.runner import evaluate
35
+ from .ingest import SyncStats, sync
36
+ from .search import (
37
+ MODES,
38
+ Filters,
39
+ Outcome,
40
+ Searcher,
41
+ TicketNotFoundError,
42
+ describe,
43
+ find_precedents,
44
+ resolve_ticket,
45
+ search_or_degrade,
46
+ ticket_details,
47
+ )
48
+ from .store import IndexMismatchError, Store
49
+
50
+
51
+ def main(argv: list[str] | None = None) -> int:
52
+ args = _parser().parse_args(argv)
53
+ handler: Callable[[argparse.Namespace], int] = args.handler
54
+ try:
55
+ return handler(args)
56
+ except (
57
+ ConfigError,
58
+ DemoError,
59
+ EmbeddingError,
60
+ IndexMismatchError,
61
+ RateLimitError,
62
+ TicketNotFoundError,
63
+ ) as error:
64
+ print(f"error: {error}", file=sys.stderr)
65
+ return 1
66
+
67
+
68
+ def _parser() -> argparse.ArgumentParser:
69
+ parser = argparse.ArgumentParser(prog="tp", description="Find precedents for new tickets.")
70
+ parser.add_argument("--config", type=Path, help="config file (default ~/.config/...)")
71
+ commands = parser.add_subparsers(required=True, metavar="command")
72
+
73
+ cmd = commands.add_parser("sync", help="fetch new and updated tickets into the index")
74
+ cmd.add_argument("--source", help="only this source")
75
+ cmd.add_argument("--full", action="store_true", help="refetch everything")
76
+ cmd.set_defaults(handler=_sync)
77
+
78
+ cmd = commands.add_parser("search", help="search the index")
79
+ cmd.add_argument("text")
80
+ cmd.add_argument("--source")
81
+ cmd.add_argument("--project")
82
+ cmd.add_argument("--platform", help='only this platform, "all" for every source')
83
+ cmd.add_argument("--limit", type=int, default=5)
84
+ cmd.add_argument("--mode", choices=MODES, default="hybrid")
85
+ cmd.add_argument("--json", action="store_true")
86
+ cmd.set_defaults(handler=_search)
87
+
88
+ cmd = commands.add_parser("precedents", help="earlier tickets that look like an indexed one")
89
+ cmd.add_argument("key", help="ticket key, e.g. PROJ-42 or a helpdesk number")
90
+ cmd.add_argument("--source", help="source of the ticket when the key is ambiguous")
91
+ cmd.add_argument("--only-source", help="only return tickets from this source")
92
+ cmd.add_argument("--platform", help="platform of the results (default: the ticket's own)")
93
+ cmd.add_argument("--limit", type=int, default=5)
94
+ cmd.add_argument("--json", action="store_true")
95
+ cmd.set_defaults(handler=_precedents)
96
+
97
+ cmd = commands.add_parser("effort", help="logged hours of similar tickets finished earlier")
98
+ cmd.add_argument("key", help="ticket key, e.g. PROJ-42")
99
+ cmd.add_argument("--source", help="source of the ticket when the key is ambiguous")
100
+ cmd.add_argument("--since", help="only tickets created on or after YYYY-MM-DD")
101
+ cmd.add_argument("--platform", help="platform of the results (default: the ticket's own)")
102
+ cmd.add_argument("--limit", type=int, default=10)
103
+ cmd.add_argument("--json", action="store_true")
104
+ cmd.set_defaults(handler=_effort)
105
+
106
+ cmd = commands.add_parser("show", help="print one indexed ticket")
107
+ cmd.add_argument("source")
108
+ cmd.add_argument("key")
109
+ cmd.set_defaults(handler=_show)
110
+
111
+ cmd = commands.add_parser("stats", help="indexed sources")
112
+ cmd.set_defaults(handler=_stats)
113
+
114
+ cmd = commands.add_parser("serve", help="run the MCP server on stdio")
115
+ cmd.set_defaults(handler=_serve)
116
+
117
+ cmd = commands.add_parser("demo", help="try it on a ready-made index of public tickets")
118
+ cmd.add_argument("--force", action="store_true", help="download the index again")
119
+ cmd.set_defaults(handler=_demo)
120
+
121
+ cmd = commands.add_parser("eval", help="benchmark on a public Apache JIRA project")
122
+ cmd.add_argument("project", help="Apache JIRA project key, e.g. KAFKA")
123
+ cmd.add_argument("--since", help="only index tickets created on or after YYYY-MM-DD")
124
+ cmd.add_argument("--model", default="bge-m3", help="Ollama embedding model")
125
+ cmd.add_argument("--query-prefix", default="")
126
+ cmd.add_argument("--document-prefix", default="")
127
+ cmd.add_argument("--no-comments", action="store_true", help="index title + description only")
128
+ cmd.add_argument("--no-sync", action="store_true", help="evaluate the existing index")
129
+ cmd.add_argument("--modes", default=",".join(MODES))
130
+ cmd.add_argument("--max-queries", type=int)
131
+ cmd.add_argument("--out", type=Path, help="write per-query results as JSON")
132
+ cmd.set_defaults(handler=_eval)
133
+ return parser
134
+
135
+
136
+ def _sync(args: argparse.Namespace) -> int:
137
+ config = load_config(args.config)
138
+ sources = [config.source(args.source)] if args.source else config.sources
139
+ if not sources:
140
+ raise ConfigError("No sources configured; see config.example.yaml")
141
+ with sync_lock(config.index_path) as acquired:
142
+ if not acquired:
143
+ print(f"error: another process is syncing {config.index_path}", file=sys.stderr)
144
+ return 1
145
+ _sync_sources(config, sources, full=args.full)
146
+ return 0
147
+
148
+
149
+ def _sync_sources(config: Config, sources: list[SourceConfig], full: bool) -> None:
150
+ store = Store(config.index_path)
151
+ embedder = build_embedder(config.embedding)
152
+ for source in sources:
153
+ print(f"{source.name}: syncing", file=sys.stderr)
154
+ stats = sync(
155
+ store,
156
+ embedder,
157
+ build_connector(source),
158
+ source.name,
159
+ source.chunking,
160
+ full=full,
161
+ progress=_progress(source.name),
162
+ )
163
+ print(
164
+ f"\n{source.name}: {stats.tickets} tickets, {stats.embedded} new chunks",
165
+ file=sys.stderr,
166
+ )
167
+
168
+
169
+ def _search(args: argparse.Namespace) -> int:
170
+ config = load_config(args.config)
171
+ store = Store(config.index_path)
172
+ searcher = build_searcher(config, store)
173
+ _, sources = (None, None) if args.source else config.scope(args.platform)
174
+ filters = Filters(args.source, args.project, sources=sources)
175
+ outcome = search_or_degrade(searcher, args.text, args.mode, args.limit, filters)
176
+ return _print_outcome(store, outcome, as_json=args.json)
177
+
178
+
179
+ def _precedents(args: argparse.Namespace) -> int:
180
+ config = load_config(args.config)
181
+ store = Store(config.index_path)
182
+ ticket = resolve_ticket(store, args.key, args.source)
183
+ print(f"precedents for [{ticket['source']}] {ticket['key']} {ticket['title']}", file=sys.stderr)
184
+ _, sources = (None, None) if args.only_source else config.scope(args.platform, ticket["source"])
185
+ searcher = build_searcher(config, store)
186
+ outcome = find_precedents(searcher, ticket, args.limit, args.only_source, sources)
187
+ return _print_outcome(store, outcome, as_json=args.json)
188
+
189
+
190
+ def _effort(args: argparse.Namespace) -> int:
191
+ config = load_config(args.config)
192
+ store = Store(config.index_path)
193
+ ticket = resolve_ticket(store, args.key, args.source)
194
+ _, sources = config.scope(args.platform, ticket["source"])
195
+ searcher = build_searcher(config, store)
196
+ found = reference_for_ticket(searcher, ticket, args.limit, args.since, sources=sources)
197
+ summary = found.summary()
198
+ print(
199
+ f"[{ticket['source']}] {ticket['key']} {ticket['title']}: {summary['tickets']} tickets "
200
+ f"finished before {found.as_of[:10]}, median {summary['median_hours']} h, "
201
+ f"P25-P75 {summary['p25_hours']}-{summary['p75_hours']} h",
202
+ file=sys.stderr,
203
+ )
204
+ return _print_outcome(store, Outcome(found.hits, found.warning), as_json=args.json)
205
+
206
+
207
+ def _print_outcome(store: Store, outcome: Outcome, as_json: bool) -> int:
208
+ if outcome.warning:
209
+ print(f"warning: {outcome.warning}", file=sys.stderr)
210
+ results = describe(store, outcome.hits)
211
+ if as_json:
212
+ print(json.dumps(results, ensure_ascii=False, indent=2))
213
+ return 0
214
+ for position, result in enumerate(results, start=1):
215
+ spent = f" · {result['time_spent_hours']} h" if result["time_spent_hours"] else ""
216
+ print(f"{position}. [{result['source']}] {result['key']} {result['title']}")
217
+ print(f" {result['status']} {result['resolution']}{spent} · {result['url']}")
218
+ print(f" {result['snippet'][:160]}".replace("\n", " "))
219
+ return 0
220
+
221
+
222
+ def _show(args: argparse.Namespace) -> int:
223
+ config = load_config(args.config)
224
+ details = ticket_details(Store(config.index_path), args.source, args.key)
225
+ if details is None:
226
+ print(f"{args.source} {args.key}: not indexed", file=sys.stderr)
227
+ return 1
228
+ print(json.dumps(details, ensure_ascii=False, indent=2))
229
+ return 0
230
+
231
+
232
+ def _stats(args: argparse.Namespace) -> int:
233
+ config = load_config(args.config)
234
+ print(f"index: {config.index_path}")
235
+ for row in Store(config.index_path).stats():
236
+ platform = config.platform_of(row["source"])
237
+ label = f"{row['source']} [{platform}]" if platform else row["source"]
238
+ print(
239
+ f"{label}: {row['tickets']} tickets, {row['chunks']} chunks, "
240
+ f"updated up to {row['last_updated']}, synced {row['synced_at']}"
241
+ )
242
+ return 0
243
+
244
+
245
+ def _serve(args: argparse.Namespace) -> int:
246
+ from .server import create_server
247
+
248
+ create_server(load_config(args.config)).run()
249
+ return 0
250
+
251
+
252
+ def _eval(args: argparse.Namespace) -> int:
253
+ project = args.project.upper()
254
+ source = f"apache-{project.lower()}"
255
+ variant = "nocomments" if args.no_comments else "comments"
256
+ since = f"-since{args.since}" if args.since else ""
257
+ slug = re.sub(r"[^a-z0-9]+", "-", args.model.lower()).strip("-")
258
+ index = data_dir() / "eval" / f"{source}{since}-{variant}-{slug}.db"
259
+ store = Store(index)
260
+ embedder = build_embedder(
261
+ EmbeddingConfig(
262
+ model=args.model,
263
+ query_prefix=args.query_prefix,
264
+ document_prefix=args.document_prefix,
265
+ )
266
+ )
267
+ if not args.no_sync:
268
+ jql = f"project = {project}" + (f' AND created >= "{args.since}"' if args.since else "")
269
+ print(f"{source}: syncing into {index}", file=sys.stderr)
270
+ sync(
271
+ store,
272
+ embedder,
273
+ JiraConnector(source, APACHE_JIRA, jql, page_size=100, changelog=False),
274
+ source,
275
+ ChunkingConfig(index_comments=not args.no_comments, skip_comment_authors=APACHE_BOTS),
276
+ progress=_progress(source),
277
+ )
278
+ print(file=sys.stderr)
279
+
280
+ queries = duplicate_queries(store, source)[: args.max_queries]
281
+ modes = [mode.strip() for mode in args.modes.split(",") if mode.strip()]
282
+ print(f"{len(queries)} duplicate queries, modes {modes}", file=sys.stderr)
283
+ summaries, details = evaluate(Searcher(store, embedder), queries, modes, source)
284
+ print(f"\n{project} · {variant} · {args.model}\n")
285
+ print(markdown_table(summaries))
286
+ if args.out:
287
+ args.out.write_text(
288
+ json.dumps(
289
+ {
290
+ "project": project,
291
+ "since": args.since,
292
+ "variant": variant,
293
+ "model": args.model,
294
+ "summaries": [asdict(s) for s in summaries],
295
+ "queries": [asdict(d) for d in details],
296
+ },
297
+ indent=2,
298
+ )
299
+ + "\n"
300
+ )
301
+ return 0
302
+
303
+
304
+ MB = 1_000_000
305
+ DEMO_QUERY = "session expires but ephemeral nodes stay around"
306
+ DEMO_PRECEDENTS = "ZOOKEEPER-2376"
307
+
308
+
309
+ def _demo(args: argparse.Namespace) -> int:
310
+ index = ZOOKEEPER
311
+ index_path = data_dir() / "demo" / f"{index.source}-bge-m3.db"
312
+ config_path = config_dir() / "demo.yaml"
313
+ if args.force or not index_path.exists():
314
+ print(
315
+ f"Downloading a ready-made index of {index.tickets:,} public {index.name} "
316
+ f"tickets with their comments ({index.size_mb} MB)",
317
+ file=sys.stderr,
318
+ )
319
+ with httpx.Client(timeout=60) as client:
320
+ download(client, index, index_path, _download_progress)
321
+ print(file=sys.stderr)
322
+ write_config(index, index_path, config_path)
323
+
324
+ config = load_config(config_path)
325
+ store = Store(config.index_path)
326
+ outcome = search_or_degrade(build_searcher(config, store), DEMO_QUERY, "hybrid", 3, Filters())
327
+ print(f'$ tp search "{DEMO_QUERY}"')
328
+ _print_outcome(store, outcome, as_json=False)
329
+ if outcome.warning:
330
+ print(
331
+ "\nFor semantic search start Ollama and pull the model: "
332
+ "https://ollama.com, then `ollama pull bge-m3`.",
333
+ file=sys.stderr,
334
+ )
335
+ print(
336
+ f"""
337
+ The demo configuration is {config_path}. Point tp at it and try:
338
+
339
+ export TICKET_PRECEDENT_CONFIG={config_path}
340
+ tp search "zookeeper won't boot after a crash, log file has zero bytes"
341
+ tp precedents {DEMO_PRECEDENTS}
342
+ tp sync # fetch tickets updated since the index was built
343
+
344
+ Give it to Claude Code (or any MCP client) and ask for precedents in your own words:
345
+
346
+ claude mcp add ticket-precedent-demo -s user -- uvx ticket-precedent --config {config_path} serve
347
+
348
+ Installed with uvx? Use `uvx ticket-precedent` wherever `tp` is written.
349
+ For your own trackers copy config.example.yaml: https://github.com/bondie/ticket-precedent#getting-started"""
350
+ )
351
+ return 0
352
+
353
+
354
+ def _download_progress(received: int, total: int | None) -> None:
355
+ size = f"{received // MB} / {total // MB} MB" if total else f"{received // MB} MB"
356
+ print(f"\r{size}", end="", file=sys.stderr, flush=True)
357
+
358
+
359
+ def _progress(name: str) -> Callable[[SyncStats], None]:
360
+ def report(stats: SyncStats) -> None:
361
+ print(
362
+ f"\r{name}: {stats.tickets} tickets, {stats.embedded} chunks embedded",
363
+ end="",
364
+ file=sys.stderr,
365
+ flush=True,
366
+ )
367
+
368
+ return report
369
+
370
+
371
+ if __name__ == "__main__":
372
+ raise SystemExit(main())