docassemble-simulator 26.10.9__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 (33) hide show
  1. docassemble_simulator/__init__.py +24 -0
  2. docassemble_simulator/__main__.py +4 -0
  3. docassemble_simulator/_artifacts.py +273 -0
  4. docassemble_simulator/_compat.py +27 -0
  5. docassemble_simulator/_diagnostics.py +238 -0
  6. docassemble_simulator/_environment.py +27 -0
  7. docassemble_simulator/_files.py +103 -0
  8. docassemble_simulator/_outcomes.py +91 -0
  9. docassemble_simulator/_preload.py +181 -0
  10. docassemble_simulator/_runtime.py +1797 -0
  11. docassemble_simulator/_screen_actions.py +119 -0
  12. docassemble_simulator/_serialization.py +80 -0
  13. docassemble_simulator/_submission.py +1172 -0
  14. docassemble_simulator/_timeouts.py +7 -0
  15. docassemble_simulator/bootstrap.py +52 -0
  16. docassemble_simulator/catalog.py +1107 -0
  17. docassemble_simulator/cli.py +3163 -0
  18. docassemble_simulator/compatibility.py +290 -0
  19. docassemble_simulator/config.py +437 -0
  20. docassemble_simulator/demo_corpus.py +1655 -0
  21. docassemble_simulator/describe.py +804 -0
  22. docassemble_simulator/detect.py +41 -0
  23. docassemble_simulator/execution.py +2578 -0
  24. docassemble_simulator/preflight.py +199 -0
  25. docassemble_simulator/render.py +522 -0
  26. docassemble_simulator/runner.py +675 -0
  27. docassemble_simulator/trace.py +1331 -0
  28. docassemble_simulator/worker.py +565 -0
  29. docassemble_simulator-26.10.9.dist-info/METADATA +1129 -0
  30. docassemble_simulator-26.10.9.dist-info/RECORD +33 -0
  31. docassemble_simulator-26.10.9.dist-info/WHEEL +4 -0
  32. docassemble_simulator-26.10.9.dist-info/entry_points.txt +4 -0
  33. docassemble_simulator-26.10.9.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,24 @@
1
+ """Local docassemble interview simulator.
2
+
3
+ Loads a docassemble package's interview in-process (no server), runs the real
4
+ seek/assemble machinery, and exposes a CLI that humans and AI agents can use
5
+ to step through screens, answer fields, and debug variable-resolution errors.
6
+ """
7
+
8
+ from docassemble_simulator.cli import main
9
+ from docassemble_simulator.execution import ExecutionScope
10
+ from docassemble_simulator.runner import (
11
+ Runner,
12
+ RunnerError,
13
+ RunnerResponse,
14
+ SimulatorRunner,
15
+ )
16
+
17
+ __all__ = [
18
+ "ExecutionScope",
19
+ "Runner",
20
+ "RunnerError",
21
+ "RunnerResponse",
22
+ "SimulatorRunner",
23
+ "main",
24
+ ]
@@ -0,0 +1,4 @@
1
+ from docassemble_simulator.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,273 @@
1
+ """Durable simulator-owned numbered files and published attachment capture."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import mimetypes
7
+ import re
8
+ import shutil
9
+ import xml.etree.ElementTree as ET
10
+ from contextlib import contextmanager
11
+ from contextvars import ContextVar
12
+ from pathlib import Path
13
+ from typing import Any
14
+ from zipfile import BadZipFile, ZipFile
15
+
16
+ from docassemble_simulator._diagnostics import Diagnostic
17
+ from docassemble_simulator._files import atomic_replace, flock
18
+ from docassemble_simulator._outcomes import PublishedAttachment
19
+
20
+ _PUBLISHED: ContextVar[list[PublishedAttachment] | None] = ContextVar(
21
+ "docassemble_simulator_published_attachments", default=None
22
+ )
23
+ _ACTIVE_REGISTRY: ContextVar[LocalFileRegistry | None] = ContextVar(
24
+ "docassemble_simulator_file_registry", default=None
25
+ )
26
+
27
+
28
+ @contextmanager
29
+ def capture_published_attachments():
30
+ attachments: list[PublishedAttachment] = []
31
+ token = _PUBLISHED.set(attachments)
32
+ try:
33
+ yield attachments
34
+ finally:
35
+ _PUBLISHED.reset(token)
36
+
37
+
38
+ class LocalFileRegistry:
39
+ """Persist docassemble numbered files beneath one simulator workspace."""
40
+
41
+ def __init__(self, directory: str | Path):
42
+ self.directory = Path(directory).resolve()
43
+ self.index_path = self.directory / "index.json"
44
+ self.lock_path = self.directory / "index.lock"
45
+
46
+ def save(self, filename: str, source: str | Path) -> tuple[int, str, str]:
47
+ source_path = Path(source)
48
+ suffix = Path(filename).suffix or source_path.suffix
49
+ extension = suffix.lstrip(".").lower()
50
+ mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
51
+ self.directory.mkdir(parents=True, exist_ok=True)
52
+ with flock(self.lock_path):
53
+ index = self._read_index()
54
+ number = int(index.get("next", 1))
55
+ index["next"] = number + 1
56
+ destination = self.directory / f"dasimulator-{number}{suffix}"
57
+ atomic_replace(
58
+ destination,
59
+ lambda temporary: shutil.copyfile(source_path, temporary),
60
+ lock_destination=True,
61
+ )
62
+ files = index.setdefault("files", {})
63
+ files[str(number)] = {
64
+ "path": str(destination),
65
+ "fullpath": str(destination),
66
+ "filename": Path(filename).name,
67
+ "extension": extension,
68
+ "mimetype": mimetype,
69
+ "persistent": False,
70
+ "private": True,
71
+ }
72
+ self._write_index(index)
73
+ return number, extension, mimetype
74
+
75
+ def reserve(self, filename: str, extension: str | None = None) -> tuple[int, str]:
76
+ """Allocate a number and path for a file the caller will create locally.
77
+
78
+ docassemble's ``DAFile.initialize()`` allocates a new numbered file
79
+ through the server before its content is written. The simulator backs
80
+ that seam with this registry so generated DOCX bundles, merged
81
+ documents, and ZIP archives become ordinary published files once the
82
+ caller writes to the reserved path.
83
+ """
84
+ suffix = Path(filename).suffix or (f".{extension}" if extension else "")
85
+ resolved_extension = (extension or suffix.lstrip(".")).lower()
86
+ mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
87
+ self.directory.mkdir(parents=True, exist_ok=True)
88
+ with flock(self.lock_path):
89
+ index = self._read_index()
90
+ number = int(index.get("next", 1))
91
+ index["next"] = number + 1
92
+ destination = self.directory / f"dasimulator-{number}{suffix}"
93
+ index.setdefault("files", {})[str(number)] = {
94
+ "path": str(destination),
95
+ "fullpath": str(destination),
96
+ "filename": Path(filename).name,
97
+ "extension": resolved_extension,
98
+ "mimetype": mimetype,
99
+ "persistent": False,
100
+ "private": True,
101
+ }
102
+ self._write_index(index)
103
+ return number, str(destination)
104
+
105
+ def remove(self, file_number: int) -> None:
106
+ """Forget a numbered file and delete its local artifact if present."""
107
+ with flock(self.lock_path):
108
+ index = self._read_index()
109
+ entry = index.get("files", {}).pop(str(file_number), None)
110
+ self._write_index(index)
111
+ if isinstance(entry, dict) and entry.get("path"):
112
+ Path(entry["path"]).unlink(missing_ok=True)
113
+
114
+ def find(self, file_number: int, filename: str | None = None) -> dict | None:
115
+ with flock(self.lock_path):
116
+ value = self._read_index().get("files", {}).get(str(file_number))
117
+ if not isinstance(value, dict):
118
+ return None
119
+ found = dict(value)
120
+ # Index files written before ``fullpath`` existed still resolve for
121
+ # docassemble's DAFile.path(), which reads the fullpath key.
122
+ if "fullpath" not in found and found.get("path"):
123
+ found["fullpath"] = found["path"]
124
+ if filename:
125
+ found["filename"] = Path(filename).name
126
+ return found
127
+
128
+ def url_for(self, file_reference: Any) -> str | None:
129
+ file_reference = self._first_file(file_reference)
130
+ number = getattr(file_reference, "number", None)
131
+ if number is None:
132
+ return None
133
+ metadata = self.find(number)
134
+ if metadata is None:
135
+ return None
136
+ path = Path(metadata["path"]).resolve()
137
+ if not path.is_file():
138
+ return None
139
+ uri = path.as_uri()
140
+ diagnostics = (
141
+ tuple(validate_docx_structure(path))
142
+ if str(metadata["extension"]).lower() == "docx"
143
+ else ()
144
+ )
145
+ structure = (
146
+ "n/a"
147
+ if str(metadata["extension"]).lower() != "docx"
148
+ else ("warning" if diagnostics else "ok")
149
+ )
150
+ attachment = PublishedAttachment(
151
+ str(metadata["filename"]),
152
+ str(metadata["extension"]),
153
+ str(metadata["mimetype"]),
154
+ path,
155
+ uri,
156
+ diagnostics,
157
+ structure,
158
+ )
159
+ published = _PUBLISHED.get()
160
+ if published is not None and all(item.path != path for item in published):
161
+ published.append(attachment)
162
+ return uri
163
+
164
+ def _read_index(self) -> dict[str, Any]:
165
+ if not self.index_path.is_file():
166
+ files = {}
167
+ highest = 0
168
+ for path in self.directory.glob("dasimulator-*.*"):
169
+ match = re.fullmatch(r"dasimulator-(\d+)(\.[^.]+)", path.name)
170
+ if match is None:
171
+ continue
172
+ number = int(match.group(1))
173
+ highest = max(highest, number)
174
+ extension = match.group(2).lstrip(".").lower()
175
+ files[str(number)] = {
176
+ "path": str(path.resolve()),
177
+ "fullpath": str(path.resolve()),
178
+ "filename": path.name,
179
+ "extension": extension,
180
+ "mimetype": mimetypes.guess_type(path.name)[0]
181
+ or "application/octet-stream",
182
+ "persistent": False,
183
+ "private": True,
184
+ }
185
+ return {"schema": 1, "next": highest + 1, "files": files}
186
+ try:
187
+ value = json.loads(self.index_path.read_text(encoding="utf-8"))
188
+ except (OSError, ValueError, TypeError) as error:
189
+ raise RuntimeError(
190
+ f"simulator file index is unreadable: {self.index_path} ({error})"
191
+ ) from error
192
+ if not isinstance(value, dict) or value.get("schema") != 1:
193
+ raise RuntimeError(
194
+ f"simulator file index uses an unsupported format: {self.index_path}"
195
+ )
196
+ return value
197
+
198
+ def _write_index(self, value: dict[str, Any]) -> None:
199
+ payload = json.dumps(value, indent=2, sort_keys=True) + "\n"
200
+ atomic_replace(
201
+ self.index_path,
202
+ lambda temporary: temporary.write_text(payload, encoding="utf-8"),
203
+ lock_destination=False,
204
+ )
205
+
206
+ @staticmethod
207
+ def _first_file(file_reference: Any) -> Any:
208
+ elements = getattr(file_reference, "elements", None)
209
+ if isinstance(elements, list) and elements:
210
+ return elements[0]
211
+ first_file = getattr(file_reference, "_first_file", None)
212
+ if callable(first_file):
213
+ return first_file()
214
+ return file_reference
215
+
216
+
217
+ def validate_docx_structure(path: str | Path) -> list[Diagnostic]:
218
+ """Report strict paragraph nesting without mutating the DOCX package."""
219
+ diagnostics: list[Diagnostic] = []
220
+ paragraph_tag = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}p"
221
+ try:
222
+ with ZipFile(path) as archive:
223
+ parts = [
224
+ name
225
+ for name in archive.namelist()
226
+ if name.startswith("word/") and name.endswith(".xml")
227
+ ]
228
+ for part in parts:
229
+ try:
230
+ root = ET.fromstring(archive.read(part))
231
+ except ET.ParseError:
232
+ continue
233
+ count = sum(
234
+ 1
235
+ for paragraph in root.iter(paragraph_tag)
236
+ for descendant in paragraph.iter(paragraph_tag)
237
+ if descendant is not paragraph
238
+ )
239
+ if count:
240
+ diagnostics.append(
241
+ Diagnostic(
242
+ "docx-structure",
243
+ f"{part} contains {count} nested paragraph element(s)",
244
+ {
245
+ "part": part,
246
+ "problem": "nested-paragraph",
247
+ "count": count,
248
+ },
249
+ )
250
+ )
251
+ except (BadZipFile, OSError):
252
+ return []
253
+ return diagnostics
254
+
255
+
256
+ def activate_file_registry(directory: str | Path) -> LocalFileRegistry:
257
+ registry = LocalFileRegistry(directory)
258
+ _ACTIVE_REGISTRY.set(registry)
259
+ return registry
260
+
261
+
262
+ def active_file_registry() -> LocalFileRegistry | None:
263
+ return _ACTIVE_REGISTRY.get()
264
+
265
+
266
+ __all__ = [
267
+ "LocalFileRegistry",
268
+ "PublishedAttachment",
269
+ "activate_file_registry",
270
+ "active_file_registry",
271
+ "capture_published_attachments",
272
+ "validate_docx_structure",
273
+ ]
@@ -0,0 +1,27 @@
1
+ """Standard-library compatibility for the oldest supported Python (3.10)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ if sys.version_info >= (3, 11):
8
+ from enum import StrEnum
9
+
10
+ import tomllib
11
+ else: # pragma: no cover - exercised by the CPython 3.10 lane
12
+ from enum import Enum
13
+
14
+ import tomli as tomllib
15
+
16
+ class StrEnum(str, Enum):
17
+ """Python 3.11's ``StrEnum`` for 3.10."""
18
+
19
+ __str__ = str.__str__
20
+ __format__ = str.__format__
21
+
22
+ @staticmethod
23
+ def _generate_next_value_(name, start, count, last_values):
24
+ return name.lower()
25
+
26
+
27
+ __all__ = ["StrEnum", "tomllib"]
@@ -0,0 +1,238 @@
1
+ """Operation-local diagnostic capture for docassemble runtime traces."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from contextlib import contextmanager
6
+ from contextvars import ContextVar
7
+ from dataclasses import dataclass, replace
8
+ from typing import Any
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class Diagnostic:
13
+ """A non-fatal fact observed while an operation runs."""
14
+
15
+ kind: str
16
+ message: str
17
+ details: dict[str, Any]
18
+
19
+
20
+ _ACTIVE: ContextVar[list[Diagnostic] | None] = ContextVar(
21
+ "docassemble_simulator_diagnostics", default=None
22
+ )
23
+ _PENDING_CULPRIT: ContextVar[tuple[str, dict[str, Any]] | None] = ContextVar(
24
+ "docassemble_simulator_pending_culprit", default=None
25
+ )
26
+ _ENABLED = True
27
+
28
+
29
+ def set_capture_enabled(enabled: bool) -> None:
30
+ """Turn seek-trace capture on or off for this process."""
31
+ global _ENABLED
32
+ _ENABLED = bool(enabled)
33
+
34
+
35
+ def is_capture_enabled() -> bool:
36
+ return _ENABLED
37
+
38
+
39
+ @contextmanager
40
+ def capture_diagnostics():
41
+ """Collect diagnostics for one operation without sharing concurrent state."""
42
+ collected: list[Diagnostic] = []
43
+ token = _ACTIVE.set(collected)
44
+ pending = _PENDING_CULPRIT.set(None)
45
+ try:
46
+ yield collected
47
+ finally:
48
+ _ACTIVE.reset(token)
49
+ _PENDING_CULPRIT.reset(pending)
50
+
51
+
52
+ def is_collecting() -> bool:
53
+ return _ACTIVE.get() is not None
54
+
55
+
56
+ def record_diagnostic(
57
+ kind: str, message: str, details: dict[str, Any] | None = None
58
+ ) -> None:
59
+ """Record one non-fatal fact for the active operation, if any."""
60
+ collected = _ACTIVE.get()
61
+ if collected is None or not _ENABLED:
62
+ return
63
+ collected.append(Diagnostic(kind, message, details or {}))
64
+
65
+
66
+ def record_seeking(stages: list[Any] | None) -> None:
67
+ """Convert docassemble's native seeking trace into typed diagnostics."""
68
+ collected = _ACTIVE.get()
69
+ if collected is None or not _ENABLED:
70
+ return
71
+ for stage in stages or ():
72
+ if not isinstance(stage, dict) or stage.get("done"):
73
+ continue
74
+ details: dict[str, Any] = {}
75
+ variable = stage.get("variable")
76
+ if variable is not None:
77
+ details["variable"] = str(variable)
78
+ question = stage.get("question")
79
+ question_name = getattr(question, "name", None)
80
+ if question_name:
81
+ details["question"] = str(question_name)
82
+ reason = stage.get("reason")
83
+ if reason:
84
+ details["reason"] = str(reason)
85
+ if not details:
86
+ continue
87
+ if "variable" in details:
88
+ message = f"seeking {details['variable']}"
89
+ elif "reason" in details:
90
+ message = f"{details['reason']} question {details['question']}"
91
+ else:
92
+ message = f"considering question {details['question']}"
93
+ collected.append(Diagnostic("variable-seek", message, details))
94
+ pending = _PENDING_CULPRIT.get()
95
+ if pending is not None:
96
+ _PENDING_CULPRIT.set(None)
97
+ record_culprit(*pending)
98
+
99
+
100
+ def record_culprit(variable: str, culprit: dict[str, Any]) -> None:
101
+ """Attach the terminal seek culprit without rewriting tolerated events."""
102
+ collected = _ACTIVE.get()
103
+ if collected is None or not _ENABLED:
104
+ return
105
+ for index in range(len(collected) - 1, -1, -1):
106
+ event = collected[index]
107
+ if event.kind != "variable-seek":
108
+ continue
109
+ if event.details.get("variable") != str(variable):
110
+ continue
111
+ details = dict(event.details)
112
+ details["culprit"] = culprit
113
+ collected[index] = replace(event, details=details)
114
+ return
115
+ _PENDING_CULPRIT.set((str(variable), culprit))
116
+
117
+
118
+ def is_lazy_seek_log(message: Any) -> bool:
119
+ """Whether a docassemble log line duplicates its structured seek trace."""
120
+ text = str(message)
121
+ return text.startswith(
122
+ (
123
+ "NameError exception during document assembly:",
124
+ "UndefinedError exception during document assembly:",
125
+ )
126
+ )
127
+
128
+
129
+ __all__ = [
130
+ "Diagnostic",
131
+ "capture_diagnostics",
132
+ "is_capture_enabled",
133
+ "is_collecting",
134
+ "is_lazy_seek_log",
135
+ "record_culprit",
136
+ "record_diagnostic",
137
+ "record_seeking",
138
+ "set_capture_enabled",
139
+ ]
140
+
141
+
142
+ _SEEN_COMPILE_WARNINGS: set[tuple[Any, ...]] = set()
143
+ _PENDING_COMPILE_WARNINGS: dict[str, dict[tuple[Any, ...], Diagnostic]] = {}
144
+
145
+
146
+ @contextmanager
147
+ def capture_compile_warnings(interview: str):
148
+ """Attribute Python compiler warnings only from authored docassemble code.
149
+
150
+ The compiler uses synthetic filenames, so provenance comes from the active
151
+ parser question rather than treating that filename as an interview path.
152
+ All other warnings retain the caller's warning handler and filters.
153
+ """
154
+ import sys
155
+ import warnings
156
+
157
+ collected = _ACTIVE.get()
158
+ if collected is not None:
159
+ for key, event in _PENDING_COMPILE_WARNINGS.pop(interview, {}).items():
160
+ if key not in _SEEN_COMPILE_WARNINGS:
161
+ collected.append(event)
162
+ _SEEN_COMPILE_WARNINGS.add(key)
163
+
164
+ with warnings.catch_warnings():
165
+ previous = warnings.showwarning
166
+
167
+ def showwarning(message, category, filename, lineno, file=None, line=None):
168
+ question = None
169
+ if filename.startswith("<") and (
170
+ issubclass(category, SyntaxWarning)
171
+ or (
172
+ issubclass(category, DeprecationWarning)
173
+ and "invalid escape sequence" in str(message)
174
+ )
175
+ ):
176
+ frame = sys._getframe(1)
177
+ try:
178
+ while frame is not None:
179
+ if frame.f_globals.get("__name__") == "docassemble.base.parse":
180
+ candidate = frame.f_locals.get(
181
+ "question"
182
+ ) or frame.f_locals.get("self")
183
+ if getattr(candidate, "from_source", None) is not None:
184
+ question = candidate
185
+ break
186
+ frame = frame.f_back
187
+ finally:
188
+ del frame
189
+ if question is None:
190
+ previous(message, category, filename, lineno, file=file, line=line)
191
+ return
192
+ source = question.from_source
193
+ details = {
194
+ "interview": interview,
195
+ "source_file": str(getattr(source, "path", None) or interview),
196
+ "line": getattr(question, "line_number", None),
197
+ "question": str(
198
+ getattr(question, "name", "")
199
+ or (f"ID {question.id}" if getattr(question, "id", None) else "")
200
+ ),
201
+ "category": category.__name__,
202
+ "compile_filename": filename,
203
+ "compile_line": lineno,
204
+ }
205
+ text = str(message)[:1000]
206
+ # Recompiles and AST scans can use another filepath or <unknown>;
207
+ # warning identity belongs to the authored block, not that wrapper.
208
+ key = (
209
+ interview,
210
+ details["source_file"],
211
+ details["line"],
212
+ details["question"],
213
+ details["category"],
214
+ details["compile_line"],
215
+ text,
216
+ )
217
+ collected = _ACTIVE.get()
218
+ if collected is None and key not in _SEEN_COMPILE_WARNINGS:
219
+ pending = _PENDING_COMPILE_WARNINGS.setdefault(interview, {})
220
+ if len(pending) < 20:
221
+ pending[key] = Diagnostic("compile-warning", text, details)
222
+ if (
223
+ collected is not None
224
+ and key not in _SEEN_COMPILE_WARNINGS
225
+ and sum(event.kind == "compile-warning" for event in collected) < 20
226
+ ):
227
+ collected.append(Diagnostic("compile-warning", text, details))
228
+ _SEEN_COMPILE_WARNINGS.add(key)
229
+
230
+ warnings.showwarning = showwarning
231
+ warnings.filterwarnings("always", category=SyntaxWarning, module=r"^<")
232
+ warnings.filterwarnings(
233
+ "always",
234
+ message=".*invalid escape sequence.*",
235
+ category=DeprecationWarning,
236
+ module=r"^<",
237
+ )
238
+ yield
@@ -0,0 +1,27 @@
1
+ """Environment policy applied before loading the target document runtime."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Mapping
7
+
8
+
9
+ def target_interpreter_environment(
10
+ environment: Mapping[str, str] | None = None,
11
+ ) -> dict[str, str]:
12
+ """Disable ORT telemetry before import, even if the caller enabled it.
13
+
14
+ The pre-import switch prevents the 1DS SDK manager/uploader initialization,
15
+ not the existence of ONNX Runtime's PosixTelemetry provider object. The
16
+ post-import disable_telemetry_events() API is too late to prevent that SDK
17
+ initialization and the macOS exit race. Force the switch instead; a caller's
18
+ opt-in cannot safely override this mitigation.
19
+
20
+ Callers bypassing CLI/runner launch seams (direct in-process bootstrap,
21
+ custom test harnesses, or sitecustomize/.pth startup hooks) must set
22
+ ORT_DISABLE_TELEMETRY=1 before any runtime bootstrap or onnxruntime import.
23
+ """
24
+ return {
25
+ **(os.environ if environment is None else environment),
26
+ "ORT_DISABLE_TELEMETRY": "1",
27
+ }