backlog-tiny-mcp 0.34.2__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.
Files changed (97) hide show
  1. backlog_mcp/__init__.py +29 -0
  2. backlog_mcp/__main__.py +10 -0
  3. backlog_mcp/auth.py +199 -0
  4. backlog_mcp/backlog.py +696 -0
  5. backlog_mcp/cli.py +2046 -0
  6. backlog_mcp/client.py +320 -0
  7. backlog_mcp/computer.py +33 -0
  8. backlog_mcp/database.py +80 -0
  9. backlog_mcp/embeddings.py +900 -0
  10. backlog_mcp/global_rules.md +126 -0
  11. backlog_mcp/guidance.py +11 -0
  12. backlog_mcp/guide/index.md +11 -0
  13. backlog_mcp/guide/memory.md +27 -0
  14. backlog_mcp/guide/projects.md +16 -0
  15. backlog_mcp/guide/search.md +72 -0
  16. backlog_mcp/guide/tasks.md +40 -0
  17. backlog_mcp/guide/workflow.md +22 -0
  18. backlog_mcp/httpd.py +270 -0
  19. backlog_mcp/migrate.py +113 -0
  20. backlog_mcp/migrations/0001-initial.sql +194 -0
  21. backlog_mcp/migrations/0002-task-assignment.sql +2 -0
  22. backlog_mcp/migrations/0003-task-edit-claims.sql +5 -0
  23. backlog_mcp/migrations/0004-memory-visibility.sql +42 -0
  24. backlog_mcp/model/CITATION.bib +9 -0
  25. backlog_mcp/model/LICENSE +202 -0
  26. backlog_mcp/model/README.md +12 -0
  27. backlog_mcp/model/UPSTREAM.md +2053 -0
  28. backlog_mcp/model/config.json +12 -0
  29. backlog_mcp/model/model.safetensors +4 -0
  30. backlog_mcp/model/modules.json +14 -0
  31. backlog_mcp/model/provenance.json +16 -0
  32. backlog_mcp/model/tokenizer.json +1 -0
  33. backlog_mcp/models.py +581 -0
  34. backlog_mcp/names.py +35 -0
  35. backlog_mcp/paths.py +53 -0
  36. backlog_mcp/protocol_storage.py +104 -0
  37. backlog_mcp/queries.py +7 -0
  38. backlog_mcp/queries.sql +531 -0
  39. backlog_mcp/records.py +215 -0
  40. backlog_mcp/render.py +479 -0
  41. backlog_mcp/server.py +2864 -0
  42. backlog_mcp/skills/autopilot/SKILL.md +96 -0
  43. backlog_mcp/skills/planning/SKILL.md +106 -0
  44. backlog_mcp/skills/planning/references/splitting.md +45 -0
  45. backlog_mcp/skills/triage/SKILL.md +104 -0
  46. backlog_mcp/skills/triage/references/conventions.md +43 -0
  47. backlog_mcp/skills.py +56 -0
  48. backlog_mcp/static/agent-config.js +20 -0
  49. backlog_mcp/static/app.css +1950 -0
  50. backlog_mcp/static/app.js +1301 -0
  51. backlog_mcp/static/assignments.js +96 -0
  52. backlog_mcp/static/breadcrumbs.js +54 -0
  53. backlog_mcp/static/comment-composer.js +95 -0
  54. backlog_mcp/static/connect.css +98 -0
  55. backlog_mcp/static/connect.html +74 -0
  56. backlog_mcp/static/connect.js +160 -0
  57. backlog_mcp/static/credentials.js +72 -0
  58. backlog_mcp/static/diagrams.js +128 -0
  59. backlog_mcp/static/dom.js +162 -0
  60. backlog_mcp/static/editor-claim.js +104 -0
  61. backlog_mcp/static/editor.js +355 -0
  62. backlog_mcp/static/index.html +137 -0
  63. backlog_mcp/static/markdown.css +33 -0
  64. backlog_mcp/static/markdown.js +72 -0
  65. backlog_mcp/static/mcp.js +177 -0
  66. backlog_mcp/static/memory-append.js +34 -0
  67. backlog_mcp/static/memory-editor.js +173 -0
  68. backlog_mcp/static/memory.js +279 -0
  69. backlog_mcp/static/package.json +1 -0
  70. backlog_mcp/static/project-form.js +71 -0
  71. backlog_mcp/static/project-settings.js +225 -0
  72. backlog_mcp/static/scope.js +90 -0
  73. backlog_mcp/static/statistics.js +87 -0
  74. backlog_mcp/static/task-browser.js +100 -0
  75. backlog_mcp/static/task-pagination.js +94 -0
  76. backlog_mcp/static/task-picker.js +164 -0
  77. backlog_mcp/static/task-table.js +74 -0
  78. backlog_mcp/static/vendor/README.md +12 -0
  79. backlog_mcp/static/vendor/dompurify-LICENSE +202 -0
  80. backlog_mcp/static/vendor/highlight-LICENSE +29 -0
  81. backlog_mcp/static/vendor/highlight-dark.css +118 -0
  82. backlog_mcp/static/vendor/highlight-light.css +118 -0
  83. backlog_mcp/static/vendor/highlight.min.js +1262 -0
  84. backlog_mcp/static/vendor/marked-LICENSE +44 -0
  85. backlog_mcp/static/vendor/marked.esm.js +80 -0
  86. backlog_mcp/static/vendor/marked.esm.js.map +7 -0
  87. backlog_mcp/static/vendor/mermaid-LICENSE +21 -0
  88. backlog_mcp/static/vendor/mermaid.min.js +4376 -0
  89. backlog_mcp/static/vendor/purify.es.mjs +2722 -0
  90. backlog_mcp/static/vendor/purify.es.mjs.map +1 -0
  91. backlog_mcp/transaction.py +47 -0
  92. backlog_mcp/version.py +79 -0
  93. backlog_mcp/webui.py +63 -0
  94. backlog_tiny_mcp-0.34.2.dist-info/METADATA +84 -0
  95. backlog_tiny_mcp-0.34.2.dist-info/RECORD +97 -0
  96. backlog_tiny_mcp-0.34.2.dist-info/WHEEL +4 -0
  97. backlog_tiny_mcp-0.34.2.dist-info/entry_points.txt +4 -0
@@ -0,0 +1,900 @@
1
+ """Offline Model2Vec embeddings and text, vector, or mixed search."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import json
8
+ import logging
9
+ import re
10
+ from collections import deque
11
+ from dataclasses import asdict, dataclass, field
12
+ from hashlib import sha256
13
+ from pathlib import Path
14
+ from threading import Lock
15
+ from typing import TYPE_CHECKING, Annotated, Literal, Self
16
+ from weakref import WeakKeyDictionary
17
+
18
+ import aiosqlite
19
+ import numpy as np
20
+ from aiohttp_tiny_mcp import Extension
21
+ from aiohttp_tiny_mcp.protocol.core import Failure, FailureKind, Rejected
22
+ from aiohttp_tiny_mcp.protocol.models import ResultModel
23
+ from numpy.typing import NDArray
24
+ from pydantic import BaseModel, Field, StringConstraints, model_validator
25
+
26
+ from . import backlog as scope
27
+ from .backlog import Backlog
28
+ from .database import Database
29
+ from .models import Actor, CommentOut, NoteOut, ProjectOut, Status, TaskOut
30
+ from .queries import QUERIES
31
+ from .records import Comment, Note, Project, Task
32
+ from .transaction import Transaction
33
+
34
+ if TYPE_CHECKING:
35
+ from model2vec import StaticModel
36
+
37
+ EXTENSION = "backlog-mcp/model2vec"
38
+ MODEL_NAME = "static-similarity-mrl-multilingual-v1-512-int8"
39
+ MODEL_PATH = Path(__file__).with_name("model")
40
+ DIMENSIONS = 512
41
+ DEFAULT_MIN_SCORE = 0.15
42
+ Text = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=16384)]
43
+
44
+
45
+ class ModelUnavailable(RuntimeError):
46
+ """The bundled model cannot be loaded from disk."""
47
+
48
+
49
+ class Encoder:
50
+ """Load once from a local directory; run inference outside the event loop."""
51
+
52
+ def __init__(self, path: Path = MODEL_PATH) -> None:
53
+ self.path = path.resolve()
54
+ self.model: StaticModel | None = None
55
+ self.lock = Lock()
56
+
57
+ def encode(self, texts: list[str]) -> NDArray[np.float32]:
58
+ with self.lock:
59
+ if self.model is None:
60
+ for name in ("model.safetensors", "config.json", "tokenizer.json"):
61
+ if not (self.path / name).is_file():
62
+ raise ModelUnavailable(f"Bundled model file is missing: {name}")
63
+ from model2vec import StaticModel
64
+
65
+ try:
66
+ self.model = StaticModel.from_pretrained(
67
+ self.path, force_download=False, normalize=True
68
+ )
69
+ except OSError, ValueError:
70
+ raise ModelUnavailable("The bundled Model2Vec model cannot be loaded") from None
71
+ if self.model.dim != DIMENSIONS:
72
+ self.model = None
73
+ raise ModelUnavailable(f"The bundled model must have {DIMENSIONS} dimensions")
74
+ values = np.asarray(
75
+ self.model.encode(texts, max_length=None, use_multiprocessing=False),
76
+ dtype=np.float32,
77
+ )
78
+ norms = np.linalg.norm(values, axis=1, keepdims=True)
79
+ normalized = np.zeros_like(values)
80
+ np.divide(values, norms, out=normalized, where=norms > 0)
81
+ return normalized
82
+
83
+
84
+ encoder = Encoder()
85
+ extension = Extension(
86
+ EXTENSION,
87
+ capabilities={"model": MODEL_NAME, "dimensions": DIMENSIONS, "quantization": "int8"},
88
+ )
89
+
90
+
91
+ class EncodeTexts(BaseModel):
92
+ texts: list[Text] = Field(min_length=1, max_length=128)
93
+
94
+
95
+ class Encoded(ResultModel):
96
+ model: str = MODEL_NAME
97
+ dimensions: int = DIMENSIONS
98
+ embeddings: list[list[float]]
99
+
100
+
101
+ class Search(BaseModel):
102
+ kinds: list[Literal["tasks", "comments", "memory", "projects"]] = Field(
103
+ default=["tasks", "comments", "memory", "projects"],
104
+ min_length=1,
105
+ description="Content to search: projects, tasks, comments, or memory.",
106
+ )
107
+ query: list[Annotated[str, StringConstraints(min_length=1, max_length=16384)]] = Field(
108
+ min_length=1,
109
+ max_length=5,
110
+ description=(
111
+ "1–5 formulations of what to find. "
112
+ "2–5 short rephrasings of the same intent, e.g. in both languages; improves recall. "
113
+ "Quoted expressions search text; unquoted text searches vectors. "
114
+ "Mixed queries use both. See backlog://guide/search for syntax and examples."
115
+ ),
116
+ )
117
+
118
+ @model_validator(mode="after")
119
+ def nonblank_formulations(self) -> Self:
120
+ if any(not text.strip() for text in self.query):
121
+ raise ValueError("Query formulations must not be blank")
122
+ return self
123
+
124
+ project: str | None = Field(
125
+ default=None, description="Defaults to connection project scope; required if unscoped."
126
+ )
127
+ all_projects: bool = Field(default=False, description="Every project of this computer.")
128
+ computer: str | None = Field(
129
+ default=None, description="Every project of the named computer instead."
130
+ )
131
+ all_computers: bool = Field(default=False, description="Every project of every computer.")
132
+ status: list[Status] | None = Field(default=None, description="Task statuses only.")
133
+ tag: str | None = None
134
+ limit: int = Field(default=20, ge=1, le=200, description="Maximum matches per content kind.")
135
+ min_score: float = Field(
136
+ default=DEFAULT_MIN_SCORE,
137
+ ge=-1,
138
+ le=1,
139
+ allow_inf_nan=False,
140
+ description=(
141
+ "Minimum cosine similarity for vector search, default 0.15. "
142
+ "Does not filter full-text matches."
143
+ ),
144
+ )
145
+
146
+
147
+ class TaskHit(TaskOut):
148
+ match: Literal["fts", "semantic"] = Field(description="How this record matched the query.")
149
+ score: float | None = Field(
150
+ default=None,
151
+ description=(
152
+ "Cosine similarity for one formulation, RRF sum for multiple; null for FTS-only hits."
153
+ ),
154
+ )
155
+
156
+
157
+ class NoteHit(NoteOut):
158
+ match: Literal["fts", "semantic"] = Field(description="How this record matched the query.")
159
+ score: float | None = Field(
160
+ default=None,
161
+ description=(
162
+ "Cosine similarity for one formulation, RRF sum for multiple; null for FTS-only hits."
163
+ ),
164
+ )
165
+
166
+
167
+ class CommentHit(CommentOut):
168
+ match: Literal["fts", "semantic"]
169
+ score: float | None = None
170
+ snippet: str | None = None
171
+
172
+
173
+ class ProjectHit(ProjectOut):
174
+ match: Literal["fts", "semantic"]
175
+ score: float | None = None
176
+
177
+
178
+ class Matches(Actor):
179
+ queries: list[str] = Field(default_factory=list)
180
+ model: str = MODEL_NAME
181
+ tasks: list[TaskHit]
182
+ projects: list[ProjectHit]
183
+ memory: list[NoteHit]
184
+ comments: list[CommentHit]
185
+ count: int
186
+ project: str | None
187
+
188
+
189
+ async def encode(texts: list[str]) -> NDArray[np.float32]:
190
+ try:
191
+ return await asyncio.to_thread(encoder.encode, texts)
192
+ except ModelUnavailable as error:
193
+ raise Rejected(Failure(FailureKind.INTERNAL, str(error))) from error
194
+
195
+
196
+ @extension.method("model2vec/encode")
197
+ async def encode_texts(args: EncodeTexts) -> Encoded:
198
+ """Create normalized 512-dimensional embeddings locally, in input order."""
199
+ vectors = await encode(args.texts)
200
+ return Encoded(embeddings=vectors.tolist())
201
+
202
+
203
+ def document(record: Task | Note) -> str:
204
+ return "\n".join((record.title, record.body, " ".join(record.tags)))
205
+
206
+
207
+ @dataclass(slots=True)
208
+ class VectorIndex:
209
+ """Only record IDs and vectors; record contents stay in SQLite."""
210
+
211
+ ids: list[int]
212
+ vectors: NDArray[np.float32]
213
+ digests: dict[int, bytes] = field(default_factory=dict)
214
+
215
+ def search(
216
+ self, query: NDArray[np.float32], allowed: set[int], limit: int, min_score: float
217
+ ) -> list[tuple[int, float]]:
218
+ if not np.any(query):
219
+ return []
220
+ positions = [index for index, record_id in enumerate(self.ids) if record_id in allowed]
221
+ vectors = self.vectors[positions]
222
+ ids = [self.ids[index] for index in positions]
223
+ scores = np.clip(vectors @ query, -1, 1)
224
+ best: dict[int, float] = {}
225
+ for record_id, score, vector in zip(ids, scores, vectors, strict=True):
226
+ if score >= min_score and np.any(vector):
227
+ best[record_id] = max(best.get(record_id, -1.0), float(score))
228
+ return sorted(best.items(), key=lambda item: (-item[1], item[0]))[:limit]
229
+
230
+ def blocks(self) -> dict[int, NDArray[np.float32]]:
231
+ """Return contiguous vector blocks; IDs are sorted when a snapshot is built."""
232
+ if not self.ids:
233
+ return {}
234
+ starts = [
235
+ i for i, record_id in enumerate(self.ids) if not i or self.ids[i - 1] != record_id
236
+ ]
237
+ ends = starts[1:] + [len(self.ids)]
238
+ return {
239
+ self.ids[start]: self.vectors[start:end]
240
+ for start, end in zip(starts, ends, strict=True)
241
+ }
242
+
243
+
244
+ def paragraphs(text: str) -> list[str]:
245
+ """Keep the full document and each distinct paragraph, including short ones."""
246
+ pieces = [part.strip() for part in re.split(r"\n\s*\n", text) if part.strip()]
247
+ return [text] + list(dict.fromkeys(part for part in pieces if part != text.strip()))
248
+
249
+
250
+ type Indexes = tuple[VectorIndex, VectorIndex, VectorIndex, VectorIndex]
251
+
252
+
253
+ @dataclass(frozen=True)
254
+ class Change:
255
+ kind: int
256
+ id: int
257
+ project_id: int
258
+ text: str | None
259
+ passages: tuple[str, ...] = ()
260
+ private_to: str | None = None
261
+
262
+
263
+ def record_passages(record: Task | Note | Comment | Project) -> tuple[str, ...]:
264
+ """Keep the heading separate from body paragraphs and the full document."""
265
+ if isinstance(record, Comment):
266
+ return tuple(paragraphs(record.body))
267
+ if isinstance(record, Project):
268
+ heading = "\n".join((record.full_name, record.name))
269
+ body = record.description
270
+ full = "\n".join((heading, body))
271
+ else:
272
+ heading = "\n".join((record.title, " ".join(record.tags))).strip()
273
+ body = record.body
274
+ full = document(record)
275
+ body_parts = paragraphs(body)
276
+ passages = body_parts[1:] or [body.strip()]
277
+ return tuple(
278
+ dict.fromkeys(
279
+ [full, *[part for part in [heading, *passages] if part and part != full.strip()]]
280
+ )
281
+ )
282
+
283
+
284
+ def change(record: Task | Note | Comment | Project, *, deleted: bool = False) -> Change:
285
+ match record:
286
+ case Task():
287
+ kind, text = 0, document(record)
288
+ case Note():
289
+ kind, text = 1, document(record)
290
+ case Comment():
291
+ kind, text = 2, record.body
292
+ case Project():
293
+ return Change(
294
+ 3,
295
+ record.id,
296
+ record.id,
297
+ None
298
+ if deleted or record.archived
299
+ else "\n".join((record.full_name, record.name, record.description)),
300
+ record_passages(record),
301
+ )
302
+ return Change(
303
+ kind,
304
+ record.id,
305
+ record.project_id,
306
+ None if deleted else text,
307
+ record_passages(record),
308
+ record.created_by.principal
309
+ if isinstance(record, Note) and not record.shared and record.created_by
310
+ else None,
311
+ )
312
+
313
+
314
+ def build_indexes(previous: Indexes | None, changes: list[Change], *, replace: bool) -> Indexes:
315
+ """Build a new snapshot in a worker thread; retain vectors for unchanged texts."""
316
+ indexes = []
317
+ for kind in range(4):
318
+ old = previous[kind] if previous is not None else None
319
+ vectors = old.blocks() if old else {}
320
+ digests = dict(old.digests) if old else {}
321
+ updates = {item.id: item for item in changes if item.kind == kind}
322
+ if not replace and not updates and old is not None:
323
+ indexes.append(old)
324
+ continue
325
+ if replace:
326
+ vectors = {key: value for key, value in vectors.items() if key in updates}
327
+ digests = {key: value for key, value in digests.items() if key in updates}
328
+ texts = {}
329
+ for record_id, item in updates.items():
330
+ text = item.text
331
+ if text is None:
332
+ vectors.pop(record_id, None)
333
+ digests.pop(record_id, None)
334
+ else:
335
+ passages = item.passages or tuple(paragraphs(text))
336
+ digest = sha256(json.dumps(passages).encode()).digest()
337
+ if digests.get(record_id) != digest:
338
+ texts[record_id] = passages
339
+ digests[record_id] = digest
340
+ if texts:
341
+ encoded = encoder.encode([text for chunks in texts.values() for text in chunks])
342
+ offset = 0
343
+ for record_id, chunks in texts.items():
344
+ vectors[record_id] = encoded[offset : offset + len(chunks)]
345
+ offset += len(chunks)
346
+ records = sorted(vectors)
347
+ ids = [record_id for record_id in records for _ in vectors[record_id]]
348
+ matrix = (
349
+ np.concatenate([vectors[key] for key in records])
350
+ if ids
351
+ else np.empty((0, DIMENSIONS), dtype=np.float32)
352
+ )
353
+ indexes.append(VectorIndex(ids, matrix, digests))
354
+ return indexes[0], indexes[1], indexes[2], indexes[3]
355
+
356
+
357
+ async def snapshot(
358
+ backlog: Backlog, connection: aiosqlite.Connection
359
+ ) -> tuple[list[Task], list[Note], list[Comment], list[Project]]:
360
+ from . import server
361
+
362
+ tasks = await server.read_tasks(connection, backlog.actor, status=list(Status), limit=-1)
363
+ notes = await server.read_notes(connection, backlog.actor, limit=-1)
364
+ comments = await server.read_comments(connection, backlog.actor, status=list(Status), limit=-1)
365
+ projects = await scope.read_projects(connection, backlog.actor)
366
+ return tasks, notes, comments, projects
367
+
368
+
369
+ @dataclass
370
+ class IndexState:
371
+ backlog: Backlog
372
+ indexes: Indexes | None = None
373
+
374
+
375
+ @dataclass
376
+ class Indexer:
377
+ connection: aiosqlite.Connection
378
+ transaction: Transaction
379
+ pending: deque[Change | None] = field(default_factory=deque)
380
+ states: dict[str, IndexState] = field(default_factory=dict)
381
+ version: int | None = None
382
+ lock: asyncio.Lock = field(default_factory=asyncio.Lock)
383
+ worker: asyncio.Task[None] | None = None
384
+
385
+ async def refresh(self) -> None:
386
+ async with self.lock:
387
+ batch: list[Change | None] = []
388
+ try:
389
+ async with self.transaction.lock:
390
+ version = await data_version(self.connection)
391
+ states = list(self.states.values())
392
+ if (
393
+ version == self.version
394
+ and not self.pending
395
+ and all(state.indexes is not None for state in states)
396
+ ):
397
+ return
398
+ batch = list(self.pending)
399
+ self.pending.clear()
400
+ replace = version != self.version or None in batch
401
+ snapshots: list[tuple[IndexState, list[Change], bool]] = []
402
+ while True:
403
+ snapshots.clear()
404
+ for state in states:
405
+ full = replace or state.indexes is None
406
+ if full:
407
+ records = await snapshot(state.backlog, self.connection)
408
+ updates = [change(item) for group in records for item in group]
409
+ else:
410
+ updates = []
411
+ allowed = {
412
+ project_id: bool(
413
+ await QUERIES.membership(
414
+ self.connection,
415
+ project_id=project_id,
416
+ principal=state.backlog.principal,
417
+ )
418
+ )
419
+ for project_id in {
420
+ item.project_id for item in batch if item is not None
421
+ }
422
+ }
423
+ for item in batch:
424
+ if item is not None:
425
+ updates.append(
426
+ item
427
+ if allowed[item.project_id]
428
+ and item.private_to in (None, state.backlog.principal)
429
+ else Change(item.kind, item.id, item.project_id, None)
430
+ )
431
+ snapshots.append((state, updates, full))
432
+ after = await data_version(self.connection)
433
+ if after == version:
434
+ break
435
+ # An external commit raced the reads. Take a fresh snapshot.
436
+ version, replace = after, True
437
+ built = [
438
+ (
439
+ state,
440
+ await asyncio.to_thread(
441
+ build_indexes, state.indexes, updates, replace=full
442
+ ),
443
+ )
444
+ for state, updates, full in snapshots
445
+ ]
446
+ # Publish complete snapshots together. Writes during encoding stay queued.
447
+ for state, indexes in built:
448
+ state.indexes = indexes
449
+ self.version = version
450
+ except BaseException:
451
+ self.pending.extendleft(reversed(batch))
452
+ raise
453
+
454
+ async def run(self) -> None:
455
+ while True:
456
+ await asyncio.sleep(1)
457
+ try:
458
+ await self.refresh()
459
+ except Exception:
460
+ logging.getLogger(__name__).exception("Failed to update embeddings; will retry")
461
+
462
+
463
+ indexers: WeakKeyDictionary[Database, Indexer] = WeakKeyDictionary()
464
+
465
+
466
+ def enqueue(
467
+ backlog: Backlog, *records: Task | Note | Comment | Project, deleted: bool = False
468
+ ) -> None:
469
+ """Queue committed records. Before the first search, the initial snapshot covers writes."""
470
+ if indexer := indexers.get(backlog.database):
471
+ indexer.pending.extend(change(record, deleted=deleted) for record in records)
472
+
473
+
474
+ def invalidate(backlog: Backlog) -> None:
475
+ """Access changes or project deletion require a new scoped snapshot."""
476
+ if indexer := indexers.get(backlog.database):
477
+ indexer.pending.append(None)
478
+
479
+
480
+ async def stop(database: Database) -> None:
481
+ if (indexer := indexers.pop(database, None)) and indexer.worker:
482
+ indexer.worker.cancel()
483
+ with contextlib.suppress(asyncio.CancelledError):
484
+ await indexer.worker
485
+
486
+
487
+ async def data_version(connection: aiosqlite.Connection) -> int:
488
+ # Cache invalidation is an inline PRAGMA exception; data queries belong in queries.sql.
489
+ async with connection.execute("PRAGMA data_version") as cursor:
490
+ row = await cursor.fetchone()
491
+ assert row is not None
492
+ return int(row[0])
493
+
494
+
495
+ async def indexes(
496
+ backlog: Backlog, connection: aiosqlite.Connection, transaction: Transaction
497
+ ) -> Indexes:
498
+ """Wait for the first index only; later searches use the last completed snapshot."""
499
+ indexer = indexers.setdefault(backlog.database, Indexer(connection, transaction))
500
+ state = indexer.states.setdefault(backlog.principal, IndexState(backlog))
501
+ if state.indexes is None:
502
+ await indexer.refresh()
503
+ if indexer.worker is None:
504
+ indexer.worker = asyncio.create_task(indexer.run(), name="embeddings-indexer")
505
+ assert state.indexes is not None
506
+ return state.indexes
507
+
508
+
509
+ def match_ids(
510
+ indexes: tuple[VectorIndex, VectorIndex, VectorIndex, VectorIndex],
511
+ args: Search,
512
+ task_ids: set[int],
513
+ note_ids: set[int],
514
+ comment_ids: set[int],
515
+ project_ids: set[int],
516
+ min_score: float,
517
+ ) -> tuple[
518
+ list[tuple[int, float]],
519
+ list[tuple[int, float]],
520
+ list[tuple[int, float]],
521
+ list[tuple[int, float]],
522
+ ]:
523
+ """Rank allowed IDs entirely in a worker thread."""
524
+ formulations = args.query
525
+ encoded = encoder.encode(formulations)
526
+
527
+ def rank(index: VectorIndex, allowed: set[int]) -> list[tuple[int, float]]:
528
+ if len(encoded) == 1:
529
+ return index.search(encoded[0], allowed, args.limit, min_score)
530
+ rankings = [index.search(vector, allowed, len(allowed), min_score) for vector in encoded]
531
+ return reciprocal_rank_fusion(rankings, args.limit)
532
+
533
+ return (
534
+ rank(indexes[0], task_ids),
535
+ rank(indexes[1], note_ids),
536
+ rank(indexes[2], comment_ids),
537
+ rank(indexes[3], project_ids),
538
+ )
539
+
540
+
541
+ def reciprocal_rank_fusion(
542
+ rankings: list[list[tuple[int, float]]], limit: int
543
+ ) -> list[tuple[int, float]]:
544
+ scores: dict[int, float] = {}
545
+ for ranking in rankings:
546
+ for position, (record_id, _) in enumerate(ranking, 1):
547
+ scores[record_id] = scores.get(record_id, 0.0) + 1.0 / (60 + position)
548
+ return sorted(scores.items(), key=lambda item: (-item[1], item[0]))[:limit]
549
+
550
+
551
+ def split_query(query: str) -> tuple[str | None, str | None]:
552
+ """Select text, vector, or mixed search without passing prose to the text parser."""
553
+ if '"' not in query:
554
+ return None, query
555
+ phrases = list(re.finditer(r'"(?:[^"]|"")*"\*?', query))
556
+ remainder = re.sub(r'"(?:[^"]|"")*"\*?', " ", query)
557
+ if '"' in remainder:
558
+ raise ValueError("Invalid FTS5 expression: unterminated quote")
559
+ # Operators and column filters belong to a text expression, not semantic prose.
560
+ syntax = re.sub(r"-?(?:[\w]+|\{[\w\s]+\})\s*:", " ", remainder)
561
+ syntax = re.sub(r",\s*\d+\s*(?=\))", "", syntax)
562
+ syntax = re.sub(r"\b(?:AND|OR|NOT|NEAR)\b|[()^+*\s]", "", syntax)
563
+ if not syntax:
564
+ return query, None
565
+ return " ".join(match.group() for match in phrases), query.replace('"', "")
566
+
567
+
568
+ async def search(
569
+ args: Search, backlog: Backlog, connection: aiosqlite.Connection, transaction: Transaction
570
+ ) -> Matches:
571
+ """Preserve exact text matches before fusing only semantic formulations."""
572
+ modes = [split_query(text.strip()) for text in args.query]
573
+ results: list[Matches] = []
574
+ for text_query, _ in modes:
575
+ if text_query is not None:
576
+ results.append(
577
+ await search_mode(
578
+ args.model_copy(update={"query": [text_query]}),
579
+ backlog,
580
+ connection,
581
+ transaction,
582
+ )
583
+ )
584
+ vector_queries = [text for _, text in modes if text is not None]
585
+ if vector_queries:
586
+ semantic = await search_mode(
587
+ args.model_copy(update={"query": vector_queries}), backlog, connection, transaction
588
+ )
589
+ if len(args.query) > 1 and len(vector_queries) == 1:
590
+
591
+ def rank_scores[T: (TaskHit, NoteHit, CommentHit, ProjectHit)](items: list[T]) -> None:
592
+ for position, item in enumerate(items, 1):
593
+ item.score = 1.0 / (60 + position)
594
+
595
+ rank_scores(semantic.tasks)
596
+ rank_scores(semantic.memory)
597
+ rank_scores(semantic.comments)
598
+ rank_scores(semantic.projects)
599
+ results.append(semantic)
600
+ result = merge_matches(results, args.limit)
601
+ result.queries = args.query
602
+ return result
603
+
604
+
605
+ def merge_matches(results: list[Matches], limit: int) -> Matches:
606
+ result = results[0].model_copy(deep=True)
607
+ for name in ("tasks", "memory", "comments", "projects"):
608
+ items = {item.id: item for item in getattr(result, name)}
609
+ for other in results[1:]:
610
+ for item in getattr(other, name):
611
+ items.setdefault(item.id, item)
612
+ setattr(result, name, list(items.values())[:limit])
613
+ result.count = sum(
614
+ len(getattr(result, name)) for name in ("tasks", "memory", "comments", "projects")
615
+ )
616
+ return result
617
+
618
+
619
+ async def search_mode(
620
+ args: Search, backlog: Backlog, connection: aiosqlite.Connection, transaction: Transaction
621
+ ) -> Matches:
622
+ """Choose text or vector search, then fetch accessible records."""
623
+ from . import server
624
+
625
+ query = args.query[0]
626
+ reach = await backlog.reach(
627
+ args.project,
628
+ all_projects=args.all_projects,
629
+ computer=args.computer,
630
+ all_computers=args.all_computers,
631
+ )
632
+ project_id, computer = reach.project_id, reach.computer
633
+
634
+ def inside(record: Task | Note | Comment) -> bool:
635
+ """True when the record is in the selected project scope."""
636
+ if project_id is not None:
637
+ return record.project_id == project_id or (
638
+ isinstance(record, Note) and record.global_scope
639
+ )
640
+ if computer is not None:
641
+ return True
642
+ return True
643
+
644
+ if '"' in query:
645
+ try:
646
+ lexical_tasks = (
647
+ await server.search_tasks(
648
+ connection,
649
+ backlog.actor,
650
+ query,
651
+ project_id=project_id,
652
+ computer=computer,
653
+ status=args.status,
654
+ tag=args.tag,
655
+ limit=args.limit,
656
+ raw=True,
657
+ )
658
+ if "tasks" in args.kinds
659
+ else []
660
+ )
661
+ lexical_notes = (
662
+ await server.search_notes(
663
+ connection,
664
+ backlog.actor,
665
+ query,
666
+ project_id=project_id,
667
+ computer=computer,
668
+ tag=args.tag,
669
+ limit=args.limit,
670
+ raw=True,
671
+ )
672
+ if "memory" in args.kinds
673
+ else []
674
+ )
675
+ lexical_comments = (
676
+ await server.read_comments(
677
+ connection,
678
+ backlog.actor,
679
+ query=query,
680
+ project_id=project_id,
681
+ computer=computer,
682
+ status=args.status,
683
+ tag=args.tag,
684
+ limit=args.limit,
685
+ raw=True,
686
+ )
687
+ if "comments" in args.kinds
688
+ else []
689
+ )
690
+ lexical_projects = (
691
+ await server.search_projects(
692
+ connection,
693
+ backlog.actor,
694
+ query,
695
+ project_id=project_id,
696
+ computer=computer,
697
+ limit=args.limit,
698
+ raw=True,
699
+ )
700
+ if "projects" in args.kinds
701
+ else []
702
+ )
703
+ except aiosqlite.OperationalError as error:
704
+ if any(token in str(error) for token in ("fts5:", "unterminated", "no such column")):
705
+ raise ValueError(f"Invalid FTS5 expression: {error}") from error
706
+ raise
707
+ exact_tasks = [TaskHit(**asdict(item), match="fts") for item in lexical_tasks]
708
+ exact_notes = [NoteHit(**asdict(item), match="fts") for item in lexical_notes]
709
+ exact_comments = [CommentHit(**asdict(item), match="fts") for item in lexical_comments]
710
+ exact_projects = [
711
+ ProjectHit(
712
+ **server.project_out(
713
+ item, computer=backlog.computer, principal=backlog.principal
714
+ ).model_dump(),
715
+ match="fts",
716
+ )
717
+ for item in lexical_projects
718
+ ]
719
+ return Matches(
720
+ tasks=exact_tasks,
721
+ memory=exact_notes,
722
+ comments=exact_comments,
723
+ projects=exact_projects,
724
+ count=len(exact_tasks) + len(exact_notes) + len(exact_comments) + len(exact_projects),
725
+ project=reach.slug,
726
+ computer=backlog.computer,
727
+ principal=backlog.principal,
728
+ )
729
+ min_score = args.min_score
730
+ vectors = await indexes(backlog, connection, transaction)
731
+ tasks = await server.read_tasks(
732
+ connection,
733
+ backlog.actor,
734
+ project_id=project_id,
735
+ computer=computer,
736
+ status=args.status,
737
+ tag=args.tag,
738
+ limit=-1,
739
+ )
740
+ notes = await server.read_notes(
741
+ connection, backlog.actor, project_id=project_id, computer=computer, tag=args.tag, limit=-1
742
+ )
743
+ tag = args.tag.strip().lower() if args.tag else None
744
+ allowed_tasks = {
745
+ item.id
746
+ for item in tasks
747
+ if inside(item)
748
+ and (not args.status or item.status in args.status)
749
+ and (item.status != Status.DELETED or (args.status and Status.DELETED in args.status))
750
+ and (not tag or tag in item.tags)
751
+ }
752
+ allowed_notes = {item.id for item in notes if inside(item) and (not tag or tag in item.tags)}
753
+ comments = (
754
+ await server.read_comments(
755
+ connection,
756
+ backlog.actor,
757
+ project_id=project_id,
758
+ computer=computer,
759
+ status=args.status,
760
+ tag=args.tag,
761
+ limit=-1,
762
+ )
763
+ if "comments" in args.kinds
764
+ else []
765
+ )
766
+ allowed_comments = {item.id for item in comments}
767
+ if "tasks" not in args.kinds:
768
+ allowed_tasks = set()
769
+ if "memory" not in args.kinds:
770
+ allowed_notes = set()
771
+ del tasks, notes, comments
772
+ projects = (
773
+ await scope.read_projects(connection, backlog.actor, computer=computer)
774
+ if "projects" in args.kinds
775
+ else []
776
+ )
777
+ allowed_projects = {item.id for item in projects if project_id is None or item.id == project_id}
778
+ task_ids, note_ids, comment_ids, project_ids = await asyncio.to_thread(
779
+ match_ids,
780
+ vectors,
781
+ args,
782
+ allowed_tasks,
783
+ allowed_notes,
784
+ allowed_comments,
785
+ allowed_projects,
786
+ min_score,
787
+ )
788
+ task_hits: list[TaskHit] = []
789
+ note_hits: list[NoteHit] = []
790
+ tag = args.tag.strip().lower() if args.tag else None
791
+ task_scores = dict(task_ids)
792
+ note_scores = dict(note_ids)
793
+ ranked_tasks = list(task_scores)[: args.limit]
794
+ ranked_notes = list(note_scores)[: args.limit]
795
+ for record_id in ranked_tasks:
796
+ task = await server.read_task(connection, backlog.actor, record_id)
797
+ if (
798
+ task is None
799
+ or not inside(task)
800
+ or (args.status and task.status not in args.status)
801
+ or (
802
+ task.status == Status.DELETED
803
+ and (not args.status or Status.DELETED not in args.status)
804
+ )
805
+ or (tag and tag not in task.tags)
806
+ ):
807
+ continue
808
+ data = asdict(task)
809
+ data["snippet"] = None
810
+ task_hits.append(
811
+ TaskHit(
812
+ **data,
813
+ match="semantic",
814
+ score=task_scores.get(record_id),
815
+ )
816
+ )
817
+ for record_id in ranked_notes:
818
+ note = await server.read_note(connection, backlog.actor, record_id)
819
+ if note is None or not inside(note):
820
+ continue
821
+ if tag and tag not in note.tags:
822
+ continue
823
+ data = asdict(note)
824
+ data["snippet"] = None
825
+ note_hits.append(
826
+ NoteHit(
827
+ **data,
828
+ match="semantic",
829
+ score=note_scores.get(record_id),
830
+ )
831
+ )
832
+ comment_hits: list[CommentHit] = []
833
+ comment_scores = dict(comment_ids)
834
+ ranked_comments = list(comment_scores)[: args.limit]
835
+ current_comments = (
836
+ {
837
+ item.id: item
838
+ for item in await server.read_comments(
839
+ connection,
840
+ backlog.actor,
841
+ project_id=project_id,
842
+ computer=computer,
843
+ status=args.status,
844
+ tag=args.tag,
845
+ limit=-1,
846
+ )
847
+ }
848
+ if ranked_comments
849
+ else {}
850
+ )
851
+ for record_id in ranked_comments:
852
+ comment = current_comments.get(record_id)
853
+ if comment is None:
854
+ continue
855
+ data = asdict(comment)
856
+ data["snippet"] = comment.body[:200]
857
+ comment_hits.append(
858
+ CommentHit(
859
+ **data,
860
+ match="semantic",
861
+ score=comment_scores.get(record_id),
862
+ )
863
+ )
864
+ from .server import project_out
865
+
866
+ project_hits: list[ProjectHit] = []
867
+ project_scores = dict(project_ids)
868
+ ranked_projects = list(project_scores)[: args.limit]
869
+ for record_id in ranked_projects:
870
+ project = await scope.read_project(connection, backlog.actor, record_id)
871
+ if (
872
+ project is None
873
+ or project.archived
874
+ or (project_id is not None and project.id != project_id)
875
+ ):
876
+ continue
877
+ if computer is not None and not any(root.computer == computer for root in project.roots):
878
+ continue
879
+ project_hits.append(
880
+ ProjectHit(
881
+ **project_out(
882
+ project, computer=backlog.computer, principal=backlog.principal
883
+ ).model_dump(),
884
+ match="semantic",
885
+ score=project_scores.get(record_id),
886
+ )
887
+ )
888
+ return Matches(
889
+ projects=project_hits,
890
+ comments=comment_hits,
891
+ tasks=task_hits,
892
+ memory=note_hits,
893
+ count=len(task_hits) + len(note_hits) + len(comment_hits) + len(project_hits),
894
+ project=reach.slug,
895
+ computer=backlog.computer,
896
+ principal=backlog.principal,
897
+ )
898
+
899
+
900
+ __all__ = ["DIMENSIONS", "EXTENSION", "MODEL_NAME", "MODEL_PATH", "Encoder", "extension"]