@withgateway/sdk 0.4.0 → 0.9.1

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 (157) hide show
  1. package/dist/agents/index.d.mts +573 -0
  2. package/dist/agents/index.d.ts +573 -0
  3. package/dist/agents/index.js +1443 -0
  4. package/dist/agents/index.js.map +1 -0
  5. package/dist/agents/index.mjs +1394 -0
  6. package/dist/agents/index.mjs.map +1 -0
  7. package/dist/apiError-DHpfbmdx.d.mts +17 -0
  8. package/dist/apiError-DHpfbmdx.d.ts +17 -0
  9. package/dist/cli.js +5655 -1890
  10. package/dist/cli.js.map +1 -1
  11. package/dist/cli.mjs +5769 -2005
  12. package/dist/cli.mjs.map +1 -1
  13. package/dist/files/index.d.mts +3 -1
  14. package/dist/files/index.d.ts +3 -1
  15. package/dist/files/index.js +418 -120
  16. package/dist/files/index.js.map +1 -1
  17. package/dist/files/index.mjs +418 -120
  18. package/dist/files/index.mjs.map +1 -1
  19. package/dist/hooks/index.js +346 -136
  20. package/dist/hooks/index.js.map +1 -1
  21. package/dist/hooks/index.mjs +346 -136
  22. package/dist/hooks/index.mjs.map +1 -1
  23. package/dist/{index-DUHmS74p.d.ts → index-DIN14Lhg.d.ts} +27 -4
  24. package/dist/{index-mJhG3vZU.d.mts → index-DuB-eQ0Z.d.mts} +27 -4
  25. package/dist/index.d.mts +7 -4
  26. package/dist/index.d.ts +7 -4
  27. package/dist/index.js +2862 -438
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +2820 -431
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/media-CQUC7TkS.d.mts +39 -0
  32. package/dist/media-DQnBloaX.d.ts +39 -0
  33. package/dist/replay/index.d.mts +1 -1
  34. package/dist/replay/index.d.ts +1 -1
  35. package/dist/replay/index.js.map +1 -1
  36. package/dist/replay/index.mjs.map +1 -1
  37. package/dist/traces/index.d.mts +3 -1
  38. package/dist/traces/index.d.ts +3 -1
  39. package/dist/traces/index.js +418 -120
  40. package/dist/traces/index.js.map +1 -1
  41. package/dist/traces/index.mjs +418 -120
  42. package/dist/traces/index.mjs.map +1 -1
  43. package/dist/tracing/index.d.mts +3 -2
  44. package/dist/tracing/index.d.ts +3 -2
  45. package/dist/tracing/index.js +257 -16
  46. package/dist/tracing/index.js.map +1 -1
  47. package/dist/tracing/index.mjs +257 -16
  48. package/dist/tracing/index.mjs.map +1 -1
  49. package/dist/transport-CpRe7zgd.d.mts +123 -0
  50. package/dist/transport-CpRe7zgd.d.ts +123 -0
  51. package/dist/worlds/index.d.mts +2086 -1749
  52. package/dist/worlds/index.d.ts +2086 -1749
  53. package/dist/worlds/index.js +1471 -269
  54. package/dist/worlds/index.js.map +1 -1
  55. package/dist/worlds/index.mjs +1466 -265
  56. package/dist/worlds/index.mjs.map +1 -1
  57. package/package.json +6 -1
  58. package/runtime/gatewaysdk/environment/_bundle.py +4 -6
  59. package/runtime/gatewaysdk/environment/_world.py +24 -1
  60. package/runtime/gatewaysdk/environment/bundle_manifest.py +243 -0
  61. package/runtime/gatewaysdk/environment/runtime.py +45 -2
  62. package/runtime/gatewaysdk/environment/schema/__main__.py +2 -2
  63. package/runtime/gatewaysdk/environment/schema/_slack_fidelity.py +8 -23
  64. package/runtime/gatewaysdk/environment/schema/api.py +27 -7
  65. package/runtime/gatewaysdk/environment/schema/assertions.py +7 -1
  66. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +2 -0
  67. package/runtime/gatewaysdk/environment/schema/call_capture.py +13 -1
  68. package/runtime/gatewaysdk/environment/schema/call_log.py +66 -0
  69. package/runtime/gatewaysdk/environment/schema/call_redaction.py +6 -0
  70. package/runtime/gatewaysdk/environment/schema/compiler.py +4 -1
  71. package/runtime/gatewaysdk/environment/schema/conform.py +32 -8
  72. package/runtime/gatewaysdk/environment/schema/connector.py +5 -0
  73. package/runtime/gatewaysdk/environment/schema/connectors/custom/handlers.py +2 -1
  74. package/runtime/gatewaysdk/environment/schema/connectors/github/api/handlers.py +217 -58
  75. package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +9 -19
  76. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_webhooks.json +10 -2
  77. package/runtime/gatewaysdk/environment/schema/connectors/github/tests/webhooks.json +47 -0
  78. package/runtime/gatewaysdk/environment/schema/connectors/github/world.json +21 -0
  79. package/runtime/gatewaysdk/environment/schema/connectors/jamf/api/handlers.py +185 -18
  80. package/runtime/gatewaysdk/environment/schema/connectors/jamf/connector.toml +29 -14
  81. package/runtime/gatewaysdk/environment/schema/connectors/jamf/provenance.json +43 -12
  82. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_webhooks.json +2 -2
  83. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scope.toml +4 -17
  84. package/runtime/gatewaysdk/environment/schema/connectors/jamf/tests/webhooks.json +107 -0
  85. package/runtime/gatewaysdk/environment/schema/connectors/jamf/vendor-openapi.json +1 -1
  86. package/runtime/gatewaysdk/environment/schema/connectors/linear/api/handlers.py +85 -1
  87. package/runtime/gatewaysdk/environment/schema/connectors/linear/connector.toml +19 -31
  88. package/runtime/gatewaysdk/environment/schema/connectors/linear/provenance.json +18 -8
  89. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/webhooks.json +19 -3
  90. package/runtime/gatewaysdk/environment/schema/connectors/linear/tests/test_webhooks.py +71 -0
  91. package/runtime/gatewaysdk/environment/schema/database/base.py +2 -2
  92. package/runtime/gatewaysdk/environment/schema/database/guard.py +2 -1
  93. package/runtime/gatewaysdk/environment/schema/handler_errors.py +27 -1
  94. package/runtime/gatewaysdk/environment/schema/host.py +74 -11
  95. package/runtime/gatewaysdk/environment/schema/host_browser.py +48 -0
  96. package/runtime/gatewaysdk/environment/schema/host_control.py +33 -2
  97. package/runtime/gatewaysdk/environment/schema/host_handoff.py +4 -1
  98. package/runtime/gatewaysdk/environment/schema/host_requests.py +14 -0
  99. package/runtime/gatewaysdk/environment/schema/host_session.py +13 -2
  100. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +6 -0
  101. package/runtime/gatewaysdk/environment/schema/host_versions.py +96 -19
  102. package/runtime/gatewaysdk/environment/schema/journal.py +10 -4
  103. package/runtime/gatewaysdk/environment/schema/local.py +33 -7
  104. package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +20 -5
  105. package/runtime/gatewaysdk/environment/schema/page_checks.py +123 -0
  106. package/runtime/gatewaysdk/environment/schema/platform.py +33 -480
  107. package/runtime/gatewaysdk/environment/schema/platform_templates.py +332 -0
  108. package/runtime/gatewaysdk/environment/schema/request_ledger.py +4 -1
  109. package/runtime/gatewaysdk/environment/schema/run_parameters.py +25 -0
  110. package/runtime/gatewaysdk/environment/schema/runtime.py +49 -4
  111. package/runtime/gatewaysdk/environment/schema/scaffold.py +369 -218
  112. package/runtime/gatewaysdk/environment/schema/session_files.py +13 -2
  113. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +1 -1
  114. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  115. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +20 -24
  116. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +11 -11
  117. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +9 -9
  118. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +45 -12
  119. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +40 -9
  120. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +17 -2
  121. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  122. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/ui-map.md +3 -2
  123. package/runtime/gatewaysdk/environment/schema/slack.py +55 -10
  124. package/runtime/gatewaysdk/environment/schema/snapshot.py +30 -4
  125. package/runtime/gatewaysdk/environment/schema/tasks.py +25 -2
  126. package/runtime/gatewaysdk/environment/schema/template_record.py +131 -0
  127. package/runtime/gatewaysdk/environment/schema/tools_world.py +26 -5
  128. package/runtime/gatewaysdk/environment/schema/ui.py +54 -33
  129. package/runtime/gatewaysdk/environment/schema/ui_interactions.py +419 -0
  130. package/runtime/gatewaysdk/environment/schema/ui_recorder.js +895 -0
  131. package/runtime/gatewaysdk/environment/schema/ui_replay.py +366 -0
  132. package/runtime/gatewaysdk/environment/schema/ui_replay_record.LICENSE +25 -0
  133. package/runtime/gatewaysdk/environment/schema/ui_replay_record.js +109 -0
  134. package/runtime/gatewaysdk/environment/schema/validation.py +10 -1
  135. package/runtime/gatewaysdk/environment/schema/verbs.py +6 -0
  136. package/runtime/gatewaysdk/environment/schema/webhooks.py +687 -0
  137. package/runtime/gatewaysdk/environment/schema/worker.py +5 -1
  138. package/runtime/gatewaysdk/environment/schema/workers.py +8 -1
  139. package/runtime/gatewaysdk/environment/schema/world_host.py +64 -18
  140. package/runtime/gatewaysdk/environment/schema/world_tests.py +74 -0
  141. package/runtime/gatewaysdk/environment/secret_values.py +1 -1
  142. package/runtime/gatewaysdk/environment/world.py +34 -43
  143. package/runtime/gatewaysdk/environment/world_session_contract.py +7 -34
  144. package/skills/benchmarks-getting-started/SKILL.md +1 -1
  145. package/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  146. package/skills/connector-schema-authoring/SKILL.md +20 -24
  147. package/skills/connector-schema-authoring/connector-worlds.md +155 -13
  148. package/skills/connector-schema-authoring/world-schema.md +36 -29
  149. package/skills/world-data-ingestion/SKILL.md +11 -11
  150. package/skills/worlds-getting-started/SKILL.md +9 -9
  151. package/skills/worlds-getting-started/references/cli-mcp-map.md +45 -12
  152. package/skills/worlds-getting-started/references/gotchas.md +40 -9
  153. package/skills/worlds-getting-started/references/journal-checks.md +17 -2
  154. package/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  155. package/skills/worlds-getting-started/references/ui-map.md +3 -2
  156. package/dist/media-BIApiPzS.d.mts +0 -102
  157. package/dist/media-BIApiPzS.d.ts +0 -102
@@ -13,7 +13,7 @@ from typing import TYPE_CHECKING, Any
13
13
  from .._toml import tomllib
14
14
  from .call_redaction import REDACTED, CallRedaction
15
15
  from .database.base import SideTable
16
- from .tasks import JOURNAL, JOURNAL_META, WITHHELD_FIELD
16
+ from .tasks import JOURNAL, JOURNAL_META, PAGE_NOTES, WITHHELD_FIELD
17
17
  from .validation import fail
18
18
 
19
19
  if TYPE_CHECKING:
@@ -26,7 +26,7 @@ JOURNAL_TABLES = frozenset(JOURNAL_KEYS)
26
26
  MAX_JOURNAL_REQUESTS = 20_000
27
27
  NOT_RECORDED = "not recorded: only a World Host session records the requests its world receives"
28
28
  LINKED_NOT_RECORDED = "not recorded for a linked world: the root world's verifiers and the task's checks read it"
29
- VIAS = ("api", "ui", "tool")
29
+ VIAS = ("api", "ui", "tool", "webhook", "page")
30
30
  JSON_HINTS = ("json",)
31
31
  WITHHELD_ROUTE_BODY = ["body", "selectors"]
32
32
  WITHHELD_TOOL_ARGS = ["args", "selectors"]
@@ -244,7 +244,8 @@ LINKED_JOURNAL = WorldJournal.unrecorded(LINKED_NOT_RECORDED)
244
244
 
245
245
 
246
246
  class CallsView:
247
- """A request no route took and a tool call the door refused are the journal's alone: they never were calls."""
247
+ """A request no route took, a tool call the door refused and a webhook the world sent (``via``
248
+ webhook) are the journal's alone: they never were the agent's calls."""
248
249
 
249
250
  def __init__(self, spec: Spec | None, redaction: CallRedaction, admitted: Callable[[str], bool]) -> None:
250
251
  self.spec = spec
@@ -255,12 +256,17 @@ class CallsView:
255
256
  return [call for call in map(self._call, journal.entries) if call is not None]
256
257
 
257
258
  def _call(self, entry: JournalEntry) -> dict | None:
258
- if entry.operation is None:
259
+ if entry.operation is None or entry.raw["via"] == "webhook":
259
260
  return None
260
261
  if entry.raw["via"] == "tool" and entry.raw["method"] is None:
261
262
  return self._tool(entry) if self.admitted(entry.operation) else None
263
+ if entry.raw["via"] == "page":
264
+ return None if entry.operation in PAGE_NOTES else self._interaction(entry)
262
265
  return self._route(entry)
263
266
 
267
+ def _interaction(self, entry: JournalEntry) -> dict:
268
+ return {**self._tool(entry), "path": entry.raw["path"], "query": entry.raw["query"]}
269
+
264
270
  def _tool(self, entry: JournalEntry) -> dict:
265
271
  body = entry.request
266
272
  args = body.value if body.whole else REDACTED
@@ -10,6 +10,7 @@ import tempfile
10
10
  import threading
11
11
  import urllib.parse
12
12
  from dataclasses import dataclass, field
13
+ from functools import partial
13
14
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
14
15
  from pathlib import Path
15
16
  from typing import Any, Callable
@@ -33,6 +34,7 @@ from .tools_world import (
33
34
  ToolsWorldState,
34
35
  load_tools_version,
35
36
  )
37
+ from .ui_interactions import RECORDER_PATH, UiRecorder
36
38
  from .validation import ContractError
37
39
  from .verbs import refusal, session_verb, unknown_verb
38
40
 
@@ -51,7 +53,7 @@ def load_local_version(root: Path, scratch: Path) -> ToolsVersion:
51
53
  f"{root} is not a schema world (no gateway-env.toml with a [schema] table); "
52
54
  "`gateway worlds schema init` starts one",
53
55
  )
54
- return load_tools_version(root, scratch / "template.db", None, run_handlers=True)
56
+ return load_tools_version(root, scratch / "template.db", fetched=False, run_handlers=True)
55
57
 
56
58
 
57
59
  def load_local_dependencies(root: Path, version: ToolsVersion, scratch: Path) -> dict[str, DependencyWorld]:
@@ -306,6 +308,7 @@ def make_session_handler(
306
308
  "POST seed": seed,
307
309
  "POST call": world.call,
308
310
  "POST close": close,
311
+ "POST webhooks": lambda poll: calls.webhook_page(world.world.webhooks, poll),
309
312
  }
310
313
 
311
314
  class Handler(WorldRequestHandler):
@@ -316,10 +319,7 @@ def make_session_handler(
316
319
  raw = self.rfile.read(length) if length else b""
317
320
  path = self.path.split("?", 1)[0]
318
321
  if ui_origin:
319
- assert ui is not None
320
- if app is not None and api_target(ui, path) is not None:
321
- return self._ui_api(method, path, raw, Via.UI)
322
- return self._ui(method, path)
322
+ return self._ui_origin(method, path, raw)
323
323
  origin = self.headers.get("Origin")
324
324
  if origin and not _local_origin(origin):
325
325
  return self._reply(403, {"error": "this session answers this machine's pages, not another site's"})
@@ -343,11 +343,32 @@ def make_session_handler(
343
343
  )
344
344
  send_response(self, status, body, extra, app.settings.error_content_type)
345
345
 
346
+ def _ui_origin(self, method: str, path: str, raw: bytes) -> None:
347
+ assert ui is not None
348
+ if app is not None and api_target(ui, path) is not None:
349
+ return self._ui_api(method, path, raw, Via.UI)
350
+ if path == RECORDER_PATH:
351
+ return self._page(method, UiRecorder.script)
352
+ if UiRecorder.serves(path):
353
+ return self._recorded(method, path, raw)
354
+ return self._page(method, partial(self._served, path))
355
+
356
+ def _served(self, path: str) -> tuple[int, dict[str, str], bytes]:
357
+ assert ui is not None
358
+ status, headers, payload = static_file(ui, path)
359
+ page = UiRecorder.page(status, headers, payload)
360
+ if page is not None:
361
+ UiRecorder.served(path, calls)
362
+ return status, headers, payload if page is None else page
363
+
346
364
  def _ui(self, method: str, path: str) -> None:
365
+ assert ui is not None
366
+ return self._page(method, partial(static_file, ui, path))
367
+
368
+ def _page(self, method: str, answer: Callable[[], tuple[int, dict[str, str], bytes]]) -> None:
347
369
  if method != "GET":
348
370
  return self._reply(405, {"error": "the static ui answers GET only"})
349
- assert ui is not None
350
- status, headers, payload = static_file(ui, path)
371
+ status, headers, payload = answer()
351
372
  self.send_response(status)
352
373
  for name, value in headers.items():
353
374
  self.send_header(name, value)
@@ -355,6 +376,11 @@ def make_session_handler(
355
376
  self.end_headers()
356
377
  write_body(self, payload)
357
378
 
379
+ def _recorded(self, method: str, path: str, raw: bytes) -> None:
380
+ if cross_site({k.lower(): v for k, v in self.headers.items()}, _local_origin):
381
+ return self._reply(403, {"error": "the recorder answers the page on this server, not another site"})
382
+ return self._reply(*UiRecorder.record(method, path, raw, calls))
383
+
358
384
  def _ui_api(self, method: str, path: str, raw: bytes, via: Via) -> None:
359
385
  """Answers with the world's own credential for the pin, as the host does for the session cookie."""
360
386
  assert app is not None and ui is not None
@@ -142,6 +142,7 @@ class Namespace:
142
142
  return candidate, True
143
143
 
144
144
 
145
+ GENERIC_SUFFIXES = frozenset({"item", "items", "entry", "summary", "response", "detail", "details", "object", "record", "resource"})
145
146
  SCALARS = frozenset({"string", "integer", "number", "boolean"})
146
147
 
147
148
 
@@ -175,8 +176,9 @@ class EntityKey:
175
176
 
176
177
  def detect(self, *, lookups: tuple[str, ...] = (), fallback: bool = True) -> str | None:
177
178
  """:meth:`declared`, else the field a route's own ``{segment}`` looks the row up by
178
- (``/works/{doi}`` → ``DOI``; nested, ``/studies/{nctId}`` → a JSON Pointer), else
179
- (when ``fallback``) the first required scalar."""
179
+ (``/works/{doi}`` → ``DOI``; nested, ``/studies/{nctId}`` → a JSON Pointer), else the resource's
180
+ own id named from a shorter form of the schema or its namespace (``messages_MessageItem`` →
181
+ ``message_id``), else (when ``fallback``) the first required scalar."""
180
182
  declared = self.declared()
181
183
  if declared is not None:
182
184
  return declared
@@ -184,6 +186,9 @@ class EntityKey:
184
186
  found = self.top_level(own) or self.nested(own)
185
187
  if found is not None:
186
188
  return found
189
+ resource = next((name for name in self._resource_id_like() if self._keyable(name)), None)
190
+ if resource is not None:
191
+ return resource
187
192
  if not fallback:
188
193
  return None
189
194
  return next((name for name in self.properties if name in self.required and self._keyable(name)), None)
@@ -252,9 +257,19 @@ class EntityKey:
252
257
  return types if isinstance(types, str) and not resolved.get("properties") else None
253
258
 
254
259
  def _id_like(self) -> list[str]:
255
- singular = Names.snake(self.source)
256
- camel = re.sub(r"_([a-z0-9])", lambda m: m.group(1).upper(), singular)
257
- candidates = ["id", "ID", "Id", f"{camel}Id", f"{camel}_id", f"{singular}_id", f"{singular}Id", f"{camel}ID"]
260
+ return self._named_ids(["id", "ID", "Id"], [Names.snake(self.source)])
261
+
262
+ def _resource_id_like(self) -> list[str]:
263
+ own = self.source.partition("_")[2] if self.source.partition("_")[2][:1].isupper() else self.source
264
+ words = [word for word in Names.snake(own).split("_") if word]
265
+ trailing = ["_".join(words[start:]) for start in range(len(words)) if words[start:] != [words[-1]] or words[-1] not in GENERIC_SUFFIXES]
266
+ meaningful = words[:-1] if len(words) > 1 and words[-1] in GENERIC_SUFFIXES else words
267
+ return self._named_ids([], [*trailing, "_".join(meaningful), *meaningful[-1:]])
268
+
269
+ def _named_ids(self, candidates: list[str], stems: list[str]) -> list[str]:
270
+ for stem in stems:
271
+ camel = re.sub(r"_([a-z0-9])", lambda m: m.group(1).upper(), stem)
272
+ candidates = [*candidates, f"{camel}Id", f"{camel}_id", f"{stem}_id", f"{stem}Id", f"{camel}ID"]
258
273
  return [c for c in dict.fromkeys(candidates) if c in self.properties]
259
274
 
260
275
  def _keyable(self, name: str) -> bool:
@@ -0,0 +1,123 @@
1
+ """The grader's view of a UI world's page (``via: page``): which checks read it, and whether what
2
+ the page reported can decide them. A check that does not name the page reads what it read before
3
+ pages reported anything; the host's notes (``ui.recording`` at open, ``ui.served`` per page) are
4
+ evidence for :class:`PageReport`, never a row a check reads."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections import defaultdict
9
+ from collections.abc import Iterable, Mapping
10
+ from dataclasses import dataclass, field
11
+ from typing import Any
12
+
13
+ from .tasks import (
14
+ DOOR_FIELD,
15
+ JOURNAL,
16
+ ORDER_KEYS,
17
+ PAGE_DOOR,
18
+ PAGE_GAP,
19
+ PAGE_NOTES,
20
+ PAGE_RECORDING,
21
+ PAGE_SERVED,
22
+ PAGE_UNHEARD,
23
+ PAGE_UNJOURNALED,
24
+ PAGE_UNRECORDED,
25
+ PAGE_UNRECORDED_LIFE,
26
+ )
27
+
28
+ PAGE_OPERATIONS = "ui."
29
+ PAGE_PATHS = ("args.target.", "request.body.target.")
30
+
31
+
32
+ def _listed(value: Any) -> list[Any]:
33
+ return list(value) if isinstance(value, (list, tuple)) else [value]
34
+
35
+
36
+ def _names_door(value: Any) -> bool:
37
+ return any(item == PAGE_DOOR for item in _listed(value))
38
+
39
+
40
+ def _names_operation(value: Any) -> bool:
41
+ return any(isinstance(item, str) and item.startswith(PAGE_OPERATIONS) for item in _listed(value))
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class PageCheck:
46
+ """One check as the page sees it: it names the page when a clause or its ``field`` pins the
47
+ page door or a ``ui.*`` operation, or a clause reads what a page interaction acted on."""
48
+
49
+ check: Mapping[str, Any]
50
+
51
+ @property
52
+ def names_the_page(self) -> bool:
53
+ clauses = [self.check.get("where") or {}, *(self.check.get(key) or {} for key in ORDER_KEYS)]
54
+ return any(self._clause(clause) for clause in clauses) or self._field()
55
+
56
+ def _clause(self, clause: Mapping[str, Any]) -> bool:
57
+ pinned = _names_door(clause.get(DOOR_FIELD)) or _names_operation(clause.get("operation"))
58
+ return pinned or any(path.startswith(PAGE_PATHS) for path in clause)
59
+
60
+ def _field(self) -> bool:
61
+ value = self.check.get("value")
62
+ named = {DOOR_FIELD: _names_door, "operation": _names_operation}.get(self.check.get("field") or "")
63
+ return named is not None and named(value)
64
+
65
+ def keeps(self, values: Mapping[str, Any]) -> bool:
66
+ if values.get(DOOR_FIELD) != PAGE_DOOR:
67
+ return True
68
+ return self.names_the_page and values.get("operation") not in PAGE_NOTES
69
+
70
+
71
+ @dataclass
72
+ class PageReport:
73
+ """What the session's journal says about its pages: whether a host noted it recorded them,
74
+ whether it served any, whether any interaction came back, and each page load's numbered
75
+ interactions. A grade with no journal has none of this to read."""
76
+
77
+ journaled: bool = False
78
+ recording: bool = False
79
+ unrecorded: bool = False
80
+ served: bool = False
81
+ reported: bool = False
82
+ loads: dict[str, set[int]] = field(default_factory=lambda: defaultdict(set))
83
+
84
+ @classmethod
85
+ def of(cls, state: Mapping, entity: str) -> PageReport:
86
+ prefix = entity[: entity.rfind(".") + 1]
87
+ rows = state.get(f"{prefix}{JOURNAL}")
88
+ report = cls(journaled=isinstance(rows, list))
89
+ for row in rows if isinstance(rows, list) else ():
90
+ if isinstance(row, Mapping) and row.get(DOOR_FIELD) == PAGE_DOOR:
91
+ report._note(row)
92
+ return report
93
+
94
+ def _note(self, row: Mapping[str, Any]) -> None:
95
+ operation = row.get("operation")
96
+ self.recording = self.recording or operation == PAGE_RECORDING
97
+ self.unrecorded = self.unrecorded or operation == PAGE_UNRECORDED_LIFE
98
+ self.served = self.served or operation == PAGE_SERVED
99
+ if operation in PAGE_NOTES:
100
+ return
101
+ self.reported = True
102
+ query = row.get("query")
103
+ load, seq = (query.get("load"), query.get("seq")) if isinstance(query, Mapping) else (None, None)
104
+ if isinstance(load, str) and isinstance(seq, int) and not isinstance(seq, bool):
105
+ self.loads[load].add(seq)
106
+
107
+ def missing(self) -> int:
108
+ return sum(max(seqs) - len(seqs) for seqs in self.loads.values() if seqs)
109
+
110
+ def refusal(self) -> str | None:
111
+ if not self.journaled:
112
+ return PAGE_UNJOURNALED
113
+ if self.unrecorded or not self.recording:
114
+ return PAGE_UNRECORDED
115
+ if self.served and not self.reported:
116
+ return PAGE_UNHEARD
117
+ gaps = self.missing()
118
+ return PAGE_GAP.format(missing=gaps) if gaps else None
119
+
120
+
121
+ def page_rows(check: Mapping[str, Any], rows: Iterable[Any]) -> list[Any]:
122
+ view = PageCheck(check)
123
+ return [row for row in rows if view.keeps(row.values)]