@withgateway/sdk 0.3.1 → 0.4.0

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 (176) hide show
  1. package/README.md +8 -6
  2. package/dist/cli.js +4372 -2265
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cli.mjs +4362 -2256
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/files/index.d.mts +1 -1
  7. package/dist/files/index.d.ts +1 -1
  8. package/dist/files/index.js +259 -58
  9. package/dist/files/index.js.map +1 -1
  10. package/dist/files/index.mjs +249 -50
  11. package/dist/files/index.mjs.map +1 -1
  12. package/dist/hooks/index.d.mts +1 -1
  13. package/dist/hooks/index.d.ts +1 -1
  14. package/dist/hooks/index.js +124 -11
  15. package/dist/hooks/index.js.map +1 -1
  16. package/dist/hooks/index.mjs +124 -11
  17. package/dist/hooks/index.mjs.map +1 -1
  18. package/dist/{index-C3UzD0G3.d.mts → index-CDPQBsU5.d.mts} +19 -3
  19. package/dist/{index-C3UzD0G3.d.ts → index-CDPQBsU5.d.ts} +19 -3
  20. package/dist/{index-CBqbB_0J.d.ts → index-DUHmS74p.d.ts} +1 -1
  21. package/dist/{index-D-AMnAMa.d.mts → index-mJhG3vZU.d.mts} +1 -1
  22. package/dist/index.d.mts +5 -5
  23. package/dist/index.d.ts +5 -5
  24. package/dist/index.js +2240 -789
  25. package/dist/index.js.map +1 -1
  26. package/dist/index.mjs +2150 -739
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/{media-CbcAfQvd.d.mts → media-BIApiPzS.d.mts} +21 -2
  29. package/dist/{media-CbcAfQvd.d.ts → media-BIApiPzS.d.ts} +21 -2
  30. package/dist/traces/index.d.mts +1 -1
  31. package/dist/traces/index.d.ts +1 -1
  32. package/dist/traces/index.js +253 -52
  33. package/dist/traces/index.js.map +1 -1
  34. package/dist/traces/index.mjs +243 -44
  35. package/dist/traces/index.mjs.map +1 -1
  36. package/dist/tracing/index.d.mts +2 -2
  37. package/dist/tracing/index.d.ts +2 -2
  38. package/dist/tracing/index.js +75 -13
  39. package/dist/tracing/index.js.map +1 -1
  40. package/dist/tracing/index.mjs +75 -13
  41. package/dist/tracing/index.mjs.map +1 -1
  42. package/dist/worlds/index.d.mts +893 -482
  43. package/dist/worlds/index.d.ts +893 -482
  44. package/dist/worlds/index.js +1968 -669
  45. package/dist/worlds/index.js.map +1 -1
  46. package/dist/worlds/index.mjs +1960 -662
  47. package/dist/worlds/index.mjs.map +1 -1
  48. package/package.json +1 -1
  49. package/runtime/gatewaysdk/environment/_bundle.py +2 -27
  50. package/runtime/gatewaysdk/environment/_materialize.py +48 -88
  51. package/runtime/gatewaysdk/environment/_world.py +155 -237
  52. package/runtime/gatewaysdk/environment/backing.py +133 -0
  53. package/runtime/gatewaysdk/environment/core.py +2 -17
  54. package/runtime/gatewaysdk/environment/legacy_sqlite.py +288 -0
  55. package/runtime/gatewaysdk/environment/reward_keys.py +25 -0
  56. package/runtime/gatewaysdk/environment/runtime.py +8 -13
  57. package/runtime/gatewaysdk/environment/schema/__init__.py +4 -4
  58. package/runtime/gatewaysdk/environment/schema/admin_routes.py +86 -0
  59. package/runtime/gatewaysdk/environment/schema/admission.py +174 -0
  60. package/runtime/gatewaysdk/environment/schema/api.py +347 -892
  61. package/runtime/gatewaysdk/environment/schema/assertions.py +458 -0
  62. package/runtime/gatewaysdk/environment/schema/batch.py +44 -39
  63. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +17 -5
  64. package/runtime/gatewaysdk/environment/schema/cache_layout.py +5 -0
  65. package/runtime/gatewaysdk/environment/schema/call_capture.py +309 -0
  66. package/runtime/gatewaysdk/environment/schema/call_log.py +503 -0
  67. package/runtime/gatewaysdk/environment/schema/call_redaction.py +526 -0
  68. package/runtime/gatewaysdk/environment/schema/cast.py +15 -35
  69. package/runtime/gatewaysdk/environment/schema/compiler.py +334 -158
  70. package/runtime/gatewaysdk/environment/schema/conform.py +14 -39
  71. package/runtime/gatewaysdk/environment/schema/connector.py +113 -211
  72. package/runtime/gatewaysdk/environment/schema/connectors/confluence/connector.toml +1 -12
  73. package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +1 -0
  74. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/connector.toml +2 -5
  75. package/runtime/gatewaysdk/environment/schema/cors.py +54 -0
  76. package/runtime/gatewaysdk/environment/schema/credentials.py +313 -8
  77. package/runtime/gatewaysdk/environment/schema/data.py +60 -216
  78. package/runtime/gatewaysdk/environment/schema/database/__init__.py +24 -0
  79. package/runtime/gatewaysdk/environment/schema/database/audit.py +121 -0
  80. package/runtime/gatewaysdk/environment/schema/database/base.py +936 -0
  81. package/runtime/gatewaysdk/environment/schema/database/budget.py +33 -0
  82. package/runtime/gatewaysdk/environment/schema/database/connections.py +101 -0
  83. package/runtime/gatewaysdk/environment/schema/database/engines.py +8 -0
  84. package/runtime/gatewaysdk/environment/schema/database/guard.py +215 -0
  85. package/runtime/gatewaysdk/environment/schema/database/ingest.py +154 -0
  86. package/runtime/gatewaysdk/environment/schema/database/matching.py +58 -0
  87. package/runtime/gatewaysdk/environment/schema/database/provenance.py +30 -0
  88. package/runtime/gatewaysdk/environment/schema/database/reads.py +169 -0
  89. package/runtime/gatewaysdk/environment/schema/database/rows.py +53 -0
  90. package/runtime/gatewaysdk/environment/schema/database/runtime_rows.py +39 -0
  91. package/runtime/gatewaysdk/environment/schema/database/sqlite.py +393 -0
  92. package/runtime/gatewaysdk/environment/schema/declared_routes.py +210 -0
  93. package/runtime/gatewaysdk/environment/schema/domain_migration.py +236 -0
  94. package/runtime/gatewaysdk/environment/schema/door.py +899 -0
  95. package/runtime/gatewaysdk/environment/schema/envelope.py +227 -0
  96. package/runtime/gatewaysdk/environment/schema/extract.py +6 -13
  97. package/runtime/gatewaysdk/environment/schema/grading.py +90 -103
  98. package/runtime/gatewaysdk/environment/schema/handler_errors.py +163 -12
  99. package/runtime/gatewaysdk/environment/schema/host.py +237 -1795
  100. package/runtime/gatewaysdk/environment/schema/host_control.py +144 -0
  101. package/runtime/gatewaysdk/environment/schema/host_handoff.py +370 -0
  102. package/runtime/gatewaysdk/environment/schema/host_loops.py +97 -0
  103. package/runtime/gatewaysdk/environment/schema/host_owners.py +121 -0
  104. package/runtime/gatewaysdk/environment/schema/host_proxy.py +111 -0
  105. package/runtime/gatewaysdk/environment/schema/host_requests.py +6 -0
  106. package/runtime/gatewaysdk/environment/schema/host_session.py +126 -0
  107. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +79 -21
  108. package/runtime/gatewaysdk/environment/schema/host_transfers.py +127 -0
  109. package/runtime/gatewaysdk/environment/schema/host_versions.py +242 -0
  110. package/runtime/gatewaysdk/environment/schema/host_workers.py +577 -0
  111. package/runtime/gatewaysdk/environment/schema/journal.py +437 -0
  112. package/runtime/gatewaysdk/environment/schema/lanes.py +53 -0
  113. package/runtime/gatewaysdk/environment/schema/ledger_spill.py +828 -0
  114. package/runtime/gatewaysdk/environment/schema/local.py +58 -170
  115. package/runtime/gatewaysdk/environment/schema/mapping.py +5 -25
  116. package/runtime/gatewaysdk/environment/schema/openapi_import.py +112 -73
  117. package/runtime/gatewaysdk/environment/schema/openapi_paging.py +147 -0
  118. package/runtime/gatewaysdk/environment/schema/openapi_payloads.py +288 -0
  119. package/runtime/gatewaysdk/environment/schema/openapi_routes.py +97 -102
  120. package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +113 -30
  121. package/runtime/gatewaysdk/environment/schema/platform.py +137 -187
  122. package/runtime/gatewaysdk/environment/schema/platform_import.py +2 -3
  123. package/runtime/gatewaysdk/environment/schema/platform_query.py +61 -5
  124. package/runtime/gatewaysdk/environment/schema/primary_key.py +61 -0
  125. package/runtime/gatewaysdk/environment/schema/proof.py +19 -12
  126. package/runtime/gatewaysdk/environment/schema/request_body.py +238 -0
  127. package/runtime/gatewaysdk/environment/schema/request_ledger.py +958 -0
  128. package/runtime/gatewaysdk/environment/schema/route_bindings.py +25 -3
  129. package/runtime/gatewaysdk/environment/schema/route_miss.py +54 -0
  130. package/runtime/gatewaysdk/environment/schema/runtime.py +178 -308
  131. package/runtime/gatewaysdk/environment/schema/served_names.py +58 -0
  132. package/runtime/gatewaysdk/environment/schema/session_files.py +275 -0
  133. package/runtime/gatewaysdk/environment/schema/session_move.py +275 -0
  134. package/runtime/gatewaysdk/environment/schema/skills/agents/connector-template-author.md +5 -1
  135. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +10 -11
  136. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +49 -16
  137. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +39 -9
  138. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +27 -27
  139. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +33 -33
  140. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +13 -7
  141. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +49 -1
  142. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +182 -0
  143. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/openapi-import.md +50 -21
  144. package/runtime/gatewaysdk/environment/schema/slack.py +4 -8
  145. package/runtime/gatewaysdk/environment/schema/snapshot.py +516 -140
  146. package/runtime/gatewaysdk/environment/schema/spill_files.py +228 -0
  147. package/runtime/gatewaysdk/environment/schema/store_contract.py +8 -14
  148. package/runtime/gatewaysdk/environment/schema/tasks.py +267 -276
  149. package/runtime/gatewaysdk/environment/schema/tools_world.py +146 -242
  150. package/runtime/gatewaysdk/environment/schema/ui.py +24 -5
  151. package/runtime/gatewaysdk/environment/schema/ui_static/app.js +100 -130
  152. package/runtime/gatewaysdk/environment/schema/ui_static/index.html +1 -8
  153. package/runtime/gatewaysdk/environment/schema/validation.py +235 -41
  154. package/runtime/gatewaysdk/environment/schema/verbs.py +32 -36
  155. package/runtime/gatewaysdk/environment/schema/worker.py +6 -4
  156. package/runtime/gatewaysdk/environment/schema/workers.py +345 -96
  157. package/runtime/gatewaysdk/environment/schema/world_host.py +953 -0
  158. package/runtime/gatewaysdk/environment/schema/world_sql.py +81 -0
  159. package/runtime/gatewaysdk/environment/schema/world_tests.py +80 -50
  160. package/runtime/gatewaysdk/environment/score.py +57 -0
  161. package/runtime/gatewaysdk/environment/secret_values.py +36 -0
  162. package/runtime/gatewaysdk/environment/world.py +43 -4
  163. package/runtime/gatewaysdk/environment/world_session_contract.py +46 -5
  164. package/skills/agents/connector-template-author.md +5 -1
  165. package/skills/benchmarks-getting-started/SKILL.md +10 -11
  166. package/skills/connector-schema-authoring/SKILL.md +49 -16
  167. package/skills/connector-schema-authoring/connector-worlds.md +142 -11
  168. package/skills/connector-schema-authoring/world-schema.md +103 -51
  169. package/skills/world-data-ingestion/ROWS.md +39 -9
  170. package/skills/world-data-ingestion/SKILL.md +27 -27
  171. package/skills/worlds-getting-started/SKILL.md +33 -33
  172. package/skills/worlds-getting-started/references/cli-mcp-map.md +13 -7
  173. package/skills/worlds-getting-started/references/gotchas.md +49 -1
  174. package/skills/worlds-getting-started/references/journal-checks.md +182 -0
  175. package/skills/worlds-getting-started/references/openapi-import.md +50 -21
  176. package/runtime/gatewaysdk/environment/schema/store.py +0 -1013
@@ -26,10 +26,10 @@ from typing import TYPE_CHECKING, Any
26
26
 
27
27
  from .._materialize import materialize_template
28
28
  from ..world import WorldTree
29
- from . import ContractError, SQLiteStore, bundle_mode, check_bundle, compile_bundle, platform_import, platform_query
29
+ from . import ContractError, WorldDatabase, bundle_mode, check_bundle, compile_bundle, platform_import, platform_query
30
30
  from . import snapshot as snapshots
31
31
  from .cast import world_fields
32
- from .compiler import retarget_empty_journals
32
+ from .compiler import CompilePlan, retarget_journals
33
33
  from .handler_scan import HandlerScan
34
34
  from .redaction import check_world_redaction
35
35
  from .scaffold import request_files
@@ -73,6 +73,8 @@ COMMANDS = (
73
73
  "reconcile",
74
74
  "counts",
75
75
  "query",
76
+ "sql",
77
+ "verify-legacy",
76
78
  "api-bundle",
77
79
  "templates",
78
80
  "validate-rows",
@@ -90,20 +92,15 @@ def compile_world(root: Path) -> dict:
90
92
 
91
93
  The platform stores compiled trees, so a world whose authored inputs changed
92
94
  (``schema/world.json``, ``gateway-env.toml``, handlers) is recompiled here
93
- rather than rejected with ``lock_mismatch``. Only a journal that holds no
94
- state (``mutations == []``) follows the contract to its new identity, even
95
- across a changed ``$id`` (``retarget_empty_journals``); a journal with rows is
96
- refused, never migrated silently — state migration stays manual (re-import
97
- the rows against the new schema). The snapshots are then rebuilt loudly:
98
- data the contract refuses is a rejection, not a dropped snapshot.
95
+ rather than rejected with ``lock_mismatch``. A journal follows the contract when
96
+ its rows carry over (``retarget_journals``) and is refused otherwise, before
97
+ anything is written. The snapshots are then rebuilt loudly: data the contract
98
+ refuses is a rejection, not a dropped snapshot.
99
99
  """
100
100
  from .snapshot import build_all
101
101
 
102
102
  if bundle_mode(root) is None:
103
- fail(
104
- "mode",
105
- "Expected a schema-backed mock-tools world (gateway-env.toml with [schema] language)",
106
- )
103
+ fail("mode", "Expected a schema-backed mock-tools world (gateway-env.toml with [schema] language)")
107
104
  added = []
108
105
  base = root / "schema/base.json"
109
106
  if not base.exists():
@@ -112,7 +109,9 @@ def compile_world(root: Path) -> dict:
112
109
  base.parent.mkdir(parents=True, exist_ok=True)
113
110
  base.write_bytes((TEMPLATES / "base.json").read_bytes())
114
111
  added.append("schema/base.json")
115
- contract = compile_bundle(root, snapshots=False)
112
+ plan = CompilePlan.of(root)
113
+ retargeted = retarget_journals(root, plan.contract)
114
+ contract = plan.write()
116
115
  initial = root / "data/initial.json"
117
116
  if not initial.exists():
118
117
  initial.parent.mkdir(parents=True, exist_ok=True)
@@ -128,7 +127,6 @@ def compile_world(root: Path) -> dict:
128
127
  )
129
128
  )
130
129
  added.append("data/initial.json")
131
- retargeted = retarget_empty_journals(root, contract)
132
130
  build_all(root, contract)
133
131
  return {"added": added, "retargeted": retargeted}
134
132
 
@@ -143,6 +141,7 @@ def append_batch(root: Path, batch: dict, *, source: str | None = None) -> dict:
143
141
  Replaying every prior journal first makes a repeated batch id idempotent and
144
142
  a reused id with different content a conflict, exactly as in the store.
145
143
  """
144
+ snapshots.refuse_pinned_rows(root)
146
145
  contract = check_bundle(root)
147
146
  members(
148
147
  batch,
@@ -151,7 +150,7 @@ def append_batch(root: Path, batch: dict, *, source: str | None = None) -> dict:
151
150
  "/batch",
152
151
  )
153
152
  nonempty(batch["id"], "/batch/id")
154
- if "target" in batch and batch["target"] != contract.target:
153
+ if "target" in batch and not contract.targets(batch["target"]):
155
154
  fail(
156
155
  "batch_target",
157
156
  "Batch targets a different domain identity/version/hash",
@@ -182,7 +181,7 @@ def append_batch(root: Path, batch: dict, *, source: str | None = None) -> dict:
182
181
  journals = journal_paths(root)
183
182
  with (
184
183
  tempfile.TemporaryDirectory(prefix="gateway-apply-batch-") as temporary,
185
- SQLiteStore.create(Path(temporary) / "state.sqlite", contract) as store,
184
+ WorldDatabase.create(Path(temporary) / "world.db", contract) as store,
186
185
  ):
187
186
  for path in journals:
188
187
  store.apply_batch(read_json(path))
@@ -195,9 +194,8 @@ def append_batch(root: Path, batch: dict, *, source: str | None = None) -> dict:
195
194
  existing = len(journals) - 1
196
195
  target = batches / f"{existing + 1:06d}-{digest(batch['id'].encode())[:16]}.json"
197
196
  target.write_bytes(encoded(resolved))
198
- if snapshots.default_snapshot(root).is_file():
199
- # The journals grew; a snapshot built before this batch would be served
200
- # over them. Rebuild so the tree stays one thing (default + scenarios).
197
+ if snapshots.has_default_snapshot(root):
198
+ # A snapshot built before this batch would be served over the grown journals.
201
199
  from .compiler import build
202
200
  from .snapshot import build_all
203
201
 
@@ -205,38 +203,6 @@ def append_batch(root: Path, batch: dict, *, source: str | None = None) -> dict:
205
203
  return {**result, "journal": str(target.relative_to(root))}
206
204
 
207
205
 
208
- def _pinned_state(bundle: Path, contract) -> dict[str, int] | None:
209
- """The entity counts of a data-only version whose hosted snapshot is not in the
210
- tree: ``db/snapshot.json`` alone. The platform audited that snapshot through
211
- this contract when it built it, so the pin stands in for the state check —
212
- provided it names this contract; a snapshot built through another contract
213
- is refused, since the tree's data files cannot reproduce it either. A tree
214
- that carries its snapshot, or no pin at all, materializes as usual."""
215
- from .snapshot import contract_hash, current_default, pinned_default
216
-
217
- pin = pinned_default(bundle)
218
- if pin is None or current_default(bundle, contract) is not None:
219
- return None
220
- if pin.get("contractHash") != contract_hash(contract):
221
- fail(
222
- "snapshot_pinned",
223
- "db/snapshot.json pins a hosted snapshot built through a different contract; "
224
- "re-import its rows against the current schema (import_world_data, "
225
- "gateway worlds data import) or restore the schema it was built against",
226
- "/db/snapshot.json",
227
- )
228
- counts = pin.get("entityCounts")
229
- if not isinstance(counts, dict) or any(
230
- not isinstance(value, int) or isinstance(value, bool) for value in counts.values()
231
- ):
232
- fail(
233
- "snapshot_pin",
234
- "db/snapshot.json must carry the hosted snapshot's entityCounts",
235
- "/db/snapshot.json",
236
- )
237
- return {entity: int(counts.get(entity, 0)) for entity in contract.entities}
238
-
239
-
240
206
  def validate_bundle(bundle: str | Path, *, execute: bool = False) -> dict:
241
207
  """Check a schema world: the contract, the handlers by syntax and by name, the
242
208
  initial state, every verifier over it, the tasks and the links. ``execute``
@@ -255,14 +221,13 @@ def validate_bundle(bundle: str | Path, *, execute: bool = False) -> dict:
255
221
  load_api_settings(bundle, parse_spec((bundle / "connector.toml").read_text(encoding="utf-8")))
256
222
  _check_mappings(bundle, contract)
257
223
  check_world_redaction(bundle)
258
- pinned = _pinned_state(bundle, contract)
224
+ pinned = snapshots.pinned_counts(bundle, contract)
259
225
  verifiers: dict[str, Any] = {}
260
226
  if pinned is not None:
261
227
  counts, initial_state = pinned, "pinned"
262
- # The pinned snapshot is not in the tree, so the verifiers run over the
263
- # bare schema: an error still surfaces; a score means nothing here.
228
+ # The pinned snapshot is not in the tree: an error still surfaces, a score means nothing.
264
229
  with tempfile.TemporaryDirectory(prefix="gateway-state-check-") as staging:
265
- with SQLiteStore.create(Path(staging) / "world.db", contract) as store:
230
+ with WorldDatabase.create(Path(staging) / "world.db", contract) as store:
266
231
  unattached = _attach_dependencies(bundle, store, Path(staging))
267
232
  verifiers = _check_verifiers(bundle, store, unattached, scored=False)
268
233
  else:
@@ -270,7 +235,7 @@ def validate_bundle(bundle: str | Path, *, execute: bool = False) -> dict:
270
235
  with tempfile.TemporaryDirectory(prefix="gateway-state-check-") as staging:
271
236
  database = Path(staging) / "world.db"
272
237
  materialize_template(bundle, database)
273
- with SQLiteStore.open(database, contract) as store:
238
+ with WorldDatabase.open(database, contract) as store:
274
239
  store.audit()
275
240
  counts = {entity: len(store.list(entity)) for entity in contract.entities}
276
241
  unattached = _attach_dependencies(bundle, store, Path(staging))
@@ -280,8 +245,9 @@ def validate_bundle(bundle: str | Path, *, execute: bool = False) -> dict:
280
245
  "domain": contract.target,
281
246
  "package": contract.metadata["package"],
282
247
  "initial_state": initial_state,
283
- "handler_execution": _handler_execution(bundle, execute, declared),
248
+ "handler_execution": _handler_execution(bundle, execute, declared, hosted=pinned is not None),
284
249
  "entity_counts": counts,
250
+ "data_migration": snapshots.migration_view(bundle, contract),
285
251
  "tools": sorted(declared),
286
252
  "verifiers": verifiers,
287
253
  "tasks": _check_tasks(bundle, sorted(verifiers)),
@@ -294,7 +260,7 @@ def _check_mappings(bundle: Path, contract: Contract) -> None:
294
260
  """Each ``[dependencies.<alias>.entities]`` mapping against this contract
295
261
  and, for a dependency whose ``path`` is here, against that contract too."""
296
262
  from .. import _bundle
297
- from .dependencies import FieldMap, check_mappings, parse_dependencies
263
+ from .dependencies import check_mappings, parse_dependencies
298
264
 
299
265
  dependencies = parse_dependencies(_bundle.parse_manifest(bundle).raw)
300
266
  deps: dict[str, FieldMap] = {}
@@ -311,7 +277,7 @@ def _field_map(contract: Contract) -> FieldMap:
311
277
  return {name: set(entity["schema"].get("properties", {})) for name, entity in contract.entities.items()}
312
278
 
313
279
 
314
- def _attach_dependencies(bundle: Path, store: SQLiteStore, staging: Path) -> dict[str, str]:
280
+ def _attach_dependencies(bundle: Path, store: WorldDatabase, staging: Path) -> dict[str, str]:
315
281
  """Each ``[dependencies]`` entry whose local ``path`` is on this machine,
316
282
  materialized beside the root's store and attached as ``<alias>.<table>``,
317
283
  so a cross-world verifier runs here the way it runs in a session. Returns
@@ -343,7 +309,7 @@ def _attach_dependencies(bundle: Path, store: SQLiteStore, staging: Path) -> dic
343
309
  return unattached
344
310
 
345
311
 
346
- def _check_verifiers(bundle: Path, store: SQLiteStore, unattached: dict[str, str], *, scored: bool) -> dict[str, Any]:
312
+ def _check_verifiers(bundle: Path, store: WorldDatabase, unattached: dict[str, str], *, scored: bool) -> dict[str, Any]:
347
313
  """Every ``verifiers/*.sql`` run over the template through the store's
348
314
  read-only authorizer, the way a session grades. A verifier that names a
349
315
  table or column the contract lacks is refused here — at check — not at
@@ -362,11 +328,13 @@ def _check_verifiers(bundle: Path, store: SQLiteStore, unattached: dict[str, str
362
328
  return out
363
329
 
364
330
 
365
- def _check_verifier(path: Path, store: SQLiteStore, unattached: dict[str, str], *, scored: bool) -> dict[str, Any]:
331
+ def _check_verifier(path: Path, store: WorldDatabase, unattached: dict[str, str], *, scored: bool) -> dict[str, Any]:
366
332
  from .._world import SqlVerifier, VerifierError
367
333
 
368
334
  try:
369
- score, _sql = SqlVerifier.read(path).score(lambda statement: store.query(statement, private=True))
335
+ score, _sql = SqlVerifier.read(path, store.split_statements).score(
336
+ lambda statement: store.query(statement, private=True)
337
+ )
370
338
  except ContractError as error:
371
339
  alias = _refuse_verifier(path, store, unattached, error)
372
340
  return {
@@ -381,15 +349,16 @@ def _check_verifier(path: Path, store: SQLiteStore, unattached: dict[str, str],
381
349
  return {"status": "ok", "initial_score": score}
382
350
 
383
351
 
384
- def _refuse_verifier(path: Path, store: SQLiteStore, unattached: dict[str, str], error: ContractError) -> str:
352
+ def _refuse_verifier(path: Path, store: WorldDatabase, unattached: dict[str, str], error: ContractError) -> str:
385
353
  """The unattached dependency alias the failure names — the one refusal
386
354
  check reports rather than raises; every other failure is refused here."""
387
355
  reason = error.__cause__ if error.__cause__ is not None else error.detail["message"]
388
- alias = _missing_dependency_alias(str(reason), unattached)
356
+ missing = store.missing_table(reason)
357
+ alias = _missing_dependency_alias(missing, unattached)
389
358
  if alias is not None:
390
359
  return alias
391
360
  hint = ""
392
- if "no such table" in str(reason):
361
+ if missing is not None:
393
362
  tables = sorted(store.contract.entities)
394
363
  tables += [f"{a}.{t}" for a, ts in sorted(store.attached.items()) for t in sorted(ts)]
395
364
  hint = f"; the world's entities are {', '.join(tables) or '(none)'}"
@@ -400,14 +369,9 @@ def _refuse_verifier(path: Path, store: SQLiteStore, unattached: dict[str, str],
400
369
  )
401
370
 
402
371
 
403
- def _missing_dependency_alias(reason: str, unattached: dict[str, str]) -> str | None:
404
- """The alias of an unattached dependency a ``no such table: alias.table``
405
- failure names, else ``None``."""
406
- marker = "no such table: "
407
- if marker not in reason:
408
- return None
409
- table = reason.split(marker, 1)[1].strip()
410
- alias, dot, _ = table.partition(".")
372
+ def _missing_dependency_alias(table: str | None, unattached: dict[str, str]) -> str | None:
373
+ """The alias of an unattached dependency a missing ``alias.table`` names, else ``None``."""
374
+ alias, dot, _ = (table or "").partition(".")
411
375
  if dot and alias in unattached:
412
376
  return alias
413
377
  return None
@@ -420,7 +384,7 @@ def _check_tasks(bundle: Path, verifiers: list[str]) -> list[dict[str, Any]]:
420
384
  from .tools_world import load_tasks
421
385
 
422
386
  manifest = _bundle.parse_manifest(bundle)
423
- tasks = load_tasks(bundle, manifest, verifiers, required=False)
387
+ tasks = load_tasks(bundle, manifest, verifiers)
424
388
  out = []
425
389
  for task in tasks.values():
426
390
  unknown = sorted(set(task.selected(verifiers)) - set(verifiers))
@@ -475,9 +439,7 @@ def describe_dependencies(bundle: Path) -> list[dict[str, Any]]:
475
439
  return out
476
440
 
477
441
 
478
- #: Set by a runtime that may run the world's own Python — the CLI's bundled
479
- #: runtime on the author's machine. The platform's bridge never sets it, so a
480
- #: request that asks for execution there gets ``not_run`` and the reason.
442
+ # Only the CLI's bundled runtime sets this; the platform's bridge never runs the world's own Python.
481
443
  EXECUTE_ENV = "GATEWAY_RUNTIME_EXECUTE"
482
444
 
483
445
 
@@ -485,14 +447,15 @@ def may_execute() -> bool:
485
447
  return os.environ.get(EXECUTE_ENV) == "1"
486
448
 
487
449
 
488
- def _handler_execution(bundle: Path, execute: bool, declared: set[str]) -> dict[str, Any]:
450
+ def _handler_execution(bundle: Path, execute: bool, declared: set[str], *, hosted: bool) -> dict[str, Any]:
489
451
  """Whether the handlers were run: imported, every declared tool bound, the
490
452
  ``[dependencies]`` opened from their paths — one session of the world,
491
- opened and closed. Only where authored code may run. ``tools`` is the
492
- declared handlers the session bound (the report's top-level ``tools``);
493
- ``served`` every name ``worlds call`` answers there — handlers, the connector
494
- routes as operations, a dependency's ``alias.tool`` — so the two lists differ
495
- by design and say what each counts."""
453
+ opened and closed. Only where authored code may run, and only over rows this
454
+ tree holds (``hosted``: its data is a snapshot the platform keeps). ``tools`` is
455
+ the declared handlers the session bound (the report's top-level ``tools``);
456
+ ``served`` every name ``worlds call`` answers there — the handlers and a
457
+ dependency's ``alias.tool``; a connector route answers over HTTP, never by
458
+ name — so the two lists differ by design and say what each counts."""
496
459
  if not execute:
497
460
  return {
498
461
  "status": "not_run",
@@ -505,6 +468,12 @@ def _handler_execution(bundle: Path, execute: bool, declared: set[str]) -> dict[
505
468
  "reason": "this runtime does not run a world's Python (the platform's "
506
469
  "bridge); check with the CLI's bundled runtime on your machine",
507
470
  }
471
+ if hosted:
472
+ return {
473
+ "status": "not_run",
474
+ "reason": "this world's rows are the hosted snapshot db/snapshot.json pins, which "
475
+ "is not in this tree; `gateway worlds session open <slug>` runs the handlers over it",
476
+ }
508
477
  from .local import open_world
509
478
 
510
479
  with open_world(bundle, http=False) as session:
@@ -520,11 +489,10 @@ def _handler_execution(bundle: Path, execute: bool, declared: set[str]) -> dict[
520
489
 
521
490
 
522
491
  def world_root(root: Path) -> Path:
523
- """The world inside the tree the platform holds (``WorldTree.world``).
524
- ``bench push`` uploads a schema world as its api bundle, so a version's
525
- tree is ``gateway-api-world.toml`` + ``seed/`` + ``scenarios/`` +
526
- ``server/world/<the authoring world>``: that nested world is what data
527
- commands operate on. A plain tree is its own root."""
492
+ """The world inside the tree the platform holds (``WorldTree.world``). A
493
+ version stored as an api bundle is ``gateway-api-world.toml`` + ``seed/`` +
494
+ ``scenarios/`` + ``server/world/<the authoring world>``: that nested world
495
+ is what data commands operate on. A plain tree is its own root."""
528
496
  return WorldTree.from_dir(root).world
529
497
 
530
498
 
@@ -626,8 +594,7 @@ def _capture(request: dict) -> dict:
626
594
  fail("input", "Expected the connector.toml text and an operation name")
627
595
  if not isinstance(args, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in args.items()):
628
596
  fail("input", "args map names to strings")
629
- # params arrive as [[name, value], ...] so a repeated key survives the wire; the
630
- # {name: value} form older callers send is accepted too.
597
+ # Pairs so a repeated key survives the wire; older callers still send a mapping.
631
598
  try:
632
599
  params = pairs_of(request.get("params"))
633
600
  except ContractError:
@@ -691,7 +658,6 @@ def _template_summary(files: dict[str, bytes]) -> dict:
691
658
  from .redaction import parse_env_policy
692
659
  from .scaffold import template_digest
693
660
 
694
- # A template keeps world.json at its root; an initialized world keeps it under schema/.
695
661
  world_path = next((path for path in ("world.json", "schema/world.json") if path in files), None)
696
662
  if world_path is None:
697
663
  fail(
@@ -759,8 +725,6 @@ def _template_summary(files: dict[str, bytes]) -> dict:
759
725
 
760
726
 
761
727
  COMPILED_MARKERS = ("schema/world.json", "tool-schemas.json")
762
- # The compiled world's files a description is read from; the rest of a bundle
763
- # (seed data, verifiers, tool sources) says nothing about the contract.
764
728
  DESCRIBE_PATHS = (
765
729
  "schema/world.json",
766
730
  "tool-schemas.json",
@@ -781,13 +745,13 @@ def _describe(request: dict) -> dict:
781
745
  straight through. Never runs the connector's Python."""
782
746
  from .connector import load_spec, parse_spec
783
747
  from .redaction import env_policy
784
- from .ui import ui_kind
785
748
  from .scaffold import (
786
749
  TEMPLATES,
787
750
  init_bundle,
788
751
  init_bundle_from_files,
789
752
  template_digest,
790
753
  )
754
+ from .ui import ui_kind
791
755
 
792
756
  connector = request.get("connector")
793
757
  with tempfile.TemporaryDirectory(prefix="gateway-schema-") as directory:
@@ -841,8 +805,7 @@ def _describe(request: dict) -> dict:
841
805
  try:
842
806
  settings = load_api_settings(root, spec)
843
807
  except ContractError:
844
- # A template without its handlers still has a shape worth showing;
845
- # the routes render with the default action and status.
808
+ # A template without its handlers still has a shape worth showing.
846
809
  settings = None
847
810
  _annotate_redaction(summary["entities"], spec)
848
811
  summary["connection"] = {
@@ -914,7 +877,7 @@ def _ingest_calls(request: dict) -> dict:
914
877
  )
915
878
  answer: dict = {"status": "ok", **report}
916
879
  if report["changed"] and report.get("kind") == KIND_SCHEMA:
917
- if snapshots.default_snapshot(world).is_file():
880
+ if snapshots.has_default_snapshot(world):
918
881
  from .compiler import build
919
882
  from .snapshot import build_all
920
883
 
@@ -952,7 +915,7 @@ def _chunk_specs(workdir: Path, request: dict) -> list:
952
915
  from .batch import ChunkSpec
953
916
 
954
917
  listed = request.get("chunks")
955
- if not isinstance(listed, list) or not listed:
918
+ if not isinstance(listed, list):
956
919
  fail("input", "Expected chunks as [{ordinal, path, entity?}]")
957
920
  specs = []
958
921
  seen = set()
@@ -1035,14 +998,16 @@ def _redactor(root: Path, request: dict):
1035
998
 
1036
999
 
1037
1000
  def _snapshot_build(request: dict) -> dict:
1038
- """``snapshot-build``: the parent snapshot (or the tree's default) with the chunks
1039
- applied in dependency order, one transaction (atomic) or one per chunk; the new
1040
- snapshot saved under workdir with its sidecar, or nothing on dryRun or an atomic
1041
- refusal."""
1001
+ """``snapshot-build``: the parent snapshot (or the tree's default), carried to the
1002
+ tree's contract when that only adds to the domain its rows were stored under, with
1003
+ the chunks applied in dependency order, one transaction (atomic) or one per chunk;
1004
+ the new snapshot saved under workdir with its sidecar (its absolute path answered),
1005
+ or nothing on dryRun or an atomic refusal."""
1042
1006
  from .batch import build_batch
1043
1007
  from .compiler import check_bundle
1044
1008
  from .data import MERGES, MODES
1045
- from .snapshot import EMPTY_DIGEST, build_default, default_snapshot
1009
+ from .domain_migration import DomainMigration
1010
+ from .snapshot import EMPTY_DIGEST, SIDECAR, build_default, default_snapshot, snapshot_name
1046
1011
 
1047
1012
  workdir = _workdir(request)
1048
1013
  mode = request.get("mode", "append")
@@ -1063,21 +1028,21 @@ def _snapshot_build(request: dict) -> dict:
1063
1028
  contract = check_bundle(root)
1064
1029
  redactor = _redactor(root, request)
1065
1030
  chunks = _chunk_specs(workdir, request)
1066
- # One directory per batch, so a parent built by an earlier call in the same
1067
- # workdir is never the file being written.
1031
+ # One directory per batch, so a parent built by an earlier call is never the file being written.
1068
1032
  out_dir = workdir / "snapshot" / batch_id
1069
1033
  out_dir.mkdir(parents=True, exist_ok=True)
1070
- out = out_dir / "state.sqlite"
1034
+ out = out_dir / snapshot_name(contract)
1071
1035
  out.unlink(missing_ok=True)
1072
- out.with_name("state.json").unlink(missing_ok=True)
1036
+ out.with_name(SIDECAR).unlink(missing_ok=True)
1073
1037
  if request.get("parentSnapshot") is not None:
1074
1038
  parent = _under(workdir, request["parentSnapshot"], "parentSnapshot")
1075
1039
  if not parent.is_file():
1076
1040
  fail("input", "parentSnapshot is missing under workdir")
1077
- shutil.copyfile(parent, out)
1041
+ WorldDatabase.clone_file(parent, out)
1042
+ DomainMigration.carry(out, contract, root)
1078
1043
  else:
1079
1044
  build_default(root, contract)
1080
- shutil.copyfile(default_snapshot(root), out)
1045
+ WorldDatabase.clone_file(default_snapshot(root, contract), out)
1081
1046
  result = build_batch(
1082
1047
  contract,
1083
1048
  out,
@@ -1091,7 +1056,6 @@ def _snapshot_build(request: dict) -> dict:
1091
1056
  redactor=redactor,
1092
1057
  )
1093
1058
  if "snapshot" in result:
1094
- # Absolute, under workdir: the caller opens it as it is.
1095
1059
  result["snapshot"] = str(result["snapshot"])
1096
1060
  return {"status": "ok", **result}
1097
1061
 
@@ -1100,20 +1064,20 @@ def _snapshot_default(request: dict) -> dict:
1100
1064
  """``snapshot-default``: the tree's default snapshot and every scenario snapshot,
1101
1065
  built under ``workdir/tree``; the sidecars come back with absolute paths."""
1102
1066
  from .compiler import check_bundle
1103
- from .snapshot import build_all, default_snapshot, scenario_snapshot
1067
+ from .snapshot import build_all, build_default, default_snapshot, scenario_snapshot
1104
1068
 
1105
1069
  workdir = _workdir(request)
1106
1070
  root = _write_tree(workdir, request)
1107
- built = build_all(root, check_bundle(root))
1108
- # Paths are absolute, under workdir; the sidecar sits both at the top level and
1109
- # keyed by its tree path, so a reader may take either.
1071
+ contract = check_bundle(root)
1072
+ build_default(root, contract)
1073
+ built = build_all(root, contract)
1110
1074
  return {
1111
1075
  "status": "ok",
1112
- "snapshot": str(default_snapshot(root)),
1076
+ "snapshot": str(default_snapshot(root, contract)),
1113
1077
  "sidecar": built["default"],
1114
1078
  "sidecars": {"db/state.json": built["default"]},
1115
1079
  "scenarios": {
1116
- name: {"snapshot": str(scenario_snapshot(root, name)), "sidecar": sidecar}
1080
+ name: {"snapshot": str(scenario_snapshot(root, name, contract)), "sidecar": sidecar}
1117
1081
  for name, sidecar in built["scenarios"].items()
1118
1082
  },
1119
1083
  }
@@ -1154,7 +1118,6 @@ def _ingest(request: dict) -> dict:
1154
1118
  root.mkdir()
1155
1119
  _write_files(root, request.get("files"))
1156
1120
  if dry_run:
1157
- # Every violation of every capture, grouped; no files come back since none changed.
1158
1121
  return {"status": "ok", "result": check(world_root(root))}
1159
1122
  result = ingest(world_root(root), batch_id=batch_id)
1160
1123
  return {"status": "ok", "result": result, "files": _tree(root)}
@@ -1259,17 +1222,22 @@ def _world_for(request: dict, staging: Path) -> Path:
1259
1222
  is copied."""
1260
1223
  if request.get("workdir") is not None:
1261
1224
  return _prepared_tree(request)
1262
- world = request.get("world")
1263
- if world is None:
1225
+ if request.get("world") is None:
1264
1226
  root = staging / "world"
1265
1227
  root.mkdir()
1266
1228
  _write_files(root, request.get("files"))
1267
1229
  return world_root(root)
1230
+ return world_root(_local_tree(request))
1231
+
1232
+
1233
+ def _local_tree(request: dict) -> Path:
1234
+ """``world``, opened in place: an absolute directory on this machine, only where this runtime may run authored code."""
1235
+ world = request.get("world")
1268
1236
  if not may_execute():
1269
1237
  fail("input", "world is a local-runtime field; this runtime takes files")
1270
1238
  if not isinstance(world, str) or not Path(world).is_absolute() or not Path(world).is_dir():
1271
1239
  fail("input", "world must be an absolute path to a directory on this machine")
1272
- return world_root(Path(world).resolve())
1240
+ return Path(world).resolve()
1273
1241
 
1274
1242
 
1275
1243
  def _call(request: dict) -> dict:
@@ -1323,7 +1291,7 @@ def _dry_run(request: dict) -> dict:
1323
1291
  task card (prompt, tools, verifiers), the state's rows per entity, and
1324
1292
  ``grade`` — or, when a verifier cannot run (bad SQL, a missing entity),
1325
1293
  ``grade: null`` and ``verifier_errors`` naming each verifier that failed
1326
- with SQLite's own words. That is the point of the dry run: a benchmark
1294
+ with the database engine's own words. That is the point of the dry run: a benchmark
1327
1295
  whose grader dies is found here, not on the runner. Only where this
1328
1296
  runtime may run a world's Python (:func:`may_execute`)."""
1329
1297
  from ..errors import VerifierError
@@ -1364,7 +1332,7 @@ def _dry_run(request: dict) -> dict:
1364
1332
  return answer
1365
1333
  except (ContractError, VerifierError):
1366
1334
  pass
1367
- # Name the verifier: the grade runs them together, so run each alone.
1335
+ # The grade runs the verifiers together, so run each alone to name the failing one.
1368
1336
  errors: dict[str, str] = {}
1369
1337
  for name in card["verifiers"]:
1370
1338
  try:
@@ -1409,81 +1377,59 @@ def _templates(request: dict) -> dict:
1409
1377
  return {"status": "ok", "templates": templates}
1410
1378
 
1411
1379
 
1380
+ def _answering_commands() -> dict:
1381
+ """The commands that answer on their own, without the shared write-validate-return tree below."""
1382
+ return {
1383
+ "validate-rows": _validate_rows,
1384
+ "snapshot-build": _snapshot_build,
1385
+ "snapshot-default": _snapshot_default,
1386
+ "capture": _capture,
1387
+ "import-data": platform_import.import_data,
1388
+ "import-files": lambda request: platform_import.import_files(request, _world_for),
1389
+ "chunk-files": lambda request: platform_import.chunk_files(request, _world_for),
1390
+ "ingest": _ingest,
1391
+ "ingest-calls": _ingest_calls,
1392
+ "conform": _conform,
1393
+ "reconcile": _reconcile,
1394
+ "run-tests": _run_tests,
1395
+ "call": _call,
1396
+ "dry-run": _dry_run,
1397
+ "counts": lambda request: platform_query.counts(request, _world_for),
1398
+ "query": lambda request: platform_query.query(request, _world_for),
1399
+ "sql": lambda request: platform_query.sql(request, _world_for),
1400
+ "verify-legacy": lambda request: platform_query.verify_legacy(request, _world_for),
1401
+ "templates": _templates,
1402
+ "api-bundle": _api_bundle,
1403
+ "template-summary": lambda request: _template_summary(request_files(request)),
1404
+ "describe": _describe,
1405
+ }
1406
+
1407
+
1412
1408
  def execute(request: dict) -> dict:
1413
1409
  if not isinstance(request, dict) or request.get("command") not in COMMANDS:
1414
- fail(
1415
- "command",
1416
- "Expected one of " + ", ".join(COMMANDS[:-1]) + " or " + COMMANDS[-1],
1417
- )
1418
- if request["command"] == "validate-rows":
1419
- return _validate_rows(request)
1420
- if request["command"] == "snapshot-build":
1421
- return _snapshot_build(request)
1422
- if request["command"] == "snapshot-default":
1423
- return _snapshot_default(request)
1424
- if request["command"] == "capture":
1425
- return _capture(request)
1426
- if request["command"] == "import-data":
1427
- return platform_import.import_data(request)
1428
- if request["command"] == "import-files":
1429
- return platform_import.import_files(request, _world_for)
1430
- if request["command"] == "chunk-files":
1431
- return platform_import.chunk_files(request, _world_for)
1432
- if request["command"] == "ingest":
1433
- return _ingest(request)
1434
- if request["command"] == "ingest-calls":
1435
- return _ingest_calls(request)
1436
- if request["command"] == "conform":
1437
- return _conform(request)
1438
- if request["command"] == "reconcile":
1439
- return _reconcile(request)
1440
- if request["command"] == "run-tests":
1441
- return _run_tests(request)
1442
- if request["command"] == "call":
1443
- return _call(request)
1444
- if request["command"] == "dry-run":
1445
- return _dry_run(request)
1446
- if request["command"] == "counts":
1447
- return platform_query.counts(request, _world_for)
1448
- if request["command"] == "query":
1449
- return platform_query.query(request, _world_for)
1450
- if request["command"] == "templates":
1451
- return _templates(request)
1452
- if request["command"] == "api-bundle":
1453
- return _api_bundle(request)
1454
- if request["command"] == "template-summary":
1455
- return _template_summary(request_files(request))
1456
- if request["command"] == "describe":
1457
- return _describe(request)
1410
+ fail("command", "Expected one of " + ", ".join(COMMANDS[:-1]) + " or " + COMMANDS[-1])
1411
+ handler = _answering_commands().get(request["command"])
1412
+ if handler is not None:
1413
+ return handler(request)
1458
1414
  extra: dict = {}
1459
1415
  with tempfile.TemporaryDirectory(prefix="gateway-schema-") as directory:
1460
1416
  root = Path(directory) / "bundle"
1461
1417
  root.mkdir()
1462
1418
  if request["command"] == "validate-archive":
1463
1419
  _write_files(root, _archive_files(request.get("archive")))
1464
- # A stored version may be the api bundle of a schema world: the
1465
- # world lives under server/world, and that is what gets validated.
1466
1420
  root = world_root(root)
1467
1421
  if bundle_mode(root) is None:
1468
1422
  return {"status": "ok", "mode": "legacy"}
1469
- if request["command"] == "validate" and request.get("world") is not None:
1470
- # The CLI's bundled runtime checks a directory in place, so the
1471
- # ``[dependencies]`` paths beside it resolve and its handlers may run.
1472
- root = _world_for(request, Path(directory))
1473
- elif request["command"] in (
1474
- "validate",
1475
- "compile",
1476
- "apply-batch",
1477
- "refresh-slack",
1478
- ):
1423
+ in_place = request["command"] in ("validate", "compile") and request.get("world") is not None
1424
+ if in_place:
1425
+ # In place, so the ``[dependencies]`` paths beside it resolve and its snapshots are compiled where they are.
1426
+ root = _local_tree(request)
1427
+ elif request["command"] in ("validate", "compile", "apply-batch", "refresh-slack"):
1479
1428
  _write_files(root, request.get("files"))
1480
- # The tree the platform sent may be a schema world's api bundle; the
1481
- # world itself sits under server/world and is what compiles, takes a
1482
- # batch and validates. The whole tree still travels back.
1429
+ # A schema world's api bundle keeps the world under server/world; the whole tree still travels back.
1483
1430
  world = world_root(root)
1484
1431
  if request["command"] == "compile":
1485
- # Arbitrary custom worlds: the agent authors schema/world.json (+ manifest,
1486
- # handlers, journals); the trusted compiler owns every generated artifact.
1432
+ # The agent authors schema/world.json; the trusted compiler owns every generated artifact.
1487
1433
  extra["compile"] = compile_world(world)
1488
1434
  if world != root and (world / "data/initial.json").is_file():
1489
1435
  from .api import write_base_seed
@@ -1511,8 +1457,7 @@ def execute(request: dict) -> dict:
1511
1457
  with_example_tool=request.get("with_example_tool") is True,
1512
1458
  )
1513
1459
  if request["command"] == "init-template-files":
1514
- # A workspace connector: the template arrives as files, never as a path
1515
- # the request chose, and the world is built exactly as from an installed one.
1460
+ # The template arrives as files, never as a path the request chose.
1516
1461
  from .scaffold import init_bundle_from_files
1517
1462
 
1518
1463
  connector = request.get("connector")
@@ -1539,7 +1484,7 @@ def execute(request: dict) -> dict:
1539
1484
  **validate_bundle(world_root(root), execute=_flag(request, "execute", False)),
1540
1485
  **extra,
1541
1486
  }
1542
- if request["command"] not in ("validate", "validate-archive"):
1487
+ if request["command"] not in ("validate", "validate-archive") and not in_place:
1543
1488
  paths = [path for path in sorted(root.rglob("*")) if path.is_file()]
1544
1489
  if len(paths) > MAX_FILES:
1545
1490
  fail("size", f"The world tree has {len(paths)} files, over the {MAX_FILES} limit")
@@ -1558,11 +1503,16 @@ def main():
1558
1503
  raw = sys.stdin.buffer.read(2 * MAX_BYTES + 1)
1559
1504
  if len(raw) > 2 * MAX_BYTES:
1560
1505
  fail("size", "Bridge request is too large")
1561
- result = execute(json.loads(raw))
1506
+ request = json.loads(raw)
1507
+ platform_query.cap_memory_for(request)
1508
+ result = execute(request)
1562
1509
  print(json.dumps(result, sort_keys=True))
1563
1510
  except ContractError as error:
1564
1511
  print(json.dumps({"status": "rejected", "error": error.detail}, sort_keys=True))
1565
1512
  return 1
1513
+ except MemoryError:
1514
+ print(json.dumps({"status": "rejected", "error": {"code": "size", "message": "Out of memory"}}))
1515
+ return 1
1566
1516
  except (OSError, ValueError, TypeError):
1567
1517
  # Never dump request content or provider records in process diagnostics.
1568
1518
  print(