scyvera 1.1.0__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.
scyvera/__init__.py ADDED
@@ -0,0 +1,23 @@
1
+ from .builder import AgentIdentity, Contract, SystemIdentity
2
+ from .linter import LintResult, LintWarning, lint_contract
3
+ from .validator import (
4
+ SCHEMA_V1_PATH,
5
+ SCHEMA_V1_1_PATH,
6
+ ValidationError,
7
+ ValidationResult,
8
+ validate_contract,
9
+ )
10
+
11
+ __all__ = [
12
+ "AgentIdentity",
13
+ "Contract",
14
+ "LintResult",
15
+ "LintWarning",
16
+ "SCHEMA_V1_PATH",
17
+ "SCHEMA_V1_1_PATH",
18
+ "SystemIdentity",
19
+ "ValidationError",
20
+ "ValidationResult",
21
+ "lint_contract",
22
+ "validate_contract",
23
+ ]
scyvera/builder.py ADDED
@@ -0,0 +1,296 @@
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass
3
+ from pathlib import Path
4
+ from typing import Any
5
+ import tempfile
6
+ import yaml
7
+
8
+ from .validator import validate_contract, ValidationResult
9
+
10
+
11
+ @dataclass
12
+ class SystemIdentity:
13
+ name: str
14
+ purpose: str | None = None
15
+ version: str | None = None
16
+
17
+ def to_dict(self) -> dict[str, Any]:
18
+ data: dict[str, Any] = {"name": self.name}
19
+ if self.purpose is not None:
20
+ data["purpose"] = self.purpose
21
+ if self.version is not None:
22
+ data["version"] = self.version
23
+ return data
24
+
25
+
26
+ # Backward-compatibility alias
27
+ AgentIdentity = SystemIdentity
28
+
29
+
30
+ class Contract:
31
+ """
32
+ High-level, type-safe programmatic builder for Agent Contracts.
33
+ Allows non-YAML experts to define, serialize, and validate Agent Contracts in Python.
34
+ """
35
+ def __init__(
36
+ self,
37
+ name: str,
38
+ purpose: str | None = None,
39
+ version: float | str = 1.1,
40
+ system_version: str | None = None,
41
+ ) -> None:
42
+ self.version = version
43
+ self.system = SystemIdentity(name=name, purpose=purpose, version=system_version)
44
+ self.agent = self.system # Backward-compatibility property alias
45
+ self.domain: str | None = None
46
+ self.capabilities: list[dict[str, Any] | str] = []
47
+ self.resources: list[dict[str, Any] | str] = []
48
+ self.inputs: list[dict[str, Any] | str] = []
49
+ self.outputs: list[dict[str, Any] | str] = []
50
+ self.permissions: list[dict[str, Any]] = []
51
+ self.constraints: list[dict[str, Any]] = []
52
+ self.side_effects: list[dict[str, Any] | str] = []
53
+ self.approvals: list[dict[str, Any] | str] = []
54
+ self.dependencies: list[dict[str, Any] | str] = []
55
+ self.state: dict[str, Any] | str | None = None
56
+ self.recovery: dict[str, Any] | str | None = None
57
+ self.replay: dict[str, Any] | str | None = None
58
+ self.observability: dict[str, Any] | list[str] | str | None = None
59
+ self.artifacts: list[dict[str, Any]] = []
60
+ self.security: dict[str, Any] | None = None
61
+ self.risk: dict[str, Any] | None = None
62
+ self.implementation: dict[str, Any] | None = None
63
+
64
+ def set_domain(self, domain: str) -> Contract:
65
+ self.domain = domain
66
+ return self
67
+
68
+ def add_capability(self, name: str, description: str | None = None) -> Contract:
69
+ if description:
70
+ self.capabilities.append({"name": name, "description": description})
71
+ else:
72
+ self.capabilities.append(name)
73
+ return self
74
+
75
+ def add_resource(self, name: str, type: str | None = None, access: str | None = None) -> Contract:
76
+ res: dict[str, Any] = {"name": name}
77
+ if type:
78
+ res["type"] = type
79
+ if access:
80
+ res["access"] = access
81
+ self.resources.append(res)
82
+ return self
83
+
84
+ def add_input(self, name: str, type: str | None = None, required: bool = True) -> Contract:
85
+ inp: dict[str, Any] = {"name": name, "required": required}
86
+ if type:
87
+ inp["type"] = type
88
+ self.inputs.append(inp)
89
+ return self
90
+
91
+ def add_output(self, name: str, type: str | None = None) -> Contract:
92
+ out: dict[str, Any] = {"name": name}
93
+ if type:
94
+ out["type"] = type
95
+ self.outputs.append(out)
96
+ return self
97
+
98
+ def add_permission(self, resource: str, actions: list[str], scope: str | None = None) -> Contract:
99
+ perm: dict[str, Any] = {"resource": resource, "actions": actions}
100
+ if scope:
101
+ perm["scope"] = scope
102
+ self.permissions.append(perm)
103
+ return self
104
+
105
+ def add_constraint(
106
+ self,
107
+ type: str,
108
+ maximum: float | int | None = None,
109
+ minimum: float | int | None = None,
110
+ currency: str | None = None,
111
+ unit: str | None = None,
112
+ allowed: list[str] | None = None,
113
+ description: str | None = None,
114
+ ) -> Contract:
115
+ c: dict[str, Any] = {"type": type}
116
+ if maximum is not None:
117
+ c["maximum"] = maximum
118
+ if minimum is not None:
119
+ c["minimum"] = minimum
120
+ if currency is not None:
121
+ c["currency"] = currency
122
+ if unit is not None:
123
+ c["unit"] = unit
124
+ if allowed is not None:
125
+ c["allowed"] = allowed
126
+ if description is not None:
127
+ c["description"] = description
128
+ self.constraints.append(c)
129
+ return self
130
+
131
+ def add_side_effect(self, type: str, resource: str | None = None, description: str | None = None) -> Contract:
132
+ se: dict[str, Any] = {"type": type}
133
+ if resource:
134
+ se["resource"] = resource
135
+ if description:
136
+ se["description"] = description
137
+ self.side_effects.append(se)
138
+ return self
139
+
140
+ def add_approval(self, action: str, required: bool = True, approver: str | None = None, condition: str | None = None) -> Contract:
141
+ app: dict[str, Any] = {"action": action, "required": required}
142
+ if approver:
143
+ app["approver"] = approver
144
+ if condition:
145
+ app["condition"] = condition
146
+ self.approvals.append(app)
147
+ return self
148
+
149
+ def add_dependency(self, name: str, type: str | None = None, required: bool = True) -> Contract:
150
+ dep: dict[str, Any] = {"name": name, "required": required}
151
+ if type:
152
+ dep["type"] = type
153
+ self.dependencies.append(dep)
154
+ return self
155
+
156
+ def set_state(self, persistence: str, scope: str | None = None, storage: str | None = None) -> Contract:
157
+ st: dict[str, Any] = {"persistence": persistence}
158
+ if scope:
159
+ st["scope"] = scope
160
+ if storage:
161
+ st["storage"] = storage
162
+ self.state = st
163
+ return self
164
+
165
+ def set_recovery(self, strategy: str, details: str | None = None) -> Contract:
166
+ rec: dict[str, Any] = {"strategy": strategy}
167
+ if details:
168
+ rec["details"] = details
169
+ self.recovery = rec
170
+ return self
171
+
172
+ def set_replay(self, mode: str, details: str | None = None) -> Contract:
173
+ rep: dict[str, Any] = {"mode": mode}
174
+ if details:
175
+ rep["details"] = details
176
+ self.replay = rep
177
+ return self
178
+
179
+ def set_observability(self, level: str, sinks: list[str] | None = None) -> Contract:
180
+ obs: dict[str, Any] = {"level": level}
181
+ if sinks:
182
+ obs["sinks"] = sinks
183
+ self.observability = obs
184
+ return self
185
+
186
+ def add_artifact(
187
+ self,
188
+ name: str,
189
+ type: str,
190
+ source: str | None = None,
191
+ integrity_required: bool = False,
192
+ provenance_required: bool = False,
193
+ ) -> Contract:
194
+ art: dict[str, Any] = {
195
+ "name": name,
196
+ "type": type,
197
+ "integrity_required": integrity_required,
198
+ "provenance_required": provenance_required,
199
+ }
200
+ if source:
201
+ art["source"] = source
202
+ self.artifacts.append(art)
203
+ return self
204
+
205
+ def set_risk(self, level: str, category: str | None = None) -> Contract:
206
+ r: dict[str, Any] = {"level": level}
207
+ if category:
208
+ r["category"] = category
209
+ self.risk = r
210
+ return self
211
+
212
+ def set_implementation(
213
+ self,
214
+ framework: str | None = None,
215
+ runtime: str | None = None,
216
+ language: str | None = None,
217
+ repository: str | None = None,
218
+ ) -> Contract:
219
+ impl: dict[str, Any] = {}
220
+ if framework:
221
+ impl["framework"] = framework
222
+ if runtime:
223
+ impl["runtime"] = runtime
224
+ if language:
225
+ impl["language"] = language
226
+ if repository:
227
+ impl["repository"] = repository
228
+ self.implementation = impl
229
+ return self
230
+
231
+ def to_dict(self) -> dict[str, Any]:
232
+ data: dict[str, Any] = {"version": self.version}
233
+
234
+ if self.version in (1.1, "1.1"):
235
+ data["system"] = self.system.to_dict()
236
+ else:
237
+ data["agent"] = self.agent.to_dict()
238
+
239
+ if self.domain:
240
+ data["domain"] = self.domain
241
+ if self.capabilities:
242
+ data["capabilities"] = self.capabilities
243
+ if self.resources:
244
+ data["resources"] = self.resources
245
+ if self.inputs:
246
+ data["inputs"] = self.inputs
247
+ if self.outputs:
248
+ data["outputs"] = self.outputs
249
+ if self.permissions:
250
+ data["permissions"] = self.permissions
251
+ if self.constraints:
252
+ data["constraints"] = self.constraints
253
+ if self.side_effects:
254
+ data["side_effects"] = self.side_effects
255
+ if self.approvals:
256
+ data["approvals"] = self.approvals
257
+ if self.dependencies:
258
+ data["dependencies"] = self.dependencies
259
+ if self.state is not None:
260
+ data["state"] = self.state
261
+ if self.recovery is not None:
262
+ data["recovery"] = self.recovery
263
+ if self.replay is not None:
264
+ data["replay"] = self.replay
265
+ if self.observability is not None:
266
+ data["observability"] = self.observability
267
+ if self.artifacts:
268
+ data["artifacts"] = self.artifacts
269
+ if self.security is not None:
270
+ data["security"] = self.security
271
+ if self.risk is not None:
272
+ data["risk"] = self.risk
273
+ if self.implementation is not None:
274
+ data["implementation"] = self.implementation
275
+ return data
276
+
277
+ def to_yaml(self) -> str:
278
+ return yaml.dump(self.to_dict(), sort_keys=False)
279
+
280
+ def save(self, path: str | Path) -> Path:
281
+ p = Path(path)
282
+ p.parent.mkdir(parents=True, exist_ok=True)
283
+ with p.open("w", encoding="utf-8") as f:
284
+ yaml.dump(self.to_dict(), f, sort_keys=False)
285
+ return p
286
+
287
+ def validate(self) -> ValidationResult:
288
+ with tempfile.NamedTemporaryFile("w", suffix=".yaml", delete=False, encoding="utf-8") as tmp:
289
+ tmp_path = Path(tmp.name)
290
+ yaml.dump(self.to_dict(), tmp, sort_keys=False)
291
+
292
+ try:
293
+ return validate_contract(tmp_path)
294
+ finally:
295
+ if tmp_path.exists():
296
+ tmp_path.unlink()
scyvera/cli.py ADDED
@@ -0,0 +1,290 @@
1
+ import argparse
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ import yaml
6
+
7
+ from .linter import lint_contract
8
+ from .validator import validate_contract
9
+
10
+
11
+ def build_parser() -> argparse.ArgumentParser:
12
+ parser = argparse.ArgumentParser(
13
+ prog="scyvera",
14
+ description="Validate and manage Agent Contract files.",
15
+ )
16
+
17
+ subparsers = parser.add_subparsers(
18
+ dest="command",
19
+ required=True,
20
+ )
21
+
22
+ # validate subcommand
23
+ validate_parser = subparsers.add_parser(
24
+ "validate",
25
+ help="Validate an Agent Contract against its specification schema.",
26
+ )
27
+
28
+ validate_parser.add_argument(
29
+ "contract",
30
+ type=Path,
31
+ help="Path to contract.yaml",
32
+ )
33
+
34
+ validate_parser.add_argument(
35
+ "--schema",
36
+ type=Path,
37
+ default=None,
38
+ help="Path to custom JSON Schema file",
39
+ )
40
+
41
+ # lint subcommand
42
+ lint_parser = subparsers.add_parser(
43
+ "lint",
44
+ help="Perform Tier 2 semantic analysis on an Agent Contract.",
45
+ )
46
+
47
+ lint_parser.add_argument(
48
+ "contract",
49
+ type=Path,
50
+ help="Path to contract.yaml",
51
+ )
52
+
53
+ # init subcommand
54
+ init_parser = subparsers.add_parser(
55
+ "init",
56
+ help="Initialize a new Agent Contract starter template.",
57
+ )
58
+
59
+ init_parser.add_argument(
60
+ "output",
61
+ type=Path,
62
+ nargs="?",
63
+ default=Path("contract.yaml"),
64
+ help="Target output path (default: contract.yaml)",
65
+ )
66
+
67
+ init_parser.add_argument(
68
+ "--name",
69
+ type=str,
70
+ default="My System",
71
+ help="System or agent name",
72
+ )
73
+
74
+ init_parser.add_argument(
75
+ "--domain",
76
+ type=str,
77
+ default=None,
78
+ help="Operational domain (e.g. healthcare, finance, education, research, software, business)",
79
+ )
80
+
81
+ init_parser.add_argument(
82
+ "--spec-version",
83
+ type=str,
84
+ choices=["1.1", "1"],
85
+ default="1.1",
86
+ help="Specification version (default: 1.1)",
87
+ )
88
+
89
+ init_parser.add_argument(
90
+ "--force",
91
+ action="store_true",
92
+ help="Overwrite target file if it already exists",
93
+ )
94
+
95
+ init_parser.add_argument(
96
+ "-i", "--interactive",
97
+ action="store_true",
98
+ help="Prompt interactively for contract details",
99
+ )
100
+
101
+ return parser
102
+
103
+
104
+ def run_validate(contract_path: Path, schema_path: Path | None = None) -> int:
105
+ try:
106
+ result = validate_contract(contract_path, schema_path=schema_path)
107
+
108
+ except FileNotFoundError:
109
+ print(f"ERROR {contract_path}")
110
+ print(" file not found")
111
+ return 2
112
+
113
+ except PermissionError:
114
+ print(f"ERROR {contract_path}")
115
+ print(" permission denied")
116
+ return 2
117
+
118
+ except yaml.YAMLError as error:
119
+ print(f"FAIL {contract_path}")
120
+ print(f" invalid YAML: {error}")
121
+ return 1
122
+
123
+ if result.valid:
124
+ print(f"PASS {contract_path}")
125
+ return 0
126
+
127
+ print(f"FAIL {contract_path}")
128
+
129
+ for error in result.errors:
130
+ if error.path:
131
+ print(f" {error.path}: {error.message}")
132
+ else:
133
+ print(f" {error.message}")
134
+
135
+ return 1
136
+
137
+
138
+ def run_init(
139
+ output_path: Path,
140
+ name: str = "My System",
141
+ domain: str | None = None,
142
+ spec_version: str = "1.1",
143
+ force: bool = False,
144
+ interactive: bool = False,
145
+ ) -> int:
146
+ if output_path.exists() and not force:
147
+ print(f"ERROR {output_path} already exists. Use --force to overwrite.")
148
+ return 1
149
+
150
+ purpose = "Operational contract for intelligent/automated system"
151
+ risk_level = "low"
152
+
153
+ if interactive:
154
+ try:
155
+ user_name = input(f"System Name [{name}]: ").strip()
156
+ if user_name:
157
+ name = user_name
158
+ user_domain = input("Domain (e.g. healthcare, finance, education, research, software, business): ").strip()
159
+ if user_domain:
160
+ domain = user_domain
161
+ user_purpose = input("Purpose/Description: ").strip()
162
+ if user_purpose:
163
+ purpose = user_purpose
164
+ user_risk = input("Risk Level (low/medium/high/critical) [low]: ").strip()
165
+ if user_risk in ("low", "medium", "high", "critical"):
166
+ risk_level = user_risk
167
+ except (KeyboardInterrupt, EOFError):
168
+ print("\nCancelled.")
169
+ return 1
170
+
171
+ if spec_version == "1.1":
172
+ contract_data: dict[str, Any] = {
173
+ "version": 1.1,
174
+ "system": {
175
+ "name": name,
176
+ "purpose": purpose,
177
+ "version": "1.0.0",
178
+ },
179
+ }
180
+ if domain:
181
+ contract_data["domain"] = domain
182
+
183
+ contract_data.update({
184
+ "capabilities": [
185
+ {"name": "example_capability", "description": "Example capability claim"}
186
+ ],
187
+ "resources": [
188
+ {"name": "example_resource", "type": "dataset", "access": "read"}
189
+ ],
190
+ "inputs": [
191
+ {"name": "example_input", "type": "string", "required": True}
192
+ ],
193
+ "outputs": [
194
+ {"name": "example_output", "type": "document"}
195
+ ],
196
+ "permissions": [
197
+ {"resource": "example_resource", "actions": ["read"]}
198
+ ],
199
+ "side_effects": [],
200
+ "approvals": [],
201
+ "dependencies": [],
202
+ "state": {"persistence": "session"},
203
+ "recovery": {"strategy": "retry"},
204
+ "replay": {"mode": "idempotent"},
205
+ "observability": {"level": "basic"},
206
+ "risk": {"level": risk_level},
207
+ })
208
+ else:
209
+ contract_data = {
210
+ "version": 1,
211
+ "workflow": name,
212
+ "inputs": ["example_input"],
213
+ "outputs": ["example_output"],
214
+ "permissions": [{"example_resource": "read"}],
215
+ "side_effects": [],
216
+ "approval_points": [],
217
+ "recovery_strategy": "retry",
218
+ "replay_semantics": "idempotent",
219
+ "dependencies": [],
220
+ "state": "session",
221
+ "observability": ["basic_logs"],
222
+ }
223
+
224
+ output_path.parent.mkdir(parents=True, exist_ok=True)
225
+ with output_path.open("w", encoding="utf-8") as f:
226
+ yaml.dump(contract_data, f, sort_keys=False)
227
+
228
+ print(f"CREATED {output_path} (spec version {spec_version})")
229
+ return 0
230
+
231
+
232
+ def run_lint(contract_path: Path) -> int:
233
+ try:
234
+ result = lint_contract(contract_path)
235
+ except FileNotFoundError:
236
+ print(f"ERROR {contract_path}")
237
+ print(" file not found")
238
+ return 2
239
+ except PermissionError:
240
+ print(f"ERROR {contract_path}")
241
+ print(" permission denied")
242
+ return 2
243
+ except yaml.YAMLError as error:
244
+ print(f"FAIL {contract_path}")
245
+ print(f" invalid YAML: {error}")
246
+ return 1
247
+
248
+ if not result.valid_structure:
249
+ print(f"FAIL {contract_path} (structural validation failed)")
250
+ for w in result.warnings:
251
+ print(f" [{w.rule_id}] {w.title}: {w.message}")
252
+ return 1
253
+
254
+ if not result.warnings:
255
+ print(f"PASS {contract_path} (0 semantic warnings)")
256
+ return 0
257
+
258
+ print(f"WARN {contract_path} ({len(result.warnings)} semantic warning(s))")
259
+ for w in result.warnings:
260
+ print(f" [{w.rule_id}] {w.title}: {w.message}")
261
+
262
+ return 0
263
+
264
+
265
+ def main() -> int:
266
+ parser = build_parser()
267
+ args = parser.parse_args()
268
+
269
+ if args.command == "validate":
270
+ return run_validate(args.contract, schema_path=args.schema)
271
+
272
+ if args.command == "lint":
273
+ return run_lint(args.contract)
274
+
275
+ if args.command == "init":
276
+ return run_init(
277
+ output_path=args.output,
278
+ name=args.name,
279
+ domain=args.domain,
280
+ spec_version=args.spec_version,
281
+ force=args.force,
282
+ interactive=args.interactive,
283
+ )
284
+
285
+ parser.error(f"unknown command: {args.command}")
286
+ return 2
287
+
288
+
289
+ if __name__ == "__main__":
290
+ sys.exit(main())