specadia 0.2.7__py3-none-any.whl
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.
- specadia/__init__.py +3 -0
- specadia/_agents/__init__.py +22 -0
- specadia/_agents/agent_base.py +58 -0
- specadia/_agents/agent_callbacks.py +123 -0
- specadia/_agents/agent_util.py +170 -0
- specadia/_agents/local_providers.py +44 -0
- specadia/_agents/model_base.py +15 -0
- specadia/_agents/prompt_safety.py +9 -0
- specadia/_constants.py +3 -0
- specadia/_contracts/__init__.py +7 -0
- specadia/_contracts/cli.py +352 -0
- specadia/_contracts/context.py +120 -0
- specadia/_contracts/generator.py +190 -0
- specadia/_contracts/models.py +50 -0
- specadia/_contracts/prompt_safety.py +56 -0
- specadia/_contracts/requirement_ids.py +16 -0
- specadia/_contracts/session_store.py +100 -0
- specadia/_contracts/specadia_pipeline.py +238 -0
- specadia/_contracts/traceability.py +118 -0
- specadia/_contracts/validation.py +166 -0
- specadia/_contracts/workflow.py +409 -0
- specadia/_contracts/writer.py +49 -0
- specadia/_design/__init__.py +7 -0
- specadia/_design/design_agent/__init__.py +5 -0
- specadia/_design/design_agent/design_wrapper.py +43 -0
- specadia/_design/designer/__init__.py +6 -0
- specadia/_design/designer/designer_agent.py +61 -0
- specadia/_design/designer/designer_models.py +21 -0
- specadia/_design/documenter/__init__.py +5 -0
- specadia/_design/documenter/documenter_agent.py +51 -0
- specadia/_diagnostics/__init__.py +7 -0
- specadia/_diagnostics/doctor.py +221 -0
- specadia/_orchestrator/__init__.py +23 -0
- specadia/_orchestrator/constants.py +4 -0
- specadia/_orchestrator/orchestrator.py +326 -0
- specadia/_orchestrator/plugins.py +59 -0
- specadia/_orchestrator/read_wrapper.py +88 -0
- specadia/_orchestrator/session_manager.py +57 -0
- specadia/_prompt_templates/__init__.py +21 -0
- specadia/_prompt_templates/analyzer_prompt.py +36 -0
- specadia/_prompt_templates/collector_prompt.py +48 -0
- specadia/_prompt_templates/design_prompt.py +17 -0
- specadia/_prompt_templates/designer_prompt.py +46 -0
- specadia/_prompt_templates/documenter_prompt.py +16 -0
- specadia/_prompt_templates/kb/design_kb.py +60 -0
- specadia/_prompt_templates/kb/requirements_kb.py +40 -0
- specadia/_prompt_templates/re_prompt.py +10 -0
- specadia/_prompt_templates/single_prompt.py +121 -0
- specadia/_prompt_templates/specifier_prompt.py +32 -0
- specadia/_prompt_templates/templates/design_template.py +25 -0
- specadia/_prompt_templates/templates/srs_template.py +83 -0
- specadia/_rag/__init__.py +1 -0
- specadia/_rag/cli.py +146 -0
- specadia/_rag/knowledge_base.py +570 -0
- specadia/_requirement/__init__.py +8 -0
- specadia/_requirement/analyzer/__init__.py +14 -0
- specadia/_requirement/analyzer/analyzer_agent.py +55 -0
- specadia/_requirement/analyzer/analyzer_models.py +30 -0
- specadia/_requirement/collector/__init__.py +14 -0
- specadia/_requirement/collector/collector_agent.py +74 -0
- specadia/_requirement/collector/collector_models.py +11 -0
- specadia/_requirement/re_agent/__init__.py +7 -0
- specadia/_requirement/re_agent/requirements_wrapper.py +57 -0
- specadia/_requirement/specifier/__init__.py +5 -0
- specadia/_requirement/specifier/specifier_agent.py +52 -0
- specadia/_requirement/specifier/specifier_models.py +23 -0
- specadia/_single/__init__.py +5 -0
- specadia/_single/single_agent.py +58 -0
- specadia/_tools/__init__.py +5 -0
- specadia/_tools/constants.py +13 -0
- specadia/_tools/save_to_file_tool.py +59 -0
- specadia/_utils/__init__.py +7 -0
- specadia/_utils/constants.py +40 -0
- specadia/_utils/logger.py +47 -0
- specadia/cli.py +28 -0
- specadia/contracts/__init__.py +22 -0
- specadia/contracts/cli.py +8 -0
- specadia/diagnostics/__init__.py +1 -0
- specadia/diagnostics/doctor.py +5 -0
- specadia/providers.py +61 -0
- specadia-0.2.7.dist-info/METADATA +264 -0
- specadia-0.2.7.dist-info/RECORD +86 -0
- specadia-0.2.7.dist-info/WHEEL +5 -0
- specadia-0.2.7.dist-info/entry_points.txt +4 -0
- specadia-0.2.7.dist-info/licenses/LICENSE +201 -0
- specadia-0.2.7.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Deterministic quality checks for generated SRS and design documents."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
from .requirement_ids import normalize_requirement_id
|
|
7
|
+
|
|
8
|
+
_REQ_ID = re.compile(
|
|
9
|
+
r"(?<![A-Za-z0-9])(?:FR|NFR|REQ|AC)[-_ ]?\d+(?![A-Za-z0-9])",
|
|
10
|
+
re.IGNORECASE,
|
|
11
|
+
)
|
|
12
|
+
_DEFINITION = re.compile(
|
|
13
|
+
r"^\s*(?:[-*+]\s*)?"
|
|
14
|
+
r"(?P<markup>\*\*|__|\*|_|`)?"
|
|
15
|
+
r"(?P<id>(?:FR|NFR|REQ|AC)[-_ ]?\d+)"
|
|
16
|
+
r"(?(markup)(?P=markup)[ \t]*(?:[:.)-]|\Z)|[ \t]*[:.)-])",
|
|
17
|
+
re.IGNORECASE,
|
|
18
|
+
)
|
|
19
|
+
_LABELED_DEFINITION = re.compile(
|
|
20
|
+
r"^\s*(?:[-*+]\s*)?"
|
|
21
|
+
r"(?:\*\*|__|\*|_|`)?ID[ \t]*:[ \t]*(?:\*\*|__|\*|_|`)?[ \t]*"
|
|
22
|
+
r"(?P<id>(?:FR|NFR|REQ|AC)[-_ ]?\d+)",
|
|
23
|
+
re.IGNORECASE,
|
|
24
|
+
)
|
|
25
|
+
_PLACEHOLDER = re.compile(
|
|
26
|
+
r"\[(?:todo|tbd|project name|insert|placeholder)[^\]]*\]|\b(?:TODO|TBD)\b",
|
|
27
|
+
re.IGNORECASE,
|
|
28
|
+
)
|
|
29
|
+
_NAMED_TECHNOLOGY = re.compile(
|
|
30
|
+
r"\b(?:"
|
|
31
|
+
r"FastAPI|Kafka|RabbitMQ|Kubernetes|Terraform|Helm|Pinecone|Milvus|"
|
|
32
|
+
r"PostgreSQL|Redis|GraphQL|gRPC|Avro|ITAR|IAEA|COPUOS|"
|
|
33
|
+
r"Prometheus|Grafana|AES-?\d*|TLS(?:\s+\d(?:\.\d)?)?|OIDC|JWT"
|
|
34
|
+
r")\b",
|
|
35
|
+
re.IGNORECASE,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class QualityIssue:
|
|
41
|
+
code: str
|
|
42
|
+
message: str
|
|
43
|
+
document: str
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class QualityReport:
|
|
48
|
+
issues: list[QualityIssue]
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def ok(self) -> bool:
|
|
52
|
+
return not self.issues
|
|
53
|
+
|
|
54
|
+
def require_valid(self) -> None:
|
|
55
|
+
if self.issues:
|
|
56
|
+
details = "; ".join(
|
|
57
|
+
f"{issue.document}:{issue.code}: {issue.message}" for issue in self.issues
|
|
58
|
+
)
|
|
59
|
+
raise ValueError(f"Generated document quality gate failed: {details}")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def validate_documents(srs: str, design: str) -> QualityReport:
|
|
63
|
+
"""Validate release-critical document structure and requirement identity."""
|
|
64
|
+
issues: list[QualityIssue] = []
|
|
65
|
+
_nonempty("srs", srs, issues)
|
|
66
|
+
_nonempty("design", design, issues)
|
|
67
|
+
srs_ids: set[str] = set()
|
|
68
|
+
if srs.strip():
|
|
69
|
+
_heading("srs", srs, ("requirement", "functional"), "requirements-section", issues)
|
|
70
|
+
direct_ids = [
|
|
71
|
+
normalize_requirement_id(match.group("id"))
|
|
72
|
+
for line in srs.splitlines()
|
|
73
|
+
if (match := _DEFINITION.match(line))
|
|
74
|
+
]
|
|
75
|
+
labeled_ids = [
|
|
76
|
+
normalize_requirement_id(match.group("id"))
|
|
77
|
+
for line in srs.splitlines()
|
|
78
|
+
if (match := _LABELED_DEFINITION.match(line))
|
|
79
|
+
]
|
|
80
|
+
# A field-style ``ID: FR-1`` directly beneath an ``FR-1`` heading is
|
|
81
|
+
# metadata for that same definition, not a second definition.
|
|
82
|
+
ids = direct_ids + [
|
|
83
|
+
requirement_id for requirement_id in labeled_ids if requirement_id not in direct_ids
|
|
84
|
+
]
|
|
85
|
+
if not ids:
|
|
86
|
+
issues.append(
|
|
87
|
+
QualityIssue("missing-requirement-ids", "No stable requirement IDs found", "srs")
|
|
88
|
+
)
|
|
89
|
+
duplicates = sorted({value for value in ids if ids.count(value) > 1})
|
|
90
|
+
if duplicates:
|
|
91
|
+
issues.append(
|
|
92
|
+
QualityIssue(
|
|
93
|
+
"duplicate-requirement-ids",
|
|
94
|
+
f"Requirement IDs occur more than once: {', '.join(duplicates)}",
|
|
95
|
+
"srs",
|
|
96
|
+
)
|
|
97
|
+
)
|
|
98
|
+
srs_ids = {normalize_requirement_id(value) for value in _REQ_ID.findall(srs)}
|
|
99
|
+
if design.strip():
|
|
100
|
+
_heading("design", design, ("architecture", "design"), "architecture-section", issues)
|
|
101
|
+
design_ids = {normalize_requirement_id(value) for value in _REQ_ID.findall(design)}
|
|
102
|
+
missing = sorted(srs_ids - design_ids)
|
|
103
|
+
if missing:
|
|
104
|
+
issues.append(
|
|
105
|
+
QualityIssue(
|
|
106
|
+
"missing-design-requirement-ids",
|
|
107
|
+
f"Design omits stable requirement IDs: {', '.join(missing)}",
|
|
108
|
+
"design",
|
|
109
|
+
)
|
|
110
|
+
)
|
|
111
|
+
unexpected = sorted(design_ids - srs_ids)
|
|
112
|
+
if unexpected:
|
|
113
|
+
issues.append(
|
|
114
|
+
QualityIssue(
|
|
115
|
+
"unexpected-design-requirement-ids",
|
|
116
|
+
f"Design introduces requirement IDs absent from the SRS: {', '.join(unexpected)}",
|
|
117
|
+
"design",
|
|
118
|
+
)
|
|
119
|
+
)
|
|
120
|
+
unsupported = sorted(
|
|
121
|
+
{
|
|
122
|
+
match.group(0)
|
|
123
|
+
for match in _NAMED_TECHNOLOGY.finditer(design)
|
|
124
|
+
if not re.search(rf"\b{re.escape(match.group(0))}\b", srs, re.IGNORECASE)
|
|
125
|
+
},
|
|
126
|
+
key=str.casefold,
|
|
127
|
+
)
|
|
128
|
+
if unsupported:
|
|
129
|
+
issues.append(
|
|
130
|
+
QualityIssue(
|
|
131
|
+
"unsupported-named-technology",
|
|
132
|
+
"Design introduces named technologies or regulations absent from the SRS: "
|
|
133
|
+
+ ", ".join(unsupported),
|
|
134
|
+
"design",
|
|
135
|
+
)
|
|
136
|
+
)
|
|
137
|
+
for name, content in (("srs", srs), ("design", design)):
|
|
138
|
+
placeholders = sorted(set(match.group(0) for match in _PLACEHOLDER.finditer(content)))
|
|
139
|
+
if placeholders:
|
|
140
|
+
issues.append(
|
|
141
|
+
QualityIssue(
|
|
142
|
+
"unresolved-placeholders",
|
|
143
|
+
f"Unresolved placeholders: {', '.join(placeholders)}",
|
|
144
|
+
name,
|
|
145
|
+
)
|
|
146
|
+
)
|
|
147
|
+
return QualityReport(issues)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _nonempty(name: str, content: str, issues: list[QualityIssue]) -> None:
|
|
151
|
+
if len(content.strip()) < 40:
|
|
152
|
+
issues.append(QualityIssue("empty-or-short", "Document is empty or too short", name))
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _heading(
|
|
156
|
+
name: str,
|
|
157
|
+
content: str,
|
|
158
|
+
terms: tuple[str, ...],
|
|
159
|
+
code: str,
|
|
160
|
+
issues: list[QualityIssue],
|
|
161
|
+
) -> None:
|
|
162
|
+
headings = [
|
|
163
|
+
line.lstrip("#").strip().lower() for line in content.splitlines() if line.startswith("#")
|
|
164
|
+
]
|
|
165
|
+
if not any(any(term in heading for term in terms) for heading in headings):
|
|
166
|
+
issues.append(QualityIssue(code, f"Missing heading containing one of: {terms}", name))
|
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
"""Human-approved Specadia pipeline for contract generation."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import inspect
|
|
5
|
+
import uuid
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from enum import StrEnum
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Awaitable
|
|
10
|
+
from typing import Callable
|
|
11
|
+
from typing import Protocol
|
|
12
|
+
|
|
13
|
+
from .generator import ContractGenerator
|
|
14
|
+
from .models import ContractBundle
|
|
15
|
+
from .models import Harness
|
|
16
|
+
from .session_store import RunCheckpoint
|
|
17
|
+
from .session_store import SessionStore
|
|
18
|
+
from .traceability import build_traceability
|
|
19
|
+
from .traceability import write_traceability
|
|
20
|
+
from .validation import validate_documents
|
|
21
|
+
from .validation import QualityReport
|
|
22
|
+
from .writer import write_bundles
|
|
23
|
+
|
|
24
|
+
CollectorDraft = dict[str, object]
|
|
25
|
+
CollectDraft = Callable[
|
|
26
|
+
[str, CollectorDraft | None, str | None],
|
|
27
|
+
Awaitable[CollectorDraft],
|
|
28
|
+
]
|
|
29
|
+
GenerateDocuments = Callable[
|
|
30
|
+
[str, CollectorDraft],
|
|
31
|
+
Awaitable["GeneratedDocuments"],
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ApprovalAction(StrEnum):
|
|
36
|
+
"""Available human decisions for a Collector draft."""
|
|
37
|
+
|
|
38
|
+
APPROVE = "approve"
|
|
39
|
+
REFINE = "refine"
|
|
40
|
+
CANCEL = "cancel"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class ApprovalDecision:
|
|
45
|
+
"""A human decision about a Collector draft."""
|
|
46
|
+
|
|
47
|
+
action: ApprovalAction
|
|
48
|
+
feedback: str | None = None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class GeneratedDocuments:
|
|
53
|
+
"""Documents produced after the Collector draft is approved."""
|
|
54
|
+
|
|
55
|
+
srs: str
|
|
56
|
+
design: str
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True)
|
|
60
|
+
class WorkflowResult:
|
|
61
|
+
"""Outputs from a completed intent-to-contract workflow."""
|
|
62
|
+
|
|
63
|
+
approved_draft: CollectorDraft
|
|
64
|
+
documents: GeneratedDocuments
|
|
65
|
+
written_paths: list[Path]
|
|
66
|
+
refinement_count: int
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class ApprovalGate(Protocol):
|
|
70
|
+
"""Review a Collector draft without coupling the workflow to a UI."""
|
|
71
|
+
|
|
72
|
+
def review(
|
|
73
|
+
self, draft: CollectorDraft, attempt: int
|
|
74
|
+
) -> ApprovalDecision | Awaitable[ApprovalDecision]:
|
|
75
|
+
"""Return approve, refine, or cancel."""
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class WorkflowCancelled(RuntimeError):
|
|
79
|
+
"""Raised when a human cancels before downstream generation."""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class PartialDocumentsError(RuntimeError):
|
|
83
|
+
"""A later document stage failed after producing a valid SRS."""
|
|
84
|
+
|
|
85
|
+
def __init__(self, message: str, *, srs: str):
|
|
86
|
+
super().__init__(message)
|
|
87
|
+
self.srs = srs
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class ContractWorkflow:
|
|
91
|
+
"""Run Collector refinement before any downstream Specadia agents."""
|
|
92
|
+
|
|
93
|
+
def __init__(
|
|
94
|
+
self,
|
|
95
|
+
collect_draft: CollectDraft,
|
|
96
|
+
generate_documents: GenerateDocuments,
|
|
97
|
+
approval_gate: ApprovalGate,
|
|
98
|
+
contract_generator: ContractGenerator | None = None,
|
|
99
|
+
session_store: SessionStore | None = None,
|
|
100
|
+
progress: Callable[[str, str], None] | None = None,
|
|
101
|
+
collector_fallbacks: list[CollectDraft] | None = None,
|
|
102
|
+
document_fallbacks: list[GenerateDocuments] | None = None,
|
|
103
|
+
quality_gate: (
|
|
104
|
+
Callable[[QualityReport], ApprovalDecision | Awaitable[ApprovalDecision]] | None
|
|
105
|
+
) = None,
|
|
106
|
+
):
|
|
107
|
+
self._collect_draft = collect_draft
|
|
108
|
+
self._generate_documents = generate_documents
|
|
109
|
+
self._approval_gate = approval_gate
|
|
110
|
+
self._contract_generator = contract_generator or ContractGenerator()
|
|
111
|
+
self._session_store = session_store
|
|
112
|
+
self._progress = progress
|
|
113
|
+
self._collector_fallbacks = collector_fallbacks or []
|
|
114
|
+
self._document_fallbacks = document_fallbacks or []
|
|
115
|
+
self._quality_gate = quality_gate
|
|
116
|
+
|
|
117
|
+
async def run(
|
|
118
|
+
self,
|
|
119
|
+
intent: str,
|
|
120
|
+
harnesses: list[Harness],
|
|
121
|
+
output_dir: Path,
|
|
122
|
+
*,
|
|
123
|
+
project_name: str | None = None,
|
|
124
|
+
max_refinements: int = 5,
|
|
125
|
+
force: bool = False,
|
|
126
|
+
run_id: str | None = None,
|
|
127
|
+
resume: bool = False,
|
|
128
|
+
stage_timeout: float | None = 300,
|
|
129
|
+
cancel_event: asyncio.Event | None = None,
|
|
130
|
+
metadata: dict[str, object] | None = None,
|
|
131
|
+
) -> WorkflowResult:
|
|
132
|
+
"""Generate approved SRS/design documents and coding contracts."""
|
|
133
|
+
if not intent.strip():
|
|
134
|
+
raise ValueError("User intent cannot be empty")
|
|
135
|
+
if max_refinements < 0:
|
|
136
|
+
raise ValueError("max_refinements cannot be negative")
|
|
137
|
+
if not harnesses:
|
|
138
|
+
raise ValueError("At least one harness is required")
|
|
139
|
+
|
|
140
|
+
run_id = run_id or uuid.uuid4().hex
|
|
141
|
+
checkpoint = self._checkpoint(
|
|
142
|
+
run_id,
|
|
143
|
+
intent,
|
|
144
|
+
harnesses,
|
|
145
|
+
output_dir,
|
|
146
|
+
project_name,
|
|
147
|
+
resume=resume,
|
|
148
|
+
metadata=metadata or {},
|
|
149
|
+
)
|
|
150
|
+
draft: CollectorDraft | None = checkpoint.approved_draft
|
|
151
|
+
if draft is None and checkpoint.collector_drafts:
|
|
152
|
+
draft = checkpoint.collector_drafts[-1]
|
|
153
|
+
feedback: str | None = None
|
|
154
|
+
refinements = len(checkpoint.feedback)
|
|
155
|
+
|
|
156
|
+
try:
|
|
157
|
+
while checkpoint.approved_draft is None:
|
|
158
|
+
self._cancel_if_requested(cancel_event)
|
|
159
|
+
if draft is None or feedback is not None:
|
|
160
|
+
self._emit("collector", "running")
|
|
161
|
+
draft = await self._run_stage(
|
|
162
|
+
"collector",
|
|
163
|
+
[
|
|
164
|
+
lambda: self._collect_draft(intent, draft, feedback),
|
|
165
|
+
*(
|
|
166
|
+
lambda fallback=fallback: fallback(intent, draft, feedback)
|
|
167
|
+
for fallback in self._collector_fallbacks
|
|
168
|
+
),
|
|
169
|
+
],
|
|
170
|
+
stage_timeout,
|
|
171
|
+
)
|
|
172
|
+
if not draft:
|
|
173
|
+
raise ValueError("Collector returned an empty draft")
|
|
174
|
+
checkpoint.collector_drafts.append(draft)
|
|
175
|
+
checkpoint.touch(stage="collector", status="waiting_for_approval")
|
|
176
|
+
self._save(checkpoint)
|
|
177
|
+
|
|
178
|
+
self._emit("approval", "waiting")
|
|
179
|
+
decision = self._approval_gate.review(draft, refinements + 1)
|
|
180
|
+
if inspect.isawaitable(decision):
|
|
181
|
+
decision = await decision
|
|
182
|
+
|
|
183
|
+
if decision.action == ApprovalAction.CANCEL:
|
|
184
|
+
checkpoint.touch(stage="approval", status="cancelled")
|
|
185
|
+
self._save(checkpoint)
|
|
186
|
+
raise WorkflowCancelled("Contract generation cancelled before approval")
|
|
187
|
+
if decision.action == ApprovalAction.APPROVE:
|
|
188
|
+
checkpoint.approved_draft = draft
|
|
189
|
+
checkpoint.touch(stage="approval", status="approved")
|
|
190
|
+
self._save(checkpoint)
|
|
191
|
+
break
|
|
192
|
+
if decision.action != ApprovalAction.REFINE:
|
|
193
|
+
raise ValueError(f"Unsupported approval action: {decision.action}")
|
|
194
|
+
if not decision.feedback or not decision.feedback.strip():
|
|
195
|
+
raise ValueError("Refinement feedback cannot be empty")
|
|
196
|
+
if refinements >= max_refinements:
|
|
197
|
+
raise ValueError(f"Maximum Collector refinements reached: {max_refinements}")
|
|
198
|
+
feedback = decision.feedback.strip()
|
|
199
|
+
checkpoint.feedback.append(feedback)
|
|
200
|
+
checkpoint.touch(stage="collector", status="refining")
|
|
201
|
+
self._save(checkpoint)
|
|
202
|
+
refinements += 1
|
|
203
|
+
|
|
204
|
+
while True:
|
|
205
|
+
self._cancel_if_requested(cancel_event)
|
|
206
|
+
if checkpoint.srs is not None and checkpoint.design is not None:
|
|
207
|
+
documents = GeneratedDocuments(checkpoint.srs, checkpoint.design)
|
|
208
|
+
else:
|
|
209
|
+
self._emit("documents", "running")
|
|
210
|
+
documents = await self._run_stage(
|
|
211
|
+
"documents",
|
|
212
|
+
[
|
|
213
|
+
lambda: self._generate_documents(intent, checkpoint.approved_draft or draft),
|
|
214
|
+
*(
|
|
215
|
+
lambda fallback=fallback: fallback(intent, checkpoint.approved_draft or draft)
|
|
216
|
+
for fallback in self._document_fallbacks
|
|
217
|
+
),
|
|
218
|
+
],
|
|
219
|
+
stage_timeout * 4 if stage_timeout else None,
|
|
220
|
+
)
|
|
221
|
+
checkpoint.srs = documents.srs
|
|
222
|
+
checkpoint.design = documents.design
|
|
223
|
+
checkpoint.touch(stage="documents", status="generated")
|
|
224
|
+
self._save(checkpoint)
|
|
225
|
+
|
|
226
|
+
quality = validate_documents(documents.srs, documents.design)
|
|
227
|
+
if quality.ok:
|
|
228
|
+
break
|
|
229
|
+
if not self._quality_gate:
|
|
230
|
+
quality.require_valid()
|
|
231
|
+
quality_decision = self._quality_gate(quality)
|
|
232
|
+
if inspect.isawaitable(quality_decision):
|
|
233
|
+
quality_decision = await quality_decision
|
|
234
|
+
if quality_decision.action == ApprovalAction.CANCEL:
|
|
235
|
+
raise WorkflowCancelled("Contract generation cancelled at quality review")
|
|
236
|
+
if (
|
|
237
|
+
quality_decision.action != ApprovalAction.REFINE
|
|
238
|
+
or not quality_decision.feedback
|
|
239
|
+
or not quality_decision.feedback.strip()
|
|
240
|
+
):
|
|
241
|
+
quality.require_valid()
|
|
242
|
+
if refinements >= max_refinements:
|
|
243
|
+
raise ValueError(f"Maximum Collector refinements reached: {max_refinements}")
|
|
244
|
+
feedback = quality_decision.feedback.strip()
|
|
245
|
+
refinements += 1
|
|
246
|
+
draft = await self._collect_with_fallback(
|
|
247
|
+
intent,
|
|
248
|
+
checkpoint.approved_draft or draft,
|
|
249
|
+
feedback,
|
|
250
|
+
stage_timeout,
|
|
251
|
+
)
|
|
252
|
+
checkpoint.collector_drafts.append(draft)
|
|
253
|
+
checkpoint.feedback.append(feedback)
|
|
254
|
+
checkpoint.approved_draft = draft
|
|
255
|
+
checkpoint.srs = None
|
|
256
|
+
checkpoint.design = None
|
|
257
|
+
checkpoint.touch(stage="quality", status="refined")
|
|
258
|
+
self._save(checkpoint)
|
|
259
|
+
source_dir = output_dir / "sources"
|
|
260
|
+
spec_path = source_dir / "srs.md"
|
|
261
|
+
design_path = source_dir / "design.md"
|
|
262
|
+
targets = list(dict.fromkeys(harnesses))
|
|
263
|
+
planned_paths = [
|
|
264
|
+
spec_path,
|
|
265
|
+
design_path,
|
|
266
|
+
*(output_dir / harness.filename for harness in targets),
|
|
267
|
+
output_dir / "contract-manifest.json",
|
|
268
|
+
output_dir / "traceability.json",
|
|
269
|
+
output_dir / "traceability.md",
|
|
270
|
+
]
|
|
271
|
+
existing = [path for path in planned_paths if path.exists()]
|
|
272
|
+
if existing and not force:
|
|
273
|
+
names = ", ".join(str(path) for path in existing)
|
|
274
|
+
raise FileExistsError(f"Refusing to overwrite generated files: {names}")
|
|
275
|
+
|
|
276
|
+
source_dir.mkdir(parents=True, exist_ok=True)
|
|
277
|
+
spec_path.write_text(documents.srs, encoding="utf-8")
|
|
278
|
+
design_path.write_text(documents.design, encoding="utf-8")
|
|
279
|
+
|
|
280
|
+
bundles: list[ContractBundle] = [
|
|
281
|
+
self._contract_generator.generate(
|
|
282
|
+
spec_path=spec_path,
|
|
283
|
+
design_path=design_path,
|
|
284
|
+
harness=harness,
|
|
285
|
+
output_dir=output_dir,
|
|
286
|
+
project_name=project_name,
|
|
287
|
+
)
|
|
288
|
+
for harness in targets
|
|
289
|
+
]
|
|
290
|
+
written = write_bundles(bundles, force=force)
|
|
291
|
+
traceability = build_traceability(
|
|
292
|
+
checkpoint.approved_draft or draft,
|
|
293
|
+
documents.srs,
|
|
294
|
+
documents.design,
|
|
295
|
+
[bundle.content for bundle in bundles],
|
|
296
|
+
)
|
|
297
|
+
traceability.require_valid()
|
|
298
|
+
trace_paths = write_traceability(traceability, output_dir)
|
|
299
|
+
all_paths = [spec_path, design_path, *written, *trace_paths]
|
|
300
|
+
checkpoint.written_paths = [str(path) for path in all_paths]
|
|
301
|
+
checkpoint.error = None
|
|
302
|
+
checkpoint.touch(stage="complete", status="complete")
|
|
303
|
+
self._save(checkpoint)
|
|
304
|
+
self._emit("complete", "complete")
|
|
305
|
+
return WorkflowResult(
|
|
306
|
+
approved_draft=checkpoint.approved_draft or draft,
|
|
307
|
+
documents=documents,
|
|
308
|
+
written_paths=all_paths,
|
|
309
|
+
refinement_count=refinements,
|
|
310
|
+
)
|
|
311
|
+
except BaseException as error:
|
|
312
|
+
if isinstance(error, PartialDocumentsError):
|
|
313
|
+
checkpoint.srs = error.srs
|
|
314
|
+
checkpoint.error = f"{type(error).__name__}: {error}"
|
|
315
|
+
if checkpoint.status != "cancelled":
|
|
316
|
+
checkpoint.touch(status="failed")
|
|
317
|
+
self._save(checkpoint)
|
|
318
|
+
raise
|
|
319
|
+
|
|
320
|
+
def _checkpoint(
|
|
321
|
+
self,
|
|
322
|
+
run_id: str,
|
|
323
|
+
intent: str,
|
|
324
|
+
harnesses: list[Harness],
|
|
325
|
+
output_dir: Path,
|
|
326
|
+
project_name: str | None,
|
|
327
|
+
*,
|
|
328
|
+
resume: bool,
|
|
329
|
+
metadata: dict[str, object],
|
|
330
|
+
) -> RunCheckpoint:
|
|
331
|
+
if resume:
|
|
332
|
+
if not self._session_store:
|
|
333
|
+
raise ValueError("resume requires a session store")
|
|
334
|
+
checkpoint = self._session_store.load(run_id)
|
|
335
|
+
if checkpoint.intent != intent:
|
|
336
|
+
raise ValueError("Saved run intent does not match")
|
|
337
|
+
if checkpoint.harnesses != [harness.value for harness in harnesses]:
|
|
338
|
+
raise ValueError("Saved run harnesses do not match")
|
|
339
|
+
if checkpoint.output_dir != str(output_dir):
|
|
340
|
+
raise ValueError("Saved run output directory does not match")
|
|
341
|
+
checkpoint.config.update(metadata)
|
|
342
|
+
self._save(checkpoint)
|
|
343
|
+
return checkpoint
|
|
344
|
+
checkpoint = RunCheckpoint(
|
|
345
|
+
run_id=run_id,
|
|
346
|
+
intent=intent,
|
|
347
|
+
harnesses=[harness.value for harness in harnesses],
|
|
348
|
+
output_dir=str(output_dir),
|
|
349
|
+
project_name=project_name,
|
|
350
|
+
config=metadata,
|
|
351
|
+
)
|
|
352
|
+
self._save(checkpoint)
|
|
353
|
+
return checkpoint
|
|
354
|
+
|
|
355
|
+
async def _run_stage(
|
|
356
|
+
self,
|
|
357
|
+
stage: str,
|
|
358
|
+
attempts: list[Callable[[], Awaitable]],
|
|
359
|
+
timeout: float | None,
|
|
360
|
+
):
|
|
361
|
+
errors: list[BaseException] = []
|
|
362
|
+
for index, attempt in enumerate(attempts):
|
|
363
|
+
try:
|
|
364
|
+
operation = attempt()
|
|
365
|
+
return await asyncio.wait_for(operation, timeout) if timeout else await operation
|
|
366
|
+
except (Exception, asyncio.TimeoutError) as error:
|
|
367
|
+
errors.append(error)
|
|
368
|
+
self._emit(stage, f"attempt-{index + 1}-failed")
|
|
369
|
+
if isinstance(errors[-1], PartialDocumentsError):
|
|
370
|
+
raise errors[-1]
|
|
371
|
+
raise RuntimeError(
|
|
372
|
+
f"{stage} failed after {len(attempts)} attempt(s): "
|
|
373
|
+
+ "; ".join(f"{type(error).__name__}: {error}" for error in errors)
|
|
374
|
+
) from errors[-1]
|
|
375
|
+
|
|
376
|
+
async def _collect_with_fallback(
|
|
377
|
+
self,
|
|
378
|
+
intent: str,
|
|
379
|
+
draft: CollectorDraft,
|
|
380
|
+
feedback: str,
|
|
381
|
+
timeout: float | None,
|
|
382
|
+
) -> CollectorDraft:
|
|
383
|
+
result = await self._run_stage(
|
|
384
|
+
"collector",
|
|
385
|
+
[
|
|
386
|
+
lambda: self._collect_draft(intent, draft, feedback),
|
|
387
|
+
*(
|
|
388
|
+
lambda fallback=fallback: fallback(intent, draft, feedback)
|
|
389
|
+
for fallback in self._collector_fallbacks
|
|
390
|
+
),
|
|
391
|
+
],
|
|
392
|
+
timeout,
|
|
393
|
+
)
|
|
394
|
+
if not result:
|
|
395
|
+
raise ValueError("Collector returned an empty draft")
|
|
396
|
+
return result
|
|
397
|
+
|
|
398
|
+
@staticmethod
|
|
399
|
+
def _cancel_if_requested(cancel_event: asyncio.Event | None) -> None:
|
|
400
|
+
if cancel_event and cancel_event.is_set():
|
|
401
|
+
raise WorkflowCancelled("Contract generation cancelled")
|
|
402
|
+
|
|
403
|
+
def _save(self, checkpoint: RunCheckpoint) -> None:
|
|
404
|
+
if self._session_store:
|
|
405
|
+
self._session_store.save(checkpoint)
|
|
406
|
+
|
|
407
|
+
def _emit(self, stage: str, status: str) -> None:
|
|
408
|
+
if self._progress:
|
|
409
|
+
self._progress(stage, status)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Write generated contracts and their manifest."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from .models import ContractBundle
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def write_bundles(bundles: list[ContractBundle], force: bool = False) -> list[Path]:
|
|
10
|
+
"""Write contracts and a manifest, refusing accidental overwrites."""
|
|
11
|
+
if not bundles:
|
|
12
|
+
raise ValueError("At least one contract bundle is required")
|
|
13
|
+
|
|
14
|
+
output_dir = bundles[0].output_path.parent
|
|
15
|
+
paths = [bundle.output_path for bundle in bundles]
|
|
16
|
+
manifest_path = output_dir / "contract-manifest.json"
|
|
17
|
+
existing = [path for path in [*paths, manifest_path] if path.exists()]
|
|
18
|
+
if existing and not force:
|
|
19
|
+
names = ", ".join(str(path) for path in existing)
|
|
20
|
+
raise FileExistsError(f"Refusing to overwrite existing contract files: {names}")
|
|
21
|
+
|
|
22
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
23
|
+
for bundle in bundles:
|
|
24
|
+
bundle.output_path.write_text(bundle.content, encoding="utf-8")
|
|
25
|
+
|
|
26
|
+
manifest = {
|
|
27
|
+
"schema_version": "1.0",
|
|
28
|
+
"project_name": bundles[0].project_name,
|
|
29
|
+
"sources": [source.model_dump() for source in bundles[0].sources],
|
|
30
|
+
"contracts": [
|
|
31
|
+
{
|
|
32
|
+
"harness": bundle.harness.value,
|
|
33
|
+
# Manifests are routinely shared with generated contracts. Keep paths
|
|
34
|
+
# relative to the manifest so local usernames and checkout layouts are
|
|
35
|
+
# never embedded in release artifacts.
|
|
36
|
+
"path": bundle.output_path.name,
|
|
37
|
+
"sha256": _sha256(bundle.content),
|
|
38
|
+
}
|
|
39
|
+
for bundle in bundles
|
|
40
|
+
],
|
|
41
|
+
}
|
|
42
|
+
manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
|
|
43
|
+
return [*paths, manifest_path]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _sha256(content: str) -> str:
|
|
47
|
+
import hashlib
|
|
48
|
+
|
|
49
|
+
return hashlib.sha256(content.encode("utf-8")).hexdigest()
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Wrapper agent to create a workflow of the Design agents."""
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
from specadia._agents import AgentBase
|
|
5
|
+
from specadia._utils.constants import AgentRunMode, DEFAULT_MODEL_NAME
|
|
6
|
+
|
|
7
|
+
from google.adk.agents import SequentialAgent
|
|
8
|
+
from specadia._utils.logger import (get_run_id, setup_logging)
|
|
9
|
+
from specadia._design import DesignerAgent
|
|
10
|
+
from specadia._design import DocumenterAgent
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class DesignWrapperAgent(AgentBase):
|
|
14
|
+
"""This class defines the wrapper agent for the Design phase of the SDLC."""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
llm_model_name: str,
|
|
19
|
+
system_prompt: Optional[str] = None,
|
|
20
|
+
run_mode: Optional[AgentRunMode] = AgentRunMode.MAIN,
|
|
21
|
+
rag: Optional[bool] = True,
|
|
22
|
+
):
|
|
23
|
+
super().__init__(llm_model_name, system_prompt, run_mode, rag)
|
|
24
|
+
self._designer_agent = DesignerAgent(
|
|
25
|
+
llm_model_name, run_mode=run_mode, rag=rag
|
|
26
|
+
).get_agent()
|
|
27
|
+
self._documenter_agent = DocumenterAgent(
|
|
28
|
+
llm_model_name, run_mode=run_mode, rag=rag
|
|
29
|
+
).get_agent()
|
|
30
|
+
|
|
31
|
+
def get_agent(self) -> SequentialAgent:
|
|
32
|
+
return SequentialAgent(
|
|
33
|
+
name="design_agent",
|
|
34
|
+
sub_agents=[self._designer_agent, self._documenter_agent],
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# For testing in adk web ui
|
|
39
|
+
def __getattr__(name: str):
|
|
40
|
+
if name == "root_agent":
|
|
41
|
+
setup_logging(get_run_id(), "adk")
|
|
42
|
+
return DesignWrapperAgent(DEFAULT_MODEL_NAME).get_agent()
|
|
43
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|