@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,627 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The Requirements Agent for a host such as ForgeQE's web app: one operation per process (`req-agent web <op> --dir D`),
|
|
3
|
+
its request as one JSON object on stdin, its progress and answer as JSON lines on stdout. All state is in the review's
|
|
4
|
+
folder, so any operation can follow any other, from any process:
|
|
5
|
+
|
|
6
|
+
review {title, design, context?: {chunks, personas}, consolidate?} the full pipeline into the folder
|
|
7
|
+
show {} the review as the page draws it
|
|
8
|
+
fix {index, answer?} a proposed change for gap or question n
|
|
9
|
+
accept {rescore?} keep the proposal; remember the decision
|
|
10
|
+
skip {index} leave item n open, drop its proposal
|
|
11
|
+
undo {} put back the version before the last accept
|
|
12
|
+
export {format: "pdf"} the current report as PDF
|
|
13
|
+
suggest {index} a suggested answer for item n, kept
|
|
14
|
+
consolidate {} the requirements report (BRD) written again
|
|
15
|
+
from the Spec Circuit report and the decisions
|
|
16
|
+
|
|
17
|
+
These are `/fix n`, `/yes`, `/undo` of the terminal shell. Each line on stdout is {"type": ...}; the last is
|
|
18
|
+
{"type": "result", ...} or {"type": "error", "message"}. Every file is read and written inside the folder only, never
|
|
19
|
+
through a link; what was written there is read back as untrusted (known keys, plain shapes).
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import difflib
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import re
|
|
28
|
+
import sys
|
|
29
|
+
import time
|
|
30
|
+
from dataclasses import is_dataclass
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
33
|
+
|
|
34
|
+
from requirements_agent.context.memory import ReviewMemory
|
|
35
|
+
from requirements_agent.context.untrusted import one_line
|
|
36
|
+
|
|
37
|
+
SPEC = "01-spec-circuit-report.md"
|
|
38
|
+
BRD = "02-requirements-report.md"
|
|
39
|
+
STATE = "state.json"
|
|
40
|
+
REQUEST = "request.json"
|
|
41
|
+
PROPOSAL = "proposal.md"
|
|
42
|
+
VERSIONS = "versions"
|
|
43
|
+
MAX_STDIN = 2 * 1024 * 1024
|
|
44
|
+
MAX_DESIGN = 200_000
|
|
45
|
+
MAX_ITEMS = 60
|
|
46
|
+
MAX_DIFF = 400
|
|
47
|
+
OPS = ("review", "show", "fix", "accept", "skip", "undo", "export", "suggest", "consolidate")
|
|
48
|
+
DIMENSIONS = (
|
|
49
|
+
("completeness", "Completeness"),
|
|
50
|
+
("clarity", "Clarity"),
|
|
51
|
+
("testability", "Testability"),
|
|
52
|
+
("risk_nfr_consistency", "Risk and NFRs"),
|
|
53
|
+
("traceability", "Traceability"),
|
|
54
|
+
("dependency_integration", "Dependencies"),
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
Emit = Callable[[Dict[str, Any]], None]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class OpError(Exception):
|
|
61
|
+
pass
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def out_line(payload: Dict[str, Any]) -> None:
|
|
65
|
+
sys.stdout.write(json.dumps(payload, ensure_ascii=False, default=str) + "\n")
|
|
66
|
+
sys.stdout.flush()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# --- the folder ---------------------------------------------------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Folder:
|
|
73
|
+
def __init__(self, path: Path, *, create: bool = False):
|
|
74
|
+
if create:
|
|
75
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
76
|
+
if path.is_symlink() or not path.is_dir():
|
|
77
|
+
raise OpError("The review's folder is not there.")
|
|
78
|
+
self.root = path.resolve()
|
|
79
|
+
|
|
80
|
+
def file(self, name: str) -> Path:
|
|
81
|
+
p = self.root / name
|
|
82
|
+
if p.is_symlink():
|
|
83
|
+
raise OpError(f"{name} is a link; a review's files are never read or written through one.")
|
|
84
|
+
try:
|
|
85
|
+
p.resolve().relative_to(self.root)
|
|
86
|
+
except ValueError as e:
|
|
87
|
+
raise OpError(f"{name} is outside the review's folder.") from e
|
|
88
|
+
return p
|
|
89
|
+
|
|
90
|
+
def read(self, name: str) -> Optional[str]:
|
|
91
|
+
p = self.file(name)
|
|
92
|
+
try:
|
|
93
|
+
return p.read_text(encoding="utf-8") if p.is_file() else None
|
|
94
|
+
except OSError:
|
|
95
|
+
return None
|
|
96
|
+
|
|
97
|
+
def write(self, name: str, text: str) -> Path:
|
|
98
|
+
p = self.file(name)
|
|
99
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
100
|
+
tmp = p.with_name(f".{p.name}.{os.getpid()}.tmp")
|
|
101
|
+
tmp.write_text(text, encoding="utf-8")
|
|
102
|
+
os.replace(tmp, p)
|
|
103
|
+
return p
|
|
104
|
+
|
|
105
|
+
def json(self, name: str) -> Any:
|
|
106
|
+
text = self.read(name)
|
|
107
|
+
if text is None:
|
|
108
|
+
return None
|
|
109
|
+
try:
|
|
110
|
+
return json.loads(text)
|
|
111
|
+
except ValueError:
|
|
112
|
+
return None
|
|
113
|
+
|
|
114
|
+
def write_json(self, name: str, data: Any) -> Path:
|
|
115
|
+
return self.write(name, json.dumps(data, indent=2, ensure_ascii=False))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# --- state, read back as untrusted --------------------------------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
STATUSES = ("open", "accepted", "skipped")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def clean_items(raw: Any) -> List[Dict[str, Any]]:
|
|
124
|
+
out: List[Dict[str, Any]] = []
|
|
125
|
+
for i, it in enumerate(raw if isinstance(raw, list) else [], start=1):
|
|
126
|
+
if not isinstance(it, dict) or not isinstance(it.get("text"), str):
|
|
127
|
+
continue
|
|
128
|
+
out.append(
|
|
129
|
+
{
|
|
130
|
+
"index": i,
|
|
131
|
+
"kind": "question" if it.get("kind") == "question" else "gap",
|
|
132
|
+
"text": one_line(it["text"], 600),
|
|
133
|
+
"category": one_line(it.get("category") or "", 60),
|
|
134
|
+
"status": it.get("status") if it.get("status") in STATUSES else "open",
|
|
135
|
+
}
|
|
136
|
+
)
|
|
137
|
+
return out[:MAX_ITEMS]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def clean_proposal(raw: Any) -> Optional[Dict[str, Any]]:
|
|
141
|
+
if not isinstance(raw, dict) or not isinstance(raw.get("index"), int):
|
|
142
|
+
return None
|
|
143
|
+
diff = [
|
|
144
|
+
{"op": d["op"], "text": str(d.get("text", ""))[:2000]}
|
|
145
|
+
for d in (raw.get("diff") if isinstance(raw.get("diff"), list) else [])
|
|
146
|
+
if isinstance(d, dict) and d.get("op") in ("-", "+", " ")
|
|
147
|
+
][:MAX_DIFF]
|
|
148
|
+
return {
|
|
149
|
+
"index": raw["index"],
|
|
150
|
+
"section": one_line(raw.get("section") or "", 160),
|
|
151
|
+
"answer": one_line(raw.get("answer") or "", 1200),
|
|
152
|
+
"diff": diff,
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def load_state(folder: Folder) -> Dict[str, Any]:
|
|
157
|
+
raw = folder.json(STATE)
|
|
158
|
+
raw = raw if isinstance(raw, dict) else {}
|
|
159
|
+
history = []
|
|
160
|
+
for h in raw.get("history") if isinstance(raw.get("history"), list) else []:
|
|
161
|
+
if isinstance(h, dict) and isinstance(h.get("index"), int) and isinstance(h.get("version"), int):
|
|
162
|
+
history.append({"index": h["index"], "version": h["version"], "section": one_line(h.get("section") or "", 160), "answer": one_line(h.get("answer") or "", 1200)})
|
|
163
|
+
suggestions: Dict[str, Dict[str, str]] = {}
|
|
164
|
+
for k, v in (raw.get("suggestions") if isinstance(raw.get("suggestions"), dict) else {}).items():
|
|
165
|
+
if isinstance(k, str) and k.isdigit() and isinstance(v, dict) and isinstance(v.get("text"), str):
|
|
166
|
+
suggestions[k] = {"text": str(v["text"])[:2000], "rationale": one_line(v.get("rationale") or "", 800)}
|
|
167
|
+
return {
|
|
168
|
+
"items": clean_items(raw.get("items")),
|
|
169
|
+
"suggestions": dict(list(suggestions.items())[:MAX_ITEMS]),
|
|
170
|
+
"proposal": clean_proposal(raw.get("proposal")),
|
|
171
|
+
"history": history[-50:],
|
|
172
|
+
"score_before": raw.get("score_before") if isinstance(raw.get("score_before"), int) else None,
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def save_state(folder: Folder, state: Dict[str, Any]) -> None:
|
|
177
|
+
folder.write_json(STATE, state)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def doc_name(folder: Folder) -> str:
|
|
181
|
+
return BRD if folder.read(BRD) is not None else SPEC
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def clean_quality(raw: Any) -> Dict[str, Any]:
|
|
185
|
+
raw = raw if isinstance(raw, dict) else {}
|
|
186
|
+
dims = raw.get("dimensions") if isinstance(raw.get("dimensions"), dict) else {}
|
|
187
|
+
|
|
188
|
+
def pct(v: Any) -> Optional[int]:
|
|
189
|
+
return int(v) if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v <= 100 else None
|
|
190
|
+
|
|
191
|
+
return {
|
|
192
|
+
"overall": pct(raw.get("overall_score")),
|
|
193
|
+
"dimensions": [{"key": k, "label": label, "score": pct(dims.get(k))} for k, label in DIMENSIONS],
|
|
194
|
+
"rationale": one_line(raw.get("rationale") or "", 1200),
|
|
195
|
+
"gaps": [one_line(g, 600) for g in (raw.get("top_gaps") if isinstance(raw.get("top_gaps"), list) else []) if isinstance(g, str)][:MAX_ITEMS],
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def request_of(folder: Folder) -> Dict[str, Any]:
|
|
200
|
+
raw = folder.json(REQUEST)
|
|
201
|
+
raw = raw if isinstance(raw, dict) else {}
|
|
202
|
+
personas = []
|
|
203
|
+
for p in raw.get("personas") if isinstance(raw.get("personas"), list) else []:
|
|
204
|
+
if isinstance(p, dict) and isinstance(p.get("id"), str):
|
|
205
|
+
personas.append({k: one_line(p.get(k) or "", 120) for k in ("id", "name", "role")})
|
|
206
|
+
return {
|
|
207
|
+
"title": one_line(raw.get("title") or "", 300),
|
|
208
|
+
"design": str(raw.get("design") or "")[:MAX_DESIGN],
|
|
209
|
+
"personas": personas,
|
|
210
|
+
"created": one_line(raw.get("created") or "", 40),
|
|
211
|
+
"context": raw.get("context") if isinstance(raw.get("context"), dict) else None,
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
# --- the agent ------------------------------------------------------------------------------------------------------
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
LLM_KEYS = ("provider", "model", "deployment", "endpoint", "api_key", "api_key_env", "api_version", "temperature", "auth", "managed_identity_client_id")
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def host_profile(raw: Any) -> Optional[Dict[str, Any]]:
|
|
222
|
+
"""The model profile a host hands over on stdin (ForgeQE's own, so the review runs on its model): known keys only."""
|
|
223
|
+
if not isinstance(raw, dict) or not isinstance(raw.get("provider"), str) or not isinstance(raw.get("model"), str):
|
|
224
|
+
return None
|
|
225
|
+
out = {k: raw[k] for k in LLM_KEYS if isinstance(raw.get(k), (str, int, float)) and not isinstance(raw.get(k), bool)}
|
|
226
|
+
return {k: (one_line(v, 300) if isinstance(v, str) else v) for k, v in out.items()}
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def build_agent(args: Dict[str, Any], given: Any = None):
|
|
230
|
+
from requirements_agent.agent import RequirementsAgent
|
|
231
|
+
from requirements_agent.config import load_config, parse_config, select_profile
|
|
232
|
+
from requirements_agent.llm.router import build_llm_client
|
|
233
|
+
|
|
234
|
+
profile = host_profile(args.get("llm"))
|
|
235
|
+
if profile:
|
|
236
|
+
cfg = parse_config(load_config_raw(), llms_data={"default": "forgeqe", "models": {"forgeqe": profile}}, profile_name="forgeqe")
|
|
237
|
+
else:
|
|
238
|
+
cfg = load_config(None, llms_json=Path(args["llms"]) if args.get("llms") else None)
|
|
239
|
+
if args.get("profile"):
|
|
240
|
+
try:
|
|
241
|
+
cfg = select_profile(cfg, args["profile"])
|
|
242
|
+
except KeyError as e:
|
|
243
|
+
raise OpError(str(e).strip("'\"")) from e
|
|
244
|
+
try:
|
|
245
|
+
return RequirementsAgent(cfg, build_llm_client(cfg.llm), given=given)
|
|
246
|
+
except ValueError as e:
|
|
247
|
+
raise OpError(str(e)) from e
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def load_config_raw() -> Dict[str, Any]:
|
|
251
|
+
"""With a host's model, the host also finds the context: of the config files only the prompts are kept. A
|
|
252
|
+
repository's requirements-agent.yaml never picks a search command, a folder to read or a pack for it."""
|
|
253
|
+
from requirements_agent.config import load_raw_config
|
|
254
|
+
|
|
255
|
+
prompts = load_raw_config(None).get("prompts")
|
|
256
|
+
return {"prompts": prompts} if isinstance(prompts, dict) else {}
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def progress_to(emit: Emit) -> Callable[[Dict[str, Any]], None]:
|
|
260
|
+
"""The pipeline's progress as plain events: no streamed text, no objects."""
|
|
261
|
+
|
|
262
|
+
def on(ev: Dict[str, Any]) -> None:
|
|
263
|
+
kind = ev.get("type")
|
|
264
|
+
if kind == "stream":
|
|
265
|
+
return
|
|
266
|
+
if kind == "segment":
|
|
267
|
+
sec = ev.get("section")
|
|
268
|
+
emit({"type": "segment", "heading": getattr(sec, "heading", "")})
|
|
269
|
+
return
|
|
270
|
+
if kind == "done":
|
|
271
|
+
return
|
|
272
|
+
if kind == "context":
|
|
273
|
+
ctx = ev.get("context") or {}
|
|
274
|
+
emit({"type": "context", "by_provider": ctx.get("by_provider") or {}, "personas": ctx.get("personas") or [], "excerpts": ctx.get("excerpts_injected", 0)})
|
|
275
|
+
return
|
|
276
|
+
keep = {k: v for k, v in ev.items() if k in ("type", "phase", "message", "step", "total", "heading", "label", "count") and not is_dataclass(v)}
|
|
277
|
+
if keep.get("type"):
|
|
278
|
+
emit(keep)
|
|
279
|
+
|
|
280
|
+
return on
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def items_from(quality: Dict[str, Any], questions: Any) -> List[Dict[str, Any]]:
|
|
284
|
+
items: List[Dict[str, Any]] = []
|
|
285
|
+
seen = set()
|
|
286
|
+
for g in quality.get("gaps") or []:
|
|
287
|
+
if g.lower() not in seen:
|
|
288
|
+
seen.add(g.lower())
|
|
289
|
+
items.append({"kind": "gap", "text": g, "category": "Gap", "status": "open"})
|
|
290
|
+
cats = questions.get("categories") if isinstance(questions, dict) else []
|
|
291
|
+
for cat in cats if isinstance(cats, list) else []:
|
|
292
|
+
if not isinstance(cat, dict):
|
|
293
|
+
continue
|
|
294
|
+
label = one_line(cat.get("title") or cat.get("id") or "Question", 60)
|
|
295
|
+
for q in cat.get("questions") or []:
|
|
296
|
+
text = one_line(q, 600)
|
|
297
|
+
if text and text.lower() not in seen:
|
|
298
|
+
seen.add(text.lower())
|
|
299
|
+
items.append({"kind": "question", "text": text, "category": label, "status": "open"})
|
|
300
|
+
return clean_items(items)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def diff_lines(before: str, after: str) -> List[Dict[str, str]]:
|
|
304
|
+
out = []
|
|
305
|
+
for line in difflib.ndiff(before.splitlines(), after.splitlines()):
|
|
306
|
+
if line.startswith("? "):
|
|
307
|
+
continue
|
|
308
|
+
out.append({"op": line[0], "text": line[2:]})
|
|
309
|
+
return out[:MAX_DIFF]
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
# --- operations ---------------------------------------------------------------------------------------------------
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def op_review(folder: Folder, req: Dict[str, Any], args: Dict[str, Any], emit: Emit) -> Dict[str, Any]:
|
|
316
|
+
title = one_line(req.get("title"), 300)
|
|
317
|
+
design = req.get("design")
|
|
318
|
+
if not title:
|
|
319
|
+
raise OpError("A review needs a title.")
|
|
320
|
+
if not isinstance(design, str) or len(design.strip()) < 10:
|
|
321
|
+
raise OpError("A review needs the requirement's text (at least 10 characters).")
|
|
322
|
+
if len(design) > MAX_DESIGN:
|
|
323
|
+
raise OpError(f"The requirement is longer than {MAX_DESIGN} characters.")
|
|
324
|
+
given = req.get("context") if isinstance(req.get("context"), dict) else None
|
|
325
|
+
agent = build_agent(args, given)
|
|
326
|
+
for problem in agent.spec.context.problems:
|
|
327
|
+
emit({"type": "warning", "message": one_line(problem, 300)})
|
|
328
|
+
personas = [{"id": p["id"], "name": p["name"], "role": p["role"]} for p in agent.spec.context.personas]
|
|
329
|
+
folder.write_json(REQUEST, {"title": title, "design": design, "personas": personas, "created": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "context": given})
|
|
330
|
+
result = agent.run(title, design, out_dir=folder.root, export_format="md", consolidate=req.get("consolidate") is not False, on_progress=progress_to(emit))
|
|
331
|
+
if not result.get("success"):
|
|
332
|
+
raise OpError(one_line(result.get("error") or "The review failed.", 400))
|
|
333
|
+
quality = clean_quality(result.get("quality"))
|
|
334
|
+
state = {"items": items_from(quality, result.get("questions")), "proposal": None, "history": [], "score_before": quality["overall"]}
|
|
335
|
+
save_state(folder, state)
|
|
336
|
+
for w in result.get("warnings") or []:
|
|
337
|
+
emit({"type": "warning", "message": one_line(w, 300)})
|
|
338
|
+
ReviewMemory(memory_dir(args)).add({"kind": "review", "title": title, "score": quality["overall"] or 0})
|
|
339
|
+
return op_show(folder, {}, args, emit)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def op_show(folder: Folder, req: Dict[str, Any], args: Dict[str, Any], emit: Emit) -> Dict[str, Any]:
|
|
343
|
+
from requirements_agent.pipeline.sections import list_h2_sections
|
|
344
|
+
|
|
345
|
+
state = load_state(folder)
|
|
346
|
+
request = request_of(folder)
|
|
347
|
+
name = doc_name(folder)
|
|
348
|
+
doc = folder.read(name) or ""
|
|
349
|
+
files = [n for n in (SPEC, BRD, "requirements.json", "quality-score.json", "open-questions.json", "01-spec-circuit-report.pdf", "02-requirements-report.pdf") if folder.file(n).is_file()]
|
|
350
|
+
meta = folder.json("run-meta.json")
|
|
351
|
+
meta = meta if isinstance(meta, dict) else {}
|
|
352
|
+
ctx = meta.get("context") if isinstance(meta.get("context"), dict) else {}
|
|
353
|
+
return {
|
|
354
|
+
"title": request["title"],
|
|
355
|
+
"created": request["created"],
|
|
356
|
+
"personas": request["personas"],
|
|
357
|
+
"document": name,
|
|
358
|
+
"sections": [one_line(s.heading, 160) for s in list_h2_sections(doc)],
|
|
359
|
+
"quality": clean_quality(folder.json("quality-score.json")),
|
|
360
|
+
"score_before": state["score_before"],
|
|
361
|
+
"items": state["items"],
|
|
362
|
+
"suggestions": state["suggestions"],
|
|
363
|
+
"decisions": decisions_of(state),
|
|
364
|
+
"reviewers": reviewers_of(folder),
|
|
365
|
+
"proposal": state["proposal"],
|
|
366
|
+
"can_undo": bool(state["history"]),
|
|
367
|
+
"files": files,
|
|
368
|
+
"context": {
|
|
369
|
+
"by_provider": {one_line(k, 40): v for k, v in (ctx.get("by_provider") or {}).items() if isinstance(v, int)},
|
|
370
|
+
"excerpts": ctx.get("excerpts_injected") if isinstance(ctx.get("excerpts_injected"), int) else 0,
|
|
371
|
+
},
|
|
372
|
+
"status": one_line(meta.get("status") or "", 40),
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def reviewers_of(folder: Folder) -> List[Dict[str, str]]:
|
|
377
|
+
"""Who reviewed, in order: each section the review wrote (sections/NN-<who>.md), by its heading."""
|
|
378
|
+
out: List[Dict[str, str]] = []
|
|
379
|
+
d = folder.root / "sections"
|
|
380
|
+
if d.is_symlink() or not d.is_dir():
|
|
381
|
+
return out
|
|
382
|
+
for f in sorted(d.iterdir())[:30]:
|
|
383
|
+
if f.is_symlink() or not f.is_file() or f.suffix != ".md" or not re.match(r"^\d{2}-[\w-]{1,60}\.md$", f.name):
|
|
384
|
+
continue
|
|
385
|
+
try:
|
|
386
|
+
first = f.read_text(encoding="utf-8", errors="replace")[:400].lstrip().splitlines()[:1]
|
|
387
|
+
except OSError:
|
|
388
|
+
continue
|
|
389
|
+
heading = one_line(re.sub(r"^#+\s*", "", first[0]) if first else "", 120)
|
|
390
|
+
out.append({"id": one_line(f.stem[3:], 60), "heading": heading or one_line(f.stem[3:], 60), "persona": "true" if f.stem[3:].startswith("persona-") else ""})
|
|
391
|
+
return out
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def decisions_of(state: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
395
|
+
"""The changes kept, oldest first: which item, in which section, and the person's answer."""
|
|
396
|
+
items = {i["index"]: i for i in state["items"]}
|
|
397
|
+
return [
|
|
398
|
+
{"index": h["index"], "text": items[h["index"]]["text"] if h["index"] in items else "", "section": h["section"], "answer": h["answer"]}
|
|
399
|
+
for h in state["history"]
|
|
400
|
+
if h["index"] in items
|
|
401
|
+
]
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def op_suggest(folder: Folder, req: Dict[str, Any], args: Dict[str, Any], emit: Emit) -> Dict[str, Any]:
|
|
405
|
+
state = load_state(folder)
|
|
406
|
+
index = req.get("index")
|
|
407
|
+
item = next((i for i in state["items"] if i["index"] == index), None) if isinstance(index, int) else None
|
|
408
|
+
if not item:
|
|
409
|
+
raise OpError(f"No gap or question {one_line(index, 20)}.")
|
|
410
|
+
request = request_of(folder)
|
|
411
|
+
doc = folder.read(doc_name(folder))
|
|
412
|
+
if not doc:
|
|
413
|
+
raise OpError("The review has no report yet.")
|
|
414
|
+
agent = build_agent(args, request["context"])
|
|
415
|
+
emit({"type": "phase", "phase": "refine", "message": f"Suggesting an answer for item {item['index']}"})
|
|
416
|
+
out = agent.resolve(request["title"], request["design"], doc, item["text"])
|
|
417
|
+
if not out.get("success") or not str(out.get("suggestion") or "").strip():
|
|
418
|
+
raise OpError(one_line(out.get("error") or "No answer could be suggested.", 400))
|
|
419
|
+
state["suggestions"][str(item["index"])] = {"text": str(out["suggestion"]).strip()[:2000], "rationale": one_line(out.get("rationale") or "", 800)}
|
|
420
|
+
save_state(folder, state)
|
|
421
|
+
return op_show(folder, {}, args, emit)
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def op_consolidate(folder: Folder, req: Dict[str, Any], args: Dict[str, Any], emit: Emit) -> Dict[str, Any]:
|
|
425
|
+
from requirements_agent.export.requirements_json import write_requirements_json
|
|
426
|
+
|
|
427
|
+
state = load_state(folder)
|
|
428
|
+
spec = folder.read(SPEC)
|
|
429
|
+
if not spec:
|
|
430
|
+
raise OpError("The review has no Spec Circuit report yet.")
|
|
431
|
+
request = request_of(folder)
|
|
432
|
+
decided = [d for d in decisions_of(state) if d["text"]]
|
|
433
|
+
draft = spec
|
|
434
|
+
if decided:
|
|
435
|
+
draft += "\n\n## Decisions taken in refinement\n\n" + "\n".join(
|
|
436
|
+
f"- {d['text']} → {d['answer'] or 'resolved in ' + d['section']}" for d in decided
|
|
437
|
+
)
|
|
438
|
+
current = folder.read(BRD)
|
|
439
|
+
if current and current.strip():
|
|
440
|
+
draft += "\n\n## Current requirements report (keep its accepted changes)\n\n" + current
|
|
441
|
+
agent = build_agent(args, request["context"])
|
|
442
|
+
emit({"type": "phase", "phase": "consolidate", "message": "Writing the requirements report (BRD)"})
|
|
443
|
+
out = agent.consolidate(request["title"], request["design"], draft, on_progress=progress_to(emit))
|
|
444
|
+
if not out.get("success"):
|
|
445
|
+
raise OpError(one_line(out.get("error") or "The requirements report could not be written.", 400))
|
|
446
|
+
if current:
|
|
447
|
+
version = (max((h["version"] for h in state["history"]), default=0)) + 1
|
|
448
|
+
folder.write(f"{VERSIONS}/{version:03d}.md", current)
|
|
449
|
+
state["history"].append({"index": 0, "version": version, "section": "Whole report (written again)", "answer": ""})
|
|
450
|
+
save_state(folder, state)
|
|
451
|
+
folder.write(BRD, out["report_markdown"])
|
|
452
|
+
write_requirements_json(folder.file(BRD), out["report_markdown"])
|
|
453
|
+
return op_show(folder, {}, args, emit)
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def op_fix(folder: Folder, req: Dict[str, Any], args: Dict[str, Any], emit: Emit) -> Dict[str, Any]:
|
|
457
|
+
from requirements_agent.pipeline.sections import resolve_section, section_slice
|
|
458
|
+
from requirements_agent.shell.actions import FixItem, build_fix_instruction, map_item_to_section
|
|
459
|
+
|
|
460
|
+
state = load_state(folder)
|
|
461
|
+
index = req.get("index")
|
|
462
|
+
item = next((i for i in state["items"] if i["index"] == index), None) if isinstance(index, int) else None
|
|
463
|
+
if not item:
|
|
464
|
+
raise OpError(f"No gap or question {one_line(index, 20)}.")
|
|
465
|
+
answer = one_line(req.get("answer") or "", 1200)
|
|
466
|
+
request = request_of(folder)
|
|
467
|
+
name = doc_name(folder)
|
|
468
|
+
doc = folder.read(name)
|
|
469
|
+
if not doc:
|
|
470
|
+
raise OpError("The review has no report yet.")
|
|
471
|
+
section = map_item_to_section(doc, item["text"])
|
|
472
|
+
instruction = build_fix_instruction(FixItem(index=item["index"], kind=item["kind"], text=item["text"], category=item["category"]), answer)
|
|
473
|
+
agent = build_agent(args, request["context"])
|
|
474
|
+
emit({"type": "phase", "phase": "refine", "message": f"Proposing a change for item {item['index']}"})
|
|
475
|
+
out = agent.refine(request["title"], request["design"], doc, instruction, section=section, on_progress=progress_to(emit))
|
|
476
|
+
if not out.get("success"):
|
|
477
|
+
raise OpError(one_line(out.get("error") or "The change could not be made.", 400))
|
|
478
|
+
new_doc = out["report_markdown"]
|
|
479
|
+
heading = (out.get("section") or {}).get("heading") or "Whole document"
|
|
480
|
+
if section:
|
|
481
|
+
before_sec, _ = resolve_section(doc, section)
|
|
482
|
+
after_sec, _ = resolve_section(new_doc, section)
|
|
483
|
+
before = section_slice(doc, before_sec) if before_sec else doc
|
|
484
|
+
after = section_slice(new_doc, after_sec) if after_sec else new_doc
|
|
485
|
+
else:
|
|
486
|
+
before, after = doc, new_doc
|
|
487
|
+
folder.write(PROPOSAL, new_doc)
|
|
488
|
+
state["proposal"] = {"index": item["index"], "section": heading, "answer": answer, "diff": diff_lines(before, after)}
|
|
489
|
+
save_state(folder, state)
|
|
490
|
+
return op_show(folder, {}, args, emit)
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def memory_dir(args: Dict[str, Any]) -> Optional[Path]:
|
|
494
|
+
return Path(args["memory"]) if args.get("memory") else None
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def op_accept(folder: Folder, req: Dict[str, Any], args: Dict[str, Any], emit: Emit) -> Dict[str, Any]:
|
|
498
|
+
from requirements_agent.export.requirements_json import write_requirements_json
|
|
499
|
+
|
|
500
|
+
state = load_state(folder)
|
|
501
|
+
prop = state["proposal"]
|
|
502
|
+
new_doc = folder.read(PROPOSAL)
|
|
503
|
+
if not prop or new_doc is None:
|
|
504
|
+
raise OpError("There is no proposed change to accept.")
|
|
505
|
+
name = doc_name(folder)
|
|
506
|
+
old = folder.read(name) or ""
|
|
507
|
+
version = (max((h["version"] for h in state["history"]), default=0)) + 1
|
|
508
|
+
folder.write(f"{VERSIONS}/{version:03d}.md", old)
|
|
509
|
+
folder.write(name, new_doc)
|
|
510
|
+
if name == BRD:
|
|
511
|
+
write_requirements_json(folder.file(BRD), new_doc)
|
|
512
|
+
folder.file(PROPOSAL).unlink(missing_ok=True)
|
|
513
|
+
item = next(i for i in state["items"] if i["index"] == prop["index"])
|
|
514
|
+
item["status"] = "accepted"
|
|
515
|
+
state["history"].append({"index": prop["index"], "version": version, "section": prop["section"], "answer": prop["answer"]})
|
|
516
|
+
state["proposal"] = None
|
|
517
|
+
save_state(folder, state)
|
|
518
|
+
|
|
519
|
+
added = " ".join(d["text"].strip() for d in prop["diff"] if d["op"] == "+" and d["text"].strip())
|
|
520
|
+
decided = prop["answer"] or f"Resolved in {prop['section']}: {added}"
|
|
521
|
+
ReviewMemory(memory_dir(args)).add(
|
|
522
|
+
{"kind": "decision", "title": request_of(folder)["title"], "item": item["text"], "answer": decided, "section": prop["section"], "category": item["category"]}
|
|
523
|
+
)
|
|
524
|
+
if req.get("rescore"):
|
|
525
|
+
request = request_of(folder)
|
|
526
|
+
agent = build_agent(args, request["context"])
|
|
527
|
+
emit({"type": "phase", "phase": "score", "message": "Scoring the changed report"})
|
|
528
|
+
q = agent.score(request["title"], request["design"], new_doc, on_progress=progress_to(emit))
|
|
529
|
+
if q.success:
|
|
530
|
+
old_q = folder.json("quality-score.json")
|
|
531
|
+
folder.write_json(
|
|
532
|
+
"quality-score.json",
|
|
533
|
+
{"overall_score": q.overall_score, "dimensions": q.dimensions, "rationale": q.rationale, "top_gaps": (old_q or {}).get("top_gaps", []) if isinstance(old_q, dict) else [], "success": True, "error": None},
|
|
534
|
+
)
|
|
535
|
+
return op_show(folder, {}, args, emit)
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def op_skip(folder: Folder, req: Dict[str, Any], args: Dict[str, Any], emit: Emit) -> Dict[str, Any]:
|
|
539
|
+
state = load_state(folder)
|
|
540
|
+
index = req.get("index")
|
|
541
|
+
item = next((i for i in state["items"] if i["index"] == index), None) if isinstance(index, int) else None
|
|
542
|
+
if not item:
|
|
543
|
+
raise OpError(f"No gap or question {one_line(index, 20)}.")
|
|
544
|
+
item["status"] = "skipped"
|
|
545
|
+
if state["proposal"] and state["proposal"]["index"] == index:
|
|
546
|
+
state["proposal"] = None
|
|
547
|
+
folder.file(PROPOSAL).unlink(missing_ok=True)
|
|
548
|
+
save_state(folder, state)
|
|
549
|
+
return op_show(folder, {}, args, emit)
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def op_undo(folder: Folder, req: Dict[str, Any], args: Dict[str, Any], emit: Emit) -> Dict[str, Any]:
|
|
553
|
+
from requirements_agent.export.requirements_json import write_requirements_json
|
|
554
|
+
|
|
555
|
+
state = load_state(folder)
|
|
556
|
+
if not state["history"]:
|
|
557
|
+
raise OpError("Nothing to undo.")
|
|
558
|
+
last = state["history"].pop()
|
|
559
|
+
old = folder.read(f"{VERSIONS}/{last['version']:03d}.md")
|
|
560
|
+
if old is None:
|
|
561
|
+
raise OpError("The earlier version is not there.")
|
|
562
|
+
name = doc_name(folder)
|
|
563
|
+
folder.write(name, old)
|
|
564
|
+
if name == BRD:
|
|
565
|
+
write_requirements_json(folder.file(BRD), old)
|
|
566
|
+
for i in state["items"]:
|
|
567
|
+
if i["index"] == last["index"]:
|
|
568
|
+
i["status"] = "open"
|
|
569
|
+
save_state(folder, state)
|
|
570
|
+
return op_show(folder, {}, args, emit)
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def op_export(folder: Folder, req: Dict[str, Any], args: Dict[str, Any], emit: Emit) -> Dict[str, Any]:
|
|
574
|
+
from requirements_agent.export.pdf import export_pdf
|
|
575
|
+
|
|
576
|
+
if req.get("format") != "pdf":
|
|
577
|
+
raise OpError("Export is pdf; the Markdown is already in the review's folder.")
|
|
578
|
+
name = doc_name(folder)
|
|
579
|
+
doc = folder.read(name)
|
|
580
|
+
if not doc:
|
|
581
|
+
raise OpError("The review has no report yet.")
|
|
582
|
+
target = folder.file(name.replace(".md", ".pdf"))
|
|
583
|
+
try:
|
|
584
|
+
export_pdf(doc, target, title=request_of(folder)["title"])
|
|
585
|
+
except Exception as e:
|
|
586
|
+
raise OpError(f"The PDF could not be written: {one_line(e, 200)}") from e
|
|
587
|
+
return op_show(folder, {}, args, emit)
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
HANDLERS = {
|
|
591
|
+
"review": op_review,
|
|
592
|
+
"show": op_show,
|
|
593
|
+
"fix": op_fix,
|
|
594
|
+
"accept": op_accept,
|
|
595
|
+
"skip": op_skip,
|
|
596
|
+
"undo": op_undo,
|
|
597
|
+
"export": op_export,
|
|
598
|
+
"suggest": op_suggest,
|
|
599
|
+
"consolidate": op_consolidate,
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def run(op: str, folder_path: Path, args: Dict[str, Any], stdin_text: str) -> int:
|
|
604
|
+
"""Runs one operation; 0 when it ended with a result, 1 with an error. Never raises."""
|
|
605
|
+
try:
|
|
606
|
+
if op not in OPS:
|
|
607
|
+
raise OpError(f"Unknown operation: {one_line(op, 20)}. Operations: {', '.join(OPS)}.")
|
|
608
|
+
if len(stdin_text) > MAX_STDIN:
|
|
609
|
+
raise OpError("The request is too large.")
|
|
610
|
+
try:
|
|
611
|
+
req = json.loads(stdin_text) if stdin_text.strip() else {}
|
|
612
|
+
except ValueError as e:
|
|
613
|
+
raise OpError("The request is not JSON.") from e
|
|
614
|
+
if not isinstance(req, dict):
|
|
615
|
+
raise OpError("The request is a JSON object.")
|
|
616
|
+
folder = Folder(folder_path, create=op == "review")
|
|
617
|
+
# The model is the host's, for this operation only: never written to the folder.
|
|
618
|
+
args = {**args, "llm": req.pop("llm", None)}
|
|
619
|
+
result = HANDLERS[op](folder, req, args, out_line)
|
|
620
|
+
out_line({"type": "result", "op": op, "review": result})
|
|
621
|
+
return 0
|
|
622
|
+
except OpError as e:
|
|
623
|
+
out_line({"type": "error", "message": str(e)})
|
|
624
|
+
return 1
|
|
625
|
+
except Exception as e: # anything else is reported in a line, never a traceback with the request in it
|
|
626
|
+
out_line({"type": "error", "message": f"{type(e).__name__}: {one_line(e, 300)}"})
|
|
627
|
+
return 1
|