tracedojo 0.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.
- tracedojo/__init__.py +59 -0
- tracedojo/__main__.py +7 -0
- tracedojo/_json.py +211 -0
- tracedojo/cli.py +341 -0
- tracedojo/clock.py +226 -0
- tracedojo/compare.py +191 -0
- tracedojo/demo.py +77 -0
- tracedojo/errors.py +6 -0
- tracedojo/langgraph.py +127 -0
- tracedojo/privacy.py +88 -0
- tracedojo/py.typed +0 -0
- tracedojo/reports.py +36 -0
- tracedojo/runner.py +789 -0
- tracedojo/schema.py +856 -0
- tracedojo/signal.py +50 -0
- tracedojo/summary.py +66 -0
- tracedojo/templates/__init__.py +0 -0
- tracedojo/templates/booking/__init__.py +0 -0
- tracedojo/templates/booking/adapter.py +59 -0
- tracedojo/templates/booking/workflow.json +106 -0
- tracedojo/upload.py +146 -0
- tracedojo-0.1.0.dist-info/METADATA +212 -0
- tracedojo-0.1.0.dist-info/RECORD +27 -0
- tracedojo-0.1.0.dist-info/WHEEL +4 -0
- tracedojo-0.1.0.dist-info/entry_points.txt +2 -0
- tracedojo-0.1.0.dist-info/licenses/LICENSE +202 -0
- tracedojo-0.1.0.dist-info/licenses/NOTICE +5 -0
tracedojo/__init__.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Syed Arman
|
|
3
|
+
"""TraceDojo: controlled tool failures and state assertions for AI agents."""
|
|
4
|
+
|
|
5
|
+
from ._json import bounded_json, dumps, loads, stable_json
|
|
6
|
+
from .clock import WorkflowClock
|
|
7
|
+
from .errors import TracedojoError
|
|
8
|
+
from .runner import (
|
|
9
|
+
Adapter,
|
|
10
|
+
Agent,
|
|
11
|
+
SimpleAdapter,
|
|
12
|
+
Tool,
|
|
13
|
+
ToolContext,
|
|
14
|
+
TrialStopped,
|
|
15
|
+
WorkflowContext,
|
|
16
|
+
run_workflow,
|
|
17
|
+
run_workflow_sync,
|
|
18
|
+
tool,
|
|
19
|
+
)
|
|
20
|
+
from .schema import (
|
|
21
|
+
SchemaError,
|
|
22
|
+
evaluate_checks,
|
|
23
|
+
is_model_fault,
|
|
24
|
+
parse_batch,
|
|
25
|
+
parse_report,
|
|
26
|
+
parse_workflow,
|
|
27
|
+
workflow_exit_code,
|
|
28
|
+
)
|
|
29
|
+
from .signal import Cancelled, Signal
|
|
30
|
+
|
|
31
|
+
__version__ = "0.1.0"
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"Adapter",
|
|
35
|
+
"Agent",
|
|
36
|
+
"Cancelled",
|
|
37
|
+
"SchemaError",
|
|
38
|
+
"Signal",
|
|
39
|
+
"SimpleAdapter",
|
|
40
|
+
"Tool",
|
|
41
|
+
"ToolContext",
|
|
42
|
+
"TracedojoError",
|
|
43
|
+
"TrialStopped",
|
|
44
|
+
"WorkflowClock",
|
|
45
|
+
"WorkflowContext",
|
|
46
|
+
"bounded_json",
|
|
47
|
+
"dumps",
|
|
48
|
+
"evaluate_checks",
|
|
49
|
+
"is_model_fault",
|
|
50
|
+
"loads",
|
|
51
|
+
"parse_batch",
|
|
52
|
+
"parse_report",
|
|
53
|
+
"parse_workflow",
|
|
54
|
+
"run_workflow",
|
|
55
|
+
"run_workflow_sync",
|
|
56
|
+
"stable_json",
|
|
57
|
+
"tool",
|
|
58
|
+
"workflow_exit_code",
|
|
59
|
+
]
|
tracedojo/__main__.py
ADDED
tracedojo/_json.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Syed Arman
|
|
3
|
+
"""JSON helpers that serialize exactly like JavaScript's JSON.stringify.
|
|
4
|
+
|
|
5
|
+
Report fingerprints and imported report IDs are SHA-256 digests of JSON text, so
|
|
6
|
+
the Python SDK must produce the same bytes as the JavaScript SDK for the same
|
|
7
|
+
values: JavaScript number formatting, UTF-16 key ordering, and string escaping.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import math
|
|
14
|
+
import re
|
|
15
|
+
from decimal import Decimal
|
|
16
|
+
from typing import Any, Union
|
|
17
|
+
|
|
18
|
+
Json = Union[None, bool, int, float, str, list["Json"], dict[str, "Json"]]
|
|
19
|
+
State = dict[str, Json]
|
|
20
|
+
|
|
21
|
+
_SURROGATE = re.compile("[\ud800-\udfff]")
|
|
22
|
+
_INDEX_KEY = re.compile(r"(?:0|[1-9][0-9]*)\Z")
|
|
23
|
+
_SAFE = 2**53
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class JsonError(ValueError):
|
|
27
|
+
"""Raised when a value is not finite, acyclic, plain JSON within bounds."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def is_number(value: object) -> bool:
|
|
31
|
+
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def is_integer(value: object) -> bool:
|
|
35
|
+
"""Number.isInteger: integral floats count, booleans and non-finite values do not."""
|
|
36
|
+
if isinstance(value, bool):
|
|
37
|
+
return False
|
|
38
|
+
if isinstance(value, int):
|
|
39
|
+
return True
|
|
40
|
+
return isinstance(value, float) and math.isfinite(value) and value.is_integer()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def js_len(value: str) -> int:
|
|
44
|
+
"""String length in UTF-16 code units, as JavaScript and zod measure it."""
|
|
45
|
+
return len(value.encode("utf-16-le", "surrogatepass")) // 2
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _utf16_key(value: str) -> bytes:
|
|
49
|
+
return value.encode("utf-16-be", "surrogatepass")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def js_number(value: int | float) -> str:
|
|
53
|
+
"""Format a number like JavaScript's Number.prototype.toString."""
|
|
54
|
+
if isinstance(value, int):
|
|
55
|
+
if -_SAFE < value < _SAFE:
|
|
56
|
+
return str(value)
|
|
57
|
+
value = float(value)
|
|
58
|
+
if not math.isfinite(value):
|
|
59
|
+
return "null"
|
|
60
|
+
if value == 0:
|
|
61
|
+
return "0"
|
|
62
|
+
sign = "-" if value < 0 else ""
|
|
63
|
+
digits_tuple, exponent = Decimal(repr(abs(value))).as_tuple()[1:]
|
|
64
|
+
digits = "".join(map(str, digits_tuple)).lstrip("0")
|
|
65
|
+
stripped = digits.rstrip("0")
|
|
66
|
+
exponent = int(exponent) + len(digits) - len(stripped)
|
|
67
|
+
digits = stripped
|
|
68
|
+
k = len(digits)
|
|
69
|
+
n = k + exponent
|
|
70
|
+
if k <= n <= 21:
|
|
71
|
+
text = digits + "0" * (n - k)
|
|
72
|
+
elif 0 < n <= 21:
|
|
73
|
+
text = digits[:n] + "." + digits[n:]
|
|
74
|
+
elif -6 < n <= 0:
|
|
75
|
+
text = "0." + "0" * (-n) + digits
|
|
76
|
+
else:
|
|
77
|
+
e = n - 1
|
|
78
|
+
mark = "+" if e >= 0 else "-"
|
|
79
|
+
mantissa = digits if k == 1 else digits[0] + "." + digits[1:]
|
|
80
|
+
text = f"{mantissa}e{mark}{abs(e)}"
|
|
81
|
+
return sign + text
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def js_string(value: str) -> str:
|
|
85
|
+
"""Quote a string like JSON.stringify (well-formed: lone surrogates escaped)."""
|
|
86
|
+
text = json.dumps(value, ensure_ascii=False)
|
|
87
|
+
return _SURROGATE.sub(lambda m: "\\u%04x" % ord(m.group()), text)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _ordered(value: dict[str, Any]) -> list[tuple[str, Any]]:
|
|
91
|
+
# JavaScript enumerates array-index keys first, ascending, then insertion order.
|
|
92
|
+
index = [k for k in value if _INDEX_KEY.match(k) and int(k) < 2**32 - 1]
|
|
93
|
+
if not index:
|
|
94
|
+
return list(value.items())
|
|
95
|
+
rest = [k for k in value if not (_INDEX_KEY.match(k) and int(k) < 2**32 - 1)]
|
|
96
|
+
return [(k, value[k]) for k in sorted(index, key=int)] + [(k, value[k]) for k in rest]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _scalar(value: Any) -> str:
|
|
100
|
+
if value is None:
|
|
101
|
+
return "null"
|
|
102
|
+
if value is True:
|
|
103
|
+
return "true"
|
|
104
|
+
if value is False:
|
|
105
|
+
return "false"
|
|
106
|
+
if isinstance(value, str):
|
|
107
|
+
return js_string(value)
|
|
108
|
+
if is_number(value):
|
|
109
|
+
return js_number(value)
|
|
110
|
+
raise JsonError("Expected finite, acyclic JSON data.")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def stable_json(value: Any) -> str:
|
|
114
|
+
"""Port of the SDK's stableJson: keys sorted by UTF-16 code units."""
|
|
115
|
+
if isinstance(value, list):
|
|
116
|
+
return "[" + ",".join(stable_json(item) for item in value) + "]"
|
|
117
|
+
if isinstance(value, dict):
|
|
118
|
+
items = sorted(value.items(), key=lambda kv: _utf16_key(kv[0]))
|
|
119
|
+
return "{" + ",".join(f"{js_string(k)}:{stable_json(v)}" for k, v in items) + "}"
|
|
120
|
+
return _scalar(value)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def dumps(value: Any, indent: int | None = None) -> str:
|
|
124
|
+
"""JSON.stringify(value, null, indent)."""
|
|
125
|
+
if indent is None:
|
|
126
|
+
return _compact(value)
|
|
127
|
+
return _pretty(value, " " * indent, "")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _compact(value: Any) -> str:
|
|
131
|
+
if isinstance(value, list):
|
|
132
|
+
return "[" + ",".join(_compact(item) for item in value) + "]"
|
|
133
|
+
if isinstance(value, dict):
|
|
134
|
+
return "{" + ",".join(f"{js_string(k)}:{_compact(v)}" for k, v in _ordered(value)) + "}"
|
|
135
|
+
return _scalar(value)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _pretty(value: Any, step: str, current: str) -> str:
|
|
139
|
+
inner = current + step
|
|
140
|
+
if isinstance(value, list):
|
|
141
|
+
if not value:
|
|
142
|
+
return "[]"
|
|
143
|
+
body = (",\n" + inner).join(_pretty(item, step, inner) for item in value)
|
|
144
|
+
return f"[\n{inner}{body}\n{current}]"
|
|
145
|
+
if isinstance(value, dict):
|
|
146
|
+
if not value:
|
|
147
|
+
return "{}"
|
|
148
|
+
body = (",\n" + inner).join(
|
|
149
|
+
f"{js_string(k)}: {_pretty(v, step, inner)}" for k, v in _ordered(value)
|
|
150
|
+
)
|
|
151
|
+
return f"{{\n{inner}{body}\n{current}}}"
|
|
152
|
+
return _scalar(value)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def utf8_size(value: Any) -> int:
|
|
156
|
+
"""Byte length of JSON.stringify(value) encoded as UTF-8."""
|
|
157
|
+
return len(_compact(value).encode("utf-8"))
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _reject_constant(name: str) -> Any:
|
|
161
|
+
raise JsonError(f"Invalid JSON value {name}.")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def loads(text: str) -> Any:
|
|
165
|
+
"""JSON.parse equivalent: rejects NaN and Infinity literals."""
|
|
166
|
+
return json.loads(text, parse_constant=_reject_constant)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def bounded_json(value: Any, max_bytes: int = 5_000_000) -> None:
|
|
170
|
+
"""Validate before cloning, hashing, or schema checks of untrusted JSON."""
|
|
171
|
+
nodes = 0
|
|
172
|
+
path: set[int] = set()
|
|
173
|
+
|
|
174
|
+
def walk(item: Any, depth: int) -> None:
|
|
175
|
+
nonlocal nodes
|
|
176
|
+
nodes += 1
|
|
177
|
+
if nodes > 100000 or depth > 30:
|
|
178
|
+
raise JsonError("JSON is too deeply nested or too large.")
|
|
179
|
+
if item is None or isinstance(item, (str, bool)):
|
|
180
|
+
return
|
|
181
|
+
if is_number(item):
|
|
182
|
+
if isinstance(item, float) and not math.isfinite(item):
|
|
183
|
+
raise JsonError("Expected finite, acyclic JSON data.")
|
|
184
|
+
return
|
|
185
|
+
if not isinstance(item, (list, dict)) or id(item) in path:
|
|
186
|
+
if isinstance(item, (list, dict)):
|
|
187
|
+
raise JsonError("Expected finite, acyclic JSON data.")
|
|
188
|
+
raise JsonError("Expected plain JSON objects.")
|
|
189
|
+
path.add(id(item))
|
|
190
|
+
if isinstance(item, dict):
|
|
191
|
+
for key, child in item.items():
|
|
192
|
+
if not isinstance(key, str):
|
|
193
|
+
raise JsonError("Expected plain JSON objects.")
|
|
194
|
+
walk(child, depth + 1)
|
|
195
|
+
else:
|
|
196
|
+
for child in item:
|
|
197
|
+
walk(child, depth + 1)
|
|
198
|
+
path.discard(id(item))
|
|
199
|
+
|
|
200
|
+
walk(value, 0)
|
|
201
|
+
if utf8_size(value) > max_bytes:
|
|
202
|
+
raise JsonError("JSON exceeds the size limit.")
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def clone(value: Any) -> Any:
|
|
206
|
+
"""structuredClone for JSON values."""
|
|
207
|
+
if isinstance(value, dict):
|
|
208
|
+
return {k: clone(v) for k, v in value.items()}
|
|
209
|
+
if isinstance(value, list):
|
|
210
|
+
return [clone(v) for v in value]
|
|
211
|
+
return value
|
tracedojo/cli.py
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Syed Arman
|
|
3
|
+
"""``tracedojo`` command line: test, demo, compare, upload.
|
|
4
|
+
|
|
5
|
+
Flags, console output, never-overwrite behavior, and exit codes follow the
|
|
6
|
+
JavaScript CLI so CI scripts work the same in either language.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import asyncio
|
|
13
|
+
import importlib.util
|
|
14
|
+
import os
|
|
15
|
+
import signal as os_signal
|
|
16
|
+
import sys
|
|
17
|
+
import uuid
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from types import ModuleType
|
|
20
|
+
from typing import Any, Optional, Sequence
|
|
21
|
+
|
|
22
|
+
from ._json import bounded_json, dumps, loads
|
|
23
|
+
from .compare import compare_workflow_batches, comparison_exit_code, comparison_summary
|
|
24
|
+
from .demo import run_demo
|
|
25
|
+
from .errors import TracedojoError
|
|
26
|
+
from .privacy import sanitize_batch
|
|
27
|
+
from .runner import run_workflow
|
|
28
|
+
from .schema import is_commit_sha, parse_workflow, workflow_exit_code
|
|
29
|
+
from .signal import Signal
|
|
30
|
+
from .summary import workflow_summary
|
|
31
|
+
from .upload import upload_message, upload_workflow_reports
|
|
32
|
+
|
|
33
|
+
HELP = """TraceDojo for Python - test your agent against controlled tool failures
|
|
34
|
+
|
|
35
|
+
tracedojo demo
|
|
36
|
+
tracedojo test
|
|
37
|
+
tracedojo test --config dojo/workflow.json --adapter dojo/adapter.py --out dojo-report.json
|
|
38
|
+
tracedojo compare --base main-report.json --candidate pr-report.json --out comparison.json --summary comparison.md
|
|
39
|
+
tracedojo upload dojo-report.json --url https://tracedojo.com --project PROJECT_UUID
|
|
40
|
+
|
|
41
|
+
Uploads use TRACEDOJO_UPLOAD_TOKEN from your environment; credentials stay local.
|
|
42
|
+
|
|
43
|
+
test runs a no-fault control followed by every configured scenario.
|
|
44
|
+
--trials 1-20 independent attempts per scenario (default 1)
|
|
45
|
+
--out New JSON file; existing evidence is never overwritten
|
|
46
|
+
Default: .tracedojo/reports/<unique-id>.json
|
|
47
|
+
--summary Optional new Markdown summary file for CI
|
|
48
|
+
--commit Full lowercase Git SHA to label reports for trends
|
|
49
|
+
|
|
50
|
+
The adapter is a trusted local Python module (.py) that defines `tools` and
|
|
51
|
+
`create_agent`. It can access your environment and network. Simulated tools may
|
|
52
|
+
be async and must operate only on their state draft. Deadlines are cooperative,
|
|
53
|
+
not process isolation. Model API calls in your adapter may incur provider
|
|
54
|
+
charges; the shipped reference agent uses no API.
|
|
55
|
+
|
|
56
|
+
Reports use the same format as the JavaScript SDK (@tracedojo/sdk). The dashboard,
|
|
57
|
+
`compare`, and the CI gate accept reports from either SDK.
|
|
58
|
+
|
|
59
|
+
Exit codes: 0 pass, 1 failed checks, 2 invalid input, 3 incomplete/inconclusive.
|
|
60
|
+
demo exits 0 when it reproduces both the expected failure and the passing fix.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
_OPTIONS = (
|
|
64
|
+
"config",
|
|
65
|
+
"adapter",
|
|
66
|
+
"out",
|
|
67
|
+
"trials",
|
|
68
|
+
"summary",
|
|
69
|
+
"commit",
|
|
70
|
+
"url",
|
|
71
|
+
"project",
|
|
72
|
+
"base",
|
|
73
|
+
"candidate",
|
|
74
|
+
"base_sha",
|
|
75
|
+
"head_sha",
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _read_json(path: str | Path) -> Any:
|
|
80
|
+
file = Path(path)
|
|
81
|
+
if file.stat().st_size > 5_000_000:
|
|
82
|
+
raise TracedojoError("JSON exceeds the 5 MB limit.")
|
|
83
|
+
value = loads(file.read_text("utf-8"))
|
|
84
|
+
bounded_json(value)
|
|
85
|
+
return value
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _reserve(path: Path) -> int:
|
|
89
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
90
|
+
return os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _write(fd: int, text: str) -> None:
|
|
94
|
+
data = text.encode("utf-8")
|
|
95
|
+
while data:
|
|
96
|
+
written = os.write(fd, data)
|
|
97
|
+
data = data[written:]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def load_adapter(path: str | Path) -> ModuleType:
|
|
101
|
+
"""Import a trusted local adapter module that defines ``tools`` and ``create_agent``."""
|
|
102
|
+
file = Path(path).resolve()
|
|
103
|
+
name = f"tracedojo_adapter_{uuid.uuid4().hex}"
|
|
104
|
+
spec = importlib.util.spec_from_file_location(name, file)
|
|
105
|
+
if spec is None or spec.loader is None:
|
|
106
|
+
raise TracedojoError("Could not load the adapter. Check its syntax and installed dependencies.")
|
|
107
|
+
module = importlib.util.module_from_spec(spec)
|
|
108
|
+
sys.path.insert(0, str(file.parent))
|
|
109
|
+
try:
|
|
110
|
+
sys.modules[name] = module
|
|
111
|
+
# Compile from source every time. The bytecode cache is keyed on whole-second
|
|
112
|
+
# mtime and size, so an adapter edited right after a run could load stale code.
|
|
113
|
+
code = compile(file.read_bytes(), str(file), "exec", dont_inherit=True)
|
|
114
|
+
exec(code, module.__dict__)
|
|
115
|
+
except Exception:
|
|
116
|
+
sys.modules.pop(name, None)
|
|
117
|
+
raise TracedojoError(
|
|
118
|
+
"Could not load the adapter. Check its syntax and installed dependencies."
|
|
119
|
+
) from None
|
|
120
|
+
finally:
|
|
121
|
+
try:
|
|
122
|
+
sys.path.remove(str(file.parent))
|
|
123
|
+
except ValueError:
|
|
124
|
+
pass
|
|
125
|
+
return module
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _parser() -> argparse.ArgumentParser:
|
|
129
|
+
parser = argparse.ArgumentParser(prog="tracedojo", add_help=False, allow_abbrev=False)
|
|
130
|
+
parser.add_argument("positionals", nargs="*")
|
|
131
|
+
parser.add_argument("-h", "--help", action="store_true")
|
|
132
|
+
for option in _OPTIONS:
|
|
133
|
+
parser.add_argument("--" + option.replace("_", "-"), dest=option)
|
|
134
|
+
return parser
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _given(values: argparse.Namespace) -> set[str]:
|
|
138
|
+
return {key for key in _OPTIONS if getattr(values, key) is not None}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _install_cancel(signal: Signal) -> None:
|
|
142
|
+
loop = asyncio.get_running_loop()
|
|
143
|
+
for sig in (os_signal.SIGINT, os_signal.SIGTERM):
|
|
144
|
+
try:
|
|
145
|
+
loop.add_signal_handler(sig, signal.abort)
|
|
146
|
+
except (NotImplementedError, RuntimeError): # Windows event loops
|
|
147
|
+
pass
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _remove_cancel() -> None:
|
|
151
|
+
loop = asyncio.get_running_loop()
|
|
152
|
+
for sig in (os_signal.SIGINT, os_signal.SIGTERM):
|
|
153
|
+
try:
|
|
154
|
+
loop.remove_signal_handler(sig)
|
|
155
|
+
except (NotImplementedError, RuntimeError):
|
|
156
|
+
pass
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
async def _test(values: argparse.Namespace) -> int:
|
|
160
|
+
if values.commit is not None and not is_commit_sha(values.commit):
|
|
161
|
+
raise TracedojoError("--commit must be a full lowercase Git SHA.")
|
|
162
|
+
config = values.config or "dojo/workflow.json"
|
|
163
|
+
adapter_path = values.adapter or "dojo/adapter.py"
|
|
164
|
+
workflow = parse_workflow(_read_json(config))
|
|
165
|
+
try:
|
|
166
|
+
trials = int(values.trials) if values.trials is not None else 1
|
|
167
|
+
except ValueError:
|
|
168
|
+
trials = 0
|
|
169
|
+
if not 1 <= trials <= 20:
|
|
170
|
+
raise TracedojoError("--trials must be from 1 to 20.")
|
|
171
|
+
if not adapter_path.endswith(".py") or not Path(adapter_path).is_file():
|
|
172
|
+
raise TracedojoError("Use a trusted local .py adapter module.")
|
|
173
|
+
destination = Path(values.out or f".tracedojo/reports/{uuid.uuid4()}.json").resolve()
|
|
174
|
+
# Reserve every destination before invoking customer code or a paid model.
|
|
175
|
+
output = _reserve(destination)
|
|
176
|
+
summary_path = Path(values.summary).resolve() if values.summary else None
|
|
177
|
+
summary_fd: Optional[int] = None
|
|
178
|
+
saved = False
|
|
179
|
+
cancel = Signal()
|
|
180
|
+
_install_cancel(cancel)
|
|
181
|
+
try:
|
|
182
|
+
if summary_path:
|
|
183
|
+
summary_fd = _reserve(summary_path)
|
|
184
|
+
adapter = load_adapter(adapter_path)
|
|
185
|
+
batch = sanitize_batch(
|
|
186
|
+
await run_workflow(workflow, adapter, trials=trials, signal=cancel, commit_sha=values.commit)
|
|
187
|
+
)
|
|
188
|
+
_write(output, dumps(batch, 2) + "\n")
|
|
189
|
+
saved = True
|
|
190
|
+
if summary_fd is not None:
|
|
191
|
+
_write(summary_fd, workflow_summary(batch))
|
|
192
|
+
print(f"Control: {batch['baseline']['status']}")
|
|
193
|
+
for run in batch["runs"]:
|
|
194
|
+
print(f"{run['scenario']['title']}: {run['status']}")
|
|
195
|
+
for check in run["assertions"]:
|
|
196
|
+
if not check["passed"]:
|
|
197
|
+
print(f" {check['label']}: {check['detail']}")
|
|
198
|
+
if batch.get("skippedReason"):
|
|
199
|
+
print(batch["skippedReason"])
|
|
200
|
+
print(f"Completed {len(batch['runs'])}/{batch['planned']} fault trials. Report: {destination}")
|
|
201
|
+
return workflow_exit_code(batch)
|
|
202
|
+
finally:
|
|
203
|
+
_remove_cancel()
|
|
204
|
+
os.close(output)
|
|
205
|
+
if summary_fd is not None:
|
|
206
|
+
os.close(summary_fd)
|
|
207
|
+
if not saved:
|
|
208
|
+
destination.unlink(missing_ok=True)
|
|
209
|
+
if summary_fd is not None and summary_path:
|
|
210
|
+
summary_path.unlink(missing_ok=True)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _compare(values: argparse.Namespace) -> int:
|
|
214
|
+
if values.base_sha or values.head_sha:
|
|
215
|
+
if not is_commit_sha(values.base_sha or "") or not is_commit_sha(values.head_sha or ""):
|
|
216
|
+
raise TracedojoError("Provide both --base-sha and --head-sha as full commit hashes.")
|
|
217
|
+
|
|
218
|
+
def read_optional(path: str) -> Any:
|
|
219
|
+
try:
|
|
220
|
+
return _read_json(path)
|
|
221
|
+
except FileNotFoundError:
|
|
222
|
+
return None
|
|
223
|
+
|
|
224
|
+
result = compare_workflow_batches(read_optional(values.base), read_optional(values.candidate))
|
|
225
|
+
destination = Path(values.out or f".tracedojo/comparisons/{uuid.uuid4()}.json").resolve()
|
|
226
|
+
output = _reserve(destination)
|
|
227
|
+
summary_path = Path(values.summary).resolve() if values.summary else None
|
|
228
|
+
summary_fd: Optional[int] = None
|
|
229
|
+
saved = False
|
|
230
|
+
try:
|
|
231
|
+
if summary_path:
|
|
232
|
+
summary_fd = _reserve(summary_path)
|
|
233
|
+
document = dict(result)
|
|
234
|
+
if values.base_sha:
|
|
235
|
+
document["source"] = {"baseSha": values.base_sha, "headSha": values.head_sha}
|
|
236
|
+
_write(output, dumps(document, 2) + "\n")
|
|
237
|
+
if summary_fd is not None:
|
|
238
|
+
_write(summary_fd, comparison_summary(result))
|
|
239
|
+
saved = True
|
|
240
|
+
print(result["reason"])
|
|
241
|
+
return comparison_exit_code(result)
|
|
242
|
+
finally:
|
|
243
|
+
os.close(output)
|
|
244
|
+
if summary_fd is not None:
|
|
245
|
+
os.close(summary_fd)
|
|
246
|
+
if not saved:
|
|
247
|
+
destination.unlink(missing_ok=True)
|
|
248
|
+
if summary_fd is not None and summary_path:
|
|
249
|
+
summary_path.unlink(missing_ok=True)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
async def _demo(values: argparse.Namespace) -> int:
|
|
253
|
+
directory = Path(values.out or f".tracedojo/demo-{uuid.uuid4()}").resolve()
|
|
254
|
+
directory.parent.mkdir(parents=True, exist_ok=True)
|
|
255
|
+
before, after = await run_demo(directory)
|
|
256
|
+
print("A booking succeeded. Its confirmation timed out. The agent retried.")
|
|
257
|
+
print(
|
|
258
|
+
f"Before: {before['runs'][0]['status']} — {before['runs'][0]['metrics']['mutations']} "
|
|
259
|
+
"committed writes; duplicate booking."
|
|
260
|
+
)
|
|
261
|
+
print(
|
|
262
|
+
f"After: {after['runs'][0]['status']} — {after['runs'][0]['metrics']['mutations']} "
|
|
263
|
+
"committed write; the retry reused the original booking."
|
|
264
|
+
)
|
|
265
|
+
print("Both no-fault controls passed. Scripted example; no model calls.")
|
|
266
|
+
print(
|
|
267
|
+
f"Open before.json and after.json from {directory} in a project at https://tracedojo.com "
|
|
268
|
+
"(sign-in required), using Workflows → Preview report. Preview does not save reports.\n"
|
|
269
|
+
"Local dashboard and upload instructions: https://tracedojo.com/docs#inspect-and-save-reports"
|
|
270
|
+
)
|
|
271
|
+
return 0
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _run(argv: Sequence[str]) -> int:
|
|
275
|
+
parser = _parser()
|
|
276
|
+
try:
|
|
277
|
+
values = parser.parse_args(list(argv))
|
|
278
|
+
except SystemExit:
|
|
279
|
+
raise TracedojoError("Unsupported arguments. See --help.") from None
|
|
280
|
+
positionals = values.positionals
|
|
281
|
+
command = positionals[0] if positionals else None
|
|
282
|
+
if not command or values.help:
|
|
283
|
+
print(HELP)
|
|
284
|
+
return 0
|
|
285
|
+
given = _given(values)
|
|
286
|
+
if command == "upload":
|
|
287
|
+
if len(positionals) != 2 or given - {"url", "project"}:
|
|
288
|
+
raise TracedojoError("upload takes one report file and --url/--project.")
|
|
289
|
+
receipt = upload_workflow_reports(
|
|
290
|
+
_read_json(positionals[1]),
|
|
291
|
+
url=values.url or os.environ.get("TRACEDOJO_URL", ""),
|
|
292
|
+
project=values.project or os.environ.get("TRACEDOJO_PROJECT_ID", ""),
|
|
293
|
+
token=os.environ.get("TRACEDOJO_UPLOAD_TOKEN", ""),
|
|
294
|
+
)
|
|
295
|
+
print(upload_message(receipt))
|
|
296
|
+
return 0
|
|
297
|
+
if command == "compare":
|
|
298
|
+
allowed = {"base", "candidate", "out", "summary", "base_sha", "head_sha"}
|
|
299
|
+
if len(positionals) != 1 or not values.base or not values.candidate or given - allowed:
|
|
300
|
+
raise TracedojoError("compare requires --base and --candidate report files.")
|
|
301
|
+
return _compare(values)
|
|
302
|
+
allowed_by_command = {
|
|
303
|
+
"test": {"config", "adapter", "out", "trials", "summary", "commit"},
|
|
304
|
+
"demo": {"out"},
|
|
305
|
+
}
|
|
306
|
+
if command not in allowed_by_command:
|
|
307
|
+
raise TracedojoError("Unknown command. See --help.")
|
|
308
|
+
if given - allowed_by_command[command] or len(positionals) != 1:
|
|
309
|
+
raise TracedojoError("Unsupported arguments. See --help.")
|
|
310
|
+
runner = _test if command == "test" else _demo
|
|
311
|
+
return asyncio.run(runner(values))
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
315
|
+
try:
|
|
316
|
+
code = _run(sys.argv[1:] if argv is None else argv)
|
|
317
|
+
except TracedojoError as error:
|
|
318
|
+
print(str(error), file=sys.stderr)
|
|
319
|
+
code = 2
|
|
320
|
+
except FileExistsError as error:
|
|
321
|
+
print(f"Refusing to overwrite existing evidence: {error.filename}", file=sys.stderr)
|
|
322
|
+
code = 2
|
|
323
|
+
except FileNotFoundError as error:
|
|
324
|
+
print(f"File not found: {error.filename}", file=sys.stderr)
|
|
325
|
+
code = 2
|
|
326
|
+
except Exception:
|
|
327
|
+
# Schema errors can contain customer inputs; never print them.
|
|
328
|
+
print(
|
|
329
|
+
"Invalid input or output. Check the file paths, JSON, and workflow contract.",
|
|
330
|
+
file=sys.stderr,
|
|
331
|
+
)
|
|
332
|
+
code = 2
|
|
333
|
+
return code
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def entrypoint() -> None:
|
|
337
|
+
sys.exit(main())
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
if __name__ == "__main__":
|
|
341
|
+
entrypoint()
|