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/cli.py ADDED
@@ -0,0 +1,2786 @@
1
+ """Click command definitions for the Lore CLI."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import yaml
7
+
8
+ import click
9
+
10
+ from lore import __version__
11
+ from lore import paths
12
+ from lore import validators
13
+ from lore import knight as knight_module
14
+ from lore import graph
15
+ from lore.root import find_project_root, ProjectNotFoundError
16
+
17
+
18
+ def _validate_mission_id(entity_id, ctx):
19
+ """Validate a mission ID format. Returns True if valid, handles error if not."""
20
+ json_mode = ctx.obj.get("json", False)
21
+ err = validators.validate_mission_id(entity_id)
22
+ if err:
23
+ if json_mode:
24
+ click.echo(json.dumps({"error": err}), err=True)
25
+ else:
26
+ click.echo(err, err=True)
27
+ ctx.exit(1)
28
+ return False
29
+ return True
30
+
31
+
32
+ def _validate_entity_id(entity_id, ctx):
33
+ """Validate an entity ID format (quest or mission). Returns True if valid."""
34
+ json_mode = ctx.obj.get("json", False)
35
+ err = validators.validate_entity_id(entity_id)
36
+ if err:
37
+ if json_mode:
38
+ click.echo(json.dumps({"error": err}), err=True)
39
+ else:
40
+ click.echo(err, err=True)
41
+ ctx.exit(1)
42
+ return False
43
+ return True
44
+
45
+
46
+ def _validate_sender_id(sender, ctx):
47
+ """Validate a sender ID format (q-xxxx or q-xxxx/m-yyyy). Returns True if valid."""
48
+ json_mode = ctx.obj.get("json", False)
49
+ err = validators.validate_entity_id(sender)
50
+ if err:
51
+ if json_mode:
52
+ click.echo(json.dumps({"error": err}), err=True)
53
+ else:
54
+ click.echo(err, err=True)
55
+ ctx.exit(1)
56
+ return False
57
+ return True
58
+
59
+
60
+ def _validate_name(name, ctx):
61
+ """Validate a knight or doctrine name. Returns True if valid, handles error if not."""
62
+ json_mode = ctx.obj.get("json", False)
63
+ err = validators.validate_name(name)
64
+ if err:
65
+ if json_mode:
66
+ click.echo(json.dumps({"error": err}), err=True)
67
+ else:
68
+ click.echo(err, err=True)
69
+ ctx.exit(1)
70
+ return False
71
+ return True
72
+
73
+
74
+ def _format_table(headers: list[str], rows: list[list[str]]) -> list[str]:
75
+ """Format a table with consistent column padding and spacing.
76
+
77
+ Rules:
78
+ - 2-space indent before first column
79
+ - 2-space gap between columns
80
+ - Each column is padded to the widest value (header or any row)
81
+ - Last column is NOT right-padded
82
+ - Returns a list of strings (header + one per row)
83
+ """
84
+ num_cols = len(headers)
85
+ # Compute column widths as max of header width and all row values
86
+ col_widths = []
87
+ for i, h in enumerate(headers):
88
+ w = len(h)
89
+ for row in rows:
90
+ if i < len(row):
91
+ w = max(w, len(row[i]))
92
+ col_widths.append(w)
93
+
94
+ lines = []
95
+ for row_data in [headers] + [list(r) for r in rows]:
96
+ parts = []
97
+ for i, col_w in enumerate(col_widths):
98
+ val = row_data[i] if i < len(row_data) else ""
99
+ if i == num_cols - 1:
100
+ # Last column: no padding
101
+ parts.append(val)
102
+ else:
103
+ parts.append(f"{val:<{col_w}}")
104
+ lines.append(" " + " ".join(parts))
105
+ return lines
106
+
107
+
108
+ @click.group(invoke_without_command=True)
109
+ @click.version_option(version=__version__, prog_name="lore")
110
+ @click.option("--json", "json_mode", is_flag=True, help="Output as JSON.")
111
+ @click.pass_context
112
+ def main(ctx, json_mode):
113
+ """Lore — Agent Task Manager.
114
+
115
+ Lore organises agent work into two core entity types:
116
+
117
+ \b
118
+ Quest — a body of work (feature, fix, or refactor).
119
+ Mission — a single executable task assigned to an agent.
120
+
121
+ Supporting entities:
122
+
123
+ \b
124
+ Knight — a reusable agent persona attached to missions.
125
+ Doctrine — workflow templates that guide how missions are executed.
126
+ Codex — project documentation, searchable and graph-traversable.
127
+ Artifact — reusable read-only template files referenced by stable ID.
128
+ Watcher — definitions for agents that monitor and react to project state.
129
+
130
+ Run any command group with --help for details on that concept.
131
+ """
132
+ ctx.ensure_object(dict)
133
+ ctx.obj["json"] = json_mode
134
+
135
+ # init and --help don't require a project root
136
+ if ctx.invoked_subcommand in ("init",):
137
+ return
138
+
139
+ try:
140
+ ctx.obj["project_root"] = find_project_root()
141
+ except ProjectNotFoundError as e:
142
+ if json_mode:
143
+ click.echo(json.dumps({"error": str(e)}), err=True)
144
+ else:
145
+ click.echo(str(e), err=True)
146
+ ctx.exit(1)
147
+ return
148
+
149
+ if ctx.invoked_subcommand is None:
150
+ _show_dashboard(ctx)
151
+
152
+
153
+ def _show_dashboard(ctx):
154
+ """Display the dashboard overview of active quests with mission progress."""
155
+ from lore.db import get_dashboard_quests
156
+
157
+ project_root = ctx.obj["project_root"]
158
+ quests = get_dashboard_quests(project_root)
159
+ json_mode = ctx.obj.get("json", False)
160
+
161
+ if json_mode:
162
+ data = {
163
+ "quests": [
164
+ {
165
+ "id": q["id"],
166
+ "title": q["title"],
167
+ "status": q["status"],
168
+ "priority": q["priority"],
169
+ "missions": q["missions"],
170
+ }
171
+ for q in quests
172
+ ]
173
+ }
174
+ click.echo(json.dumps(data))
175
+ return
176
+
177
+ if not quests:
178
+ click.echo('No quests yet. Run "lore new quest" to get started.')
179
+ return
180
+
181
+ for q in quests:
182
+ m = q["missions"]
183
+ click.echo(
184
+ f" {q['id']} P{q['priority']} [{q['status']}] {q['title']} "
185
+ f"(open:{m['open']} in_progress:{m['in_progress']} blocked:{m['blocked']} closed:{m['closed']})"
186
+ )
187
+
188
+
189
+ @main.command("stats")
190
+ @click.pass_context
191
+ def stats(ctx):
192
+ """Show aggregate statistics across all quests and missions."""
193
+ from lore.db import get_aggregate_stats
194
+
195
+ project_root = ctx.obj["project_root"]
196
+ data = get_aggregate_stats(project_root)
197
+
198
+ if ctx.obj.get("json", False):
199
+ click.echo(json.dumps(data))
200
+ return
201
+
202
+ q = data["quests"]
203
+ click.echo("Quests:")
204
+ click.echo(f" open: {q['open']}")
205
+ click.echo(f" in_progress: {q['in_progress']}")
206
+ click.echo(f" closed: {q['closed']}")
207
+ click.echo("")
208
+ m = data["missions"]
209
+ click.echo("Missions:")
210
+ click.echo(f" open: {m['open']}")
211
+ click.echo(f" in_progress: {m['in_progress']}")
212
+ click.echo(f" blocked: {m['blocked']}")
213
+ click.echo(f" closed: {m['closed']}")
214
+
215
+
216
+ @main.command("oracle")
217
+ @click.option(
218
+ "--json", "json_flag", is_flag=True, hidden=True, help="Ignored for oracle."
219
+ )
220
+ @click.pass_context
221
+ def oracle(ctx, json_flag):
222
+ """Generate human-readable markdown reports in .lore/reports/. Produces one file per quest and mission. Wipes and recreates the reports directory on every run — do not store custom files there. Intended for human stakeholders, not for agent consumption. JSON output is not supported for this command."""
223
+ from lore.oracle import generate_reports
224
+
225
+ project_root = ctx.obj["project_root"]
226
+ generate_reports(project_root)
227
+ click.echo("Reports generated in .lore/reports/")
228
+
229
+
230
+ @main.command()
231
+ @click.pass_context
232
+ def init(ctx):
233
+ """Initialize a Lore project in the current directory."""
234
+ from lore.init import run_init
235
+
236
+ messages = run_init()
237
+ click.echo("Initialized Lore project:")
238
+ for msg in messages:
239
+ click.echo(msg)
240
+
241
+
242
+ @main.group()
243
+ @click.pass_context
244
+ def new(ctx):
245
+ """Create quests and missions.
246
+
247
+ A Quest is a body of work (feature, bug fix, refactor). A Mission is a
248
+ single executable task within a quest. Missions without a quest (-q) are
249
+ standalone.
250
+
251
+ Example sequence: lore new quest "My feature" then
252
+ lore new mission -q <id> "Task one" to build a plan."""
253
+ pass
254
+
255
+
256
+ @new.command("quest")
257
+ @click.argument("title")
258
+ @click.option("-d", "--description", default="", help="Quest description.")
259
+ @click.option("-p", "--priority", type=int, default=2, help="Priority 0-4.")
260
+ @click.option(
261
+ "--auto-close",
262
+ "auto_close",
263
+ is_flag=True,
264
+ default=False,
265
+ help="Enable auto-close when all missions done.",
266
+ )
267
+ @click.option(
268
+ "--no-auto-close", "no_auto_close", is_flag=True, default=False, hidden=True
269
+ )
270
+ @click.pass_context
271
+ def new_quest(ctx, title, description, priority, auto_close, no_auto_close):
272
+ """Create a new quest."""
273
+ err = validators.validate_priority(priority)
274
+ if err:
275
+ raise click.ClickException(err)
276
+
277
+ from lore.db import create_quest
278
+
279
+ project_root = ctx.obj["project_root"]
280
+ json_mode = ctx.obj.get("json", False)
281
+
282
+ ac_value = 1 if auto_close else 0
283
+ try:
284
+ quest_id = create_quest(
285
+ project_root, title, description, priority, auto_close=ac_value
286
+ )
287
+ except ValueError as e:
288
+ raise click.ClickException(str(e))
289
+ except RuntimeError:
290
+ msg = "ID generation failed: collision after maximum length. Please retry."
291
+ if json_mode:
292
+ click.echo(json.dumps({"error": msg}), err=True)
293
+ else:
294
+ click.echo(msg, err=True)
295
+ ctx.exit(1)
296
+ return
297
+
298
+ if json_mode:
299
+ click.echo(json.dumps({"id": quest_id}))
300
+ return
301
+
302
+ click.echo(f"Created quest {quest_id}")
303
+
304
+
305
+ @new.command("mission")
306
+ @click.argument("title")
307
+ @click.option("-q", "--quest", "quest_id", default=None, help="Parent quest ID.")
308
+ @click.option("-d", "--description", default="", help="Mission description.")
309
+ @click.option("-p", "--priority", type=int, default=2, help="Priority 0-4.")
310
+ @click.option("-k", "--knight", default=None, help="Knight filename.")
311
+ @click.option(
312
+ "-T",
313
+ "--type",
314
+ "mission_type",
315
+ type=str,
316
+ default=None,
317
+ help="Mission type.",
318
+ )
319
+ @click.pass_context
320
+ def new_mission(ctx, title, quest_id, description, priority, knight, mission_type):
321
+ """Create a new mission."""
322
+ json_mode = ctx.obj.get("json", False)
323
+
324
+ err = validators.validate_priority(priority)
325
+ if err:
326
+ raise click.ClickException(err)
327
+
328
+ from lore.db import create_mission, get_connection
329
+
330
+ project_root = ctx.obj["project_root"]
331
+
332
+ # Infer quest if not specified and exactly one non-closed quest exists
333
+ if quest_id is None:
334
+ conn = get_connection(project_root)
335
+ try:
336
+ cursor = conn.execute("SELECT id FROM quests WHERE status != 'closed'")
337
+ active_quests = cursor.fetchall()
338
+ if len(active_quests) == 1:
339
+ quest_id = active_quests[0]["id"]
340
+ finally:
341
+ conn.close()
342
+
343
+ try:
344
+ mission_id = create_mission(
345
+ project_root,
346
+ title,
347
+ quest_id=quest_id,
348
+ description=description,
349
+ priority=priority,
350
+ knight=knight,
351
+ mission_type=mission_type,
352
+ )
353
+ except RuntimeError:
354
+ msg = "ID generation failed: collision after maximum length. Please retry."
355
+ if json_mode:
356
+ click.echo(json.dumps({"error": msg}), err=True)
357
+ else:
358
+ click.echo(msg, err=True)
359
+ ctx.exit(1)
360
+ return
361
+ except ValueError as e:
362
+ if json_mode:
363
+ click.echo(json.dumps({"error": str(e)}), err=True)
364
+ ctx.exit(1)
365
+ return
366
+ click.echo(str(e), err=True)
367
+ ctx.exit(1)
368
+ return
369
+
370
+ if json_mode:
371
+ click.echo(json.dumps({"id": mission_id}))
372
+ return
373
+
374
+ click.echo(f"Created mission {mission_id}")
375
+
376
+
377
+ @main.command("claim")
378
+ @click.argument("mission_ids", nargs=-1, required=True)
379
+ @click.pass_context
380
+ def claim(ctx, mission_ids):
381
+ """Claim one or more missions (open -> in_progress)."""
382
+ from lore.db import claim_mission
383
+
384
+ project_root = ctx.obj["project_root"]
385
+ json_mode = ctx.obj.get("json", False)
386
+
387
+ if json_mode:
388
+ updated = []
389
+ quest_status_changed = []
390
+ errors = []
391
+
392
+ for mid in mission_ids:
393
+ mid_err = validators.validate_mission_id(mid)
394
+ if mid_err:
395
+ errors.append(mid_err)
396
+ continue
397
+ result = claim_mission(project_root, mid)
398
+ if not result["ok"]:
399
+ errors.append(result["error"])
400
+ else:
401
+ updated.append(mid)
402
+ if result["quest_status_changed"]:
403
+ quest_status_changed.append({"id": result["quest_id"], "status": result["quest_status"]})
404
+
405
+ click.echo(
406
+ json.dumps(
407
+ {
408
+ "updated": updated,
409
+ "quest_status_changed": quest_status_changed,
410
+ "errors": errors,
411
+ }
412
+ )
413
+ )
414
+ if errors:
415
+ ctx.exit(1)
416
+ return
417
+
418
+ any_failed = False
419
+
420
+ for mid in mission_ids:
421
+ mid_err = validators.validate_mission_id(mid)
422
+ if mid_err:
423
+ click.echo(mid_err, err=True)
424
+ any_failed = True
425
+ continue
426
+ result = claim_mission(project_root, mid)
427
+
428
+ if not result["ok"]:
429
+ click.echo(result["error"], err=True)
430
+ any_failed = True
431
+ else:
432
+ click.echo(f"{mid}: {result['status']}")
433
+
434
+ if any_failed:
435
+ ctx.exit(1)
436
+
437
+
438
+ @main.command("done")
439
+ @click.argument("entity_ids", nargs=-1, required=True)
440
+ @click.pass_context
441
+ def done(ctx, entity_ids):
442
+ """Close one or more missions or quests.
443
+
444
+ For missions: transitions in_progress -> closed and unblocks any dependents.
445
+
446
+ For quests: use only if auto_close is disabled; quests with auto_close
447
+ enabled close automatically when all missions are done.
448
+ """
449
+ from lore.db import close_mission, close_quest
450
+
451
+ project_root = ctx.obj["project_root"]
452
+ json_mode = ctx.obj.get("json", False)
453
+
454
+ def _is_quest_id(eid):
455
+ return eid.startswith("q-") and "/" not in eid
456
+
457
+ if json_mode:
458
+ updated = []
459
+ quest_closed = []
460
+ errors = []
461
+ for eid in entity_ids:
462
+ if _is_quest_id(eid):
463
+ result = close_quest(project_root, eid)
464
+ if not result["ok"]:
465
+ errors.append(result["error"])
466
+ else:
467
+ updated.append(eid)
468
+ else:
469
+ eid_err = validators.validate_mission_id(eid)
470
+ if eid_err:
471
+ errors.append(eid_err)
472
+ continue
473
+ result = close_mission(project_root, eid)
474
+ if not result["ok"]:
475
+ errors.append(result["error"])
476
+ else:
477
+ updated.append(eid)
478
+ if result["quest_closed"]:
479
+ quest_closed.append(result["quest_id"])
480
+ click.echo(
481
+ json.dumps(
482
+ {
483
+ "updated": updated,
484
+ "quest_closed": quest_closed,
485
+ "errors": errors,
486
+ }
487
+ )
488
+ )
489
+ if errors:
490
+ ctx.exit(1)
491
+ return
492
+
493
+ any_failed = False
494
+
495
+ for eid in entity_ids:
496
+ if _is_quest_id(eid):
497
+ result = close_quest(project_root, eid)
498
+ if not result["ok"]:
499
+ click.echo(result["error"], err=True)
500
+ any_failed = True
501
+ else:
502
+ if result.get("already_closed"):
503
+ click.echo(f"{eid}: already closed")
504
+ else:
505
+ click.echo(f"{eid}: closed (closed_at: {result['closed_at']})")
506
+ else:
507
+ eid_err = validators.validate_mission_id(eid)
508
+ if eid_err:
509
+ click.echo(eid_err, err=True)
510
+ any_failed = True
511
+ continue
512
+ result = close_mission(project_root, eid)
513
+
514
+ if not result["ok"]:
515
+ click.echo(result["error"], err=True)
516
+ any_failed = True
517
+ else:
518
+ if result["quest_closed"]:
519
+ click.echo(f"{eid}: closed (quest auto-closed)")
520
+ else:
521
+ click.echo(f"{eid}: {result['status']}")
522
+
523
+ if any_failed:
524
+ ctx.exit(1)
525
+
526
+
527
+ @main.command("block")
528
+ @click.argument("mission_id")
529
+ @click.argument("reason")
530
+ @click.pass_context
531
+ def block(ctx, mission_id, reason):
532
+ """Mark a mission as blocked with a reason."""
533
+ from lore.db import block_mission
534
+
535
+ project_root = ctx.obj["project_root"]
536
+ json_mode = ctx.obj.get("json", False)
537
+
538
+ if not _validate_mission_id(mission_id, ctx):
539
+ return
540
+
541
+ result = block_mission(project_root, mission_id, reason)
542
+
543
+ if json_mode:
544
+ if not result["ok"]:
545
+ click.echo(json.dumps({"error": result["error"]}), err=True)
546
+ ctx.exit(1)
547
+ else:
548
+ click.echo(
549
+ json.dumps(
550
+ {
551
+ "id": mission_id,
552
+ "status": "blocked",
553
+ "block_reason": reason,
554
+ }
555
+ )
556
+ )
557
+ return
558
+
559
+ if not result["ok"]:
560
+ click.echo(result["error"], err=True)
561
+ ctx.exit(1)
562
+ else:
563
+ click.echo(f"{mission_id}: {result['status']}")
564
+
565
+
566
+ @main.command("unblock")
567
+ @click.argument("mission_id")
568
+ @click.pass_context
569
+ def unblock(ctx, mission_id):
570
+ """Unblock a blocked mission, returning it to open status."""
571
+ from lore.db import unblock_mission
572
+
573
+ project_root = ctx.obj["project_root"]
574
+ json_mode = ctx.obj.get("json", False)
575
+
576
+ if not _validate_mission_id(mission_id, ctx):
577
+ return
578
+
579
+ result = unblock_mission(project_root, mission_id)
580
+
581
+ if json_mode:
582
+ if not result["ok"]:
583
+ click.echo(json.dumps({"error": result["error"]}), err=True)
584
+ ctx.exit(1)
585
+ else:
586
+ click.echo(
587
+ json.dumps(
588
+ {
589
+ "id": mission_id,
590
+ "status": "open",
591
+ }
592
+ )
593
+ )
594
+ return
595
+
596
+ if not result["ok"]:
597
+ click.echo(result["error"], err=True)
598
+ ctx.exit(1)
599
+ else:
600
+ click.echo(f"{mission_id}: {result['status']}")
601
+
602
+
603
+ @main.command("ready")
604
+ @click.argument("count", type=int, default=1, required=False)
605
+ @click.pass_context
606
+ def ready(ctx, count):
607
+ """Show the highest priority unblocked mission(s), sorted by priority.
608
+
609
+ Blocked and closed missions are excluded.
610
+
611
+ Optional COUNT returns multiple missions at once: 'lore ready 5'."""
612
+ from lore.priority import get_ready_missions
613
+
614
+ project_root = ctx.obj["project_root"]
615
+ json_mode = ctx.obj.get("json", False)
616
+ missions = get_ready_missions(project_root, count=count)
617
+
618
+ if json_mode:
619
+ data = {
620
+ "missions": [
621
+ {
622
+ "id": m["id"],
623
+ "quest_id": m["quest_id"],
624
+ "title": m["title"],
625
+ "status": m["status"],
626
+ "priority": m["priority"],
627
+ "mission_type": m["mission_type"],
628
+ "knight": m["knight"],
629
+ "created_at": m["created_at"],
630
+ }
631
+ for m in missions
632
+ ]
633
+ }
634
+ click.echo(json.dumps(data))
635
+ return
636
+
637
+ if not missions:
638
+ click.echo("No missions are ready.")
639
+ return
640
+
641
+ for m in missions:
642
+ knight_str = f" [{m['knight']}]" if m["knight"] else ""
643
+ type_str = f" [{m['mission_type']}]" if m["mission_type"] else ""
644
+ click.echo(
645
+ f" {m['id']} P{m['priority']} [{m['status']}]{type_str} {m['title']}{knight_str}"
646
+ )
647
+
648
+
649
+ @main.command("needs")
650
+ @click.argument("pairs", nargs=-1, required=True)
651
+ @click.pass_context
652
+ def needs(ctx, pairs):
653
+ """Declare dependencies between missions using colon-pair syntax."""
654
+ from lore.db import add_dependency
655
+
656
+ project_root = ctx.obj["project_root"]
657
+ json_mode = ctx.obj.get("json", False)
658
+
659
+ if json_mode:
660
+ created = []
661
+ existing = []
662
+ errors = []
663
+ for pair in pairs:
664
+ parts = pair.split(":")
665
+ if len(parts) != 2 or not parts[0] or not parts[1]:
666
+ errors.append(
667
+ f'Invalid dependency pair format: "{pair}". Expected "from:to".'
668
+ )
669
+ continue
670
+ from_id, to_id = parts[0], parts[1]
671
+ result = add_dependency(project_root, from_id, to_id)
672
+ if not result["ok"]:
673
+ errors.append(result["error"])
674
+ elif result["duplicate"]:
675
+ existing.append({"from": from_id, "to": to_id})
676
+ else:
677
+ created.append({"from": from_id, "to": to_id})
678
+ click.echo(
679
+ json.dumps(
680
+ {
681
+ "created": created,
682
+ "existing": existing,
683
+ "errors": errors,
684
+ }
685
+ )
686
+ )
687
+ if errors:
688
+ ctx.exit(1)
689
+ return
690
+
691
+ any_failed = False
692
+
693
+ for pair in pairs:
694
+ # Validate pair format: exactly one colon, non-empty sides
695
+ parts = pair.split(":")
696
+ if len(parts) != 2 or not parts[0] or not parts[1]:
697
+ click.echo(
698
+ f'Invalid dependency pair format: "{pair}". Expected "from:to".',
699
+ err=True,
700
+ )
701
+ any_failed = True
702
+ continue
703
+
704
+ from_id, to_id = parts[0], parts[1]
705
+ result = add_dependency(project_root, from_id, to_id)
706
+
707
+ if not result["ok"]:
708
+ click.echo(result["error"], err=True)
709
+ any_failed = True
710
+ elif result["duplicate"]:
711
+ click.echo(f"Dependency already exists: {from_id} -> {to_id}")
712
+ else:
713
+ click.echo(f"Dependency created: {from_id} -> {to_id}")
714
+ if result["closed_target"]:
715
+ click.echo(
716
+ f"Note: dependency target {to_id} is already closed. Mission {from_id} is not blocked."
717
+ )
718
+
719
+ if any_failed:
720
+ ctx.exit(1)
721
+
722
+
723
+ @main.command("unneed")
724
+ @click.option("--json", "json_flag", is_flag=True, help="Output as JSON.")
725
+ @click.argument("pairs", nargs=-1, required=True)
726
+ @click.pass_context
727
+ def unneed(ctx, json_flag, pairs):
728
+ """Remove dependencies between missions using colon-pair syntax."""
729
+ from lore.db import remove_dependency
730
+
731
+ project_root = ctx.obj["project_root"]
732
+ json_mode = json_flag or ctx.obj.get("json", False)
733
+
734
+ removed_list = []
735
+ not_found_list = []
736
+ errors_list = []
737
+ any_error = False
738
+
739
+ for pair in pairs:
740
+ parts = pair.split(":")
741
+ if len(parts) != 2 or not parts[0] or not parts[1]:
742
+ errors_list.append(f'Invalid pair format: "{pair}"')
743
+ any_error = True
744
+ if not json_mode:
745
+ click.echo(f'Invalid pair format: "{pair}"', err=True)
746
+ continue
747
+
748
+ from_id, to_id = parts
749
+
750
+ # Validate mission ID format
751
+ from_err = validators.validate_mission_id(from_id)
752
+ to_err = validators.validate_mission_id(to_id)
753
+ if from_err or to_err:
754
+ msg = from_err if from_err else to_err
755
+ errors_list.append(msg)
756
+ any_error = True
757
+ if not json_mode:
758
+ click.echo(msg, err=True)
759
+ continue
760
+
761
+ result = remove_dependency(project_root, from_id, to_id)
762
+
763
+ if result.get("removed", False):
764
+ removed_list.append({"from": from_id, "to": to_id})
765
+ if not json_mode:
766
+ click.echo(f"Dependency removed: {from_id} -> {to_id}")
767
+ else:
768
+ not_found_list.append({"from": from_id, "to": to_id})
769
+ if not json_mode:
770
+ click.echo(f"Warning: no dependency found: {from_id} -> {to_id}")
771
+
772
+ if json_mode:
773
+ click.echo(
774
+ json.dumps(
775
+ {
776
+ "removed": removed_list,
777
+ "not_found": not_found_list,
778
+ "errors": errors_list,
779
+ }
780
+ )
781
+ )
782
+
783
+ if any_error:
784
+ ctx.exit(1)
785
+
786
+
787
+ @main.command("list")
788
+ @click.option("--all", "show_all", is_flag=True, help="Include closed quests.")
789
+ @click.pass_context
790
+ def list_quests(ctx, show_all):
791
+ """List quests."""
792
+ from lore.db import list_quests as db_list_quests
793
+
794
+ project_root = ctx.obj["project_root"]
795
+ quests = db_list_quests(project_root, include_closed=show_all)
796
+
797
+ if ctx.obj.get("json", False):
798
+ data = {
799
+ "quests": [
800
+ {
801
+ "id": q["id"],
802
+ "title": q["title"],
803
+ "status": q["status"],
804
+ "priority": q["priority"],
805
+ "created_at": q["created_at"],
806
+ }
807
+ for q in quests
808
+ ]
809
+ }
810
+ click.echo(json.dumps(data))
811
+ return
812
+
813
+ if not quests:
814
+ click.echo("No quests found.")
815
+ return
816
+
817
+ for q in quests:
818
+ click.echo(f" {q['id']} P{q['priority']} [{q['status']}] {q['title']}")
819
+
820
+
821
+ @main.command("missions")
822
+ @click.argument("quest_id", required=False, default=None)
823
+ @click.option("--all", "show_all", is_flag=True, help="Include all statuses.")
824
+ @click.pass_context
825
+ def missions(ctx, quest_id, show_all):
826
+ """List missions across all quests, or scoped to one quest.
827
+
828
+ Missions have four statuses: open, in_progress, blocked, closed.
829
+
830
+ The mission_type field is free-form. Lore does not interpret it.
831
+
832
+ Use 'lore ready' to find the next mission to dispatch.
833
+ """
834
+ from lore.db import get_deleted_at, get_quest, list_missions
835
+
836
+ project_root = ctx.obj["project_root"]
837
+ json_mode = ctx.obj.get("json", False)
838
+
839
+ # Validate quest exists if specified
840
+ if quest_id is not None:
841
+ quest = get_quest(project_root, quest_id)
842
+ if quest is None:
843
+ if json_mode:
844
+ click.echo(
845
+ json.dumps({"error": f'Quest "{quest_id}" not found'}), err=True
846
+ )
847
+ ctx.exit(1)
848
+ return
849
+ click.echo(f'Quest "{quest_id}" not found', err=True)
850
+ ctx.exit(1)
851
+ return
852
+
853
+ grouped = list_missions(project_root, quest_id=quest_id, include_closed=show_all)
854
+
855
+ if json_mode:
856
+ flat = []
857
+ for qid, mission_list in grouped.items():
858
+ for m in mission_list:
859
+ flat.append(
860
+ {
861
+ "id": m["id"],
862
+ "quest_id": m["quest_id"],
863
+ "title": m["title"],
864
+ "status": m["status"],
865
+ "priority": m["priority"],
866
+ "mission_type": m["mission_type"],
867
+ "knight": m["knight"],
868
+ "created_at": m["created_at"],
869
+ }
870
+ )
871
+ click.echo(json.dumps({"missions": flat}))
872
+ return
873
+
874
+ if not grouped:
875
+ click.echo("No missions found.")
876
+ return
877
+
878
+ # Display quest-bound missions first, then standalone
879
+ quest_ids = sorted([k for k in grouped if k is not None])
880
+ has_standalone = None in grouped
881
+
882
+ def _format_mission_line(m):
883
+ knight_str = f" [{m['knight']}]" if m["knight"] else ""
884
+ type_str = f" [{m['mission_type']}]" if m["mission_type"] else ""
885
+ return f" {m['id']} P{m['priority']} [{m['status']}]{type_str} {m['title']}{knight_str}"
886
+
887
+ for qid in quest_ids:
888
+ # Fetch quest title for display
889
+ quest = get_quest(project_root, qid)
890
+ if quest:
891
+ quest_title = quest["title"]
892
+ quest_deleted_annotation = ""
893
+ else:
894
+ # Quest may be soft-deleted
895
+ deleted_at = get_deleted_at(project_root, qid)
896
+ quest_title = qid
897
+ quest_deleted_annotation = " (quest deleted)" if deleted_at else ""
898
+ click.echo(f"Quest: {quest_title} ({qid}){quest_deleted_annotation}")
899
+ for m in grouped[qid]:
900
+ click.echo(_format_mission_line(m))
901
+ click.echo("")
902
+
903
+ if has_standalone:
904
+ click.echo("Standalone:")
905
+ for m in grouped[None]:
906
+ click.echo(_format_mission_line(m))
907
+
908
+
909
+ @main.group()
910
+ @click.pass_context
911
+ def knight(ctx):
912
+ """Manage knight personas — reusable markdown files that tell a worker agent how to approach work (style, constraints, authority). Assign a knight to a mission with 'lore new mission -k <name>.md'. When a worker runs 'lore show <mission-id>', the knight's content is included in the output. Knights encode the 'how'; mission descriptions encode the 'what'."""
913
+ pass
914
+
915
+
916
+ @knight.command("list")
917
+ @click.option("--json", "json_flag", is_flag=True, help="Output as JSON.")
918
+ @click.pass_context
919
+ def knight_list(ctx, json_flag):
920
+ """List available knights."""
921
+ project_root = ctx.obj["project_root"]
922
+ json_mode = json_flag or ctx.obj.get("json", False)
923
+ knights_dir = paths.knights_dir(project_root)
924
+
925
+ records = knight_module.list_knights(knights_dir)
926
+
927
+ if json_mode:
928
+ filtered = [
929
+ {"id": r["id"], "group": r["group"], "title": r["title"], "summary": r["summary"]}
930
+ for r in records
931
+ ]
932
+ click.echo(json.dumps({"knights": filtered}))
933
+ return
934
+
935
+ if not records:
936
+ click.echo("No knights found.")
937
+ return
938
+
939
+ rows = [[r["id"], r["group"], r["title"], r["summary"]] for r in records]
940
+ for line in _format_table(["ID", "GROUP", "TITLE", "SUMMARY"], rows):
941
+ click.echo(line)
942
+
943
+
944
+ @knight.command("show")
945
+ @click.argument("name")
946
+ @click.pass_context
947
+ def knight_show(ctx, name):
948
+ """Show the contents of a knight file."""
949
+ project_root = ctx.obj["project_root"]
950
+ json_mode = ctx.obj.get("json", False)
951
+ knights_dir = paths.knights_dir(project_root)
952
+
953
+ try:
954
+ knight_path = knight_module.find_knight(knights_dir, name)
955
+ except ValueError:
956
+ knight_path = None
957
+
958
+ if knight_path is None:
959
+ if json_mode:
960
+ click.echo(
961
+ json.dumps(
962
+ {"error": f'Knight "{name}" not found in .lore/knights/'}
963
+ ),
964
+ err=True,
965
+ )
966
+ ctx.exit(1)
967
+ return
968
+ click.echo(f'Knight "{name}" not found in .lore/knights/', err=True)
969
+ ctx.exit(1)
970
+ return
971
+
972
+ if json_mode:
973
+ click.echo(
974
+ json.dumps(
975
+ {
976
+ "name": name,
977
+ "filename": f"{name}.md",
978
+ "contents": knight_path.read_text(),
979
+ }
980
+ )
981
+ )
982
+ return
983
+
984
+ click.echo(knight_path.read_text())
985
+
986
+
987
+ @knight.command("new", context_settings={"ignore_unknown_options": True})
988
+ @click.argument("name")
989
+ @click.option(
990
+ "--from", "-f", "from_file", default=None, help="Source file for knight content."
991
+ )
992
+ @click.pass_context
993
+ def knight_new(ctx, name, from_file):
994
+ """Create a new knight."""
995
+ if not _validate_name(name, ctx):
996
+ return
997
+ project_root = ctx.obj["project_root"]
998
+ json_mode = ctx.obj.get("json", False)
999
+ knights_dir = paths.knights_dir(project_root)
1000
+ knight_path = knights_dir / f"{name}.md"
1001
+
1002
+ # Check for duplicate (flat path or any subdirectory)
1003
+ if knight_path.exists() or (
1004
+ knights_dir.exists() and list(knights_dir.rglob(f"{name}.md"))
1005
+ ):
1006
+ msg = f'Knight "{name}" already exists.'
1007
+ if json_mode:
1008
+ click.echo(json.dumps({"error": msg}))
1009
+ else:
1010
+ click.echo(msg)
1011
+ ctx.exit(1)
1012
+ return
1013
+
1014
+ if from_file is not None and from_file != "-":
1015
+ source = Path(from_file)
1016
+ if not source.exists():
1017
+ msg = f"File not found: {from_file}"
1018
+ if json_mode:
1019
+ click.echo(json.dumps({"error": msg}))
1020
+ else:
1021
+ click.echo(msg)
1022
+ ctx.exit(1)
1023
+ return
1024
+ content = source.read_text()
1025
+ else:
1026
+ content = click.get_text_stream("stdin").read()
1027
+ if not content.strip():
1028
+ msg = "No content provided on stdin."
1029
+ if json_mode:
1030
+ click.echo(json.dumps({"error": msg}))
1031
+ else:
1032
+ click.echo(msg)
1033
+ ctx.exit(1)
1034
+ return
1035
+
1036
+ knights_dir.mkdir(parents=True, exist_ok=True)
1037
+ knight_path.write_text(content)
1038
+
1039
+ if json_mode:
1040
+ click.echo(json.dumps({"name": name, "filename": f"{name}.md"}))
1041
+ return
1042
+ click.echo(f"Created knight {name}")
1043
+
1044
+
1045
+ @knight.command("edit")
1046
+ @click.argument("name")
1047
+ @click.option(
1048
+ "--from", "-f", "from_file", default=None, help="Source file for knight content."
1049
+ )
1050
+ @click.pass_context
1051
+ def knight_edit(ctx, name, from_file):
1052
+ """Edit an existing knight."""
1053
+ if not _validate_name(name, ctx):
1054
+ return
1055
+ project_root = ctx.obj["project_root"]
1056
+ json_mode = ctx.obj.get("json", False)
1057
+ knight_path = paths.knights_dir(project_root) / f"{name}.md"
1058
+
1059
+ if not knight_path.exists():
1060
+ msg = f'Knight "{name}" not found.'
1061
+ if json_mode:
1062
+ click.echo(json.dumps({"error": msg}))
1063
+ else:
1064
+ click.echo(msg)
1065
+ ctx.exit(1)
1066
+ return
1067
+
1068
+ if from_file is not None and from_file != "-":
1069
+ source = Path(from_file)
1070
+ if not source.exists():
1071
+ msg = f"File not found: {from_file}"
1072
+ if json_mode:
1073
+ click.echo(json.dumps({"error": msg}))
1074
+ else:
1075
+ click.echo(msg)
1076
+ ctx.exit(1)
1077
+ return
1078
+ content = source.read_text()
1079
+ else:
1080
+ content = click.get_text_stream("stdin").read()
1081
+ if not content.strip():
1082
+ msg = "No content provided on stdin."
1083
+ if json_mode:
1084
+ click.echo(json.dumps({"error": msg}))
1085
+ else:
1086
+ click.echo(msg)
1087
+ ctx.exit(1)
1088
+ return
1089
+
1090
+ knight_path.write_text(content)
1091
+
1092
+ if json_mode:
1093
+ click.echo(json.dumps({"name": name, "filename": f"{name}.md"}))
1094
+ return
1095
+ click.echo(f"Updated knight {name}")
1096
+
1097
+
1098
+ @knight.command("delete")
1099
+ @click.argument("name")
1100
+ @click.pass_context
1101
+ def knight_delete(ctx, name):
1102
+ """Delete a knight."""
1103
+ if not _validate_name(name, ctx):
1104
+ return
1105
+ project_root = ctx.obj["project_root"]
1106
+ json_mode = ctx.obj.get("json", False)
1107
+ knight_path = paths.knights_dir(project_root) / f"{name}.md"
1108
+
1109
+ if not knight_path.exists():
1110
+ msg = f'Knight "{name}" not found in .lore/knights/'
1111
+ if json_mode:
1112
+ click.echo(json.dumps({"error": msg}), err=True)
1113
+ else:
1114
+ click.echo(msg, err=True)
1115
+ ctx.exit(1)
1116
+ return
1117
+
1118
+ knight_path.rename(knight_path.with_suffix(".md.deleted"))
1119
+
1120
+ if json_mode:
1121
+ click.echo(json.dumps({"name": name, "deleted": True}))
1122
+ return
1123
+ click.echo(f"Deleted knight {name}")
1124
+
1125
+
1126
+ @main.group()
1127
+ @click.pass_context
1128
+ def doctrine(ctx):
1129
+ """Manage doctrine templates — YAML files that describe the step sequence and suggested knights for a standard body of work (e.g. a feature or bugfix workflow). Doctrines have no execution engine; an orchestrator reads them with 'lore doctrine show <name>' and translates the steps into quests and missions as guidance. Doctrines are passive — they do not trigger actions."""
1130
+ pass
1131
+
1132
+
1133
+ @doctrine.command("list")
1134
+ @click.option("--json", "json_flag", is_flag=True, help="Output as JSON.")
1135
+ @click.pass_context
1136
+ def doctrine_list(ctx, json_flag):
1137
+ """List available doctrines."""
1138
+ from lore.doctrine import list_doctrines
1139
+
1140
+ project_root = ctx.obj["project_root"]
1141
+ json_mode = json_flag or ctx.obj.get("json", False)
1142
+ doctrines_dir = paths.doctrines_dir(project_root)
1143
+
1144
+ doctrines = list_doctrines(doctrines_dir)
1145
+
1146
+ if json_mode:
1147
+ data = {
1148
+ "doctrines": [
1149
+ {
1150
+ "id": d.get("id", d["name"]),
1151
+ "group": d.get("group", ""),
1152
+ "title": d.get("title", d["name"]),
1153
+ "summary": d.get("summary", ""),
1154
+ "valid": d["valid"],
1155
+ }
1156
+ for d in doctrines
1157
+ ]
1158
+ }
1159
+ click.echo(json.dumps(data))
1160
+ return
1161
+
1162
+ if not doctrines:
1163
+ click.echo("No doctrines found.")
1164
+ return
1165
+
1166
+ rows = [
1167
+ [
1168
+ d.get("id", d["name"]),
1169
+ d.get("group", ""),
1170
+ d.get("title", d["name"]),
1171
+ (d.get("summary", d.get("description", "")) + (" [INVALID]" if not d.get("valid", True) else "")),
1172
+ ]
1173
+ for d in doctrines
1174
+ ]
1175
+ for line in _format_table(["ID", "GROUP", "TITLE", "SUMMARY"], rows):
1176
+ click.echo(line)
1177
+
1178
+
1179
+ @doctrine.command("show")
1180
+ @click.argument("name")
1181
+ @click.pass_context
1182
+ def doctrine_show(ctx, name):
1183
+ """Show and validate a doctrine."""
1184
+ from lore.doctrine import load_doctrine, DoctrineError
1185
+
1186
+ project_root = ctx.obj["project_root"]
1187
+ json_mode = ctx.obj.get("json", False)
1188
+ doctrines_dir = paths.doctrines_dir(project_root)
1189
+
1190
+ if "/" in name or "\\" in name:
1191
+ if json_mode:
1192
+ click.echo(
1193
+ json.dumps(
1194
+ {"error": f'Doctrine "{name}" not found in .lore/doctrines/'}
1195
+ ),
1196
+ err=True,
1197
+ )
1198
+ ctx.exit(1)
1199
+ return
1200
+ click.echo(f'Doctrine "{name}" not found in .lore/doctrines/', err=True)
1201
+ ctx.exit(1)
1202
+ return
1203
+
1204
+ doctrine_path = doctrines_dir / f"{name}.yaml"
1205
+
1206
+ if not doctrine_path.exists():
1207
+ # Search in subdirectories (e.g. default/)
1208
+ matches = (
1209
+ list(doctrines_dir.rglob(f"{name}.yaml")) if doctrines_dir.exists() else []
1210
+ )
1211
+ if matches:
1212
+ doctrine_path = matches[0]
1213
+ else:
1214
+ if json_mode:
1215
+ click.echo(
1216
+ json.dumps(
1217
+ {"error": f'Doctrine "{name}" not found in .lore/doctrines/'}
1218
+ ),
1219
+ err=True,
1220
+ )
1221
+ ctx.exit(1)
1222
+ return
1223
+ click.echo(f'Doctrine "{name}" not found in .lore/doctrines/', err=True)
1224
+ ctx.exit(1)
1225
+ return
1226
+
1227
+ try:
1228
+ doctrine = load_doctrine(doctrine_path)
1229
+ except DoctrineError as e:
1230
+ if json_mode:
1231
+ click.echo(json.dumps({"error": str(e)}), err=True)
1232
+ ctx.exit(1)
1233
+ return
1234
+ click.echo(str(e), err=True)
1235
+ ctx.exit(1)
1236
+ return
1237
+
1238
+ if json_mode:
1239
+ data = {
1240
+ "name": doctrine["name"],
1241
+ "description": doctrine["description"],
1242
+ "steps": doctrine["steps"],
1243
+ }
1244
+ click.echo(json.dumps(data))
1245
+ return
1246
+
1247
+ click.echo(f"Doctrine: {doctrine['name']}")
1248
+ click.echo(f"Description: {doctrine['description']}")
1249
+ click.echo("")
1250
+ click.echo("Steps:")
1251
+ for step in doctrine["steps"]:
1252
+ click.echo(f" [{step['id']}] {step['title']}")
1253
+ click.echo(f" Priority: {step['priority']}")
1254
+ if step["type"]:
1255
+ click.echo(f" Type: {step['type']}")
1256
+ if step["needs"]:
1257
+ click.echo(f" Needs: {', '.join(step['needs'])}")
1258
+ if step["knight"]:
1259
+ click.echo(f" Knight: {step['knight']}")
1260
+ if step["notes"]:
1261
+ click.echo(f" Notes: {step['notes']}")
1262
+
1263
+
1264
+ @doctrine.command("new", context_settings={"ignore_unknown_options": True})
1265
+ @click.argument("name")
1266
+ @click.option("--from", "-f", "from_file", default=None, help="Source file.")
1267
+ @click.pass_context
1268
+ def doctrine_new(ctx, name, from_file):
1269
+ """Create a new doctrine."""
1270
+ import sys
1271
+ from lore.doctrine import validate_doctrine_content, scaffold_doctrine, DoctrineError
1272
+
1273
+ json_mode = ctx.obj.get("json", False)
1274
+
1275
+ if not _validate_name(name, ctx):
1276
+ return
1277
+
1278
+ project_root = ctx.obj["project_root"]
1279
+ doctrines_dir = paths.doctrines_dir(project_root)
1280
+ doctrine_path = doctrines_dir / f"{name}.yaml"
1281
+
1282
+ # Check duplicate (flat path or any subdirectory)
1283
+ if doctrine_path.exists() or (
1284
+ doctrines_dir.exists() and list(doctrines_dir.rglob(f"{name}.yaml"))
1285
+ ):
1286
+ msg = f"Error: doctrine '{name}' already exists. Use 'lore doctrine edit {name}' to modify it."
1287
+ if json_mode:
1288
+ click.echo(json.dumps({"error": msg}))
1289
+ else:
1290
+ click.echo(msg)
1291
+ ctx.exit(1)
1292
+ return
1293
+
1294
+ # Read content
1295
+ if from_file is not None and from_file != "-":
1296
+ source = Path(from_file)
1297
+ if not source.exists():
1298
+ msg = f"File not found: {from_file}"
1299
+ if json_mode:
1300
+ click.echo(json.dumps({"error": msg}))
1301
+ else:
1302
+ click.echo(msg)
1303
+ ctx.exit(1)
1304
+ return
1305
+ content = source.read_text()
1306
+ # Validate content (strict: requires name, description, steps)
1307
+ try:
1308
+ validate_doctrine_content(content, name)
1309
+ except DoctrineError as e:
1310
+ msg = str(e)
1311
+ if json_mode:
1312
+ click.echo(json.dumps({"error": msg}))
1313
+ else:
1314
+ click.echo(msg)
1315
+ ctx.exit(1)
1316
+ return
1317
+ else:
1318
+ # Scaffold path: TTY detected, or stdin is empty/whitespace
1319
+ content = click.get_text_stream("stdin").read() if not sys.stdin.isatty() else ""
1320
+ if not content or not content.strip():
1321
+ content = scaffold_doctrine(name)
1322
+ doctrines_dir.mkdir(parents=True, exist_ok=True)
1323
+ doctrine_path.write_text(content)
1324
+ if json_mode:
1325
+ click.echo(json.dumps({"name": name, "filename": f"{name}.yaml"}))
1326
+ return
1327
+ click.echo(f"Created doctrine {name}")
1328
+ return
1329
+ # Light validation for stdin: valid YAML + id-if-present must match
1330
+ import yaml as _yaml
1331
+ try:
1332
+ data = _yaml.safe_load(content)
1333
+ except _yaml.YAMLError as e:
1334
+ msg = str(e)
1335
+ if json_mode:
1336
+ click.echo(json.dumps({"error": msg}))
1337
+ else:
1338
+ click.echo(msg)
1339
+ ctx.exit(1)
1340
+ return
1341
+ if not isinstance(data, dict):
1342
+ msg = "Doctrine must be a YAML mapping"
1343
+ if json_mode:
1344
+ click.echo(json.dumps({"error": msg}))
1345
+ else:
1346
+ click.echo(msg)
1347
+ ctx.exit(1)
1348
+ return
1349
+ if "id" in data and str(data["id"]) != name:
1350
+ msg = f'Doctrine id "{data["id"]}" does not match command argument "{name}"'
1351
+ if json_mode:
1352
+ click.echo(json.dumps({"error": msg}))
1353
+ else:
1354
+ click.echo(msg)
1355
+ ctx.exit(1)
1356
+ return
1357
+
1358
+ doctrines_dir.mkdir(parents=True, exist_ok=True)
1359
+ doctrine_path.write_text(content)
1360
+
1361
+ if json_mode:
1362
+ click.echo(json.dumps({"name": name, "filename": f"{name}.yaml"}))
1363
+ return
1364
+ click.echo(f"Created doctrine {name}")
1365
+
1366
+
1367
+ @doctrine.command("edit")
1368
+ @click.argument("name")
1369
+ @click.option("--from", "-f", "from_file", default=None, help="Source file.")
1370
+ @click.pass_context
1371
+ def doctrine_edit(ctx, name, from_file):
1372
+ """Edit an existing doctrine."""
1373
+ from lore.doctrine import validate_doctrine_content, DoctrineError
1374
+
1375
+ json_mode = ctx.obj.get("json", False)
1376
+
1377
+ if not _validate_name(name, ctx):
1378
+ return
1379
+
1380
+ project_root = ctx.obj["project_root"]
1381
+ doctrine_path = paths.doctrines_dir(project_root) / f"{name}.yaml"
1382
+
1383
+ # Check existence
1384
+ if not doctrine_path.exists():
1385
+ msg = f'Doctrine "{name}" not found.'
1386
+ if json_mode:
1387
+ click.echo(json.dumps({"error": msg}))
1388
+ else:
1389
+ click.echo(msg)
1390
+ ctx.exit(1)
1391
+ return
1392
+
1393
+ # Read content
1394
+ if from_file is not None and from_file != "-":
1395
+ source = Path(from_file)
1396
+ if not source.exists():
1397
+ msg = f"File not found: {from_file}"
1398
+ if json_mode:
1399
+ click.echo(json.dumps({"error": msg}))
1400
+ else:
1401
+ click.echo(msg)
1402
+ ctx.exit(1)
1403
+ return
1404
+ content = source.read_text()
1405
+ else:
1406
+ content = click.get_text_stream("stdin").read()
1407
+ if not content or not content.strip():
1408
+ msg = "No content provided on stdin."
1409
+ if json_mode:
1410
+ click.echo(json.dumps({"error": msg}))
1411
+ else:
1412
+ click.echo(msg)
1413
+ ctx.exit(1)
1414
+ return
1415
+
1416
+ # Validate content
1417
+ try:
1418
+ validate_doctrine_content(content, name)
1419
+ except DoctrineError as e:
1420
+ msg = str(e)
1421
+ if json_mode:
1422
+ click.echo(json.dumps({"error": msg}))
1423
+ else:
1424
+ click.echo(msg)
1425
+ ctx.exit(1)
1426
+ return
1427
+
1428
+ # Preserve existing frontmatter fields (id, title, summary) that the new
1429
+ # content may have omitted.
1430
+ try:
1431
+ existing_raw = yaml.safe_load(doctrine_path.read_text()) or {}
1432
+ except Exception:
1433
+ existing_raw = {}
1434
+ new_data = yaml.safe_load(content) or {}
1435
+ for field in ("id", "title", "summary"):
1436
+ if field in existing_raw and field not in new_data:
1437
+ new_data[field] = existing_raw[field]
1438
+ merged_content = yaml.dump(new_data, default_flow_style=False, allow_unicode=True, sort_keys=False)
1439
+
1440
+ doctrine_path.write_text(merged_content)
1441
+
1442
+ if json_mode:
1443
+ click.echo(json.dumps({"name": name, "filename": f"{name}.yaml"}))
1444
+ return
1445
+ click.echo(f"Updated doctrine {name}")
1446
+
1447
+
1448
+ @doctrine.command("delete")
1449
+ @click.argument("name")
1450
+ @click.pass_context
1451
+ def doctrine_delete(ctx, name):
1452
+ """Delete a doctrine."""
1453
+ if not _validate_name(name, ctx):
1454
+ return
1455
+ project_root = ctx.obj["project_root"]
1456
+ json_mode = ctx.obj.get("json", False)
1457
+ doctrine_path = paths.doctrines_dir(project_root) / f"{name}.yaml"
1458
+
1459
+ if not doctrine_path.exists():
1460
+ msg = f'Doctrine "{name}" not found'
1461
+ if json_mode:
1462
+ click.echo(json.dumps({"error": msg}), err=True)
1463
+ else:
1464
+ click.echo(msg, err=True)
1465
+ ctx.exit(1)
1466
+ return
1467
+
1468
+ doctrine_path.rename(doctrine_path.with_suffix(".yaml.deleted"))
1469
+
1470
+ if json_mode:
1471
+ click.echo(json.dumps({"name": name, "deleted": True}))
1472
+ return
1473
+ click.echo(f"Deleted doctrine {name}")
1474
+
1475
+
1476
+ @main.command("edit")
1477
+ @click.argument("entity_id")
1478
+ @click.option("-t", "--title", default=None, help="New title.")
1479
+ @click.option("-d", "--description", default=None, help="New description.")
1480
+ @click.option("-p", "--priority", type=int, default=None, help="New priority 0-4.")
1481
+ @click.option("-k", "--knight", default=None, help="Assign knight.")
1482
+ @click.option(
1483
+ "--no-knight", is_flag=True, default=False, help="Remove knight assignment."
1484
+ )
1485
+ @click.option(
1486
+ "--auto-close", "auto_close", is_flag=True, default=False, help="Enable auto-close."
1487
+ )
1488
+ @click.option(
1489
+ "--no-auto-close",
1490
+ "no_auto_close",
1491
+ is_flag=True,
1492
+ default=False,
1493
+ help="Disable auto-close.",
1494
+ )
1495
+ @click.option(
1496
+ "-T",
1497
+ "--type",
1498
+ "mission_type",
1499
+ type=str,
1500
+ default=None,
1501
+ help="Mission type.",
1502
+ )
1503
+ @click.pass_context
1504
+ def edit(
1505
+ ctx,
1506
+ entity_id,
1507
+ title,
1508
+ description,
1509
+ priority,
1510
+ knight,
1511
+ no_knight,
1512
+ auto_close,
1513
+ no_auto_close,
1514
+ mission_type,
1515
+ ):
1516
+ """Edit a quest or mission."""
1517
+ # Mutual exclusion check for --knight and --no-knight
1518
+ if knight is not None and no_knight:
1519
+ raise click.UsageError("--knight and --no-knight are mutually exclusive.")
1520
+
1521
+ if auto_close and no_auto_close:
1522
+ raise click.UsageError(
1523
+ "--auto-close and --no-auto-close are mutually exclusive."
1524
+ )
1525
+
1526
+ has_auto_close_flag = auto_close or no_auto_close
1527
+
1528
+ if (
1529
+ title is None
1530
+ and description is None
1531
+ and priority is None
1532
+ and knight is None
1533
+ and not no_knight
1534
+ and not has_auto_close_flag
1535
+ and mission_type is None
1536
+ ):
1537
+ raise click.UsageError(
1538
+ "At least one of --title, --description, --priority, --knight, --no-knight, --auto-close, --no-auto-close, or --type is required."
1539
+ )
1540
+
1541
+ if not _validate_entity_id(entity_id, ctx):
1542
+ return
1543
+
1544
+ if entity_id.startswith("q-") and "/" not in entity_id:
1545
+ ac_value = None
1546
+ if auto_close:
1547
+ ac_value = 1
1548
+ elif no_auto_close:
1549
+ ac_value = 0
1550
+ _edit_quest(ctx, entity_id, title, description, priority, auto_close=ac_value)
1551
+ else:
1552
+ _edit_mission(
1553
+ ctx,
1554
+ entity_id,
1555
+ title,
1556
+ description,
1557
+ priority,
1558
+ knight,
1559
+ no_knight,
1560
+ mission_type=mission_type,
1561
+ )
1562
+
1563
+
1564
+ def _edit_quest(ctx, quest_id, title, description, priority, auto_close=None):
1565
+ """Edit a quest's fields."""
1566
+ from lore.db import edit_quest, get_quest, get_missions_for_quest
1567
+
1568
+ project_root = ctx.obj["project_root"]
1569
+ json_mode = ctx.obj.get("json", False)
1570
+
1571
+ result = edit_quest(
1572
+ project_root,
1573
+ quest_id,
1574
+ title=title,
1575
+ description=description,
1576
+ priority=priority,
1577
+ auto_close=auto_close,
1578
+ )
1579
+
1580
+ if not result["ok"]:
1581
+ if json_mode:
1582
+ err_data = {"error": result["error"]}
1583
+ if "deleted_at" in result:
1584
+ err_data["deleted_at"] = result["deleted_at"]
1585
+ click.echo(json.dumps(err_data), err=True)
1586
+ else:
1587
+ click.echo(result["error"], err=True)
1588
+ ctx.exit(1)
1589
+ return
1590
+
1591
+ if json_mode:
1592
+ quest = get_quest(project_root, quest_id)
1593
+ missions = get_missions_for_quest(project_root, quest_id)
1594
+ data = {
1595
+ "id": quest["id"],
1596
+ "title": quest["title"],
1597
+ "description": quest["description"],
1598
+ "status": quest["status"],
1599
+ "priority": quest["priority"],
1600
+ "created_at": quest["created_at"],
1601
+ "updated_at": quest["updated_at"],
1602
+ "closed_at": quest["closed_at"],
1603
+ "auto_close": bool(quest["auto_close"]),
1604
+ "missions": [
1605
+ {
1606
+ "id": m["id"],
1607
+ "title": m["title"],
1608
+ "status": m["status"],
1609
+ "priority": m["priority"],
1610
+ "mission_type": m["mission_type"],
1611
+ "knight": m["knight"],
1612
+ }
1613
+ for m in missions
1614
+ ],
1615
+ }
1616
+ click.echo(json.dumps(data))
1617
+ return
1618
+
1619
+ click.echo(f"Updated quest {quest_id}")
1620
+
1621
+
1622
+ def _edit_mission(
1623
+ ctx, mission_id, title, description, priority, knight, no_knight, mission_type=None
1624
+ ):
1625
+ """Edit a mission's fields."""
1626
+ from lore.db import (
1627
+ edit_mission,
1628
+ get_mission,
1629
+ get_mission_depends_on,
1630
+ get_mission_blocks,
1631
+ )
1632
+
1633
+ project_root = ctx.obj["project_root"]
1634
+ json_mode = ctx.obj.get("json", False)
1635
+
1636
+ result = edit_mission(
1637
+ project_root,
1638
+ mission_id,
1639
+ title=title,
1640
+ description=description,
1641
+ priority=priority,
1642
+ knight=knight,
1643
+ remove_knight=no_knight,
1644
+ mission_type=mission_type,
1645
+ )
1646
+
1647
+ if not result["ok"]:
1648
+ if json_mode:
1649
+ err_data = {"error": result["error"]}
1650
+ if "deleted_at" in result:
1651
+ err_data["deleted_at"] = result["deleted_at"]
1652
+ click.echo(json.dumps(err_data), err=True)
1653
+ else:
1654
+ click.echo(result["error"], err=True)
1655
+ ctx.exit(1)
1656
+ return
1657
+
1658
+ if json_mode:
1659
+ mission = get_mission(project_root, mission_id)
1660
+ depends_on = get_mission_depends_on(project_root, mission_id)
1661
+ blocks = get_mission_blocks(project_root, mission_id)
1662
+ data = {
1663
+ "id": mission["id"],
1664
+ "quest_id": mission["quest_id"],
1665
+ "title": mission["title"],
1666
+ "description": mission["description"],
1667
+ "status": mission["status"],
1668
+ "priority": mission["priority"],
1669
+ "knight": mission["knight"],
1670
+ "mission_type": mission["mission_type"],
1671
+ "block_reason": mission["block_reason"],
1672
+ "created_at": mission["created_at"],
1673
+ "updated_at": mission["updated_at"],
1674
+ "closed_at": mission["closed_at"],
1675
+ "dependencies": {
1676
+ "needs": depends_on,
1677
+ "blocks": blocks,
1678
+ },
1679
+ }
1680
+ click.echo(json.dumps(data))
1681
+ return
1682
+
1683
+ click.echo(f"Updated mission {mission_id}")
1684
+
1685
+
1686
+ @main.command("delete")
1687
+ @click.argument("entity_id")
1688
+ @click.option(
1689
+ "--cascade",
1690
+ is_flag=True,
1691
+ default=False,
1692
+ help="Also delete all missions and dependencies.",
1693
+ )
1694
+ @click.pass_context
1695
+ def delete(ctx, entity_id, cascade):
1696
+ """Delete a quest or mission."""
1697
+ json_mode = ctx.obj.get("json", False)
1698
+
1699
+ if entity_id.startswith("q-") and "/" not in entity_id:
1700
+ # Use loose validation for delete (allows lookup of any quest-like ID)
1701
+ if validators.validate_quest_id_loose(entity_id) is not None:
1702
+ msg = f'Invalid quest ID format: "{entity_id}"'
1703
+ if json_mode:
1704
+ click.echo(json.dumps({"error": msg}), err=True)
1705
+ else:
1706
+ click.echo(msg, err=True)
1707
+ ctx.exit(1)
1708
+ return
1709
+ _delete_quest(ctx, entity_id, cascade)
1710
+ elif "m-" in entity_id:
1711
+ if not _validate_mission_id(entity_id, ctx):
1712
+ return
1713
+ _delete_mission(ctx, entity_id)
1714
+ else:
1715
+ msg = f'Invalid ID format: "{entity_id}"'
1716
+ if json_mode:
1717
+ click.echo(json.dumps({"error": msg}), err=True)
1718
+ else:
1719
+ click.echo(msg, err=True)
1720
+ ctx.exit(1)
1721
+
1722
+
1723
+ def _delete_quest(ctx, quest_id, cascade):
1724
+ """Soft-delete a quest."""
1725
+ from lore.db import delete_quest
1726
+
1727
+ project_root = ctx.obj["project_root"]
1728
+ json_mode = ctx.obj.get("json", False)
1729
+
1730
+ result = delete_quest(project_root, quest_id, cascade=cascade)
1731
+
1732
+ if not result["ok"]:
1733
+ if json_mode:
1734
+ click.echo(json.dumps({"error": result["error"]}), err=True)
1735
+ else:
1736
+ click.echo(result["error"], err=True)
1737
+ ctx.exit(1)
1738
+ return
1739
+
1740
+ if result["already_deleted"]:
1741
+ if json_mode:
1742
+ click.echo(
1743
+ json.dumps(
1744
+ {
1745
+ "id": quest_id,
1746
+ "deleted_at": result["deleted_at"],
1747
+ "warning": "Quest already deleted",
1748
+ }
1749
+ )
1750
+ )
1751
+ else:
1752
+ click.echo(
1753
+ f"Warning: Quest {quest_id} was already deleted on {result['deleted_at']}"
1754
+ )
1755
+ return
1756
+
1757
+ if json_mode:
1758
+ data = {"id": quest_id, "deleted_at": result["deleted_at"]}
1759
+ if cascade:
1760
+ data["cascade"] = result["cascade"]
1761
+ click.echo(json.dumps(data))
1762
+ return
1763
+
1764
+ click.echo(f"Deleted quest {quest_id}")
1765
+ if cascade and result["cascade"]:
1766
+ click.echo("Cascade deleted:")
1767
+ for mid in result["cascade"]:
1768
+ click.echo(f" {mid}")
1769
+
1770
+
1771
+ def _delete_mission(ctx, mission_id):
1772
+ """Soft-delete a mission."""
1773
+ from lore.db import delete_mission
1774
+
1775
+ project_root = ctx.obj["project_root"]
1776
+ json_mode = ctx.obj.get("json", False)
1777
+
1778
+ result = delete_mission(project_root, mission_id)
1779
+
1780
+ if not result["ok"]:
1781
+ if json_mode:
1782
+ click.echo(json.dumps({"error": result["error"]}), err=True)
1783
+ else:
1784
+ click.echo(result["error"], err=True)
1785
+ ctx.exit(1)
1786
+ return
1787
+
1788
+ if result["already_deleted"]:
1789
+ if json_mode:
1790
+ click.echo(
1791
+ json.dumps(
1792
+ {
1793
+ "id": mission_id,
1794
+ "deleted_at": result["deleted_at"],
1795
+ "warning": "Mission already deleted",
1796
+ }
1797
+ )
1798
+ )
1799
+ else:
1800
+ click.echo(
1801
+ f"Warning: Mission {mission_id} was already deleted on {result['deleted_at']}"
1802
+ )
1803
+ return
1804
+
1805
+ if json_mode:
1806
+ click.echo(json.dumps({"id": mission_id, "deleted_at": result["deleted_at"]}))
1807
+ return
1808
+
1809
+ click.echo(f"Deleted mission {mission_id}")
1810
+
1811
+
1812
+ @main.command("show")
1813
+ @click.argument("entity_id")
1814
+ @click.option(
1815
+ "--no-knight", is_flag=True, default=False, help="Omit knight file contents."
1816
+ )
1817
+ @click.option(
1818
+ "--json",
1819
+ "json_flag",
1820
+ is_flag=True,
1821
+ default=False,
1822
+ hidden=True,
1823
+ help="Output as JSON.",
1824
+ )
1825
+ @click.pass_context
1826
+ def show(ctx, entity_id, no_knight, json_flag):
1827
+ """Show details of a quest or mission."""
1828
+ json_mode = ctx.obj.get("json", False)
1829
+ if json_flag:
1830
+ ctx.obj["json"] = True
1831
+ json_mode = True
1832
+ if entity_id.startswith("q-") and "/" not in entity_id:
1833
+ # Use loose validation to allow test IDs inserted directly into the DB.
1834
+ # If loose validation fails, reject immediately with a format error.
1835
+ # If loose passes but strict fails, we still proceed to DB lookup;
1836
+ # the "not found" path handles missing quests gracefully.
1837
+ loose_err = validators.validate_quest_id_loose(entity_id)
1838
+ if loose_err:
1839
+ msg = f'Invalid quest ID format: "{entity_id}"'
1840
+ if json_mode:
1841
+ click.echo(json.dumps({"error": msg}), err=True)
1842
+ else:
1843
+ click.echo(msg, err=True)
1844
+ ctx.exit(1)
1845
+ return
1846
+ # For IDs that pass loose but not strict validation, only proceed if
1847
+ # the quest actually exists in the DB; otherwise emit a format error.
1848
+ if validators.validate_entity_id(entity_id) is not None:
1849
+ from lore.db import get_quest as _gq
1850
+
1851
+ if _gq(ctx.obj["project_root"], entity_id) is None:
1852
+ msg = f'Invalid quest ID format: "{entity_id}"'
1853
+ if json_mode:
1854
+ click.echo(json.dumps({"error": msg}), err=True)
1855
+ else:
1856
+ click.echo(msg, err=True)
1857
+ ctx.exit(1)
1858
+ return
1859
+ _show_quest(ctx, entity_id)
1860
+ elif "m-" in entity_id:
1861
+ if not _validate_mission_id(entity_id, ctx):
1862
+ return
1863
+ _show_mission(ctx, entity_id, no_knight)
1864
+ else:
1865
+ msg = f'Invalid ID format: "{entity_id}"'
1866
+ if json_mode:
1867
+ click.echo(json.dumps({"error": msg}), err=True)
1868
+ else:
1869
+ click.echo(msg, err=True)
1870
+ ctx.exit(1)
1871
+
1872
+
1873
+ def _emit_not_found(ctx, entity_id, entity_type):
1874
+ """Emit a 'not found' error, annotating with deletion timestamp if soft-deleted."""
1875
+ from lore.db import get_deleted_at
1876
+
1877
+ project_root = ctx.obj["project_root"]
1878
+ json_mode = ctx.obj.get("json", False)
1879
+ deleted_at = get_deleted_at(project_root, entity_id)
1880
+
1881
+ label = entity_type.capitalize()
1882
+ if deleted_at:
1883
+ msg = f'{label} "{entity_id}" not found (deleted on {deleted_at})'
1884
+ if json_mode:
1885
+ click.echo(json.dumps({"error": msg, "deleted_at": deleted_at}), err=True)
1886
+ else:
1887
+ click.echo(msg, err=True)
1888
+ else:
1889
+ msg = f'{label} "{entity_id}" not found'
1890
+ if json_mode:
1891
+ click.echo(json.dumps({"error": msg}), err=True)
1892
+ else:
1893
+ click.echo(msg, err=True)
1894
+ ctx.exit(1)
1895
+
1896
+
1897
+ def _dep_status_symbol(status):
1898
+ """Return a circle symbol for the given status.
1899
+
1900
+ ● closed ◕ in_progress/blocked ○ open or unknown
1901
+ """
1902
+ if status == "closed":
1903
+ return "\u25cf" # ●
1904
+ if status in ("in_progress", "blocked"):
1905
+ return "\u25d5" # ◕
1906
+ return "\u25cb" # ○
1907
+
1908
+
1909
+ def _dep_display_id(dep_id, current_quest_id):
1910
+ """Return short-form m-xxxx for intra-quest deps, fully-qualified otherwise."""
1911
+ if "/" in dep_id:
1912
+ parts = dep_id.split("/", 1)
1913
+ if parts[0] == current_quest_id:
1914
+ return parts[1]
1915
+ return dep_id
1916
+
1917
+
1918
+ def _dep_to_rich(dep, current_quest_id):
1919
+ """Convert a dep dict to a (symbol, display_id, title) display tuple."""
1920
+ deleted = dep.get("deleted_at") is not None
1921
+ title = "[unknown]" if deleted else (dep.get("title") or "[unknown]")
1922
+ status = None if deleted else dep.get("status")
1923
+ symbol = _dep_status_symbol(status)
1924
+ display_id = _dep_display_id(dep["id"], current_quest_id)
1925
+ return symbol, display_id, title
1926
+
1927
+
1928
+ def _show_mission(ctx, mission_id, no_knight):
1929
+ """Display mission detail with optional knight contents."""
1930
+ from lore.db import (
1931
+ get_mission,
1932
+ get_mission_depends_on_details,
1933
+ get_mission_blocks_details,
1934
+ get_deleted_at,
1935
+ get_board_messages,
1936
+ )
1937
+
1938
+ project_root = ctx.obj["project_root"]
1939
+ json_mode = ctx.obj.get("json", False)
1940
+ mission = get_mission(project_root, mission_id)
1941
+
1942
+ if mission is None:
1943
+ _emit_not_found(ctx, mission_id, "mission")
1944
+ return
1945
+
1946
+ # Check if parent quest is soft-deleted
1947
+ quest_deleted = False
1948
+ if mission["quest_id"]:
1949
+ quest_del_at = get_deleted_at(project_root, mission["quest_id"])
1950
+ if quest_del_at:
1951
+ quest_deleted = True
1952
+
1953
+ depends_on_details = get_mission_depends_on_details(project_root, mission_id)
1954
+ blocks_details = get_mission_blocks_details(project_root, mission_id)
1955
+ board_messages = get_board_messages(project_root, mission_id)
1956
+
1957
+ quest_id = mission["quest_id"] or ""
1958
+
1959
+ if json_mode:
1960
+ knight_contents = None
1961
+ if mission["knight"] and not no_knight:
1962
+ _knights_dir = paths.knights_dir(project_root)
1963
+ knight_name = Path(mission["knight"]).stem
1964
+ knight_path = knight_module.find_knight(_knights_dir, knight_name)
1965
+ if knight_path is not None:
1966
+ knight_contents = knight_path.read_text()
1967
+
1968
+ def _dep_to_json(dep):
1969
+ deleted = dep.get("deleted_at") is not None
1970
+ return {
1971
+ "id": dep["id"],
1972
+ "title": "[unknown]" if deleted else (dep.get("title") or "[unknown]"),
1973
+ "status": None if deleted else dep.get("status"),
1974
+ }
1975
+
1976
+ data = {
1977
+ "id": mission["id"],
1978
+ "quest_id": mission["quest_id"],
1979
+ "title": mission["title"],
1980
+ "description": mission["description"],
1981
+ "status": mission["status"],
1982
+ "priority": mission["priority"],
1983
+ "mission_type": mission["mission_type"],
1984
+ "knight": mission["knight"],
1985
+ "knight_contents": knight_contents,
1986
+ "block_reason": mission["block_reason"],
1987
+ "created_at": mission["created_at"],
1988
+ "updated_at": mission["updated_at"],
1989
+ "closed_at": mission["closed_at"],
1990
+ "dependencies": {
1991
+ "needs": [_dep_to_json(d) for d in depends_on_details],
1992
+ "blocks": [_dep_to_json(d) for d in blocks_details],
1993
+ },
1994
+ "board": [
1995
+ {
1996
+ "id": m["id"],
1997
+ "sender": m["sender"],
1998
+ "message": m["message"],
1999
+ "created_at": m["created_at"],
2000
+ }
2001
+ for m in board_messages
2002
+ ],
2003
+ }
2004
+ click.echo(json.dumps(data))
2005
+ return
2006
+
2007
+ quest_deleted_note = " (quest deleted)" if quest_deleted else ""
2008
+ click.echo(f"Mission: {mission['id']}{quest_deleted_note}")
2009
+ click.echo(f"Title: {mission['title']}")
2010
+ click.echo(f"Status: {mission['status']}")
2011
+ click.echo(f"Priority: {mission['priority']}")
2012
+ if mission["mission_type"]:
2013
+ click.echo(f"Type: {mission['mission_type']}")
2014
+ if mission["description"]:
2015
+ click.echo(f"Description: {mission['description']}")
2016
+ if mission["knight"]:
2017
+ click.echo(f"Knight: {mission['knight']}")
2018
+ if mission["block_reason"]:
2019
+ click.echo(f"Block Reason: {mission['block_reason']}")
2020
+ click.echo(f"Created: {mission['created_at']}")
2021
+ click.echo(f"Updated: {mission['updated_at']}")
2022
+ if mission["closed_at"]:
2023
+ click.echo(f"Closed: {mission['closed_at']}")
2024
+
2025
+ # Dependencies: flat Needs / Blocks sections
2026
+ if depends_on_details or blocks_details:
2027
+ click.echo("")
2028
+ click.echo("Dependencies:")
2029
+ if depends_on_details:
2030
+ click.echo(" Needs:")
2031
+ for dep in depends_on_details:
2032
+ symbol, display_id, title = _dep_to_rich(dep, quest_id)
2033
+ click.echo(f" {symbol} {display_id} {title}")
2034
+ if blocks_details:
2035
+ click.echo(" Blocks:")
2036
+ for dep in blocks_details:
2037
+ symbol, display_id, title = _dep_to_rich(dep, quest_id)
2038
+ click.echo(f" {symbol} {display_id} {title}")
2039
+
2040
+ if board_messages:
2041
+ click.echo("")
2042
+ click.echo("Board:")
2043
+ for msg in board_messages:
2044
+ if msg["sender"]:
2045
+ click.echo(
2046
+ f" [{msg['created_at']}] ({msg['sender']}) {msg['message']}"
2047
+ )
2048
+ else:
2049
+ click.echo(f" [{msg['created_at']}] {msg['message']}")
2050
+
2051
+ # Knight contents
2052
+ if mission["knight"] and not no_knight:
2053
+ _knights_dir = paths.knights_dir(project_root)
2054
+ knight_name = Path(mission["knight"]).stem
2055
+ knight_path = knight_module.find_knight(_knights_dir, knight_name)
2056
+ if knight_path is not None:
2057
+ click.echo("")
2058
+ click.echo("--- Knight Contents ---")
2059
+ click.echo(knight_path.read_text())
2060
+ else:
2061
+ click.echo("")
2062
+ click.echo(
2063
+ f'Warning: knight file "{mission["knight"]}" not found in .lore/knights/'
2064
+ )
2065
+
2066
+
2067
+ def _show_quest(ctx, quest_id):
2068
+ """Display quest detail with missions."""
2069
+ json_mode = ctx.obj.get("json", False)
2070
+
2071
+ from lore.db import (
2072
+ get_quest,
2073
+ get_missions_for_quest,
2074
+ get_board_messages,
2075
+ get_all_dependencies_for_quest,
2076
+ get_mission,
2077
+ )
2078
+
2079
+ project_root = ctx.obj["project_root"]
2080
+ quest = get_quest(project_root, quest_id)
2081
+
2082
+ if quest is None:
2083
+ _emit_not_found(ctx, quest_id, "quest")
2084
+ return
2085
+
2086
+ missions = get_missions_for_quest(project_root, quest_id)
2087
+ board_messages = get_board_messages(project_root, quest_id)
2088
+ edges = get_all_dependencies_for_quest(project_root, quest_id)
2089
+
2090
+ if json_mode:
2091
+ # Build per-mission dependency index
2092
+ # edges: from_id needs to_id; to_id blocks from_id
2093
+ mission_map = {m["id"]: m for m in missions}
2094
+ needs_map = {} # mission_id -> list of to_id (what it needs)
2095
+ blocks_map = {} # mission_id -> list of from_id (what it blocks)
2096
+ for edge in edges:
2097
+ needs_map.setdefault(edge["from_id"], []).append(edge["to_id"])
2098
+ blocks_map.setdefault(edge["to_id"], []).append(edge["from_id"])
2099
+
2100
+ def _mission_ref(mid):
2101
+ m = mission_map.get(mid)
2102
+ if m is None:
2103
+ m = get_mission(project_root, mid)
2104
+ if m is None:
2105
+ return {"id": mid, "title": "[unknown]", "status": None}
2106
+ return {"id": mid, "title": m["title"], "status": m["status"]}
2107
+
2108
+ missions_json = []
2109
+ for m in missions:
2110
+ mid = m["id"]
2111
+ needs_refs = [_mission_ref(tid) for tid in needs_map.get(mid, [])]
2112
+ blocks_refs = [_mission_ref(fid) for fid in blocks_map.get(mid, [])]
2113
+ missions_json.append(
2114
+ {
2115
+ "id": mid,
2116
+ "title": m["title"],
2117
+ "status": m["status"],
2118
+ "priority": m["priority"],
2119
+ "mission_type": m["mission_type"],
2120
+ "knight": m["knight"],
2121
+ "dependencies": {
2122
+ "needs": needs_refs,
2123
+ "blocks": blocks_refs,
2124
+ },
2125
+ }
2126
+ )
2127
+
2128
+ data = {
2129
+ "id": quest["id"],
2130
+ "title": quest["title"],
2131
+ "description": quest["description"],
2132
+ "status": quest["status"],
2133
+ "priority": quest["priority"],
2134
+ "created_at": quest["created_at"],
2135
+ "updated_at": quest["updated_at"],
2136
+ "closed_at": quest["closed_at"],
2137
+ "auto_close": bool(quest["auto_close"]),
2138
+ "missions": missions_json,
2139
+ "board": [
2140
+ {
2141
+ "id": msg["id"],
2142
+ "sender": msg["sender"],
2143
+ "message": msg["message"],
2144
+ "created_at": msg["created_at"],
2145
+ }
2146
+ for msg in board_messages
2147
+ ],
2148
+ }
2149
+ click.echo(json.dumps(data))
2150
+ return
2151
+
2152
+ click.echo(f"Quest: {quest['id']}")
2153
+ click.echo(f"Title: {quest['title']}")
2154
+ click.echo(f"Status: {quest['status']}")
2155
+ click.echo(f"Priority: {quest['priority']}")
2156
+ click.echo(f"Auto-Close: {'enabled' if quest['auto_close'] else 'disabled'}")
2157
+ if quest["description"]:
2158
+ click.echo(f"Description: {quest['description']}")
2159
+ click.echo(f"Created: {quest['created_at']}")
2160
+ click.echo(f"Updated: {quest['updated_at']}")
2161
+ if quest["closed_at"]:
2162
+ click.echo(f"Closed: {quest['closed_at']}")
2163
+
2164
+ click.echo("")
2165
+ if not missions:
2166
+ click.echo("No missions.")
2167
+ else:
2168
+ click.echo("Missions:")
2169
+ mission_ids = {m["id"] for m in missions}
2170
+
2171
+ # Filter edges to intra-quest pairs only before passing to graph module
2172
+ intra_quest_edges = [
2173
+ edge for edge in edges
2174
+ if edge["from_id"] in mission_ids and edge["to_id"] in mission_ids
2175
+ ]
2176
+ sorted_missions = graph.topological_sort_missions(missions, intra_quest_edges)
2177
+
2178
+ # Build parents_map: child_id -> [display_id of each direct parent]
2179
+ parents_map = {}
2180
+ for edge in edges:
2181
+ child = edge["from_id"]
2182
+ parent = edge["to_id"]
2183
+ if child in mission_ids:
2184
+ pdisplay = _dep_display_id(parent, quest_id)
2185
+ parents_map.setdefault(child, []).append(pdisplay)
2186
+
2187
+ # Build all base strings first, then measure max width for alignment
2188
+ lines_data = []
2189
+ for m in sorted_missions:
2190
+ symbol = _dep_status_symbol(m["status"])
2191
+ display_id = _dep_display_id(m["id"], quest_id)
2192
+ type_bracket = f" [{m['mission_type']}]" if m["mission_type"] else ""
2193
+ base = f"{symbol} {display_id} {m['title']}{type_bracket}"
2194
+ parents = parents_map.get(m["id"], [])
2195
+ lines_data.append((base, parents))
2196
+
2197
+ # Render lines with tab-aligned ← column
2198
+ has_any_parents = any(parents for _, parents in lines_data)
2199
+ if has_any_parents:
2200
+ col_width = max(len(base) for base, _ in lines_data)
2201
+ for base, parents in lines_data:
2202
+ if parents:
2203
+ click.echo(f"{base:<{col_width}} \u2190 {', '.join(parents)}")
2204
+ else:
2205
+ click.echo(base)
2206
+ else:
2207
+ for base, _ in lines_data:
2208
+ click.echo(base)
2209
+
2210
+ if board_messages:
2211
+ click.echo("")
2212
+ click.echo("Board:")
2213
+ for msg in board_messages:
2214
+ if msg["sender"]:
2215
+ click.echo(
2216
+ f" [{msg['created_at']}] ({msg['sender']}) {msg['message']}"
2217
+ )
2218
+ else:
2219
+ click.echo(f" [{msg['created_at']}] {msg['message']}")
2220
+
2221
+
2222
+ @main.group()
2223
+ @click.pass_context
2224
+ def codex(ctx):
2225
+ """Access project documentation — a set of typed markdown files maintained in .lore/codex/. Use 'lore codex list' to see all documents, 'lore codex search <keyword>' to narrow by keyword, and 'lore codex show <id>' to read one or more documents in full. Prefer 'lore codex show id1 id2' over multiple separate calls."""
2226
+ pass
2227
+
2228
+
2229
+ @codex.command("list")
2230
+ @click.option("--json", "json_flag", is_flag=True, help="Output as JSON.")
2231
+ @click.pass_context
2232
+ def codex_list(ctx, json_flag):
2233
+ """List all codex documents."""
2234
+ from lore.codex import scan_codex
2235
+
2236
+ project_root = ctx.obj["project_root"]
2237
+ json_mode = json_flag or ctx.obj.get("json", False)
2238
+ codex_dir = paths.codex_dir(project_root)
2239
+
2240
+ documents = scan_codex(codex_dir)
2241
+
2242
+ if json_mode:
2243
+ data = {
2244
+ "codex": [
2245
+ {
2246
+ "id": d["id"],
2247
+ "group": paths.derive_group(d["path"], codex_dir),
2248
+ "title": d["title"],
2249
+ "summary": d["summary"],
2250
+ }
2251
+ for d in documents
2252
+ ]
2253
+ }
2254
+ click.echo(json.dumps(data))
2255
+ return
2256
+
2257
+ if not documents:
2258
+ click.echo("No codex documents found.")
2259
+ return
2260
+
2261
+ rows = [
2262
+ [d["id"], paths.derive_group(d["path"], codex_dir), d["title"], d["summary"]]
2263
+ for d in documents
2264
+ ]
2265
+ for line in _format_table(["ID", "GROUP", "TITLE", "SUMMARY"], rows):
2266
+ click.echo(line)
2267
+
2268
+
2269
+ @codex.command("search")
2270
+ @click.argument("keyword")
2271
+ @click.pass_context
2272
+ def codex_search(ctx, keyword):
2273
+ """Search codex documents by keyword."""
2274
+ from lore.codex import search_documents
2275
+
2276
+ project_root = ctx.obj["project_root"]
2277
+ json_mode = ctx.obj.get("json", False)
2278
+ codex_dir = paths.codex_dir(project_root)
2279
+
2280
+ documents = search_documents(codex_dir, keyword)
2281
+
2282
+ if json_mode:
2283
+ data = {
2284
+ "documents": [
2285
+ {
2286
+ "id": d["id"],
2287
+ "title": d["title"],
2288
+ "summary": d["summary"],
2289
+ }
2290
+ for d in documents
2291
+ ]
2292
+ }
2293
+ click.echo(json.dumps(data))
2294
+ return
2295
+
2296
+ if not documents:
2297
+ click.echo(f'No documents matching "{keyword}".')
2298
+ return
2299
+
2300
+ col_id = max(max(len(d["id"]) for d in documents), 2)
2301
+ col_title = max(max(len(d["title"]) for d in documents), 5)
2302
+
2303
+ header = (
2304
+ f" {'ID':<{col_id}} {'TITLE':<{col_title}} SUMMARY"
2305
+ )
2306
+ click.echo(header)
2307
+ for d in documents:
2308
+ click.echo(
2309
+ f" {d['id']:<{col_id}} {d['title']:<{col_title}} {d['summary']}"
2310
+ )
2311
+
2312
+
2313
+ @codex.command("show")
2314
+ @click.argument("ids", nargs=-1, required=True)
2315
+ @click.pass_context
2316
+ def codex_show(ctx, ids):
2317
+ """Show full content of one or more codex documents."""
2318
+ from lore.codex import read_document
2319
+
2320
+ project_root = ctx.obj["project_root"]
2321
+ json_mode = ctx.obj.get("json", False)
2322
+ codex_dir = paths.codex_dir(project_root)
2323
+
2324
+ results = []
2325
+ for doc_id in dict.fromkeys(ids):
2326
+ doc = read_document(codex_dir, doc_id)
2327
+ if doc is None:
2328
+ if json_mode:
2329
+ click.echo(
2330
+ json.dumps({"error": f'Document "{doc_id}" not found'}), err=True
2331
+ )
2332
+ ctx.exit(1)
2333
+ return
2334
+ click.echo(f'Document "{doc_id}" not found', err=True)
2335
+ ctx.exit(1)
2336
+ return
2337
+ results.append(doc)
2338
+
2339
+ if json_mode:
2340
+ click.echo(json.dumps({"documents": results}))
2341
+ return
2342
+
2343
+ for doc in results:
2344
+ click.echo(f"=== {doc['id']} ===")
2345
+ click.echo(doc["body"])
2346
+
2347
+
2348
+ @codex.command("map")
2349
+ @click.argument("doc_id")
2350
+ @click.option(
2351
+ "--depth",
2352
+ type=click.IntRange(min=0),
2353
+ default=1,
2354
+ show_default=True,
2355
+ help="BFS traversal depth (0 = root only).",
2356
+ )
2357
+ @click.pass_context
2358
+ def codex_map(ctx, doc_id, depth):
2359
+ """Map a codex document cluster via BFS traversal of 'related' links."""
2360
+ from lore.codex import map_documents
2361
+
2362
+ project_root = ctx.obj["project_root"]
2363
+ json_mode = ctx.obj.get("json", False)
2364
+ codex_dir = paths.codex_dir(project_root)
2365
+
2366
+ documents = map_documents(codex_dir, doc_id, depth=depth)
2367
+
2368
+ if documents is None:
2369
+ if json_mode:
2370
+ click.echo(
2371
+ json.dumps({"error": f'Document "{doc_id}" not found'}), err=True
2372
+ )
2373
+ ctx.exit(1)
2374
+ return
2375
+ click.echo(f'Document "{doc_id}" not found', err=True)
2376
+ ctx.exit(1)
2377
+ return
2378
+
2379
+ if json_mode:
2380
+ click.echo(json.dumps({"documents": documents}))
2381
+ return
2382
+
2383
+ for doc in documents:
2384
+ click.echo(f"=== {doc['id']} ===")
2385
+ click.echo(doc["body"])
2386
+
2387
+
2388
+ @codex.command("chaos")
2389
+ @click.argument("doc_id")
2390
+ @click.option(
2391
+ "--threshold",
2392
+ type=int,
2393
+ required=True,
2394
+ help="Walk termination threshold as an integer percentage (30–100).",
2395
+ )
2396
+ @click.option(
2397
+ "--json",
2398
+ "json_flag",
2399
+ is_flag=True,
2400
+ default=False,
2401
+ help="Output as JSON.",
2402
+ )
2403
+ @click.pass_context
2404
+ def codex_chaos(ctx, doc_id, threshold, json_flag):
2405
+ """Random-walk traversal of connected codex documents from a seed ID."""
2406
+ from lore.codex import chaos_documents
2407
+
2408
+ project_root = ctx.obj["project_root"]
2409
+ json_mode = json_flag or ctx.obj.get("json", False)
2410
+
2411
+ try:
2412
+ documents = chaos_documents(project_root, doc_id, threshold=threshold)
2413
+ except ValueError as exc:
2414
+ if json_mode:
2415
+ click.echo(json.dumps({"error": str(exc)}), err=True)
2416
+ else:
2417
+ click.echo(str(exc), err=True)
2418
+ ctx.exit(1)
2419
+ return
2420
+
2421
+ if documents is None:
2422
+ if json_mode:
2423
+ click.echo(
2424
+ json.dumps({"error": f'Document "{doc_id}" not found'}), err=True
2425
+ )
2426
+ else:
2427
+ click.echo(f'Document "{doc_id}" not found', err=True)
2428
+ ctx.exit(1)
2429
+ return
2430
+
2431
+ if json_mode:
2432
+ click.echo(json.dumps({"documents": documents}))
2433
+ return
2434
+
2435
+ headers = ["ID", "TYPE", "TITLE", "SUMMARY"]
2436
+ rows = [
2437
+ [doc["id"], "", doc["title"], doc["summary"]]
2438
+ for doc in documents
2439
+ ]
2440
+ for line in _format_table(headers, rows):
2441
+ click.echo(line)
2442
+
2443
+
2444
+ @main.group()
2445
+ @click.pass_context
2446
+ def artifact(ctx):
2447
+ """Access project artifacts — reusable template files stored in .lore/artifacts/ and accessed by stable ID. Use 'lore artifact list' to see available templates and 'lore artifact show <id>' to retrieve content. Always use these commands rather than reading .lore/artifacts/ files directly. Artifacts are read-only via the CLI; maintainers create and update them on disk."""
2448
+ pass
2449
+
2450
+
2451
+ @artifact.command("list")
2452
+ @click.option("--json", "json_flag", is_flag=True, help="Output as JSON.")
2453
+ @click.pass_context
2454
+ def artifact_list(ctx, json_flag):
2455
+ """List all artifacts."""
2456
+ from lore.artifact import scan_artifacts
2457
+
2458
+ project_root = ctx.obj["project_root"]
2459
+ json_mode = json_flag or ctx.obj.get("json", False)
2460
+ artifacts_dir = paths.artifacts_dir(project_root)
2461
+
2462
+ artifacts = scan_artifacts(artifacts_dir)
2463
+
2464
+ if json_mode:
2465
+ data = {
2466
+ "artifacts": [
2467
+ {
2468
+ "id": a["id"],
2469
+ "group": a["group"],
2470
+ "title": a["title"],
2471
+ "summary": a["summary"],
2472
+ }
2473
+ for a in artifacts
2474
+ ]
2475
+ }
2476
+ click.echo(json.dumps(data))
2477
+ return
2478
+
2479
+ if not artifacts:
2480
+ click.echo("No artifacts found.")
2481
+ return
2482
+
2483
+ rows = [[a["id"], a["group"], a["title"], a["summary"]] for a in artifacts]
2484
+ for line in _format_table(["ID", "GROUP", "TITLE", "SUMMARY"], rows):
2485
+ click.echo(line)
2486
+
2487
+
2488
+ @artifact.command("show")
2489
+ @click.argument("ids", nargs=-1, required=True)
2490
+ @click.pass_context
2491
+ def artifact_show(ctx, ids):
2492
+ """Show full content of one or more artifacts."""
2493
+ from lore.artifact import read_artifact
2494
+
2495
+ project_root = ctx.obj["project_root"]
2496
+ json_mode = ctx.obj.get("json", False)
2497
+ artifacts_dir = paths.artifacts_dir(project_root)
2498
+
2499
+ results = []
2500
+ for artifact_id in dict.fromkeys(ids):
2501
+ art = read_artifact(artifacts_dir, artifact_id)
2502
+ if art is None:
2503
+ if json_mode:
2504
+ click.echo(
2505
+ json.dumps({"error": f'Artifact "{artifact_id}" not found'}),
2506
+ err=True,
2507
+ )
2508
+ ctx.exit(1)
2509
+ return
2510
+ click.echo(f'Artifact "{artifact_id}" not found', err=True)
2511
+ ctx.exit(1)
2512
+ return
2513
+ results.append(art)
2514
+
2515
+ if json_mode:
2516
+ click.echo(json.dumps({"artifacts": results}))
2517
+ return
2518
+
2519
+ for art in results:
2520
+ click.echo(f"=== {art['id']} ===")
2521
+ click.echo(art["body"])
2522
+
2523
+
2524
+ @main.group()
2525
+ @click.pass_context
2526
+ def board(ctx):
2527
+ """Manage board messages for quests and missions."""
2528
+ pass
2529
+
2530
+
2531
+ @board.command("add")
2532
+ @click.argument("entity_id")
2533
+ @click.argument("message")
2534
+ @click.option("--sender", "-s", default=None, help="Sender identifier.")
2535
+ @click.pass_context
2536
+ def board_add(ctx, entity_id, message, sender):
2537
+ """Post a message to a quest or mission board."""
2538
+ from lore.db import add_board_message
2539
+
2540
+ project_root = ctx.obj["project_root"]
2541
+ json_mode = ctx.obj.get("json", False)
2542
+
2543
+ result = add_board_message(project_root, entity_id, message, sender)
2544
+
2545
+ if not result.get("ok", False):
2546
+ error = result.get("error", "Unknown error")
2547
+ if json_mode:
2548
+ click.echo(json.dumps({"error": error}), err=True)
2549
+ else:
2550
+ click.echo(error, err=True)
2551
+ ctx.exit(1)
2552
+ return
2553
+
2554
+ if json_mode:
2555
+ click.echo(
2556
+ json.dumps(
2557
+ {
2558
+ "id": result["id"],
2559
+ "entity_id": result["entity_id"],
2560
+ "sender": result["sender"],
2561
+ "created_at": result["created_at"],
2562
+ }
2563
+ )
2564
+ )
2565
+ return
2566
+
2567
+ click.echo(f"Board message posted (id: {result['id']}).")
2568
+
2569
+
2570
+ @board.command("delete")
2571
+ @click.argument("message_id", type=int)
2572
+ @click.pass_context
2573
+ def board_delete(ctx, message_id):
2574
+ """Delete a board message by its integer ID."""
2575
+ from lore.db import delete_board_message
2576
+
2577
+ project_root = ctx.obj["project_root"]
2578
+ json_mode = ctx.obj.get("json", False)
2579
+
2580
+ result = delete_board_message(project_root, message_id)
2581
+
2582
+ if not result.get("ok", False):
2583
+ error = result.get("error", "Unknown error")
2584
+ if json_mode:
2585
+ click.echo(json.dumps({"error": error}), err=True)
2586
+ else:
2587
+ click.echo(error, err=True)
2588
+ ctx.exit(1)
2589
+ return
2590
+
2591
+ if json_mode:
2592
+ click.echo(json.dumps({"id": result["id"], "deleted_at": result["deleted_at"]}))
2593
+ return
2594
+
2595
+ click.echo(f"Board message {message_id} deleted.")
2596
+
2597
+
2598
+ # ---------------------------------------------------------------------------
2599
+ # Watcher commands
2600
+ # ---------------------------------------------------------------------------
2601
+
2602
+
2603
+ @main.group()
2604
+ @click.pass_context
2605
+ def watcher(ctx):
2606
+ """Manage watcher definitions stored in .lore/watchers/."""
2607
+ pass
2608
+
2609
+
2610
+ @watcher.command("list")
2611
+ @click.option("--json", "json_mode", is_flag=True, help="Output as JSON.")
2612
+ @click.pass_context
2613
+ def watcher_list(ctx, json_mode):
2614
+ """List all watcher definitions."""
2615
+ from lore import watcher as watcher_module
2616
+
2617
+ project_root = ctx.obj["project_root"]
2618
+ # Honour both the local --json flag and the global --json flag
2619
+ json_mode = json_mode or ctx.obj.get("json", False)
2620
+ w_dir = paths.watchers_dir(project_root)
2621
+
2622
+ watchers = watcher_module.list_watchers(w_dir)
2623
+
2624
+ if json_mode:
2625
+ click.echo(json.dumps({"watchers": watchers}))
2626
+ return
2627
+
2628
+ if not watchers:
2629
+ click.echo("No watchers found.")
2630
+ return
2631
+
2632
+ headers = ["ID", "GROUP", "TITLE", "SUMMARY"]
2633
+ rows = [[w["id"], w["group"], w["title"], w["summary"]] for w in watchers]
2634
+ for line in _format_table(headers, rows):
2635
+ click.echo(line)
2636
+
2637
+
2638
+ @watcher.command("show")
2639
+ @click.argument("name")
2640
+ @click.option("--json", "json_mode", is_flag=True, help="Output as JSON.")
2641
+ @click.pass_context
2642
+ def watcher_show(ctx, name, json_mode):
2643
+ """Show the full definition of a watcher."""
2644
+ from lore import watcher as watcher_module
2645
+
2646
+ project_root = ctx.obj["project_root"]
2647
+ json_mode = json_mode or ctx.obj.get("json", False)
2648
+ w_dir = paths.watchers_dir(project_root)
2649
+
2650
+ try:
2651
+ filepath = watcher_module.find_watcher(w_dir, name)
2652
+ except ValueError as exc:
2653
+ if json_mode:
2654
+ click.echo(json.dumps({"error": str(exc)}), err=True)
2655
+ else:
2656
+ click.echo(str(exc), err=True)
2657
+ ctx.exit(1)
2658
+
2659
+ if filepath is None:
2660
+ msg = f'Watcher "{name}" not found.'
2661
+ if json_mode:
2662
+ click.echo(json.dumps({"error": msg}), err=True)
2663
+ else:
2664
+ click.echo(msg, err=True)
2665
+ ctx.exit(1)
2666
+
2667
+ if json_mode:
2668
+ data = watcher_module.load_watcher(filepath)
2669
+ click.echo(json.dumps(data))
2670
+ else:
2671
+ click.echo(filepath.read_text(), nl=False)
2672
+
2673
+
2674
+ @watcher.command("new")
2675
+ @click.argument("name")
2676
+ @click.option("--from", "from_file", default=None, help="Read content from file instead of stdin.")
2677
+ @click.option("--json", "json_mode", is_flag=True, help="Output as JSON.")
2678
+ @click.pass_context
2679
+ def watcher_new(ctx, name, from_file, json_mode):
2680
+ """Create a new watcher definition."""
2681
+ from lore import watcher as watcher_module
2682
+
2683
+ project_root = ctx.obj["project_root"]
2684
+ json_mode = json_mode or ctx.obj.get("json", False)
2685
+ w_dir = paths.watchers_dir(project_root)
2686
+
2687
+ # Read content
2688
+ if from_file is not None:
2689
+ src = Path(from_file)
2690
+ if not src.exists():
2691
+ click.echo(f"File not found: {from_file}", err=True)
2692
+ ctx.exit(1)
2693
+ return
2694
+ content = src.read_text()
2695
+ else:
2696
+ content = click.get_text_stream("stdin").read()
2697
+
2698
+ if not content or not content.strip():
2699
+ click.echo("No content provided on stdin.", err=True)
2700
+ ctx.exit(1)
2701
+ return
2702
+
2703
+ try:
2704
+ result = watcher_module.create_watcher(w_dir, name, content)
2705
+ except ValueError as exc:
2706
+ click.echo(str(exc), err=True)
2707
+ ctx.exit(1)
2708
+ return
2709
+
2710
+ if json_mode:
2711
+ click.echo(json.dumps(result))
2712
+ else:
2713
+ click.echo(f"Created watcher {name}")
2714
+
2715
+
2716
+ @watcher.command("edit")
2717
+ @click.argument("name")
2718
+ @click.option("--from", "from_file", default=None, help="Read content from file instead of stdin.")
2719
+ @click.option("--json", "json_mode", is_flag=True, help="Output as JSON.")
2720
+ @click.pass_context
2721
+ def watcher_edit(ctx, name, from_file, json_mode):
2722
+ """Update an existing watcher definition in place."""
2723
+ from lore import watcher as watcher_module
2724
+
2725
+ project_root = ctx.obj["project_root"]
2726
+ json_mode = json_mode or ctx.obj.get("json", False)
2727
+ w_dir = paths.watchers_dir(project_root)
2728
+
2729
+ # Read content
2730
+ if from_file is not None:
2731
+ src = Path(from_file)
2732
+ if not src.exists():
2733
+ click.echo(f"File not found: {from_file}", err=True)
2734
+ ctx.exit(1)
2735
+ return
2736
+ content = src.read_text()
2737
+ else:
2738
+ content = click.get_text_stream("stdin").read()
2739
+
2740
+ if not content or not content.strip():
2741
+ click.echo("No content provided on stdin.", err=True)
2742
+ ctx.exit(1)
2743
+ return
2744
+
2745
+ try:
2746
+ result = watcher_module.update_watcher(w_dir, name, content)
2747
+ except ValueError as exc:
2748
+ if json_mode:
2749
+ click.echo(json.dumps({"error": str(exc)}))
2750
+ else:
2751
+ click.echo(str(exc), err=True)
2752
+ ctx.exit(1)
2753
+ return
2754
+
2755
+ if json_mode:
2756
+ click.echo(json.dumps(result))
2757
+ else:
2758
+ click.echo(f"Updated watcher {name}")
2759
+
2760
+
2761
+ @watcher.command("delete")
2762
+ @click.argument("name")
2763
+ @click.option("--json", "json_mode", is_flag=True, help="Output as JSON.")
2764
+ @click.pass_context
2765
+ def watcher_delete(ctx, name, json_mode):
2766
+ """Soft-delete a watcher definition (renames to .yaml.deleted)."""
2767
+ from lore import watcher as watcher_module
2768
+
2769
+ project_root = ctx.obj["project_root"]
2770
+ json_mode = json_mode or ctx.obj.get("json", False)
2771
+ w_dir = paths.watchers_dir(project_root)
2772
+
2773
+ try:
2774
+ result = watcher_module.delete_watcher(w_dir, name)
2775
+ except ValueError as exc:
2776
+ if json_mode:
2777
+ click.echo(json.dumps({"error": str(exc)}))
2778
+ else:
2779
+ click.echo(str(exc), err=True)
2780
+ ctx.exit(1)
2781
+ return
2782
+
2783
+ if json_mode:
2784
+ click.echo(json.dumps(result))
2785
+ else:
2786
+ click.echo(f"Deleted watcher {name}")