Coverage for src/governed_harness/orchestration/architecture_catalogue.py: 91%

68 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1"""The catalogue of architecture styles and their experts (wave 11, #97). 

2 

3Under ``architecture.catalogue: experts`` a new project is offered ten styles (layered, hexagonal, 

4clean, ddd, modular-monolith, microservices, mvvm, mvi, event-driven, cqrs). Each one ships as a 

5Markdown file in ``resources/architecture``: a front matter with the purpose, when it fits, its 

6benefits and costs and the layer rules where they apply; sections with the structure, the best 

7practices and the dependency rules; and a last section, ``Expert prompt``, which is what the 

8expert for that style is told. The documentation is read by people and agents; only the expert 

9prompt travels in the requests (the documentation is copied into the project when a style is 

10chosen, and requests point to it).""" 

11 

12from __future__ import annotations 

13 

14from dataclasses import dataclass 

15from functools import cache 

16from importlib import resources 

17from typing import Any 

18 

19import yaml 

20 

21from governed_harness.configuration.engineering import CATALOGUE_STYLES 

22 

23EXPERT_HEADING = "## Expert prompt" 

24STYLE_DOC_FILE = "architecture-style.md" 

25RECOMMENDATION_FILE = "architecture-options.md" 

26ORGANIZATION_FILE = "architecture-organization.md" 

27_MAX_DOC = 20_000 

28 

29 

30@dataclass(frozen=True) 

31class StyleEntry: 

32 """One style of the catalogue.""" 

33 

34 style: str 

35 title: str 

36 purpose: str 

37 fits: tuple[str, ...] 

38 benefits: tuple[str, ...] 

39 costs: tuple[str, ...] 

40 layers: tuple[dict[str, Any], ...] 

41 allow: dict[str, list[str]] 

42 document: str 

43 expert_prompt: str 

44 

45 def summary(self) -> dict[str, Any]: 

46 """What the advise request carries about the style: enough to choose, not the document.""" 

47 return { 

48 "id": self.style, 

49 "title": self.title, 

50 "purpose": self.purpose, 

51 "fits": list(self.fits), 

52 } 

53 

54 def as_option(self) -> dict[str, Any]: 

55 """The style as an architecture option, with the layer rules of its template.""" 

56 return { 

57 "id": f"catalogue-{self.style}", 

58 "style": self.style, 

59 "title": self.title, 

60 "benefits": list(self.benefits), 

61 "costs": list(self.costs), 

62 "fit": "; ".join(self.fits), 

63 "supports": [], 

64 "recommended": False, 

65 "layers": [ 

66 {"name": item["name"], "paths": list(item["paths"]), "modules": []} 

67 for item in self.layers 

68 ], 

69 "allow": {key: list(value) for key, value in self.allow.items()}, 

70 } 

71 

72 

73def _split(text: str) -> tuple[dict[str, Any], str]: 

74 """The front matter and the body of a catalogue file.""" 

75 _, front, body = text.split("---\n", 2) 

76 meta = yaml.safe_load(front) 

77 if not isinstance(meta, dict): 77 ↛ 78line 77 didn't jump to line 78 because the condition on line 77 was never true

78 raise ValueError("a catalogue file needs a front matter") 

79 return meta, body 

80 

81 

82def _entry(text: str) -> StyleEntry: 

83 meta, body = _split(text) 

84 document, _, prompt = body.partition(EXPERT_HEADING) 

85 if not prompt.strip(): 85 ↛ 86line 85 didn't jump to line 86 because the condition on line 85 was never true

86 raise ValueError(f"catalogue style {meta.get('id')!r} has no expert prompt") 

87 return StyleEntry( 

88 style=str(meta["id"]), 

89 title=str(meta["title"]), 

90 purpose=str(meta["purpose"]), 

91 fits=tuple(str(item) for item in meta["fits"]), 

92 benefits=tuple(str(item) for item in meta["benefits"]), 

93 costs=tuple(str(item) for item in meta["costs"]), 

94 layers=tuple(meta.get("layers") or ()), 

95 allow={str(key): list(value) for key, value in (meta.get("allow") or {}).items()}, 

96 document=document.strip()[:_MAX_DOC] + "\n", 

97 expert_prompt=prompt.strip(), 

98 ) 

99 

100 

101@cache 

102def style_entry(style: str) -> StyleEntry: 

103 """The catalogue entry of ``style``; a style outside the catalogue is an error.""" 

104 if style not in CATALOGUE_STYLES: 104 ↛ 105line 104 didn't jump to line 105 because the condition on line 104 was never true

105 raise ValueError( 

106 f"{style!r} is not a style of the catalogue ({', '.join(CATALOGUE_STYLES)})" 

107 ) 

108 target = resources.files("governed_harness.resources").joinpath("architecture", f"{style}.md") 

109 return _entry(target.read_text(encoding="utf-8")) 

110 

111 

112def catalogue() -> tuple[StyleEntry, ...]: 

113 return tuple(style_entry(style) for style in CATALOGUE_STYLES) 

114 

115 

116def in_catalogue(style: Any) -> bool: 

117 return isinstance(style, str) and style in CATALOGUE_STYLES 

118 

119 

120def render_recommendation(options: list[dict[str, Any]], project_kind: dict[str, Any]) -> str: 

121 """The report a person reads before choosing (Markdown): the style the agent recommends, why, 

122 the characteristics of the project that support it, the other options, and how to decide.""" 

123 recommended = next((item for item in options if item.get("recommended")), None) 

124 lines = ["# Architecture recommendation", ""] 

125 if recommended is not None: 125 ↛ 139line 125 didn't jump to line 139 because the condition on line 125 was always true

126 lines += [ 

127 f"Recommended: **{recommended['title']}** (`{recommended['style']}`, option " 

128 f"`{recommended['id']}`).", 

129 "", 

130 "## Why", 

131 "", 

132 recommended["fit"] or "The agent gave no further reason.", 

133 "", 

134 "## Characteristics of the project that support it", 

135 "", 

136 *[f"- {item}" for item in recommended.get("supports") or []], 

137 "", 

138 ] 

139 lines += ["## Options", ""] 

140 for item in options: 

141 mark = " (recommended)" if item.get("recommended") else "" 

142 lines.append(f"- `{item['id']}`: {item['title']} ({item['style']}){mark}") 

143 lines += [f" - benefit: {text}" for text in item["benefits"]] 

144 lines += [f" - cost: {text}" for text in item["costs"]] 

145 styles = ", ".join(CATALOGUE_STYLES) 

146 lines += [ 

147 "", 

148 "## How to decide", 

149 "", 

150 "- Accept the recommendation: `harness architecture decide --option <recommended id> " 

151 + "--digest <digest> --rationale <why>`.", 

152 "- Choose another option of the list with its id.", 

153 f"- Choose any style of the catalogue with `--style <style>` ({styles}).", 

154 "", 

155 f"Project kind: {project_kind.get('kind', 'unknown')}.", 

156 ] 

157 return "\n".join(lines).rstrip() + "\n" 

158 

159 

160def expert_block(style: str) -> dict[str, Any]: 

161 """What the requests carry about the chosen style: the expert prompt and where the 

162 documentation of the style lives in the project.""" 

163 entry = style_entry(style) 

164 return {"prompt": entry.expert_prompt, "document": f".harness/{STYLE_DOC_FILE}"} 

165 

166 

167__all__ = [ 

168 "ORGANIZATION_FILE", 

169 "RECOMMENDATION_FILE", 

170 "STYLE_DOC_FILE", 

171 "StyleEntry", 

172 "catalogue", 

173 "expert_block", 

174 "in_catalogue", 

175 "render_recommendation", 

176 "style_entry", 

177]