@grifhinz/logics-manager 2.1.1 → 2.2.0

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.
@@ -8,6 +8,7 @@ from os import path as os_path
8
8
  from pathlib import Path
9
9
 
10
10
  from .config import find_repo_root
11
+ from .path_utils import resolve_repo_output_path
11
12
 
12
13
 
13
14
  @dataclass(frozen=True)
@@ -91,7 +92,7 @@ def index_payload(repo_root: Path, *, out: str = "logics/INDEX.md") -> dict[str,
91
92
  for title, rel_dir, show_progress in SECTION_DEFINITIONS:
92
93
  sections.append((title, _collect_entries(repo_root, rel_dir), show_progress))
93
94
 
94
- out_path = (repo_root / out).resolve()
95
+ out_path, output_path = resolve_repo_output_path(repo_root, out)
95
96
  out_dir = out_path.parent
96
97
  content = "\n".join(
97
98
  [
@@ -104,15 +105,10 @@ def index_payload(repo_root: Path, *, out: str = "logics/INDEX.md") -> dict[str,
104
105
  out_path.parent.mkdir(parents=True, exist_ok=True)
105
106
  out_path.write_text(content, encoding="utf-8")
106
107
 
107
- try:
108
- printable = out_path.relative_to(repo_root)
109
- except ValueError:
110
- printable = out_path
111
-
112
108
  counts = {key: len(entries) for key, (_, entries, _) in zip(SECTION_COUNT_KEYS, sections)}
113
109
  return {
114
110
  "ok": True,
115
- "output_path": printable.as_posix(),
111
+ "output_path": output_path,
116
112
  "counts": counts,
117
113
  }
118
114
 
@@ -0,0 +1,418 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ import shlex
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+
10
+ WORKFLOW_KINDS = ("request", "backlog", "task")
11
+ COMPANION_KINDS = ("product", "architecture")
12
+ OPEN_STATUSES = {"Draft", "Ready", "In progress", "Blocked"}
13
+ CLOSED_STATUSES = {"Done", "Archived"}
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class LogicsDoc:
18
+ kind: str
19
+ path: Path
20
+ rel_path: str
21
+ ref: str
22
+ title: str
23
+ status: str | None
24
+ progress: int | None
25
+ content: str
26
+
27
+
28
+ def _doc_dirs(repo_root: Path) -> dict[str, Path]:
29
+ return {
30
+ "request": repo_root / "logics" / "request",
31
+ "backlog": repo_root / "logics" / "backlog",
32
+ "task": repo_root / "logics" / "tasks",
33
+ "product": repo_root / "logics" / "product",
34
+ "architecture": repo_root / "logics" / "architecture",
35
+ }
36
+
37
+
38
+ def _progress_value(raw: str | None) -> int | None:
39
+ if raw is None:
40
+ return None
41
+ match = re.search(r"(\d+)", raw)
42
+ if not match:
43
+ return None
44
+ return max(0, min(100, int(match.group(1))))
45
+
46
+
47
+ def _parse_doc(repo_root: Path, kind: str, path: Path) -> LogicsDoc:
48
+ content = path.read_text(encoding="utf-8")
49
+ title = "(missing title)"
50
+ status: str | None = None
51
+ progress: int | None = None
52
+ for line in content.splitlines():
53
+ if line.startswith("## "):
54
+ heading = line.removeprefix("## ").strip()
55
+ if " - " in heading:
56
+ _, title = heading.split(" - ", 1)
57
+ else:
58
+ title = heading
59
+ continue
60
+ if line.startswith("> Status:"):
61
+ status = line.split(":", 1)[1].strip()
62
+ continue
63
+ if line.startswith("> Progress:"):
64
+ progress = _progress_value(line.split(":", 1)[1].strip())
65
+ continue
66
+ return LogicsDoc(
67
+ kind=kind,
68
+ path=path,
69
+ rel_path=path.relative_to(repo_root).as_posix(),
70
+ ref=path.stem,
71
+ title=title,
72
+ status=status,
73
+ progress=progress,
74
+ content=content,
75
+ )
76
+
77
+
78
+ def collect_logics_docs(repo_root: Path, *, kinds: tuple[str, ...] = WORKFLOW_KINDS + COMPANION_KINDS) -> list[LogicsDoc]:
79
+ docs: list[LogicsDoc] = []
80
+ for kind, directory in _doc_dirs(repo_root).items():
81
+ if kind not in kinds or not directory.is_dir():
82
+ continue
83
+ for path in sorted(directory.glob("*.md")):
84
+ docs.append(_parse_doc(repo_root, kind, path))
85
+ return docs
86
+
87
+
88
+ def _status_counts(docs: list[LogicsDoc]) -> dict[str, dict[str, int]]:
89
+ counts: dict[str, dict[str, int]] = {}
90
+ for doc in docs:
91
+ status = doc.status or "(missing)"
92
+ counts.setdefault(doc.kind, {})
93
+ counts[doc.kind][status] = counts[doc.kind].get(status, 0) + 1
94
+ return counts
95
+
96
+
97
+ def _doc_summary(doc: LogicsDoc) -> dict[str, object]:
98
+ return {
99
+ "ref": doc.ref,
100
+ "title": doc.title,
101
+ "kind": doc.kind,
102
+ "status": doc.status,
103
+ "progress": doc.progress,
104
+ "path": doc.rel_path,
105
+ }
106
+
107
+
108
+ def status_payload(repo_root: Path, *, limit: int = 10) -> dict[str, object]:
109
+ docs = collect_logics_docs(repo_root, kinds=WORKFLOW_KINDS)
110
+ open_docs = [doc for doc in docs if doc.status not in CLOSED_STATUSES]
111
+ active_tasks = [
112
+ doc
113
+ for doc in open_docs
114
+ if doc.kind == "task" and doc.status in {"Ready", "In progress", "Blocked"}
115
+ ]
116
+ ready_backlog = [
117
+ doc
118
+ for doc in open_docs
119
+ if doc.kind == "backlog" and doc.status in {"Ready", "In progress", "Blocked"}
120
+ ]
121
+ task_text = "\n".join(doc.content for doc in docs if doc.kind == "task")
122
+ backlog_without_task = [doc for doc in ready_backlog if doc.ref not in task_text]
123
+ draft_requests = [doc for doc in open_docs if doc.kind == "request" and doc.status == "Draft"]
124
+ blocked_docs = [doc for doc in open_docs if doc.status == "Blocked"]
125
+
126
+ next_actions: list[str] = []
127
+ if blocked_docs:
128
+ next_actions.append(f"Review {len(blocked_docs)} blocked doc(s).")
129
+ if active_tasks:
130
+ next_actions.append(f"Continue or finish {len(active_tasks)} active task(s).")
131
+ if backlog_without_task:
132
+ next_actions.append(f"Promote {len(backlog_without_task)} ready backlog item(s) without detected task links.")
133
+ if draft_requests:
134
+ next_actions.append(f"Groom {len(draft_requests)} draft request(s).")
135
+ if not next_actions:
136
+ next_actions.append("No open workflow action detected.")
137
+
138
+ return {
139
+ "ok": True,
140
+ "counts": _status_counts(docs),
141
+ "open_count": len(open_docs),
142
+ "active_tasks": [_doc_summary(doc) for doc in active_tasks[:limit]],
143
+ "backlog_without_task": [_doc_summary(doc) for doc in backlog_without_task[:limit]],
144
+ "draft_requests": [_doc_summary(doc) for doc in draft_requests[:limit]],
145
+ "blocked_docs": [_doc_summary(doc) for doc in blocked_docs[:limit]],
146
+ "next_actions": next_actions,
147
+ }
148
+
149
+
150
+ def render_status(repo_root: Path, *, output_format: str = "text", limit: int = 10) -> str:
151
+ payload = status_payload(repo_root, limit=limit)
152
+ if output_format == "json":
153
+ return json.dumps(payload, indent=2, sort_keys=True)
154
+
155
+ lines = [
156
+ "Logics status:",
157
+ f"- open workflow docs: {payload['open_count']}",
158
+ "- next actions:",
159
+ ]
160
+ lines.extend(f" - {action}" for action in payload["next_actions"])
161
+ for key, label in (
162
+ ("active_tasks", "Active tasks"),
163
+ ("backlog_without_task", "Backlog without detected task"),
164
+ ("draft_requests", "Draft requests"),
165
+ ("blocked_docs", "Blocked docs"),
166
+ ):
167
+ items = payload[key]
168
+ if not items:
169
+ continue
170
+ lines.append(f"- {label}:")
171
+ for item in items:
172
+ lines.append(f" - {item['ref']} [{item['status']}]: {item['title']}")
173
+ return "\n".join(lines)
174
+
175
+
176
+ def health_payload(repo_root: Path, *, limit: int = 10) -> dict[str, object]:
177
+ docs = collect_logics_docs(repo_root, kinds=WORKFLOW_KINDS + COMPANION_KINDS)
178
+ workflow_docs = [doc for doc in docs if doc.kind in WORKFLOW_KINDS]
179
+ missing_status = [doc for doc in docs if not doc.status]
180
+ done_without_full_progress = [
181
+ doc for doc in workflow_docs if doc.status == "Done" and doc.kind in {"backlog", "task"} and doc.progress != 100
182
+ ]
183
+ complete_progress_not_done = [
184
+ doc for doc in workflow_docs if doc.progress == 100 and doc.status not in CLOSED_STATUSES
185
+ ]
186
+ blocked_docs = [doc for doc in workflow_docs if doc.status == "Blocked"]
187
+ open_docs = [doc for doc in workflow_docs if doc.status not in CLOSED_STATUSES]
188
+
189
+ task_text = "\n".join(doc.content for doc in workflow_docs if doc.kind == "task")
190
+ backlog_without_task = [
191
+ doc
192
+ for doc in open_docs
193
+ if doc.kind == "backlog" and doc.status in {"Ready", "In progress", "Blocked"} and doc.ref not in task_text
194
+ ]
195
+
196
+ issue_groups = {
197
+ "missing_status": missing_status,
198
+ "done_without_full_progress": done_without_full_progress,
199
+ "complete_progress_not_done": complete_progress_not_done,
200
+ "blocked_docs": blocked_docs,
201
+ "backlog_without_task": backlog_without_task,
202
+ }
203
+ issue_count = sum(len(items) for items in issue_groups.values())
204
+ return {
205
+ "ok": issue_count == 0,
206
+ "doc_count": len(docs),
207
+ "workflow_doc_count": len(workflow_docs),
208
+ "open_workflow_count": len(open_docs),
209
+ "counts": _status_counts(docs),
210
+ "issue_count": issue_count,
211
+ "issues": {key: [_doc_summary(doc) for doc in items[:limit]] for key, items in issue_groups.items()},
212
+ }
213
+
214
+
215
+ def render_health(repo_root: Path, *, output_format: str = "text", limit: int = 10) -> str:
216
+ payload = health_payload(repo_root, limit=limit)
217
+ if output_format == "json":
218
+ return json.dumps(payload, indent=2, sort_keys=True)
219
+
220
+ lines = [
221
+ "Logics health:",
222
+ f"- docs: {payload['doc_count']}",
223
+ f"- workflow docs: {payload['workflow_doc_count']}",
224
+ f"- open workflow docs: {payload['open_workflow_count']}",
225
+ f"- issue signals: {payload['issue_count']}",
226
+ ]
227
+ issues = payload["issues"]
228
+ for key, items in issues.items():
229
+ if not items:
230
+ continue
231
+ label = key.replace("_", " ")
232
+ lines.append(f"- {label}:")
233
+ for item in items:
234
+ lines.append(f" - {item['ref']} [{item['status']}]: {item['title']}")
235
+ return "\n".join(lines)
236
+
237
+
238
+ def _slug_command_title(text: str) -> str:
239
+ cleaned = re.sub(r"`([^`]+)`", r"\1", text)
240
+ cleaned = re.sub(r"[*_]+", "", cleaned)
241
+ cleaned = re.sub(r"\s+", " ", cleaned.strip(" .:-"))
242
+ if len(cleaned) > 96:
243
+ cleaned = cleaned[:93].rstrip(" ,.;:") + "..."
244
+ return cleaned[:1].upper() + cleaned[1:] if cleaned else "Follow up"
245
+
246
+
247
+ def _is_actionable_followup(text: str) -> bool:
248
+ normalized = re.sub(r"\s+", " ", text.strip(" .")).lower()
249
+ if normalized in {"none", "n/a", "not needed", "no follow-up"}:
250
+ return False
251
+ if normalized.startswith("no ") and "follow-up" in normalized:
252
+ return False
253
+ if normalized.startswith("no ") and "is required" in normalized:
254
+ return False
255
+ if "no new adr is required" in normalized:
256
+ return False
257
+ if "no new architecture decision" in normalized:
258
+ return False
259
+ return True
260
+
261
+
262
+ def followups_payload(
263
+ repo_root: Path,
264
+ *,
265
+ limit: int = 50,
266
+ source_kind: str = "all",
267
+ include_closed: bool = False,
268
+ closed_only: bool = False,
269
+ ) -> dict[str, object]:
270
+ docs = collect_logics_docs(repo_root, kinds=WORKFLOW_KINDS + COMPANION_KINDS)
271
+ if source_kind != "all":
272
+ docs = [doc for doc in docs if doc.kind == source_kind]
273
+ if closed_only:
274
+ docs = [doc for doc in docs if doc.status in CLOSED_STATUSES]
275
+ elif not include_closed:
276
+ docs = [doc for doc in docs if doc.status not in CLOSED_STATUSES]
277
+ followups: list[dict[str, object]] = []
278
+ patterns = ("Follow-up area:", "Product follow-up:", "Architecture follow-up:")
279
+ for doc in docs:
280
+ for index, line in enumerate(doc.content.splitlines(), start=1):
281
+ stripped = line.strip().lstrip("- ").strip()
282
+ matched = next((pattern for pattern in patterns if stripped.startswith(pattern)), None)
283
+ if not matched:
284
+ continue
285
+ text = stripped.removeprefix(matched).strip()
286
+ if not _is_actionable_followup(text):
287
+ continue
288
+ title = _slug_command_title(text)
289
+ quoted_title = shlex.quote(title)
290
+ followups.append(
291
+ {
292
+ "source_ref": doc.ref,
293
+ "source_path": doc.rel_path,
294
+ "source_kind": doc.kind,
295
+ "line": index,
296
+ "text": text,
297
+ "suggested_title": title,
298
+ "suggested_command": f"python3 -m logics_manager flow new request --title {quoted_title}",
299
+ }
300
+ )
301
+ return {
302
+ "ok": True,
303
+ "count": len(followups),
304
+ "returned_count": min(len(followups), limit),
305
+ "filters": {
306
+ "source_kind": source_kind,
307
+ "include_closed": include_closed,
308
+ "closed_only": closed_only,
309
+ },
310
+ "followups": followups[:limit],
311
+ }
312
+
313
+
314
+ def render_followups(
315
+ repo_root: Path,
316
+ *,
317
+ output_format: str = "text",
318
+ limit: int = 50,
319
+ source_kind: str = "all",
320
+ include_closed: bool = False,
321
+ closed_only: bool = False,
322
+ ) -> str:
323
+ payload = followups_payload(
324
+ repo_root,
325
+ limit=limit,
326
+ source_kind=source_kind,
327
+ include_closed=include_closed,
328
+ closed_only=closed_only,
329
+ )
330
+ if output_format == "json":
331
+ return json.dumps(payload, indent=2, sort_keys=True)
332
+
333
+ lines = [f"Logics follow-ups: {payload['count']} found"]
334
+ for item in payload["followups"]:
335
+ lines.append(f"- {item['source_ref']}:{item['line']} {item['text']}")
336
+ lines.append(f" command: {item['suggested_command']}")
337
+ return "\n".join(lines)
338
+
339
+
340
+ def _related_ref(content: str, label: str) -> str | None:
341
+ prefix = f"> Related {label}:"
342
+ for line in content.splitlines():
343
+ if not line.startswith(prefix):
344
+ continue
345
+ value = line.split(":", 1)[1].strip()
346
+ normalized = value.strip("`").strip().lower()
347
+ if not normalized or normalized.startswith("(none"):
348
+ return None
349
+ match = re.search(r"`([^`]+)`", value)
350
+ return match.group(1) if match else value
351
+ return None
352
+
353
+
354
+ def product_consistency_payload(repo_root: Path, *, limit: int = 50) -> dict[str, object]:
355
+ docs = collect_logics_docs(repo_root, kinds=WORKFLOW_KINDS + COMPANION_KINDS)
356
+ docs_by_ref = {doc.ref: doc for doc in docs}
357
+ product_docs = [doc for doc in docs if doc.kind == "product"]
358
+ checked_product_docs = [doc for doc in product_docs if doc.status != "Proposed"]
359
+ issues: list[dict[str, object]] = []
360
+ expected = {
361
+ "request": "request",
362
+ "backlog": "backlog",
363
+ "task": "task",
364
+ }
365
+ for doc in checked_product_docs:
366
+ missing_related: list[str] = []
367
+ broken_related: list[dict[str, str]] = []
368
+ for label, expected_kind in expected.items():
369
+ ref = _related_ref(doc.content, label)
370
+ if ref is None:
371
+ missing_related.append(label)
372
+ continue
373
+ target = docs_by_ref.get(ref)
374
+ if target is None:
375
+ broken_related.append({"kind": label, "ref": ref, "reason": "missing"})
376
+ elif target.kind != expected_kind:
377
+ broken_related.append({"kind": label, "ref": ref, "reason": f"expected {expected_kind}, found {target.kind}"})
378
+ if missing_related or broken_related:
379
+ issues.append(
380
+ {
381
+ "ref": doc.ref,
382
+ "title": doc.title,
383
+ "status": doc.status,
384
+ "path": doc.rel_path,
385
+ "missing_related": missing_related,
386
+ "broken_related": broken_related,
387
+ }
388
+ )
389
+ return {
390
+ "ok": not issues,
391
+ "product_count": len(product_docs),
392
+ "checked_product_count": len(checked_product_docs),
393
+ "skipped_product_count": len(product_docs) - len(checked_product_docs),
394
+ "issue_count": len(issues),
395
+ "issues": issues[:limit],
396
+ "truncated": len(issues) > limit,
397
+ "limit": limit,
398
+ }
399
+
400
+
401
+ def render_product_consistency(repo_root: Path, *, output_format: str = "text", limit: int = 50) -> str:
402
+ payload = product_consistency_payload(repo_root, limit=limit)
403
+ if output_format == "json":
404
+ return json.dumps(payload, indent=2, sort_keys=True)
405
+
406
+ lines = [
407
+ "Product consistency:",
408
+ f"- product briefs: {payload['product_count']}",
409
+ f"- issue signals: {payload['issue_count']}",
410
+ ]
411
+ for issue in payload["issues"]:
412
+ details: list[str] = []
413
+ if issue["missing_related"]:
414
+ details.append("missing " + ", ".join(issue["missing_related"]))
415
+ if issue["broken_related"]:
416
+ details.append("broken " + ", ".join(item["ref"] for item in issue["broken_related"]))
417
+ lines.append(f"- {issue['ref']} [{issue['status']}]: {'; '.join(details)}")
418
+ return "\n".join(lines)
@@ -578,12 +578,26 @@ def lint_payload(repo_root: Path, *, require_status: bool = False) -> dict[str,
578
578
  if warnings:
579
579
  all_warnings.append((rel_path, warnings))
580
580
 
581
+ issues = [{"path": path.as_posix(), "message": issue, "severity": "blocking"} for path, issues in all_issues for issue in issues]
582
+ warnings: list[dict[str, str]] = []
583
+ for path, path_warnings in all_warnings:
584
+ for warning in path_warnings:
585
+ item = {"path": path.as_posix(), "message": warning, "severity": "warning"}
586
+ if "Mermaid context signature" in warning:
587
+ item["repair_command"] = "logics-manager sync refresh-mermaid-signatures"
588
+ warnings.append(item)
581
589
  return {
582
- "ok": not all_issues,
583
- "issue_count": sum(len(issues) for _path, issues in all_issues),
584
- "warning_count": sum(len(warnings) for _path, warnings in all_warnings),
585
- "issues": [{"path": path.as_posix(), "message": issue} for path, issues in all_issues for issue in issues],
586
- "warnings": [{"path": path.as_posix(), "message": warning} for path, warnings in all_warnings for warning in warnings],
590
+ "ok": not issues,
591
+ "can_continue": not issues,
592
+ "release_ready": not issues and not warnings,
593
+ "issue_count": len(issues),
594
+ "warning_count": len(warnings),
595
+ "strict_count": 0,
596
+ "finding_count": len(issues) + len(warnings),
597
+ "issues": issues,
598
+ "warnings": warnings,
599
+ "strict": [],
600
+ "findings": [*issues, *warnings],
587
601
  }
588
602
 
589
603
 
@@ -594,11 +608,11 @@ def render_lint(repo_root: Path, *, require_status: bool = False, output_format:
594
608
  if not payload["issues"] and not payload["warnings"]:
595
609
  return "Logics lint: OK"
596
610
  if not payload["issues"]:
597
- lines = ["Logics lint: OK (warnings)"]
611
+ lines = ["Logics lint: OK (warnings)", f"Blocking issues: {payload['issue_count']}; warnings: {payload['warning_count']}"]
598
612
  for warning in payload["warnings"]:
599
613
  lines.append(f"- {warning['path']}: WARNING: {warning['message']}")
600
614
  return "\n".join(lines)
601
- lines = ["Logics lint: FAILED"]
615
+ lines = ["Logics lint: FAILED", f"Blocking issues: {payload['issue_count']}; warnings: {payload['warning_count']}"]
602
616
  for issue in payload["issues"]:
603
617
  lines.append(f"- {issue['path']}: {issue['message']}")
604
618
  for warning in payload["warnings"]: