lore-agent-task-manager 0.1.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. lore/__init__.py +5 -0
  2. lore/__main__.py +5 -0
  3. lore/artifact.py +50 -0
  4. lore/cli.py +2786 -0
  5. lore/codex.py +316 -0
  6. lore/db.py +1320 -0
  7. lore/defaults/GETTING-STARTED.md +38 -0
  8. lore/defaults/LORE-AGENT.md +32 -0
  9. lore/defaults/artifacts/codex/CODEX.md +143 -0
  10. lore/defaults/artifacts/codex/conceptual/entities/task.md +51 -0
  11. lore/defaults/artifacts/codex/conceptual/entities/user.md +47 -0
  12. lore/defaults/artifacts/codex/conceptual/relationships/user--task.md +58 -0
  13. lore/defaults/artifacts/codex/conceptual/workflows/complete-task.md +47 -0
  14. lore/defaults/artifacts/codex/conceptual/workflows/create-and-assign-entity.md +68 -0
  15. lore/defaults/artifacts/codex/constraints/constraints.md +59 -0
  16. lore/defaults/artifacts/codex/decisions/001-sqlite-storage.md +64 -0
  17. lore/defaults/artifacts/codex/decisions/adr-no-default-content-tests.md +33 -0
  18. lore/defaults/artifacts/codex/glossary/glossary.md +40 -0
  19. lore/defaults/artifacts/codex/integrations/integrations.md +47 -0
  20. lore/defaults/artifacts/codex/operations/deployment/development.md +105 -0
  21. lore/defaults/artifacts/codex/operations/deployment/overview.md +57 -0
  22. lore/defaults/artifacts/codex/operations/deployment/production.md +88 -0
  23. lore/defaults/artifacts/codex/operations/deployment/staging.md +57 -0
  24. lore/defaults/artifacts/codex/operations/git.md +95 -0
  25. lore/defaults/artifacts/codex/operations/runbooks/runbook-template.md +75 -0
  26. lore/defaults/artifacts/codex/personas/persona.md +48 -0
  27. lore/defaults/artifacts/codex/security/security-model.md +62 -0
  28. lore/defaults/artifacts/codex/standards/code-conventions.md +61 -0
  29. lore/defaults/artifacts/codex/standards/design-principles.md +67 -0
  30. lore/defaults/artifacts/codex/standards/testing.md +71 -0
  31. lore/defaults/artifacts/codex/technical/backend/api/tasks.md +81 -0
  32. lore/defaults/artifacts/codex/technical/backend/overview.md +58 -0
  33. lore/defaults/artifacts/codex/technical/database/overview.md +45 -0
  34. lore/defaults/artifacts/codex/technical/database/schemas/tasks.md +49 -0
  35. lore/defaults/artifacts/codex/technical/database/schemas/users.md +38 -0
  36. lore/defaults/artifacts/codex/technical/frontend/overview.md +41 -0
  37. lore/defaults/artifacts/codex/technical/overview.md +59 -0
  38. lore/defaults/artifacts/feature-implementation/codex-change-proposal.md +91 -0
  39. lore/defaults/artifacts/feature-implementation/context-map.md +44 -0
  40. lore/defaults/artifacts/feature-implementation/crazy-prd.md +88 -0
  41. lore/defaults/artifacts/feature-implementation/crazy-tech-spec.md +79 -0
  42. lore/defaults/artifacts/feature-implementation/prd-draft.md +128 -0
  43. lore/defaults/artifacts/feature-implementation/prd.md +125 -0
  44. lore/defaults/artifacts/feature-implementation/tech-spec-draft.md +134 -0
  45. lore/defaults/artifacts/feature-implementation/tech-spec.md +138 -0
  46. lore/defaults/artifacts/feature-implementation/user-story-index.md +59 -0
  47. lore/defaults/artifacts/feature-implementation/user-story.md +126 -0
  48. lore/defaults/doctrines/feature-implementation/feature-implementation.yaml +387 -0
  49. lore/defaults/doctrines/feature-implementation/quick-feature-implementation.yaml +206 -0
  50. lore/defaults/doctrines/feature-implementation/tdd-implementation.yaml +51 -0
  51. lore/defaults/doctrines/update-changelog.yaml +24 -0
  52. lore/defaults/gitignore +20 -0
  53. lore/defaults/knights/changelog-scribe.md +105 -0
  54. lore/defaults/knights/feature-implementation/architect.md +65 -0
  55. lore/defaults/knights/feature-implementation/ba.md +73 -0
  56. lore/defaults/knights/feature-implementation/crazy-architect.md +41 -0
  57. lore/defaults/knights/feature-implementation/crazy-pm.md +39 -0
  58. lore/defaults/knights/feature-implementation/pm.md +61 -0
  59. lore/defaults/knights/feature-implementation/scout.md +67 -0
  60. lore/defaults/knights/feature-implementation/tdd-green.md +32 -0
  61. lore/defaults/knights/feature-implementation/tdd-red.md +31 -0
  62. lore/defaults/knights/feature-implementation/tdd-refactor.md +40 -0
  63. lore/defaults/knights/feature-implementation/tech-lead.md +73 -0
  64. lore/defaults/knights/feature-implementation/tech-writer.md +68 -0
  65. lore/defaults/schema.sql +60 -0
  66. lore/defaults/skills/explore-codex/SKILL.md +60 -0
  67. lore/defaults/skills/new-artifact/SKILL.md +73 -0
  68. lore/defaults/skills/new-doctrine/SKILL.md +79 -0
  69. lore/defaults/skills/new-knight/SKILL.md +72 -0
  70. lore/defaults/skills/new-watcher/SKILL.md +45 -0
  71. lore/defaults/skills/start-quest/SKILL.md +100 -0
  72. lore/defaults/watchers/change-log-updates.yaml +16 -0
  73. lore/doctrine.py +271 -0
  74. lore/frontmatter.py +96 -0
  75. lore/graph.py +73 -0
  76. lore/ids.py +16 -0
  77. lore/init.py +137 -0
  78. lore/knight.py +97 -0
  79. lore/migrations/__init__.py +1 -0
  80. lore/migrations/v1_to_v2.py +10 -0
  81. lore/migrations/v2_to_v3.py +24 -0
  82. lore/migrations/v3_to_v4.py +19 -0
  83. lore/migrations/v4_to_v5.py +41 -0
  84. lore/migrations/v5_to_v6.py +18 -0
  85. lore/models.py +323 -0
  86. lore/oracle.py +204 -0
  87. lore/paths.py +56 -0
  88. lore/priority.py +36 -0
  89. lore/py.typed +0 -0
  90. lore/root.py +27 -0
  91. lore/validators.py +149 -0
  92. lore/watcher.py +158 -0
  93. lore_agent_task_manager-0.1.0.dist-info/METADATA +194 -0
  94. lore_agent_task_manager-0.1.0.dist-info/RECORD +97 -0
  95. lore_agent_task_manager-0.1.0.dist-info/WHEEL +4 -0
  96. lore_agent_task_manager-0.1.0.dist-info/entry_points.txt +2 -0
  97. lore_agent_task_manager-0.1.0.dist-info/licenses/LICENSE +21 -0
lore/db.py ADDED
@@ -0,0 +1,1320 @@
1
+ """SQLite schema and operations."""
2
+
3
+ import importlib
4
+ import sqlite3
5
+ from datetime import datetime, timezone
6
+ from importlib import resources
7
+ from pathlib import Path
8
+
9
+ from lore import paths
10
+ from lore import validators
11
+ from lore.ids import generate_id
12
+
13
+ SCHEMA_VERSION = 6
14
+
15
+
16
+ def get_schema_sql() -> str:
17
+ """Read the DDL from the bundled schema.sql file."""
18
+ return resources.files("lore.defaults").joinpath("schema.sql").read_text()
19
+
20
+
21
+ def init_database(db_path: Path) -> str:
22
+ """Initialize the SQLite database with the full schema.
23
+
24
+ Returns a status string: 'created', 'existing', or 'reinitialized'.
25
+ """
26
+ db_existed = db_path.exists()
27
+
28
+ if db_existed:
29
+ # Check if lore_meta table exists (corruption check)
30
+ conn = sqlite3.connect(str(db_path))
31
+ try:
32
+ cursor = conn.execute(
33
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='lore_meta'"
34
+ )
35
+ has_meta = cursor.fetchone() is not None
36
+ finally:
37
+ conn.close()
38
+
39
+ if has_meta:
40
+ return "existing"
41
+
42
+ # Corrupted: lore_meta missing — reinitialize from scratch
43
+ db_path.unlink()
44
+ _create_database(db_path)
45
+ return "reinitialized"
46
+
47
+ _create_database(db_path)
48
+ return "created"
49
+
50
+
51
+ def _create_database(db_path: Path) -> None:
52
+ """Create a fresh database with the full schema."""
53
+ conn = sqlite3.connect(str(db_path))
54
+ try:
55
+ conn.executescript(get_schema_sql())
56
+ finally:
57
+ conn.close()
58
+
59
+
60
+ def get_connection(project_root: Path) -> sqlite3.Connection:
61
+ """Open a connection to the project database with standard pragmas.
62
+
63
+ Checks schema version and runs any pending migrations before returning.
64
+ """
65
+ db_path = paths.db_path(project_root)
66
+ conn = sqlite3.connect(str(db_path))
67
+ conn.execute("PRAGMA journal_mode = WAL")
68
+ conn.execute("PRAGMA busy_timeout = 5000")
69
+ conn.execute("PRAGMA foreign_keys = ON")
70
+ conn.row_factory = sqlite3.Row
71
+ _run_migrations(conn)
72
+ return conn
73
+
74
+
75
+ def _run_migrations(conn: sqlite3.Connection) -> None:
76
+ """Check schema version and run pending migrations sequentially."""
77
+ cursor = conn.execute(
78
+ "SELECT value FROM lore_meta WHERE key = 'schema_version'"
79
+ )
80
+ row = cursor.fetchone()
81
+ if row is None:
82
+ raise RuntimeError("Missing schema_version in lore_meta")
83
+ current = int(row[0])
84
+
85
+ if current == SCHEMA_VERSION:
86
+ return
87
+
88
+ if current > SCHEMA_VERSION:
89
+ raise RuntimeError(
90
+ f"Database schema version {current} is newer than "
91
+ f"supported version {SCHEMA_VERSION}. Upgrade Lore."
92
+ )
93
+
94
+ # Run migrations sequentially from current to SCHEMA_VERSION
95
+ conn.execute("BEGIN IMMEDIATE")
96
+ try:
97
+ # Re-check version after acquiring lock (another connection may have migrated)
98
+ cursor = conn.execute(
99
+ "SELECT value FROM lore_meta WHERE key = 'schema_version'"
100
+ )
101
+ row = cursor.fetchone()
102
+ current = int(row[0])
103
+ if current >= SCHEMA_VERSION:
104
+ conn.rollback()
105
+ return
106
+
107
+ for from_ver in range(current, SCHEMA_VERSION):
108
+ to_ver = from_ver + 1
109
+ module_name = f"lore.migrations.v{from_ver}_to_v{to_ver}"
110
+ try:
111
+ mod = importlib.import_module(module_name)
112
+ except ImportError:
113
+ raise RuntimeError(
114
+ f"Migration module {module_name} not found"
115
+ )
116
+ if not hasattr(mod, "migrate"):
117
+ raise RuntimeError(
118
+ f"Migration module {module_name} has no migrate() function"
119
+ )
120
+ mod.migrate(conn)
121
+ conn.execute(
122
+ "UPDATE lore_meta SET value = ? WHERE key = 'schema_version'",
123
+ (str(to_ver),),
124
+ )
125
+ conn.commit()
126
+ except Exception:
127
+ conn.rollback()
128
+ raise
129
+
130
+
131
+ def _now_utc() -> str:
132
+ """Return current UTC time as ISO 8601 string with Z suffix."""
133
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
134
+
135
+
136
+ def list_quests(project_root: Path, include_closed: bool = False) -> list[sqlite3.Row]:
137
+ """List quests sorted by priority asc, then created_at asc."""
138
+ conn = get_connection(project_root)
139
+ try:
140
+ if include_closed:
141
+ cursor = conn.execute(
142
+ "SELECT * FROM quests WHERE deleted_at IS NULL ORDER BY priority ASC, created_at ASC"
143
+ )
144
+ else:
145
+ cursor = conn.execute(
146
+ "SELECT * FROM quests WHERE status != 'closed' AND deleted_at IS NULL "
147
+ "ORDER BY priority ASC, created_at ASC"
148
+ )
149
+ return cursor.fetchall()
150
+ finally:
151
+ conn.close()
152
+
153
+
154
+ def get_quest(project_root: Path, quest_id: str) -> sqlite3.Row | None:
155
+ """Fetch a single quest by ID (excludes soft-deleted)."""
156
+ conn = get_connection(project_root)
157
+ try:
158
+ cursor = conn.execute(
159
+ "SELECT * FROM quests WHERE id = ? AND deleted_at IS NULL",
160
+ (quest_id,),
161
+ )
162
+ return cursor.fetchone()
163
+ finally:
164
+ conn.close()
165
+
166
+
167
+ def get_deleted_at(project_root: Path, entity_id: str) -> str | None:
168
+ """Return the deleted_at timestamp if the entity is soft-deleted, else None.
169
+
170
+ Determines the table from the ID format: 'q-xxxx' for quests,
171
+ anything containing 'm-' for missions.
172
+ """
173
+ table = "quests" if entity_id.startswith("q-") and "/" not in entity_id else "missions"
174
+ conn = get_connection(project_root)
175
+ try:
176
+ cursor = conn.execute(
177
+ f"SELECT deleted_at FROM {table} WHERE id = ? AND deleted_at IS NOT NULL",
178
+ (entity_id,),
179
+ )
180
+ row = cursor.fetchone()
181
+ return row["deleted_at"] if row else None
182
+ finally:
183
+ conn.close()
184
+
185
+
186
+ def get_missions_for_quest(project_root: Path, quest_id: str) -> list[sqlite3.Row]:
187
+ """Fetch missions for a quest, sorted by status group, priority, created_at.
188
+
189
+ Status order: open/in_progress first, blocked next, closed last.
190
+ """
191
+ conn = get_connection(project_root)
192
+ try:
193
+ cursor = conn.execute(
194
+ "SELECT * FROM missions WHERE quest_id = ? AND deleted_at IS NULL "
195
+ "ORDER BY "
196
+ " CASE status "
197
+ " WHEN 'open' THEN 0 "
198
+ " WHEN 'in_progress' THEN 0 "
199
+ " WHEN 'blocked' THEN 1 "
200
+ " WHEN 'closed' THEN 2 "
201
+ " END ASC, "
202
+ " priority ASC, "
203
+ " created_at ASC",
204
+ (quest_id,),
205
+ )
206
+ return cursor.fetchall()
207
+ finally:
208
+ conn.close()
209
+
210
+
211
+ def list_missions(
212
+ project_root: Path,
213
+ quest_id: str | None = None,
214
+ include_closed: bool = False,
215
+ ) -> dict[str | None, list[sqlite3.Row]]:
216
+ """List missions grouped by quest_id.
217
+
218
+ Returns a dict mapping quest_id (or None for standalone) to lists of missions.
219
+ Sorted by priority ascending, then created_at ascending within each group.
220
+ If quest_id is specified, only that quest's missions are returned.
221
+ If include_closed is False, only active (open, in_progress, blocked) missions are returned.
222
+ """
223
+ conn = get_connection(project_root)
224
+ try:
225
+ conditions = ["m.deleted_at IS NULL"]
226
+ params: list[str] = []
227
+
228
+ if quest_id is not None:
229
+ conditions.append("m.quest_id = ?")
230
+ params.append(quest_id)
231
+
232
+ if not include_closed:
233
+ conditions.append("m.status IN ('open', 'in_progress', 'blocked')")
234
+
235
+ where = "WHERE " + " AND ".join(conditions)
236
+
237
+ cursor = conn.execute(
238
+ f"SELECT m.* FROM missions m {where} ORDER BY priority ASC, created_at ASC",
239
+ params,
240
+ )
241
+ rows = cursor.fetchall()
242
+
243
+ # Group by quest_id
244
+ grouped: dict[str | None, list[sqlite3.Row]] = {}
245
+ for row in rows:
246
+ grouped.setdefault(row["quest_id"], []).append(row)
247
+
248
+ return grouped
249
+ finally:
250
+ conn.close()
251
+
252
+
253
+ def get_mission(project_root: Path, mission_id: str) -> sqlite3.Row | None:
254
+ """Fetch a single mission by ID (excludes soft-deleted)."""
255
+ conn = get_connection(project_root)
256
+ try:
257
+ cursor = conn.execute(
258
+ "SELECT * FROM missions WHERE id = ? AND deleted_at IS NULL",
259
+ (mission_id,),
260
+ )
261
+ return cursor.fetchone()
262
+ finally:
263
+ conn.close()
264
+
265
+
266
+ def get_mission_depends_on(project_root: Path, mission_id: str) -> list[str]:
267
+ """Return IDs of missions that this mission depends on (needs done first)."""
268
+ conn = get_connection(project_root)
269
+ try:
270
+ cursor = conn.execute(
271
+ "SELECT to_id FROM dependencies WHERE from_id = ? AND deleted_at IS NULL", (mission_id,)
272
+ )
273
+ return [row["to_id"] for row in cursor.fetchall()]
274
+ finally:
275
+ conn.close()
276
+
277
+
278
+ def get_mission_blocks(project_root: Path, mission_id: str) -> list[str]:
279
+ """Return IDs of missions that this mission blocks (waiting on this one)."""
280
+ conn = get_connection(project_root)
281
+ try:
282
+ cursor = conn.execute(
283
+ "SELECT from_id FROM dependencies WHERE to_id = ? AND deleted_at IS NULL", (mission_id,)
284
+ )
285
+ return [row["from_id"] for row in cursor.fetchall()]
286
+ finally:
287
+ conn.close()
288
+
289
+
290
+ def get_mission_depends_on_details(project_root: Path, mission_id: str) -> list[dict]:
291
+ """Return details (id, title, status) of missions that this mission depends on."""
292
+ conn = get_connection(project_root)
293
+ try:
294
+ cursor = conn.execute(
295
+ "SELECT d.to_id, m.id, m.title, m.status, m.deleted_at FROM dependencies d "
296
+ "LEFT JOIN missions m ON d.to_id = m.id "
297
+ "WHERE d.from_id = ? AND d.deleted_at IS NULL",
298
+ (mission_id,),
299
+ )
300
+ return [
301
+ {
302
+ "id": row["to_id"],
303
+ "title": row["title"],
304
+ "status": row["status"],
305
+ "deleted_at": row["deleted_at"],
306
+ }
307
+ for row in cursor.fetchall()
308
+ ]
309
+ finally:
310
+ conn.close()
311
+
312
+
313
+ def get_mission_blocks_details(project_root: Path, mission_id: str) -> list[dict]:
314
+ """Return details (id, title, status) of missions that depend on this mission."""
315
+ conn = get_connection(project_root)
316
+ try:
317
+ cursor = conn.execute(
318
+ "SELECT d.from_id, m.id, m.title, m.status, m.deleted_at FROM dependencies d "
319
+ "LEFT JOIN missions m ON d.from_id = m.id "
320
+ "WHERE d.to_id = ? AND d.deleted_at IS NULL",
321
+ (mission_id,),
322
+ )
323
+ return [
324
+ {
325
+ "id": row["from_id"],
326
+ "title": row["title"],
327
+ "status": row["status"],
328
+ "deleted_at": row["deleted_at"],
329
+ }
330
+ for row in cursor.fetchall()
331
+ ]
332
+ finally:
333
+ conn.close()
334
+
335
+
336
+ def get_all_dependencies_for_quest(project_root: Path, quest_id: str) -> list[dict]:
337
+ """Return all active dependency edges where from_id belongs to the quest.
338
+
339
+ Returns a list of {"from_id": ..., "to_id": ...} dicts.
340
+ Cross-quest upstream nodes (to_id belonging to a different quest) are included.
341
+ """
342
+ conn = get_connection(project_root)
343
+ try:
344
+ cursor = conn.execute(
345
+ "SELECT d.from_id, d.to_id "
346
+ "FROM dependencies d "
347
+ "JOIN missions m ON m.id = d.from_id "
348
+ "WHERE m.quest_id = ? "
349
+ "AND m.deleted_at IS NULL "
350
+ "AND d.deleted_at IS NULL",
351
+ (quest_id,),
352
+ )
353
+ return [{"from_id": row["from_id"], "to_id": row["to_id"]} for row in cursor.fetchall()]
354
+ finally:
355
+ conn.close()
356
+
357
+
358
+ def claim_mission(project_root: Path, mission_id: str) -> dict:
359
+ """Claim a mission by transitioning it from open to in_progress.
360
+
361
+ Returns a dict with keys: ok (bool), status (str|None), error (str|None),
362
+ quest_id (str|None), quest_status_changed (bool), quest_status (str|None).
363
+ Also recomputes parent quest status if the mission belongs to a quest.
364
+ """
365
+ # Step 1: ID format validation before any DB access
366
+ err = validators.validate_mission_id(mission_id)
367
+ if err:
368
+ return {"ok": False, "status": None, "error": err,
369
+ "quest_id": None, "quest_status_changed": False, "quest_status": None}
370
+
371
+ conn = get_connection(project_root)
372
+ try:
373
+ conn.execute("BEGIN IMMEDIATE")
374
+
375
+ cursor = conn.execute("SELECT * FROM missions WHERE id = ?", (mission_id,))
376
+ mission = cursor.fetchone()
377
+ if mission is None:
378
+ conn.rollback()
379
+ return {"ok": False, "status": None, "error": f'Mission "{mission_id}" not found',
380
+ "quest_id": None, "quest_status_changed": False, "quest_status": None}
381
+
382
+ current_status = mission["status"]
383
+
384
+ # Idempotent: already in_progress
385
+ if current_status == "in_progress":
386
+ conn.rollback()
387
+ return {"ok": True, "status": "in_progress", "error": None,
388
+ "quest_id": None, "quest_status_changed": False, "quest_status": None}
389
+
390
+ # Only open -> in_progress is valid
391
+ if current_status != "open":
392
+ conn.rollback()
393
+ return {
394
+ "ok": False,
395
+ "status": current_status,
396
+ "error": f'Cannot claim mission "{mission_id}": status is {current_status}',
397
+ "quest_id": None, "quest_status_changed": False, "quest_status": None,
398
+ }
399
+
400
+ now = _now_utc()
401
+ conn.execute(
402
+ "UPDATE missions SET status = 'in_progress', updated_at = ? WHERE id = ?",
403
+ (now, mission_id),
404
+ )
405
+
406
+ # Recompute parent quest status and track changes
407
+ quest_id = mission["quest_id"]
408
+ quest_status_before = None
409
+ if quest_id is not None:
410
+ row = conn.execute("SELECT status FROM quests WHERE id = ?", (quest_id,)).fetchone()
411
+ quest_status_before = row["status"] if row else None
412
+ _derive_quest_status(conn, quest_id, now)
413
+
414
+ quest_status_after = None
415
+ quest_status_changed = False
416
+ if quest_id is not None:
417
+ row = conn.execute("SELECT status FROM quests WHERE id = ?", (quest_id,)).fetchone()
418
+ quest_status_after = row["status"] if row else None
419
+ quest_status_changed = quest_status_after != quest_status_before
420
+
421
+ conn.commit()
422
+ return {"ok": True, "status": "in_progress", "error": None,
423
+ "quest_id": quest_id,
424
+ "quest_status_changed": quest_status_changed,
425
+ "quest_status": quest_status_after}
426
+ except Exception:
427
+ conn.rollback()
428
+ raise
429
+ finally:
430
+ conn.close()
431
+
432
+
433
+ def close_mission(project_root: Path, mission_id: str) -> dict:
434
+ """Close a mission, cascade unblock dependents, and recompute quest status.
435
+
436
+ Returns a dict with 'ok' (bool), 'status', 'error', and 'quest_closed' (bool).
437
+ """
438
+ conn = get_connection(project_root)
439
+ try:
440
+ conn.execute("BEGIN IMMEDIATE")
441
+
442
+ cursor = conn.execute("SELECT * FROM missions WHERE id = ?", (mission_id,))
443
+ mission = cursor.fetchone()
444
+ if mission is None:
445
+ conn.rollback()
446
+ return {"ok": False, "status": None, "error": f'Mission "{mission_id}" not found', "quest_closed": False, "quest_id": None}
447
+
448
+ current_status = mission["status"]
449
+
450
+ # Idempotent: already closed
451
+ if current_status == "closed":
452
+ conn.rollback()
453
+ return {"ok": True, "status": "closed", "error": None, "quest_closed": False, "quest_id": None}
454
+
455
+ # Any non-closed status can transition to closed
456
+ now = _now_utc()
457
+ conn.execute(
458
+ "UPDATE missions SET status = 'closed', block_reason = NULL, closed_at = ?, updated_at = ? WHERE id = ?",
459
+ (now, now, mission_id),
460
+ )
461
+
462
+ # Cascade: recompute parent quest status
463
+ quest_id = mission["quest_id"]
464
+ quest_closed = False
465
+ if quest_id is not None:
466
+ # Get quest status before derivation
467
+ cursor = conn.execute("SELECT status FROM quests WHERE id = ?", (quest_id,))
468
+ quest_before = cursor.fetchone()
469
+ old_quest_status = quest_before["status"] if quest_before else None
470
+
471
+ _derive_quest_status(conn, quest_id, now)
472
+
473
+ # Check if quest was auto-closed
474
+ cursor = conn.execute("SELECT status FROM quests WHERE id = ?", (quest_id,))
475
+ quest_after = cursor.fetchone()
476
+ if quest_after and quest_after["status"] == "closed" and old_quest_status != "closed":
477
+ quest_closed = True
478
+
479
+ conn.commit()
480
+ return {"ok": True, "status": "closed", "error": None, "quest_closed": quest_closed, "quest_id": quest_id}
481
+ except Exception:
482
+ conn.rollback()
483
+ raise
484
+ finally:
485
+ conn.close()
486
+
487
+
488
+ def block_mission(project_root: Path, mission_id: str, reason: str) -> dict:
489
+ """Block a mission with a reason.
490
+
491
+ Valid transitions: open -> blocked, in_progress -> blocked.
492
+ Returns a dict with 'ok', 'status', 'error'.
493
+ """
494
+ conn = get_connection(project_root)
495
+ try:
496
+ conn.execute("BEGIN IMMEDIATE")
497
+
498
+ cursor = conn.execute("SELECT * FROM missions WHERE id = ?", (mission_id,))
499
+ mission = cursor.fetchone()
500
+ if mission is None:
501
+ conn.rollback()
502
+ return {"ok": False, "status": None, "error": f'Mission "{mission_id}" not found'}
503
+
504
+ current_status = mission["status"]
505
+
506
+ if current_status not in ("open", "in_progress"):
507
+ conn.rollback()
508
+ return {
509
+ "ok": False,
510
+ "status": current_status,
511
+ "error": f'Cannot block mission "{mission_id}": status is {current_status}',
512
+ }
513
+
514
+ now = _now_utc()
515
+ conn.execute(
516
+ "UPDATE missions SET status = 'blocked', block_reason = ?, updated_at = ? WHERE id = ?",
517
+ (reason, now, mission_id),
518
+ )
519
+
520
+ # Recompute parent quest status
521
+ quest_id = mission["quest_id"]
522
+ if quest_id is not None:
523
+ _derive_quest_status(conn, quest_id, now)
524
+
525
+ conn.commit()
526
+ return {"ok": True, "status": "blocked", "error": None}
527
+ except Exception:
528
+ conn.rollback()
529
+ raise
530
+ finally:
531
+ conn.close()
532
+
533
+
534
+ def unblock_mission(project_root: Path, mission_id: str) -> dict:
535
+ """Unblock a mission, returning it to open status.
536
+
537
+ Valid transition: blocked -> open.
538
+ Returns a dict with 'ok', 'status', 'error'.
539
+ """
540
+ conn = get_connection(project_root)
541
+ try:
542
+ conn.execute("BEGIN IMMEDIATE")
543
+
544
+ cursor = conn.execute("SELECT * FROM missions WHERE id = ?", (mission_id,))
545
+ mission = cursor.fetchone()
546
+ if mission is None:
547
+ conn.rollback()
548
+ return {"ok": False, "status": None, "error": f'Mission "{mission_id}" not found'}
549
+
550
+ current_status = mission["status"]
551
+
552
+ if current_status != "blocked":
553
+ conn.rollback()
554
+ return {
555
+ "ok": False,
556
+ "status": current_status,
557
+ "error": f'Cannot unblock mission "{mission_id}": status is {current_status}',
558
+ }
559
+
560
+ now = _now_utc()
561
+ conn.execute(
562
+ "UPDATE missions SET status = 'open', block_reason = NULL, updated_at = ? WHERE id = ?",
563
+ (now, mission_id),
564
+ )
565
+
566
+ # Recompute parent quest status
567
+ quest_id = mission["quest_id"]
568
+ if quest_id is not None:
569
+ _derive_quest_status(conn, quest_id, now)
570
+
571
+ conn.commit()
572
+ return {"ok": True, "status": "open", "error": None}
573
+ except Exception:
574
+ conn.rollback()
575
+ raise
576
+ finally:
577
+ conn.close()
578
+
579
+
580
+ def _derive_quest_status(conn: sqlite3.Connection, quest_id: str, now: str) -> None:
581
+ """Recompute and update a quest's status based on its missions.
582
+
583
+ Rules:
584
+ - If any mission is in_progress -> quest is in_progress
585
+ - If all missions are closed -> quest is closed
586
+ - Otherwise -> open
587
+ - If no missions -> open
588
+ """
589
+ # Check quest's auto_close setting
590
+ auto_close = conn.execute(
591
+ "SELECT auto_close FROM quests WHERE id = ?", (quest_id,)
592
+ ).fetchone()["auto_close"]
593
+
594
+ cursor = conn.execute(
595
+ "SELECT status FROM missions WHERE quest_id = ? AND deleted_at IS NULL", (quest_id,)
596
+ )
597
+ statuses = [row["status"] for row in cursor.fetchall()]
598
+
599
+ if not statuses:
600
+ new_status = "open"
601
+ elif any(s == "in_progress" for s in statuses):
602
+ new_status = "in_progress"
603
+ elif all(s == "closed" for s in statuses):
604
+ new_status = "closed"
605
+ elif any(s == "closed" for s in statuses):
606
+ # Mix of closed and non-closed means work is in progress
607
+ new_status = "in_progress"
608
+ else:
609
+ new_status = "open"
610
+
611
+ # When auto_close is disabled, prevent automatic transition to closed
612
+ if not auto_close and new_status == "closed":
613
+ new_status = "open"
614
+
615
+ if new_status == "closed":
616
+ conn.execute(
617
+ "UPDATE quests SET status = ?, closed_at = ?, updated_at = ? WHERE id = ?",
618
+ (new_status, now, now, quest_id),
619
+ )
620
+ else:
621
+ conn.execute(
622
+ "UPDATE quests SET status = ?, closed_at = NULL, updated_at = ? WHERE id = ?",
623
+ (new_status, now, quest_id),
624
+ )
625
+
626
+
627
+ def _would_create_cycle(conn: sqlite3.Connection, from_id: str, to_id: str) -> bool:
628
+ """Return True if adding from_id->to_id would create a cycle.
629
+
630
+ Starting from to_id, follows forward dependency edges (what does current
631
+ depend on?) to see if from_id is reachable. If so, adding from_id->to_id
632
+ would close a cycle.
633
+ """
634
+ visited: set[str] = set()
635
+ stack = [to_id]
636
+ while stack:
637
+ current = stack.pop()
638
+ if current == from_id:
639
+ return True
640
+ if current in visited:
641
+ continue
642
+ visited.add(current)
643
+ # Follow forward edges: what does current depend on?
644
+ cursor = conn.execute(
645
+ "SELECT to_id FROM dependencies WHERE from_id = ? AND deleted_at IS NULL", (current,)
646
+ )
647
+ for row in cursor.fetchall():
648
+ stack.append(row[0])
649
+ return False
650
+
651
+
652
+ def add_dependency(project_root: Path, from_id: str, to_id: str) -> dict:
653
+ """Create a dependency where from_id depends on to_id.
654
+
655
+ Returns a dict with:
656
+ - 'ok' (bool): True if dependency was created or already exists
657
+ - 'created' (bool): True if a new row was inserted
658
+ - 'duplicate' (bool): True if dependency already existed
659
+ - 'closed_target' (bool): True if to_id mission is closed
660
+ - 'error' (str or None): Error message if failed
661
+ """
662
+ conn = get_connection(project_root)
663
+ try:
664
+ conn.execute("BEGIN IMMEDIATE")
665
+
666
+ # Check from_id mission exists
667
+ cursor = conn.execute("SELECT id, status FROM missions WHERE id = ?", (from_id,))
668
+ from_mission = cursor.fetchone()
669
+ if from_mission is None:
670
+ conn.rollback()
671
+ return {"ok": False, "created": False, "duplicate": False, "closed_target": False,
672
+ "error": f'Mission "{from_id}" not found'}
673
+
674
+ # Check to_id mission exists
675
+ cursor = conn.execute("SELECT id, status FROM missions WHERE id = ?", (to_id,))
676
+ to_mission = cursor.fetchone()
677
+ if to_mission is None:
678
+ conn.rollback()
679
+ return {"ok": False, "created": False, "duplicate": False, "closed_target": False,
680
+ "error": f'Mission "{to_id}" not found'}
681
+
682
+ # Check for duplicate
683
+ cursor = conn.execute(
684
+ "SELECT id FROM dependencies WHERE from_id = ? AND to_id = ? AND type = 'blocks' AND deleted_at IS NULL",
685
+ (from_id, to_id),
686
+ )
687
+ if cursor.fetchone() is not None:
688
+ conn.rollback()
689
+ return {"ok": True, "created": False, "duplicate": True, "closed_target": False,
690
+ "error": None}
691
+
692
+ # Check for cycles (includes self-dependency since from_id == to_id is trivially a cycle)
693
+ if _would_create_cycle(conn, from_id, to_id):
694
+ conn.rollback()
695
+ return {"ok": False, "created": False, "duplicate": False, "closed_target": False,
696
+ "error": f"Circular dependency detected: adding {from_id} -> {to_id} would create a cycle"}
697
+
698
+ # Check for soft-deleted row to reactivate instead of inserting
699
+ cursor = conn.execute(
700
+ "SELECT id FROM dependencies WHERE from_id = ? AND to_id = ? AND type = 'blocks' AND deleted_at IS NOT NULL",
701
+ (from_id, to_id),
702
+ )
703
+ existing_deleted = cursor.fetchone()
704
+ if existing_deleted:
705
+ conn.execute(
706
+ "UPDATE dependencies SET deleted_at = NULL WHERE id = ?",
707
+ (existing_deleted["id"],),
708
+ )
709
+ else:
710
+ conn.execute(
711
+ "INSERT INTO dependencies (from_id, to_id, type) VALUES (?, ?, 'blocks')",
712
+ (from_id, to_id),
713
+ )
714
+ conn.commit()
715
+
716
+ closed_target = to_mission["status"] == "closed"
717
+ return {"ok": True, "created": True, "duplicate": False, "closed_target": closed_target,
718
+ "error": None}
719
+ except Exception:
720
+ conn.rollback()
721
+ raise
722
+ finally:
723
+ conn.close()
724
+
725
+
726
+ def remove_dependency(project_root: Path, from_id: str, to_id: str) -> dict:
727
+ """Remove (soft-delete) a dependency where from_id depends on to_id.
728
+
729
+ Returns a dict with:
730
+ - 'removed' (bool): True if a row was soft-deleted
731
+ - 'not_found' (bool): True if no active dependency existed
732
+ """
733
+ conn = get_connection(project_root)
734
+ try:
735
+ now = _now_utc()
736
+ cursor = conn.execute(
737
+ "UPDATE dependencies SET deleted_at = ? "
738
+ "WHERE from_id = ? AND to_id = ? AND type = 'blocks' AND deleted_at IS NULL",
739
+ (now, from_id, to_id),
740
+ )
741
+ conn.commit()
742
+ if cursor.rowcount > 0:
743
+ return {"removed": True, "not_found": False}
744
+ else:
745
+ return {"removed": False, "not_found": True}
746
+ finally:
747
+ conn.close()
748
+
749
+
750
+ def get_dashboard_quests(project_root: Path) -> list[dict]:
751
+ """Return non-closed quests with mission count breakdowns for the dashboard.
752
+
753
+ Each quest dict includes: id, title, status, priority, and missions dict
754
+ with counts for open, in_progress, blocked, closed.
755
+ Sorted by priority ascending, then created_at ascending.
756
+ """
757
+ conn = get_connection(project_root)
758
+ try:
759
+ cursor = conn.execute(
760
+ "SELECT * FROM quests WHERE status != 'closed' AND deleted_at IS NULL "
761
+ "ORDER BY priority ASC, created_at ASC"
762
+ )
763
+ quests = cursor.fetchall()
764
+
765
+ result = []
766
+ for q in quests:
767
+ # Count missions by status for this quest
768
+ mcursor = conn.execute(
769
+ "SELECT status, COUNT(*) as cnt FROM missions "
770
+ "WHERE quest_id = ? AND deleted_at IS NULL GROUP BY status",
771
+ (q["id"],),
772
+ )
773
+ counts = {"open": 0, "in_progress": 0, "blocked": 0, "closed": 0}
774
+ for row in mcursor.fetchall():
775
+ if row["status"] in counts:
776
+ counts[row["status"]] = row["cnt"]
777
+
778
+ result.append({
779
+ "id": q["id"],
780
+ "title": q["title"],
781
+ "status": q["status"],
782
+ "priority": q["priority"],
783
+ "missions": counts,
784
+ })
785
+
786
+ return result
787
+ finally:
788
+ conn.close()
789
+
790
+
791
+ def get_aggregate_stats(project_root: Path) -> dict:
792
+ """Return aggregate counts of quests and missions by status."""
793
+ conn = get_connection(project_root)
794
+ try:
795
+ quest_counts = {"open": 0, "in_progress": 0, "closed": 0}
796
+ cursor = conn.execute(
797
+ "SELECT status, COUNT(*) as cnt FROM quests WHERE deleted_at IS NULL GROUP BY status"
798
+ )
799
+ for row in cursor.fetchall():
800
+ if row["status"] in quest_counts:
801
+ quest_counts[row["status"]] = row["cnt"]
802
+
803
+ mission_counts = {"open": 0, "in_progress": 0, "blocked": 0, "closed": 0}
804
+ cursor = conn.execute(
805
+ "SELECT status, COUNT(*) as cnt FROM missions WHERE deleted_at IS NULL GROUP BY status"
806
+ )
807
+ for row in cursor.fetchall():
808
+ if row["status"] in mission_counts:
809
+ mission_counts[row["status"]] = row["cnt"]
810
+
811
+ return {"quests": quest_counts, "missions": mission_counts}
812
+ finally:
813
+ conn.close()
814
+
815
+
816
+
817
+ def create_mission(
818
+ project_root: Path,
819
+ title: str,
820
+ quest_id: str | None = None,
821
+ description: str = "",
822
+ priority: int = 2,
823
+ knight: str | None = None,
824
+ mission_type: str | None = None,
825
+ ) -> str:
826
+ """Create a new mission and return its ID.
827
+
828
+ If quest_id is provided, the mission belongs to that quest (hierarchical ID).
829
+ If quest_id is None and exactly one non-closed quest exists, infer it.
830
+ If quest_id is None and zero or multiple non-closed quests exist, standalone.
831
+ Raises ValueError if the quest does not exist.
832
+ """
833
+ if not (0 <= priority <= 4):
834
+ raise ValueError(f"priority {priority!r} out of range 0-4")
835
+ conn = get_connection(project_root)
836
+ try:
837
+ conn.execute("BEGIN IMMEDIATE")
838
+
839
+ # Validate quest exists if specified
840
+ if quest_id is not None:
841
+ cursor = conn.execute("SELECT id, status FROM quests WHERE id = ?", (quest_id,))
842
+ quest = cursor.fetchone()
843
+ if quest is None:
844
+ raise ValueError(f'Quest "{quest_id}" not found')
845
+
846
+ # Reopen closed quest
847
+ if quest["status"] == "closed":
848
+ now = _now_utc()
849
+ conn.execute(
850
+ "UPDATE quests SET status = 'open', closed_at = NULL, updated_at = ? WHERE id = ?",
851
+ (now, quest_id),
852
+ )
853
+
854
+ # Generate mission ID
855
+ if quest_id is not None:
856
+ cursor = conn.execute(
857
+ "SELECT id FROM missions WHERE quest_id = ?", (quest_id,)
858
+ )
859
+ existing_ids = set()
860
+ for row in cursor.fetchall():
861
+ # Extract the m-xxxx part from q-xxxx/m-xxxx
862
+ parts = row["id"].split("/")
863
+ if len(parts) == 2:
864
+ existing_ids.add(parts[1])
865
+ m_part = generate_id("m", existing_ids)
866
+ mission_id = f"{quest_id}/{m_part}"
867
+ else:
868
+ cursor = conn.execute(
869
+ "SELECT id FROM missions WHERE quest_id IS NULL"
870
+ )
871
+ existing_ids = {row["id"] for row in cursor.fetchall()}
872
+ mission_id = generate_id("m", existing_ids)
873
+
874
+ now = _now_utc()
875
+ conn.execute(
876
+ "INSERT INTO missions (id, quest_id, title, description, status, priority, knight, created_at, updated_at, mission_type) "
877
+ "VALUES (?, ?, ?, ?, 'open', ?, ?, ?, ?, ?)",
878
+ (mission_id, quest_id, title, description, priority, knight, now, now, mission_type),
879
+ )
880
+ conn.commit()
881
+ return mission_id
882
+ except Exception:
883
+ conn.rollback()
884
+ raise
885
+ finally:
886
+ conn.close()
887
+
888
+
889
+ def delete_quest(project_root: Path, quest_id: str, cascade: bool = False) -> dict:
890
+ """Soft-delete a quest (and optionally cascade to missions/dependencies).
891
+
892
+ Returns a dict with:
893
+ - 'ok' (bool)
894
+ - 'deleted_at' (str or None): timestamp of deletion
895
+ - 'already_deleted' (bool): True if quest was already soft-deleted
896
+ - 'cascade' (list[str] or None): IDs of cascade-deleted missions (only if cascade=True)
897
+ - 'error' (str or None)
898
+ """
899
+ conn = get_connection(project_root)
900
+ try:
901
+ conn.execute("BEGIN IMMEDIATE")
902
+
903
+ # Check if quest exists at all
904
+ cursor = conn.execute("SELECT id, deleted_at FROM quests WHERE id = ?", (quest_id,))
905
+ quest = cursor.fetchone()
906
+
907
+ if quest is None:
908
+ conn.rollback()
909
+ return {"ok": False, "deleted_at": None, "already_deleted": False, "cascade": None,
910
+ "error": f'Quest "{quest_id}" not found'}
911
+
912
+ # Already deleted - idempotent
913
+ if quest["deleted_at"] is not None:
914
+ conn.rollback()
915
+ return {"ok": True, "deleted_at": quest["deleted_at"], "already_deleted": True,
916
+ "cascade": None, "error": None}
917
+
918
+ now = _now_utc()
919
+
920
+ # Soft-delete the quest
921
+ conn.execute(
922
+ "UPDATE quests SET deleted_at = ?, updated_at = ? WHERE id = ?",
923
+ (now, now, quest_id),
924
+ )
925
+
926
+ cascaded_ids: list[str] = []
927
+ if cascade:
928
+ # Collect mission IDs before soft-deleting
929
+ cursor = conn.execute(
930
+ "SELECT id FROM missions WHERE quest_id = ? AND deleted_at IS NULL",
931
+ (quest_id,),
932
+ )
933
+ cascaded_ids = [row["id"] for row in cursor.fetchall()]
934
+
935
+ # Soft-delete missions
936
+ if cascaded_ids:
937
+ conn.execute(
938
+ "UPDATE missions SET deleted_at = ?, updated_at = ? WHERE quest_id = ? AND deleted_at IS NULL",
939
+ (now, now, quest_id),
940
+ )
941
+
942
+ # Soft-delete dependencies involving these missions
943
+ conn.execute(
944
+ "UPDATE dependencies SET deleted_at = ? WHERE deleted_at IS NULL AND "
945
+ "(from_id IN (SELECT id FROM missions WHERE quest_id = ?) "
946
+ "OR to_id IN (SELECT id FROM missions WHERE quest_id = ?))",
947
+ (now, quest_id, quest_id),
948
+ )
949
+
950
+ conn.commit()
951
+ return {"ok": True, "deleted_at": now, "already_deleted": False,
952
+ "cascade": cascaded_ids if cascade else None, "error": None}
953
+ except Exception:
954
+ conn.rollback()
955
+ raise
956
+ finally:
957
+ conn.close()
958
+
959
+
960
+ def delete_mission(project_root: Path, mission_id: str) -> dict:
961
+ """Soft-delete a mission, its dependencies, and re-derive parent quest status.
962
+
963
+ Returns a dict with:
964
+ - 'ok' (bool)
965
+ - 'deleted_at' (str or None): timestamp of deletion
966
+ - 'already_deleted' (bool): True if mission was already soft-deleted
967
+ - 'error' (str or None)
968
+ """
969
+ conn = get_connection(project_root)
970
+ try:
971
+ conn.execute("BEGIN IMMEDIATE")
972
+
973
+ # Check if mission exists at all
974
+ cursor = conn.execute("SELECT id, quest_id, deleted_at FROM missions WHERE id = ?", (mission_id,))
975
+ mission = cursor.fetchone()
976
+
977
+ if mission is None:
978
+ conn.rollback()
979
+ return {"ok": False, "deleted_at": None, "already_deleted": False,
980
+ "error": f'Mission "{mission_id}" not found'}
981
+
982
+ # Already deleted - idempotent
983
+ if mission["deleted_at"] is not None:
984
+ conn.rollback()
985
+ return {"ok": True, "deleted_at": mission["deleted_at"], "already_deleted": True,
986
+ "error": None}
987
+
988
+ now = _now_utc()
989
+
990
+ # Soft-delete the mission
991
+ conn.execute(
992
+ "UPDATE missions SET deleted_at = ?, updated_at = ? WHERE id = ?",
993
+ (now, now, mission_id),
994
+ )
995
+
996
+ # Soft-delete all dependencies involving this mission
997
+ conn.execute(
998
+ "UPDATE dependencies SET deleted_at = ? WHERE (from_id = ? OR to_id = ?) AND deleted_at IS NULL",
999
+ (now, mission_id, mission_id),
1000
+ )
1001
+
1002
+ # Re-derive parent quest status
1003
+ quest_id = mission["quest_id"]
1004
+ if quest_id is not None:
1005
+ _derive_quest_status(conn, quest_id, now)
1006
+
1007
+ conn.commit()
1008
+ return {"ok": True, "deleted_at": now, "already_deleted": False, "error": None}
1009
+ except Exception:
1010
+ conn.rollback()
1011
+ raise
1012
+ finally:
1013
+ conn.close()
1014
+
1015
+
1016
+ def edit_quest(
1017
+ project_root: Path,
1018
+ quest_id: str,
1019
+ title: str | None = None,
1020
+ description: str | None = None,
1021
+ priority: int | None = None,
1022
+ auto_close: int | None = None,
1023
+ ) -> dict:
1024
+ """Edit a quest's fields. Only provided (non-None) fields are updated.
1025
+
1026
+ Returns a dict with 'ok' (bool) and 'error' (str or None).
1027
+ On error, may include 'deleted_at' if the quest was soft-deleted.
1028
+ """
1029
+ if priority is not None:
1030
+ err = validators.validate_priority(priority)
1031
+ if err:
1032
+ return {"ok": False, "error": err}
1033
+
1034
+ conn = get_connection(project_root)
1035
+ try:
1036
+ conn.execute("BEGIN IMMEDIATE")
1037
+
1038
+ # Check if quest exists (including soft-deleted)
1039
+ cursor = conn.execute("SELECT * FROM quests WHERE id = ?", (quest_id,))
1040
+ quest = cursor.fetchone()
1041
+
1042
+ if quest is None:
1043
+ conn.rollback()
1044
+ return {"ok": False, "error": f'Quest "{quest_id}" not found'}
1045
+
1046
+ if quest["deleted_at"] is not None:
1047
+ conn.rollback()
1048
+ return {
1049
+ "ok": False,
1050
+ "error": f'Quest "{quest_id}" not found (deleted on {quest["deleted_at"]})',
1051
+ "deleted_at": quest["deleted_at"],
1052
+ }
1053
+
1054
+ # Build dynamic UPDATE
1055
+ set_clauses = []
1056
+ params: list = []
1057
+ if title is not None:
1058
+ set_clauses.append("title = ?")
1059
+ params.append(title)
1060
+ if description is not None:
1061
+ set_clauses.append("description = ?")
1062
+ params.append(description)
1063
+ if priority is not None:
1064
+ set_clauses.append("priority = ?")
1065
+ params.append(priority)
1066
+ if auto_close is not None:
1067
+ set_clauses.append("auto_close = ?")
1068
+ params.append(auto_close)
1069
+
1070
+ now = _now_utc()
1071
+ set_clauses.append("updated_at = ?")
1072
+ params.append(now)
1073
+ params.append(quest_id)
1074
+
1075
+ conn.execute(
1076
+ f"UPDATE quests SET {', '.join(set_clauses)} WHERE id = ?",
1077
+ params,
1078
+ )
1079
+ conn.commit()
1080
+ return {"ok": True, "error": None}
1081
+ except Exception:
1082
+ conn.rollback()
1083
+ raise
1084
+ finally:
1085
+ conn.close()
1086
+
1087
+
1088
+ def edit_mission(
1089
+ project_root: Path,
1090
+ mission_id: str,
1091
+ title: str | None = None,
1092
+ description: str | None = None,
1093
+ priority: int | None = None,
1094
+ knight: str | None = None,
1095
+ remove_knight: bool = False,
1096
+ mission_type: str | None = None,
1097
+ ) -> dict:
1098
+ """Edit a mission's fields. Only provided (non-None) fields are updated.
1099
+
1100
+ Returns a dict with 'ok' (bool) and 'error' (str or None).
1101
+ On error, may include 'deleted_at' if the mission was soft-deleted.
1102
+ """
1103
+ if priority is not None:
1104
+ err = validators.validate_priority(priority)
1105
+ if err:
1106
+ return {"ok": False, "error": err}
1107
+
1108
+ conn = get_connection(project_root)
1109
+ try:
1110
+ conn.execute("BEGIN IMMEDIATE")
1111
+
1112
+ # Check if mission exists (including soft-deleted)
1113
+ cursor = conn.execute("SELECT * FROM missions WHERE id = ?", (mission_id,))
1114
+ mission = cursor.fetchone()
1115
+
1116
+ if mission is None:
1117
+ conn.rollback()
1118
+ return {"ok": False, "error": f'Mission "{mission_id}" not found'}
1119
+
1120
+ if mission["deleted_at"] is not None:
1121
+ conn.rollback()
1122
+ return {
1123
+ "ok": False,
1124
+ "error": f'Mission "{mission_id}" not found (deleted on {mission["deleted_at"]})',
1125
+ "deleted_at": mission["deleted_at"],
1126
+ }
1127
+
1128
+ # Build dynamic UPDATE
1129
+ set_clauses = []
1130
+ params: list = []
1131
+ if title is not None:
1132
+ set_clauses.append("title = ?")
1133
+ params.append(title)
1134
+ if description is not None:
1135
+ set_clauses.append("description = ?")
1136
+ params.append(description)
1137
+ if priority is not None:
1138
+ set_clauses.append("priority = ?")
1139
+ params.append(priority)
1140
+ if remove_knight:
1141
+ set_clauses.append("knight = NULL")
1142
+ elif knight is not None:
1143
+ set_clauses.append("knight = ?")
1144
+ params.append(knight)
1145
+ if mission_type is not None:
1146
+ set_clauses.append("mission_type = ?")
1147
+ params.append(mission_type)
1148
+
1149
+ now = _now_utc()
1150
+ set_clauses.append("updated_at = ?")
1151
+ params.append(now)
1152
+ params.append(mission_id)
1153
+
1154
+ conn.execute(
1155
+ f"UPDATE missions SET {', '.join(set_clauses)} WHERE id = ?",
1156
+ params,
1157
+ )
1158
+ conn.commit()
1159
+ return {"ok": True, "error": None}
1160
+ except Exception:
1161
+ conn.rollback()
1162
+ raise
1163
+ finally:
1164
+ conn.close()
1165
+
1166
+
1167
+ def close_quest(project_root: Path, quest_id: str) -> dict:
1168
+ """Close a quest by ID.
1169
+
1170
+ Returns a dict with 'ok' (bool), 'status', 'closed_at', 'already_closed', and 'error'.
1171
+ """
1172
+ conn = get_connection(project_root)
1173
+ try:
1174
+ conn.execute("BEGIN IMMEDIATE")
1175
+
1176
+ # First check including soft-deleted to give informative error
1177
+ cursor = conn.execute("SELECT * FROM quests WHERE id = ?", (quest_id,))
1178
+ quest = cursor.fetchone()
1179
+
1180
+ if quest is None:
1181
+ conn.rollback()
1182
+ return {"ok": False, "error": f'Quest "{quest_id}" not found'}
1183
+
1184
+ if quest["deleted_at"] is not None:
1185
+ conn.rollback()
1186
+ return {"ok": False, "error": f'Quest "{quest_id}" not found (deleted on {quest["deleted_at"]})'}
1187
+
1188
+ if quest["status"] == "closed":
1189
+ conn.rollback()
1190
+ return {"ok": True, "status": "closed", "closed_at": quest["closed_at"], "already_closed": True, "error": None}
1191
+
1192
+ now = _now_utc()
1193
+ conn.execute(
1194
+ "UPDATE quests SET status = 'closed', closed_at = ?, updated_at = ? WHERE id = ?",
1195
+ (now, now, quest_id),
1196
+ )
1197
+ conn.commit()
1198
+ return {"ok": True, "status": "closed", "closed_at": now, "already_closed": False, "error": None}
1199
+ except Exception:
1200
+ conn.rollback()
1201
+ raise
1202
+ finally:
1203
+ conn.close()
1204
+
1205
+
1206
+ def create_quest(project_root: Path, title: str, description: str = "", priority: int = 2, auto_close: int = 0) -> str:
1207
+ """Create a new quest and return its ID."""
1208
+ if not (0 <= priority <= 4):
1209
+ raise ValueError(f"priority {priority!r} out of range 0-4")
1210
+ conn = get_connection(project_root)
1211
+ try:
1212
+ conn.execute("BEGIN IMMEDIATE")
1213
+ # Get existing quest IDs for collision avoidance
1214
+ cursor = conn.execute("SELECT id FROM quests")
1215
+ existing_ids = {row["id"] for row in cursor.fetchall()}
1216
+ quest_id = generate_id("q", existing_ids)
1217
+
1218
+ now = _now_utc()
1219
+ conn.execute(
1220
+ "INSERT INTO quests (id, title, description, status, priority, created_at, updated_at, auto_close) "
1221
+ "VALUES (?, ?, ?, 'open', ?, ?, ?, ?)",
1222
+ (quest_id, title, description, priority, now, now, auto_close),
1223
+ )
1224
+ conn.commit()
1225
+ return quest_id
1226
+ except Exception:
1227
+ conn.rollback()
1228
+ raise
1229
+ finally:
1230
+ conn.close()
1231
+
1232
+
1233
+ def add_board_message(
1234
+ project_root: Path, entity_id: str, message: str, sender: str | None = None
1235
+ ) -> dict:
1236
+ """Insert a board message for the given entity and return the new row as a dict."""
1237
+ # 1. Validate entity ID format
1238
+ err = validators.validate_entity_id(entity_id)
1239
+ if err:
1240
+ return {"ok": False, "error": err}
1241
+
1242
+ # 2. Validate message
1243
+ err = validators.validate_message(message)
1244
+ if err:
1245
+ return {"ok": False, "error": err}
1246
+
1247
+ # 3. Route entity to table
1248
+ table, id_col = validators.route_entity(entity_id)
1249
+
1250
+ conn = get_connection(project_root)
1251
+ try:
1252
+ # Validate entity existence
1253
+ entity_label = "Quest" if table == "quests" else "Mission"
1254
+ row_check = conn.execute(
1255
+ f"SELECT id FROM {table} WHERE {id_col} = ? AND deleted_at IS NULL",
1256
+ (entity_id,),
1257
+ ).fetchone()
1258
+ if row_check is None:
1259
+ return {"ok": False, "error": f'{entity_label} "{entity_id}" not found'}
1260
+
1261
+ cursor = conn.execute(
1262
+ "INSERT INTO board_messages (entity_id, message, sender) VALUES (?, ?, ?)",
1263
+ (entity_id, message, sender),
1264
+ )
1265
+ conn.commit()
1266
+ row_id = cursor.lastrowid
1267
+ row = conn.execute(
1268
+ "SELECT id, entity_id, sender, created_at FROM board_messages WHERE id = ?",
1269
+ (row_id,),
1270
+ ).fetchone()
1271
+ return {
1272
+ "ok": True,
1273
+ "id": row["id"],
1274
+ "entity_id": row["entity_id"],
1275
+ "sender": row["sender"],
1276
+ "created_at": row["created_at"],
1277
+ }
1278
+ finally:
1279
+ conn.close()
1280
+
1281
+
1282
+ def get_board_messages(project_root: Path, entity_id: str) -> list[dict]:
1283
+ """Return all non-deleted board messages for the given entity, oldest first."""
1284
+ conn = get_connection(project_root)
1285
+ try:
1286
+ cursor = conn.execute(
1287
+ "SELECT id, entity_id, message, sender, created_at FROM board_messages "
1288
+ "WHERE entity_id = ? AND deleted_at IS NULL ORDER BY created_at ASC",
1289
+ (entity_id,),
1290
+ )
1291
+ rows = cursor.fetchall()
1292
+ return [
1293
+ {
1294
+ "id": row["id"],
1295
+ "entity_id": row["entity_id"],
1296
+ "message": row["message"],
1297
+ "sender": row["sender"],
1298
+ "created_at": row["created_at"],
1299
+ }
1300
+ for row in rows
1301
+ ]
1302
+ finally:
1303
+ conn.close()
1304
+
1305
+
1306
+ def delete_board_message(project_root: Path, message_id: int) -> dict:
1307
+ """Soft-delete a board message by its integer ID."""
1308
+ conn = get_connection(project_root)
1309
+ try:
1310
+ now = _now_utc()
1311
+ cursor = conn.execute(
1312
+ "UPDATE board_messages SET deleted_at = ? WHERE id = ? AND deleted_at IS NULL",
1313
+ (now, message_id),
1314
+ )
1315
+ conn.commit()
1316
+ if cursor.rowcount == 0:
1317
+ return {"ok": False, "error": f"Board message {message_id} not found."}
1318
+ return {"ok": True, "id": message_id, "deleted_at": now}
1319
+ finally:
1320
+ conn.close()