@capagents/forgeqe 3.3.1 → 3.3.3

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 (234) hide show
  1. package/HOW_TO_USE.md +337 -8
  2. package/dist/docs-site/docs/area-operations/index.html +126 -2
  3. package/dist/docs-site/docs/area-quality/index.html +159 -3
  4. package/dist/docs-site/docs/area-setup/index.html +1 -0
  5. package/dist/docs-site/docs/area-test-cases/index.html +25 -0
  6. package/dist/docs-site/docs/overview/index.html +2 -2
  7. package/dist/docs-site/docs/search.js +1 -1
  8. package/dist/forgeqe.js +2159 -1928
  9. package/dist/requirement-agent/requirements_agent/__init__.py +3 -0
  10. package/dist/requirement-agent/requirements_agent/__main__.py +5 -0
  11. package/dist/requirement-agent/requirements_agent/agent.py +363 -0
  12. package/dist/requirement-agent/requirements_agent/chat_session.py +424 -0
  13. package/dist/requirement-agent/requirements_agent/cli.py +870 -0
  14. package/dist/requirement-agent/requirements_agent/config.py +403 -0
  15. package/dist/requirement-agent/requirements_agent/console_ui.py +632 -0
  16. package/dist/requirement-agent/requirements_agent/context/__init__.py +3 -0
  17. package/dist/requirement-agent/requirements_agent/context/aggregate.py +214 -0
  18. package/dist/requirement-agent/requirements_agent/context/base.py +14 -0
  19. package/dist/requirement-agent/requirements_agent/context/folder.py +107 -0
  20. package/dist/requirement-agent/requirements_agent/context/given.py +70 -0
  21. package/dist/requirement-agent/requirements_agent/context/graph.py +181 -0
  22. package/dist/requirement-agent/requirements_agent/context/knowledge.py +192 -0
  23. package/dist/requirement-agent/requirements_agent/context/mcp.py +24 -0
  24. package/dist/requirement-agent/requirements_agent/context/memory.py +144 -0
  25. package/dist/requirement-agent/requirements_agent/context/personas.py +214 -0
  26. package/dist/requirement-agent/requirements_agent/context/rag.py +148 -0
  27. package/dist/requirement-agent/requirements_agent/context/untrusted.py +56 -0
  28. package/dist/requirement-agent/requirements_agent/docs/HOW_TO_USE.md +505 -0
  29. package/dist/requirement-agent/requirements_agent/docs/requirements-agent-architecture.html +348 -0
  30. package/dist/requirement-agent/requirements_agent/docs_cmd.py +51 -0
  31. package/dist/requirement-agent/requirements_agent/export/__init__.py +3 -0
  32. package/dist/requirement-agent/requirements_agent/export/markdown.py +55 -0
  33. package/dist/requirement-agent/requirements_agent/export/pdf.py +82 -0
  34. package/dist/requirement-agent/requirements_agent/export/requirements_json.py +120 -0
  35. package/dist/requirement-agent/requirements_agent/init_cmd.py +191 -0
  36. package/dist/requirement-agent/requirements_agent/llm/__init__.py +3 -0
  37. package/dist/requirement-agent/requirements_agent/llm/base.py +49 -0
  38. package/dist/requirement-agent/requirements_agent/llm/copilot.py +171 -0
  39. package/dist/requirement-agent/requirements_agent/llm/mock.py +144 -0
  40. package/dist/requirement-agent/requirements_agent/llm/providers.py +277 -0
  41. package/dist/requirement-agent/requirements_agent/llm/router.py +35 -0
  42. package/dist/requirement-agent/requirements_agent/models.py +73 -0
  43. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/analyst.md +29 -0
  44. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/architect.md +28 -0
  45. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/bmad-orchestrator.md +26 -0
  46. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/dev.md +27 -0
  47. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/pm.md +27 -0
  48. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/po.md +27 -0
  49. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/qa.md +28 -0
  50. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/sm.md +26 -0
  51. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-analyst.md +8 -0
  52. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-architect.md +11 -0
  53. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-dev.md +11 -0
  54. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-orchestrator.md +9 -0
  55. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-pm.md +9 -0
  56. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-po.md +10 -0
  57. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-qa.md +11 -0
  58. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-sm.md +8 -0
  59. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/data/bmad-kb.md +19 -0
  60. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/data/requirements-standards-baseline.md +188 -0
  61. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/data/technical-preferences.md +54 -0
  62. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/utils/template-format.md +7 -0
  63. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/workflows/greenfield-fullstack.yml +177 -0
  64. package/dist/requirement-agent/requirements_agent/pipeline/__init__.py +3 -0
  65. package/dist/requirement-agent/requirements_agent/pipeline/brd.py +86 -0
  66. package/dist/requirement-agent/requirements_agent/pipeline/pack.py +233 -0
  67. package/dist/requirement-agent/requirements_agent/pipeline/progress.py +60 -0
  68. package/dist/requirement-agent/requirements_agent/pipeline/prompts.py +150 -0
  69. package/dist/requirement-agent/requirements_agent/pipeline/quality.py +124 -0
  70. package/dist/requirement-agent/requirements_agent/pipeline/refine.py +386 -0
  71. package/dist/requirement-agent/requirements_agent/pipeline/sections.py +117 -0
  72. package/dist/requirement-agent/requirements_agent/pipeline/spec_circuit.py +142 -0
  73. package/dist/requirement-agent/requirements_agent/shell/__init__.py +7 -0
  74. package/dist/requirement-agent/requirements_agent/shell/actions.py +208 -0
  75. package/dist/requirement-agent/requirements_agent/shell/app.py +902 -0
  76. package/dist/requirement-agent/requirements_agent/shell/commands.py +206 -0
  77. package/dist/requirement-agent/requirements_agent/shell/progress_pane.py +114 -0
  78. package/dist/requirement-agent/requirements_agent/shell/ref_picker.py +59 -0
  79. package/dist/requirement-agent/requirements_agent/shell/refs.py +120 -0
  80. package/dist/requirement-agent/requirements_agent/shell/session.py +362 -0
  81. package/dist/requirement-agent/requirements_agent/shell/transcript.py +241 -0
  82. package/dist/requirement-agent/requirements_agent/shell/usage.py +64 -0
  83. package/dist/requirement-agent/requirements_agent/shell/usage_llm.py +64 -0
  84. package/dist/requirement-agent/requirements_agent/shell/worker.py +378 -0
  85. package/dist/requirement-agent/requirements_agent/tuios_hook.py +182 -0
  86. package/dist/requirement-agent/requirements_agent/webops.py +627 -0
  87. package/dist/template.html +67 -67
  88. package/dist/web/assets/{3d-force-graph-Df2wOlpF.js → 3d-force-graph-KUdc_88B.js} +3 -3
  89. package/dist/web/assets/Agent-Bd54dLhD.js +10 -0
  90. package/dist/web/assets/AgentWork-CqMhsFBP.js +2 -0
  91. package/dist/web/assets/ApiTests-BO_sKAg8.js +15 -0
  92. package/dist/web/assets/Browse-BjPPdirz.js +1 -0
  93. package/dist/web/assets/Chat-DO-UvDWX.js +3 -0
  94. package/dist/web/assets/CommandPalette-BBGtkkz4.js +1 -0
  95. package/dist/web/assets/Compare-BFuLcrBB.js +1 -0
  96. package/dist/web/assets/Cost-DbKrBm9m.js +1 -0
  97. package/dist/web/assets/{Data-Be3ZNkUu.js → Data-B6_6Rm7C.js} +4 -4
  98. package/dist/web/assets/Desktop-CnBxMp68.js +1 -0
  99. package/dist/web/assets/DesktopReview-DVITz4Jv.js +2 -0
  100. package/dist/web/assets/DeviceScreen-BHmTd9Q-.js +1 -0
  101. package/dist/web/assets/Evidence-BZx9UF1t.js +1 -0
  102. package/dist/web/assets/{Explore-AtSStzNg.js → Explore-Kkl9koqy.js} +2 -2
  103. package/dist/web/assets/Features-_WrrIGBz.js +1 -0
  104. package/dist/web/assets/{Flags-GxmNrnSn.js → Flags-BGqG09qD.js} +2 -2
  105. package/dist/web/assets/Flaky-B7mr96H8.js +1 -0
  106. package/dist/web/assets/Impact-DzAtWie1.js +3 -0
  107. package/dist/web/assets/Jobs-YSmfG7C9.js +5 -0
  108. package/dist/web/assets/KindPage-UqU2qh63.js +6 -0
  109. package/dist/web/assets/LiveDevice-jFCQ_zeU.js +1 -0
  110. package/dist/web/assets/Migration-CfHZeobD.js +8 -0
  111. package/dist/web/assets/Mobile-DTMPjWeO.js +1 -0
  112. package/dist/web/assets/Observability-B-9cikxK.js +1 -0
  113. package/dist/web/assets/OwnItems-BC9M20At.js +5 -0
  114. package/dist/web/assets/PageAgent-CvV8gwuP.js +1 -0
  115. package/dist/web/assets/Product-lDXsflpD.js +6 -0
  116. package/dist/web/assets/Production-BHXWX-ww.js +1 -0
  117. package/dist/web/assets/Quality-Bsljiu_v.js +1 -0
  118. package/dist/web/assets/Readiness-BZppEirK.js +1 -0
  119. package/dist/web/assets/Record-7h0EFEiJ.js +1 -0
  120. package/dist/web/assets/Regression-DdM66t2E.js +5 -0
  121. package/dist/web/assets/RelationGraph-CBY9FhUu.js +1 -0
  122. package/dist/web/assets/Reports-u72R1XBV.js +2 -0
  123. package/dist/web/assets/Requirements-BAcEi5Fl.js +2 -0
  124. package/dist/web/assets/Responsive-CCPzSbdd.js +3 -0
  125. package/dist/web/assets/RunDiff-CGhLqPpP.js +1 -0
  126. package/dist/web/assets/Settings-DDCiQZ0T.js +21 -0
  127. package/dist/web/assets/Steps-sfVkdv7g.js +2 -0
  128. package/dist/web/assets/TestData-B4-xVlvt.js +2 -0
  129. package/dist/web/assets/TestManagement-BGBKGV1L.js +4 -0
  130. package/dist/web/assets/WhatsNew-BMTuBbaX.js +1 -0
  131. package/dist/web/assets/agentSettingsSheet-Cc2W6lyp.js +1 -0
  132. package/dist/web/assets/api-BsiuHmJq.js +1 -0
  133. package/dist/web/assets/choice-C4-yW2x9.js +1 -0
  134. package/dist/web/assets/code-Jek8uWUO.js +1 -0
  135. package/dist/web/assets/{coverage-DirEXtfZ.js → coverage-pqIlfEP0.js} +1 -1
  136. package/dist/web/assets/dataParts-CkwgLllh.js +3 -0
  137. package/dist/web/assets/desktopAppPath-D3mGDKPz.js +1 -0
  138. package/dist/web/assets/flowTheme-DKuXe5nP.js +7 -0
  139. package/dist/web/assets/frame-BMpSUo2-.js +13 -0
  140. package/dist/web/assets/index-6SZomYE0.js +55 -0
  141. package/dist/web/assets/index-CWqwtFKz.css +2 -0
  142. package/dist/web/assets/line-icons-CwCZidXs.js +1 -0
  143. package/dist/web/assets/logos-P2LOMyTK.js +1 -0
  144. package/dist/web/assets/{markdown-BnrLv6Iw.js → markdown-1wY7hIbM.js} +5 -5
  145. package/dist/web/assets/nav-B_68FVw_.js +1 -0
  146. package/dist/web/assets/pageBack-CbyKfisx.js +3 -0
  147. package/dist/web/assets/palette-6YAAmgkD.js +1 -0
  148. package/dist/web/assets/{paletteCommands-LXIICD4V.js → paletteCommands-Isq1rLs-.js} +1 -1
  149. package/dist/web/assets/parts-ClnDV-6r.js +1 -0
  150. package/dist/web/assets/preload-helper-BupTYkQW.js +1 -0
  151. package/dist/web/assets/productParts-D18glCBr.js +1 -0
  152. package/dist/web/assets/qualityParts-1F1Ee4Ay.js +1 -0
  153. package/dist/web/assets/radio-BLI4Ubhk.js +1 -0
  154. package/dist/web/assets/react-BDur5s0O.js +1 -0
  155. package/dist/web/assets/{recordTest-BzKpS4m5.js → recordTest-7uIZiqOW.js} +1 -1
  156. package/dist/web/assets/route-oDy8sV6H.js +1 -0
  157. package/dist/web/assets/sectionList-B651VPon.js +1 -0
  158. package/dist/web/assets/step-mark-CaKf4dAR.js +1 -0
  159. package/dist/web/assets/stepper-DdgwJtbU.js +1 -0
  160. package/dist/web/assets/utils-DJRAScIl.js +1 -0
  161. package/dist/web/assets/wizardParts-C0cNmIK9.js +1 -0
  162. package/dist/web/index.html +15 -13
  163. package/docs/user-guide.html +309 -3
  164. package/evals/prompts/perf-report/limit-broken.yaml +28 -0
  165. package/evals/prompts/perf-report/regression-other-load.yaml +28 -0
  166. package/forgeqe.example.yaml +10 -0
  167. package/package.json +2 -1
  168. package/prompts/README.md +4 -0
  169. package/prompts/brain.md +17 -0
  170. package/prompts/perf-report.md +41 -0
  171. package/prompts/perf-strategy.md +45 -0
  172. package/prompts/perf.md +45 -0
  173. package/prompts/team-builder.md +50 -0
  174. package/py/forgeqe_engine/cli.py +7 -0
  175. package/dist/web/assets/Agent-CRfgRnq2.js +0 -8
  176. package/dist/web/assets/AgentWork-DqiO3LUi.js +0 -2
  177. package/dist/web/assets/ApiTests-DCAnizu5.js +0 -15
  178. package/dist/web/assets/Browse-D5VDHN9Z.js +0 -1
  179. package/dist/web/assets/Chat-CLGQ1ymU.js +0 -3
  180. package/dist/web/assets/CommandPalette-D3F4iHrP.js +0 -1
  181. package/dist/web/assets/Compare-B1WN67Ny.js +0 -1
  182. package/dist/web/assets/Cost-Dk4m3r8z.js +0 -1
  183. package/dist/web/assets/Desktop-B3GcbaPu.js +0 -1
  184. package/dist/web/assets/DesktopReview-DfvAL3m8.js +0 -2
  185. package/dist/web/assets/DeviceScreen-DJqblqBh.js +0 -1
  186. package/dist/web/assets/Evidence-BsA7vCZG.js +0 -1
  187. package/dist/web/assets/Features-CDBlFLaJ.js +0 -1
  188. package/dist/web/assets/Flaky-C062Mh6z.js +0 -1
  189. package/dist/web/assets/Impact-BeXw3-oL.js +0 -3
  190. package/dist/web/assets/Jobs-QYWqmdDI.js +0 -5
  191. package/dist/web/assets/KindPage-C2g51s9c.js +0 -6
  192. package/dist/web/assets/LiveDevice-C9LRZMhC.js +0 -1
  193. package/dist/web/assets/Migration-ByUU0Oa_.js +0 -8
  194. package/dist/web/assets/Mobile-Dd3jL0Cn.js +0 -1
  195. package/dist/web/assets/Observability-Dx4ZCRDj.js +0 -1
  196. package/dist/web/assets/PageAgent-DYBOhs2x.js +0 -1
  197. package/dist/web/assets/Product-Ch1XAeAT.js +0 -12
  198. package/dist/web/assets/Production-TEdyFmo4.js +0 -1
  199. package/dist/web/assets/Quality-DH8EdI2u.js +0 -1
  200. package/dist/web/assets/Readiness-B8S7Ex0C.js +0 -1
  201. package/dist/web/assets/Record-uFQ-YaHg.js +0 -1
  202. package/dist/web/assets/Regression-CSDT2AnY.js +0 -5
  203. package/dist/web/assets/RelationGraph-gc0Xmklt.js +0 -1
  204. package/dist/web/assets/Reports-CSHhRfWv.js +0 -2
  205. package/dist/web/assets/Responsive-CEG1hbbQ.js +0 -3
  206. package/dist/web/assets/RunDiff-CHrMivzC.js +0 -1
  207. package/dist/web/assets/Settings-B63s0b1g.js +0 -21
  208. package/dist/web/assets/Steps-BsDjv-pm.js +0 -2
  209. package/dist/web/assets/TestData-CJoCXihI.js +0 -2
  210. package/dist/web/assets/TestManagement-Dkb-paWh.js +0 -4
  211. package/dist/web/assets/WhatsNew-Dtk9mJU4.js +0 -1
  212. package/dist/web/assets/agentSettingsSheet-BlM8KSpN.js +0 -1
  213. package/dist/web/assets/api-6pHfHEgB.js +0 -1
  214. package/dist/web/assets/choice-CiFogD01.js +0 -1
  215. package/dist/web/assets/code-DzYywAs5.js +0 -1
  216. package/dist/web/assets/dataParts-Di7PdPHu.js +0 -3
  217. package/dist/web/assets/desktopAppPath-B8j1-pX0.js +0 -1
  218. package/dist/web/assets/frame-CNLw552P.js +0 -13
  219. package/dist/web/assets/index-DLuCgQKX.js +0 -55
  220. package/dist/web/assets/index-DRcPg81h.css +0 -2
  221. package/dist/web/assets/line-icons-B-O8oBsY.js +0 -1
  222. package/dist/web/assets/nav-Ds_6IERv.js +0 -1
  223. package/dist/web/assets/pageBack-DJxbEPfN.js +0 -3
  224. package/dist/web/assets/palette-H2g-hemT.js +0 -1
  225. package/dist/web/assets/parts-DKRLtrjs.js +0 -1
  226. package/dist/web/assets/preload-helper-BML5SvL4.js +0 -1
  227. package/dist/web/assets/productParts-imNtw-1N.js +0 -1
  228. package/dist/web/assets/qualityParts-DJhFlgCm.js +0 -1
  229. package/dist/web/assets/radio-CbR6ODxQ.js +0 -1
  230. package/dist/web/assets/route-DjewvmpL.js +0 -1
  231. package/dist/web/assets/sectionList-0umoKvRv.js +0 -1
  232. package/dist/web/assets/step-mark-g8Eb6foB.js +0 -1
  233. package/dist/web/assets/stepper-CzZIC36d.js +0 -1
  234. /package/dist/web/assets/{Product-DLioOiRN.css → flowTheme-DLioOiRN.css} +0 -0
@@ -0,0 +1,120 @@
1
+ """The requirements of a report as structured data, for ForgeQE to write and trace test cases from.
2
+
3
+ Requirements Agent's report is Markdown. Its requirements carry ids (FR-001, NFR-002, BR-003, BRULE-004), mostly in
4
+ tables with an acceptance signal column, sometimes as bullets. ``requirements.json`` next to the report lists them:
5
+
6
+ {"format": "requirements-agent/1", "source": "02-requirements-report.md",
7
+ "requirements": [{"id": "FR-001", "kind": "functional", "text": "...", "acceptance": "...", "section": "..."}]}
8
+
9
+ ForgeQE reads it (its ``requirements_file`` tool), writes a case per requirement, and traces each case to its id.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import re
16
+ from datetime import datetime, timezone
17
+ from pathlib import Path
18
+ from typing import Dict, List, Optional
19
+
20
+ FORMAT = "requirements-agent/1"
21
+ FILE_NAME = "requirements.json"
22
+ MAX_REQUIREMENTS = 500
23
+ MAX_TEXT = 1000
24
+
25
+ _ID = re.compile(r"^\s*\**\s*((?:FR|NFR|BR|BRULE)-\d{1,4})\s*\**\s*$", re.IGNORECASE)
26
+ _BULLET = re.compile(r"^\s*[-*]\s+\**((?:FR|NFR|BR|BRULE)-\d{1,4})\**\s*[:—–-]\s*(.+)$", re.IGNORECASE)
27
+ _SEPARATOR = re.compile(r"^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$")
28
+ _KIND = {"FR": "functional", "NFR": "non-functional", "BR": "business", "BRULE": "business rule"}
29
+ _TEXT_HEADER = re.compile(r"behaviou?r|requirement|description|statement|rule|need|objective", re.IGNORECASE)
30
+ _ACCEPT_HEADER = re.compile(r"acceptance", re.IGNORECASE)
31
+
32
+
33
+ def _cells(line: str) -> List[str]:
34
+ body = line.strip()
35
+ if body.startswith("|"):
36
+ body = body[1:]
37
+ if body.endswith("|"):
38
+ body = body[:-1]
39
+ return [c.strip() for c in re.split(r"(?<!\\)\|", body)]
40
+
41
+
42
+ def _clip(text: str) -> str:
43
+ text = re.sub(r"\s+", " ", text.replace("\\|", "|")).strip()
44
+ return text[:MAX_TEXT]
45
+
46
+
47
+ def _kind(req_id: str) -> str:
48
+ return _KIND.get(req_id.split("-")[0].upper(), "other")
49
+
50
+
51
+ def extract_requirements(markdown: str) -> List[Dict[str, str]]:
52
+ """Requirements with ids from a report's tables and bullets, each once (the first wins), in report order."""
53
+ out: List[Dict[str, str]] = []
54
+ seen = set()
55
+ section = ""
56
+ header: Optional[List[str]] = None
57
+ lines = (markdown or "").splitlines()
58
+
59
+ def add(req_id: str, text: str, acceptance: str = "") -> None:
60
+ key = req_id.upper()
61
+ if key in seen or len(out) >= MAX_REQUIREMENTS or not text:
62
+ return
63
+ seen.add(key)
64
+ item = {"id": key, "kind": _kind(key), "text": _clip(text), "section": section}
65
+ if acceptance:
66
+ item["acceptance"] = _clip(acceptance)
67
+ out.append(item)
68
+
69
+ for i, line in enumerate(lines):
70
+ heading = re.match(r"^#{1,6}\s+(.*)$", line)
71
+ if heading:
72
+ section = _clip(heading.group(1))[:200]
73
+ header = None
74
+ continue
75
+ if line.strip().startswith("|"):
76
+ nxt = lines[i + 1] if i + 1 < len(lines) else ""
77
+ if header is None and _SEPARATOR.match(nxt):
78
+ header = _cells(line)
79
+ continue
80
+ if _SEPARATOR.match(line):
81
+ continue
82
+ cells = _cells(line)
83
+ id_col = next((k for k, c in enumerate(cells) if _ID.match(c)), None)
84
+ if id_col is None:
85
+ continue
86
+ req_id = _ID.match(cells[id_col]).group(1)
87
+ names = header or []
88
+ text_col = next((k for k, h in enumerate(names) if k != id_col and _TEXT_HEADER.search(h)), None)
89
+ if text_col is None:
90
+ text_col = id_col + 1
91
+ accept_col = next((k for k, h in enumerate(names) if _ACCEPT_HEADER.search(h)), None)
92
+ text = cells[text_col] if text_col < len(cells) else ""
93
+ acceptance = cells[accept_col] if accept_col is not None and accept_col < len(cells) else ""
94
+ add(req_id, text, acceptance)
95
+ continue
96
+ header = None
97
+ bullet = _BULLET.match(line)
98
+ if bullet:
99
+ add(bullet.group(1), bullet.group(2))
100
+ return out
101
+
102
+
103
+ def requirements_document(markdown: str, source: str) -> Dict[str, object]:
104
+ return {
105
+ "format": FORMAT,
106
+ "source": Path(source).name,
107
+ "generated": datetime.now(timezone.utc).isoformat(timespec="seconds"),
108
+ "requirements": extract_requirements(markdown),
109
+ }
110
+
111
+
112
+ def write_requirements_json(report_path: Path, markdown: str) -> Optional[Path]:
113
+ """Write requirements.json next to the report; nothing when it has no requirement with an id."""
114
+ doc = requirements_document(markdown, str(report_path))
115
+ if not doc["requirements"]:
116
+ return None
117
+ path = report_path.parent / FILE_NAME
118
+ path.parent.mkdir(parents=True, exist_ok=True)
119
+ path.write_text(json.dumps(doc, indent=2), encoding="utf-8")
120
+ return path
@@ -0,0 +1,191 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from typing import Any, Dict, List, Optional, Tuple
6
+
7
+ import yaml
8
+
9
+ DEFAULT_LLMS_JSON: Dict[str, Any] = {
10
+ "default": "mock",
11
+ "models": {
12
+ "mock": {
13
+ "provider": "mock",
14
+ "model": "mock",
15
+ "temperature": 0.0,
16
+ "description": "Offline deterministic provider for tests and dry-runs",
17
+ },
18
+ "azure-gpt4o": {
19
+ "provider": "azure",
20
+ "model": "gpt-4o",
21
+ "deployment": "gpt-4o",
22
+ "endpoint": "https://YOUR_RESOURCE.openai.azure.com/",
23
+ "api_key_env": "RA_AZURE_API_KEY",
24
+ "api_version": "2024-05-01-preview",
25
+ "temperature": 0.3,
26
+ "description": "Azure OpenAI GPT-4o",
27
+ },
28
+ "openai-gpt4o": {
29
+ "provider": "openai",
30
+ "model": "gpt-4o",
31
+ "api_key_env": "OPENAI_API_KEY",
32
+ "temperature": 0.3,
33
+ "description": "OpenAI API GPT-4o",
34
+ },
35
+ "ollama-llama": {
36
+ "provider": "ollama",
37
+ "model": "llama3.2",
38
+ "endpoint": "http://127.0.0.1:11434/v1",
39
+ "api_key_env": "RA_API_KEY",
40
+ "temperature": 0.2,
41
+ "description": "Local Ollama (OpenAI-compatible)",
42
+ },
43
+ "compatible": {
44
+ "provider": "openai_compatible",
45
+ "model": "gpt-4o",
46
+ "endpoint": "https://your-gateway.example/v1",
47
+ "api_key_env": "RA_API_KEY",
48
+ "temperature": 0.3,
49
+ "description": "Any OpenAI-compatible chat endpoint",
50
+ },
51
+ },
52
+ }
53
+
54
+ DEFAULT_AGENT_YAML: Dict[str, Any] = {
55
+ "llm": {
56
+ "models_file": "./llms.json",
57
+ "active": "mock",
58
+ },
59
+ "context": {
60
+ "providers": ["folder"],
61
+ "folder_paths": [],
62
+ # "rag": {}, # phase 2
63
+ # "mcp": {}, # phase 2
64
+ },
65
+ "prompts": {
66
+ "step_instruction": "",
67
+ "guiderails": "",
68
+ "personas": {
69
+ "bmad-orchestrator": {"system_extra": ""},
70
+ "analyst": {"system_extra": ""},
71
+ "pm": {"system_extra": ""},
72
+ "po": {"system_extra": ""},
73
+ "architect": {"system_extra": ""},
74
+ "dev": {"system_extra": ""},
75
+ "qa": {"system_extra": ""},
76
+ "sm": {"system_extra": ""},
77
+ },
78
+ },
79
+ "export": {
80
+ "default_format": "md",
81
+ "out_dir": "./out",
82
+ },
83
+ }
84
+
85
+ ENV_EXAMPLE = """# Requirements Agent — copy values into your shell profile or `.env`
86
+ # Active profile is selected in requirements-agent.yaml → llm.active (or --profile)
87
+
88
+ # Azure
89
+ # export RA_AZURE_API_KEY=...
90
+ # export RA_AZURE_ENDPOINT=https://YOUR_RESOURCE.openai.azure.com/
91
+ # export RA_AZURE_DEPLOYMENT=gpt-4o
92
+
93
+ # OpenAI
94
+ # export OPENAI_API_KEY=...
95
+
96
+ # Generic / compatible / ollama
97
+ # export RA_API_KEY=...
98
+ # export RA_LLM_ENDPOINT=http://127.0.0.1:11434/v1
99
+
100
+ # Optional overrides
101
+ # export RA_CONFIG=./requirements-agent.yaml
102
+ # export RA_LLMS_JSON=./llms.json
103
+ # export RA_LLM_PROFILE=azure-gpt4o
104
+ """
105
+
106
+
107
+ def write_json(path: Path, data: Dict[str, Any]) -> Path:
108
+ path.parent.mkdir(parents=True, exist_ok=True)
109
+ path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
110
+ return path
111
+
112
+
113
+ def write_yaml(path: Path, data: Dict[str, Any]) -> Path:
114
+ path.parent.mkdir(parents=True, exist_ok=True)
115
+ path.write_text(
116
+ yaml.safe_dump(data, sort_keys=False, allow_unicode=True, default_flow_style=False),
117
+ encoding="utf-8",
118
+ )
119
+ return path
120
+
121
+
122
+ def init_workspace(
123
+ target: Path,
124
+ *,
125
+ force: bool = False,
126
+ active_profile: str = "mock",
127
+ global_home: bool = False,
128
+ ) -> Tuple[List[Path], List[str]]:
129
+ """Create requirements-agent.yaml, llms.json, and .env.example.
130
+
131
+ Returns (created_or_updated_paths, notes).
132
+ """
133
+ target = target.expanduser().resolve()
134
+ target.mkdir(parents=True, exist_ok=True)
135
+
136
+ if global_home:
137
+ # Still write relative models_file inside user config dir
138
+ yaml_path = target / "requirements-agent.yaml"
139
+ llms_path = target / "llms.json"
140
+ env_path = target / ".env.example"
141
+ models_file = str(llms_path)
142
+ else:
143
+ yaml_path = target / "requirements-agent.yaml"
144
+ llms_path = target / "llms.json"
145
+ env_path = target / ".env.example"
146
+ models_file = "./llms.json"
147
+
148
+ created: List[Path] = []
149
+ notes: List[str] = []
150
+
151
+ llms = json.loads(json.dumps(DEFAULT_LLMS_JSON)) # deep copy
152
+ if active_profile in llms["models"]:
153
+ llms["default"] = active_profile
154
+ else:
155
+ notes.append(f"Unknown profile '{active_profile}'; keeping default 'mock'.")
156
+ active_profile = "mock"
157
+ llms["default"] = "mock"
158
+
159
+ agent = json.loads(json.dumps(DEFAULT_AGENT_YAML))
160
+ agent["llm"]["models_file"] = models_file
161
+ agent["llm"]["active"] = active_profile
162
+
163
+ def _write(path: Path, writer) -> None:
164
+ if path.exists() and not force:
165
+ notes.append(f"Skipped existing {path} (use --force to overwrite)")
166
+ return
167
+ writer()
168
+ created.append(path)
169
+
170
+ _write(llms_path, lambda: write_json(llms_path, llms))
171
+ _write(yaml_path, lambda: write_yaml(yaml_path, agent))
172
+ _write(env_path, lambda: env_path.write_text(ENV_EXAMPLE, encoding="utf-8") or env_path)
173
+
174
+ gitignore = target / ".gitignore"
175
+ if not gitignore.exists() or force:
176
+ extra = "\n".join(
177
+ [
178
+ "# requirements-agent secrets / local config",
179
+ ".env",
180
+ "llms.local.json",
181
+ "out/",
182
+ "",
183
+ ]
184
+ )
185
+ if gitignore.exists() and force:
186
+ gitignore.write_text(gitignore.read_text(encoding="utf-8") + "\n" + extra, encoding="utf-8")
187
+ elif not gitignore.exists():
188
+ gitignore.write_text(extra, encoding="utf-8")
189
+ created.append(gitignore)
190
+
191
+ return created, notes
@@ -0,0 +1,3 @@
1
+ from __future__ import annotations
2
+
3
+ # llm package
@@ -0,0 +1,49 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+ from dataclasses import dataclass, field
5
+ from typing import Any, Callable, Dict, List, Optional
6
+
7
+ DeltaCallback = Callable[[str, str], None] # (delta, accumulated)
8
+
9
+
10
+ @dataclass
11
+ class ChatMessage:
12
+ role: str
13
+ content: str
14
+
15
+
16
+ @dataclass
17
+ class ChatResult:
18
+ content: str
19
+ usage: Dict[str, Any] = field(default_factory=dict)
20
+
21
+
22
+ class LlmClient(ABC):
23
+ @abstractmethod
24
+ def chat(
25
+ self,
26
+ messages: List[ChatMessage],
27
+ *,
28
+ max_tokens: int = 4096,
29
+ temperature: Optional[float] = None,
30
+ seed: Optional[int] = None,
31
+ ) -> ChatResult:
32
+ raise NotImplementedError
33
+
34
+ def stream_chat(
35
+ self,
36
+ messages: List[ChatMessage],
37
+ *,
38
+ max_tokens: int = 4096,
39
+ temperature: Optional[float] = None,
40
+ seed: Optional[int] = None,
41
+ on_delta: Optional[DeltaCallback] = None,
42
+ ) -> ChatResult:
43
+ """Stream tokens when supported; default falls back to one-shot ``chat``."""
44
+ result = self.chat(
45
+ messages, max_tokens=max_tokens, temperature=temperature, seed=seed
46
+ )
47
+ if on_delta and result.content:
48
+ on_delta(result.content, result.content)
49
+ return result
@@ -0,0 +1,171 @@
1
+ """
2
+ GitHub Copilot seats as the model (``provider: github_copilot`` in llms.json), through GitHub's Copilot SDK
3
+ (``pip install 'requirements-agent[copilot]'``), the way ForgeQE runs it (ForgeQE/py/forgeqe_engine/copilot_gateway.py).
4
+
5
+ It signs in as the SDK documents: on the user's own machine as the signed-in user (``forgeqe auth login copilot``, or
6
+ GitHub's ``copilot login``); without a browser, with a fine-grained token with the Copilot Requests permission in
7
+ COPILOT_GITHUB_TOKEN (or the profile's ``api_key_env``). Each call is a Copilot session with the caller's prompt only:
8
+ none of Copilot's own tools, no project files, skills, saved sessions or session telemetry, and every permission
9
+ request refused. GitHub counts each call as one premium request times the model's multiplier.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import os
15
+ import tempfile
16
+ import threading
17
+ from typing import Any, Dict, List, Optional
18
+
19
+ from requirements_agent.config import LlmConfig
20
+ from requirements_agent.llm.base import ChatMessage, ChatResult, DeltaCallback, LlmClient
21
+
22
+ TOKEN_ENV = "COPILOT_GITHUB_TOKEN"
23
+ DEFAULT_KEY_ENV = "RA_API_KEY"
24
+ REQUEST_TIMEOUT_S = 300.0
25
+ EFFORTS = ("low", "medium", "high", "xhigh", "max")
26
+
27
+ NOT_INSTALLED = (
28
+ "GitHub Copilot needs GitHub's Copilot SDK: pip install 'requirements-agent[copilot]' "
29
+ "(or pip install github-copilot-sdk==1.0.28)."
30
+ )
31
+ CLASSIC_TOKEN = (
32
+ "GitHub Copilot does not take classic tokens (ghp_): sign in with forgeqe auth login copilot or GitHub's "
33
+ "copilot login, or use a fine-grained token with the Copilot Requests permission."
34
+ )
35
+
36
+
37
+ def copilot_token(config: LlmConfig, env: Optional[Dict[str, str]] = None) -> Optional[str]:
38
+ """The profile's api_key_env when it names one, else COPILOT_GITHUB_TOKEN; None means the signed-in user.
39
+
40
+ Other providers' keys (OPENAI_API_KEY, RA_AZURE_API_KEY) are never sent to GitHub.
41
+ """
42
+ e = os.environ if env is None else env
43
+ name = config.api_key_env if config.api_key_env and config.api_key_env != DEFAULT_KEY_ENV else TOKEN_ENV
44
+ value = (e.get(name) or "").strip()
45
+ if value.startswith("ghp_"):
46
+ raise ValueError(CLASSIC_TOKEN)
47
+ return value or None
48
+
49
+
50
+ def copilot_home(env: Optional[Dict[str, str]] = None) -> Optional[str]:
51
+ """Where the sign-in is: RA_COPILOT_HOME, else ForgeQE's Copilot home when it has one, else the SDK's own."""
52
+ e = os.environ if env is None else env
53
+ if e.get("RA_COPILOT_HOME"):
54
+ return os.path.expanduser(e["RA_COPILOT_HOME"])
55
+ forgeqe = os.path.join(e.get("FORGEQE_HOME") or os.path.join(os.path.expanduser("~"), ".forgeqe"), "copilot")
56
+ return forgeqe if os.path.isdir(forgeqe) else None
57
+
58
+
59
+ def prompt_of(messages: List[ChatMessage]) -> Dict[str, str]:
60
+ """The system message, and the rest as one prompt, oldest first."""
61
+ system = "\n\n".join(m.content for m in messages if m.role in ("system", "developer") and m.content)
62
+ turns = [m for m in messages if m.role not in ("system", "developer")]
63
+ if len(turns) == 1:
64
+ prompt = turns[0].content
65
+ else:
66
+ body = "\n\n".join(f"<{m.role}>\n{m.content}\n</{m.role}>" for m in turns)
67
+ prompt = "The conversation so far, oldest first. Reply as the assistant to the last message.\n\n" + body
68
+ return {"system": system or "You are a helpful assistant.", "prompt": prompt}
69
+
70
+
71
+ class CopilotClient(LlmClient):
72
+ """One Copilot client for the agent's life, on a loop of its own; each chat is a fresh Copilot session."""
73
+
74
+ def __init__(self, config: LlmConfig, sdk: Any = None) -> None:
75
+ self.config = config
76
+ self.token = copilot_token(config)
77
+ self._sdk = sdk
78
+ self._client: Any = None
79
+ self._loop = asyncio.new_event_loop()
80
+ self._thread = threading.Thread(target=self._loop.run_forever, name="copilot", daemon=True)
81
+ self._thread.start()
82
+ self._workdir = tempfile.mkdtemp(prefix="req-agent-copilot-")
83
+
84
+ def _run(self, coro: Any) -> Any:
85
+ return asyncio.run_coroutine_threadsafe(coro, self._loop).result(REQUEST_TIMEOUT_S + 30)
86
+
87
+ async def _ensure(self) -> Any:
88
+ if self._client is not None:
89
+ return self._client
90
+ sdk = self._sdk
91
+ if sdk is None:
92
+ try:
93
+ import copilot as sdk # type: ignore[no-redef]
94
+ except ImportError as e:
95
+ raise RuntimeError(NOT_INSTALLED) from e
96
+ auth: Dict[str, Any] = {"github_token": self.token, "use_logged_in_user": False} if self.token else {"use_logged_in_user": True}
97
+ home = copilot_home()
98
+ client = sdk.CopilotClient(**auth, **({"base_directory": home} if home else {}), working_directory=self._workdir, log_level="error")
99
+ await client.start()
100
+ status = await client.get_auth_status()
101
+ if not getattr(status, "isAuthenticated", False):
102
+ await client.stop()
103
+ raise RuntimeError(
104
+ "GitHub Copilot did not accept the token: use a fine-grained token with the Copilot Requests permission."
105
+ if self.token
106
+ else "GitHub Copilot is not signed in: run forgeqe auth login copilot (or GitHub's copilot login), "
107
+ f"or set {TOKEN_ENV} to a fine-grained token with the Copilot Requests permission."
108
+ )
109
+ self._client = client
110
+ return client
111
+
112
+ async def _chat(self, messages: List[ChatMessage], on_delta: Optional[DeltaCallback]) -> ChatResult:
113
+ client = await self._ensure()
114
+ from copilot.generated.rpc import PermissionDecisionReject # type: ignore
115
+ from copilot.session_events import AssistantMessageData, AssistantMessageDeltaData, AssistantUsageData # type: ignore
116
+
117
+ p = prompt_of(messages)
118
+ usage = {"input_tokens": 0, "output_tokens": 0}
119
+ text: List[str] = []
120
+
121
+ def on_event(event: Any) -> None:
122
+ data = getattr(event, "data", None)
123
+ if isinstance(data, AssistantUsageData):
124
+ usage["input_tokens"] += data.input_tokens or 0
125
+ usage["output_tokens"] += data.output_tokens or 0
126
+ elif on_delta and isinstance(data, AssistantMessageDeltaData) and data.delta_content and not data.parent_tool_call_id:
127
+ text.append(data.delta_content)
128
+ on_delta(data.delta_content, "".join(text))
129
+
130
+ effort = os.getenv("RA_COPILOT_REASONING_EFFORT", "").strip().lower()
131
+ session = await client.create_session(
132
+ model=self.config.model,
133
+ system_message={"mode": "replace", "content": p["system"]},
134
+ available_tools=[],
135
+ on_permission_request=lambda *_: PermissionDecisionReject(),
136
+ working_directory=self._workdir,
137
+ skip_custom_instructions=True,
138
+ enable_config_discovery=False,
139
+ enable_skills=False,
140
+ enable_session_store=False,
141
+ enable_session_telemetry=False,
142
+ on_event=on_event,
143
+ **({"reasoning_effort": effort} if effort in EFFORTS else {}),
144
+ **({"streaming": True} if on_delta else {}),
145
+ )
146
+ try:
147
+ reply = await session.send_and_wait(p["prompt"], timeout=REQUEST_TIMEOUT_S)
148
+ finally:
149
+ try:
150
+ await session.disconnect()
151
+ except Exception:
152
+ pass
153
+ data = getattr(reply, "data", None)
154
+ content = (data.content or "") if isinstance(data, AssistantMessageData) else ""
155
+ usage["total_tokens"] = usage["input_tokens"] + usage["output_tokens"]
156
+ return ChatResult(content=content.strip(), usage=usage)
157
+
158
+ def chat(self, messages: List[ChatMessage], *, max_tokens: int = 4096, temperature: Optional[float] = None, seed: Optional[int] = None) -> ChatResult:
159
+ # Copilot sessions take no max_tokens, temperature or seed: the model's own settings apply.
160
+ return self._run(self._chat(messages, None))
161
+
162
+ def stream_chat(
163
+ self,
164
+ messages: List[ChatMessage],
165
+ *,
166
+ max_tokens: int = 4096,
167
+ temperature: Optional[float] = None,
168
+ seed: Optional[int] = None,
169
+ on_delta: Optional[DeltaCallback] = None,
170
+ ) -> ChatResult:
171
+ return self._run(self._chat(messages, on_delta))
@@ -0,0 +1,144 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ from typing import List, Optional
5
+
6
+ from requirements_agent.llm.base import ChatMessage, ChatResult, DeltaCallback, LlmClient
7
+
8
+
9
+ class MockLlmClient(LlmClient):
10
+ """Deterministic offline provider for tests and dry runs."""
11
+
12
+ def __init__(self, label: str = "mock", *, stream_delay: float = 0.0, stream_chunk: int = 48):
13
+ self.label = label
14
+ self.calls: List[List[ChatMessage]] = []
15
+ self.stream_delay = stream_delay
16
+ self.stream_chunk = max(8, stream_chunk)
17
+
18
+ def chat(
19
+ self,
20
+ messages: List[ChatMessage],
21
+ *,
22
+ max_tokens: int = 4096,
23
+ temperature: Optional[float] = None,
24
+ seed: Optional[int] = None,
25
+ ) -> ChatResult:
26
+ self.calls.append(list(messages))
27
+ content = self._content_for(messages)
28
+ return ChatResult(content=content, usage={"total_tokens": 42, "estimated": True})
29
+
30
+ def stream_chat(
31
+ self,
32
+ messages: List[ChatMessage],
33
+ *,
34
+ max_tokens: int = 4096,
35
+ temperature: Optional[float] = None,
36
+ seed: Optional[int] = None,
37
+ on_delta: Optional[DeltaCallback] = None,
38
+ ) -> ChatResult:
39
+ self.calls.append(list(messages))
40
+ content = self._content_for(messages)
41
+ if on_delta and content:
42
+ acc = ""
43
+ step = self.stream_chunk
44
+ for i in range(0, len(content), step):
45
+ piece = content[i : i + step]
46
+ acc += piece
47
+ on_delta(piece, acc)
48
+ if self.stream_delay:
49
+ time.sleep(self.stream_delay)
50
+ return ChatResult(content=content, usage={"total_tokens": 42, "estimated": True})
51
+
52
+ def _content_for(self, messages: List[ChatMessage]) -> str:
53
+ system = next((m.content for m in messages if m.role == "system"), "")
54
+ user = next((m.content for m in reversed(messages) if m.role == "user"), "")
55
+
56
+ if "score requirement" in user.lower() or "dimensions" in system.lower():
57
+ return (
58
+ '{"overall_score":72,"dimensions":{"completeness":70,"clarity":75,'
59
+ '"testability":68,"risk_nfr_consistency":72,"traceability":74,'
60
+ '"dependency_integration":71},"rationale":"Mock score for offline run.",'
61
+ '"top_gaps":["Add measurable NFRs","Clarify integration owners"]}'
62
+ )
63
+ if "extract unresolved" in system.lower() or "open questions" in user.lower():
64
+ return (
65
+ '{"categories":['
66
+ '{"id":"technical","title":"Technical & Architecture","questions":["What auth protocol is required?"]},'
67
+ '{"id":"business","title":"Business & Logic","questions":["Who owns the KPI?"]},'
68
+ '{"id":"general","title":"Ambiguities & Clarifications","questions":["What is out of scope for v1?"]}'
69
+ "]}"
70
+ )
71
+ if "resolving a single open question" in system.lower():
72
+ return (
73
+ '{"suggestion":"Use OAuth 2.0 Authorization Code with PKCE for interactive clients.",'
74
+ '"rationale":"Matches common enterprise defaults for SSO.",'
75
+ '"resolution_steps":[{"title":"Adopt OAuth2+PKCE","detail":"Require Authorization Code + PKCE.",'
76
+ '"example":"grant_type=authorization_code"}],'
77
+ '"examples":[{"label":"Sample AC","content":"Given a user logs in, When tokens issue, Then refresh is rotatable."}],'
78
+ '"assumptions":["Assumes B2B SaaS"]}'
79
+ )
80
+ if "refining ONE section" in system or "TARGET section to rewrite" in user:
81
+ import re
82
+
83
+ m = re.search(r"Return ONLY the revised `## (.+?)` section", user)
84
+ heading = m.group(1).strip() if m else "Section"
85
+ return (
86
+ f"## {heading}\n\n"
87
+ f"Refined content for **{heading}** per BA instruction.\n\n"
88
+ "| ID | item | acceptance |\n|---|---|---|\n"
89
+ f"| REF-001 | Updated {heading} detail | Measurable signal |\n\n"
90
+ "- Clarified owners and success metrics.\n"
91
+ )
92
+ if "enterprise BRD" in system or "complete enterprise BRD" in system.lower() or (
93
+ "# Requirements report" in system and "backlog" in system.lower()
94
+ ):
95
+ return (
96
+ "# Requirements report\n\n"
97
+ "## Business objective\n\nDeliver the described capability with measurable outcomes.\n\n"
98
+ "## Problem statement\n\nCurrent process is manual and error-prone.\n\n"
99
+ "## Scope\n\n### In scope\n- Core flow\n\n### Out of scope\n- Adjacent products\n\n"
100
+ "## High-level business requirements\n\n| BR-ID | statement | success signal |\n|---|---|---|\n| BR-001 | Users can complete the flow | Conversion >= baseline |\n\n"
101
+ "## User journey\n\n### Current\n1. Manual steps\n\n### Future\n1. Guided digital flow\n\n"
102
+ "## Functional requirements\n\n| FR-ID | behaviour | trigger / preconditions | acceptance signal | error codes |\n|---|---|---|---|---|\n| FR-001 | Submit request | Authenticated | 201 Created | 400,401 |\n\n"
103
+ "## Business rules\n\n| BRULE-ID | rule | enforcement | exception |\n|---|---|---|---|\n| BRULE-001 | Validate input | API | admin override |\n\n"
104
+ "## Non-functional requirements\n\n| NFR-ID | category | target | how verified |\n|---|---|---|---|\n| NFR-001 | latency | p95 < 300ms | load test |\n\n"
105
+ "## Data and audit requirements\n\nEntities and audit events recorded.\n\n"
106
+ "## Dependencies\n\n| system | contract / API | timeout | failure mode | owner |\n|---|---|---|---|---|\n| IdP | OIDC | 3s | fail-closed | IAM |\n\n"
107
+ "## Risks and considerations\n\n| risk | likelihood | impact | mitigation | residual |\n|---|---|---|---|\n| Token theft | med | high | PKCE + short TTL | low |\n\n"
108
+ "## Assumptions\n\n1. Single region deployment.\n\n"
109
+ "## Reporting and monitoring\n\nDashboards for conversion and error rates.\n"
110
+ )
111
+ if "editor for AI-generated requirements" in system.lower():
112
+ return (
113
+ "# Spec circuit report\n\n## Overview\n\nRefined mock report incorporating the latest request.\n\n"
114
+ "## Business Analyst\n\nUpdated clarity and stakeholder notes.\n"
115
+ )
116
+ if "## " in system and "heading" in system.lower() or "multi-role requirements review" in system.lower():
117
+ import re
118
+
119
+ heading = "Overview"
120
+ m = re.search(r"Start with exactly one markdown heading: ## (.+)", system)
121
+ if m:
122
+ heading = m.group(1).strip()
123
+ else:
124
+ for token in (
125
+ "Overview",
126
+ "Business Analyst",
127
+ "Product Manager",
128
+ "Product Owner",
129
+ "Solution Architect",
130
+ "Developer",
131
+ "QA",
132
+ "Scrum Master",
133
+ ):
134
+ if token in system:
135
+ heading = token
136
+ break
137
+ return (
138
+ f"## {heading}\n\n"
139
+ f"Mock analysis for **{heading}** based on the supplied requirement.\n\n"
140
+ "| ID | Finding | Recommendation |\n|---|---|---|\n"
141
+ f"| FR-MOCK-1 | Clarify success metrics for {heading} | Add measurable acceptance |\n\n"
142
+ "- Gap: missing edge cases\n- Risk: integration ownership unclear\n"
143
+ )
144
+ return "# Mock response\n\nGenerated by MockLlmClient.\n"