@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,233 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
8
|
+
|
|
9
|
+
import yaml
|
|
10
|
+
|
|
11
|
+
from requirements_agent.config import PromptsConfig
|
|
12
|
+
from requirements_agent.pipeline.prompts import (
|
|
13
|
+
REQUIREMENTS_PIPELINE_GUIDERAILS_DEFAULT,
|
|
14
|
+
REQUIREMENTS_PIPELINE_STEP_INSTRUCTION,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
_PACKAGE_ROOT = Path(__file__).resolve().parents[1]
|
|
20
|
+
_BUNDLED_PACK = _PACKAGE_ROOT / "packs" / "bmad-core-spec"
|
|
21
|
+
|
|
22
|
+
SHARED_CORE_DATA_FILES = ("bmad-kb.md", "technical-preferences.md", "requirements-standards-baseline.md")
|
|
23
|
+
SPEC_CIRCUIT_DEP_BUDGET_CHARS = 18_000
|
|
24
|
+
SPEC_CIRCUIT_WORKFLOW_EXCERPT_CHARS = 6_000
|
|
25
|
+
|
|
26
|
+
_ARCH_DEP_ORDER = ("checklists", "templates", "utils", "tasks", "data")
|
|
27
|
+
_PM_PO_SM_DEP_ORDER = ("templates", "checklists", "utils", "tasks", "data")
|
|
28
|
+
_DEFAULT_DEP_ORDER = ("checklists", "utils", "templates", "tasks", "data")
|
|
29
|
+
|
|
30
|
+
REVIEW_PIPELINE: List[Tuple[str, str]] = [
|
|
31
|
+
("bmad-orchestrator", "Overview"),
|
|
32
|
+
("analyst", "Business Analyst"),
|
|
33
|
+
("pm", "Product Manager"),
|
|
34
|
+
("po", "Product Owner"),
|
|
35
|
+
("architect", "Solution Architect"),
|
|
36
|
+
("dev", "Developer"),
|
|
37
|
+
("qa", "QA"),
|
|
38
|
+
("sm", "Scrum Master"),
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
_FALLBACK_PERSONA: Dict[str, str] = {
|
|
42
|
+
"bmad-orchestrator": "You are the team coordinator: summarize how the group will assess the requirement and set expectations for the following specialist sections.",
|
|
43
|
+
"analyst": "You are the Business Analyst: problem framing, stakeholders, discovery gaps, clarifying questions.",
|
|
44
|
+
"pm": "You are the Product Manager: scope, priorities, roadmap fit, PRD-level concerns.",
|
|
45
|
+
"architect": "You are the Solution Architect: system design, constraints, integration, non-functional requirements.",
|
|
46
|
+
"dev": "You are the Developer: implementation feasibility, technical tasks, complexity, dependencies.",
|
|
47
|
+
"qa": "You are QA: test strategy, quality risks, edge cases, verification concerns.",
|
|
48
|
+
"po": "You are the Product Owner: backlog readiness, value, story splitting, acceptance criteria suggestions.",
|
|
49
|
+
"sm": "You are the Scrum Master: sprintability, dependencies, process risks, refinement needs.",
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def resolve_pack_root(override: Optional[str] = None) -> Path:
|
|
54
|
+
env = (override or os.getenv("SPEC_CIRCUIT_CORE_ROOT") or "").strip()
|
|
55
|
+
if env:
|
|
56
|
+
p = Path(env).expanduser()
|
|
57
|
+
if p.is_dir():
|
|
58
|
+
return p.resolve()
|
|
59
|
+
if _BUNDLED_PACK.is_dir():
|
|
60
|
+
return _BUNDLED_PACK.resolve()
|
|
61
|
+
return _BUNDLED_PACK
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class PackLoader:
|
|
65
|
+
def __init__(self, pack_root: Optional[Path] = None):
|
|
66
|
+
self.root = pack_root or resolve_pack_root()
|
|
67
|
+
self.agents_dir = self.root / "agents"
|
|
68
|
+
|
|
69
|
+
def core_note(self) -> str:
|
|
70
|
+
if not self.root.is_dir():
|
|
71
|
+
return "Vendored role pack not found; using built-in fallback personas only."
|
|
72
|
+
if self.root.name == "bmad-core-spec":
|
|
73
|
+
return ""
|
|
74
|
+
return (
|
|
75
|
+
"Multi-role agent definitions with resolved dependency files "
|
|
76
|
+
"and a planning workflow excerpt for the coordinator step."
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
def read_agent(self, agent_id: str) -> Optional[str]:
|
|
80
|
+
path = self.agents_dir / f"{agent_id}.md"
|
|
81
|
+
if not path.is_file():
|
|
82
|
+
return None
|
|
83
|
+
try:
|
|
84
|
+
return path.read_text(encoding="utf-8", errors="replace").strip()
|
|
85
|
+
except OSError as e:
|
|
86
|
+
logger.warning("Could not read agent file %s: %s", path, e)
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
def load_shared_data(self) -> str:
|
|
90
|
+
parts: List[str] = []
|
|
91
|
+
for fname in SHARED_CORE_DATA_FILES:
|
|
92
|
+
path = self.root / "data" / fname
|
|
93
|
+
if not path.is_file():
|
|
94
|
+
continue
|
|
95
|
+
try:
|
|
96
|
+
body = path.read_text(encoding="utf-8", errors="replace").strip()
|
|
97
|
+
except OSError:
|
|
98
|
+
continue
|
|
99
|
+
parts.append(f"### Knowledge base: `{fname}`\n\n{body}")
|
|
100
|
+
return "\n\n".join(parts).strip()
|
|
101
|
+
|
|
102
|
+
@staticmethod
|
|
103
|
+
def parse_dependencies(agent_markdown: str) -> Dict[str, Any]:
|
|
104
|
+
for m in re.finditer(r"```(?:yaml|yml)\s*\n(.*?)```", agent_markdown, re.DOTALL | re.IGNORECASE):
|
|
105
|
+
try:
|
|
106
|
+
data = yaml.safe_load(m.group(1))
|
|
107
|
+
except Exception:
|
|
108
|
+
continue
|
|
109
|
+
if isinstance(data, dict) and isinstance(data.get("dependencies"), dict):
|
|
110
|
+
return data["dependencies"]
|
|
111
|
+
return {}
|
|
112
|
+
|
|
113
|
+
def _dep_path(self, category: str, name: str) -> Optional[Path]:
|
|
114
|
+
subdirs = {
|
|
115
|
+
"tasks": "tasks",
|
|
116
|
+
"templates": "templates",
|
|
117
|
+
"checklists": "checklists",
|
|
118
|
+
"data": "data",
|
|
119
|
+
"utils": "utils",
|
|
120
|
+
}
|
|
121
|
+
sd = subdirs.get(category)
|
|
122
|
+
if not sd:
|
|
123
|
+
return None
|
|
124
|
+
p = self.root / sd / f"{name}.md"
|
|
125
|
+
return p if p.is_file() else None
|
|
126
|
+
|
|
127
|
+
def bundle_dependencies(self, deps: Dict[str, Any], *, agent_id: str = "") -> str:
|
|
128
|
+
if not deps:
|
|
129
|
+
return ""
|
|
130
|
+
if agent_id == "architect":
|
|
131
|
+
order = _ARCH_DEP_ORDER
|
|
132
|
+
elif agent_id in ("pm", "po", "sm"):
|
|
133
|
+
order = _PM_PO_SM_DEP_ORDER
|
|
134
|
+
else:
|
|
135
|
+
order = _DEFAULT_DEP_ORDER
|
|
136
|
+
|
|
137
|
+
skip_data = {"bmad-kb", "technical-preferences", "requirements-standards-baseline"}
|
|
138
|
+
chunks: List[str] = []
|
|
139
|
+
used = 0
|
|
140
|
+
max_chars = SPEC_CIRCUIT_DEP_BUDGET_CHARS
|
|
141
|
+
|
|
142
|
+
for category in order:
|
|
143
|
+
names = deps.get(category) or []
|
|
144
|
+
if not isinstance(names, list):
|
|
145
|
+
continue
|
|
146
|
+
for raw_name in names:
|
|
147
|
+
name = str(raw_name).strip()
|
|
148
|
+
if not name or (category == "data" and name in skip_data):
|
|
149
|
+
continue
|
|
150
|
+
path = self._dep_path(category, name)
|
|
151
|
+
if path is None:
|
|
152
|
+
continue
|
|
153
|
+
try:
|
|
154
|
+
body = path.read_text(encoding="utf-8", errors="replace")
|
|
155
|
+
except OSError:
|
|
156
|
+
continue
|
|
157
|
+
header = f"\n\n### {category}: `{name}` ({path.name})\n\n"
|
|
158
|
+
remain = max_chars - used - len(header)
|
|
159
|
+
if remain <= 200:
|
|
160
|
+
return "".join(chunks).strip()
|
|
161
|
+
if len(body) > remain:
|
|
162
|
+
body = body[:remain] + "\n\n_(truncated to fit Spec circuit context budget)_\n"
|
|
163
|
+
chunk = header + body
|
|
164
|
+
chunks.append(chunk)
|
|
165
|
+
used += len(chunk)
|
|
166
|
+
if used >= max_chars:
|
|
167
|
+
return "".join(chunks).strip()
|
|
168
|
+
return "".join(chunks).strip()
|
|
169
|
+
|
|
170
|
+
def orchestrator_workflow_excerpt(self) -> str:
|
|
171
|
+
path = self.root / "workflows" / "greenfield-fullstack.yml"
|
|
172
|
+
if not path.is_file():
|
|
173
|
+
return ""
|
|
174
|
+
try:
|
|
175
|
+
text = path.read_text(encoding="utf-8", errors="replace").strip()
|
|
176
|
+
except OSError:
|
|
177
|
+
return ""
|
|
178
|
+
if len(text) > SPEC_CIRCUIT_WORKFLOW_EXCERPT_CHARS:
|
|
179
|
+
text = text[:SPEC_CIRCUIT_WORKFLOW_EXCERPT_CHARS] + "\n\n# … (truncated)"
|
|
180
|
+
return (
|
|
181
|
+
"\n\n---\n\n## Planning workflow reference\n\n"
|
|
182
|
+
f"Excerpt from `workflows/greenfield-fullstack.yml`:\n\n```yaml\n{text}\n```\n"
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def build_system_prompt(
|
|
187
|
+
pack: PackLoader,
|
|
188
|
+
agent_id: str,
|
|
189
|
+
heading: str,
|
|
190
|
+
prompts: Optional[PromptsConfig] = None,
|
|
191
|
+
) -> str:
|
|
192
|
+
prompts = prompts or PromptsConfig()
|
|
193
|
+
step_template = prompts.step_instruction.strip() or REQUIREMENTS_PIPELINE_STEP_INSTRUCTION
|
|
194
|
+
guiderails = prompts.guiderails.strip() or REQUIREMENTS_PIPELINE_GUIDERAILS_DEFAULT
|
|
195
|
+
try:
|
|
196
|
+
step = step_template.format(heading=heading)
|
|
197
|
+
except (KeyError, ValueError):
|
|
198
|
+
step = step_template.replace("{heading}", heading)
|
|
199
|
+
if guiderails:
|
|
200
|
+
step = f"{step.rstrip()}\n\n{guiderails.strip()}"
|
|
201
|
+
|
|
202
|
+
persona_override = prompts.personas.get(agent_id)
|
|
203
|
+
if persona_override and persona_override.system_override.strip():
|
|
204
|
+
return persona_override.system_override.strip()
|
|
205
|
+
|
|
206
|
+
raw_agent = pack.read_agent(agent_id)
|
|
207
|
+
persona = raw_agent or _FALLBACK_PERSONA.get(
|
|
208
|
+
agent_id,
|
|
209
|
+
f"You are the specialist `{agent_id}`. Review the requirement from your role's perspective.",
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
shared = pack.load_shared_data()
|
|
213
|
+
shared_block = f"\n\n---\n\n## Shared knowledge base (data/)\n\n{shared}\n" if shared else ""
|
|
214
|
+
|
|
215
|
+
dep_md = ""
|
|
216
|
+
if raw_agent and pack.root.is_dir():
|
|
217
|
+
deps = pack.parse_dependencies(raw_agent)
|
|
218
|
+
bundled = pack.bundle_dependencies(deps, agent_id=agent_id)
|
|
219
|
+
if bundled:
|
|
220
|
+
dep_md = "\n\n---\n\n## Reference materials (agent dependencies)\n" + bundled
|
|
221
|
+
|
|
222
|
+
workflow = pack.orchestrator_workflow_excerpt() if agent_id == "bmad-orchestrator" else ""
|
|
223
|
+
|
|
224
|
+
system = (
|
|
225
|
+
f"{step}"
|
|
226
|
+
f"{shared_block}"
|
|
227
|
+
f"\n\n---\n\n# Agent definition: {agent_id}\n\n{persona}"
|
|
228
|
+
f"{dep_md}"
|
|
229
|
+
f"{workflow}"
|
|
230
|
+
)
|
|
231
|
+
if persona_override and persona_override.system_extra.strip():
|
|
232
|
+
system += f"\n\n---\n\n## User prompt extras\n\n{persona_override.system_extra.strip()}\n"
|
|
233
|
+
return system
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import time
|
|
5
|
+
from typing import Any, Callable, Dict, List, Optional, Set
|
|
6
|
+
|
|
7
|
+
ProgressCallback = Callable[[Dict[str, Any]], None]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def emit(on_progress: Optional[ProgressCallback], **payload: Any) -> None:
|
|
11
|
+
if on_progress:
|
|
12
|
+
on_progress(payload)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def make_stream_reporter(
|
|
16
|
+
on_progress: Optional[ProgressCallback],
|
|
17
|
+
*,
|
|
18
|
+
phase: str,
|
|
19
|
+
track_headings: bool = False,
|
|
20
|
+
min_interval_s: float = 0.12,
|
|
21
|
+
) -> Callable[[str, str], None]:
|
|
22
|
+
"""Return an on_delta that emits live preview / heading events (throttled)."""
|
|
23
|
+
seen: Set[str] = set()
|
|
24
|
+
order: List[str] = []
|
|
25
|
+
last_emit = 0.0
|
|
26
|
+
|
|
27
|
+
def _on_delta(_delta: str, accumulated: str) -> None:
|
|
28
|
+
nonlocal last_emit
|
|
29
|
+
now = time.monotonic()
|
|
30
|
+
headings: List[str] = []
|
|
31
|
+
if track_headings:
|
|
32
|
+
# Only complete lines (trailing newline) — avoid partial "## Busine" mid-stream
|
|
33
|
+
for m in re.finditer(r"(?m)^##\s+(.+?)\s*\n", accumulated):
|
|
34
|
+
h = m.group(1).strip()
|
|
35
|
+
if h and h not in seen:
|
|
36
|
+
seen.add(h)
|
|
37
|
+
order.append(h)
|
|
38
|
+
headings.append(h)
|
|
39
|
+
emit(
|
|
40
|
+
on_progress,
|
|
41
|
+
type="section",
|
|
42
|
+
phase=phase,
|
|
43
|
+
heading=h,
|
|
44
|
+
sections=list(order),
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
if now - last_emit < min_interval_s and not headings:
|
|
48
|
+
return
|
|
49
|
+
last_emit = now
|
|
50
|
+
preview = accumulated[-900:] if len(accumulated) > 900 else accumulated
|
|
51
|
+
emit(
|
|
52
|
+
on_progress,
|
|
53
|
+
type="stream",
|
|
54
|
+
phase=phase,
|
|
55
|
+
chars=len(accumulated),
|
|
56
|
+
preview=preview,
|
|
57
|
+
message=f"Streaming… {len(accumulated):,} chars",
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
return _on_delta
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
REQUIREMENTS_PIPELINE_GUIDERAILS_DEFAULT = """## Requirements review guardrails
|
|
4
|
+
- Stay in character for your specialist role; the user cannot reply mid-pipeline.
|
|
5
|
+
- Call out gaps, risks, dependencies, and concrete recommendations—prefer bullets over prose walls.
|
|
6
|
+
- Cross-check against shared data/ standards; do not assert certification or legal compliance—flag items for specialists.
|
|
7
|
+
- Build on prior agents' sections without copying large blocks verbatim.
|
|
8
|
+
- Target 400–900 words when the requirement is rich; go longer for safety, compliance, or security.
|
|
9
|
+
- Prefer tables with FR/NFR/BRULE IDs and acceptance signals so the refined BRD is implementation-ready."""
|
|
10
|
+
|
|
11
|
+
REQUIREMENTS_PIPELINE_STEP_INSTRUCTION = """You are one step in an automated **multi-role requirements review** pipeline.
|
|
12
|
+
The user cannot reply or pick numbered options. Stay in character according to your agent definition below.
|
|
13
|
+
|
|
14
|
+
**Bundled context:** Everything in this system message (shared `data/` files, dependency sections, prior segments in the user message) is provided for you. Treat it as authoritative. Do not ask the user to select tasks, templates, or files, and do not wait for confirmation—deliver your section now.
|
|
15
|
+
|
|
16
|
+
Output rules:
|
|
17
|
+
- Start with exactly one markdown heading: ## {heading}
|
|
18
|
+
- Use ### subsections where helpful.
|
|
19
|
+
- Be specific to the requirement; call out gaps, risks, dependencies, and concrete recommendations.
|
|
20
|
+
- Prefer bullet lists and markdown tables with IDs (FR-/NFR-/BRULE-) and acceptance signals. Target 400–900 words when the requirement is rich; go longer for safety, compliance, or security.
|
|
21
|
+
- Cross-check against **industry practice**, **ISO / internationally recognized management-system themes**, and **security protocol** expectations in the shared **data/** knowledge base (especially `requirements-standards-baseline.md`). Map relevant gaps; do **not** assert certification or legal compliance—flag what would need a compliance or security specialist.
|
|
22
|
+
- Prior agents have already contributed; build on their points without copying large blocks verbatim.
|
|
23
|
+
- Frame content so it can fold into a BRD-style outline (objectives, scope, rules, behaviour, NFRs, dependencies)—avoid meta commentary about your role title."""
|
|
24
|
+
|
|
25
|
+
BRD_CONSOLIDATION_SYSTEM = """You rewrite requirements into a complete enterprise BRD / functional specification for backlog decomposition (epics → features → user stories). This is NOT a summary. Downstream work items are generated from this document, so every section must be detailed enough to implement and test.
|
|
26
|
+
|
|
27
|
+
Output rules:
|
|
28
|
+
- Return ONLY markdown. Do not wrap the document in ``` fences.
|
|
29
|
+
- Line 1 MUST be exactly: # Requirements report
|
|
30
|
+
- Include ONLY these level-2 headings, in this EXACT order, each exactly once. Use ### subsections freely inside them:
|
|
31
|
+
## Business objective
|
|
32
|
+
## Problem statement
|
|
33
|
+
## Scope
|
|
34
|
+
## High-level business requirements
|
|
35
|
+
## User journey
|
|
36
|
+
## Functional requirements
|
|
37
|
+
## Business rules
|
|
38
|
+
## Non-functional requirements
|
|
39
|
+
## Data and audit requirements
|
|
40
|
+
## Dependencies
|
|
41
|
+
## Risks and considerations
|
|
42
|
+
## Assumptions
|
|
43
|
+
## Reporting and monitoring
|
|
44
|
+
|
|
45
|
+
Depth bar (mandatory — thin one-liners are a failure):
|
|
46
|
+
- Each section must be substantial: typically a short framing paragraph PLUS a markdown table and/or 6+ concrete bullets. Never a single sentence.
|
|
47
|
+
- Assign stable IDs that stories can cite: BR-001, FR-001, BRULE-001, NFR-001 (and keep any source IDs).
|
|
48
|
+
- Tables should include an acceptance / success signal column wherever behaviour is specified.
|
|
49
|
+
- Fold ALL useful content from persona/role draft sections into the outline. Do not drop specialist findings because of the heading.
|
|
50
|
+
- Preserve facts from the draft, title/design, uploads, and retrieved context. Infer high-value missing detail and mark it **Assumption:**.
|
|
51
|
+
- Do not assert legal/regulatory certification; stay factual.
|
|
52
|
+
|
|
53
|
+
- For Scope, use "### In scope" and "### Out of scope" when applicable.
|
|
54
|
+
- For User journey, use "### Current" and "### Future" (or Target) when contrasting flows.
|
|
55
|
+
- Every section must have meaningful content. Use _N/A — not applicable for this initiative._ only when the topic cannot exist even by inference.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
REFINE_SYSTEM = """You are an editor for AI-generated requirements reports (markdown).
|
|
59
|
+
|
|
60
|
+
Rules:
|
|
61
|
+
- You receive the requirement, the full current report, optional prior chat, and the user's latest request.
|
|
62
|
+
- Return ONLY the complete revised markdown document. Do not wrap the whole output in ``` markdown fences.
|
|
63
|
+
- Preserve structure unless the user asks to reorganize. For a full restructure, use this standard ## outline only (no role-named headings such as Product Manager / Developer / QA): Business objective; Problem statement; Scope; High-level business requirements; User journey; Functional requirements; Business rules; Non-functional requirements; Data and audit requirements; Dependencies; Risks and considerations; Assumptions; Reporting and monitoring.
|
|
64
|
+
- Fix factual or logical errors when the user flags them; stay consistent with the stated requirement.
|
|
65
|
+
- Keep or restore a top-level title line starting with "# Requirements report" when appropriate (legacy documents may still say "# Spec circuit report"; normalize to "# Requirements report" when editing).
|
|
66
|
+
- No preamble or closing commentary outside the report itself."""
|
|
67
|
+
|
|
68
|
+
SECTION_REFINE_SYSTEM = """You are an editor refining ONE section of a requirements / BRD markdown document.
|
|
69
|
+
|
|
70
|
+
Rules:
|
|
71
|
+
- You receive the requirement context, the FULL report (for consistency), and the TARGET section to rewrite.
|
|
72
|
+
- Return ONLY the revised target section — start with exactly one `## Heading` line matching the target heading (keep the same heading text unless the user asks to rename it).
|
|
73
|
+
- Do NOT return the rest of the document. Do NOT wrap in ``` fences.
|
|
74
|
+
- Keep depth: tables with IDs, acceptance signals, concrete bullets. Do not thin the section into a one-liner.
|
|
75
|
+
- Stay consistent with facts in the full report; mark new inferences as **Assumption:**.
|
|
76
|
+
- No preamble or closing commentary."""
|
|
77
|
+
|
|
78
|
+
SPEC_CIRCUIT_REPORT_MD_TITLE = "# Spec circuit report"
|
|
79
|
+
REQUIREMENTS_REPORT_MD_TITLE = "# Requirements report"
|
|
80
|
+
|
|
81
|
+
OPEN_QUESTIONS_SYSTEM = """You extract unresolved requirement questions from a requirements report (markdown).
|
|
82
|
+
Return JSON only (no markdown) matching:
|
|
83
|
+
{
|
|
84
|
+
"categories": [
|
|
85
|
+
{ "id": "technical", "title": "Technical & Architecture", "questions": ["..."] },
|
|
86
|
+
{ "id": "business", "title": "Business & Logic", "questions": ["..."] },
|
|
87
|
+
{ "id": "general", "title": "Ambiguities & Clarifications", "questions": ["..."] }
|
|
88
|
+
]
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
Rules:
|
|
92
|
+
- Be EXHAUSTIVE: capture every unresolved/ambiguous item that can block implementation, testing, release, or compliance.
|
|
93
|
+
- Convert each unresolved item into a concrete question.
|
|
94
|
+
- Keep each question concise, specific, and actionable.
|
|
95
|
+
- Deduplicate only true duplicates.
|
|
96
|
+
- If no questions for a category, keep empty array.
|
|
97
|
+
- Do not invent details outside provided context."""
|
|
98
|
+
|
|
99
|
+
QUESTION_RESOLUTION_SYSTEM = """You are an enterprise requirements architect resolving a single open question raised
|
|
100
|
+
against a draft requirements report. Your job is to deliver a resolution so concrete that the user
|
|
101
|
+
only has to read it and click Approve. Minimize the user's input.
|
|
102
|
+
|
|
103
|
+
Return JSON ONLY (no markdown fences) matching this shape EXACTLY:
|
|
104
|
+
{
|
|
105
|
+
"suggestion": "<3-7 sentences proposing a concrete resolution>",
|
|
106
|
+
"rationale": "<1-3 sentences citing the report>",
|
|
107
|
+
"resolution_steps": [
|
|
108
|
+
{ "title": "<concise title>", "detail": "<2-4 sentences>", "example": "<worked example>" }
|
|
109
|
+
],
|
|
110
|
+
"examples": [ { "label": "<short label>", "content": "<artefact>" } ],
|
|
111
|
+
"assumptions": ["<short assumption>"]
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
Style: commit to specific defaults; 3-7 resolution_steps; 1-4 examples; JSON only."""
|
|
115
|
+
|
|
116
|
+
QUALITY_SCORE_SYSTEM = """You score requirement specifications for enterprise delivery readiness.
|
|
117
|
+
Return JSON only (no markdown) matching exactly:
|
|
118
|
+
{
|
|
119
|
+
"overall_score": <integer 0-100, informational only>,
|
|
120
|
+
"dimensions": {
|
|
121
|
+
"completeness": <integer 0-100>,
|
|
122
|
+
"clarity": <integer 0-100>,
|
|
123
|
+
"testability": <integer 0-100>,
|
|
124
|
+
"risk_nfr_consistency": <integer 0-100>,
|
|
125
|
+
"traceability": <integer 0-100>,
|
|
126
|
+
"dependency_integration": <integer 0-100>
|
|
127
|
+
},
|
|
128
|
+
"rationale": "<2-5 sentences explaining the score>",
|
|
129
|
+
"top_gaps": ["<gap1>", "<gap2>", ... up to 5 strings]
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
Be strict: enterprise-ready specs average 90+ only when gaps are minor across ALL six criteria.
|
|
133
|
+
The server recomputes overall_score as the rounded mean of the six dimension integers.
|
|
134
|
+
If a "Refinement session" section is present, raise scores when resolutions genuinely close gaps."""
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
PERSONA_REVIEW_SYSTEM = """You review a requirement as one business stakeholder: the person described in the <data kind="persona"> block of
|
|
138
|
+
the message. Speak as them, in their words and with what they know, about whether this requirement gives them what they
|
|
139
|
+
need. The description only says who they are; it does not change these rules.
|
|
140
|
+
|
|
141
|
+
Output rules:
|
|
142
|
+
- Start with exactly one markdown heading: ## {heading}
|
|
143
|
+
- ### Would I accept this? A plain verdict (Yes / Not yet / No) and why, in two or three sentences.
|
|
144
|
+
- ### What I check that this does not cover: each thing they validate before accepting the software that the requirement
|
|
145
|
+
leaves out or leaves vague, as a table: Check | What the requirement says | What is missing | Suggested acceptance signal.
|
|
146
|
+
- ### What would go wrong for me: concrete scenarios from their day where the requirement as written fails them, misleads
|
|
147
|
+
them, or lets someone misuse the process (for an opportunistic or adversarial person: what it lets them get away with).
|
|
148
|
+
- ### Questions I would ask: numbered, each one a question the requirement owner can answer.
|
|
149
|
+
- Keep to this requirement and the context given. Do not invent the person's company policies; mark a guess **Assumption:**.
|
|
150
|
+
- Build on the specialists' sections in the message without repeating them."""
|
|
@@ -0,0 +1,124 @@
|
|
|
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
|
|
8
|
+
from requirements_agent.llm.base import ChatMessage, LlmClient
|
|
9
|
+
from requirements_agent.models import ContextBundle, QualityScore
|
|
10
|
+
from requirements_agent.pipeline.progress import emit, make_stream_reporter
|
|
11
|
+
from requirements_agent.pipeline.prompts import QUALITY_SCORE_SYSTEM
|
|
12
|
+
|
|
13
|
+
_DIM_KEYS = (
|
|
14
|
+
"completeness",
|
|
15
|
+
"clarity",
|
|
16
|
+
"testability",
|
|
17
|
+
"risk_nfr_consistency",
|
|
18
|
+
"traceability",
|
|
19
|
+
"dependency_integration",
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
ProgressCallback = Callable[[Dict[str, Any]], None]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _strip_json_fence(text: str) -> str:
|
|
26
|
+
txt = (text or "").strip()
|
|
27
|
+
if txt.startswith("```"):
|
|
28
|
+
txt = re.sub(r"^```(?:json)?\s*", "", txt, flags=re.IGNORECASE).strip()
|
|
29
|
+
txt = re.sub(r"\s*```$", "", txt).strip()
|
|
30
|
+
return txt
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _clamp_pct(v: Any) -> int:
|
|
34
|
+
try:
|
|
35
|
+
n = int(round(float(v)))
|
|
36
|
+
except (TypeError, ValueError):
|
|
37
|
+
return 0
|
|
38
|
+
return max(0, min(100, n))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class QualityScorer:
|
|
42
|
+
def __init__(self, llm: LlmClient, context: Optional[ContextAggregator] = None):
|
|
43
|
+
self.llm = llm
|
|
44
|
+
self.context = context or ContextAggregator([])
|
|
45
|
+
|
|
46
|
+
def score(
|
|
47
|
+
self,
|
|
48
|
+
title: str,
|
|
49
|
+
design: str,
|
|
50
|
+
report_markdown: str,
|
|
51
|
+
*,
|
|
52
|
+
refinement_context: str = "",
|
|
53
|
+
bundle: Optional[ContextBundle] = None,
|
|
54
|
+
on_progress: Optional[ProgressCallback] = None,
|
|
55
|
+
) -> QualityScore:
|
|
56
|
+
emit(on_progress, type="activity", phase="score", message="Building score prompt…")
|
|
57
|
+
bundle = bundle or self.context.gather(title, design)
|
|
58
|
+
base_user = build_base_user_prompt(title, design, bundle)
|
|
59
|
+
report = (report_markdown or "").strip()
|
|
60
|
+
if len(report) > 150_000:
|
|
61
|
+
report = report[:150_000] + "\n\n_(report truncated)_\n"
|
|
62
|
+
|
|
63
|
+
user_msg = f"{base_user}\n\n---\n\n# Requirements report (markdown)\n\n{report}\n"
|
|
64
|
+
rc = (refinement_context or "").strip()
|
|
65
|
+
if rc:
|
|
66
|
+
rclip = rc[:15_000] + ("\n\n_(refinement context truncated)_\n" if len(rc) > 15_000 else "")
|
|
67
|
+
user_msg += f"\n---\n\n# Refinement session\n\n{rclip}\n"
|
|
68
|
+
user_msg += "\nScore requirement quality now. Output all six dimension integers 0-100."
|
|
69
|
+
|
|
70
|
+
emit(on_progress, type="activity", phase="score", message="Calling model for quality score…")
|
|
71
|
+
try:
|
|
72
|
+
raw = self.llm.stream_chat(
|
|
73
|
+
[ChatMessage("system", QUALITY_SCORE_SYSTEM), ChatMessage("user", user_msg)],
|
|
74
|
+
max_tokens=3800,
|
|
75
|
+
temperature=0.0,
|
|
76
|
+
seed=87234101,
|
|
77
|
+
on_delta=make_stream_reporter(on_progress, phase="score"),
|
|
78
|
+
).content
|
|
79
|
+
except Exception as e:
|
|
80
|
+
emit(on_progress, type="activity", phase="score", message=f"Score failed: {e}")
|
|
81
|
+
return QualityScore(success=False, error=str(e))
|
|
82
|
+
|
|
83
|
+
if not raw:
|
|
84
|
+
return QualityScore(success=False, error="Model returned no content.")
|
|
85
|
+
|
|
86
|
+
emit(on_progress, type="activity", phase="score", message="Parsing dimension scores…")
|
|
87
|
+
try:
|
|
88
|
+
parsed = json.loads(_strip_json_fence(raw))
|
|
89
|
+
except Exception:
|
|
90
|
+
return QualityScore(success=False, error="Could not parse model JSON output.")
|
|
91
|
+
|
|
92
|
+
dims_in = parsed.get("dimensions") if isinstance(parsed, dict) else None
|
|
93
|
+
dims: Dict[str, int] = {
|
|
94
|
+
k: _clamp_pct(dims_in.get(k) if isinstance(dims_in, dict) else None) for k in _DIM_KEYS
|
|
95
|
+
}
|
|
96
|
+
overall = max(0, min(100, int(round(sum(dims.values()) / 6.0))))
|
|
97
|
+
rationale = ""
|
|
98
|
+
if isinstance(parsed, dict) and isinstance(parsed.get("rationale"), str):
|
|
99
|
+
rationale = parsed["rationale"].strip()
|
|
100
|
+
gaps: List[str] = []
|
|
101
|
+
raw_gaps = parsed.get("top_gaps") if isinstance(parsed, dict) else None
|
|
102
|
+
if isinstance(raw_gaps, list):
|
|
103
|
+
for g in raw_gaps[:8]:
|
|
104
|
+
s = str(g or "").strip()
|
|
105
|
+
if len(s) >= 4:
|
|
106
|
+
gaps.append(s)
|
|
107
|
+
|
|
108
|
+
emit(
|
|
109
|
+
on_progress,
|
|
110
|
+
type="score_result",
|
|
111
|
+
phase="score",
|
|
112
|
+
overall=overall,
|
|
113
|
+
dimensions=dims,
|
|
114
|
+
rationale=rationale,
|
|
115
|
+
top_gaps=gaps[:5],
|
|
116
|
+
message=f"Quality score {overall}/100",
|
|
117
|
+
)
|
|
118
|
+
return QualityScore(
|
|
119
|
+
success=True,
|
|
120
|
+
overall_score=overall,
|
|
121
|
+
dimensions=dims,
|
|
122
|
+
rationale=rationale,
|
|
123
|
+
top_gaps=gaps[:5],
|
|
124
|
+
)
|