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/doctrine.py ADDED
@@ -0,0 +1,271 @@
1
+ """Doctrine loading and validation."""
2
+
3
+ import textwrap
4
+ from pathlib import Path
5
+
6
+ import yaml
7
+
8
+ from lore.paths import derive_group
9
+
10
+
11
+ class DoctrineError(Exception):
12
+ """Raised when a doctrine fails validation."""
13
+
14
+
15
+ def scaffold_doctrine(name: str) -> str:
16
+ """Return a minimal valid doctrine YAML skeleton for the given name."""
17
+ return textwrap.dedent(f"""\
18
+ id: {name}
19
+ title: {name.capitalize()}
20
+ summary: A short summary of the {name} doctrine.
21
+ description: A longer description of the {name} doctrine.
22
+ steps:
23
+ - name: Example step
24
+ description: Describe what this step does.
25
+ """)
26
+
27
+
28
+ def load_doctrine(filepath: Path) -> dict:
29
+ """Load and validate a doctrine YAML file.
30
+
31
+ Returns the parsed doctrine dict on success.
32
+ Raises DoctrineError on validation failure.
33
+ """
34
+ text = filepath.read_text()
35
+ data = _parse_yaml(text)
36
+ _validate(data, filepath.name)
37
+ return _normalize(data)
38
+
39
+
40
+ def _parse_yaml(text: str) -> dict:
41
+ """Parse YAML text and ensure it is a mapping.
42
+
43
+ Raises DoctrineError on parse failure or non-dict content.
44
+ """
45
+ try:
46
+ data = yaml.safe_load(text)
47
+ except yaml.YAMLError as e:
48
+ raise DoctrineError(f"YAML parsing error: {e}") from e
49
+
50
+ if not isinstance(data, dict):
51
+ raise DoctrineError("Doctrine must be a YAML mapping")
52
+
53
+ return data
54
+
55
+
56
+ def _validate(data: dict, filename: str) -> None:
57
+ """Validate doctrine data against schema rules."""
58
+ _validate_required_fields(data)
59
+
60
+ # Name must match filename
61
+ expected_name = filename.removesuffix(".yaml")
62
+ if data["name"] != expected_name:
63
+ raise DoctrineError(
64
+ f'Doctrine name "{data["name"]}" does not match filename "{filename}"'
65
+ )
66
+
67
+ _validate_steps(data["steps"])
68
+
69
+
70
+ def _validate_required_fields(data: dict) -> None:
71
+ """Check that required top-level fields are present."""
72
+ for field in ("name", "description", "steps"):
73
+ if field not in data:
74
+ raise DoctrineError(f"Missing required field: {field}")
75
+
76
+
77
+ def _validate_steps(steps) -> None:
78
+ """Validate the steps list: structure, fields, deps, and cycles."""
79
+ if not isinstance(steps, list) or len(steps) == 0:
80
+ raise DoctrineError("Steps must be a non-empty list")
81
+
82
+ seen_ids = set()
83
+ for i, step in enumerate(steps):
84
+ if not isinstance(step, dict):
85
+ raise DoctrineError(f"Step {i} must be a mapping")
86
+
87
+ if "id" not in step:
88
+ raise DoctrineError(f"Step {i} missing required field: id")
89
+ if "title" not in step:
90
+ raise DoctrineError(f'Step "{step["id"]}" missing required field: title')
91
+
92
+ step_id = step["id"]
93
+ if step_id in seen_ids:
94
+ raise DoctrineError(f'Duplicate step id: "{step_id}"')
95
+ seen_ids.add(step_id)
96
+
97
+ if "priority" in step:
98
+ pri = step["priority"]
99
+ if not isinstance(pri, int) or pri < 0 or pri > 4:
100
+ raise DoctrineError(
101
+ f'Step "{step_id}" has invalid priority: {pri} (must be 0-4)'
102
+ )
103
+
104
+ if "type" in step and not isinstance(step["type"], str):
105
+ raise DoctrineError(f'Step "{step_id}" type must be a string')
106
+
107
+ for step in steps:
108
+ for dep in step.get("needs", []):
109
+ if dep not in seen_ids:
110
+ raise DoctrineError(
111
+ f'Step "{step["id"]}" references unknown dependency "{dep}"'
112
+ )
113
+
114
+ _check_cycles(steps)
115
+
116
+
117
+ def _check_cycles(steps: list[dict]) -> None:
118
+ """Detect dependency cycles using DFS."""
119
+ # Build adjacency: step_id -> list of step_ids it depends on
120
+ graph = {}
121
+ for step in steps:
122
+ graph[step["id"]] = step.get("needs", [])
123
+
124
+ WHITE, GRAY, BLACK = 0, 1, 2
125
+ color = {sid: WHITE for sid in graph}
126
+
127
+ def dfs(node):
128
+ color[node] = GRAY
129
+ for neighbor in graph.get(node, []):
130
+ if color[neighbor] == GRAY:
131
+ raise DoctrineError(
132
+ f'Dependency cycle detected involving step "{node}"'
133
+ )
134
+ if color[neighbor] == WHITE:
135
+ dfs(neighbor)
136
+ color[node] = BLACK
137
+
138
+ for node in graph:
139
+ if color[node] == WHITE:
140
+ dfs(node)
141
+
142
+
143
+ def _normalize(data: dict) -> dict:
144
+ """Normalize doctrine data, applying defaults."""
145
+ steps = []
146
+ for step in data["steps"]:
147
+ steps.append(
148
+ {
149
+ "id": step["id"],
150
+ "title": step["title"],
151
+ "priority": step.get("priority", 2),
152
+ "type": step.get("type", None),
153
+ "needs": step.get("needs", []),
154
+ "knight": step.get("knight"),
155
+ "notes": step.get("notes"),
156
+ }
157
+ )
158
+ result = {
159
+ "name": data["name"],
160
+ "description": data["description"],
161
+ "steps": steps,
162
+ }
163
+ for key in ("id", "title", "summary"):
164
+ if key in data:
165
+ result[key] = data[key]
166
+ return result
167
+
168
+
169
+ def validate_doctrine_content(text: str, expected_name: str) -> dict:
170
+ """Validate raw doctrine YAML text against schema rules.
171
+
172
+ Returns the parsed data dict on success.
173
+ Raises DoctrineError on validation failure.
174
+ """
175
+ data = _parse_yaml(text)
176
+
177
+ _validate_required_fields(data)
178
+
179
+ # Name must match command argument
180
+ if str(data["name"]) != expected_name:
181
+ raise DoctrineError(
182
+ f'Doctrine name "{data["name"]}" does not match command argument "{expected_name}"'
183
+ )
184
+
185
+ # If id field is present, it must match the command argument
186
+ if "id" in data and str(data["id"]) != expected_name:
187
+ raise DoctrineError(
188
+ f'Doctrine id "{data["id"]}" does not match command argument "{expected_name}"'
189
+ )
190
+
191
+ _validate_steps(data["steps"])
192
+
193
+ return data
194
+
195
+
196
+ def _truncate_description(text: str, width: int = 80) -> str:
197
+ """Truncate a description to approximately ``width`` characters at a word boundary.
198
+
199
+ If ``text`` fits within ``width`` characters, returns it unchanged.
200
+ Otherwise returns the longest prefix that ends on a word boundary and appends "...".
201
+ The total length of the returned string is at most ``width + 3`` characters.
202
+ """
203
+ if len(text) <= width:
204
+ return text
205
+ # Truncate to width chars then backtrack to last space
206
+ truncated = text[:width]
207
+ last_space = truncated.rfind(" ")
208
+ if last_space > 0:
209
+ truncated = truncated[:last_space]
210
+ return truncated + "..."
211
+
212
+
213
+ def list_doctrines(doctrines_dir: Path) -> list[dict]:
214
+ """List all doctrines with validation status.
215
+
216
+ Returns a list of dicts with keys: id, group, title, summary, valid, name,
217
+ filename, description, and optional errors.
218
+
219
+ Fallback behaviour when metadata is missing:
220
+ - ``id``: filename stem
221
+ - ``title``: id value
222
+ - ``summary``: explicit summary field; if absent, description truncated to
223
+ ~80 chars; if neither present, empty string
224
+ - ``group``: derived from subdirectory path
225
+ """
226
+ if not doctrines_dir.exists():
227
+ return []
228
+
229
+ results = []
230
+ for filepath in sorted(doctrines_dir.rglob("*.yaml")):
231
+ stem = filepath.stem
232
+ entry = {"name": stem, "filename": filepath.name}
233
+ # Always read raw YAML for enriched metadata fields
234
+ try:
235
+ raw_text = filepath.read_text()
236
+ raw = yaml.safe_load(raw_text)
237
+ if not isinstance(raw, dict):
238
+ raw = {}
239
+ except Exception:
240
+ raw = {}
241
+ try:
242
+ doctrine = load_doctrine(filepath)
243
+ entry["description"] = doctrine["description"]
244
+ entry["valid"] = True
245
+ except DoctrineError as e:
246
+ entry["description"] = raw.get("description", "") or ""
247
+ entry["valid"] = False
248
+ entry["errors"] = [str(e)]
249
+ except Exception:
250
+ entry["description"] = ""
251
+ entry["valid"] = False
252
+ entry["errors"] = ["Failed to parse YAML"]
253
+
254
+ # Enriched fields
255
+ doctrine_id = str(raw["id"]) if "id" in raw and raw["id"] is not None else stem
256
+ title = str(raw["title"]) if "title" in raw and raw["title"] is not None else doctrine_id
257
+ if "summary" in raw and raw["summary"] is not None:
258
+ summary = str(raw["summary"])
259
+ elif entry.get("description"):
260
+ summary = _truncate_description(str(entry["description"]))
261
+ else:
262
+ summary = ""
263
+
264
+ entry["id"] = doctrine_id
265
+ entry["group"] = derive_group(filepath, doctrines_dir)
266
+ entry["title"] = title
267
+ entry["summary"] = summary
268
+
269
+ results.append(entry)
270
+
271
+ return results
lore/frontmatter.py ADDED
@@ -0,0 +1,96 @@
1
+ """Shared frontmatter parsing for markdown files with YAML front matter.
2
+
3
+ Replaces the near-identical private ``_parse_doc`` and ``_parse_artifact``
4
+ functions that previously existed separately in ``codex.py`` and
5
+ ``artifact.py``.
6
+ """
7
+
8
+ from pathlib import Path
9
+
10
+ import yaml
11
+
12
+ _REQUIRED_FIELDS = ("id", "title", "summary")
13
+
14
+
15
+ def parse_frontmatter_doc(
16
+ filepath: Path,
17
+ required_fields: tuple[str, ...] | None = None,
18
+ extra_fields: tuple[str, ...] = (),
19
+ ) -> dict | None:
20
+ """Read frontmatter metadata only from a markdown file.
21
+
22
+ Returns a record dict with keys for each field in ``required_fields`` plus
23
+ ``path`` if all required fields are present. Returns ``None`` if required
24
+ fields are missing, YAML is invalid, or the file has fewer than three
25
+ ``---``-separated parts.
26
+
27
+ When ``required_fields`` is not provided, defaults to the module-level
28
+ ``_REQUIRED_FIELDS`` (``id``, ``title``, ``summary``) for
29
+ backward compatibility.
30
+
31
+ Reads the file exactly once.
32
+ """
33
+ effective_required = required_fields if required_fields is not None else _REQUIRED_FIELDS
34
+
35
+ try:
36
+ text = filepath.read_text()
37
+ parts = text.split("---")
38
+ if len(parts) < 3:
39
+ return None
40
+ frontmatter = yaml.safe_load(parts[1])
41
+ except Exception:
42
+ return None
43
+
44
+ if not isinstance(frontmatter, dict):
45
+ return None
46
+ if any(field not in frontmatter or frontmatter[field] is None for field in effective_required):
47
+ return None
48
+
49
+ result = {field: str(frontmatter[field]) for field in effective_required}
50
+ result["path"] = filepath
51
+ for field in extra_fields:
52
+ if field in frontmatter:
53
+ result[field] = frontmatter[field]
54
+ return result
55
+
56
+
57
+ def parse_frontmatter_doc_full(
58
+ filepath: Path,
59
+ required_fields: tuple[str, ...] | None = None,
60
+ extra_fields: tuple[str, ...] = (),
61
+ ) -> dict | None:
62
+ """Read frontmatter metadata and document body from a markdown file.
63
+
64
+ Returns the same dict as ``parse_frontmatter_doc`` plus a ``body`` key
65
+ containing all content after the second ``---`` delimiter, with leading
66
+ newlines stripped.
67
+
68
+ Returns ``None`` under the same conditions as ``parse_frontmatter_doc``.
69
+
70
+ Reads the file exactly once, eliminating the double-read pattern.
71
+ """
72
+ effective_required = required_fields if required_fields is not None else _REQUIRED_FIELDS
73
+
74
+ try:
75
+ text = filepath.read_text()
76
+ parts = text.split("---", 2)
77
+ if len(parts) < 3:
78
+ return None
79
+ frontmatter = yaml.safe_load(parts[1])
80
+ except Exception:
81
+ return None
82
+
83
+ if not isinstance(frontmatter, dict):
84
+ return None
85
+ if any(field not in frontmatter or frontmatter[field] is None for field in effective_required):
86
+ return None
87
+
88
+ body = parts[2].lstrip("\n")
89
+
90
+ result = {field: str(frontmatter[field]) for field in effective_required}
91
+ result["path"] = filepath
92
+ result["body"] = body
93
+ for field in extra_fields:
94
+ if field in frontmatter:
95
+ result[field] = frontmatter[field]
96
+ return result
lore/graph.py ADDED
@@ -0,0 +1,73 @@
1
+ """Graph algorithms on mission dependency sets."""
2
+
3
+ from collections import deque
4
+
5
+
6
+ def topological_sort_missions(
7
+ missions: list[dict],
8
+ edges: list[dict],
9
+ ) -> list[dict]:
10
+ """Sort missions into topological order based on dependency edges.
11
+
12
+ Uses Kahn's algorithm. Original input order is used as a tiebreaker for
13
+ missions at the same topological level.
14
+
15
+ The caller is responsible for filtering edges to intra-quest pairs only
16
+ before calling this function.
17
+
18
+ If a cycle is detected (not all missions visited after the BFS completes),
19
+ the unvisited missions are appended in their original input order without
20
+ raising an exception.
21
+
22
+ Args:
23
+ missions: List of mission dicts, each with at minimum an ``"id"`` key.
24
+ edges: List of dependency edge dicts, each with ``"from_id"`` (the
25
+ dependent mission) and ``"to_id"`` (the dependency) keys.
26
+
27
+ Returns:
28
+ The same mission dicts reordered so that a mission's dependencies
29
+ appear before it in the list.
30
+ """
31
+ mission_ids = {m["id"] for m in missions}
32
+
33
+ # Build in_degree and children_of for Kahn's algorithm
34
+ in_degree = {m["id"]: 0 for m in missions}
35
+ children_of: dict[str, list[str]] = {} # parent_id -> [child_id]
36
+
37
+ for edge in edges:
38
+ parent = edge["to_id"]
39
+ child = edge["from_id"]
40
+ if parent in mission_ids and child in mission_ids:
41
+ in_degree[child] += 1
42
+ children_of.setdefault(parent, []).append(child)
43
+
44
+ # Seed queue with missions that have no intra-quest parents (in original order)
45
+ queue = deque(m["id"] for m in missions if in_degree[m["id"]] == 0)
46
+ mission_map = {m["id"]: m for m in missions}
47
+ # Track original index for stable ordering within same topological level
48
+ original_index = {m["id"]: i for i, m in enumerate(missions)}
49
+
50
+ sorted_missions: list[dict] = []
51
+ visited: set[str] = set()
52
+ while queue:
53
+ mid = queue.popleft()
54
+ if mid in visited:
55
+ continue
56
+ visited.add(mid)
57
+ sorted_missions.append(mission_map[mid])
58
+ # Push children whose in-degree reaches 0, sorted by original index
59
+ children = children_of.get(mid, [])
60
+ ready_children = []
61
+ for child_id in children:
62
+ in_degree[child_id] -= 1
63
+ if in_degree[child_id] == 0:
64
+ ready_children.append(child_id)
65
+ ready_children.sort(key=lambda cid: original_index.get(cid, 0))
66
+ queue.extend(ready_children)
67
+
68
+ # Cycle safety: append any unvisited missions in original order
69
+ for m in missions:
70
+ if m["id"] not in visited:
71
+ sorted_missions.append(m)
72
+
73
+ return sorted_missions
lore/ids.py ADDED
@@ -0,0 +1,16 @@
1
+ """Hash-based ID generation."""
2
+
3
+ import uuid
4
+
5
+
6
+ def generate_id(prefix: str, existing_ids: set[str]) -> str:
7
+ """Generate a short hex ID with the given prefix.
8
+
9
+ Tries 4, 5, then 6 character lengths to avoid collisions.
10
+ """
11
+ hex_str = uuid.uuid4().hex
12
+ for length in (4, 5, 6):
13
+ candidate = f"{prefix}-{hex_str[:length]}"
14
+ if candidate not in existing_ids:
15
+ return candidate
16
+ raise RuntimeError(f"ID collision after 6 chars for prefix {prefix}")
lore/init.py ADDED
@@ -0,0 +1,137 @@
1
+ """Project initialization logic for `lore init`."""
2
+
3
+ from importlib import resources
4
+ from pathlib import Path
5
+
6
+ from lore.db import init_database
7
+
8
+
9
+ def _copy_defaults_tree(
10
+ source_package: str,
11
+ target_dir: Path,
12
+ exclude: set[str] | None = None,
13
+ label: str | None = None,
14
+ ) -> list[str]:
15
+ """Copy default files from a nested package subdirectory tree, overwriting existing files.
16
+
17
+ Args:
18
+ source_package: Subdirectory name within ``lore.defaults`` to copy from.
19
+ target_dir: Destination directory where files are written.
20
+ exclude: Optional set of directory names to skip at the top level.
21
+ label: Prefix used in status messages instead of ``source_package``.
22
+ Useful when the target path differs from the package name.
23
+
24
+ Returns:
25
+ List of human-readable status messages (one per file copied).
26
+ """
27
+ messages = []
28
+ source_root = resources.files("lore.defaults").joinpath(source_package)
29
+
30
+ def _walk(node, rel: Path) -> None:
31
+ for item in node.iterdir():
32
+ if item.is_dir():
33
+ if exclude and item.name in exclude:
34
+ continue
35
+ _walk(item, rel / item.name)
36
+ elif item.is_file():
37
+ dest = target_dir / rel / item.name
38
+ dest.parent.mkdir(parents=True, exist_ok=True)
39
+ verb = "Updated" if dest.exists() else "Created"
40
+ dest.write_text(item.read_text())
41
+ messages.append(
42
+ f" {verb} {label or source_package}/{(rel / item.name).as_posix()}"
43
+ )
44
+
45
+ _walk(source_root, Path())
46
+ return messages
47
+
48
+
49
+ def run_init() -> list[str]:
50
+ """Run the full lore init sequence in the current working directory.
51
+
52
+ Returns a list of human-readable status messages.
53
+ """
54
+ cwd = Path.cwd()
55
+ lore_dir = cwd / ".lore"
56
+ messages = []
57
+
58
+ # Step 1: Create .lore/ directory
59
+ if lore_dir.is_dir():
60
+ messages.append(" .lore/ directory already exists")
61
+ else:
62
+ lore_dir.mkdir()
63
+ messages.append(" Created .lore/ directory")
64
+
65
+ # Step 2: Create .lore/.gitignore
66
+ gitignore_path = lore_dir / ".gitignore"
67
+ default_gitignore = (
68
+ resources.files("lore.defaults").joinpath("gitignore").read_text()
69
+ )
70
+ verb = "Updated" if gitignore_path.exists() else "Created"
71
+ gitignore_path.write_text(default_gitignore)
72
+ messages.append(f" {verb} .gitignore")
73
+
74
+ # Step 3: Create/verify .lore/lore.db
75
+ db_path = lore_dir / "lore.db"
76
+ db_status = init_database(db_path)
77
+ match db_status:
78
+ case "created":
79
+ messages.append(" Created lore.db (schema version 1)")
80
+ case "existing":
81
+ messages.append(" Skipped lore.db (already exists)")
82
+ case "reinitialized":
83
+ messages.append(
84
+ " Warning: Existing database appears corrupted. Reinitialized lore.db"
85
+ )
86
+
87
+ # Step 4: Copy default doctrines
88
+ messages.extend(
89
+ _copy_defaults_tree(
90
+ "doctrines", lore_dir / "doctrines" / "default", label="doctrines/default"
91
+ )
92
+ )
93
+
94
+ # Step 5: Copy default knights
95
+ messages.extend(
96
+ _copy_defaults_tree(
97
+ "knights", lore_dir / "knights" / "default", label="knights/default"
98
+ )
99
+ )
100
+
101
+ # Step 6: Copy default artifacts
102
+ messages.extend(
103
+ _copy_defaults_tree(
104
+ "artifacts",
105
+ lore_dir / "artifacts" / "default",
106
+ exclude={"bootstrap"},
107
+ label="artifacts/default",
108
+ )
109
+ )
110
+
111
+ # Step 8: Copy default watchers
112
+ messages.extend(
113
+ _copy_defaults_tree(
114
+ "watchers", lore_dir / "watchers" / "default", label="watchers/default"
115
+ )
116
+ )
117
+
118
+ # Step 9: Seed LORE-AGENT.md
119
+ lore_agent_path = lore_dir / "LORE-AGENT.md"
120
+ lore_agent_content = resources.files("lore.defaults").joinpath("LORE-AGENT.md").read_text()
121
+ verb = "Updated" if lore_agent_path.exists() else "Created"
122
+ lore_agent_path.write_text(lore_agent_content)
123
+ messages.append(f" {verb} LORE-AGENT.md")
124
+
125
+ # Step 10: Seed GETTING-STARTED.md
126
+ getting_started_path = lore_dir / "GETTING-STARTED.md"
127
+ getting_started_content = resources.files("lore.defaults").joinpath("GETTING-STARTED.md").read_text()
128
+ verb = "Updated" if getting_started_path.exists() else "Created"
129
+ getting_started_path.write_text(getting_started_content)
130
+ messages.append(f" {verb} GETTING-STARTED.md")
131
+
132
+ # Step 11: Copy default skills
133
+ messages.extend(
134
+ _copy_defaults_tree("skills", lore_dir / "skills", label="skills")
135
+ )
136
+
137
+ return messages
lore/knight.py ADDED
@@ -0,0 +1,97 @@
1
+ """Knight filesystem operations.
2
+
3
+ Provides discovery and resolution of knight markdown files stored under
4
+ the ``.lore/knights/`` directory. Mirrors ``doctrine.py`` in structure.
5
+ """
6
+
7
+ from pathlib import Path
8
+
9
+ import yaml
10
+
11
+ from lore.paths import derive_group
12
+
13
+
14
+ def _parse_knight_frontmatter(filepath: Path) -> dict:
15
+ """Parse frontmatter from a knight markdown file.
16
+
17
+ Returns a dict with whatever fields are present in frontmatter.
18
+ Returns an empty dict if the file has no frontmatter or the YAML is invalid.
19
+ """
20
+ try:
21
+ text = filepath.read_text()
22
+ parts = text.split("---")
23
+ if len(parts) < 3:
24
+ return {}
25
+ frontmatter = yaml.safe_load(parts[1])
26
+ if not isinstance(frontmatter, dict):
27
+ return {}
28
+ return frontmatter
29
+ except Exception:
30
+ return {}
31
+
32
+
33
+ def list_knights(knights_dir: Path) -> list[dict]:
34
+ """Return a sorted list of knight records from the given directory tree.
35
+
36
+ Each record is a dict with keys ``id``, ``group``, ``title``, ``summary``,
37
+ ``name`` (file stem), and ``filename`` (full filename). Results are sorted
38
+ by id.
39
+
40
+ Fallback behaviour when metadata is missing:
41
+ - ``id``: filename stem
42
+ - ``title``: id value
43
+ - ``summary``: empty string
44
+ - ``group``: derived from subdirectory path
45
+
46
+ If ``knights_dir`` does not exist, returns an empty list.
47
+ """
48
+ if not knights_dir.exists():
49
+ return []
50
+
51
+ records = []
52
+ for filepath in knights_dir.rglob("*.md"):
53
+ stem = filepath.stem
54
+ fm = _parse_knight_frontmatter(filepath)
55
+ knight_id = str(fm["id"]) if "id" in fm and fm["id"] is not None else stem
56
+ title = str(fm["title"]) if "title" in fm and fm["title"] is not None else knight_id
57
+ summary = str(fm["summary"]) if "summary" in fm and fm["summary"] is not None else ""
58
+ group = derive_group(filepath, knights_dir)
59
+ records.append({
60
+ "id": knight_id,
61
+ "group": group,
62
+ "title": title,
63
+ "summary": summary,
64
+ "name": stem,
65
+ "filename": filepath.name,
66
+ })
67
+
68
+ return sorted(records, key=lambda r: r["id"])
69
+
70
+
71
+ def find_knight(knights_dir: Path, name: str) -> Path | None:
72
+ """Resolve a knight name to its file path.
73
+
74
+ Returns the Path to the knight file if found, or None if not found.
75
+
76
+ Raises ValueError immediately if ``name`` contains ``/`` or ``\\``
77
+ (path-traversal guard).
78
+
79
+ Resolution order:
80
+ 1. Direct path: ``knights_dir / f"{name}.md"``
81
+ 2. Fallback: first result of ``rglob(f"{name}.md")``
82
+ """
83
+ if "/" in name or "\\" in name:
84
+ raise ValueError("Invalid knight name: path separators not allowed")
85
+
86
+ if not knights_dir.exists():
87
+ return None
88
+
89
+ direct = knights_dir / f"{name}.md"
90
+ if direct.exists():
91
+ return direct
92
+
93
+ matches = list(knights_dir.rglob(f"{name}.md"))
94
+ if matches:
95
+ return matches[0]
96
+
97
+ return None
@@ -0,0 +1 @@
1
+ """Schema migration functions."""