@withgateway/sdk 0.6.0 → 0.9.3

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 (150) hide show
  1. package/dist/agents/index.d.mts +581 -0
  2. package/dist/agents/index.d.ts +581 -0
  3. package/dist/agents/index.js +1473 -0
  4. package/dist/agents/index.js.map +1 -0
  5. package/dist/agents/index.mjs +1424 -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 +11611 -6845
  10. package/dist/cli.js.map +1 -1
  11. package/dist/cli.mjs +10090 -5325
  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 +371 -102
  16. package/dist/files/index.js.map +1 -1
  17. package/dist/files/index.mjs +371 -102
  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-LA-PMRJT.d.ts → index-DIN14Lhg.d.ts} +1 -1
  24. package/dist/{index-Di9nNqOY.d.mts → index-DuB-eQ0Z.d.mts} +1 -1
  25. package/dist/index.d.mts +7 -4
  26. package/dist/index.d.ts +7 -4
  27. package/dist/index.js +3177 -748
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +2987 -590
  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/traces/index.d.mts +3 -1
  34. package/dist/traces/index.d.ts +3 -1
  35. package/dist/traces/index.js +371 -102
  36. package/dist/traces/index.js.map +1 -1
  37. package/dist/traces/index.mjs +371 -102
  38. package/dist/traces/index.mjs.map +1 -1
  39. package/dist/tracing/index.d.mts +3 -2
  40. package/dist/tracing/index.d.ts +3 -2
  41. package/dist/tracing/index.js +257 -16
  42. package/dist/tracing/index.js.map +1 -1
  43. package/dist/tracing/index.mjs +257 -16
  44. package/dist/tracing/index.mjs.map +1 -1
  45. package/dist/transport-CpRe7zgd.d.mts +123 -0
  46. package/dist/transport-CpRe7zgd.d.ts +123 -0
  47. package/dist/worlds/index.d.mts +1986 -1746
  48. package/dist/worlds/index.d.ts +1986 -1746
  49. package/dist/worlds/index.js +1470 -290
  50. package/dist/worlds/index.js.map +1 -1
  51. package/dist/worlds/index.mjs +1465 -286
  52. package/dist/worlds/index.mjs.map +1 -1
  53. package/package.json +6 -1
  54. package/runtime/gatewaysdk/environment/bundle_manifest.py +531 -0
  55. package/runtime/gatewaysdk/environment/factory_documents.py +670 -0
  56. package/runtime/gatewaysdk/environment/factory_rules.py +973 -0
  57. package/runtime/gatewaysdk/environment/factory_shapes.py +253 -0
  58. package/runtime/gatewaysdk/environment/factory_spine.py +1155 -0
  59. package/runtime/gatewaysdk/environment/factory_spine_shapes.py +480 -0
  60. package/runtime/gatewaysdk/environment/schema/__main__.py +2 -2
  61. package/runtime/gatewaysdk/environment/schema/_slack_fidelity.py +8 -23
  62. package/runtime/gatewaysdk/environment/schema/admission.py +61 -59
  63. package/runtime/gatewaysdk/environment/schema/api.py +3 -4
  64. package/runtime/gatewaysdk/environment/schema/assertions.py +7 -1
  65. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +1 -0
  66. package/runtime/gatewaysdk/environment/schema/call_log.py +20 -0
  67. package/runtime/gatewaysdk/environment/schema/cast.py +133 -67
  68. package/runtime/gatewaysdk/environment/schema/compiler.py +16 -17
  69. package/runtime/gatewaysdk/environment/schema/database/base.py +2 -2
  70. package/runtime/gatewaysdk/environment/schema/handler_errors.py +58 -4
  71. package/runtime/gatewaysdk/environment/schema/host.py +94 -12
  72. package/runtime/gatewaysdk/environment/schema/host_browser.py +48 -0
  73. package/runtime/gatewaysdk/environment/schema/host_control.py +35 -2
  74. package/runtime/gatewaysdk/environment/schema/host_handoff.py +4 -1
  75. package/runtime/gatewaysdk/environment/schema/host_loops.py +27 -4
  76. package/runtime/gatewaysdk/environment/schema/host_metrics.py +69 -0
  77. package/runtime/gatewaysdk/environment/schema/host_requests.py +35 -0
  78. package/runtime/gatewaysdk/environment/schema/host_session.py +20 -2
  79. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +6 -0
  80. package/runtime/gatewaysdk/environment/schema/host_versions.py +100 -19
  81. package/runtime/gatewaysdk/environment/schema/host_workers.py +172 -50
  82. package/runtime/gatewaysdk/environment/schema/ingest.py +12 -3
  83. package/runtime/gatewaysdk/environment/schema/journal.py +7 -2
  84. package/runtime/gatewaysdk/environment/schema/local.py +32 -7
  85. package/runtime/gatewaysdk/environment/schema/mapping.py +1 -1
  86. package/runtime/gatewaysdk/environment/schema/measured_tests.py +187 -0
  87. package/runtime/gatewaysdk/environment/schema/page_checks.py +123 -0
  88. package/runtime/gatewaysdk/environment/schema/platform.py +80 -270
  89. package/runtime/gatewaysdk/environment/schema/platform_query.py +4 -3
  90. package/runtime/gatewaysdk/environment/schema/platform_templates.py +420 -0
  91. package/runtime/gatewaysdk/environment/schema/process_memory.py +76 -0
  92. package/runtime/gatewaysdk/environment/schema/redaction.py +13 -0
  93. package/runtime/gatewaysdk/environment/schema/request_ledger.py +4 -1
  94. package/runtime/gatewaysdk/environment/schema/run_parameters.py +25 -0
  95. package/runtime/gatewaysdk/environment/schema/runtime.py +57 -5
  96. package/runtime/gatewaysdk/environment/schema/scaffold.py +386 -219
  97. package/runtime/gatewaysdk/environment/schema/session_files.py +13 -2
  98. package/runtime/gatewaysdk/environment/schema/shape_catalog.py +493 -0
  99. package/runtime/gatewaysdk/environment/schema/shape_declarations.py +219 -0
  100. package/runtime/gatewaysdk/environment/schema/skill.py +1 -0
  101. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +1 -1
  102. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +2 -2
  103. package/runtime/gatewaysdk/environment/schema/skills/factory-orchestrator/SKILL.md +147 -0
  104. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +5 -1
  105. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +8 -6
  106. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +9 -9
  107. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +33 -2
  108. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +6 -6
  109. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +17 -2
  110. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  111. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/shape-catalog.md +59 -0
  112. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/ui-map.md +3 -2
  113. package/runtime/gatewaysdk/environment/schema/slack.py +55 -10
  114. package/runtime/gatewaysdk/environment/schema/snapshot.py +28 -2
  115. package/runtime/gatewaysdk/environment/schema/tasks.py +25 -2
  116. package/runtime/gatewaysdk/environment/schema/template_record.py +131 -0
  117. package/runtime/gatewaysdk/environment/schema/tools_world.py +7 -5
  118. package/runtime/gatewaysdk/environment/schema/ui.py +54 -33
  119. package/runtime/gatewaysdk/environment/schema/ui_interactions.py +419 -0
  120. package/runtime/gatewaysdk/environment/schema/ui_recorder.js +895 -0
  121. package/runtime/gatewaysdk/environment/schema/ui_replay.py +366 -0
  122. package/runtime/gatewaysdk/environment/schema/ui_replay_record.LICENSE +25 -0
  123. package/runtime/gatewaysdk/environment/schema/ui_replay_record.js +109 -0
  124. package/runtime/gatewaysdk/environment/schema/validation.py +24 -1
  125. package/runtime/gatewaysdk/environment/schema/worker.py +12 -5
  126. package/runtime/gatewaysdk/environment/schema/worker_key.py +38 -0
  127. package/runtime/gatewaysdk/environment/schema/worker_peaks.py +38 -0
  128. package/runtime/gatewaysdk/environment/schema/worker_watch.py +50 -0
  129. package/runtime/gatewaysdk/environment/schema/workers.py +245 -69
  130. package/runtime/gatewaysdk/environment/schema/world_host.py +96 -73
  131. package/runtime/gatewaysdk/environment/schema/world_tests.py +3 -1
  132. package/runtime/gatewaysdk/environment/secret_values.py +1 -1
  133. package/runtime/gatewaysdk/environment/world.py +34 -43
  134. package/runtime/gatewaysdk/environment/world_session_contract.py +7 -34
  135. package/skills/benchmarks-getting-started/SKILL.md +1 -1
  136. package/skills/connector-schema-authoring/SKILL.md +2 -2
  137. package/skills/connector-schema-authoring/connector-worlds.md +3 -2
  138. package/skills/connector-schema-authoring/world-schema.md +36 -23
  139. package/skills/factory-orchestrator/SKILL.md +147 -0
  140. package/skills/world-data-ingestion/ROWS.md +5 -1
  141. package/skills/world-data-ingestion/SKILL.md +8 -6
  142. package/skills/worlds-getting-started/SKILL.md +9 -9
  143. package/skills/worlds-getting-started/references/cli-mcp-map.md +33 -2
  144. package/skills/worlds-getting-started/references/gotchas.md +6 -6
  145. package/skills/worlds-getting-started/references/journal-checks.md +17 -2
  146. package/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  147. package/skills/worlds-getting-started/references/shape-catalog.md +59 -0
  148. package/skills/worlds-getting-started/references/ui-map.md +3 -2
  149. package/dist/media-BIApiPzS.d.mts +0 -102
  150. package/dist/media-BIApiPzS.d.ts +0 -102
@@ -1,61 +1,31 @@
1
- """THE NUMBERS AND WORDS A WORLD SESSION PROMISES — the Python twin.
2
-
3
- Stdlib only, and inside ``gatewaysdk.environment`` because that package is
4
- what gets vendored on its own — the web/worker images ship
5
- ``/opt/gateway-schema/gatewaysdk/environment``, ``installSandboxRuntime``
6
- copies it into agent sandboxes and api bundles stage it beside
7
- ``server/main.py`` — so the World Host's grader, the SDK client
8
- (:mod:`gatewaysdk.world_sessions`) and the CLI all read this one module.
9
-
10
- The TypeScript source of truth is
11
- ``gateway/packages/shared/src/server/services/worldSessionContract.ts``;
12
- both are pinned to ``conformance/world-sessions.json`` by a test on each
13
- side, so the route, the World Host and the two CLIs cannot drift apart.
14
- """
1
+ """Stdlib only, inside ``gatewaysdk.environment``: that package is vendored alone into images, sandboxes and bundles."""
15
2
 
16
3
  from __future__ import annotations
17
4
 
18
5
  from datetime import datetime, timezone
19
6
 
20
- #: The largest body ``POST world-sessions/{id}/calls`` accepts. The CLI
21
- #: measures the serialized body against the byte count and refuses before
22
- #: sending; the label is what help and the refusal name.
23
7
  CALL_BODY_LIMIT_BYTES = 4 * 1024 * 1024
24
8
  CALL_BODY_LIMIT_LABEL = "4mb"
25
9
 
26
- #: ``session status`` warns once an unpinned session has less than this left.
27
10
  IDLE_WARNING_MINUTES = 5
28
11
 
29
- #: The most entries one page of the world request ledger holds, as the platform lists it
30
- #: and as a World Host drains a session's outbox.
31
12
  REQUEST_LOG_PAGE_MAX = 200
32
13
 
33
- #: How much of each body the request ledger keeps: the first this many bytes of its text.
34
14
  REQUEST_BODY_CAPTURE_BYTES = 64 * 1024
35
15
 
36
- #: What a World Host's heartbeat names to say it serves open sessions; the platform places an
37
- #: open session only on a host that does.
38
16
  OPEN_DOOR_FEATURE = "open-door"
39
17
 
40
- #: The code a session the World Host did not serve answers its request ledger read with.
18
+ WORLD_STATES_FEATURE = "world-states"
19
+
41
20
  REQUESTS_NOT_RECORDED = "requests_not_recorded"
42
21
 
43
- #: The task an exploratory session runs on when the caller names none, and
44
- #: the ``task.source`` the platform reports for it.
45
22
  EXPLORATORY_TASK: dict[str, str] = {"instruction": "exploratory session"}
46
23
  EXPLORATORY_TASK_SOURCE = "none"
47
24
 
48
- #: What a session that has no grader answers ``grade`` with, beside
49
- #: ``reward: null``.
50
25
  NO_GRADER_REASON = "no grader"
51
26
 
52
- #: Where a world's server and its runner find the token for the runner's
53
- #: ``/__world/*`` routes: set by the platform on a session pod's two
54
- #: containers, by the Batch runner on a world it boots.
55
27
  ADMIN_TOKEN_ENV = "WORLD_ADMIN_TOKEN"
56
28
 
57
- #: The code and words of a call by a route's name: a world's routes answer
58
- #: over its HTTP api, never through the tool door.
59
29
  NOT_A_TOOL = "not_a_tool"
60
30
  ROUTE_NOT_A_TOOL = "'{name}' is a route of this world, not a tool; call it over the session's api URL"
61
31
 
@@ -64,7 +34,10 @@ def route_not_a_tool(name: str) -> str:
64
34
  return ROUTE_NOT_A_TOOL.format(name=name)
65
35
 
66
36
 
67
- #: Why the benchmark runner's agent refuses an api bundle: it serves no tools.
37
+ BUNDLE_RUN_REFUSAL = (
38
+ "A world bundle runs nothing on its own: its member worlds run, opened together as one bundle session. "
39
+ "Run or open a member world."
40
+ )
68
41
  API_BUNDLE_RUN_REFUSAL = (
69
42
  "an api bundle serves no tools: its routes answer over its HTTP api and are never an agent's tools, so "
70
43
  "the benchmark runner's agent has nothing to call. Migrate it to a schema world (`gateway worlds migrate "
@@ -326,7 +326,7 @@ fields and the reward signature against the verifiers version you install.
326
326
 
327
327
  ```bash
328
328
  gateway benchmarks init ./crm-bench # custom contract: example entity, three tools, one verifier, one task
329
- gateway benchmarks init ./slack-bench --connector slack # a shipped template: the vendor's entities, routes and tools
329
+ gateway benchmarks init ./slack-bench --connector slack # an official template (needs a login): the vendor's entities, routes and tools
330
330
  gateway benchmarks init ./x --task onboard --prompt "Create an account for Acme." --model openai/gpt-5-mini -k 3
331
331
  ```
332
332
 
@@ -106,6 +106,7 @@ deliverable can finish with synthetic fixtures and explicitly skipped live valid
106
106
  - [ ] Enforce supported required fields, types, enums, key uniqueness, and reference integrity. Document vendor rules the dialect cannot express, normalization choices, and constraints the future mapper must enforce; structural validation is not vendor behavior.
107
107
  - [ ] Real vendor documents compile as they come (Brex retrospective, 2026-09-14): `format: int64`/`double` on numbers is ignored, not refused (string formats are still validated); a schema-valued `additionalProperties` types a map (`Record<string, string>`); a type nested in itself (`ExpandableExpense` holding an `ExpandableExpense`) compiles, with the nested occurrence validated as its bare type and stored as JSON, never projected to a column. A contract whose inlined files would pass the 4 MB publication cap (Google Docs' recursive body) compiles each object/array definition once under `$defs` and references it instead; nothing to do in the template. A nested key or relationship field is a JSON Pointer, `/owner/user_id`, never `owner.user_id`; the compiler's refusal says so. A primary key may be nested too (`/protocolSection/identificationModule/nctId`) when every object on its path is required and non-null; lookups (`get`, `update`, `delete`) then pass it flat under the pointer itself. Field names keep the vendor's hyphens (`reference-count`); dots and slashes never belong to a name. A verifier's SQL double-quotes such a column (`"reference-count"`): unquoted, SQLite reads a subtraction.
108
108
  - [ ] Every property verifier SQL will name has a column: scalars and compositions whose non-null branches are scalar (`anyOf [{$ref Status}, {type: null}]`, the nullable-enum shape) project; a composition that may hold an object or array stays JSON-only. A verifier that names a column the contract never projected fails the grade with the database engine's message and the statement; it never scores 0 quietly (double-quoted unknown names no longer fall back to string literals).
109
+ - [ ] Declare the shapes a writer would otherwise guess (`worlds describe --json` reads them into its shape catalog): the keys of an open JSON field defined by another entity's rows (`custom_fields`, e.g. a properties map keyed by a property-definitions entity), ids inside a row that come from another entity or a fixed vendor table (`ids`), dense vendor-minted numbers (`sequences`), and, on a handler route, where its answer keeps the records, the id, the count and the total (`[operations.answer]`). Enums and nested shapes need nothing beyond the JSON Schema itself. See `world-schema.md` and `connector-worlds.md`.
109
110
  - [ ] `gateway worlds schema compile PATH` then `check PATH` pass. Never edit generated files; SDK templates contain authored inputs and generate bundle artifacts at `init` time. Changing the root `$id` after `init` is fine: `compile` re-stamps an empty `data/initial.json` onto the new domain; a journal that holds rows follows a change that only adds to its domain (a new entity, a new field that is not required) and is refused otherwise, with the fix named (re-import its rows, or restore the schema it was written against).
110
111
  - [ ] Shared templates and committed fixtures hold synthetic data only. Tenant captures stay in their owning project; initial batches and refresh journals retain explicit capture/synthetic provenance.
111
112
 
@@ -174,7 +175,7 @@ No `upsert`: `get`, then `insert` or `update`. Read-only SQL: `gateway_env.db.on
174
175
 
175
176
  ### 7. Ship the template; register platform integration only when in scope
176
177
 
177
- - [ ] SDK-shipped: commit authored files under `gatewaysdk/sdk/src/gatewaysdk/environment/schema/connectors/<slug>/`; `list_templates()` and `test_schema_scaffold.py` cover the slug and preserve its authored dependencies/provenance during initialization. Schema-only templates declare an empty tools map and have no operation handlers.
178
+ - [ ] Official: an official editor pushes the template tree into the official organization (`gateway worlds create <slug> --from <dir>` with `GATEWAY_TOKEN` + `GATEWAY_PROJECT_ID`, then publish it), and every reader serves it from that world's head (`gateway worlds schema templates`, `schema init --connector <slug>`, `worlds create --from <slug>`). Authored trees still sit under `gatewaysdk/sdk/src/gatewaysdk/environment/schema/connectors/<slug>/` until O4 moves them out; `tests/test_official_template_world.py` pins that a world built from the files is byte-identical to the old directory init. Schema-only templates declare an empty tools map and have no operation handlers.
178
179
  - [ ] Platform integration, if separately in scope: map an existing source kind in `schemaWorldTemplates.ts` so "Build from connector" offers it. Do not register a native provider or invent a source kind for an SDK-only schema milestone.
179
180
  - [ ] Treat `connectionMode` as the primary authentication path, not the only setup path. A managed connector may retain `remoteMcpPreset` as a fallback; render that action from the preset's presence. For native source connectors such as Slack, the source-backed Link action is the managed authentication path because native-provider dispatch intentionally precedes Merge.
180
181
  - [ ] User-added templates can use `--connector custom` and SDK publication. Generic schema upload and shared/project registry infrastructure remain unimplemented.
@@ -265,7 +266,6 @@ Python SDK as package data so an agent in any repository can install it.
265
266
  Revalidated 2026-09-07 while integrating `ba89fe16` with `015d6b25`:
266
267
  `schema/scaffold.py`, `schema/platform.py`, `tests/environment/test_schema_scaffold.py`,
267
268
  `worldSchemaPublication.ts`, `worldSchemaRuntime.ts`, `environmentBundleTester.ts`,
268
- `environmentBuildWorkbench.ts`, `environmentSchemaSandbox.ts`,
269
269
  `NativeSlackService.ts`, and `deploy/benchmark-runner/engines/{session_server,schema_session}.py`.
270
270
  Full source paths and runtime boundaries are listed in [world-schema.md](../../../documentation/features/world-schema.md).
271
271
  These source checks do not imply live-provider validation or executed fidelity scores.
@@ -254,6 +254,7 @@ least one `[[operations]]` entry.
254
254
  | `[[operations]]` | `name`, `method`, `path`, `params`, `entity`, `results` | `path` may carry `{args}`; a `params` name keeps the vendor's spelling, dots included (`query.bibliographic`, `filter.overallStatus`), and may end in `[]` (`expand[]`, `status[]`) for a key the vendor repeats, which capture then sends repeated and the served route filters on any value of; `results` is the dotted path to the row array (empty when the body is the row). An operation without `entity` never seeds and answers 501 `not_modelled`. Routes are never tools: an agent calls them over HTTP (the api url and token `session open --surface api` prints), and a tool exists only where `x-gateway.tools` declares one with a handler. An `entity` (or an `explode` target) that `schema/world.json` does not declare is refused by `connector validate`, `schema compile`, `schema check` and the platform's describe (`gateway worlds describe`, local or platform) alike — `operation X lands on entity Y, which schema/world.json does not declare (declared: …)` at `/operations/<i>/entity` — and nothing is written; hand-edited TOML meets the same gate `route add` applies. |
255
255
  | `[operations.ingest]` | `drop`, `explode`, `carry_args` | `drop` removes vendor fields the entity does not carry; each `[[operations.ingest.explode]]` (`field`, `entity`, `carry`, `take`) turns a nested array into child rows; `carry_args = { account_id = "id" }` stamps the capture's path argument or query parameter onto every row before projection (a statement only knows its account from the URL it was fetched under). `connector ingest --dry-run [--report FILE]` lists every violation of every capture and writes nothing. |
256
256
  | `[operations.api]` | `filter`, `match`, `action`, `status`, `single`, `envelope`, `wrapper`, `page`, `body`, `defaults`, `generate`, `handler`, `sample`, `sample_headers`, `sample_body`, `not_found`, `not_found_status`, `cursor_absent_when_done` | `filter` maps a path argument or declared query parameter to the row field it selects on (case-insensitive, any depth; an absent parameter does not narrow, one sent more than once matches rows carrying any of its values); `match = { name = "contains" }` switches an argument from equality to substring or `prefix`, and a list field matches when any element does. `action` is `read` (default), `create`, `update`, `delete` or `handler`: writes persist through the contract, `body` maps row fields (dotted for nested) to request-body paths, `defaults` fixes constants, `generate` fills `uuid`, `int` or `now`; `update` and `delete` find their row through `filter` and answer the vendor's 404 otherwise; they, and a `single` read with a path argument, refuse (`finds its row by nothing`, 400) when neither `filter` nor a path argument naming a field selects a row, rather than act on some row; a singleton served under a scoped path answers through `action = "handler"`. `status` is the 2xx the vendor answers (201 for create, 204 for delete by default), `single` returns the row itself instead of an envelope, `envelope` and `page` override the world-wide setting per route. A dotted `envelope` nests the answer the way the vendor does (`message.items` answers `{message: {items, total-results, next-cursor}}`), and a single row is wrapped only by its own route's `envelope` (`message` answers `{message: row}`). `wrapper` is the rest of the vendor's envelope as a JSON object string (`'{"status": "ok", "message-type": "work-list"}'`), the answer laid onto it key by key; `schema init --from-openapi` writes it from the document. `handler` names a function `def name(ctx, args, query, body)` in the handlers module that returns a body, `(status, body)` or `(status, body, headers)`; `ctx` reads and writes the store (`rows`, `get`, `find`, `insert`, `update`, `delete`), keeps time (`now`, `elapsed`, `ladder` for status machines, frozen by `GATEWAY_WORLD_CLOCK`), mints ids (`uuid`) and shapes answers (`envelope`, `not_found`, `invalid`) and sees the request's `headers` and `query_all` (every value of every parameter, `{"expand[]": ["a", "b"]}`; the `query` argument keeps the first value only). `not_found` / `not_found_status` answer this route's missing row the vendor's own way (a 403 with its own message for one resource) and fall back to `[api]`; `cursor_absent_when_done` overrides `[api]` for this route. `sample = { ip = "203.0.113.5" }` gives the conformance run a value a validating route accepts when no seeded row can supply one; `sample_headers = { "Idempotency-Key" = "conform-1" }` and `sample_body = { reason = "conform" }` give it the headers and body a route demands (read by `connector conform` only; the served API never sends requests). |
257
+ | `[operations.answer]` | `records`, `id`, `fields`, `count`, `total`, `cursor`, `cursor_param` | What the route's answer holds where the served settings cannot say (a handler's own shape): JSON pointers to the records (a list or the one record), the count, the total and the next-page reference, the record's id key, the per-record fields a recorded answer is compared on, and the request parameter that takes the cursor. Each key overrides what `describe` derives from `[api]` (`envelope`, `hits_key`, `cursor_key`, paging) and the entity's key; read by the shape catalog only, never by the served route. |
257
258
  | `[webhooks]` | `subscriptions`, `url`, `events`, `secret`, `enabled`, `scope`, `signing`, `signature_header` | Where the world's webhook subscriptions live and how the vendor signs what it sends (see Webhooks below). `subscriptions` names the entity agents register endpoints in through the vendor's own routes; `url`, `events`, `secret`, `enabled` and each `scope` value name its fields (checked against the contract at compile). `signing` is `svix`, `github`, `linear`, `stripe`, `hmac-sha256` (with `signature_header`) or `none`. |
258
259
 
259
260
  ### Scaffolding a route
@@ -618,8 +619,8 @@ gateway worlds connector skill --install . # the authoring skill + agen
618
619
  - **Compile before accept.** Every push is run through the schema runtime on the platform
619
620
  (`validateConnectorTemplate`); a template that does not make a world is refused with a 400
620
621
  carrying the reason and nothing is committed. The digest is `template_digest`, the same
621
- algorithm an installed template pins with, so a workspace connector and an identical installed
622
- template pin identically.
622
+ algorithm an official template pins with (over its official world head's files), so a workspace
623
+ connector and an identical official template pin identically.
623
624
  - **Re-publishing is a commit.** A second publish to the same slug pulls the head, sends
624
625
  `parent_commit`, and deletes paths no longer in the directory, so the connector always equals
625
626
  the directory. `--workspace-visible` makes it visible to the whole workspace rather than the
@@ -23,12 +23,12 @@ session](#raw-ingestion-schema-gated-sql), and connector
23
23
  | SDK `gwenv.init_from_path` | Checks artifacts and materializes isolated schema-aware worlds. |
24
24
  | Direct benchmark `mock-tools` runner | Reuses SDK materialization and `World` enforcement. |
25
25
  | SDK/public and platform publication, including READY/dedup/fork/ref promotion | Verifies the stored SHA-256, generated artifacts and exact lock through the trusted compiler/materializer using actual archive bytes; uploaded Python is parsed, not imported during publication. |
26
- | Worker builder, bundle tester, and workbench | Materialize through the shared schema store; tester/workbench execution uses an isolated sandbox with an installed trusted runtime. No legacy seed-SQL fallback. |
26
+ | Worker Environment Actions (`BundleTester`, `BundleCompleteness`) | Never run a schema world: Environment Actions skip every check for it, and the tester and the completeness gate refuse a schema tree (`WORLD_SCHEMA_UNSUPPORTED`). The environment builder and its E2B workbench were deleted (2026-10-13). |
27
27
  | Hosted `mock-tools` sessions | Use the shared `World` in a child process for validated calls, reset and grading; dependency worlds are unsupported. |
28
28
  | Platform agent (`run_gateway_cli`) | Edits schema worlds in its sandbox with the `gateway worlds` CLI and publishes as the user through its doors (`create`, `push`, `data import <slug>`), checked like any CLI push; see [agent.md](./agent.md#platform-actions-worlds-tasks-rollouts-connectors-ingestion-self-schedules). |
29
29
  | SDK Harbor worlds and Harbor/API/verifiers engines | Retain their separate unsupported-mode guards; do not combine their bundle markers with schema mode. |
30
30
 
31
- Environment Actions remain advisory. See [Environment Builder](./environment-builder.md) and
31
+ Environment Actions remain advisory. See [Environment Actions](../../system-architecture/worlds/environment-actions.md) and
32
32
  [Benchmark Container Hub](./benchmark-containers.md).
33
33
 
34
34
  ## Bundle layout and authoring
@@ -115,6 +115,13 @@ The root's `x-gateway` requires:
115
115
  Add `$defs`; the
116
116
  [CRM fixture](../../samples/schema-worlds/crm/schema/world.json) supplies examples.
117
117
  Entities require `schema`/`primary_key`; `unique`/`relationships` default to empty.
118
+ Three more members are optional and describe the rows rather than store them, so they never
119
+ change the domain hash: `custom_fields` (the keys of an object field, or the ids of an array
120
+ of `{id, value}` items, are rows of another entity: `{field, definitions, key, where?, pairs?}`),
121
+ `ids` (the values at a JSON pointer come from another entity's rows, `{pointer, entity, key,
122
+ where?}`, or a fixed table, `{pointer, values: [{id, label}]}`) and `sequences` (an integer
123
+ field numbered densely within `scope`: `{field, scope?, start?}`). `worlds describe --json`
124
+ reads them into its shape catalog ([world-shape-catalog](../../system-architecture/worlds/world-shape-catalog.md)).
118
125
  Tools require `input`/`output`; `description` is optional. Unknown members reject.
119
126
  Version labels imply no semantic-version compatibility.
120
127
 
@@ -403,12 +410,13 @@ committed and a rejected session.
403
410
 
404
411
  ## Connector templates and `init`
405
412
 
406
- The SDK ships authored `gateway-world/1` contracts under
407
- `gatewaysdk/sdk/src/gatewaysdk/environment/schema/connectors/`: `slack`, `github`,
408
- `linear`, `jira`, `google-drive`, `google-calendar`, `salesforce`,
409
- `microsoft-teams`, and a one-entity `custom` template. They declare entities,
410
- keys, and relationships. Tools are optional; templates contain authored inputs,
411
- and `init` produces generated artifacts. The
413
+ Vendor templates are authored `gateway-world/1` contracts kept under
414
+ `gatewaysdk/sdk/src/gatewaysdk/environment/schema/connectors/` until O4, and served
415
+ from the official organization: each one is an ordinary schema world built from its
416
+ template (`init_official_world`), which keeps every file the template brought and
417
+ records `schema/template.json` (`connector`, `digest`: the template's
418
+ `template_digest`, the digest every world made from it pins). Only the one-entity
419
+ `custom` template ships in code. The
412
420
  [Microsoft Teams guide](./microsoft-teams-schema.md) documents its schema-only
413
421
  Graph v1.0 base, synthetic sample, and provisional subset assessment.
414
422
 
@@ -418,17 +426,23 @@ gateway worlds schema init ./teams-world --connector microsoft-teams
418
426
  gateway worlds schema init ./acme-crm --connector custom --name acme-crm
419
427
  ```
420
428
 
421
- `init` (also `init_bundle(path, connector=..., name=...)`) writes the manifest,
422
- the authored template's schema definitions and metadata under `schema/`, shared
423
- `schema/base.json`, `tools/handlers.py`, and a starter verifier into a new or empty
424
- directory. Supporting files must be flat regular `.json`, `.md`, or `.toml`
425
- files; symlinks, generated filenames, and collisions with shared `base.json`
426
- reject. Real `__pycache__` directories created by package installation are ignored;
427
- `api/` (the connection's `api/handlers.py`) and `scenarios/` copy verbatim to the
428
- world root, exactly as `init_bundle_from_files` treats a workspace connector;
429
- other directories reject. Supporting bytes are preserved except Slack's
430
- `capabilities.json`, whose defaults expand as described below. Descriptive
431
- metadata is not a compiler dependency or lock input; referenced schemas are.
429
+ `init --connector <slug>` reads the official world's head and copies it under the
430
+ new name (`init_bundle_from_world`, the runtime's `init-world-files`): the package id
431
+ and the manifest's name change, the contract is compiled again and its data follows
432
+ it; nothing is rebuilt from the template. `worlds create <slug> --from <template>` is
433
+ the same copy on the platform, and the new world's first version records
434
+ `forkedFromVersionId` = the official version. Building a world from template files
435
+ (`init_bundle_from_files`, a workspace connector or an official world's own build)
436
+ writes the manifest, the template's schema definitions and metadata under `schema/`,
437
+ shared `schema/base.json`, `tools/handlers.py`, and a starter verifier into a new or
438
+ empty directory. Supporting files must be flat regular `.json`, `.md`, or `.toml`
439
+ files; symlinks and collisions with shared `base.json` reject, and generated names
440
+ (`README.md`, `lock.json`, …) are not laid out. `api/`, `scenarios/`, `tests/` and
441
+ `ui/` copy verbatim to the world root, as do the carried `verifiers/`, `openapi/`,
442
+ `readers/`, `evidence/`, `reports/` and `tasks.json`; other directories reject.
443
+ Supporting bytes are preserved except Slack's `capabilities.json`, whose defaults
444
+ expand as described below. Descriptive metadata is not a compiler dependency or lock
445
+ input; referenced schemas are.
432
446
 
433
447
  Initialization compiles the contract and writes a zero-mutation
434
448
  `data/initial.json`, so the world starts empty and is filled by ingestion or
@@ -526,7 +540,7 @@ world back against the document it came from.
526
540
  **Build from connector** for Slack creates a durable populated world job in
527
541
  Gateway. Other registered source kinds show their CLI twin under **Use the CLI instead**:
528
542
  `gateway worlds schema init`, `schema check`, then `gateway worlds create <slug> --from <dir>`.
529
- A blank (custom) contract starts from the Connectors page's **New connector** form. SDK template
543
+ A blank (custom) contract starts from the WorldHub page's **New connector** form. SDK template
530
544
  availability does not register a platform source kind or supply a live mapper;
531
545
  Teams remains schema-only. The SDK checks the contract before push, and the
532
546
  shared publication validator checks actual stored bundle bytes before the world
@@ -576,7 +590,7 @@ remain exposed.
576
590
 
577
591
  ### Populated Slack worlds in Gateway
578
592
 
579
- The Connectors page offers synthetic data or selected public/private channels
593
+ The WorldHub page offers synthetic data or selected public/private channels
580
594
  from the caller's native Slack connection. Synthetic worlds include fictional
581
595
  collaboration data and a graded scenario. Live jobs create a dedicated import,
582
596
  read projected evidence, verify each artifact, map it through the shared store,
@@ -723,14 +737,13 @@ Revalidated during the merge of `ba89fe16` and `015d6b25` on 2026-09-07:
723
737
  - `deploy/benchmark-runner/engines/{mock_tools_runner,session_server,api_runner,harbor_runner,verifiers_runner}.py`
724
738
  - `gateway/packages/shared/src/domain/worldSchema.ts`
725
739
  - `gateway/web/src/features/benchmark-hub/server/{worldSchemaPublication,containerVersionService}.ts`
726
- - `gateway/worker/src/features/environmentBuild/{environmentBundleCompleteness,environmentBundleTester,environmentBuildWorkbench}.ts`
740
+ - `gateway/worker/src/features/environmentOperator/{environmentBundleCompleteness,environmentBundleTester}.ts` (moved from `environmentBuild/` on 2026-10-13, when the builder and its workbench were deleted)
727
741
  - `samples/schema-worlds/`
728
742
  - `gateway/web/src/features/environment-files/{schemaWorldTemplates.ts,components/BuildSchemaWorldDialog.tsx}`
729
743
 
730
744
  Additional sources: `gateway/packages/shared/src/server/services/worldSchemaRuntime.ts`
731
745
  (template digest and trusted bridge), `gateway/web/src/features/environment-files/server/connectorWorldService.ts`
732
746
  (durable job), `gatewaysdk/sdk/src/gatewaysdk/environment/schema/{slack,_slack_fidelity,platform}.py`,
733
- `gateway/worker/src/features/environmentBuild/environmentSchemaSandbox.ts`,
734
747
  `gateway/packages/shared/src/server/services/NativeSlackService.ts`, and
735
748
  `deploy/benchmark-runner/engines/{session_server,schema_session}.py`.
736
749
 
@@ -0,0 +1,147 @@
1
+ ---
2
+ name: factory-orchestrator
3
+ description: Co-author a world bundle's Data Factory with a person — its ontology, entity graph, rules, tests and spine — and, when your switches allow it, edit the bundle's worlds and their relationships and write their rows. Use when you are a bundle's factory orchestrator, or an outside agent joined to a factory's roster.
4
+ ---
5
+
6
+ # Data Factory: the orchestrator
7
+
8
+ ## What you work on
9
+
10
+ A Data Factory belongs to one world bundle (a bundle of one world is allowed). It holds five documents. Each is a set of nodes, and each node has a stable `id`, a `name` and one `sentence`.
11
+
12
+ - **Ontology:** the things and events of this domain and how they relate. The kinds are whatever the person needs; there is no fixed vocabulary. A relation is `{type, to}`, with `type` a free word.
13
+ - **Entity graph:** notes on the bundle's entities: which world creates a record, cardinality, how fields merge. The links between worlds (identities and references) live in the bundle's `gateway-bundle.toml`, not here.
14
+ - **Rules:** what must hold. A rule is a sentence (guidance), code (`guard`, `derive`), or both.
15
+ - **Tests:** checks attached to nodes, marked `generate`, `verify` or both.
16
+ - **Spine:** the facts every writer must agree on: rosters, calendars, storylines, partitions and their quotas, reserved keys, sequence starts. Tables, facts and checks, checked at every commit.
17
+
18
+ Any node can point at another node, a spine row (`{kind: "row", node, key}`), a world, a schema field, a record or a drive file through `refs`.
19
+
20
+ The factory writes data. It never runs or simulates worlds, and there is no clock to advance: records carry their own dates.
21
+
22
+ ## Your tools
23
+
24
+ Your switches decide which write tools you have. Call only what you were given. Reads name the bundle as `slug`, writes as `bundle`. Every result carries `head`, the head revision's id, and may carry `hook_context`: lines the factory's rules add for you (read them before your next step).
25
+
26
+ | Tool | Does |
27
+ |---|---|
28
+ | `get_factory` | The head revision and the documents (pass `doc` for one). |
29
+ | `list_factory_revisions`, `get_factory_revision`, `diff_factory_revisions` | History, the documents as they were, and the nodes added, changed and removed between two revisions. |
30
+ | `update_ontology`, `update_entity_graph`, `update_rules`, `update_tests`, `update_spine` | Commit nodes (`upsert`, `remove`) to one document, on a `base` revision. `update_spine` also takes row edits (`rows`). |
31
+ | `get_spine`, `get_spine_rows` | The spine: tables (without their rows, with `rowCount`), facts with their `resolved` values, and warnings; then one table's rows a page at a time (`offset`, `limit`, `q` to search). |
32
+ | `generate_spine` | Run tables' generators and commit their rows (`dryRun: true` shows a sample and writes nothing). Present with `update_spine` when "Writes spine" is on. |
33
+ | `accept_factory_unit` | Check a unit's quotas against the rows the run holds: `{partition, key}` → each quota's expected and actual count. |
34
+ | `get_factory_data` | What this run wrote per member: row counts per entity in its draft and in Day 0. `origin: true` adds where each entity's rows came from (`real:<source>`, `generated`, `propagated`, `authored`, `seed`); `pending: true` lists the run's pending references. |
35
+ | `describe_member` | Each member's contract as a write must fit it: every entity's fields with type, required, allowed values (`enum`) and `format`, its keys and relationships, and the identities and references that touch the member. Pass `world` (and `entity`) to narrow it. |
36
+ | `write_records`, `query_factory_data` | Write rows into the active run's drafts, for one member or several at once (`unit` names the partition unit the write is for); read one entity's rows: the run's draft, else Day 0, else main (`source` says which). Present only when "Writes data" is on. |
37
+ | `release_factory_data` | Release the drafts as each member's Day 0 state, and end the run. Present only when "Releases Day 0" is on. |
38
+ | World sandbox tools | `open_world_sandbox` … `commit_world_sandbox`, here, over MCP and with the CLI: edit a member world or the bundle's relationships, confined to the bundle and its members and signed as you. You cannot add or remove members; a commit that would is refused, and a person makes that change. Present only when "Edits worlds" is on. |
39
+ | `request_factory_upload`, `confirm_factory_upload` | Upload an export's rows into the active run, tagged `real:<source>`. Over MCP and the CLI, when "Uploads real data" is on; an upload that starts a run also needs "Starts runs". |
40
+ | `set_factory_enrichment` | Open or close one member entity's real fields to agents. Over MCP and the CLI, when "Opens real rows to agents" is on. |
41
+ | `start_factory_run` | Start a run when none is active. It is recorded on the factory's orchestrator and has no chat, and it is refused (`factory_run_needs_orchestrator`) until a person has set the factory up. Over MCP and the CLI, when "Starts runs" is on. |
42
+
43
+ These last three switches start off for every agent, and only a person turns them on. Use them only for the upload, the entity or the run the person asked for.
44
+
45
+ ## Writing rules and tests
46
+
47
+ Rule code is Python, run by the factory's rule runner: no network, no files, no clock, the same answer every time.
48
+
49
+ ```python
50
+ def guard(view, change):
51
+ payment = view.one("acme-billing", "payments", id=change["row"]["payment_id"])
52
+ if payment is None:
53
+ return "unknown payment " + str(change["row"]["payment_id"])
54
+ return True if change["row"]["amount"] <= payment["amount"] else "a refund never exceeds its payment"
55
+
56
+ def derive(view, change):
57
+ return [{"world": "acme-billing", "entity": "ledger", "row": {"payment_id": change["row"]["payment_id"]}}]
58
+ ```
59
+
60
+ - **`view`:** `rows(world, entity, **where)`, `one(world, entity, **where)`, `spine(node_id)` (a spine fact as `{value}`, a table as `{columns, key, rows}`, resolved; any other id reads that ontology node's `properties`), `statements(about=None)`, and `rng(name)`, the only randomness.
61
+ - **`change`:** `{world, entity, op, row, before, at, by: {principal, unit}}`. A hook guard on a tool call sees `{tool, input, by}`.
62
+ - **A guard returns `True` or a reason string.** Anything else is an error.
63
+ - **Imports:** only `math`, `statistics`, `decimal`, `datetime`, `re`, `json`, `collections`, `itertools` and `zoneinfo`. `now()` and `today()` are refused; take dates from the change or the spine. `hash`, `id`, `samples`, setting or deleting an attribute, and a bare `except` are refused too: catch the exception you expect.
64
+ - **Conventions:** guard the transition (`before` → `row`), not every write. Take roles from the roster, refuse an unknown reference by name, and join on reserved keys, never on text.
65
+ - **`rule_unit` test spec:** `{"rule": "<rule id>", "cases": [{"name", "rows": {"<world>.<entity>": [...]}, "spine"?, "change", "expect": "ok"|"deny", "reason"?, "derived"?: [...]}]}`. Write a passing case, the failure the rule exists for, and an edge (month end, Day 0, a time-zone boundary).
66
+ - **`chronicle` test spec:** `{"each": {"about": ["<node>"]}, "require": [{"cause": {"about": ["<node>"]}} | {"at": true} | {"causeBefore": true} | {"link": {"world", "entity"}}], "cases"?: [...]}`.
67
+ - **A commit that changes a rule's code or its tests runs those tests first.** Its answer carries `ruleTests`: warnings, and mutants no test caught ("`<=` → `<` on line 3 and every case still passes"). Add the case that would catch it.
68
+
69
+ ## Writing the spine
70
+
71
+ Put every number and name two writers must agree on in the spine, once, and point at it.
72
+
73
+ - **Tables:** `{kind: "table", columns: [{name, type, ref?}], key: "<column>", rows: [...]}`. Types: `string`, `integer`, `number`, `boolean`, `date`, `instant`, `json`, `ref`. Key cells are written literally and are unique. Change rows with `rows: [{table, upsert, remove}]` in `update_spine`; an `upsert` of a table node sends all its rows.
74
+ - **Facts:** `{kind: "fact", value}`. **Checks only:** `{kind: "check", checks: [...]}`. Any spine node may carry `checks` and a `group` ("roster", "calendar", "storyline") for the Spine tab.
75
+ - **Derived values, not copies.** A value (a fact's value, a cell, a check's field) is a literal or: `{from: {kind: "node", id}, path: "/volume"}`, `{from: {kind: "row", node, key}, path: "/publishedOn"}`, `{from: {kind: "node", id: "<table>"}, column: "tickets"}` (a list), `{formula: "a * b", with: {a: …, b: …}}`, or `{literal: …}` for an object that only looks like one. Formulas are Python expressions, with `largest_remainder(total, weights)`, `lookup(rows, column, **where)`, `count(rows, **where)`, `total(rows, column, **where)` and `working_day(date, holidays, weekend)`. When you must keep a written number, write `{copy: 3200, from: …}`: a copy that drifts from its source is a warning.
76
+ - **Checks:** `flow` (`start + created − closed = end`), `sum` (`parts` add up to `total`), `quota` (`quotas` sum to `total`, split from `weights` by largest remainder), `fact` (a history fact's `claims` equal its recomputed `value`, within `tolerance`), `steps` (each storyline row's `names` cell is a row ref that resolves, and business steps fall on working days). Arithmetic failures refuse the commit (`factory_spine_checks_failed`); off-day steps and drifted copies come back as `spineChecks.warnings`.
77
+ - **Generators:** a table's `generate` is Python `def generate(ctx)` returning its rows. `ctx.rng("<concept>")` is the only randomness, one stream per concept, so changing one roster never reshuffles another; `ctx.spine(id)` and `ctx.rows(id)` read the spine. Run it with `generate_spine`; bulk rows come from code, not from you row by row.
78
+ - **Partitions:** a table whose rows are units: `partition: {owner: "def owner(view, change): …", entities: [{world, entity}], quotas: [{column, world, entity, tolerance?}]}`. `owner` returns the unit key that owns `change["row"]`.
79
+ - **Reserved keys:** `reserves: [{column, world, entity, field}]` reserves each row's value of `column` in that member field (both ends of a cross-world join, such as an escalation's ticket and issue).
80
+
81
+ ## Writing data
82
+
83
+ - **Rows land in this run's draft of a member world**, not in the world itself. No session or run sees them until a person releases them as Day 0. A run starts from the seed chosen when it was started: by default the Day 0 the last run released (else main), so it adds to it; or main, nothing at all, a named state or a snapshot.
84
+ - **Read the contract first.** `describe_member` names each field's type, whether it is required, the values it allows and its format, so a write fits the first time.
85
+ - **Write to the member version the bundle pins.** Every read and check of a member (`describe_member`, every write, the release) uses the version the bundle pinned, even after the member's main has moved on. A world sandbox opens main, which may differ; trust `describe_member`. When the person wants a newer contract, they move the pin by committing the bundle.
86
+ - **One write is a slice:** `rows: {"<world>": {"<entity>": [rows]}}`, for any members of the bundle. It lands in every member or in none.
87
+ - **Lay structure first, then write the text with `mode: "patch"`.** A patch row names a stored row by its primary key and sends only the fields to change; objects merge, anything else replaces, nothing is filled, and the merged row is checked against the contract and the references. A patch for a row no member holds is refused as `row_not_found`. A patched row still carries its identity, so a member that lacks the person gets a counterpart.
88
+ - **A reserved key needs no order.** A reference whose value the spine reserves for its target passes, and the release refuses while a reserved value has no row (`reservation_unfulfilled`).
89
+ - **Write a unit's rows as that unit.** Send `unit: {partition, key}`: a row of an entity a partition owns is refused (`partition_other_unit`) unless the partition's owner function names your unit, both for the row you send and for the stored row it would replace. When the unit is done, `accept_factory_unit` compares its quotas with what the run holds.
90
+ - **Write referenced records first, or in the same slice.** The bundle's `[[references]]` (in `gateway-bundle.toml`) say which field names a record in another member; `write_records` refuses a row whose reference neither the slice nor any member holds. When the record comes later in the run, send `deferReferences: true`: the row lands and its reference stays pending (`pending.deferred` in the answer) until a write lands the record. Every write re-checks the pending list, and the release refuses while any remain.
91
+ - **Rows from real data keep their fields.** An upload tags its rows `real:<source>`. Changing a field such a row holds is refused (`real_field_protected`), and so is replacing an entity that holds such rows (`real_rows_protected`), unless that entity is open to enrichment. You may fill a field the real row lacks (a patch that sends only that field), and write new rows that name real ones.
92
+ - **People are written once.** For each `[[identities]]`, a row you write carries its identity value to every other member the identity spans: the platform writes the counterpart there, unless that member holds the value already or your slice writes it. Values match by the identity's key, through each span's transforms (an email under `lower` matches in any case). The answer counts counterparts in `propagated`, and `unpropagated` names a span no value reaches through its transforms.
93
+ - **Names travel with the person.** A span's `carry` (in `gateway-bundle.toml`) names fields, such as a name or a title, that are the same in every member. A carried field you send reaches every counterpart: a new one gets it, one a member holds is patched, and a counterpart you write without it gets it. Only fields you send travel, never a filled or stored value. Two values for one person's carried field in one write is `identity_conflict`. A carry into a member's primary key refuses the write; ask a person to carry it into another field. A counterpart's other fields are filled from the contract; write them yourself when they matter.
94
+ - **`complete: true` fills what a row leaves out** from the member's contract: defaults, the first enum value, null where allowed, a value hashed from the row for every key and unique field, and a parent in the same world. Send every field you care about; a filled date is one fixed instant. It never goes with a patch.
95
+ - **Give every row its own dates.** Nothing runs to advance a clock.
96
+ - **Write a few hundred rows at a time**, at most 5,000 a call. A row replaces the row with the same key; `mode: "replace"` empties each entity the write sends rows for first; an entity named with no rows is refused.
97
+ - **Check what landed** with `get_factory_data` (row counts per entity) and `query_factory_data`.
98
+ - **Release only when the person says so.** `release_factory_data` makes each member's draft its Day 0 state and ends the run; a member the run never wrote is released at its main data. It refuses while any `[[references]]` row names a record no member holds, and lists each one.
99
+
100
+ ## From a terminal
101
+
102
+ An agent with a factory-agent key (`fk_…`) stored by `gateway auth login` can do all of this with the `gateway` CLI. Each verb is the tool above that does the same work, under the same switch and the factory's rules:
103
+
104
+ - **Documents:** `gateway factory show|revisions|diff <bundle>`, and `gateway factory edit <bundle> --file edits.json --base <rev> --doc <ontology|graph|rules|tests|spine>`. Your edit must name its document with `--doc`.
105
+ - **Spine:** `gateway factory spine show <bundle>`, `spine rows <bundle> <table>`, `spine generate <bundle> <table>… --base <rev>` and `spine accept <bundle> <partition> <key>`.
106
+ - **Data:** `gateway factory describe|records|data|release <bundle>`, `gateway factory upload <bundle> <file> --world <world>`, `gateway factory enrichment <bundle> --world <world> --entity <entity> --on|--off` and `gateway factory run start <bundle>`.
107
+ - **Worlds:** `gateway worlds sandbox open <member>`, then `status`, `read`, `write`, `exec`, `check`, `commit`, `import` and `close` on that sandbox.
108
+
109
+ The key never reaches `gateway factory agents` (or its switches), `run stop`, `chat` or `sandbox list`. Those are a person's.
110
+
111
+ ## How to work
112
+
113
+ 1. **Read first.** Call `get_factory` and note `head`. Every write passes the latest `head` you saw as `base`.
114
+ 2. **Agree before writing.** Restate what you understood in a sentence or two. When the request can be read two ways, ask.
115
+ 3. **Write small.** Commit a few nodes at a time, with a `message` that says what changed. Reuse ids; never change an id to change a name.
116
+ 4. **Write in sentences.** A node's `sentence` is what a person reads first. Make it true and specific.
117
+ 5. **Point, don't copy.** Link to a world, a schema field or another node with `refs` instead of repeating it.
118
+
119
+ ## When something pushes back
120
+
121
+ - **`factory_conflict`:** someone changed the same field. Re-read the head, re-apply your change to the new text and commit on the new base. If the two intents disagree, ask the person.
122
+ - **`factory_invalid`:** each issue names its node and field. Fix those and commit again; nothing was written.
123
+ - **`factory_tool_not_granted`:** that switch is off for you. Tell the person which switch the change needs. Never reach for another tool to make the same change.
124
+ - **A result that carries `changes`:** someone moved the head since your last call; the line says what. When it touches what you are doing, re-read before your next write.
125
+ - **`factory_spine_checks_failed`:** each issue names a spine node, the check and the numbers. Fix the values or the facts they read; nothing was written.
126
+ - **`factory_spine_generate_failed`:** a generator raised or returned rows that are not objects; the error names the table. Fix its code; nothing was written.
127
+ - **`factory_unit_unknown`:** the `unit` names no partition table or no row of it.
128
+ - **`factory_rule_tests_failed`:** a `block` test failed; each failure names its test and case. Fix the rule or the test; nothing was written.
129
+ - **`factory_hook_denied`:** a rule's guard refused the call; `rule` and `reason` say why. Do what the reason asks, or tell the person; never retry the same call unchanged.
130
+ - **`factory_records_refused`:** each refusal names a row (`world`, `entity`, `index`, and `propagated` when it is a counterpart the platform wrote) and why: `reference_broken` (write the referenced record first, fix the value, or send `deferReferences: true` when it comes later), `row_refused` (the world's contract), `row_not_found` (a patch for a row no member holds; write it without `patch` first), `identity_conflict` (two values for one person's carried field; send one), `real_field_protected` or `real_rows_protected` (real data; leave those fields as they are, or ask the person to enable enrichment), `partition_other_unit` (another unit owns that row; leave it to that unit) or `partition_owner_failed` (the partition's owner function raised; fix it or tell the person). Nothing was written; fix those rows and send the write again.
131
+ - **`factory_run_required`, `factory_run_released`, `factory_run_stopped`, `factory_budget_reached`:** no run is active, or it ended, so nothing can be written. Tell the person. Start a run yourself only when the person asked for one and "Starts runs" is on.
132
+ - **`factory_agent_key_mcp_only`, `factory_roster_people_only`:** that is a person's: the roster, switches, keys, stopping a run or the chat. Tell the person what you need.
133
+ - **`factory_run_busy`:** another write or the release held the run, or other writes kept moving the drafts while yours was built. Nothing of yours was kept in any member; send the same write again.
134
+ - **`factory_run_hold_ended`:** your write ran past the run's lock (three minutes). Nothing of yours was kept; send the same rows again as smaller slices.
135
+ - **`factory_draft_name_taken`:** a member already has a world state named like this run's draft. Tell the person; nothing was written.
136
+ - **`factory_records_failed`:** a member's import failed, and the message names it. Nothing of yours was kept; read the drafts with `get_factory_data` before writing again.
137
+ - **`factory_state_carrying`:** a person moved the bundle's pin, and a member's draft or Day 0 is being carried onto the new version. Nothing was written; wait a minute, then read or send the same call again. After three such answers for the same member, stop and tell the person.
138
+ - **`factory_state_not_carried`:** that carry failed or was refused. When the message says a write, a release or a run start queues it again, at most once every 10 minutes, send the same write again after that. When it says to start from main or empty, tell the person: this run's draft cannot follow the new pin.
139
+ - **`factory_state_off_pin`:** a member's state was built on a version past the one the bundle pins. Nothing was written; tell the person, who can commit the bundle to move the pin, or start a run from main or empty.
140
+ - **`factory_release_refused`:** each refusal names a member world, a row and the value no member holds (`pending` when the row was deferred, `reservation_unfulfilled` when the spine reserved it). Write the missing records or fix the rows, then release again; nothing was released.
141
+ - **`factory_release_conflict`:** a member's draft or Day 0 state changed outside this run. Check what the members hold, then release again; nothing was released.
142
+ - **`factory_rule_runner_unavailable`:** the rule runner could not start, so nothing that needs it ran. Tell the person; try again later.
143
+
144
+ ## What never happens
145
+
146
+ - No document leaves the platform: never paste a whole document into a file, a world or a message outside this factory.
147
+ - Never invent a kind, a rule or a relationship the person did not ask for. Propose it, and wait.
@@ -260,7 +260,10 @@ A `.csv`/`.tsv` (optionally `.gz`) is read as a stream — memory is bounded at
260
260
  split by `--delimiter` (one character, `\t` for a tab; default `,`, tab for a `.tsv`). The header
261
261
  row names the fields; `--entity` says which entity they fill. Every cell is cast by that field's
262
262
  schema type, the same rule in the TypeScript CLI (`worldData/cast.ts`) and the Python package
263
- (`schema/cast.py`), pinned by `gatewaysdk/sdk/tests/conformance/csv_cast.json`:
263
+ (`schema/cast.py`), pinned by `gatewaysdk/sdk/tests/conformance/csv_cast.json`. The type is the one
264
+ `worlds describe` reports: the JSON type words the field admits through `$ref`s (into sibling
265
+ `schema/*.json` files too) and unions, so a field that is a reference to an object casts as JSON and
266
+ `anyOf [Count, null]` as `integer | null`:
264
267
 
265
268
  | Field type | Cell | Value |
266
269
  | --- | --- | --- |
@@ -270,6 +273,7 @@ schema type, the same rule in the TypeScript CLI (`worldData/cast.ts`) and the P
270
273
  | `array` / `object` | JSON text of that shape (quote it in the CSV: `"[""a"",""b""]"`) | the parsed value |
271
274
  | `string` | anything | the text as given |
272
275
  | `integer \| string` (union) | each member tried in order, `string` last | the first that fits |
276
+ | `number \| boolean \| string \| null` (a union that admits string) | `00501`, `true` | the typed member that fits first (`501.0`, `true`): leading zeros and literal text do not survive; import JSON or JSONL to keep a value as text |
273
277
  | any, empty cell | (nothing) | null when the type admits null; `""` for a required string; left out otherwise (a required one is then refused by the contract) |
274
278
 
275
279
  A cell that fits none stays its text and the contract refuses the row as it refuses a JSON row
@@ -101,7 +101,7 @@ commit, with a warning); bulk rows reach the platform world through `worlds sand
101
101
 
102
102
  ```bash
103
103
  gateway worlds describe <WORLD> # entities, keys, relationships, row counts, and how each field is stored
104
- gateway worlds describe <WORLD> --json # the same as a document (fields[].redaction, redact)
104
+ gateway worlds describe <WORLD> --json [--entity e] # the document: fields[].redaction, .enum, .format, redact, catalog (enums, JSON shapes, custom fields, ids, sequences)
105
105
  gateway worlds data show <WORLD> # {world, kind, entity_counts}
106
106
  gateway worlds data show <WORLD> --entity users # the rows of one entity
107
107
  gateway worlds data query <WORLD> users --where plan=pro --limit 50 # the rows you mean; a repeated --where key is IN
@@ -140,6 +140,7 @@ gateway worlds data import <WORLD> rows.json --redact apply # run the w
140
140
  gateway worlds data import <slug> export.jsonl -m "Q3 tenants" # platform: chunked upload, new version
141
141
  gateway worlds data import <slug> export.jsonl --per-chunk --publish later --report refusals.jsonl
142
142
  gateway worlds data import <slug> export.jsonl --resume # pick a dead upload back up
143
+ gateway worlds data import <slug> rows.jsonl --state q4-messy # into a world state only: no version, main untouched
143
144
  gateway worlds data check <WORLD> rows.json --report refusals.jsonl # the dry run on its own; exit 2 on refusals
144
145
  ```
145
146
 
@@ -162,13 +163,14 @@ state}` and `gateway worlds data status <batchId> [--report <file>]` reads it la
162
163
  published, 2 refused (the report is written when `--report` is given: JSONL of refusal
163
164
  records, at most 10,000 then `{"truncated": true, "total": N}`), 1 error.
164
165
 
166
+ `--state <name>` lands the batch in that world state (`worlds state create` first): `published`, no `versionId`, `worldState` in the view; `worlds state show|pull` reads it on any version (`--ref`); `--rebase` rebuilds a state its rows cannot follow on main's data; `--publish later` is refused.
165
167
  A manifest at `.gateway/imports/<batchId>.json` records every chunk's digest as it lands;
166
168
  `--resume` reopens the newest incomplete batch for that slug and files and uploads only the
167
169
  chunks the platform does not already hold. `--publish later` applies without a version;
168
170
  `gateway worlds data publish <slug>` folds every pending batch into one; `data batches <slug>` lists them.
169
171
  A refusal record, everywhere (dry run, report, status, MCP):
170
172
  `{"chunk", "index", "entity", "primaryKey", "field", "pointer", "detail"}`, `pointer` being
171
- `/<entity>/<index>/<field>` inside the chunk.
173
+ `/<entity>/<index>/<field>` inside the chunk (`chunk`, `index` null when it spans chunks).
172
174
 
173
175
  MCP: `import_world_data({ containerId | slug, rows, mode?, message? })`. `rows` is the JSON
174
176
  object shape (`{entity: [rows]}`), at most 5,000 rows and 4 MiB per call: the inline lane,
@@ -178,7 +180,7 @@ refused row is a tool error naming the field, and nothing is written.
178
180
  ### 2a. Pull a connector's data through an active connection
179
181
 
180
182
  For a schema world created from a connector template (`worlds create --from-connection`, or
181
- the Connectors page), the provider is the source — no rows file:
183
+ the WorldHub page), the provider is the source — no rows file:
182
184
 
183
185
  ```bash
184
186
  gateway worlds data pull <slug> --connection google_drive # connector slug when the project has one connection for it
@@ -194,7 +196,7 @@ contract like `data import`. `replace` (default) rebuilds the mapped entities fr
194
196
  `pulled|unchanged <slug> from <connector> connection <id> (<mode>, <n> calls[, k unmatched (tool…)])
195
197
  <hash> [entity=count …]`; `changed: false` in `--json` when the pull reproduced the tip (no new
196
198
  version). The key reaches the connections shared with its project; a personal connection serves
197
- its owner alone (the Connectors page, or the MCP tool as that user) and is refused here. An
199
+ its owner alone (the WorldHub page, or the MCP tool as that user) and is refused here. An
198
200
  inactive connection, a world without a contract, or a template that does not read the connector
199
201
  is a refusal (exit 1) and nothing is written; a provider failure is reported as
200
202
  `provider tool failed (HTTP n)` with no provider body.
@@ -493,6 +495,6 @@ handler or route edit keeps the imported data while an entity, field or key edit
493
495
 
494
496
  - `worlds-getting-started`: the whole path, auth to runs, CLI with MCP twins.
495
497
  - `connector-schema-authoring`: the data model the rows are checked against.
496
- - `documentation/features/world-data-ingestion.md`: what exists, the contract, code pointers.
497
- - `documentation/features/connector-worlds.md`: captures, ingest, serving the vendor's API.
498
+ - `documentation/features/world-data-ingestion.md` (the contract, code pointers) and `connector-worlds.md` (captures, ingest, the vendor's API).
499
+ - `factory-orchestrator`: a bundle's factory run takes the same files at any point with `gateway factory upload <bundle> <file> --world <member>` (chunked, `--map ingest.toml`, `--per-chunk`, `--dry-run`, `--resume`, `--report`), checked across members and tagged `real:<source>`, so agents may not change those fields.
498
500
  - Consumer page: https://docs.surfacearea.ai/worlds/data.