@capagents/forgeqe 3.3.0 → 3.3.2

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 (217) hide show
  1. package/HOW_TO_USE.md +32 -0
  2. package/dist/docs-site/docs/area-setup/index.html +1 -0
  3. package/dist/docs-site/docs/area-test-cases/index.html +25 -0
  4. package/dist/docs-site/docs/search.js +1 -1
  5. package/dist/forgeqe.js +1922 -1906
  6. package/dist/requirement-agent/requirements_agent/__init__.py +3 -0
  7. package/dist/requirement-agent/requirements_agent/__main__.py +5 -0
  8. package/dist/requirement-agent/requirements_agent/agent.py +363 -0
  9. package/dist/requirement-agent/requirements_agent/chat_session.py +424 -0
  10. package/dist/requirement-agent/requirements_agent/cli.py +870 -0
  11. package/dist/requirement-agent/requirements_agent/config.py +403 -0
  12. package/dist/requirement-agent/requirements_agent/console_ui.py +632 -0
  13. package/dist/requirement-agent/requirements_agent/context/__init__.py +3 -0
  14. package/dist/requirement-agent/requirements_agent/context/aggregate.py +214 -0
  15. package/dist/requirement-agent/requirements_agent/context/base.py +14 -0
  16. package/dist/requirement-agent/requirements_agent/context/folder.py +107 -0
  17. package/dist/requirement-agent/requirements_agent/context/given.py +70 -0
  18. package/dist/requirement-agent/requirements_agent/context/graph.py +181 -0
  19. package/dist/requirement-agent/requirements_agent/context/knowledge.py +192 -0
  20. package/dist/requirement-agent/requirements_agent/context/mcp.py +24 -0
  21. package/dist/requirement-agent/requirements_agent/context/memory.py +144 -0
  22. package/dist/requirement-agent/requirements_agent/context/personas.py +214 -0
  23. package/dist/requirement-agent/requirements_agent/context/rag.py +148 -0
  24. package/dist/requirement-agent/requirements_agent/context/untrusted.py +56 -0
  25. package/dist/requirement-agent/requirements_agent/docs/HOW_TO_USE.md +505 -0
  26. package/dist/requirement-agent/requirements_agent/docs/requirements-agent-architecture.html +348 -0
  27. package/dist/requirement-agent/requirements_agent/docs_cmd.py +51 -0
  28. package/dist/requirement-agent/requirements_agent/export/__init__.py +3 -0
  29. package/dist/requirement-agent/requirements_agent/export/markdown.py +55 -0
  30. package/dist/requirement-agent/requirements_agent/export/pdf.py +82 -0
  31. package/dist/requirement-agent/requirements_agent/export/requirements_json.py +120 -0
  32. package/dist/requirement-agent/requirements_agent/init_cmd.py +191 -0
  33. package/dist/requirement-agent/requirements_agent/llm/__init__.py +3 -0
  34. package/dist/requirement-agent/requirements_agent/llm/base.py +49 -0
  35. package/dist/requirement-agent/requirements_agent/llm/copilot.py +171 -0
  36. package/dist/requirement-agent/requirements_agent/llm/mock.py +144 -0
  37. package/dist/requirement-agent/requirements_agent/llm/providers.py +277 -0
  38. package/dist/requirement-agent/requirements_agent/llm/router.py +35 -0
  39. package/dist/requirement-agent/requirements_agent/models.py +73 -0
  40. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/analyst.md +29 -0
  41. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/architect.md +28 -0
  42. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/bmad-orchestrator.md +26 -0
  43. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/dev.md +27 -0
  44. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/pm.md +27 -0
  45. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/po.md +27 -0
  46. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/qa.md +28 -0
  47. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/sm.md +26 -0
  48. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-analyst.md +8 -0
  49. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-architect.md +11 -0
  50. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-dev.md +11 -0
  51. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-orchestrator.md +9 -0
  52. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-pm.md +9 -0
  53. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-po.md +10 -0
  54. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-qa.md +11 -0
  55. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-sm.md +8 -0
  56. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/data/bmad-kb.md +19 -0
  57. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/data/requirements-standards-baseline.md +188 -0
  58. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/data/technical-preferences.md +54 -0
  59. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/utils/template-format.md +7 -0
  60. package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/workflows/greenfield-fullstack.yml +177 -0
  61. package/dist/requirement-agent/requirements_agent/pipeline/__init__.py +3 -0
  62. package/dist/requirement-agent/requirements_agent/pipeline/brd.py +86 -0
  63. package/dist/requirement-agent/requirements_agent/pipeline/pack.py +233 -0
  64. package/dist/requirement-agent/requirements_agent/pipeline/progress.py +60 -0
  65. package/dist/requirement-agent/requirements_agent/pipeline/prompts.py +150 -0
  66. package/dist/requirement-agent/requirements_agent/pipeline/quality.py +124 -0
  67. package/dist/requirement-agent/requirements_agent/pipeline/refine.py +386 -0
  68. package/dist/requirement-agent/requirements_agent/pipeline/sections.py +117 -0
  69. package/dist/requirement-agent/requirements_agent/pipeline/spec_circuit.py +142 -0
  70. package/dist/requirement-agent/requirements_agent/shell/__init__.py +7 -0
  71. package/dist/requirement-agent/requirements_agent/shell/actions.py +208 -0
  72. package/dist/requirement-agent/requirements_agent/shell/app.py +902 -0
  73. package/dist/requirement-agent/requirements_agent/shell/commands.py +206 -0
  74. package/dist/requirement-agent/requirements_agent/shell/progress_pane.py +114 -0
  75. package/dist/requirement-agent/requirements_agent/shell/ref_picker.py +59 -0
  76. package/dist/requirement-agent/requirements_agent/shell/refs.py +120 -0
  77. package/dist/requirement-agent/requirements_agent/shell/session.py +362 -0
  78. package/dist/requirement-agent/requirements_agent/shell/transcript.py +241 -0
  79. package/dist/requirement-agent/requirements_agent/shell/usage.py +64 -0
  80. package/dist/requirement-agent/requirements_agent/shell/usage_llm.py +64 -0
  81. package/dist/requirement-agent/requirements_agent/shell/worker.py +378 -0
  82. package/dist/requirement-agent/requirements_agent/tuios_hook.py +182 -0
  83. package/dist/requirement-agent/requirements_agent/webops.py +627 -0
  84. package/dist/template.html +66 -66
  85. package/dist/web/assets/{3d-force-graph-DgKpiu6s.js → 3d-force-graph-DDyP5jcf.js} +1 -1
  86. package/dist/web/assets/Agent-sLaNlaQo.js +8 -0
  87. package/dist/web/assets/AgentWork-Dv0G4bt3.js +2 -0
  88. package/dist/web/assets/ApiTests-Bnw2qgWw.js +15 -0
  89. package/dist/web/assets/Browse-CBt1JY2E.js +1 -0
  90. package/dist/web/assets/Chat-DIWdnIZK.js +3 -0
  91. package/dist/web/assets/CommandPalette-DD04oS83.js +1 -0
  92. package/dist/web/assets/Compare-D0Ao8dZ6.js +1 -0
  93. package/dist/web/assets/Cost-BY_8-9Qt.js +1 -0
  94. package/dist/web/assets/{Data-CkQGUNww.js → Data-BC7R_FbW.js} +4 -4
  95. package/dist/web/assets/Desktop-CSQ2xLg0.js +1 -0
  96. package/dist/web/assets/DesktopReview-CCOhUdeJ.js +2 -0
  97. package/dist/web/assets/DeviceScreen-BHmTd9Q-.js +1 -0
  98. package/dist/web/assets/Evidence-9W4pqIkC.js +1 -0
  99. package/dist/web/assets/{Explore-k0Y19Q5T.js → Explore-BndXiEf8.js} +2 -2
  100. package/dist/web/assets/Features-BrfsTC9Q.js +1 -0
  101. package/dist/web/assets/{Flags-CXFDO-k_.js → Flags-DyykkeHU.js} +2 -2
  102. package/dist/web/assets/Flaky-C3gj_Brn.js +1 -0
  103. package/dist/web/assets/Impact-Z8nbNhbe.js +3 -0
  104. package/dist/web/assets/Jobs-CJWXAqSy.js +5 -0
  105. package/dist/web/assets/KindPage-C45x_cFz.js +6 -0
  106. package/dist/web/assets/LiveDevice-DGdLDigO.js +1 -0
  107. package/dist/web/assets/Migration-QFI5ctp7.js +8 -0
  108. package/dist/web/assets/Mobile-CuswZyee.js +1 -0
  109. package/dist/web/assets/Observability-CknZ_xBN.js +1 -0
  110. package/dist/web/assets/PageAgent-B2bmmMaP.js +1 -0
  111. package/dist/web/assets/Product-CrtwDiMv.js +12 -0
  112. package/dist/web/assets/Production-BMsytC2i.js +1 -0
  113. package/dist/web/assets/Quality-B4Aw6N3_.js +1 -0
  114. package/dist/web/assets/Readiness-CVIzTFX-.js +1 -0
  115. package/dist/web/assets/Record-B2Ic8Taj.js +1 -0
  116. package/dist/web/assets/Regression-bCIAE3Ne.js +5 -0
  117. package/dist/web/assets/RelationGraph-kG4YVMzl.js +1 -0
  118. package/dist/web/assets/Reports-NAZ-26Ub.js +2 -0
  119. package/dist/web/assets/Requirements-BkpiF-Bt.js +2 -0
  120. package/dist/web/assets/Responsive-CsaoisJq.js +3 -0
  121. package/dist/web/assets/RunDiff-BC-3Wg1b.js +1 -0
  122. package/dist/web/assets/Settings-DyBed-J5.js +21 -0
  123. package/dist/web/assets/Steps-DcQxQ4yA.js +2 -0
  124. package/dist/web/assets/TestData-wpUeU9Er.js +2 -0
  125. package/dist/web/assets/TestManagement-D0njkyAT.js +4 -0
  126. package/dist/web/assets/WhatsNew-BxIAAwgH.js +1 -0
  127. package/dist/web/assets/agentSettingsSheet-BdB7IXah.js +1 -0
  128. package/dist/web/assets/choice-C4-yW2x9.js +1 -0
  129. package/dist/web/assets/code-Jek8uWUO.js +1 -0
  130. package/dist/web/assets/{coverage-DirEXtfZ.js → coverage-q-ib7wOq.js} +1 -1
  131. package/dist/web/assets/dataParts-B2-a-pOD.js +3 -0
  132. package/dist/web/assets/desktopAppPath-C-p0zU40.js +1 -0
  133. package/dist/web/assets/frame-CjpZWX_X.js +13 -0
  134. package/dist/web/assets/index-BH5RbDNY.css +2 -0
  135. package/dist/web/assets/index-CfGXe_De.js +55 -0
  136. package/dist/web/assets/line-icons-CwCZidXs.js +1 -0
  137. package/dist/web/assets/logos-P2LOMyTK.js +1 -0
  138. package/dist/web/assets/{markdown-BnrLv6Iw.js → markdown-dXSsS-mD.js} +5 -5
  139. package/dist/web/assets/nav-BZfNOkhX.js +1 -0
  140. package/dist/web/assets/pageBack-BwKT31j3.js +3 -0
  141. package/dist/web/assets/palette-L37b4wTE.js +1 -0
  142. package/dist/web/assets/{paletteCommands-LXIICD4V.js → paletteCommands-zqGCORJu.js} +1 -1
  143. package/dist/web/assets/parts-3o6HnCp1.js +1 -0
  144. package/dist/web/assets/preload-helper-BupTYkQW.js +1 -0
  145. package/dist/web/assets/productParts-BDiEg0z6.js +1 -0
  146. package/dist/web/assets/qualityParts--CnSadOZ.js +1 -0
  147. package/dist/web/assets/radio-BLI4Ubhk.js +1 -0
  148. package/dist/web/assets/react-BDur5s0O.js +1 -0
  149. package/dist/web/assets/{recordTest-BzKpS4m5.js → recordTest-D092f975.js} +1 -1
  150. package/dist/web/assets/route-oDy8sV6H.js +1 -0
  151. package/dist/web/assets/sectionList-XiKcJNEK.js +1 -0
  152. package/dist/web/assets/step-mark-CaKf4dAR.js +1 -0
  153. package/dist/web/assets/stepper-naqAN_Nb.js +1 -0
  154. package/dist/web/assets/utils-DJRAScIl.js +1 -0
  155. package/dist/web/assets/wizardParts-DLlOHVMx.js +1 -0
  156. package/dist/web/index.html +14 -12
  157. package/docs/user-guide.html +26 -0
  158. package/package.json +2 -1
  159. package/py/forgeqe_engine/cli.py +7 -0
  160. package/dist/web/assets/Agent-BP11jrsE.js +0 -8
  161. package/dist/web/assets/AgentWork-DqiO3LUi.js +0 -2
  162. package/dist/web/assets/ApiTests-CLFt0wGW.js +0 -15
  163. package/dist/web/assets/Browse-D5VDHN9Z.js +0 -1
  164. package/dist/web/assets/Chat-BqqaT-n0.js +0 -3
  165. package/dist/web/assets/CommandPalette-D3F4iHrP.js +0 -1
  166. package/dist/web/assets/Compare-KeUsk4G3.js +0 -1
  167. package/dist/web/assets/Cost-CDdSNCkt.js +0 -1
  168. package/dist/web/assets/Desktop-COKu5aHU.js +0 -1
  169. package/dist/web/assets/DesktopReview-CMpXNurd.js +0 -2
  170. package/dist/web/assets/DeviceScreen-DJqblqBh.js +0 -1
  171. package/dist/web/assets/Evidence-CPevi78T.js +0 -1
  172. package/dist/web/assets/Features-D_miisXy.js +0 -1
  173. package/dist/web/assets/Flaky-CzaQIwXC.js +0 -1
  174. package/dist/web/assets/Impact-pos046GB.js +0 -3
  175. package/dist/web/assets/Jobs-C0TtzWA4.js +0 -5
  176. package/dist/web/assets/KindPage-DAvgKrwt.js +0 -6
  177. package/dist/web/assets/LiveDevice-C9LRZMhC.js +0 -1
  178. package/dist/web/assets/Migration-kYknzHdK.js +0 -8
  179. package/dist/web/assets/Mobile-AVi39qoN.js +0 -1
  180. package/dist/web/assets/Observability-l1ZN4JL0.js +0 -1
  181. package/dist/web/assets/PageAgent-DzVjKKYz.js +0 -1
  182. package/dist/web/assets/Product-CrnXTDkX.js +0 -12
  183. package/dist/web/assets/Production-B4VlKTlL.js +0 -1
  184. package/dist/web/assets/Quality-CtjVY15v.js +0 -1
  185. package/dist/web/assets/Readiness-RUzKklxF.js +0 -1
  186. package/dist/web/assets/Record-f87pdoaN.js +0 -1
  187. package/dist/web/assets/Regression-RSnjP5hS.js +0 -5
  188. package/dist/web/assets/RelationGraph-gc0Xmklt.js +0 -1
  189. package/dist/web/assets/Reports-881BJZ_u.js +0 -2
  190. package/dist/web/assets/Responsive-251XAuZE.js +0 -3
  191. package/dist/web/assets/RunDiff-DG0hKKDs.js +0 -1
  192. package/dist/web/assets/Settings-Cv3kUuOx.js +0 -21
  193. package/dist/web/assets/Steps-Cyjk5JtV.js +0 -2
  194. package/dist/web/assets/TestData-TcXA9UmV.js +0 -2
  195. package/dist/web/assets/TestManagement-D0e2N_Xr.js +0 -4
  196. package/dist/web/assets/WhatsNew-COVX946M.js +0 -1
  197. package/dist/web/assets/agentSettingsSheet-DGFh1_iF.js +0 -1
  198. package/dist/web/assets/choice-CiFogD01.js +0 -1
  199. package/dist/web/assets/code-DzYywAs5.js +0 -1
  200. package/dist/web/assets/dataParts-Di7PdPHu.js +0 -3
  201. package/dist/web/assets/desktopAppPath-B8j1-pX0.js +0 -1
  202. package/dist/web/assets/frame-CNLw552P.js +0 -13
  203. package/dist/web/assets/index-CuN17Qrj.js +0 -55
  204. package/dist/web/assets/index-Dchrk5Yt.css +0 -2
  205. package/dist/web/assets/line-icons-B-O8oBsY.js +0 -1
  206. package/dist/web/assets/nav-Ds_6IERv.js +0 -1
  207. package/dist/web/assets/pageBack-DJxbEPfN.js +0 -3
  208. package/dist/web/assets/palette-H2g-hemT.js +0 -1
  209. package/dist/web/assets/parts-DKRLtrjs.js +0 -1
  210. package/dist/web/assets/preload-helper-BML5SvL4.js +0 -1
  211. package/dist/web/assets/productParts-DvrCr604.js +0 -1
  212. package/dist/web/assets/qualityParts-BYx5phEI.js +0 -1
  213. package/dist/web/assets/radio-CbR6ODxQ.js +0 -1
  214. package/dist/web/assets/route-DjewvmpL.js +0 -1
  215. package/dist/web/assets/sectionList-0umoKvRv.js +0 -1
  216. package/dist/web/assets/step-mark-g8Eb6foB.js +0 -1
  217. package/dist/web/assets/stepper-CzZIC36d.js +0 -1
@@ -0,0 +1,386 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ from typing import Any, Callable, Dict, List, Optional
6
+
7
+ from requirements_agent.context.aggregate import ContextAggregator, build_base_user_prompt, context_for_edit
8
+ from requirements_agent.context.untrusted import data_block
9
+ from requirements_agent.llm.base import ChatMessage, LlmClient
10
+ from requirements_agent.models import ContextBundle
11
+ from requirements_agent.pipeline.progress import emit, make_stream_reporter
12
+ from requirements_agent.pipeline.prompts import (
13
+ OPEN_QUESTIONS_SYSTEM,
14
+ QUESTION_RESOLUTION_SYSTEM,
15
+ REFINE_SYSTEM,
16
+ SECTION_REFINE_SYSTEM,
17
+ )
18
+ from requirements_agent.pipeline.sections import (
19
+ list_h2_sections,
20
+ replace_section,
21
+ resolve_section,
22
+ section_slice,
23
+ )
24
+
25
+ ProgressCallback = Callable[[Dict[str, Any]], None]
26
+
27
+
28
+ def _strip_fence(text: str) -> str:
29
+ cleaned = (text or "").strip()
30
+ if cleaned.startswith("```"):
31
+ lines = cleaned.split("\n")
32
+ if lines and lines[0].startswith("```"):
33
+ lines = lines[1:]
34
+ if lines and lines[-1].strip().startswith("```"):
35
+ lines = lines[:-1]
36
+ cleaned = "\n".join(lines).strip()
37
+ return cleaned
38
+
39
+
40
+ def _strip_json_fence(text: str) -> str:
41
+ txt = (text or "").strip()
42
+ if txt.startswith("```"):
43
+ txt = re.sub(r"^```(?:json)?\s*", "", txt, flags=re.IGNORECASE).strip()
44
+ txt = re.sub(r"\s*```$", "", txt).strip()
45
+ return txt
46
+
47
+
48
+ class ReportRefiner:
49
+ def __init__(self, llm: LlmClient, context: Optional[ContextAggregator] = None):
50
+ self.llm = llm
51
+ self.context = context or ContextAggregator([])
52
+
53
+ def refine(
54
+ self,
55
+ title: str,
56
+ design: str,
57
+ report_markdown: str,
58
+ message: str,
59
+ *,
60
+ history: Optional[List[Dict[str, str]]] = None,
61
+ bundle: Optional[ContextBundle] = None,
62
+ section: Optional[str] = None,
63
+ on_progress: Optional[ProgressCallback] = None,
64
+ ) -> Dict[str, Any]:
65
+ if section:
66
+ return self.refine_section(
67
+ title,
68
+ design,
69
+ report_markdown,
70
+ message,
71
+ section=section,
72
+ history=history,
73
+ bundle=bundle,
74
+ on_progress=on_progress,
75
+ )
76
+
77
+ emit(on_progress, type="activity", phase="refine", message="Refining full document…")
78
+ rm = report_markdown or ""
79
+ if len(rm) > 120_000:
80
+ rm = rm[:120_000] + "\n\n_(report truncated for model context)_\n"
81
+
82
+ hist_lines: List[str] = []
83
+ for h in history or []:
84
+ r = (h.get("role") or "").strip()
85
+ c = (h.get("content") or "").strip()
86
+ if r in ("user", "assistant") and c:
87
+ label = "User" if r == "user" else "Assistant"
88
+ hist_lines.append(f"**{label}**: {c}")
89
+ hist_block = "\n\n".join(hist_lines) if hist_lines else "(none)"
90
+
91
+ bundle = bundle or self.context.gather(title, design)
92
+ att_section = context_for_edit(bundle)
93
+
94
+ user_content = (
95
+ f"# Requirement title\n{(title or '').strip()}\n\n"
96
+ f"# Design specification\n{data_block('requirement', 'the requirement under review', design)}\n\n"
97
+ f"{att_section}"
98
+ f"# Current report (markdown)\n\n{rm}\n\n"
99
+ f"---\n\n# Prior chat\n{hist_block}\n\n"
100
+ f"---\n\n# Latest request\n{(message or '').strip()}\n\n"
101
+ "Return the full updated markdown report now."
102
+ )
103
+ try:
104
+ out = self.llm.stream_chat(
105
+ [ChatMessage("system", REFINE_SYSTEM), ChatMessage("user", user_content)],
106
+ max_tokens=16384,
107
+ temperature=0.35,
108
+ on_delta=make_stream_reporter(on_progress, phase="refine"),
109
+ ).content
110
+ except Exception as e:
111
+ return {
112
+ "success": False,
113
+ "report_markdown": report_markdown,
114
+ "assistant_message": "",
115
+ "section": None,
116
+ "error": str(e),
117
+ }
118
+ if not out:
119
+ return {
120
+ "success": False,
121
+ "report_markdown": report_markdown,
122
+ "assistant_message": "",
123
+ "section": None,
124
+ "error": "The model returned no content.",
125
+ }
126
+ emit(on_progress, type="activity", phase="refine", message="Full document refined")
127
+ return {
128
+ "success": True,
129
+ "report_markdown": _strip_fence(out),
130
+ "assistant_message": "Report updated.",
131
+ "section": None,
132
+ "error": None,
133
+ }
134
+
135
+ def refine_section(
136
+ self,
137
+ title: str,
138
+ design: str,
139
+ report_markdown: str,
140
+ message: str,
141
+ *,
142
+ section: str,
143
+ history: Optional[List[Dict[str, str]]] = None,
144
+ bundle: Optional[ContextBundle] = None,
145
+ on_progress: Optional[ProgressCallback] = None,
146
+ ) -> Dict[str, Any]:
147
+ target, all_sections = resolve_section(report_markdown, section)
148
+ if target is None:
149
+ names = ", ".join(f"{s.index}:{s.heading}" for s in all_sections[:20]) or "(none)"
150
+ return {
151
+ "success": False,
152
+ "report_markdown": report_markdown,
153
+ "assistant_message": "",
154
+ "section": None,
155
+ "error": f"Section not found: {section!r}. Available: {names}",
156
+ }
157
+
158
+ emit(
159
+ on_progress,
160
+ type="activity",
161
+ phase="refine",
162
+ message=f"Refining section [{target.index}] {target.heading}…",
163
+ )
164
+ current = section_slice(report_markdown, target)
165
+ rm = report_markdown or ""
166
+ if len(rm) > 100_000:
167
+ rm = rm[:100_000] + "\n\n_(report truncated)_\n"
168
+
169
+ hist_lines: List[str] = []
170
+ for h in history or []:
171
+ r = (h.get("role") or "").strip()
172
+ c = (h.get("content") or "").strip()
173
+ if r in ("user", "assistant") and c:
174
+ label = "User" if r == "user" else "Assistant"
175
+ hist_lines.append(f"**{label}**: {c}")
176
+ hist_block = "\n\n".join(hist_lines) if hist_lines else "(none)"
177
+
178
+ bundle = bundle or self.context.gather(title, design)
179
+ att = context_for_edit(bundle)
180
+
181
+ user_content = (
182
+ f"# Requirement title\n{(title or '').strip()}\n\n"
183
+ f"# Design specification\n{data_block('requirement', 'the requirement under review', design)}\n\n"
184
+ f"{att}"
185
+ f"# Full report (context only — do not rewrite other sections)\n\n{rm}\n\n"
186
+ f"---\n\n# TARGET section to rewrite\n\n{current}\n\n"
187
+ f"---\n\n# Prior chat\n{hist_block}\n\n"
188
+ f"---\n\n# BA instruction for this section\n{(message or '').strip()}\n\n"
189
+ f"Return ONLY the revised `## {target.heading}` section now."
190
+ )
191
+ try:
192
+ out = self.llm.stream_chat(
193
+ [ChatMessage("system", SECTION_REFINE_SYSTEM), ChatMessage("user", user_content)],
194
+ max_tokens=8000,
195
+ temperature=0.35,
196
+ on_delta=make_stream_reporter(on_progress, phase="refine"),
197
+ ).content
198
+ except Exception as e:
199
+ return {
200
+ "success": False,
201
+ "report_markdown": report_markdown,
202
+ "assistant_message": "",
203
+ "section": {"index": target.index, "heading": target.heading},
204
+ "error": str(e),
205
+ }
206
+ if not out:
207
+ return {
208
+ "success": False,
209
+ "report_markdown": report_markdown,
210
+ "assistant_message": "",
211
+ "section": {"index": target.index, "heading": target.heading},
212
+ "error": "The model returned no content.",
213
+ }
214
+
215
+ revised = _strip_fence(out)
216
+ # Re-resolve offsets after we have the original target (still valid)
217
+ updated = replace_section(report_markdown, target, revised)
218
+ # Extract what we actually wrote back
219
+ new_target, _ = resolve_section(updated, str(target.index))
220
+ new_slice = section_slice(updated, new_target) if new_target else revised
221
+
222
+ emit(
223
+ on_progress,
224
+ type="activity",
225
+ phase="refine",
226
+ message=f"Updated section [{target.index}] {target.heading}",
227
+ preview=new_slice[-700:],
228
+ )
229
+ return {
230
+ "success": True,
231
+ "report_markdown": updated,
232
+ "section_markdown": new_slice,
233
+ "assistant_message": f"Updated ## {target.heading}",
234
+ "section": {"index": target.index, "heading": target.heading},
235
+ "error": None,
236
+ }
237
+
238
+ def list_sections(self, report_markdown: str) -> List[Dict[str, Any]]:
239
+ return [
240
+ {"index": s.index, "heading": s.heading, "chars": s.end - s.start}
241
+ for s in list_h2_sections(report_markdown)
242
+ ]
243
+
244
+ def extract_open_questions(
245
+ self,
246
+ title: str,
247
+ design: str,
248
+ report_markdown: str,
249
+ *,
250
+ bundle: Optional[ContextBundle] = None,
251
+ on_progress: Optional[ProgressCallback] = None,
252
+ ) -> Dict[str, Any]:
253
+ emit(on_progress, type="activity", phase="questions", message="Scanning report for open questions…")
254
+ bundle = bundle or self.context.gather(title, design)
255
+ base_user = build_base_user_prompt(title, design, bundle)
256
+ report = (report_markdown or "").strip()
257
+ if len(report) > 150_000:
258
+ report = report[:150_000] + "\n\n_(report truncated)_\n"
259
+ user_msg = f"{base_user}\n\n---\n\n# Current requirements report (markdown)\n\n{report}\n\nExtract open questions now."
260
+ emit(on_progress, type="activity", phase="questions", message="Calling model — extracting questions…")
261
+ try:
262
+ raw = self.llm.stream_chat(
263
+ [ChatMessage("system", OPEN_QUESTIONS_SYSTEM), ChatMessage("user", user_msg)],
264
+ max_tokens=5000,
265
+ temperature=0.15,
266
+ on_delta=make_stream_reporter(on_progress, phase="questions"),
267
+ ).content
268
+ except Exception as e:
269
+ return {"success": False, "categories": [], "error": str(e)}
270
+ if not raw:
271
+ return {"success": False, "categories": [], "error": "Model returned no content."}
272
+ emit(on_progress, type="activity", phase="questions", message="Parsing question categories…")
273
+ try:
274
+ parsed = json.loads(_strip_json_fence(raw))
275
+ except Exception:
276
+ return {"success": False, "categories": [], "error": "Could not parse model JSON output."}
277
+
278
+ expected = [
279
+ ("technical", "Technical & Architecture"),
280
+ ("business", "Business & Logic"),
281
+ ("general", "Ambiguities & Clarifications"),
282
+ ]
283
+ by_id: Dict[str, List[str]] = {k: [] for k, _ in expected}
284
+ for row in parsed.get("categories") or []:
285
+ if not isinstance(row, dict):
286
+ continue
287
+ cid = str(row.get("id") or "").strip().lower()
288
+ if cid not in by_id:
289
+ continue
290
+ seen = set(x.lower() for x in by_id[cid])
291
+ for q in row.get("questions") or []:
292
+ s = str(q or "").strip()
293
+ if len(s) < 6 or s.lower() in seen:
294
+ continue
295
+ by_id[cid].append(s)
296
+ seen.add(s.lower())
297
+ categories = [{"id": k, "title": t, "questions": by_id[k]} for k, t in expected]
298
+ total_q = sum(len(c["questions"]) for c in categories)
299
+ emit(
300
+ on_progress,
301
+ type="questions_result",
302
+ phase="questions",
303
+ categories=categories,
304
+ count=total_q,
305
+ message=f"Found {total_q} open question(s)",
306
+ )
307
+ return {"success": True, "categories": categories, "error": None}
308
+
309
+ def suggest_question_resolution(
310
+ self,
311
+ title: str,
312
+ design: str,
313
+ report_markdown: str,
314
+ question: str,
315
+ *,
316
+ bundle: Optional[ContextBundle] = None,
317
+ ) -> Dict[str, Any]:
318
+ empty = {
319
+ "success": False,
320
+ "suggestion": "",
321
+ "rationale": "",
322
+ "resolution_steps": [],
323
+ "examples": [],
324
+ "assumptions": [],
325
+ "error": None,
326
+ }
327
+ q = (question or "").strip()
328
+ if len(q) < 3:
329
+ return {**empty, "error": "Question is too short."}
330
+
331
+ bundle = bundle or self.context.gather(title, design)
332
+ base_user = build_base_user_prompt(title, design, bundle)
333
+ report = (report_markdown or "").strip()
334
+ if len(report) > 120_000:
335
+ report = report[:120_000] + "\n\n_(report truncated)_\n"
336
+ user_msg = (
337
+ f"{base_user}\n\n---\n\n# Current requirements report (markdown)\n\n{report}\n\n"
338
+ f"---\n\n# Open question to resolve\n\n{q}\n\nSuggest a resolution now."
339
+ )
340
+ try:
341
+ raw = self.llm.chat(
342
+ [ChatMessage("system", QUESTION_RESOLUTION_SYSTEM), ChatMessage("user", user_msg)],
343
+ max_tokens=4500,
344
+ temperature=0.25,
345
+ ).content
346
+ except Exception as e:
347
+ return {**empty, "error": str(e)}
348
+ if not raw:
349
+ return {**empty, "error": "Model returned no content."}
350
+ try:
351
+ parsed = json.loads(_strip_json_fence(raw))
352
+ except Exception:
353
+ return {**empty, "success": True, "suggestion": raw[:2000].strip()}
354
+
355
+ if not isinstance(parsed, dict):
356
+ return {**empty, "error": "Model JSON output was not an object."}
357
+
358
+ steps = []
359
+ for s in (parsed.get("resolution_steps") or [])[:8]:
360
+ if isinstance(s, dict) and (s.get("title") or s.get("detail")):
361
+ steps.append(
362
+ {
363
+ "title": str(s.get("title") or "")[:160],
364
+ "detail": str(s.get("detail") or "")[:1000],
365
+ "example": str(s.get("example") or "")[:600],
366
+ }
367
+ )
368
+ examples = []
369
+ for e in (parsed.get("examples") or [])[:6]:
370
+ if isinstance(e, dict) and e.get("content"):
371
+ examples.append(
372
+ {
373
+ "label": str(e.get("label") or "Example")[:120],
374
+ "content": str(e.get("content") or "")[:1200],
375
+ }
376
+ )
377
+ assumptions = [str(a).strip()[:240] for a in (parsed.get("assumptions") or [])[:6] if str(a).strip()]
378
+ return {
379
+ "success": True,
380
+ "suggestion": str(parsed.get("suggestion") or "")[:2000],
381
+ "rationale": str(parsed.get("rationale") or "")[:800],
382
+ "resolution_steps": steps[:7],
383
+ "examples": examples[:4],
384
+ "assumptions": assumptions[:4],
385
+ "error": None,
386
+ }
@@ -0,0 +1,117 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+ from typing import List, Optional, Tuple
6
+
7
+
8
+ @dataclass
9
+ class MdSection:
10
+ """A level-2 markdown section (## heading)."""
11
+
12
+ index: int # 1-based among ## sections
13
+ heading: str
14
+ start: int # char offset of "## "
15
+ end: int # char offset just before next ## or EOF
16
+ body_start: int # after heading line
17
+
18
+ @property
19
+ def full_text(self) -> str:
20
+ raise NotImplementedError # filled via slice helpers
21
+
22
+
23
+ _H2 = re.compile(r"(?m)^(##)\s+(.+?)\s*$")
24
+
25
+
26
+ def list_h2_sections(markdown: str) -> List[MdSection]:
27
+ text = markdown or ""
28
+ matches = list(_H2.finditer(text))
29
+ sections: List[MdSection] = []
30
+ for i, m in enumerate(matches):
31
+ start = m.start()
32
+ body_start = m.end()
33
+ # skip single trailing newline after heading
34
+ if body_start < len(text) and text[body_start] == "\n":
35
+ body_start += 1
36
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
37
+ sections.append(
38
+ MdSection(
39
+ index=i + 1,
40
+ heading=m.group(2).strip(),
41
+ start=start,
42
+ end=end,
43
+ body_start=body_start,
44
+ )
45
+ )
46
+ return sections
47
+
48
+
49
+ def section_slice(markdown: str, section: MdSection) -> str:
50
+ return (markdown or "")[section.start : section.end].rstrip() + "\n"
51
+
52
+
53
+ def section_body(markdown: str, section: MdSection) -> str:
54
+ return (markdown or "")[section.body_start : section.end].rstrip()
55
+
56
+
57
+ def resolve_section(
58
+ markdown: str,
59
+ query: str,
60
+ ) -> Tuple[Optional[MdSection], List[MdSection]]:
61
+ """Resolve a section by 1-based index, exact heading, or case-insensitive substring."""
62
+ sections = list_h2_sections(markdown)
63
+ q = (query or "").strip()
64
+ if not q:
65
+ return None, sections
66
+
67
+ if q.isdigit():
68
+ idx = int(q)
69
+ for s in sections:
70
+ if s.index == idx:
71
+ return s, sections
72
+ return None, sections
73
+
74
+ # Strip optional ## prefix
75
+ if q.startswith("##"):
76
+ q = q[2:].strip()
77
+
78
+ exact = [s for s in sections if s.heading.lower() == q.lower()]
79
+ if len(exact) == 1:
80
+ return exact[0], sections
81
+ if len(exact) > 1:
82
+ return exact[0], sections
83
+
84
+ partial = [s for s in sections if q.lower() in s.heading.lower()]
85
+ if len(partial) == 1:
86
+ return partial[0], sections
87
+ if len(partial) > 1:
88
+ # Prefer shortest heading (most specific match)
89
+ partial.sort(key=lambda s: len(s.heading))
90
+ return partial[0], sections
91
+ return None, sections
92
+
93
+
94
+ def replace_section(markdown: str, section: MdSection, new_section_md: str) -> str:
95
+ """Replace one ## section. ``new_section_md`` should start with ## Heading."""
96
+ text = markdown or ""
97
+ replacement = (new_section_md or "").strip()
98
+ if not replacement.startswith("##"):
99
+ replacement = f"## {section.heading}\n\n{replacement}"
100
+ if not replacement.endswith("\n"):
101
+ replacement += "\n"
102
+ before = text[: section.start].rstrip("\n")
103
+ after = text[section.end :].lstrip("\n")
104
+ parts: List[str] = []
105
+ if before:
106
+ parts.append(before)
107
+ parts.append(replacement.rstrip("\n"))
108
+ if after:
109
+ parts.append(after)
110
+ return "\n\n".join(parts) + "\n"
111
+
112
+
113
+ def format_section_menu(sections: List[MdSection]) -> str:
114
+ lines = []
115
+ for s in sections:
116
+ lines.append(f" {s.index:>2}. {s.heading}")
117
+ return "\n".join(lines)
@@ -0,0 +1,142 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from pathlib import Path
5
+ from typing import Any, Callable, Dict, List, Optional
6
+
7
+ from requirements_agent.config import AppConfig, PromptsConfig
8
+ from requirements_agent.context.aggregate import ContextAggregator, build_base_user_prompt
9
+ from requirements_agent.llm.base import LlmClient
10
+ from requirements_agent.models import ContextBundle, ReviewResult, Section
11
+ from requirements_agent.pipeline.pack import REVIEW_PIPELINE, PackLoader, build_system_prompt, resolve_pack_root
12
+ from requirements_agent.pipeline.progress import make_stream_reporter
13
+ from requirements_agent.context.personas import persona_brief
14
+ from requirements_agent.context.untrusted import data_block
15
+ from requirements_agent.pipeline.prompts import PERSONA_REVIEW_SYSTEM, SPEC_CIRCUIT_REPORT_MD_TITLE
16
+ from requirements_agent.llm.base import ChatMessage
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ ProgressCallback = Callable[[Dict[str, Any]], None]
21
+
22
+
23
+ class SpecCircuitService:
24
+ def __init__(
25
+ self,
26
+ llm: LlmClient,
27
+ *,
28
+ prompts: Optional[PromptsConfig] = None,
29
+ pack_root: Optional[Path] = None,
30
+ context: Optional[ContextAggregator] = None,
31
+ ):
32
+ self.llm = llm
33
+ self.prompts = prompts or PromptsConfig()
34
+ self.pack = PackLoader(pack_root or resolve_pack_root())
35
+ self.context = context or ContextAggregator([])
36
+
37
+ @classmethod
38
+ def from_app_config(
39
+ cls,
40
+ config: AppConfig,
41
+ llm: LlmClient,
42
+ *,
43
+ extra_folder_paths: Optional[List[str]] = None,
44
+ given: Any = None,
45
+ persona_ids: Optional[List[str]] = None,
46
+ ) -> "SpecCircuitService":
47
+ pack = resolve_pack_root(config.pack_root)
48
+ aggregator = ContextAggregator.from_config(
49
+ config.context, extra_folder_paths=extra_folder_paths, given=given, persona_ids=persona_ids
50
+ )
51
+ return cls(llm, prompts=config.prompts, pack_root=pack, context=aggregator)
52
+
53
+ def _gather_context(self, title: str, design: str) -> ContextBundle:
54
+ return self.context.gather(title, design)
55
+
56
+ def review(
57
+ self,
58
+ title: str,
59
+ design: str,
60
+ *,
61
+ max_prior_chars: int = 12_000,
62
+ on_progress: Optional[ProgressCallback] = None,
63
+ ) -> ReviewResult:
64
+ title = (title or "").strip()
65
+ design = (design or "").strip()
66
+ if not title:
67
+ return ReviewResult(success=False, error="Title is required.")
68
+ if len(design) < 10:
69
+ return ReviewResult(success=False, error="Design must be at least 10 characters (or attach context files).")
70
+
71
+ bundle = self._gather_context(title, design)
72
+ base_user = build_base_user_prompt(title, design, bundle)
73
+ if on_progress:
74
+ on_progress({"type": "phase", "phase": "memory", "message": "Indexing documents for Memory context…"})
75
+ on_progress({"type": "context", "context": bundle.summary()})
76
+ on_progress({"type": "phase", "phase": "review", "message": "Starting Spec Circuit personas…"})
77
+
78
+ sections: List[Section] = []
79
+ accumulated = ""
80
+ # The specialist roles, then each business persona in scope as a stakeholder reviewer of their own.
81
+ steps: List[tuple] = list(REVIEW_PIPELINE) + [
82
+ (f"persona:{p['id']}", f"Persona review: {p['name']}") for p in bundle.personas
83
+ ]
84
+ by_step = {f"persona:{p['id']}": p for p in bundle.personas}
85
+ total = len(steps)
86
+
87
+ for idx, (agent_id, heading) in enumerate(steps, start=1):
88
+ if on_progress:
89
+ on_progress(
90
+ {
91
+ "type": "status",
92
+ "step": idx,
93
+ "total": total,
94
+ "agent_id": agent_id,
95
+ "heading": heading,
96
+ "message": f"Running {heading} ({idx}/{total})",
97
+ }
98
+ )
99
+ persona = by_step.get(agent_id)
100
+ if persona:
101
+ system_prompt = PERSONA_REVIEW_SYSTEM.replace("{heading}", heading)
102
+ else:
103
+ system_prompt = build_system_prompt(self.pack, agent_id, heading, self.prompts)
104
+ prior = accumulated[-max_prior_chars:] if accumulated else ""
105
+ user_prompt = base_user
106
+ if persona:
107
+ user_prompt += "\n\n# The stakeholder reviewing now\n\n" + data_block("persona", persona["id"], persona_brief(persona))
108
+ if prior:
109
+ user_prompt += (
110
+ "\n\n# Prior review segments (for context; do not duplicate in full)\n\n" + prior
111
+ )
112
+ try:
113
+ content = self.llm.stream_chat(
114
+ [
115
+ ChatMessage("system", system_prompt),
116
+ ChatMessage("user", user_prompt),
117
+ ],
118
+ max_tokens=4096,
119
+ temperature=0.35,
120
+ on_delta=make_stream_reporter(on_progress, phase="review"),
121
+ ).content
122
+ except Exception as e:
123
+ logger.exception("Persona %s failed", agent_id)
124
+ content = f"## {heading}\n\n_This segment could not be generated: {e}_"
125
+ if not content.strip():
126
+ content = f"## {heading}\n\n_This segment could not be generated (empty model response)._"
127
+ section = Section(agent_id=agent_id, heading=heading, content=content.strip())
128
+ sections.append(section)
129
+ accumulated += "\n\n" + section.content
130
+ if on_progress:
131
+ on_progress({"type": "segment", "section": section})
132
+
133
+ core_note = self.pack.core_note()
134
+ report = f"{SPEC_CIRCUIT_REPORT_MD_TITLE}\n\n"
135
+ if core_note:
136
+ report += f"_{core_note}_\n\n"
137
+ report += accumulated.strip()
138
+
139
+ result = ReviewResult(success=True, report_markdown=report, sections=sections, context=bundle)
140
+ if on_progress:
141
+ on_progress({"type": "done", "result": result})
142
+ return result
@@ -0,0 +1,7 @@
1
+ from __future__ import annotations
2
+
3
+ """Chat-first Textual shell for Requirements Agent."""
4
+
5
+ from requirements_agent.shell.app import RequirementsShell, run_shell
6
+
7
+ __all__ = ["RequirementsShell", "run_shell"]