@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,192 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Product knowledge as ForgeQE keeps it: the team's notes in .forgeqe/knowledge (what the product does, roles, glossary,
|
|
3
|
+
business rules, regulations in scope) and the documents added on its Settings page (.forgeqe/documents). A requirement
|
|
4
|
+
gets the sections most about it, never whole files, so a big glossary gives the few terms it uses.
|
|
5
|
+
|
|
6
|
+
Configure with:
|
|
7
|
+
|
|
8
|
+
context:
|
|
9
|
+
providers: [folder, knowledge]
|
|
10
|
+
knowledge:
|
|
11
|
+
project: ../shop # the ForgeQE project (default: the current folder)
|
|
12
|
+
folders: [docs/policies] # more folders inside the project, beside .forgeqe/knowledge and .forgeqe/documents
|
|
13
|
+
max_chars: 8000
|
|
14
|
+
|
|
15
|
+
Read as ForgeQE reads it (`readKnowledge`, ForgeQE/src/knowledge.ts): .md and .txt only, no hidden part, no README, a
|
|
16
|
+
template copy nobody edited left out, pages the knowledge graph wrote left out, nothing reached through a link that
|
|
17
|
+
leaves the project, each file at most 200 KB.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import hashlib
|
|
23
|
+
import json
|
|
24
|
+
import logging
|
|
25
|
+
import math
|
|
26
|
+
import re
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
|
|
29
|
+
|
|
30
|
+
from requirements_agent.context.graph import words
|
|
31
|
+
from requirements_agent.models import ContextChunk
|
|
32
|
+
|
|
33
|
+
logger = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
MAX_FILE = 200_000
|
|
36
|
+
MAX_FILES = 400
|
|
37
|
+
DEFAULT_MAX_CHARS = 8000
|
|
38
|
+
MANIFESTS = (".forgeqe-manifest.json", ".webpilot-manifest.json")
|
|
39
|
+
HEADING = re.compile(r"^(#{1,4})\s+(.+?)\s*$", re.MULTILINE)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _inside(root: Path, p: Path) -> bool:
|
|
43
|
+
try:
|
|
44
|
+
p.resolve().relative_to(root.resolve())
|
|
45
|
+
return True
|
|
46
|
+
except (ValueError, OSError):
|
|
47
|
+
return False
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _manifest(folder: Path) -> Dict[str, str]:
|
|
51
|
+
for name in MANIFESTS:
|
|
52
|
+
f = folder / name
|
|
53
|
+
if f.is_file():
|
|
54
|
+
try:
|
|
55
|
+
entries = json.loads(f.read_text(encoding="utf-8")).get("entries") or {}
|
|
56
|
+
return {str(k): str((v or {}).get("sha") or "") for k, v in entries.items() if isinstance(v, dict)}
|
|
57
|
+
except (OSError, ValueError, AttributeError):
|
|
58
|
+
return {}
|
|
59
|
+
return {}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _generated(folder: Path) -> Set[str]:
|
|
63
|
+
try:
|
|
64
|
+
pages = json.loads((folder / "graph" / "pages.json").read_text(encoding="utf-8")).get("pages")
|
|
65
|
+
return {str(p) for p in pages} if isinstance(pages, list) else set()
|
|
66
|
+
except (OSError, ValueError, AttributeError):
|
|
67
|
+
return set()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _sha16(text: str) -> str:
|
|
71
|
+
return hashlib.sha256(text.replace("\r\n", "\n").encode("utf-8")).hexdigest()[:16]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def read_files(project: Path, folders: Sequence[Path]) -> List[Tuple[str, str]]:
|
|
75
|
+
"""(name, text) of each knowledge file, its name relative to the project."""
|
|
76
|
+
out: List[Tuple[str, str]] = []
|
|
77
|
+
seen: Set[Path] = set()
|
|
78
|
+
for folder in folders:
|
|
79
|
+
if not folder.is_dir() or not _inside(project, folder):
|
|
80
|
+
continue
|
|
81
|
+
manifest = _manifest(folder)
|
|
82
|
+
generated = _generated(folder)
|
|
83
|
+
for f in sorted(folder.rglob("*")):
|
|
84
|
+
if len(out) >= MAX_FILES:
|
|
85
|
+
return out
|
|
86
|
+
rel = f.relative_to(folder)
|
|
87
|
+
if any(part.startswith(".") for part in rel.parts):
|
|
88
|
+
continue
|
|
89
|
+
if f.suffix.lower() not in (".md", ".txt") or f.name.lower() == "readme.md":
|
|
90
|
+
continue
|
|
91
|
+
if not f.is_file() or not _inside(project, f):
|
|
92
|
+
continue
|
|
93
|
+
real = f.resolve()
|
|
94
|
+
if real in seen:
|
|
95
|
+
continue
|
|
96
|
+
key = rel.as_posix()
|
|
97
|
+
if key in generated:
|
|
98
|
+
continue
|
|
99
|
+
try:
|
|
100
|
+
if f.stat().st_size > MAX_FILE:
|
|
101
|
+
continue
|
|
102
|
+
text = f.read_text(encoding="utf-8", errors="replace")
|
|
103
|
+
except OSError:
|
|
104
|
+
continue
|
|
105
|
+
if manifest.get(key) and manifest[key] == _sha16(text):
|
|
106
|
+
continue # a template copy nobody filled in
|
|
107
|
+
text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL).strip()
|
|
108
|
+
if not re.sub(r"(?m)^#.*$", "", text).strip():
|
|
109
|
+
continue
|
|
110
|
+
seen.add(real)
|
|
111
|
+
try:
|
|
112
|
+
name = real.relative_to(project.resolve()).as_posix()
|
|
113
|
+
except ValueError:
|
|
114
|
+
name = key
|
|
115
|
+
out.append((name, text))
|
|
116
|
+
return out
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def sections(name: str, text: str) -> List[Tuple[str, str]]:
|
|
120
|
+
"""(heading path, text) for each section that has text of its own."""
|
|
121
|
+
marks = list(HEADING.finditer(text))
|
|
122
|
+
if not marks:
|
|
123
|
+
return [(name, text)]
|
|
124
|
+
out: List[Tuple[str, str]] = []
|
|
125
|
+
trail: List[Tuple[int, str]] = []
|
|
126
|
+
if text[: marks[0].start()].strip():
|
|
127
|
+
out.append((name, text[: marks[0].start()].strip()))
|
|
128
|
+
for i, m in enumerate(marks):
|
|
129
|
+
level = len(m.group(1))
|
|
130
|
+
trail = [t for t in trail if t[0] < level] + [(level, m.group(2))]
|
|
131
|
+
body = text[m.end() : marks[i + 1].start() if i + 1 < len(marks) else len(text)].strip()
|
|
132
|
+
if body:
|
|
133
|
+
out.append((" › ".join(t[1] for t in trail), body))
|
|
134
|
+
return out
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def rank(query: str, parts: List[Tuple[str, str, str]], max_chars: int) -> List[Tuple[float, str, str, str]]:
|
|
138
|
+
"""BM25 over (file, heading, text), a heading word counting double; at most max_chars of text."""
|
|
139
|
+
want = words(query)
|
|
140
|
+
if not want or not parts:
|
|
141
|
+
return []
|
|
142
|
+
docs = [(words(h), words(t)) for _, h, t in parts]
|
|
143
|
+
n = len(docs)
|
|
144
|
+
df = {w: sum(1 for h, t in docs if w in h or w in t) for w in want}
|
|
145
|
+
avg = sum(len(t) for _, t in docs) / n or 1.0
|
|
146
|
+
scored: List[Tuple[float, int]] = []
|
|
147
|
+
for i, (h, t) in enumerate(docs):
|
|
148
|
+
s = 0.0
|
|
149
|
+
for w in want:
|
|
150
|
+
if not df[w]:
|
|
151
|
+
continue
|
|
152
|
+
tf = (2 if w in h else 0) + (1 if w in t else 0)
|
|
153
|
+
if not tf:
|
|
154
|
+
continue
|
|
155
|
+
idf = math.log(1 + (n - df[w] + 0.5) / (df[w] + 0.5))
|
|
156
|
+
s += idf * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * len(t) / avg))
|
|
157
|
+
if s > 0:
|
|
158
|
+
scored.append((s, i))
|
|
159
|
+
scored.sort(key=lambda x: (-x[0], x[1]))
|
|
160
|
+
out: List[Tuple[float, str, str, str]] = []
|
|
161
|
+
used = 0
|
|
162
|
+
for s, i in scored:
|
|
163
|
+
f, h, t = parts[i]
|
|
164
|
+
if used + len(t) > max_chars:
|
|
165
|
+
continue
|
|
166
|
+
out.append((s, f, h, t))
|
|
167
|
+
used += len(t)
|
|
168
|
+
return out
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class KnowledgeProvider:
|
|
172
|
+
name = "knowledge"
|
|
173
|
+
|
|
174
|
+
def __init__(self, settings: Optional[Dict[str, Any]] = None):
|
|
175
|
+
s = settings or {}
|
|
176
|
+
self.project = Path(str(s.get("project") or ".")).expanduser()
|
|
177
|
+
self.extra = [str(f) for f in (s.get("folders") or []) if str(f).strip()]
|
|
178
|
+
self.dir = str(s.get("dir") or "")
|
|
179
|
+
self.max_chars = int(s.get("max_chars") or DEFAULT_MAX_CHARS)
|
|
180
|
+
|
|
181
|
+
def folders(self) -> List[Path]:
|
|
182
|
+
base = self.project
|
|
183
|
+
knowledge = (base / self.dir) if self.dir else base / ".forgeqe" / "knowledge"
|
|
184
|
+
return [knowledge, base / ".forgeqe" / "documents", *[base / f for f in self.extra]]
|
|
185
|
+
|
|
186
|
+
def fetch(self, query: str) -> List[ContextChunk]:
|
|
187
|
+
files = read_files(self.project, self.folders())
|
|
188
|
+
parts = [(name, heading, body) for name, text in files for heading, body in sections(name, text)]
|
|
189
|
+
return [
|
|
190
|
+
ContextChunk(source=f"knowledge: {f} › {h}", content=t, score=float(s), meta={"kind": "knowledge", "file": f})
|
|
191
|
+
for s, f, h, t in rank(query, parts, self.max_chars)
|
|
192
|
+
]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from typing import Any, Dict, List
|
|
5
|
+
|
|
6
|
+
from requirements_agent.models import ContextChunk
|
|
7
|
+
|
|
8
|
+
logger = logging.getLogger(__name__)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class McpProvider:
|
|
12
|
+
"""An MCP server's search tool is ForgeQE's to call (rag.mcp in forgeqe.yaml, through its checked MCP proxy): run the
|
|
13
|
+
review from ForgeQE (`forgeqe requirements`, or its web app's Requirements page) and the passages it finds arrive as
|
|
14
|
+
given context (context/given.py). Here it returns nothing."""
|
|
15
|
+
|
|
16
|
+
name = "mcp"
|
|
17
|
+
|
|
18
|
+
def __init__(self, settings: Dict[str, Any] | None = None):
|
|
19
|
+
self.settings = settings or {}
|
|
20
|
+
if self.settings:
|
|
21
|
+
logger.info("context.mcp: an MCP search is run by ForgeQE; review with forgeqe requirements to use it")
|
|
22
|
+
|
|
23
|
+
def fetch(self, query: str) -> List[ContextChunk]:
|
|
24
|
+
return []
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Review memory: what earlier reviews of this product decided, so a new review builds on it instead of asking again.
|
|
3
|
+
|
|
4
|
+
Each gap or question a person resolves (an accepted fix, with their answer) is kept as one decision, and each finished
|
|
5
|
+
review as its title and score. A new requirement gets the decisions most about it, marked as decided earlier: the
|
|
6
|
+
review keeps to them, or says plainly where the new requirement contradicts one.
|
|
7
|
+
|
|
8
|
+
Kept as JSON lines in the memory folder: `<project>/.forgeqe/requirements/memory/decisions.jsonl` in a ForgeQE project
|
|
9
|
+
(ForgeQE's web app writes the same file), else `~/.config/requirements-agent/memory/decisions.jsonl`. Configure with:
|
|
10
|
+
|
|
11
|
+
context:
|
|
12
|
+
providers: [folder, memory]
|
|
13
|
+
memory: { dir: .forgeqe/requirements/memory, limit: 8 }
|
|
14
|
+
|
|
15
|
+
What was written can be edited by anyone with the folder, so it is read back as untrusted: known keys only, each text
|
|
16
|
+
one line and clipped, the newest MAX_ENTRIES only, never through a link; the file is written at 0600.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
import logging
|
|
23
|
+
import os
|
|
24
|
+
import time
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any, Dict, List, Optional
|
|
27
|
+
|
|
28
|
+
from requirements_agent.context.graph import words
|
|
29
|
+
from requirements_agent.context.untrusted import one_line
|
|
30
|
+
from requirements_agent.models import ContextChunk
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
FILE = "decisions.jsonl"
|
|
35
|
+
KINDS = ("decision", "review")
|
|
36
|
+
MAX_ENTRIES = 2000
|
|
37
|
+
MAX_FILE = 4 * 1024 * 1024
|
|
38
|
+
DEFAULT_LIMIT = 8
|
|
39
|
+
LIMITS = {"title": 200, "item": 600, "answer": 1200, "section": 160, "category": 60, "at": 40}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def default_dir(project: Optional[Path] = None) -> Path:
|
|
43
|
+
base = Path(project or Path.cwd())
|
|
44
|
+
if (base / ".forgeqe").is_dir():
|
|
45
|
+
return base / ".forgeqe" / "requirements" / "memory"
|
|
46
|
+
return Path.home() / ".config" / "requirements-agent" / "memory"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def clean_entry(raw: Any) -> Optional[Dict[str, Any]]:
|
|
50
|
+
"""An entry in its shape, or None."""
|
|
51
|
+
if not isinstance(raw, dict) or raw.get("kind") not in KINDS:
|
|
52
|
+
return None
|
|
53
|
+
out: Dict[str, Any] = {"kind": raw["kind"]}
|
|
54
|
+
for key, n in LIMITS.items():
|
|
55
|
+
if isinstance(raw.get(key), str):
|
|
56
|
+
v = one_line(raw[key], n)
|
|
57
|
+
if v:
|
|
58
|
+
out[key] = v
|
|
59
|
+
score = raw.get("score")
|
|
60
|
+
if isinstance(score, (int, float)) and not isinstance(score, bool) and 0 <= score <= 100:
|
|
61
|
+
out["score"] = int(score)
|
|
62
|
+
if out["kind"] == "decision" and not (out.get("item") and out.get("answer")):
|
|
63
|
+
return None
|
|
64
|
+
if out["kind"] == "review" and not out.get("title"):
|
|
65
|
+
return None
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class ReviewMemory:
|
|
70
|
+
def __init__(self, folder: Optional[Path] = None):
|
|
71
|
+
self.folder = Path(folder) if folder else default_dir()
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def file(self) -> Path:
|
|
75
|
+
return self.folder / FILE
|
|
76
|
+
|
|
77
|
+
def entries(self) -> List[Dict[str, Any]]:
|
|
78
|
+
f = self.file
|
|
79
|
+
try:
|
|
80
|
+
if f.is_symlink() or not f.is_file() or f.stat().st_size > MAX_FILE:
|
|
81
|
+
return []
|
|
82
|
+
lines = f.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
83
|
+
except OSError:
|
|
84
|
+
return []
|
|
85
|
+
out: List[Dict[str, Any]] = []
|
|
86
|
+
for line in lines[-MAX_ENTRIES:]:
|
|
87
|
+
try:
|
|
88
|
+
e = clean_entry(json.loads(line))
|
|
89
|
+
except ValueError:
|
|
90
|
+
continue
|
|
91
|
+
if e:
|
|
92
|
+
out.append(e)
|
|
93
|
+
return out
|
|
94
|
+
|
|
95
|
+
def add(self, entry: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
96
|
+
e = clean_entry({**entry, "at": entry.get("at") or time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())})
|
|
97
|
+
if not e:
|
|
98
|
+
return None
|
|
99
|
+
self.folder.mkdir(parents=True, exist_ok=True)
|
|
100
|
+
f = self.file
|
|
101
|
+
if f.is_symlink():
|
|
102
|
+
raise OSError(f"{f} is a link; review memory is never written through one")
|
|
103
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND | getattr(os, "O_NOFOLLOW", 0)
|
|
104
|
+
fd = os.open(f, flags, 0o600)
|
|
105
|
+
with os.fdopen(fd, "a", encoding="utf-8") as h:
|
|
106
|
+
h.write(json.dumps(e, ensure_ascii=False) + "\n")
|
|
107
|
+
return e
|
|
108
|
+
|
|
109
|
+
def recall(self, query: str, limit: int = DEFAULT_LIMIT) -> List[Dict[str, Any]]:
|
|
110
|
+
"""The decisions most about the query, best first (shared words, the newest winning a tie)."""
|
|
111
|
+
want = words(query)
|
|
112
|
+
if not want:
|
|
113
|
+
return []
|
|
114
|
+
scored = []
|
|
115
|
+
decisions = [e for e in self.entries() if e["kind"] == "decision"]
|
|
116
|
+
for i, e in enumerate(decisions):
|
|
117
|
+
have = words(" ".join(str(e.get(k, "")) for k in ("title", "item", "answer", "section")))
|
|
118
|
+
hits = len(want & have)
|
|
119
|
+
if hits >= 2:
|
|
120
|
+
scored.append((hits, i, e))
|
|
121
|
+
scored.sort(key=lambda x: (-x[0], -x[1]))
|
|
122
|
+
return [e for _, _, e in scored[:limit]]
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def decision_line(e: Dict[str, Any]) -> str:
|
|
126
|
+
when = (e.get("at") or "")[:10]
|
|
127
|
+
on = f' on "{e["title"]}"' if e.get("title") else ""
|
|
128
|
+
where = f" (section: {e['section']})" if e.get("section") else ""
|
|
129
|
+
return f"- {when}{on}{where}: {e.get('category') or 'Gap'}: {e['item']} → decided: {e['answer']}"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class MemoryProvider:
|
|
133
|
+
name = "memory"
|
|
134
|
+
|
|
135
|
+
def __init__(self, settings: Optional[Dict[str, Any]] = None):
|
|
136
|
+
s = settings or {}
|
|
137
|
+
self.memory = ReviewMemory(Path(str(s["dir"])).expanduser() if s.get("dir") else None)
|
|
138
|
+
self.limit = int(s.get("limit") or DEFAULT_LIMIT)
|
|
139
|
+
|
|
140
|
+
def fetch(self, query: str) -> List[ContextChunk]:
|
|
141
|
+
found = self.memory.recall(query, self.limit)
|
|
142
|
+
if not found:
|
|
143
|
+
return []
|
|
144
|
+
return [ContextChunk(source="review memory", content="\n".join(decision_line(e) for e in found), meta={"kind": "memory", "count": len(found)})]
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""
|
|
2
|
+
ForgeQE's business personas (.forgeqe/business-personas/<id>.yaml): a payments SME, an everyday end user, a compliance
|
|
3
|
+
specialist. The review asks each chosen persona whether the requirement gives them what they need and covers what they
|
|
4
|
+
check before they accept the software.
|
|
5
|
+
|
|
6
|
+
A persona file can come from a repository, so it is read the way ForgeQE reads it (`businessPersonaFrom`,
|
|
7
|
+
ForgeQE/src/personas/business.ts): known keys only, no YAML aliases, each choice from its list, every text one line and
|
|
8
|
+
clipped, lists capped, text that reads as an instruction to an agent refused, a regular file only and never through a
|
|
9
|
+
link. A persona ForgeQE hands over (its built-ins too) is checked again here the same way.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import logging
|
|
15
|
+
import re
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
|
18
|
+
|
|
19
|
+
import yaml
|
|
20
|
+
|
|
21
|
+
from requirements_agent.context.untrusted import instruction_in, one_line
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
PERSONA_KEYS = (
|
|
27
|
+
"id", "handle", "name", "kind", "role", "domain", "expertise", "description", "goals", "knows", "validates",
|
|
28
|
+
"frustrations", "scenarios", "intent", "risk_appetite", "motivations", "permissions", "constraints", "mistakes",
|
|
29
|
+
"relationships", "version", "skills", "knowledge",
|
|
30
|
+
)
|
|
31
|
+
KINDS = {"sme": "Subject matter expert", "end_user": "End user", "specialist": "Specialist", "business_user": "Business user"}
|
|
32
|
+
EXPERTISE = ("novice", "intermediate", "expert")
|
|
33
|
+
INTENTS = ("legitimate", "opportunistic", "adversarial")
|
|
34
|
+
RISK = ("low", "medium", "high")
|
|
35
|
+
LISTS = ("goals", "knows", "validates", "frustrations", "scenarios", "motivations", "permissions", "constraints", "mistakes", "relationships")
|
|
36
|
+
PERSONA_ID = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
|
|
37
|
+
SKILL_REF = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")
|
|
38
|
+
KNOWLEDGE_REF = re.compile(r"^(?!.*(^|/)\.)(?!/)[\w .-]+(/[\w .-]+)+$")
|
|
39
|
+
MAX_LIST = 12
|
|
40
|
+
MAX_ITEM = 240
|
|
41
|
+
MAX_DESCRIPTION = 1200
|
|
42
|
+
MAX_FILE = 20_000
|
|
43
|
+
MAX_PERSONAS = 6
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class _NoAliases(yaml.SafeLoader):
|
|
47
|
+
"""A persona has no use for anchors or aliases, and they can make a small file expand into a large one."""
|
|
48
|
+
|
|
49
|
+
def compose_node(self, parent, index): # type: ignore[override]
|
|
50
|
+
if self.check_event(yaml.AliasEvent):
|
|
51
|
+
raise yaml.YAMLError("YAML aliases are not allowed in a persona")
|
|
52
|
+
event = self.peek_event()
|
|
53
|
+
if getattr(event, "anchor", None):
|
|
54
|
+
raise yaml.YAMLError("YAML anchors are not allowed in a persona")
|
|
55
|
+
return super().compose_node(parent, index)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def persona_from(raw: Any, id_from_file: Optional[str] = None) -> Dict[str, Any]:
|
|
59
|
+
"""A persona from its fields; raises ValueError with what is wrong."""
|
|
60
|
+
if not isinstance(raw, dict):
|
|
61
|
+
raise ValueError("A business persona is a map of its fields.")
|
|
62
|
+
unknown = [k for k in raw if k not in PERSONA_KEYS and k != "builtIn"]
|
|
63
|
+
if unknown:
|
|
64
|
+
raise ValueError("Unknown persona field(s): " + ", ".join(one_line(k, 40) for k in unknown))
|
|
65
|
+
pid = one_line(raw.get("id", id_from_file), 40).lower()
|
|
66
|
+
if not PERSONA_ID.match(pid):
|
|
67
|
+
raise ValueError(f'Persona id "{pid}" must be lower-case letters, digits and dashes.')
|
|
68
|
+
if id_from_file and pid != id_from_file:
|
|
69
|
+
raise ValueError(f'The persona in {id_from_file}.yaml has id "{pid}": a file\'s id is its name.')
|
|
70
|
+
|
|
71
|
+
def text(key: str, n: int) -> str:
|
|
72
|
+
v = raw.get(key)
|
|
73
|
+
if v is not None and not isinstance(v, str):
|
|
74
|
+
raise ValueError(f"{key} is text.")
|
|
75
|
+
t = one_line(v or "", n)
|
|
76
|
+
if instruction_in(t):
|
|
77
|
+
raise ValueError(f"{key} reads as an instruction to an agent; a persona only describes a person.")
|
|
78
|
+
return t
|
|
79
|
+
|
|
80
|
+
def pick(key: str, choices: Sequence[str], default: str) -> str:
|
|
81
|
+
v = raw.get(key)
|
|
82
|
+
v = default if v in (None, "") else str(v)
|
|
83
|
+
if v not in choices:
|
|
84
|
+
raise ValueError(f"{key} is one of {', '.join(choices)}.")
|
|
85
|
+
return v
|
|
86
|
+
|
|
87
|
+
def items(key: str) -> List[str]:
|
|
88
|
+
v = raw.get(key)
|
|
89
|
+
if v is None:
|
|
90
|
+
return []
|
|
91
|
+
if not isinstance(v, list) or any(not isinstance(x, str) for x in v):
|
|
92
|
+
raise ValueError(f"{key} is a list of text.")
|
|
93
|
+
out: List[str] = []
|
|
94
|
+
for x in v:
|
|
95
|
+
t = one_line(x, MAX_ITEM)
|
|
96
|
+
if t and t not in out:
|
|
97
|
+
out.append(t)
|
|
98
|
+
out = out[:MAX_LIST]
|
|
99
|
+
if any(instruction_in(x) for x in out):
|
|
100
|
+
raise ValueError(f"{key} has an item that reads as an instruction to an agent.")
|
|
101
|
+
return out
|
|
102
|
+
|
|
103
|
+
def refs(key: str, shape: "re.Pattern[str]") -> List[str]:
|
|
104
|
+
v = raw.get(key)
|
|
105
|
+
if v is None:
|
|
106
|
+
return []
|
|
107
|
+
if not isinstance(v, list) or any(not isinstance(x, str) for x in v):
|
|
108
|
+
raise ValueError(f"{key} is a list of names.")
|
|
109
|
+
out = [x.strip() for x in v if x.strip()]
|
|
110
|
+
if any(len(x) > 200 or not shape.match(x) for x in out) or len(out) > MAX_LIST:
|
|
111
|
+
raise ValueError(f"{key} holds a name of the wrong shape.")
|
|
112
|
+
return list(dict.fromkeys(out))
|
|
113
|
+
|
|
114
|
+
name = text("name", 80)
|
|
115
|
+
if not name:
|
|
116
|
+
raise ValueError("A persona needs a name.")
|
|
117
|
+
persona: Dict[str, Any] = {
|
|
118
|
+
"id": pid,
|
|
119
|
+
"name": name,
|
|
120
|
+
"kind": pick("kind", tuple(KINDS), "business_user"),
|
|
121
|
+
"role": text("role", 120),
|
|
122
|
+
"domain": text("domain", 80),
|
|
123
|
+
"expertise": pick("expertise", EXPERTISE, "intermediate"),
|
|
124
|
+
"description": text("description", MAX_DESCRIPTION),
|
|
125
|
+
"intent": pick("intent", INTENTS, "legitimate"),
|
|
126
|
+
"risk_appetite": pick("risk_appetite", RISK, "low"),
|
|
127
|
+
"skills": refs("skills", SKILL_REF),
|
|
128
|
+
"knowledge": refs("knowledge", KNOWLEDGE_REF),
|
|
129
|
+
}
|
|
130
|
+
for key in LISTS:
|
|
131
|
+
persona[key] = items(key)
|
|
132
|
+
if not persona["role"]:
|
|
133
|
+
raise ValueError("A persona needs a role.")
|
|
134
|
+
if not persona["validates"] and not persona["goals"]:
|
|
135
|
+
raise ValueError("A persona needs goals or what it validates.")
|
|
136
|
+
return persona
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def personas_dir(project: Path) -> Path:
|
|
140
|
+
return project / ".forgeqe" / "business-personas"
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def project_personas(project: Path) -> Tuple[List[Dict[str, Any]], List[str]]:
|
|
144
|
+
"""The project's own personas; a file that is not a valid persona is reported, not used."""
|
|
145
|
+
folder = personas_dir(project)
|
|
146
|
+
personas: List[Dict[str, Any]] = []
|
|
147
|
+
errors: List[str] = []
|
|
148
|
+
if not folder.is_dir() or folder.is_symlink():
|
|
149
|
+
return personas, errors
|
|
150
|
+
for f in sorted(folder.iterdir()):
|
|
151
|
+
if f.suffix not in (".yaml", ".yml"):
|
|
152
|
+
continue
|
|
153
|
+
pid = f.stem
|
|
154
|
+
try:
|
|
155
|
+
if not PERSONA_ID.match(pid):
|
|
156
|
+
raise ValueError("the file name must be the persona's id")
|
|
157
|
+
if f.is_symlink() or not f.is_file():
|
|
158
|
+
raise ValueError("not a regular file")
|
|
159
|
+
body = f.read_text(encoding="utf-8")
|
|
160
|
+
if len(body) > MAX_FILE:
|
|
161
|
+
raise ValueError("the file is too large for a persona")
|
|
162
|
+
personas.append(persona_from(yaml.load(body, Loader=_NoAliases), pid))
|
|
163
|
+
except (ValueError, yaml.YAMLError, OSError, UnicodeDecodeError) as e:
|
|
164
|
+
errors.append(f"{one_line(f.name, 60)}: {one_line(e, 300)}")
|
|
165
|
+
return personas, errors
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def choose(personas: Sequence[Dict[str, Any]], ids: Sequence[str]) -> List[Dict[str, Any]]:
|
|
169
|
+
"""The personas named, in the order named; an id the list does not have is an error naming the ones it has."""
|
|
170
|
+
by_id = {p["id"]: p for p in personas}
|
|
171
|
+
out: List[Dict[str, Any]] = []
|
|
172
|
+
for raw in ids:
|
|
173
|
+
pid = one_line(raw, 40).lower()
|
|
174
|
+
if pid not in by_id:
|
|
175
|
+
have = ", ".join(sorted(by_id)) or "(none)"
|
|
176
|
+
raise ValueError(f'No business persona "{pid}". Personas: {have}.')
|
|
177
|
+
if by_id[pid] not in out:
|
|
178
|
+
out.append(by_id[pid])
|
|
179
|
+
if len(out) > MAX_PERSONAS:
|
|
180
|
+
raise ValueError(f"At most {MAX_PERSONAS} personas review one requirement.")
|
|
181
|
+
return out
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def persona_brief(p: Dict[str, Any]) -> str:
|
|
185
|
+
"""Who the persona is, in the words ForgeQE uses for one (`personaBrief`), as a reviewer of a requirement."""
|
|
186
|
+
lines = [
|
|
187
|
+
f"{p['name']}, {p['role']}{' (' + p['domain'] + ')' if p.get('domain') else ''}: "
|
|
188
|
+
f"{KINDS.get(p.get('kind', ''), 'Business user').lower()}, {p.get('expertise', 'intermediate')} in the domain.",
|
|
189
|
+
]
|
|
190
|
+
if p.get("description"):
|
|
191
|
+
lines.append(p["description"])
|
|
192
|
+
for title, key in (
|
|
193
|
+
("Wants to", "goals"),
|
|
194
|
+
("Knows", "knows"),
|
|
195
|
+
("Checks before accepting the software", "validates"),
|
|
196
|
+
("Is put off by", "frustrations"),
|
|
197
|
+
("Would try", "scenarios"),
|
|
198
|
+
("Is driven by", "motivations"),
|
|
199
|
+
("May, in their role", "permissions"),
|
|
200
|
+
("Works within", "constraints"),
|
|
201
|
+
("Plausibly gets wrong", "mistakes"),
|
|
202
|
+
("Deals with", "relationships"),
|
|
203
|
+
):
|
|
204
|
+
if p.get(key):
|
|
205
|
+
lines.append(f"{title}:")
|
|
206
|
+
lines.extend(f"- {x}" for x in p[key])
|
|
207
|
+
if p.get("intent") and p["intent"] != "legitimate":
|
|
208
|
+
lines.append(
|
|
209
|
+
f"Intent: {p['intent']} (risk appetite {p.get('risk_appetite', 'low')}): looks for what the requirement "
|
|
210
|
+
"lets them do that the business did not mean to allow."
|
|
211
|
+
)
|
|
212
|
+
if p.get("knowledge"):
|
|
213
|
+
lines.append("Documents they rely on: " + ", ".join(p["knowledge"]))
|
|
214
|
+
return "\n".join(lines)
|