backlog-tiny-mcp 0.35.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.
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.35.0.dist-info/METADATA +84 -0
  95. backlog_tiny_mcp-0.35.0.dist-info/RECORD +97 -0
  96. backlog_tiny_mcp-0.35.0.dist-info/WHEEL +4 -0
  97. backlog_tiny_mcp-0.35.0.dist-info/entry_points.txt +4 -0
backlog_mcp/backlog.py ADDED
@@ -0,0 +1,696 @@
1
+ """Scope resolution: which project a call works on when nothing names one."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import os
8
+ import re
9
+ import time
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any, Literal
13
+
14
+ import aiosqlite
15
+
16
+ from .computer import check, hostname
17
+ from .database import Database
18
+ from .models import (
19
+ Actor,
20
+ Origin,
21
+ )
22
+ from .names import owner_name, project_name
23
+ from .queries import QUERIES
24
+ from .records import (
25
+ Project,
26
+ ProjectContents,
27
+ ProjectRoot,
28
+ Unset,
29
+ to_project,
30
+ )
31
+ from .transaction import Transaction
32
+
33
+ log = logging.getLogger(__name__)
34
+
35
+ #: A directory holding one of these is the root of a checkout, and so of a project.
36
+ MARKERS = (".git", ".hg", ".svn", ".jj")
37
+
38
+
39
+ class UnknownProject(LookupError):
40
+ """A project or a computer was named and there is no such thing."""
41
+
42
+
43
+ def slugify(text: str) -> str:
44
+ slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
45
+ return slug or "project"
46
+
47
+
48
+ def checkout_root(path: Path) -> Path:
49
+ """The nearest ancestor that looks like a checkout, else `path` itself."""
50
+ for candidate in (path, *path.parents):
51
+ if any((candidate / marker).exists() for marker in MARKERS):
52
+ return candidate
53
+ return path
54
+
55
+
56
+ @dataclass(frozen=True, slots=True)
57
+ class Reach:
58
+ """What a listing covers: one project, every project of one computer, or every project."""
59
+
60
+ project: Project | None = None
61
+ computer: str | None = None
62
+
63
+ @property
64
+ def project_id(self) -> int | None:
65
+ return self.project.id if self.project else None
66
+
67
+ @property
68
+ def slug(self) -> str | None:
69
+ return self.project.full_name if self.project else None
70
+
71
+ @property
72
+ def scope_computer(self) -> str | None:
73
+ """The named computer the listing covers, absent for a whole logical project."""
74
+ return self.computer
75
+
76
+ @property
77
+ def label(self) -> str:
78
+ """The scope as a phrase, for titles."""
79
+ if self.project:
80
+ return self.project.full_name
81
+ if self.computer:
82
+ return f"every project on {self.computer}"
83
+ return "every project on every computer"
84
+
85
+
86
+ class Backlog:
87
+ """The database and one working directory, as the tools see them.
88
+
89
+ Every handler asks this object which project it is working on. Resolution order:
90
+ the project named on the command line or in the URL, then the deepest registered project of
91
+ this computer containing the working directory, then a project created for it. Nothing else
92
+ chooses: no pin and no remembered choice, so two clients never redirect each other.
93
+ """
94
+
95
+ def __init__(
96
+ self,
97
+ database: Database | Path | str,
98
+ *,
99
+ principal: str = "local",
100
+ cwd: Path | str | None = None,
101
+ project: str | None = None,
102
+ computer: str | None = None,
103
+ ) -> None:
104
+ self.auth_type: Literal["basic", "jwt", "none"] = "none"
105
+ self.database = database if isinstance(database, Database) else Database(Path(database))
106
+ self.principal = principal
107
+ self.cwd = Path(cwd).expanduser().resolve() if cwd else Path.cwd().resolve()
108
+ #: Named by `--project`, and so fixed for the life of the process.
109
+ self.named = project or None
110
+ self.computer = check(computer) if computer else hostname()
111
+ #: True for a view of another computer: its directories are not here, so nothing is
112
+ #: read from the file system and nothing is registered from `cwd`.
113
+ self.remote = False
114
+
115
+ def view(
116
+ self,
117
+ *,
118
+ computer: str | None = None,
119
+ project: str | None = None,
120
+ principal: str | None = None,
121
+ ) -> Backlog:
122
+ """The same database, seen from a computer, with a project fixed when given.
123
+
124
+ One HTTP server answers for several computers: each request gets its own view.
125
+ """
126
+ seen = Backlog(
127
+ self.database,
128
+ principal=principal or self.principal,
129
+ cwd=self.cwd,
130
+ project=project or self.named,
131
+ computer=computer or self.computer,
132
+ )
133
+ seen.auth_type = self.auth_type
134
+ seen.remote = seen.computer != self.computer
135
+ return seen
136
+
137
+ @property
138
+ def actor(self) -> Actor:
139
+ return Actor(principal=self.principal, computer=self.computer)
140
+
141
+ @property
142
+ def transaction(self) -> Transaction:
143
+ assert self.database.transaction is not None, "database is not open"
144
+ return self.database.transaction
145
+
146
+ async def open(self) -> aiosqlite.Connection:
147
+ return await self.database.open(self.principal)
148
+
149
+ async def close(self) -> None:
150
+ await self.database.close()
151
+
152
+ def absolute(self, path: Path | str) -> Path:
153
+ """A path as given, made canonical against the working directory.
154
+
155
+ A path on another computer is only normalized: it must be absolute, and this file system
156
+ knows nothing about it.
157
+ """
158
+ found = Path(path)
159
+ if self.remote:
160
+ if not found.is_absolute():
161
+ raise ValueError(
162
+ f"{str(path)!r} is relative: give an absolute path on {self.computer!r}"
163
+ )
164
+ return Path(os.path.normpath(found))
165
+ found = found.expanduser()
166
+ if not found.is_absolute():
167
+ found = self.cwd / found
168
+ return found.resolve()
169
+
170
+ async def current(self) -> tuple[Project, Origin]:
171
+ """The project the tools work on, and why that one. Raises when there is none."""
172
+ return await self.decide()
173
+
174
+ async def decide(self) -> tuple[Project, Origin]:
175
+ project, origin = await self.choose()
176
+ if project is None:
177
+ raise UnknownProject(
178
+ f"no project chosen on computer {self.computer!r}: pass project=<slug> to the "
179
+ "tool, or add project=<slug> to the URL"
180
+ )
181
+ return project, origin
182
+
183
+ async def choose(self) -> tuple[Project | None, Origin]:
184
+ """The project the tools work on, or `None` with `Origin.NONE` when nothing chose one.
185
+
186
+ Only a view of another computer ends with no project: this computer always has the
187
+ working directory to fall back on.
188
+ """
189
+ connection = await self.open()
190
+ if self.named:
191
+ return await self.lookup(self.named), Origin.ARGUMENT
192
+ if self.remote:
193
+ return None, Origin.NONE
194
+ found = await project_for_path(connection, self.actor, self.cwd, computer=self.computer)
195
+ if found is not None:
196
+ return found, Origin.DIRECTORY
197
+ return await self.create(checkout_root(self.cwd)), Origin.CREATED
198
+
199
+ async def scope(self) -> tuple[Project | None, Origin]:
200
+ """Like `current`, with no project as a state to report, not an error."""
201
+ return await self.choose()
202
+
203
+ async def lookup(self, reference: str) -> Project:
204
+ """Resolve an owner/slug name, unique short slug, #id, or explicit filesystem path."""
205
+ connection = await self.open()
206
+ found = (
207
+ await read_project(connection, self.actor, int(reference[1:]))
208
+ if reference.startswith("#") and reference[1:].isdigit()
209
+ else await project_by_slug(connection, self.actor, reference)
210
+ )
211
+ if found is not None:
212
+ return found
213
+ if reference.startswith((".", "/", "~")):
214
+ path = self.absolute(reference)
215
+ found = await project_by_root(connection, self.actor, path, computer=self.computer)
216
+ if found is None:
217
+ found = await project_for_path(connection, self.actor, path, computer=self.computer)
218
+ if found is not None:
219
+ return found
220
+ raise UnknownProject(
221
+ f"no project {reference!r}: name a registered slug, or a path inside the project"
222
+ )
223
+
224
+ async def resolve(self, reference: str | None) -> Project:
225
+ """The named project, or the current one when nothing is named."""
226
+ if reference:
227
+ return await self.lookup(reference)
228
+ project, _ = await self.current()
229
+ return project
230
+
231
+ async def reach(
232
+ self,
233
+ project: str | None = None,
234
+ *,
235
+ all_projects: bool = False,
236
+ computer: str | None = None,
237
+ all_computers: bool = False,
238
+ ) -> Reach:
239
+ """What a listing covers. A named project narrows a computer scope.
240
+
241
+ `all_computers` covers everything, `computer` every project of that computer,
242
+ `all_projects` every project of this computer, and `project` one project, else the
243
+ current one. A computer nobody registered a project on is `UnknownProject`.
244
+ """
245
+ connection = await self.open()
246
+ if all_computers:
247
+ return Reach()
248
+ if project:
249
+ selected = await self.resolve(project)
250
+ name = check(computer) if computer else None
251
+ if name and not any(root.computer == name for root in selected.roots):
252
+ raise UnknownProject(f"project {selected.slug!r} has no binding on {name!r}")
253
+ return Reach(project=selected, computer=name)
254
+ if computer:
255
+ name = check(computer)
256
+ known = await computers(connection, self.actor)
257
+ if name not in known and name != self.computer:
258
+ raise UnknownProject(
259
+ f"no computer {name!r}: known computers are {', '.join(known) or 'none'}"
260
+ )
261
+ return Reach(computer=name)
262
+ if all_projects:
263
+ return Reach(computer=self.computer)
264
+ return Reach(project=await self.resolve(project))
265
+
266
+ async def free_slug(self, wanted: str) -> str:
267
+ connection = await self.open()
268
+ taken = set(await slugs(connection, self.actor, owned=True))
269
+ if wanted not in taken:
270
+ return wanted
271
+ for suffix in range(2, len(taken) + 3):
272
+ candidate = f"{wanted}-{suffix}"
273
+ if candidate not in taken:
274
+ return candidate
275
+ raise AssertionError("every candidate slug was taken")
276
+
277
+ async def create(
278
+ self, root: Path | str, *, name: str | None = None, description: str = ""
279
+ ) -> Project:
280
+ """Register a directory of this computer as a project, or return the project it has.
281
+
282
+ The directory must exist. A view of another computer cannot check that and takes the
283
+ path as given.
284
+ """
285
+ from .embeddings import enqueue
286
+
287
+ connection = await self.open()
288
+ if str(root) == "":
289
+ label = name or "project"
290
+ slug = await self.free_slug(slugify(label))
291
+ async with self.transaction:
292
+ created = await add_project(
293
+ connection,
294
+ self.actor,
295
+ slug=slug,
296
+ name=label,
297
+ root="",
298
+ computer=self.computer,
299
+ description=description,
300
+ )
301
+ enqueue(self, created)
302
+ return created
303
+ path = self.absolute(root)
304
+ existing = await project_by_root(connection, self.actor, path, computer=self.computer)
305
+ if existing is not None:
306
+ return existing
307
+ if not self.remote and not path.is_dir():
308
+ raise ValueError(f"no such directory on {self.computer!r}: {path}")
309
+ label = name or path.name or "project"
310
+ slug = await self.free_slug(slugify(label))
311
+ async with self.transaction:
312
+ created = await add_project(
313
+ connection,
314
+ self.actor,
315
+ slug=slug,
316
+ name=label,
317
+ root=path,
318
+ computer=self.computer,
319
+ description=description,
320
+ )
321
+ enqueue(self, created)
322
+ log.info("registered project %s at %s on %s", created.slug, path, self.computer)
323
+ return created
324
+
325
+ async def save(
326
+ self,
327
+ connection: aiosqlite.Connection,
328
+ transaction: Transaction,
329
+ *,
330
+ reference: str | None = None,
331
+ root: Path | str | None = None,
332
+ name: str | None = None,
333
+ description: str | None = None,
334
+ archived: bool | None = None,
335
+ preferred_language: str | None | Unset = Unset.VALUE,
336
+ ) -> Project:
337
+ """Register a project, or update the one named. Defaults to the working directory."""
338
+ from .embeddings import enqueue
339
+
340
+ match reference, root:
341
+ case None | "", None:
342
+ if self.remote:
343
+ raise ValueError(
344
+ f"on computer {self.computer!r} name the project, or give its root"
345
+ )
346
+ #: Nothing named: the working directory, registered if it is new.
347
+ path = self.absolute(self.cwd)
348
+ found = await project_by_root(connection, self.actor, path, computer=self.computer)
349
+ project = found if found is not None else await self.create(checkout_root(path))
350
+ case None | "", (str() | Path()) as directory:
351
+ project = await self.create(directory, name=name, description=description or "")
352
+ case str() as named, (str() | Path()) as directory:
353
+ project = await self.lookup(named)
354
+ root_text = str(directory)
355
+ if root_text:
356
+ path = self.absolute(directory)
357
+ if not self.remote and not path.is_dir():
358
+ raise ValueError(f"no such directory on {self.computer!r}: {path}")
359
+ async with transaction:
360
+ project = await add_root(
361
+ connection, self.actor, project.id, computer=self.computer, root=path
362
+ )
363
+ else:
364
+ async with transaction:
365
+ project = await add_root(
366
+ connection, self.actor, project.id, computer=self.computer, root=""
367
+ )
368
+ case str() as named, None:
369
+ project = await self.lookup(named)
370
+ async with transaction:
371
+ updated = await update_project(
372
+ connection,
373
+ self.actor,
374
+ project.id,
375
+ name=name,
376
+ description=description,
377
+ archived=archived,
378
+ preferred_language=preferred_language,
379
+ )
380
+ assert updated is not None, "the project just updated is gone"
381
+ enqueue(self, updated)
382
+ return updated
383
+
384
+ async def delete(
385
+ self, project: Project, connection: aiosqlite.Connection, transaction: Transaction
386
+ ) -> ProjectContents:
387
+ """Delete a project for good: its roots, tasks and notes.
388
+
389
+ The project fixed for this process by `--project` or the URL stays, because every later
390
+ call would fail to find it.
391
+ """
392
+ if self.named and (await self.lookup(self.named)).id == project.id:
393
+ raise ValueError(
394
+ f"project {project.slug!r} is fixed for this client; delete it from another one"
395
+ )
396
+ from .embeddings import invalidate
397
+
398
+ contents = await project_contents(connection, self.actor, project.id)
399
+ async with transaction:
400
+ await delete_project(connection, self.actor, project.id)
401
+ invalidate(self)
402
+ log.info(
403
+ "deleted project %s with %d tasks and %d notes",
404
+ project.slug,
405
+ contents.tasks,
406
+ contents.notes,
407
+ )
408
+ return contents
409
+
410
+
411
+ __all__ = ["MARKERS", "Backlog", "Reach", "UnknownProject", "checkout_root", "slugify"]
412
+
413
+
414
+ async def register(
415
+ connection: aiosqlite.Connection, actor: Actor, identity: str, name: str
416
+ ) -> None:
417
+
418
+ await QUERIES.register_principal(
419
+ connection, identity=identity, handle=owner_name(identity), name=name
420
+ )
421
+
422
+
423
+ async def require(
424
+ connection: aiosqlite.Connection, actor: Actor, project_id: int, *, role: str = "reader"
425
+ ) -> str:
426
+ row = await QUERIES.membership(connection, project_id=project_id, principal=actor.principal)
427
+ if row is None:
428
+ raise LookupError(f"no project #{project_id}")
429
+ actual = str(row["role"])
430
+ if role == "owner" and actual != "owner" or role == "editor" and actual == "reader":
431
+ raise PermissionError(f"project #{project_id} requires {role} access")
432
+ return actual
433
+
434
+
435
+ async def members(
436
+ connection: aiosqlite.Connection, actor: Actor, project_id: int
437
+ ) -> list[dict[str, str]]:
438
+ await require(connection, actor, project_id)
439
+ return [dict(row) async for row in QUERIES.members(connection, project_id=project_id)]
440
+
441
+
442
+ async def share(
443
+ connection: aiosqlite.Connection, actor: Actor, project_id: int, principal: str, role: str
444
+ ) -> None:
445
+ await require(connection, actor, project_id, role="owner")
446
+ if role not in {"reader", "editor"}:
447
+ raise ValueError("membership role must be reader or editor")
448
+
449
+ if await QUERIES.principal(connection, identity=principal) is None:
450
+ raise LookupError("unknown principal; use a registered authentication identity")
451
+ current = await QUERIES.membership(connection, project_id=project_id, principal=principal)
452
+ if current and current["role"] == "owner":
453
+ raise ValueError("the project owner cannot be changed")
454
+ await QUERIES.save_member(connection, project_id=project_id, principal=principal, role=role)
455
+
456
+
457
+ async def attach_roots(
458
+ connection: aiosqlite.Connection, actor: Actor, projects: list[Project]
459
+ ) -> list[Project]:
460
+ if not projects:
461
+ return projects
462
+ rows = QUERIES.project_roots(
463
+ connection, ids=json.dumps([p.id for p in projects]), principal=actor.principal
464
+ )
465
+ by_id: dict[int, list[ProjectRoot]] = {project.id: [] for project in projects}
466
+ async for row in rows:
467
+ by_id[row["project_id"]].append(ProjectRoot(row["computer"], row["root"]))
468
+ for project in projects:
469
+ project.roots = by_id[project.id]
470
+ project.role = await require(connection, actor, project.id)
471
+ return projects
472
+
473
+
474
+ async def roots(
475
+ connection: aiosqlite.Connection, actor: Actor, project_id: int
476
+ ) -> list[ProjectRoot]:
477
+ project = await read_project(connection, actor, project_id)
478
+ return project.roots if project else []
479
+
480
+
481
+ async def read_project(
482
+ connection: aiosqlite.Connection, actor: Actor, project_id: int
483
+ ) -> Project | None:
484
+ row = await QUERIES.project(connection, project_id=project_id, principal=actor.principal)
485
+ return (await attach_roots(connection, actor, [to_project(row)]))[0] if row else None
486
+
487
+
488
+ async def project_by_slug(
489
+ connection: aiosqlite.Connection, actor: Actor, slug: str
490
+ ) -> Project | None:
491
+ handle, local_slug = slug.split("/", 1) if "/" in slug else (None, slug)
492
+ rows = [
493
+ row
494
+ async for row in QUERIES.project_by_slug(
495
+ connection, handle=handle, slug=local_slug, principal=actor.principal
496
+ )
497
+ ]
498
+ if len(rows) > 1:
499
+ references = ", ".join(project_name(row["owner"], row["slug"]) for row in rows)
500
+ raise ValueError(f"ambiguous project {slug!r}; use its full name: {references}")
501
+ return (await attach_roots(connection, actor, [to_project(rows[0])]))[0] if rows else None
502
+
503
+
504
+ async def project_by_root(
505
+ connection: aiosqlite.Connection, actor: Actor, root: Path | str, *, computer: str
506
+ ) -> Project | None:
507
+ row = await QUERIES.project_by_root(
508
+ connection, computer=computer, root=str(root), principal=actor.principal
509
+ )
510
+ return (await attach_roots(connection, actor, [to_project(row)]))[0] if row else None
511
+
512
+
513
+ async def project_for_path(
514
+ connection: aiosqlite.Connection, actor: Actor, path: Path, *, computer: str
515
+ ) -> Project | None:
516
+ candidates = [str(path), *(str(parent) for parent in path.parents)]
517
+ rows = QUERIES.projects_for_paths(
518
+ connection,
519
+ computer=computer,
520
+ paths=json.dumps(candidates),
521
+ principal=actor.principal,
522
+ )
523
+ found = await attach_roots(connection, actor, [to_project(row) async for row in rows])
524
+ return (
525
+ max(
526
+ found,
527
+ key=lambda item: max(
528
+ len(root.root) for root in item.roots if root.computer == computer
529
+ ),
530
+ )
531
+ if found
532
+ else None
533
+ )
534
+
535
+
536
+ async def read_projects(
537
+ connection: aiosqlite.Connection,
538
+ actor: Actor,
539
+ *,
540
+ archived: bool = False,
541
+ computer: str | None = None,
542
+ ) -> list[Project]:
543
+ rows = QUERIES.projects(
544
+ connection, archived=archived, computer=computer, principal=actor.principal
545
+ )
546
+ return await attach_roots(connection, actor, [to_project(row) async for row in rows])
547
+
548
+
549
+ async def computers(connection: aiosqlite.Connection, actor: Actor) -> list[str]:
550
+ return [
551
+ row["computer"] async for row in QUERIES.computers(connection, principal=actor.principal)
552
+ ]
553
+
554
+
555
+ async def slugs(
556
+ connection: aiosqlite.Connection, actor: Actor, *, owned: bool = False
557
+ ) -> list[str]:
558
+ if owned:
559
+ return [
560
+ row["slug"] async for row in QUERIES.owned_slugs(connection, principal=actor.principal)
561
+ ]
562
+ return sorted(
563
+ project.full_name for project in await read_projects(connection, actor, archived=True)
564
+ )
565
+
566
+
567
+ async def add_project(
568
+ connection: aiosqlite.Connection,
569
+ actor: Actor,
570
+ *,
571
+ slug: str,
572
+ name: str,
573
+ root: Path | str,
574
+ computer: str,
575
+ description: str = "",
576
+ preferred_language: str | None = None,
577
+ ) -> Project:
578
+
579
+ now = time.time()
580
+ inserted_id = await QUERIES.add_project(
581
+ connection,
582
+ slug=slug,
583
+ name=name,
584
+ description=description,
585
+ preferred_language=preferred_language,
586
+ created_at=now,
587
+ updated_at=now,
588
+ owner=actor.principal,
589
+ created_principal=actor.principal,
590
+ created_computer=actor.computer or hostname(),
591
+ updated_principal=actor.principal,
592
+ updated_computer=actor.computer or hostname(),
593
+ )
594
+ await QUERIES.save_member(
595
+ connection, project_id=inserted_id, principal=actor.principal, role="owner"
596
+ )
597
+ await QUERIES.add_root(
598
+ connection,
599
+ project_id=inserted_id,
600
+ principal=actor.principal,
601
+ computer=computer,
602
+ root=str(root),
603
+ )
604
+ created = await read_project(connection, actor, inserted_id or 0)
605
+ assert created is not None, "the project just written is not there"
606
+ return created
607
+
608
+
609
+ async def add_root(
610
+ connection: aiosqlite.Connection,
611
+ actor: Actor,
612
+ project_id: int,
613
+ *,
614
+ computer: str,
615
+ root: Path | str,
616
+ ) -> Project:
617
+ """Bind a project to one location; non-empty paths belong to only one project."""
618
+ await require(connection, actor, project_id)
619
+
620
+ existing = await QUERIES.existing_root(
621
+ connection,
622
+ project_id=project_id,
623
+ principal=actor.principal,
624
+ computer=computer,
625
+ root=str(root),
626
+ )
627
+ if existing is not None:
628
+ project = await read_project(connection, actor, project_id)
629
+ assert project is not None
630
+ return project
631
+ try:
632
+ await QUERIES.add_root(
633
+ connection,
634
+ project_id=project_id,
635
+ principal=actor.principal,
636
+ computer=computer,
637
+ root=str(root),
638
+ )
639
+ except aiosqlite.IntegrityError as error:
640
+ raise ValueError(f"path {root!s} on {computer!r} is already registered") from error
641
+ project = await read_project(connection, actor, project_id)
642
+ assert project is not None, "the project just updated is gone"
643
+ return project
644
+
645
+
646
+ async def project_contents(
647
+ connection: aiosqlite.Connection, actor: Actor, project_id: int
648
+ ) -> ProjectContents:
649
+ await require(connection, actor, project_id)
650
+ row = await QUERIES.project_contents(connection, project_id=project_id)
651
+ assert row is not None
652
+ return ProjectContents(row["tasks"], row["notes"], row["shared_notes"])
653
+
654
+
655
+ async def delete_project(connection: aiosqlite.Connection, actor: Actor, project_id: int) -> bool:
656
+
657
+ if await read_project(connection, actor, project_id) is None:
658
+ return False
659
+ await require(connection, actor, project_id, role="owner")
660
+ await QUERIES.delete_project_tasks(connection, project_id=project_id)
661
+ await QUERIES.delete_project_notes(connection, project_id=project_id)
662
+ await QUERIES.delete_project_project_roots(connection, project_id=project_id)
663
+ removed = await QUERIES.delete_project(connection, project_id=project_id)
664
+ return bool(removed)
665
+
666
+
667
+ async def update_project(
668
+ connection: aiosqlite.Connection,
669
+ actor: Actor,
670
+ project_id: int,
671
+ *,
672
+ name: str | None = None,
673
+ description: str | None = None,
674
+ archived: bool | None = None,
675
+ slug: str | None = None,
676
+ preferred_language: str | None | Unset = Unset.VALUE,
677
+ ) -> Project | None:
678
+ changes: dict[str, Any] = {}
679
+ if name is not None:
680
+ changes["name"] = name
681
+ if description is not None:
682
+ changes["description"] = description
683
+ if archived is not None:
684
+ changes["archived"] = int(archived)
685
+ if slug is not None:
686
+ changes["slug"] = slug
687
+ if preferred_language is not Unset.VALUE:
688
+ changes["preferred_language"] = preferred_language
689
+ if changes:
690
+ await require(connection, actor, project_id, role="editor")
691
+ changes["updated_principal"] = actor.principal
692
+ changes["updated_computer"] = actor.computer or hostname()
693
+ changes["updated_at"] = time.time()
694
+
695
+ await QUERIES.update_project(connection, project_id=project_id, changes=json.dumps(changes))
696
+ return await read_project(connection, actor, project_id)