@capagents/forgeqe 3.3.1 → 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.
- package/HOW_TO_USE.md +32 -0
- package/dist/docs-site/docs/area-setup/index.html +1 -0
- package/dist/docs-site/docs/area-test-cases/index.html +25 -0
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/forgeqe.js +1922 -1906
- package/dist/requirement-agent/requirements_agent/__init__.py +3 -0
- package/dist/requirement-agent/requirements_agent/__main__.py +5 -0
- package/dist/requirement-agent/requirements_agent/agent.py +363 -0
- package/dist/requirement-agent/requirements_agent/chat_session.py +424 -0
- package/dist/requirement-agent/requirements_agent/cli.py +870 -0
- package/dist/requirement-agent/requirements_agent/config.py +403 -0
- package/dist/requirement-agent/requirements_agent/console_ui.py +632 -0
- package/dist/requirement-agent/requirements_agent/context/__init__.py +3 -0
- package/dist/requirement-agent/requirements_agent/context/aggregate.py +214 -0
- package/dist/requirement-agent/requirements_agent/context/base.py +14 -0
- package/dist/requirement-agent/requirements_agent/context/folder.py +107 -0
- package/dist/requirement-agent/requirements_agent/context/given.py +70 -0
- package/dist/requirement-agent/requirements_agent/context/graph.py +181 -0
- package/dist/requirement-agent/requirements_agent/context/knowledge.py +192 -0
- package/dist/requirement-agent/requirements_agent/context/mcp.py +24 -0
- package/dist/requirement-agent/requirements_agent/context/memory.py +144 -0
- package/dist/requirement-agent/requirements_agent/context/personas.py +214 -0
- package/dist/requirement-agent/requirements_agent/context/rag.py +148 -0
- package/dist/requirement-agent/requirements_agent/context/untrusted.py +56 -0
- package/dist/requirement-agent/requirements_agent/docs/HOW_TO_USE.md +505 -0
- package/dist/requirement-agent/requirements_agent/docs/requirements-agent-architecture.html +348 -0
- package/dist/requirement-agent/requirements_agent/docs_cmd.py +51 -0
- package/dist/requirement-agent/requirements_agent/export/__init__.py +3 -0
- package/dist/requirement-agent/requirements_agent/export/markdown.py +55 -0
- package/dist/requirement-agent/requirements_agent/export/pdf.py +82 -0
- package/dist/requirement-agent/requirements_agent/export/requirements_json.py +120 -0
- package/dist/requirement-agent/requirements_agent/init_cmd.py +191 -0
- package/dist/requirement-agent/requirements_agent/llm/__init__.py +3 -0
- package/dist/requirement-agent/requirements_agent/llm/base.py +49 -0
- package/dist/requirement-agent/requirements_agent/llm/copilot.py +171 -0
- package/dist/requirement-agent/requirements_agent/llm/mock.py +144 -0
- package/dist/requirement-agent/requirements_agent/llm/providers.py +277 -0
- package/dist/requirement-agent/requirements_agent/llm/router.py +35 -0
- package/dist/requirement-agent/requirements_agent/models.py +73 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/analyst.md +29 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/architect.md +28 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/bmad-orchestrator.md +26 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/dev.md +27 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/pm.md +27 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/po.md +27 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/qa.md +28 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/agents/sm.md +26 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-analyst.md +8 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-architect.md +11 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-dev.md +11 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-orchestrator.md +9 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-pm.md +9 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-po.md +10 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-qa.md +11 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/checklists/spec-circuit-sm.md +8 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/data/bmad-kb.md +19 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/data/requirements-standards-baseline.md +188 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/data/technical-preferences.md +54 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/utils/template-format.md +7 -0
- package/dist/requirement-agent/requirements_agent/packs/bmad-core-spec/workflows/greenfield-fullstack.yml +177 -0
- package/dist/requirement-agent/requirements_agent/pipeline/__init__.py +3 -0
- package/dist/requirement-agent/requirements_agent/pipeline/brd.py +86 -0
- package/dist/requirement-agent/requirements_agent/pipeline/pack.py +233 -0
- package/dist/requirement-agent/requirements_agent/pipeline/progress.py +60 -0
- package/dist/requirement-agent/requirements_agent/pipeline/prompts.py +150 -0
- package/dist/requirement-agent/requirements_agent/pipeline/quality.py +124 -0
- package/dist/requirement-agent/requirements_agent/pipeline/refine.py +386 -0
- package/dist/requirement-agent/requirements_agent/pipeline/sections.py +117 -0
- package/dist/requirement-agent/requirements_agent/pipeline/spec_circuit.py +142 -0
- package/dist/requirement-agent/requirements_agent/shell/__init__.py +7 -0
- package/dist/requirement-agent/requirements_agent/shell/actions.py +208 -0
- package/dist/requirement-agent/requirements_agent/shell/app.py +902 -0
- package/dist/requirement-agent/requirements_agent/shell/commands.py +206 -0
- package/dist/requirement-agent/requirements_agent/shell/progress_pane.py +114 -0
- package/dist/requirement-agent/requirements_agent/shell/ref_picker.py +59 -0
- package/dist/requirement-agent/requirements_agent/shell/refs.py +120 -0
- package/dist/requirement-agent/requirements_agent/shell/session.py +362 -0
- package/dist/requirement-agent/requirements_agent/shell/transcript.py +241 -0
- package/dist/requirement-agent/requirements_agent/shell/usage.py +64 -0
- package/dist/requirement-agent/requirements_agent/shell/usage_llm.py +64 -0
- package/dist/requirement-agent/requirements_agent/shell/worker.py +378 -0
- package/dist/requirement-agent/requirements_agent/tuios_hook.py +182 -0
- package/dist/requirement-agent/requirements_agent/webops.py +627 -0
- package/dist/template.html +67 -67
- package/dist/web/assets/{3d-force-graph-Df2wOlpF.js → 3d-force-graph-DDyP5jcf.js} +1 -1
- package/dist/web/assets/Agent-sLaNlaQo.js +8 -0
- package/dist/web/assets/AgentWork-Dv0G4bt3.js +2 -0
- package/dist/web/assets/ApiTests-Bnw2qgWw.js +15 -0
- package/dist/web/assets/Browse-CBt1JY2E.js +1 -0
- package/dist/web/assets/Chat-DIWdnIZK.js +3 -0
- package/dist/web/assets/CommandPalette-DD04oS83.js +1 -0
- package/dist/web/assets/Compare-D0Ao8dZ6.js +1 -0
- package/dist/web/assets/Cost-BY_8-9Qt.js +1 -0
- package/dist/web/assets/{Data-Be3ZNkUu.js → Data-BC7R_FbW.js} +4 -4
- package/dist/web/assets/Desktop-CSQ2xLg0.js +1 -0
- package/dist/web/assets/DesktopReview-CCOhUdeJ.js +2 -0
- package/dist/web/assets/DeviceScreen-BHmTd9Q-.js +1 -0
- package/dist/web/assets/Evidence-9W4pqIkC.js +1 -0
- package/dist/web/assets/{Explore-AtSStzNg.js → Explore-BndXiEf8.js} +2 -2
- package/dist/web/assets/Features-BrfsTC9Q.js +1 -0
- package/dist/web/assets/{Flags-GxmNrnSn.js → Flags-DyykkeHU.js} +2 -2
- package/dist/web/assets/Flaky-C3gj_Brn.js +1 -0
- package/dist/web/assets/Impact-Z8nbNhbe.js +3 -0
- package/dist/web/assets/Jobs-CJWXAqSy.js +5 -0
- package/dist/web/assets/KindPage-C45x_cFz.js +6 -0
- package/dist/web/assets/LiveDevice-DGdLDigO.js +1 -0
- package/dist/web/assets/Migration-QFI5ctp7.js +8 -0
- package/dist/web/assets/Mobile-CuswZyee.js +1 -0
- package/dist/web/assets/Observability-CknZ_xBN.js +1 -0
- package/dist/web/assets/PageAgent-B2bmmMaP.js +1 -0
- package/dist/web/assets/Product-CrtwDiMv.js +12 -0
- package/dist/web/assets/Production-BMsytC2i.js +1 -0
- package/dist/web/assets/Quality-B4Aw6N3_.js +1 -0
- package/dist/web/assets/Readiness-CVIzTFX-.js +1 -0
- package/dist/web/assets/Record-B2Ic8Taj.js +1 -0
- package/dist/web/assets/Regression-bCIAE3Ne.js +5 -0
- package/dist/web/assets/RelationGraph-kG4YVMzl.js +1 -0
- package/dist/web/assets/Reports-NAZ-26Ub.js +2 -0
- package/dist/web/assets/Requirements-BkpiF-Bt.js +2 -0
- package/dist/web/assets/Responsive-CsaoisJq.js +3 -0
- package/dist/web/assets/RunDiff-BC-3Wg1b.js +1 -0
- package/dist/web/assets/Settings-DyBed-J5.js +21 -0
- package/dist/web/assets/Steps-DcQxQ4yA.js +2 -0
- package/dist/web/assets/TestData-wpUeU9Er.js +2 -0
- package/dist/web/assets/TestManagement-D0njkyAT.js +4 -0
- package/dist/web/assets/WhatsNew-BxIAAwgH.js +1 -0
- package/dist/web/assets/agentSettingsSheet-BdB7IXah.js +1 -0
- package/dist/web/assets/choice-C4-yW2x9.js +1 -0
- package/dist/web/assets/code-Jek8uWUO.js +1 -0
- package/dist/web/assets/{coverage-DirEXtfZ.js → coverage-q-ib7wOq.js} +1 -1
- package/dist/web/assets/dataParts-B2-a-pOD.js +3 -0
- package/dist/web/assets/desktopAppPath-C-p0zU40.js +1 -0
- package/dist/web/assets/frame-CjpZWX_X.js +13 -0
- package/dist/web/assets/index-BH5RbDNY.css +2 -0
- package/dist/web/assets/index-CfGXe_De.js +55 -0
- package/dist/web/assets/line-icons-CwCZidXs.js +1 -0
- package/dist/web/assets/logos-P2LOMyTK.js +1 -0
- package/dist/web/assets/{markdown-BnrLv6Iw.js → markdown-dXSsS-mD.js} +5 -5
- package/dist/web/assets/nav-BZfNOkhX.js +1 -0
- package/dist/web/assets/pageBack-BwKT31j3.js +3 -0
- package/dist/web/assets/palette-L37b4wTE.js +1 -0
- package/dist/web/assets/{paletteCommands-LXIICD4V.js → paletteCommands-zqGCORJu.js} +1 -1
- package/dist/web/assets/parts-3o6HnCp1.js +1 -0
- package/dist/web/assets/preload-helper-BupTYkQW.js +1 -0
- package/dist/web/assets/productParts-BDiEg0z6.js +1 -0
- package/dist/web/assets/qualityParts--CnSadOZ.js +1 -0
- package/dist/web/assets/radio-BLI4Ubhk.js +1 -0
- package/dist/web/assets/react-BDur5s0O.js +1 -0
- package/dist/web/assets/{recordTest-BzKpS4m5.js → recordTest-D092f975.js} +1 -1
- package/dist/web/assets/route-oDy8sV6H.js +1 -0
- package/dist/web/assets/sectionList-XiKcJNEK.js +1 -0
- package/dist/web/assets/step-mark-CaKf4dAR.js +1 -0
- package/dist/web/assets/stepper-naqAN_Nb.js +1 -0
- package/dist/web/assets/utils-DJRAScIl.js +1 -0
- package/dist/web/assets/wizardParts-DLlOHVMx.js +1 -0
- package/dist/web/index.html +14 -12
- package/docs/user-guide.html +26 -0
- package/package.json +2 -1
- package/py/forgeqe_engine/cli.py +7 -0
- package/dist/web/assets/Agent-CRfgRnq2.js +0 -8
- package/dist/web/assets/AgentWork-DqiO3LUi.js +0 -2
- package/dist/web/assets/ApiTests-DCAnizu5.js +0 -15
- package/dist/web/assets/Browse-D5VDHN9Z.js +0 -1
- package/dist/web/assets/Chat-CLGQ1ymU.js +0 -3
- package/dist/web/assets/CommandPalette-D3F4iHrP.js +0 -1
- package/dist/web/assets/Compare-B1WN67Ny.js +0 -1
- package/dist/web/assets/Cost-Dk4m3r8z.js +0 -1
- package/dist/web/assets/Desktop-B3GcbaPu.js +0 -1
- package/dist/web/assets/DesktopReview-DfvAL3m8.js +0 -2
- package/dist/web/assets/DeviceScreen-DJqblqBh.js +0 -1
- package/dist/web/assets/Evidence-BsA7vCZG.js +0 -1
- package/dist/web/assets/Features-CDBlFLaJ.js +0 -1
- package/dist/web/assets/Flaky-C062Mh6z.js +0 -1
- package/dist/web/assets/Impact-BeXw3-oL.js +0 -3
- package/dist/web/assets/Jobs-QYWqmdDI.js +0 -5
- package/dist/web/assets/KindPage-C2g51s9c.js +0 -6
- package/dist/web/assets/LiveDevice-C9LRZMhC.js +0 -1
- package/dist/web/assets/Migration-ByUU0Oa_.js +0 -8
- package/dist/web/assets/Mobile-Dd3jL0Cn.js +0 -1
- package/dist/web/assets/Observability-Dx4ZCRDj.js +0 -1
- package/dist/web/assets/PageAgent-DYBOhs2x.js +0 -1
- package/dist/web/assets/Product-Ch1XAeAT.js +0 -12
- package/dist/web/assets/Production-TEdyFmo4.js +0 -1
- package/dist/web/assets/Quality-DH8EdI2u.js +0 -1
- package/dist/web/assets/Readiness-B8S7Ex0C.js +0 -1
- package/dist/web/assets/Record-uFQ-YaHg.js +0 -1
- package/dist/web/assets/Regression-CSDT2AnY.js +0 -5
- package/dist/web/assets/RelationGraph-gc0Xmklt.js +0 -1
- package/dist/web/assets/Reports-CSHhRfWv.js +0 -2
- package/dist/web/assets/Responsive-CEG1hbbQ.js +0 -3
- package/dist/web/assets/RunDiff-CHrMivzC.js +0 -1
- package/dist/web/assets/Settings-B63s0b1g.js +0 -21
- package/dist/web/assets/Steps-BsDjv-pm.js +0 -2
- package/dist/web/assets/TestData-CJoCXihI.js +0 -2
- package/dist/web/assets/TestManagement-Dkb-paWh.js +0 -4
- package/dist/web/assets/WhatsNew-Dtk9mJU4.js +0 -1
- package/dist/web/assets/agentSettingsSheet-BlM8KSpN.js +0 -1
- package/dist/web/assets/choice-CiFogD01.js +0 -1
- package/dist/web/assets/code-DzYywAs5.js +0 -1
- package/dist/web/assets/dataParts-Di7PdPHu.js +0 -3
- package/dist/web/assets/desktopAppPath-B8j1-pX0.js +0 -1
- package/dist/web/assets/frame-CNLw552P.js +0 -13
- package/dist/web/assets/index-DLuCgQKX.js +0 -55
- package/dist/web/assets/index-DRcPg81h.css +0 -2
- package/dist/web/assets/line-icons-B-O8oBsY.js +0 -1
- package/dist/web/assets/nav-Ds_6IERv.js +0 -1
- package/dist/web/assets/pageBack-DJxbEPfN.js +0 -3
- package/dist/web/assets/palette-H2g-hemT.js +0 -1
- package/dist/web/assets/parts-DKRLtrjs.js +0 -1
- package/dist/web/assets/preload-helper-BML5SvL4.js +0 -1
- package/dist/web/assets/productParts-imNtw-1N.js +0 -1
- package/dist/web/assets/qualityParts-DJhFlgCm.js +0 -1
- package/dist/web/assets/radio-CbR6ODxQ.js +0 -1
- package/dist/web/assets/route-DjewvmpL.js +0 -1
- package/dist/web/assets/sectionList-0umoKvRv.js +0 -1
- package/dist/web/assets/step-mark-g8Eb6foB.js +0 -1
- package/dist/web/assets/stepper-CzZIC36d.js +0 -1
|
@@ -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,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"
|