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.
Files changed (86) hide show
  1. specadia/__init__.py +3 -0
  2. specadia/_agents/__init__.py +22 -0
  3. specadia/_agents/agent_base.py +58 -0
  4. specadia/_agents/agent_callbacks.py +123 -0
  5. specadia/_agents/agent_util.py +170 -0
  6. specadia/_agents/local_providers.py +44 -0
  7. specadia/_agents/model_base.py +15 -0
  8. specadia/_agents/prompt_safety.py +9 -0
  9. specadia/_constants.py +3 -0
  10. specadia/_contracts/__init__.py +7 -0
  11. specadia/_contracts/cli.py +352 -0
  12. specadia/_contracts/context.py +120 -0
  13. specadia/_contracts/generator.py +190 -0
  14. specadia/_contracts/models.py +50 -0
  15. specadia/_contracts/prompt_safety.py +56 -0
  16. specadia/_contracts/requirement_ids.py +16 -0
  17. specadia/_contracts/session_store.py +100 -0
  18. specadia/_contracts/specadia_pipeline.py +238 -0
  19. specadia/_contracts/traceability.py +118 -0
  20. specadia/_contracts/validation.py +166 -0
  21. specadia/_contracts/workflow.py +409 -0
  22. specadia/_contracts/writer.py +49 -0
  23. specadia/_design/__init__.py +7 -0
  24. specadia/_design/design_agent/__init__.py +5 -0
  25. specadia/_design/design_agent/design_wrapper.py +43 -0
  26. specadia/_design/designer/__init__.py +6 -0
  27. specadia/_design/designer/designer_agent.py +61 -0
  28. specadia/_design/designer/designer_models.py +21 -0
  29. specadia/_design/documenter/__init__.py +5 -0
  30. specadia/_design/documenter/documenter_agent.py +51 -0
  31. specadia/_diagnostics/__init__.py +7 -0
  32. specadia/_diagnostics/doctor.py +221 -0
  33. specadia/_orchestrator/__init__.py +23 -0
  34. specadia/_orchestrator/constants.py +4 -0
  35. specadia/_orchestrator/orchestrator.py +326 -0
  36. specadia/_orchestrator/plugins.py +59 -0
  37. specadia/_orchestrator/read_wrapper.py +88 -0
  38. specadia/_orchestrator/session_manager.py +57 -0
  39. specadia/_prompt_templates/__init__.py +21 -0
  40. specadia/_prompt_templates/analyzer_prompt.py +36 -0
  41. specadia/_prompt_templates/collector_prompt.py +48 -0
  42. specadia/_prompt_templates/design_prompt.py +17 -0
  43. specadia/_prompt_templates/designer_prompt.py +46 -0
  44. specadia/_prompt_templates/documenter_prompt.py +16 -0
  45. specadia/_prompt_templates/kb/design_kb.py +60 -0
  46. specadia/_prompt_templates/kb/requirements_kb.py +40 -0
  47. specadia/_prompt_templates/re_prompt.py +10 -0
  48. specadia/_prompt_templates/single_prompt.py +121 -0
  49. specadia/_prompt_templates/specifier_prompt.py +32 -0
  50. specadia/_prompt_templates/templates/design_template.py +25 -0
  51. specadia/_prompt_templates/templates/srs_template.py +83 -0
  52. specadia/_rag/__init__.py +1 -0
  53. specadia/_rag/cli.py +146 -0
  54. specadia/_rag/knowledge_base.py +570 -0
  55. specadia/_requirement/__init__.py +8 -0
  56. specadia/_requirement/analyzer/__init__.py +14 -0
  57. specadia/_requirement/analyzer/analyzer_agent.py +55 -0
  58. specadia/_requirement/analyzer/analyzer_models.py +30 -0
  59. specadia/_requirement/collector/__init__.py +14 -0
  60. specadia/_requirement/collector/collector_agent.py +74 -0
  61. specadia/_requirement/collector/collector_models.py +11 -0
  62. specadia/_requirement/re_agent/__init__.py +7 -0
  63. specadia/_requirement/re_agent/requirements_wrapper.py +57 -0
  64. specadia/_requirement/specifier/__init__.py +5 -0
  65. specadia/_requirement/specifier/specifier_agent.py +52 -0
  66. specadia/_requirement/specifier/specifier_models.py +23 -0
  67. specadia/_single/__init__.py +5 -0
  68. specadia/_single/single_agent.py +58 -0
  69. specadia/_tools/__init__.py +5 -0
  70. specadia/_tools/constants.py +13 -0
  71. specadia/_tools/save_to_file_tool.py +59 -0
  72. specadia/_utils/__init__.py +7 -0
  73. specadia/_utils/constants.py +40 -0
  74. specadia/_utils/logger.py +47 -0
  75. specadia/cli.py +28 -0
  76. specadia/contracts/__init__.py +22 -0
  77. specadia/contracts/cli.py +8 -0
  78. specadia/diagnostics/__init__.py +1 -0
  79. specadia/diagnostics/doctor.py +5 -0
  80. specadia/providers.py +61 -0
  81. specadia-0.2.7.dist-info/METADATA +264 -0
  82. specadia-0.2.7.dist-info/RECORD +86 -0
  83. specadia-0.2.7.dist-info/WHEEL +5 -0
  84. specadia-0.2.7.dist-info/entry_points.txt +4 -0
  85. specadia-0.2.7.dist-info/licenses/LICENSE +201 -0
  86. specadia-0.2.7.dist-info/top_level.txt +1 -0
@@ -0,0 +1,352 @@
1
+ """CLI implementation for converting READ-MAS artifacts into contracts."""
2
+
3
+ import asyncio
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ import typer
9
+ from rich import print
10
+ from specadia import __version__
11
+ from specadia._constants import DEFAULT_MODEL_NAME
12
+
13
+ from .generator import ContractGenerator
14
+ from .context import inspect_repository
15
+ from .models import Harness
16
+ from .session_store import SessionStore
17
+ from .workflow import ApprovalAction
18
+ from .workflow import ApprovalDecision
19
+ from .workflow import ContractWorkflow
20
+ from .workflow import WorkflowCancelled
21
+ from .validation import QualityReport
22
+ from .writer import write_bundles
23
+
24
+ app = typer.Typer(help="Generate coding-agent contracts from READ-MAS requirements and designs.")
25
+
26
+ DEFAULT_SESSIONS_DIR = Path(".specadia/sessions")
27
+
28
+ __all__ = ["app", "generate_contract", "generate_from_intent", "list_runs"]
29
+
30
+
31
+ def _session_store(root: Path) -> SessionStore:
32
+ return SessionStore(root)
33
+
34
+
35
+ def _version_callback(value: bool) -> None:
36
+ if value:
37
+ typer.echo(f"specadia {__version__}")
38
+ raise typer.Exit()
39
+
40
+
41
+ @app.callback()
42
+ def contract_cli(
43
+ version: bool = typer.Option(
44
+ False,
45
+ "--version",
46
+ callback=_version_callback,
47
+ is_eager=True,
48
+ help="Show the Specadia version and exit.",
49
+ ),
50
+ ):
51
+ """Generate coding-agent contracts from READ-MAS requirements and designs."""
52
+
53
+
54
+ @app.command("generate")
55
+ def generate_contract(
56
+ spec: Path = typer.Argument(
57
+ ...,
58
+ exists=True,
59
+ dir_okay=False,
60
+ readable=True,
61
+ resolve_path=True,
62
+ help="Software requirements specification in Markdown.",
63
+ ),
64
+ design: Optional[Path] = typer.Option(
65
+ None,
66
+ "--design",
67
+ "-d",
68
+ exists=True,
69
+ dir_okay=False,
70
+ readable=True,
71
+ resolve_path=True,
72
+ help="Optional Specadia design document in Markdown.",
73
+ ),
74
+ harness: list[Harness] = typer.Option(
75
+ [Harness.CODEX],
76
+ "--harness",
77
+ "-H",
78
+ help="Target harness. Repeat for multiple outputs.",
79
+ ),
80
+ output_dir: Path = typer.Option(
81
+ Path(".specadia/contracts"),
82
+ "--output-dir",
83
+ "-o",
84
+ help="Directory for contracts and the traceability manifest.",
85
+ ),
86
+ project_name: Optional[str] = typer.Option(
87
+ None,
88
+ "--project-name",
89
+ help="Override the project name inferred from the SRS title.",
90
+ ),
91
+ force: bool = typer.Option(
92
+ False,
93
+ "--force",
94
+ help="Overwrite existing generated contract files.",
95
+ ),
96
+ ):
97
+ """Generate implementation contracts for coding harnesses."""
98
+ generator = ContractGenerator()
99
+ try:
100
+ targets = list(dict.fromkeys(harness))
101
+ bundles = [
102
+ generator.generate(
103
+ spec_path=spec,
104
+ design_path=design,
105
+ harness=target,
106
+ output_dir=output_dir,
107
+ project_name=project_name,
108
+ )
109
+ for target in targets
110
+ ]
111
+ written = write_bundles(bundles, force=force)
112
+ except (ValueError, FileExistsError, OSError) as error:
113
+ print(f"[red]Error: {error}[/red]")
114
+ raise typer.Exit(1) from error
115
+
116
+ for path in written:
117
+ print(f"[green]Generated:[/green] {path}")
118
+
119
+
120
+ class ConsoleApprovalGate:
121
+ """Interactive Collector approval for terminal users."""
122
+
123
+ def review(self, draft: dict[str, object], attempt: int) -> ApprovalDecision:
124
+ print(f"\n[bold]Collector draft {attempt}[/bold]")
125
+ print_json = json.dumps(draft, indent=2, default=str)
126
+ print(print_json)
127
+ action = typer.prompt(
128
+ "Choose [approve/refine/cancel]",
129
+ default=ApprovalAction.APPROVE.value,
130
+ ).lower()
131
+ try:
132
+ selected = ApprovalAction(action)
133
+ except ValueError as error:
134
+ raise ValueError("Choose must be approve, refine, or cancel") from error
135
+ if selected == ApprovalAction.REFINE:
136
+ feedback = typer.prompt("Refinement feedback")
137
+ return ApprovalDecision(ApprovalAction.REFINE, feedback)
138
+ return ApprovalDecision(selected)
139
+
140
+
141
+ class ConsoleQualityGate:
142
+ """Offer another Collector refinement when generated documents fail checks."""
143
+
144
+ def __call__(self, report: QualityReport) -> ApprovalDecision:
145
+ print("\n[bold red]Generated document quality checks failed[/bold red]")
146
+ for issue in report.issues:
147
+ print(f"- {issue.document}/{issue.code}: {issue.message}")
148
+ if not typer.confirm("Refine requirements and regenerate?", default=True):
149
+ return ApprovalDecision(ApprovalAction.CANCEL)
150
+ return ApprovalDecision(
151
+ ApprovalAction.REFINE,
152
+ typer.prompt("Refinement feedback"),
153
+ )
154
+
155
+
156
+ def _progress(stage: str, status: str) -> None:
157
+ print(f"[cyan]{stage}[/cyan]: {status}")
158
+
159
+
160
+ def _missing_agent_extras_hint() -> None:
161
+ typer.secho(
162
+ "Natural-language intent-to-contract requires the agent extras. "
163
+ 'Install with: pip install "specadia[full]"',
164
+ fg=typer.colors.RED,
165
+ )
166
+
167
+
168
+ @app.command("from-intent")
169
+ def generate_from_intent(
170
+ intent: str = typer.Argument(..., help="Initial product or system intent."),
171
+ harness: list[Harness] = typer.Option(
172
+ [Harness.CODEX],
173
+ "--harness",
174
+ "-H",
175
+ help="Target harness. Repeat for multiple outputs.",
176
+ ),
177
+ output_dir: Optional[Path] = typer.Option(
178
+ None,
179
+ "--output-dir",
180
+ "-o",
181
+ help=(
182
+ "Directory for generated sources, contracts, and manifest. Defaults to "
183
+ ".specadia/contracts, or the checkpoint's recorded directory when resuming."
184
+ ),
185
+ ),
186
+ llm_model_name: str = typer.Option(
187
+ DEFAULT_MODEL_NAME,
188
+ "--llm-model-name",
189
+ "-m",
190
+ help="Model used by the Specadia agents.",
191
+ ),
192
+ rag: bool = typer.Option(False, "--rag", help="Enable requirement retrieval."),
193
+ rag_collection: str = typer.Option(
194
+ "default",
195
+ "--rag-collection",
196
+ help="Named collection created with `specadia rag build`.",
197
+ ),
198
+ rag_index_dir: Path = typer.Option(
199
+ Path(".specadia/rag"), "--rag-index-dir", help="Root directory for user collections."
200
+ ),
201
+ project_name: Optional[str] = typer.Option(None, "--project-name"),
202
+ max_refinements: int = typer.Option(
203
+ 5,
204
+ "--max-refinements",
205
+ min=0,
206
+ help="Maximum human-requested Collector revisions.",
207
+ ),
208
+ force: bool = typer.Option(False, "--force"),
209
+ repo: Optional[Path] = typer.Option(
210
+ None,
211
+ "--repo",
212
+ exists=True,
213
+ file_okay=False,
214
+ resolve_path=True,
215
+ help="Existing repository whose structure and conventions constrain the design.",
216
+ ),
217
+ run_id: Optional[str] = typer.Option(None, "--run-id", help="Stable checkpoint identifier."),
218
+ resume: bool = typer.Option(False, "--resume", help="Resume a saved HITL run."),
219
+ sessions_dir: Path = typer.Option(
220
+ DEFAULT_SESSIONS_DIR,
221
+ "--sessions-dir",
222
+ help="Directory containing durable run checkpoints.",
223
+ ),
224
+ stage_timeout: float = typer.Option(
225
+ 300,
226
+ "--stage-timeout",
227
+ min=1,
228
+ help="Timeout in seconds for each agent stage.",
229
+ ),
230
+ fallback_model: list[str] = typer.Option(
231
+ [],
232
+ "--fallback-model",
233
+ help="Fallback agent model. Repeat to define an ordered fallback chain.",
234
+ ),
235
+ yes: bool = typer.Option(
236
+ False,
237
+ "--yes",
238
+ help="Confirm sending repository context to a hosted model.",
239
+ ),
240
+ ):
241
+ """Generate SRS/design with HITL, then emit coding-agent contracts."""
242
+ from .specadia_pipeline import SpecadiaPipeline
243
+ from specadia.providers import is_local_model
244
+
245
+ effective_intent = intent
246
+ if repo:
247
+ context = inspect_repository(repo)
248
+ hosted = not is_local_model(llm_model_name)
249
+ if (
250
+ hosted
251
+ and not yes
252
+ and not typer.confirm(
253
+ f"Send bounded metadata and convention files from {repo} to {llm_model_name}?"
254
+ )
255
+ ):
256
+ raise typer.Exit(2)
257
+ effective_intent = f"{intent}\n\n{context.to_prompt()}"
258
+
259
+ try:
260
+ pipeline = SpecadiaPipeline(
261
+ llm_model_name=llm_model_name,
262
+ rag=rag,
263
+ rag_collection=rag_collection,
264
+ rag_index_dir=rag_index_dir,
265
+ stage_timeout=stage_timeout,
266
+ )
267
+ if resume and not run_id:
268
+ print("[red]Error: --resume requires --run-id.[/red]")
269
+ raise typer.Exit(1)
270
+ store = _session_store(sessions_dir)
271
+ if output_dir is None:
272
+ output_dir = (
273
+ Path(store.load(run_id).output_dir) if resume and run_id else Path(".specadia/contracts")
274
+ )
275
+ fallback_pipelines = [
276
+ SpecadiaPipeline(
277
+ model,
278
+ rag=rag,
279
+ rag_collection=rag_collection,
280
+ rag_index_dir=rag_index_dir,
281
+ stage_timeout=stage_timeout,
282
+ )
283
+ for model in fallback_model
284
+ ]
285
+ workflow = ContractWorkflow(
286
+ collect_draft=pipeline.collect,
287
+ generate_documents=pipeline.generate_documents,
288
+ approval_gate=ConsoleApprovalGate(),
289
+ session_store=store,
290
+ progress=_progress,
291
+ collector_fallbacks=[fallback.collect for fallback in fallback_pipelines],
292
+ document_fallbacks=[fallback.generate_documents for fallback in fallback_pipelines],
293
+ quality_gate=ConsoleQualityGate(),
294
+ )
295
+ try:
296
+ result = asyncio.run(
297
+ workflow.run(
298
+ effective_intent,
299
+ harness,
300
+ output_dir,
301
+ project_name=project_name,
302
+ max_refinements=max_refinements,
303
+ force=force,
304
+ run_id=run_id,
305
+ resume=resume,
306
+ stage_timeout=stage_timeout,
307
+ metadata={
308
+ "model": llm_model_name,
309
+ "fallback_models": fallback_model,
310
+ "rag": rag,
311
+ "rag_collection": rag_collection,
312
+ "repository_context": bool(repo),
313
+ "stage_timeout": stage_timeout,
314
+ },
315
+ )
316
+ )
317
+ except WorkflowCancelled as error:
318
+ print(f"[yellow]{error}[/yellow]")
319
+ raise typer.Exit(2) from error
320
+ except (ValueError, FileExistsError, OSError) as error:
321
+ print(f"[red]Error: {error}[/red]")
322
+ raise typer.Exit(1) from error
323
+ except ImportError:
324
+ _missing_agent_extras_hint()
325
+ raise typer.Exit(1)
326
+ except RuntimeError as error:
327
+ cause = error.__cause__ or error.__context__
328
+ if isinstance(cause, ImportError):
329
+ _missing_agent_extras_hint()
330
+ raise typer.Exit(1)
331
+ raise
332
+
333
+ print(f"[green]Approved after {result.refinement_count} refinement(s).[/green]")
334
+ for path in result.written_paths:
335
+ print(f"[green]Generated:[/green] {path}")
336
+
337
+
338
+ @app.command("runs")
339
+ def list_runs(
340
+ sessions_dir: Path = typer.Option(DEFAULT_SESSIONS_DIR, "--sessions-dir"),
341
+ ):
342
+ """List durable HITL runs available for resume."""
343
+ runs = _session_store(sessions_dir).list_runs()
344
+ if not runs:
345
+ print("No saved runs.")
346
+ return
347
+ for run in runs:
348
+ print(f"{run.run_id}\t{run.status}\t{run.stage}\t{run.updated_at}")
349
+
350
+
351
+ if __name__ == "__main__":
352
+ app()
@@ -0,0 +1,120 @@
1
+ """Bounded, safe repository context for design generation."""
2
+
3
+ import json
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ import re
7
+
8
+ _MANIFESTS = {
9
+ "pyproject.toml": "Python",
10
+ "package.json": "JavaScript/TypeScript",
11
+ "go.mod": "Go",
12
+ "Cargo.toml": "Rust",
13
+ "pom.xml": "Java",
14
+ "build.gradle": "Java/Kotlin",
15
+ }
16
+ _CONVENTION_FILES = ("AGENTS.md", "CLAUDE.md", "CONTRIBUTING.md")
17
+ _EXCLUDED_PARTS = {
18
+ ".git",
19
+ ".venv",
20
+ "venv",
21
+ "node_modules",
22
+ "dist",
23
+ "build",
24
+ "runs",
25
+ "__pycache__",
26
+ }
27
+ _SENSITIVE_NAME_RE = re.compile(
28
+ r"(?:^|[._-])(?:env|secret|secrets|credential|credentials|token|tokens|password|"
29
+ r"private[-_]?key|id[-_]?rsa|id[-_]?ed25519)(?:$|[._-])",
30
+ re.IGNORECASE,
31
+ )
32
+ _SENSITIVE_SUFFIXES = {".key", ".keystore", ".p12", ".pem", ".pfx"}
33
+
34
+
35
+ def _is_sensitive_path(path: Path) -> bool:
36
+ """Return whether a relative path is likely to disclose credential material."""
37
+ return any(
38
+ _SENSITIVE_NAME_RE.search(part) or Path(part).suffix.lower() in _SENSITIVE_SUFFIXES
39
+ for part in path.parts
40
+ )
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class RepositoryContext:
45
+ root: str
46
+ languages: list[str]
47
+ manifests: list[str]
48
+ commands: list[str]
49
+ structure: list[str]
50
+ conventions: dict[str, str]
51
+
52
+ def to_prompt(self) -> str:
53
+ payload = {
54
+ "root": self.root,
55
+ "languages": self.languages,
56
+ "manifests": self.manifests,
57
+ "commands": self.commands,
58
+ "structure": self.structure,
59
+ "conventions": self.conventions,
60
+ }
61
+ return "Existing repository context (treat as constraints):\n" + json.dumps(payload, indent=2)
62
+
63
+
64
+ def inspect_repository(
65
+ root: Path,
66
+ *,
67
+ max_files: int = 200,
68
+ max_convention_chars: int = 12_000,
69
+ ) -> RepositoryContext:
70
+ """Inspect bounded metadata without disclosing local paths or file contents."""
71
+ resolved = root.expanduser().resolve()
72
+ if not resolved.is_dir():
73
+ raise ValueError(f"Repository directory does not exist: {root}")
74
+
75
+ manifests = [name for name in _MANIFESTS if (resolved / name).is_file()]
76
+ languages = sorted({_MANIFESTS[name] for name in manifests})
77
+ paths: list[str] = []
78
+ for path in sorted(resolved.rglob("*")):
79
+ relative = path.relative_to(resolved)
80
+ if any(part in _EXCLUDED_PARTS for part in relative.parts):
81
+ continue
82
+ if path.is_file() and not _is_sensitive_path(relative):
83
+ paths.append(str(relative))
84
+ if len(paths) >= max_files:
85
+ break
86
+
87
+ conventions: dict[str, str] = {}
88
+ remaining = max_convention_chars
89
+ for name in _CONVENTION_FILES:
90
+ path = resolved / name
91
+ if path.is_file() and remaining > 0:
92
+ marker = "[present; content omitted from repository context]"
93
+ conventions[name] = marker
94
+ remaining -= len(marker)
95
+
96
+ return RepositoryContext(
97
+ root=".",
98
+ languages=languages,
99
+ manifests=manifests,
100
+ commands=_commands(resolved),
101
+ structure=paths,
102
+ conventions=conventions,
103
+ )
104
+
105
+
106
+ def _commands(root: Path) -> list[str]:
107
+ commands: list[str] = []
108
+ pyproject = root / "pyproject.toml"
109
+ if pyproject.is_file():
110
+ commands.extend(["python -m pytest", "python -m pip install -e ."])
111
+ package = root / "package.json"
112
+ if package.is_file():
113
+ try:
114
+ scripts = json.loads(package.read_text(encoding="utf-8")).get("scripts", {})
115
+ commands.extend(f"npm run {name}" for name in sorted(scripts))
116
+ except (OSError, json.JSONDecodeError):
117
+ pass
118
+ if (root / "Makefile").is_file():
119
+ commands.append("make")
120
+ return commands
@@ -0,0 +1,190 @@
1
+ """Deterministic spec-to-agent contract generation."""
2
+
3
+ import hashlib
4
+ import re
5
+ from pathlib import Path
6
+
7
+ from .models import ContractBundle
8
+ from .models import ContractSection
9
+ from .models import Harness
10
+ from .models import SourceDocument
11
+
12
+ _HEADING = re.compile(r"^(#{1,6})\s+(.+?)\s*$")
13
+ _REQUIREMENT = re.compile(
14
+ r"^\s*(?:[-*]\s*)?(?P<id>(?:FR|NFR|REQ|AC)[-_ ]?\d+)\s*[:.)-]\s*(?P<body>.+)$",
15
+ re.IGNORECASE,
16
+ )
17
+ _SECTION_ALIASES = {
18
+ "objective": ("overview", "purpose", "introduction", "scope"),
19
+ "requirements": ("functional requirement", "use case", "feature"),
20
+ "quality": ("non-functional", "quality attribute", "constraint", "security"),
21
+ "architecture": ("architecture", "system design", "component design", "file structure"),
22
+ "acceptance": ("acceptance", "validation", "verification", "test"),
23
+ }
24
+
25
+
26
+ class ContractGenerator:
27
+ """Convert an SRS and optional design document into a coding contract."""
28
+
29
+ def generate(
30
+ self,
31
+ spec_path: Path,
32
+ harness: Harness,
33
+ output_dir: Path,
34
+ design_path: Path | None = None,
35
+ project_name: str | None = None,
36
+ ) -> ContractBundle:
37
+ spec_path = self._validate_source(spec_path, "spec")
38
+ design_path = self._validate_source(design_path, "design") if design_path else None
39
+ project_name = project_name or self._project_name(spec_path)
40
+
41
+ sources = [self._source("spec", spec_path)]
42
+ documents = [spec_path.read_text(encoding="utf-8")]
43
+ if design_path:
44
+ sources.append(self._source("design", design_path))
45
+ documents.append(design_path.read_text(encoding="utf-8"))
46
+
47
+ sections = self._normalize_sections(documents)
48
+ content = self._render(project_name, harness, sources, sections)
49
+ return ContractBundle(
50
+ project_name=project_name,
51
+ harness=harness,
52
+ output_path=output_dir / harness.filename,
53
+ sources=sources,
54
+ sections=sections,
55
+ content=content,
56
+ )
57
+
58
+ @staticmethod
59
+ def _validate_source(path: Path, label: str) -> Path:
60
+ resolved = path.expanduser().resolve()
61
+ if not resolved.is_file():
62
+ raise ValueError(f"{label.capitalize()} file does not exist: {path}")
63
+ if resolved.stat().st_size == 0:
64
+ raise ValueError(f"{label.capitalize()} file is empty: {path}")
65
+ return resolved
66
+
67
+ @staticmethod
68
+ def _source(kind: str, path: Path) -> SourceDocument:
69
+ digest = hashlib.sha256(path.read_bytes()).hexdigest()
70
+ # Contracts are commonly shared with coding harnesses. A basename is sufficient for
71
+ # traceability and avoids leaking usernames or local directory layouts.
72
+ return SourceDocument(kind=kind, path=path.name, sha256=digest)
73
+
74
+ @staticmethod
75
+ def _project_name(spec_path: Path) -> str:
76
+ for line in spec_path.read_text(encoding="utf-8").splitlines():
77
+ match = _HEADING.match(line)
78
+ if match and len(match.group(1)) == 1:
79
+ return match.group(2).strip()
80
+ return spec_path.stem.replace("_", " ").replace("-", " ").title()
81
+
82
+ def _normalize_sections(self, documents: list[str]) -> list[ContractSection]:
83
+ parsed = [self._parse_markdown(document) for document in documents]
84
+ normalized: list[ContractSection] = []
85
+ for target, aliases in _SECTION_ALIASES.items():
86
+ content = self._matching_content(parsed, aliases)
87
+ if content:
88
+ normalized.append(ContractSection(title=target, content=content))
89
+
90
+ requirements = self._extract_requirements(documents)
91
+ if requirements:
92
+ replacement = "\n".join(f"- `{req_id}`: {body}" for req_id, body in requirements)
93
+ normalized = [section for section in normalized if section.title != "requirements"]
94
+ normalized.insert(1 if normalized else 0, ContractSection(title="requirements", content=replacement))
95
+
96
+ if not normalized:
97
+ normalized.append(
98
+ ContractSection(title="requirements", content=self._trim("\n\n".join(documents)))
99
+ )
100
+ return normalized
101
+
102
+ @staticmethod
103
+ def _parse_markdown(document: str) -> dict[str, list[str]]:
104
+ sections: dict[str, list[str]] = {"document": []}
105
+ current = "document"
106
+ for line in document.splitlines():
107
+ heading = _HEADING.match(line)
108
+ if heading:
109
+ current = heading.group(2).strip().lower()
110
+ sections.setdefault(current, [])
111
+ else:
112
+ sections[current].append(line)
113
+ return sections
114
+
115
+ @staticmethod
116
+ def _matching_content(
117
+ documents: list[dict[str, list[str]]], aliases: tuple[str, ...]
118
+ ) -> str:
119
+ chunks: list[str] = []
120
+ for document in documents:
121
+ for heading, lines in document.items():
122
+ if any(alias in heading for alias in aliases):
123
+ content = ContractGenerator._trim("\n".join(lines))
124
+ if content and content not in chunks:
125
+ chunks.append(content)
126
+ return "\n\n".join(chunks)
127
+
128
+ @staticmethod
129
+ def _extract_requirements(documents: list[str]) -> list[tuple[str, str]]:
130
+ requirements: list[tuple[str, str]] = []
131
+ seen: set[str] = set()
132
+ for document in documents:
133
+ for line in document.splitlines():
134
+ match = _REQUIREMENT.match(line)
135
+ if not match:
136
+ continue
137
+ req_id = re.sub(r"[-_ ]", "-", match.group("id").upper())
138
+ if req_id not in seen:
139
+ requirements.append((req_id, match.group("body").strip()))
140
+ seen.add(req_id)
141
+ return requirements
142
+
143
+ @staticmethod
144
+ def _trim(content: str, limit: int = 12_000) -> str:
145
+ content = content.strip()
146
+ if len(content) <= limit:
147
+ return content
148
+ return f"{content[:limit].rstrip()}\n\n[Source section truncated by generator]"
149
+
150
+ def _render(
151
+ self,
152
+ project_name: str,
153
+ harness: Harness,
154
+ sources: list[SourceDocument],
155
+ sections: list[ContractSection],
156
+ ) -> str:
157
+ preamble = {
158
+ Harness.CODEX: (
159
+ "These instructions define the implementation contract for Codex and its subagents."
160
+ ),
161
+ Harness.CLAUDE: (
162
+ "These instructions define the implementation contract for Claude Code and its agents."
163
+ ),
164
+ Harness.GENERIC: "This document is the implementation contract for a coding agent.",
165
+ }[harness]
166
+ rendered_sections = "\n\n".join(
167
+ f"## {section.title.replace('_', ' ').title()}\n\n{section.content}"
168
+ for section in sections
169
+ )
170
+ source_lines = "\n".join(
171
+ f"- `{source.kind}`: `{source.path}` (SHA-256 `{source.sha256}`)"
172
+ for source in sources
173
+ )
174
+ return (
175
+ f"# {project_name} Agent Contract\n\n"
176
+ f"{preamble}\n\n"
177
+ "## Authority\n\n"
178
+ "The source documents listed below are the product source of truth. Preserve explicit "
179
+ "requirement identifiers in code, tests, and review notes. When sources conflict, stop "
180
+ "and report the conflict instead of silently choosing an interpretation.\n\n"
181
+ f"{source_lines}\n\n"
182
+ f"{rendered_sections}\n\n"
183
+ "## Delivery Rules\n\n"
184
+ "- Keep changes within the scope above and preserve unrelated user changes.\n"
185
+ "- Prefer existing project patterns and dependencies before adding abstractions.\n"
186
+ "- Add tests for changed behavior and run the narrowest relevant verification suite.\n"
187
+ "- Map every implemented requirement ID to verification evidence in the final report.\n"
188
+ "- Report assumptions, unresolved ambiguities, skipped tests, and residual risks.\n"
189
+ "- Do not claim completion while required acceptance criteria are unverified.\n"
190
+ )