@orthograph/prove 0.0.0-stage → 0.1.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (245) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +2 -2
  3. package/dist/index.d.ts +32 -0
  4. package/dist/index.js +32 -0
  5. package/dist/modules/build/internal/manifest.d.ts +15 -0
  6. package/dist/modules/build/internal/manifest.js +38 -0
  7. package/dist/modules/build/service.d.ts +2 -0
  8. package/dist/modules/build/service.js +74 -0
  9. package/dist/modules/build/types.d.ts +39 -0
  10. package/dist/modules/build/types.js +4 -0
  11. package/dist/modules/environments/internal/collector.d.ts +2 -0
  12. package/dist/modules/environments/internal/collector.js +5 -0
  13. package/dist/modules/environments/internal/config.d.ts +32 -0
  14. package/dist/modules/environments/internal/config.js +42 -0
  15. package/dist/modules/environments/internal/identity.d.ts +3 -0
  16. package/dist/modules/environments/internal/identity.js +17 -0
  17. package/dist/modules/environments/internal/logbook.d.ts +10 -0
  18. package/dist/modules/environments/internal/logbook.js +23 -0
  19. package/dist/modules/environments/internal/process.d.ts +41 -0
  20. package/dist/modules/environments/internal/process.js +103 -0
  21. package/dist/modules/environments/internal/secrets.d.ts +9 -0
  22. package/dist/modules/environments/internal/secrets.js +23 -0
  23. package/dist/modules/environments/internal/status.d.ts +7 -0
  24. package/dist/modules/environments/internal/status.js +31 -0
  25. package/dist/modules/environments/service.d.ts +2 -0
  26. package/dist/modules/environments/service.js +97 -0
  27. package/dist/modules/environments/types.d.ts +80 -0
  28. package/dist/modules/environments/types.js +4 -0
  29. package/dist/modules/evals/internal/calls.d.ts +19 -0
  30. package/dist/modules/evals/internal/calls.js +168 -0
  31. package/dist/modules/evals/internal/evidence.d.ts +13 -0
  32. package/dist/modules/evals/internal/evidence.js +29 -0
  33. package/dist/modules/evals/internal/run.d.ts +12 -0
  34. package/dist/modules/evals/internal/run.js +85 -0
  35. package/dist/modules/evals/internal/secrets.d.ts +5 -0
  36. package/dist/modules/evals/internal/secrets.js +72 -0
  37. package/dist/modules/evals/service.d.ts +2 -0
  38. package/dist/modules/evals/service.js +29 -0
  39. package/dist/modules/evals/testing.d.ts +12 -0
  40. package/dist/modules/evals/testing.js +15 -0
  41. package/dist/modules/evals/types.d.ts +43 -0
  42. package/dist/modules/evals/types.js +1 -0
  43. package/dist/modules/impact/internal/changed.d.ts +6 -0
  44. package/dist/modules/impact/internal/changed.js +34 -0
  45. package/dist/modules/impact/internal/closure.d.ts +12 -0
  46. package/dist/modules/impact/internal/closure.js +69 -0
  47. package/dist/modules/impact/internal/digest.d.ts +1 -0
  48. package/dist/modules/impact/internal/digest.js +2 -0
  49. package/dist/modules/impact/internal/files.d.ts +11 -0
  50. package/dist/modules/impact/internal/files.js +48 -0
  51. package/dist/modules/impact/internal/ledger.d.ts +5 -0
  52. package/dist/modules/impact/internal/ledger.js +25 -0
  53. package/dist/modules/impact/internal/linked.d.ts +4 -0
  54. package/dist/modules/impact/internal/linked.js +56 -0
  55. package/dist/modules/impact/internal/scan.d.ts +12 -0
  56. package/dist/modules/impact/internal/scan.js +66 -0
  57. package/dist/modules/impact/service.d.ts +2 -0
  58. package/dist/modules/impact/service.js +88 -0
  59. package/dist/modules/impact/types.d.ts +109 -0
  60. package/dist/modules/impact/types.js +1 -0
  61. package/dist/modules/journeys/internal/checks.d.ts +25 -0
  62. package/dist/modules/journeys/internal/checks.js +155 -0
  63. package/dist/modules/journeys/internal/d1-facts.d.ts +10 -0
  64. package/dist/modules/journeys/internal/d1-facts.js +53 -0
  65. package/dist/modules/journeys/internal/database-facts.d.ts +2 -0
  66. package/dist/modules/journeys/internal/database-facts.js +41 -0
  67. package/dist/modules/journeys/internal/device.d.ts +16 -0
  68. package/dist/modules/journeys/internal/device.js +68 -0
  69. package/dist/modules/journeys/internal/keepers.d.ts +6 -0
  70. package/dist/modules/journeys/internal/keepers.js +6 -0
  71. package/dist/modules/journeys/internal/load.d.ts +4 -0
  72. package/dist/modules/journeys/internal/load.js +94 -0
  73. package/dist/modules/journeys/internal/stand-call.d.ts +10 -0
  74. package/dist/modules/journeys/internal/stand-call.js +22 -0
  75. package/dist/modules/journeys/internal/subject.d.ts +8 -0
  76. package/dist/modules/journeys/internal/subject.js +15 -0
  77. package/dist/modules/journeys/internal/world.d.ts +70 -0
  78. package/dist/modules/journeys/internal/world.js +133 -0
  79. package/dist/modules/journeys/service.d.ts +2 -0
  80. package/dist/modules/journeys/service.js +231 -0
  81. package/dist/modules/journeys/types.d.ts +132 -0
  82. package/dist/modules/journeys/types.js +5 -0
  83. package/dist/modules/portal-feed/internal/listen.d.ts +10 -0
  84. package/dist/modules/portal-feed/internal/listen.js +32 -0
  85. package/dist/modules/portal-feed/service.d.ts +2 -0
  86. package/dist/modules/portal-feed/service.js +6 -0
  87. package/dist/modules/portal-feed/types.d.ts +30 -0
  88. package/dist/modules/portal-feed/types.js +5 -0
  89. package/dist/modules/promote/internal/environment.d.ts +6 -0
  90. package/dist/modules/promote/internal/environment.js +10 -0
  91. package/dist/modules/promote/internal/gate.d.ts +9 -0
  92. package/dist/modules/promote/internal/gate.js +37 -0
  93. package/dist/modules/promote/internal/publishing.d.ts +23 -0
  94. package/dist/modules/promote/internal/publishing.js +21 -0
  95. package/dist/modules/promote/service.d.ts +2 -0
  96. package/dist/modules/promote/service.js +112 -0
  97. package/dist/modules/promote/types.d.ts +54 -0
  98. package/dist/modules/promote/types.js +8 -0
  99. package/dist/modules/prove/internal/changed-run.d.ts +9 -0
  100. package/dist/modules/prove/internal/changed-run.js +14 -0
  101. package/dist/modules/prove/internal/device-host.d.ts +16 -0
  102. package/dist/modules/prove/internal/device-host.js +60 -0
  103. package/dist/modules/prove/internal/empty-world.d.ts +5 -0
  104. package/dist/modules/prove/internal/empty-world.js +26 -0
  105. package/dist/modules/prove/internal/exercise.d.ts +35 -0
  106. package/dist/modules/prove/internal/exercise.js +47 -0
  107. package/dist/modules/prove/internal/proof-verdicts.d.ts +5 -0
  108. package/dist/modules/prove/internal/proof-verdicts.js +37 -0
  109. package/dist/modules/prove/internal/report.d.ts +35 -0
  110. package/dist/modules/prove/internal/report.js +169 -0
  111. package/dist/modules/prove/internal/staged.d.ts +9 -0
  112. package/dist/modules/prove/internal/staged.js +30 -0
  113. package/dist/modules/prove/internal/stand.d.ts +40 -0
  114. package/dist/modules/prove/internal/stand.js +155 -0
  115. package/dist/modules/prove/internal/structured.d.ts +78 -0
  116. package/dist/modules/prove/internal/structured.js +55 -0
  117. package/dist/modules/prove/internal/test-run.d.ts +7 -0
  118. package/dist/modules/prove/internal/test-run.js +63 -0
  119. package/dist/modules/prove/service.d.ts +2 -0
  120. package/dist/modules/prove/service.js +98 -0
  121. package/dist/modules/prove/types.d.ts +120 -0
  122. package/dist/modules/prove/types.js +5 -0
  123. package/dist/modules/publish/internal/bundle.d.ts +24 -0
  124. package/dist/modules/publish/internal/bundle.js +46 -0
  125. package/dist/modules/publish/internal/env.d.ts +3 -0
  126. package/dist/modules/publish/internal/env.js +2 -0
  127. package/dist/modules/publish/internal/plan.d.ts +28 -0
  128. package/dist/modules/publish/internal/plan.js +28 -0
  129. package/dist/modules/publish/internal/registry.d.ts +24 -0
  130. package/dist/modules/publish/internal/registry.js +55 -0
  131. package/dist/modules/publish/internal/sea.d.ts +20 -0
  132. package/dist/modules/publish/internal/sea.js +77 -0
  133. package/dist/modules/publish/internal/source.d.ts +4 -0
  134. package/dist/modules/publish/internal/source.js +41 -0
  135. package/dist/modules/publish/internal/stage.d.ts +14 -0
  136. package/dist/modules/publish/internal/stage.js +95 -0
  137. package/dist/modules/publish/internal/tap.d.ts +22 -0
  138. package/dist/modules/publish/internal/tap.js +61 -0
  139. package/dist/modules/publish/service.d.ts +2 -0
  140. package/dist/modules/publish/service.js +99 -0
  141. package/dist/modules/publish/types.d.ts +80 -0
  142. package/dist/modules/publish/types.js +4 -0
  143. package/dist/modules/releases/internal/http.d.ts +12 -0
  144. package/dist/modules/releases/internal/http.js +14 -0
  145. package/dist/modules/releases/internal/stale.d.ts +13 -0
  146. package/dist/modules/releases/internal/stale.js +43 -0
  147. package/dist/modules/releases/service.d.ts +2 -0
  148. package/dist/modules/releases/service.js +59 -0
  149. package/dist/modules/releases/types.d.ts +81 -0
  150. package/dist/modules/releases/types.js +6 -0
  151. package/dist/modules/secrets/internal/file.d.ts +5 -0
  152. package/dist/modules/secrets/internal/file.js +25 -0
  153. package/dist/modules/secrets/service.d.ts +2 -0
  154. package/dist/modules/secrets/service.js +38 -0
  155. package/dist/modules/secrets/types.d.ts +44 -0
  156. package/dist/modules/secrets/types.js +7 -0
  157. package/dist/modules/server-config/internal/jsonc.d.ts +2 -0
  158. package/dist/modules/server-config/internal/jsonc.js +29 -0
  159. package/dist/modules/server-config/service.d.ts +2 -0
  160. package/dist/modules/server-config/service.js +21 -0
  161. package/dist/modules/server-config/types.d.ts +22 -0
  162. package/dist/modules/server-config/types.js +3 -0
  163. package/dist/modules/sinks/internal/axiom.d.ts +29 -0
  164. package/dist/modules/sinks/internal/axiom.js +25 -0
  165. package/dist/modules/sinks/internal/keychain.d.ts +2 -0
  166. package/dist/modules/sinks/internal/keychain.js +13 -0
  167. package/dist/modules/sinks/service.d.ts +2 -0
  168. package/dist/modules/sinks/service.js +26 -0
  169. package/dist/modules/sinks/types.d.ts +37 -0
  170. package/dist/modules/sinks/types.js +5 -0
  171. package/dist/modules/telemetry/internal/axiom-source.d.ts +2 -0
  172. package/dist/modules/telemetry/internal/axiom-source.js +108 -0
  173. package/dist/modules/telemetry/internal/binary.d.ts +11 -0
  174. package/dist/modules/telemetry/internal/binary.js +66 -0
  175. package/dist/modules/telemetry/internal/config.d.ts +13 -0
  176. package/dist/modules/telemetry/internal/config.js +22 -0
  177. package/dist/modules/telemetry/internal/file-metrics.d.ts +2 -0
  178. package/dist/modules/telemetry/internal/file-metrics.js +60 -0
  179. package/dist/modules/telemetry/internal/file-source.d.ts +2 -0
  180. package/dist/modules/telemetry/internal/file-source.js +38 -0
  181. package/dist/modules/telemetry/internal/journey-root.d.ts +44 -0
  182. package/dist/modules/telemetry/internal/journey-root.js +36 -0
  183. package/dist/modules/telemetry/internal/local.d.ts +11 -0
  184. package/dist/modules/telemetry/internal/local.js +57 -0
  185. package/dist/modules/telemetry/internal/otlp.d.ts +15 -0
  186. package/dist/modules/telemetry/internal/otlp.js +53 -0
  187. package/dist/modules/telemetry/internal/private-keys.d.ts +7 -0
  188. package/dist/modules/telemetry/internal/private-keys.js +28 -0
  189. package/dist/modules/telemetry/internal/process.d.ts +27 -0
  190. package/dist/modules/telemetry/internal/process.js +96 -0
  191. package/dist/modules/telemetry/internal/runs.d.ts +17 -0
  192. package/dist/modules/telemetry/internal/runs.js +48 -0
  193. package/dist/modules/telemetry/service.d.ts +9 -0
  194. package/dist/modules/telemetry/service.js +48 -0
  195. package/dist/modules/telemetry/types.d.ts +138 -0
  196. package/dist/modules/telemetry/types.js +13 -0
  197. package/dist/modules/test-worlds/internal/lifetime.d.ts +3 -0
  198. package/dist/modules/test-worlds/internal/lifetime.js +19 -0
  199. package/dist/modules/test-worlds/service.d.ts +2 -0
  200. package/dist/modules/test-worlds/service.js +35 -0
  201. package/dist/modules/test-worlds/types.d.ts +41 -0
  202. package/dist/modules/test-worlds/types.js +4 -0
  203. package/dist/modules/trace-trees/service.d.ts +2 -0
  204. package/dist/modules/trace-trees/service.js +40 -0
  205. package/dist/modules/trace-trees/types.d.ts +9 -0
  206. package/dist/modules/trace-trees/types.js +1 -0
  207. package/dist/modules/verdicts/internal/proof.d.ts +24 -0
  208. package/dist/modules/verdicts/internal/proof.js +59 -0
  209. package/dist/modules/verdicts/service.d.ts +16 -0
  210. package/dist/modules/verdicts/service.js +71 -0
  211. package/dist/modules/verdicts/types.d.ts +80 -0
  212. package/dist/modules/verdicts/types.js +4 -0
  213. package/dist/modules/warm/internal/source.d.ts +7 -0
  214. package/dist/modules/warm/internal/source.js +27 -0
  215. package/dist/modules/warm/service.d.ts +2 -0
  216. package/dist/modules/warm/service.js +76 -0
  217. package/dist/modules/warm/types.d.ts +43 -0
  218. package/dist/modules/warm/types.js +4 -0
  219. package/dist/modules/watch/internal/choose.d.ts +20 -0
  220. package/dist/modules/watch/internal/choose.js +24 -0
  221. package/dist/modules/watch/internal/evidence.d.ts +9 -0
  222. package/dist/modules/watch/internal/evidence.js +26 -0
  223. package/dist/modules/watch/internal/report.d.ts +18 -0
  224. package/dist/modules/watch/internal/report.js +59 -0
  225. package/dist/modules/watch/internal/tasks.d.ts +5 -0
  226. package/dist/modules/watch/internal/tasks.js +35 -0
  227. package/dist/modules/watch/service.d.ts +2 -0
  228. package/dist/modules/watch/service.js +38 -0
  229. package/dist/modules/watch/types.d.ts +44 -0
  230. package/dist/modules/watch/types.js +4 -0
  231. package/dist/modules/world/internal/ports.d.ts +8 -0
  232. package/dist/modules/world/internal/ports.js +30 -0
  233. package/dist/modules/world/internal/wrangler.d.ts +46 -0
  234. package/dist/modules/world/internal/wrangler.js +112 -0
  235. package/dist/modules/world/service.d.ts +2 -0
  236. package/dist/modules/world/service.js +46 -0
  237. package/dist/modules/world/types.d.ts +97 -0
  238. package/dist/modules/world/types.js +4 -0
  239. package/dist/modules/world-clock/internal/door.d.ts +8 -0
  240. package/dist/modules/world-clock/internal/door.js +9 -0
  241. package/dist/modules/world-clock/service.d.ts +2 -0
  242. package/dist/modules/world-clock/service.js +9 -0
  243. package/dist/modules/world-clock/types.d.ts +34 -0
  244. package/dist/modules/world-clock/types.js +1 -0
  245. package/package.json +38 -3
@@ -0,0 +1,68 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ // A call to a plugin's operation that runs on the device (M1.29): prove has no device, so it runs the plugin's `world` entry
10
+ // in its own process, as the generated SDK runs the `node` or `browser` one, under the app's mount, as an anonymous caller.
11
+ // The call is recorded as a served one is: a status, a body in the declaration's wire form, the trace it made.
12
+ import { randomBytes } from "node:crypto";
13
+ import { Cause, Effect, Exit, Schema, Tracer } from "effect";
14
+ import { Device, DeviceWorld, Mount } from "@orthograph/language-effect/device";
15
+ import { resolveFrom } from "@orthograph/compiler";
16
+ import { pathToFileURL } from "node:url";
17
+ import { resolve } from "node:path";
18
+ import { PROVE_SPAN_PREFIX } from "#modules/telemetry/types.js";
19
+ /** A declared refusal's answer is 422 with `{ _tag, code, ...fields }`, as the generated server sends it. */
20
+ const DECLARED = 422;
21
+ /** Whether this operation runs on a device, and so is called here rather than on the world's server. */
22
+ export const onDevice = (op) => op !== undefined && op.runs === "client" && op.from.kind !== "app";
23
+ const served = new WeakMap();
24
+ const load = (specifier) => Effect.tryPromise({ try: () => import(__rewriteRelativeImportExtension(specifier)), catch: (e) => new Error(`${specifier} couldn't be loaded: ${String(e)}`) }).pipe(Effect.orDie);
25
+ /** The operation served by its plugin's `world` entry, under the app's mount: made once for the project. */
26
+ const serving = (project, model, declaration) => Effect.gen(function* () {
27
+ const known = served.get(project)?.get(model.name);
28
+ if (known)
29
+ return known;
30
+ const from = model.from;
31
+ if (from.kind === "app")
32
+ return yield* Effect.die(new Error(`${model.name} is the app's own and has no world entry`));
33
+ const root = resolve(project.root);
34
+ const entry = (yield* load(resolveFrom(root, `${from.package}/src/${from.thing}/${model.verb}.world.js`)))["default"];
35
+ const mount = project.model.mounts?.[from.mount];
36
+ const wrapped = mount ? (yield* load(pathToFileURL(resolve(root, mount.file)).href))["default"] : undefined;
37
+ const handler = (wrapped ? Mount.serving(wrapped, entry) : entry);
38
+ const device = Device.serve({ name: model.name, operation: declaration, handler: handler });
39
+ const mine = served.get(project) ?? new Map();
40
+ mine.set(model.name, device);
41
+ served.set(project, mine);
42
+ return device;
43
+ });
44
+ const tagOf = (e) => typeof e === "object" && e !== null && typeof e._tag === "string" ? e._tag : undefined;
45
+ /** A refusal's fields as the wire carries them: what the class holds, but its tag and its message. */
46
+ const fieldsOf = (e) => Object.fromEntries(Object.entries(e).filter(([k]) => k !== "_tag" && k !== "message"));
47
+ export const callDevice = (project, host, name, declaration, payload) => Effect.gen(function* () {
48
+ const model = project.model.operations[name];
49
+ const wire = yield* Schema.encodeUnknownEffect(declaration.payloadSchema)(payload).pipe(Effect.orElseSucceed(() => payload));
50
+ const trace = randomBytes(16).toString("hex");
51
+ const parent = `${PROVE_SPAN_PREFIX}${randomBytes(4).toString("hex")}`;
52
+ const device = yield* serving(project, model, declaration);
53
+ const exit = yield* device.run(payload, { otlp: host.otlp, service: host.service }).pipe(Effect.provideService(DeviceWorld, host.world),
54
+ // The call's own span is the child of the one the journey made for it, in the trace prove will read back.
55
+ Effect.withParentSpan(Tracer.externalSpan({ traceId: trace, spanId: parent, sampled: true })), Effect.exit);
56
+ const base = { wire, trace, parent, journal: [] };
57
+ if (Exit.isSuccess(exit)) {
58
+ const body = yield* Schema.encodeUnknownEffect(declaration.answerSchema)(exit.value).pipe(Effect.orElseSucceed(() => exit.value));
59
+ return { ...base, status: 200, body };
60
+ }
61
+ const failure = Cause.hasDies(exit.cause) ? undefined : Cause.squash(exit.cause);
62
+ const tag = tagOf(failure);
63
+ if (failure === undefined || tag === undefined || !model.errors.includes(tag)) {
64
+ return { ...base, status: 500, body: null };
65
+ }
66
+ const code = project.model.refusals[tag];
67
+ return { ...base, status: DECLARED, body: { _tag: tag, ...(code === undefined ? {} : { code }), ...fieldsOf(failure) } };
68
+ });
@@ -0,0 +1,6 @@
1
+ type Cast = {
2
+ readonly [name: string]: unknown;
3
+ };
4
+ /** `casts` oldest first: a starting world's lineage, then the journey's own. */
5
+ export declare const keepersIn: (names: ReadonlyArray<string>, casts: ReadonlyArray<Cast>) => ReadonlySet<string>;
6
+ export {};
@@ -0,0 +1,6 @@
1
+ const isKeeper = (role) => role?.kind === "keeper";
2
+ /** `casts` oldest first: a starting world's lineage, then the journey's own. */
3
+ export const keepersIn = (names, casts) => {
4
+ const resolved = Object.assign({}, ...casts);
5
+ return new Set(names.filter((n) => isKeeper(resolved[n])));
6
+ };
@@ -0,0 +1,4 @@
1
+ import { Effect } from "effect";
2
+ import { type Model } from "@orthograph/compiler";
3
+ import { ProjectFailed, type Project } from "../types.ts";
4
+ export declare const loadProject: (given: string, model: Model) => Effect.Effect<Project, ProjectFailed>;
@@ -0,0 +1,94 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ // Loading what a project declares, by path, so every declaration is the same object the journeys import.
10
+ import { existsSync, readdirSync, realpathSync } from "node:fs";
11
+ import { createRequire } from "node:module";
12
+ import { join, relative, sep } from "node:path";
13
+ import { pathToFileURL } from "node:url";
14
+ import { Effect } from "effect";
15
+ import { pluginFolder } from "@orthograph/compiler";
16
+ import { ProjectFailed } from "../types.js";
17
+ const importFile = (path) => Effect.tryPromise({
18
+ try: () => import(__rewriteRelativeImportExtension(pathToFileURL(path).href)),
19
+ catch: (e) => new ProjectFailed({ message: `${path} couldn't be loaded: ${String(e)}` }),
20
+ });
21
+ const kindOf = (x) => (typeof x === "object" && x !== null ? x.kind : undefined);
22
+ const filesIn = (dir, ext = ".ts") => (existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith(ext) && !f.endsWith(".d.ts")).sort().map((f) => join(dir, f)) : []);
23
+ /** A declaration's file: the project's own by path, a plugin's by its specifier, resolved as the project resolves it. */
24
+ const fileOf = (root, file) => (file.startsWith("blueprint/") ? join(root, file) : createRequire(join(root, "package.json")).resolve(file));
25
+ export const loadProject = (given, model) => Effect.gen(function* () {
26
+ // By its real path, as the compiler loads it, so a declaration here is the same object the model was built from.
27
+ const root = existsSync(given) ? realpathSync(given) : given;
28
+ // The generated api names every event and error, the same way the server does.
29
+ yield* importFile(join(root, "generated/api/src/index.ts"));
30
+ const operations = new Map();
31
+ for (const op of Object.values(model.operations)) {
32
+ operations.set(op.name, (yield* importFile(fileOf(root, op.file)))["default"]);
33
+ }
34
+ const things = new Map();
35
+ for (const t of Object.values(model.things)) {
36
+ const module = yield* importFile(t.from.kind !== "app" ? fileOf(root, `${t.from.package}/blueprint/things/${t.from.thing}/thing.js`) : join(root, "blueprint/things", t.name, "thing.ts"));
37
+ const thing = Object.values(module).find((x) => kindOf(x) === "thing");
38
+ if (thing)
39
+ things.set(t.name, thing);
40
+ }
41
+ const journeys = [];
42
+ const journeyFiles = [];
43
+ // A journey with blanks (a stub from `ortho add journeys`) isn't run: prove names it, and `ortho check` names its blanks (K16 e).
44
+ const unfinished = [];
45
+ // The docs' place is blueprint/journeys/; a journey written at the project's root journeys/ is read too (D2 #24).
46
+ // A feature's own journeys run beside the app's, in the app's worlds (M1-plugins section 10).
47
+ const features = Object.values(model.mounts ?? {}).filter((m) => m.kind === "feature");
48
+ const plugins = features.flatMap((m) => {
49
+ const folder = pluginFolder(root, m.package);
50
+ return folder ? filesIn(join(folder, "journeys"), ".js").map((file) => [file, `${m.package}/blueprint/${relative(folder, file).split(sep).join("/")}`]) : [];
51
+ });
52
+ const app = [...filesIn(join(root, "blueprint/journeys")), ...filesIn(join(root, "journeys"))];
53
+ for (const [file, name] of [...app.map((f) => [f, relative(root, f).split(sep).join("/")]), ...plugins]) {
54
+ const d = (yield* importFile(file))["default"];
55
+ if (kindOf(d) !== "journey")
56
+ return yield* new ProjectFailed({ message: `${file}: the default export must be a Blueprint.journey` });
57
+ if (model.journeys[name]?.blanks) {
58
+ unfinished.push(name);
59
+ continue;
60
+ }
61
+ journeys.push(d);
62
+ journeyFiles.push(name);
63
+ }
64
+ // A journey's step that runs an operation a mount omits is skipped and named when it runs (M1-plugins section 3).
65
+ const omitted = yield* omittedBy(root, model);
66
+ // Each adapter's mount by its name: the same objects the declarations name in a `service` role.
67
+ const mounts = new Map();
68
+ for (const [name, m] of Object.entries(model.mounts ?? {})) {
69
+ if (m.kind === "adapter")
70
+ mounts.set((yield* importFile(fileOf(root, m.file)))["default"], name);
71
+ }
72
+ const startingWorlds = new Map();
73
+ for (const file of filesIn(join(root, "blueprint/starting-worlds"))) {
74
+ const d = (yield* importFile(file))["default"];
75
+ if (kindOf(d) !== "starting-world")
76
+ return yield* new ProjectFailed({ message: `${file}: the default export must be a Blueprint.startingWorld` });
77
+ startingWorlds.set(d.name, d);
78
+ }
79
+ return { root: given, model, operations, things, journeys, journeyFiles, startingWorlds, ...(mounts.size > 0 ? { mounts } : {}), ...(omitted.size > 0 ? { omitted } : {}), ...(unfinished.length > 0 ? { unfinished } : {}) };
80
+ });
81
+ /** Each operation a mount omits, by its declaration: the plugin's own file, found from the operation's final name. */
82
+ const omittedBy = (root, model) => Effect.gen(function* () {
83
+ const found = new Map();
84
+ for (const [mount, m] of Object.entries(model.mounts ?? {})) {
85
+ const own = m.package.slice(m.package.lastIndexOf("/") + 1);
86
+ for (const operation of m.omitted ?? []) {
87
+ const [thing = "", verb = ""] = operation.split(".");
88
+ const theirs = mount === own ? thing : thing.slice(mount.length + 1);
89
+ const module = yield* importFile(fileOf(root, `${m.package}/blueprint/things/${theirs}/verbs/${verb}.js`));
90
+ found.set(module["default"], { operation, file: m.file });
91
+ }
92
+ }
93
+ return found;
94
+ });
@@ -0,0 +1,10 @@
1
+ import { Effect } from "effect";
2
+ export interface StandAnswer {
3
+ /** What the stand-in answered with, or `undefined` when nothing was sent or nothing came back. */
4
+ readonly status: number | undefined;
5
+ readonly body: unknown;
6
+ /** Why the step fails, naming the mount, the command and the status; `undefined` when the answer is one. */
7
+ readonly failure: string | undefined;
8
+ }
9
+ /** Send `args` to the stand-in at `address`, the world's own for `mount`; with no address nothing is sent. */
10
+ export declare const sendCommand: (address: string | undefined, mount: string, command: string, args: unknown) => Effect.Effect<StandAnswer>;
@@ -0,0 +1,22 @@
1
+ // A journey's command to a mount's stand-in (G16-adapter-mounts call 4): `args` POSTed as JSON, once, to `/_stand/<command>`
2
+ // on the stand-in prove started for the mount. Only a 2xx JSON answer is an answer; a redirect is never followed.
3
+ import { Effect, Option, Schema } from "effect";
4
+ const parse = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
5
+ /** Send `args` to the stand-in at `address`, the world's own for `mount`; with no address nothing is sent. */
6
+ export const sendCommand = (address, mount, command, args) => Effect.gen(function* () {
7
+ const named = `the stand-in for mount ${mount}, command ${command}`;
8
+ if (address === undefined)
9
+ return { status: undefined, body: null, failure: `${named}: mount ${mount} has no stand-in running, so nothing was sent` };
10
+ const sent = yield* Effect.promise(() => fetch(`${address.replace(/\/+$/, "")}/_stand/${command}`, {
11
+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(args), redirect: "manual",
12
+ }).then((r) => r.text().then((text) => ({ status: r.status, text }), () => ({ status: r.status, text: "" })), (e) => ({ status: undefined, text: String(e) })));
13
+ if (sent.status === undefined)
14
+ return { status: undefined, body: null, failure: `${named}: couldn't be reached (${sent.text})` };
15
+ const body = parse(sent.text);
16
+ if (sent.status < 200 || sent.status > 299) {
17
+ return { status: sent.status, body: Option.getOrElse(body, () => sent.text), failure: `${named}: answered ${sent.status}` };
18
+ }
19
+ if (Option.isNone(body))
20
+ return { status: sent.status, body: sent.text, failure: `${named}: answered ${sent.status} with no JSON` };
21
+ return { status: sent.status, body: body.value, failure: undefined };
22
+ });
@@ -0,0 +1,8 @@
1
+ import type { OperationModel } from "@orthograph/compiler";
2
+ /** The answer field that names the operation's own thing: the instance a move moves. */
3
+ export declare const subjectField: (op: OperationModel) => {
4
+ readonly from: "answer" | "payload";
5
+ readonly key: string;
6
+ } | undefined;
7
+ /** The id of the instance this call moved, from its answer or its payload. */
8
+ export declare const subjectId: (op: OperationModel, payload: Readonly<Record<string, unknown>>, body: unknown) => string | undefined;
@@ -0,0 +1,15 @@
1
+ /** The answer field that names the operation's own thing: the instance a move moves. */
2
+ export const subjectField = (op) => {
3
+ const own = `${op.thing}.id`;
4
+ const a = Object.entries(op.answer).find(([, f]) => f.ref === own)?.[0];
5
+ if (a)
6
+ return { from: "answer", key: a };
7
+ const p = Object.entries(op.payload).find(([, f]) => f.ref === own)?.[0];
8
+ return p ? { from: "payload", key: p } : undefined;
9
+ };
10
+ /** The id of the instance this call moved, from its answer or its payload. */
11
+ export const subjectId = (op, payload, body) => {
12
+ const subject = subjectField(op);
13
+ const id = subject ? (subject.from === "answer" ? body?.[subject.key] : payload[subject.key]) : undefined;
14
+ return typeof id === "string" ? id : undefined;
15
+ };
@@ -0,0 +1,70 @@
1
+ import { Effect, Layer } from "effect";
2
+ import type { Operation, Read, Principal, Thing } from "orthograph";
3
+ import { Records } from "@orthograph/language-effect";
4
+ import type { CallRecord, Facts } from "../types.ts";
5
+ /** The world signs `names` up for real; `anonymous` only get an email and a password. */
6
+ export declare const castPeople: (url: string, names: ReadonlyArray<string>, anonymous?: ReadonlyArray<string>) => Effect.Effect<Record<string, {
7
+ readonly person?: string;
8
+ readonly token?: string;
9
+ readonly email: string;
10
+ readonly password: string;
11
+ }>, never, never>;
12
+ /**
13
+ * A real environment has no `/_world/cast`: its people sign up and sign in through Better Auth's own routes, with an email
14
+ * and password of their own (never `@world.test`'s fixed ones: a person made here stays in the environment). `anonymous`
15
+ * only get credentials, so a script can sign them up itself. A refusal is the problem as text.
16
+ */
17
+ export declare const signUpPeople: (url: string, names: ReadonlyArray<string>, anonymous?: ReadonlyArray<string>) => Effect.Effect<Record<string, {
18
+ person?: string;
19
+ token?: string;
20
+ email: string;
21
+ password: string;
22
+ }>, string, never>;
23
+ /**
24
+ * The credential the world mints for one cast member's way in (`key` or `agent`: an `ak_` key, the second made for an agent), or for
25
+ * the system or a service: none of which a sign-in makes. `undefined` when the world has no such door or will not mint it.
26
+ */
27
+ export declare const mintCredential: (url: string, spec: {
28
+ readonly name: string;
29
+ readonly via: string;
30
+ } | {
31
+ readonly system: true;
32
+ } | {
33
+ readonly service: string;
34
+ }) => Effect.Effect<string | undefined, never, never>;
35
+ /**
36
+ * A real environment has no `/_world/credential`: a person makes their own key through Better Auth's route, signed in with their session, and
37
+ * marks it for an agent the way a person may (`metadata.acts`). The system and a service have no credential there, so a journey that is one of
38
+ * them runs as no one, which is refused wherever it is refused for being no person.
39
+ */
40
+ export declare const makeKey: (url: string, session: string, forAnAgent: boolean) => Effect.Effect<string | undefined, never, never>;
41
+ /** The tools the MCP door lists for a credential: the wire names, as `{ tools }`; any other answer is kept as it came. */
42
+ export declare const callTools: (url: string, token: string) => Effect.Effect<{
43
+ wire: {};
44
+ status: number;
45
+ body: unknown;
46
+ trace: string;
47
+ parent: string;
48
+ journal: CallRecord["journal"];
49
+ }, never, never>;
50
+ /** Encode the payload by its declaration, call the route, and record what came back. */
51
+ /** The world's own front door, `/_world/facts/*`: only a world that hosts its tests has one (D3 #127). */
52
+ export declare const doorFacts: (url: string) => Facts;
53
+ export declare const callOperation: (url: string, facts: Facts, name: string, op: Operation | Read, payload: Record<string, unknown>, token: string, request: string | undefined, startingWorld?: boolean) => Effect.Effect<{
54
+ wire: Record<string, unknown>;
55
+ status: number;
56
+ body: unknown;
57
+ trace: string;
58
+ parent: string;
59
+ journal: readonly {
60
+ readonly event: string;
61
+ readonly move: string;
62
+ readonly subject: string;
63
+ readonly fields: Readonly<Record<string, unknown>>;
64
+ }[];
65
+ }, never, never>;
66
+ /** Records read from the world's facts: the same rows the server reads, decoded the same way (its column rules, `fromColumns`). */
67
+ export declare const factsRecords: (facts: Facts, tableOf: (thing: Thing) => string | undefined) => Layer.Layer<Records, never, never>;
68
+ /** Whether the declaration's `allowed` lets this caller make this call, judged on the world's facts. */
69
+ export declare const mayCall: (facts: Facts, tableOf: (thing: Thing) => string | undefined, op: Operation | Read, payload: object, principal: Principal, mounts?: ReadonlyMap<unknown, string>) => Effect.Effect<boolean, never, never>;
70
+ export declare const stateOf: (facts: Facts, table: string, id: string) => Effect.Effect<unknown, never, never>;
@@ -0,0 +1,133 @@
1
+ // Talking to a local world over HTTP: cast people, call operations with a trace prefixed by the caller, read facts.
2
+ import { randomBytes } from "node:crypto";
3
+ import { request as httpRequest } from "node:http";
4
+ import { request as httpsRequest } from "node:https";
5
+ import { Effect, Layer, Option, Schema } from "effect";
6
+ import { fromColumns, structOf } from "orthograph/server";
7
+ import { Access, Records } from "@orthograph/language-effect";
8
+ import { PROVE_SPAN_PREFIX } from "#modules/telemetry/types.js";
9
+ const parse = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
10
+ /** Any answer, JSON or not: a body that isn't JSON is kept as text. */
11
+ const fetchJson = (url, init) => Effect.promise(() => fetch(url, init).then((r) => r.text().then((t) => ({ status: r.status, body: Option.getOrElse(parse(t), () => (t === "" ? null : t)) }))));
12
+ /** The world signs `names` up for real; `anonymous` only get an email and a password. */
13
+ export const castPeople = (url, names, anonymous = []) => fetchJson(`${url}/_world/cast`, { method: "POST", body: JSON.stringify({ names, anonymous }) }).pipe(Effect.map((r) => r.body));
14
+ /**
15
+ * A POST from something that is not a browser. Node's `fetch` adds `Sec-Fetch-*` headers, which Better Auth reads as a
16
+ * browser's first login and so demands an `Origin` for; `node:http` sends none, as `curl` doesn't. The transport is chosen by the address's protocol: a deployed Worker is `https`.
17
+ */
18
+ const postJson = (url, body, headers = {}) => Effect.callback((resume) => {
19
+ const text = JSON.stringify(body);
20
+ const req = (url.startsWith("https:") ? httpsRequest : httpRequest)(url, { method: "POST", headers: { "content-type": "application/json", "content-length": Buffer.byteLength(text), ...headers } }, (res) => {
21
+ let received = "";
22
+ res.on("data", (chunk) => (received += chunk.toString()));
23
+ res.on("end", () => resume(Effect.succeed({ status: res.statusCode ?? 0, body: Option.getOrElse(parse(received), () => received) })));
24
+ });
25
+ req.on("error", () => resume(Effect.succeed({ status: 0, body: null })));
26
+ req.end(text);
27
+ });
28
+ const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
29
+ const random = (n) => Array.from(randomBytes(n), (b) => ALPHABET[b % 36]).join("");
30
+ /**
31
+ * A real environment has no `/_world/cast`: its people sign up and sign in through Better Auth's own routes, with an email
32
+ * and password of their own (never `@world.test`'s fixed ones: a person made here stays in the environment). `anonymous`
33
+ * only get credentials, so a script can sign them up itself. A refusal is the problem as text.
34
+ */
35
+ export const signUpPeople = (url, names, anonymous = []) => Effect.gen(function* () {
36
+ const cast = {};
37
+ for (const name of [...names, ...anonymous]) {
38
+ const member = { email: `${name}.${random(8)}@staging.test`, password: random(24) };
39
+ if (anonymous.includes(name)) {
40
+ cast[name] = member;
41
+ continue;
42
+ }
43
+ const post = (route, body) => postJson(`${url}/api/auth/${route}`, body);
44
+ const up = yield* post("sign-up/email", { ...member, name });
45
+ const person = up.body?.user?.id;
46
+ if (up.status !== 200 || typeof person !== "string")
47
+ return yield* Effect.fail(`signing ${name} up answered ${up.status}`);
48
+ const inn = yield* post("sign-in/email", member);
49
+ const token = inn.body?.token;
50
+ if (inn.status !== 200 || typeof token !== "string")
51
+ return yield* Effect.fail(`signing ${name} in answered ${inn.status}`);
52
+ cast[name] = { person, token, ...member };
53
+ }
54
+ return cast;
55
+ });
56
+ /**
57
+ * The credential the world mints for one cast member's way in (`key` or `agent`: an `ak_` key, the second made for an agent), or for
58
+ * the system or a service: none of which a sign-in makes. `undefined` when the world has no such door or will not mint it.
59
+ */
60
+ export const mintCredential = (url, spec) => fetchJson(`${url}/_world/credential`, { method: "POST", body: JSON.stringify(spec) }).pipe(Effect.map((r) => (r.status === 200 ? r.body?.token : undefined)), Effect.map((token) => (typeof token === "string" ? token : undefined)));
61
+ /**
62
+ * A real environment has no `/_world/credential`: a person makes their own key through Better Auth's route, signed in with their session, and
63
+ * marks it for an agent the way a person may (`metadata.acts`). The system and a service have no credential there, so a journey that is one of
64
+ * them runs as no one, which is refused wherever it is refused for being no person.
65
+ */
66
+ export const makeKey = (url, session, forAnAgent) => postJson(`${url}/api/auth/api-key/create`, { name: forAnAgent ? "prove agent" : "prove key", ...(forAnAgent ? { metadata: { acts: "agent" } } : {}) }, { authorization: `Bearer ${session}` }).pipe(Effect.map((r) => (r.status === 200 ? r.body?.key : undefined)), Effect.map((key) => (typeof key === "string" ? key : undefined)));
67
+ /** The tools the MCP door lists for a credential: the wire names, as `{ tools }`; any other answer is kept as it came. */
68
+ export const callTools = (url, token) => Effect.gen(function* () {
69
+ const trace = randomBytes(16).toString("hex");
70
+ const parent = `${PROVE_SPAN_PREFIX}${randomBytes(4).toString("hex")}`;
71
+ const r = yield* fetchJson(`${url}/mcp`, {
72
+ method: "POST",
73
+ headers: {
74
+ "content-type": "application/json", accept: "application/json, text/event-stream", traceparent: `00-${trace}-${parent}-01`,
75
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
76
+ },
77
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
78
+ });
79
+ const listed = r.body?.result?.tools;
80
+ const body = r.status === 200 && Array.isArray(listed) ? { tools: listed.flatMap((t) => (typeof t.name === "string" ? [t.name] : [])) } : r.body;
81
+ return { wire: {}, status: r.status, body, trace, parent, journal: [] };
82
+ });
83
+ /** Encode the payload by its declaration, call the route, and record what came back. */
84
+ /** The world's own front door, `/_world/facts/*`: only a world that hosts its tests has one (D3 #127). */
85
+ export const doorFacts = (url) => {
86
+ const ask = (what, path) => fetchJson(`${url}${path}`).pipe(Effect.flatMap((r) => r.status === 200 && typeof r.body === "object" && r.body !== undefined
87
+ ? Effect.succeed(r.body)
88
+ : Effect.die(new Error(`${url} answered ${r.status} for its ${what}: a deployed Worker closes /_world, so its database must be read with CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID`))));
89
+ return {
90
+ record: (table, id) => ask("facts", `/_world/facts/record?table=${table}&id=${encodeURIComponent(id)}`).pipe(Effect.map((b) => b)),
91
+ journal: (trace) => ask("facts", `/_world/facts/journal?trace=${trace}`).pipe(Effect.map((b) => (Array.isArray(b) ? b : []))),
92
+ };
93
+ };
94
+ export const callOperation = (url, facts, name, op, payload, token, request, startingWorld = false) => Effect.gen(function* () {
95
+ const wire = yield* Schema.encodeUnknownEffect(op.payloadSchema)(payload).pipe(Effect.orElseSucceed(() => payload));
96
+ const trace = randomBytes(16).toString("hex");
97
+ const parent = `${PROVE_SPAN_PREFIX}${randomBytes(4).toString("hex")}`;
98
+ const [thing, verb] = name.split(".");
99
+ const r = yield* fetchJson(`${url}/${thing}/${verb}`, {
100
+ method: "POST",
101
+ headers: {
102
+ "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}), traceparent: `00-${trace}-${parent}-01`,
103
+ ...(request === undefined ? {} : { "idempotency-key": request }),
104
+ ...(startingWorld ? { "x-ortho-starting-world": "1" } : {}),
105
+ },
106
+ // A payload its schema could not encode is sent as it is, with bigints as text (as the wire carries them).
107
+ body: JSON.stringify(wire, (_, v) => (typeof v === "bigint" ? v.toString() : v)),
108
+ });
109
+ const journal = yield* facts.journal(trace);
110
+ return { wire, status: r.status, body: r.body, trace, parent, journal };
111
+ });
112
+ /** Records read from the world's facts: the same rows the server reads, decoded the same way (its column rules, `fromColumns`). */
113
+ export const factsRecords = (facts, tableOf) => Layer.succeed(Records, Records.of({
114
+ find: (thing, id) => Effect.gen(function* () {
115
+ const table = tableOf(thing);
116
+ if (!table)
117
+ return undefined;
118
+ const row = yield* facts.record(table, id);
119
+ if (!row)
120
+ return undefined;
121
+ const fields = yield* Schema.decodeUnknownEffect(structOf(thing.fields))(fromColumns(thing, row)).pipe(Effect.orDie);
122
+ return (typeof row["state"] === "string" ? { ...fields, state: row["state"] } : fields);
123
+ }),
124
+ // A role's rule reads by id only. A lookup by a rule (G5, `findBy(rule, value)`) is a handler's, and a handler
125
+ // runs on the world's own server, where the runtime holds the rules and makes the refusal: it never reaches this stand-in, which reads rows and enforces nothing.
126
+ findBy: () => Effect.die(new Error("prove reads the world's rows by id; a lookup by a rule is a handler's, run by the world's server")),
127
+ list: () => Effect.die(new Error("prove reads the world's rows by id; a list is a handler's, run by the world's server")),
128
+ insert: () => Effect.die(new Error("prove reads the world; it never writes to it")),
129
+ update: () => Effect.die(new Error("prove reads the world; it never writes to it")),
130
+ }));
131
+ /** Whether the declaration's `allowed` lets this caller make this call, judged on the world's facts. */
132
+ export const mayCall = (facts, tableOf, op, payload, principal, mounts) => Access.check({ allowed: op.allowed, payloadFields: op.payload, payload, principal, thing: op.thing, ...(mounts === undefined ? {} : { mounts }) }).pipe(Effect.as(true), Effect.catchTag("NotAllowed", () => Effect.succeed(false)), Effect.provide(factsRecords(facts, tableOf)));
133
+ export const stateOf = (facts, table, id) => facts.record(table, id).pipe(Effect.map((row) => row?.["state"]));
@@ -0,0 +1,2 @@
1
+ import type { JourneysApi } from "./types.ts";
2
+ export declare const Journeys: JourneysApi;