@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,12 @@
1
+ import { digest } from "./digest.ts";
2
+ export interface Snapshot {
3
+ readonly root: string;
4
+ readonly hashes: Map<string, string>;
5
+ readonly sources: Map<string, string>;
6
+ }
7
+ export { digest };
8
+ /** What a workspace's lockfile is called in the record: the same wherever the project sits. */
9
+ export declare const WORKSPACE = "<workspace>";
10
+ export declare const scan: (root: string) => Snapshot;
11
+ /** A file of the project outside the folders above that something imports: it is read in, so a change to it is seen. */
12
+ export declare const include: (snap: Snapshot, path: string) => boolean;
@@ -0,0 +1,66 @@
1
+ // One reading of the project's files: a content hash by relative path, and the source of each code file, taken once so that
2
+ // what a proof is recorded against is what was read when it began, never what is on disk when it ends.
3
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { digest } from "./digest.js";
6
+ import { linkedFiles } from "./linked.js";
7
+ export { digest };
8
+ /** Folders whose every file can change a proof. generated/ is in: the server and the model are made there, and a change to either is not a thing the model places. */
9
+ const FOLDERS = ["blueprint", "src", "journeys", "generated"];
10
+ const CODE = /\.[cm]?[jt]sx?$/;
11
+ /** A test cannot reach a running world; a note can only where code may read it (src/, blueprint/). */
12
+ const quiet = (path) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(path) || (path.endsWith(".md") && !path.startsWith("src/") && !path.startsWith("blueprint/"));
13
+ const rootFile = (name) => name === "ortho.config.ts" || name === "package.json" || name === "pnpm-lock.yaml" || /^tsconfig.*\.json$/.test(name) || name === ".env" || name.startsWith(".env.");
14
+ const LOCKS = ["pnpm-lock.yaml", "pnpm-workspace.yaml", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "bun.lock", "bun.lockb"];
15
+ /** What a workspace's lockfile is called in the record: the same wherever the project sits. */
16
+ export const WORKSPACE = "<workspace>";
17
+ const within = (root, folder) => readdirSync(join(root, folder), { withFileTypes: true }).flatMap((entry) => {
18
+ if (entry.name.startsWith(".") || entry.name === "node_modules")
19
+ return [];
20
+ const path = `${folder}/${entry.name}`;
21
+ if (entry.isDirectory())
22
+ return within(root, path);
23
+ return entry.isFile() && !quiet(path) ? [path] : [];
24
+ });
25
+ /** The nearest folder above the project that holds a lockfile: the workspace the project's dependencies are locked in. */
26
+ const workspaceOf = (root) => {
27
+ for (let dir = dirname(root); dir !== dirname(dir); dir = dirname(dir))
28
+ if (LOCKS.some((name) => existsSync(join(dir, name))))
29
+ return dir;
30
+ return undefined;
31
+ };
32
+ /** Read one file into the snapshot under `path`, from `from`. */
33
+ const take = (snap, path, from) => {
34
+ const bytes = readFileSync(from);
35
+ snap.hashes.set(path, digest(bytes));
36
+ if (CODE.test(path) || /(^|\/)tsconfig[^/]*\.json$/.test(path))
37
+ snap.sources.set(path, bytes.toString("utf8"));
38
+ };
39
+ export const scan = (root) => {
40
+ const snap = { root, hashes: new Map(), sources: new Map() };
41
+ const paths = [
42
+ ...FOLDERS.filter((folder) => existsSync(join(root, folder))).flatMap((folder) => within(root, folder)),
43
+ ...readdirSync(root, { withFileTypes: true }).filter((e) => e.isFile() && rootFile(e.name)).map((e) => e.name),
44
+ ].sort();
45
+ for (const path of paths)
46
+ take(snap, path, join(root, path));
47
+ const workspace = workspaceOf(root);
48
+ if (workspace !== undefined)
49
+ for (const name of LOCKS)
50
+ if (existsSync(join(workspace, name)))
51
+ take(snap, `${WORKSPACE}/${name}`, join(workspace, name));
52
+ // Packages linked from source (workspace siblings, `link:`, `file:`) are not in any lockfile's hashes: their files are, unplaceable.
53
+ for (const [key, hash] of linkedFiles(root, workspace))
54
+ snap.hashes.set(key, hash);
55
+ return snap;
56
+ };
57
+ /** A file of the project outside the folders above that something imports: it is read in, so a change to it is seen. */
58
+ export const include = (snap, path) => {
59
+ if (snap.hashes.has(path))
60
+ return true;
61
+ const file = join(snap.root, path);
62
+ if (!existsSync(file) || !statSync(file).isFile())
63
+ return false;
64
+ take(snap, path, file);
65
+ return true;
66
+ };
@@ -0,0 +1,2 @@
1
+ import type { ImpactApi } from "./types.ts";
2
+ export declare const Impact: ImpactApi;
@@ -0,0 +1,88 @@
1
+ import { existsSync } from "node:fs";
2
+ import { Names } from "orthograph/server";
3
+ import { Effect } from "effect";
4
+ import { Compare } from "@orthograph/compiler";
5
+ import { evidenceHolds, modelHash, storyHash } from "#modules/verdicts/internal/proof.js";
6
+ import { ledgerPath, readLedger, writeLedger } from "./internal/ledger.js";
7
+ import { select as selectChanged, settle as settleChanged } from "./internal/changed.js";
8
+ import { stampOf } from "./internal/files.js";
9
+ const holds = (model, depends) => Object.entries(depends).every(([key, hash]) => Compare.hashOf(model, key) === hash);
10
+ const record = (root, model, verdicts, results) => Effect.sync(() => {
11
+ const prior = readLedger(root);
12
+ const before = prior?.proven ?? {};
13
+ const hash = results === undefined ? undefined : modelHash(model);
14
+ const proofs = new Map(results?.map(({ operation, journeys }) => [operation, { storyHash: storyHash(model, operation, (journeys ?? []).map((v) => v.journey)), journeys: journeys ?? [] }]));
15
+ // Still proven from before, unless this run judged it.
16
+ const kept = Object.entries(before).filter(([op, depends]) => {
17
+ const evidence = prior?.verdicts?.[op];
18
+ return holds(model, depends) && !verdicts.some((v) => v.operation === op)
19
+ && (evidence === undefined || evidenceHolds(root, model, op, evidence.storyHash, evidence.journeys));
20
+ });
21
+ const passed = Object.keys(model.operations).filter((op) => {
22
+ const mine = verdicts.filter((v) => v.operation === op);
23
+ const evidence = proofs.get(op);
24
+ return mine.length > 0 && mine.every((v) => v.failures.length === 0)
25
+ && (evidence === undefined || (evidence.journeys.every((v) => v.modelHash === hash) && evidenceHolds(root, model, op, evidence.storyHash, evidence.journeys)));
26
+ });
27
+ const proven = Object.fromEntries([...kept, ...passed.map((op) => [op, Compare.dependsOn(model, op)])].sort(([a], [b]) => a.localeCompare(b)));
28
+ for (const [op] of kept) {
29
+ const evidence = prior?.verdicts?.[op];
30
+ if (evidence)
31
+ proofs.set(op, evidence);
32
+ }
33
+ writeLedger(root, { model, proven, ...(proofs.size === 0 ? {} : { verdicts: Object.fromEntries(proofs) }), ...(prior?.changed ? { changed: prior.changed } : {}) });
34
+ });
35
+ const stamp = (root, model) => Effect.sync(() => stampOf(root, model));
36
+ const select = (root, model, taken) => Effect.sync(() => {
37
+ const prior = readLedger(root)?.changed;
38
+ return selectChanged(taken, model, prior, existsSync(ledgerPath(root)) && prior === undefined ? `no record of an earlier prove (${Names.folder}/evidence/proven.json holds none that can be read)` : undefined);
39
+ });
40
+ const settle = (root, model, ran, taken) => Effect.sync(() => {
41
+ const ledger = readLedger(root);
42
+ if (ledger !== undefined)
43
+ writeLedger(root, { ...ledger, changed: settleChanged(taken, ledger.changed, ran) });
44
+ });
45
+ const of = (root, model) => Effect.sync(() => {
46
+ const ledger = readLedger(root);
47
+ const ops = Object.keys(model.operations);
48
+ const proven = ledger?.proven ?? {};
49
+ const stale = Object.keys(proven).filter((op) => {
50
+ const evidence = ledger?.verdicts?.[op];
51
+ return op in model.operations && (!holds(model, proven[op]) || (evidence !== undefined && !evidenceHolds(root, model, op, evidence.storyHash, evidence.journeys)));
52
+ });
53
+ const edges = Compare.edges(model);
54
+ return {
55
+ ...(edges.length > 0 ? { edges } : {}),
56
+ changes: ledger ? Compare.models(ledger.model, model) : [],
57
+ stale,
58
+ proven: ops.filter((op) => op in proven && !stale.includes(op)),
59
+ unproven: ops.filter((op) => !(op in proven)),
60
+ };
61
+ });
62
+ const list = (names) => (names.length === 0 ? "none" : names.join(", "));
63
+ const staleLine = (shipped) => shipped.stale.length === 0
64
+ ? "stale none"
65
+ : `stale ${list(shipped.stale.map((s) => s.operation))} in ${list([...new Set(shipped.stale.flatMap((s) => s.environments))])}`;
66
+ const line = (c) => `${c.kind} ${c.what} ${c.bump}${c.detail ? ` (${c.detail})` : ""}`;
67
+ /** What the logbook says, with the local ledger only for what it alone knows: the declarations and what is stale on this machine. */
68
+ const shippedLines = (impact, shipped) => {
69
+ const stale = new Set(shipped.stale.map((s) => s.operation));
70
+ const everything = [...impact.proven, ...impact.stale, ...impact.unproven].sort();
71
+ return [
72
+ ...(shipped.from === null ? [] : [`changes since ${shipped.from}`, ...shipped.changes.map(line)]),
73
+ `next ${shipped.version}`,
74
+ staleLine(shipped),
75
+ ...(impact.stale.length > 0 ? [`locally stale ${list(impact.stale)}`] : []),
76
+ `proven ${list(shipped.proven)}`,
77
+ ...(everything.some((op) => !shipped.proven.includes(op) && !stale.has(op)) ? [`unproven ${list(everything.filter((op) => !shipped.proven.includes(op) && !stale.has(op)))}`] : []),
78
+ ];
79
+ };
80
+ const lines = (impact, shipped) => [...(impact.edges ?? []), ...(shipped
81
+ ? shippedLines(impact, shipped)
82
+ : [
83
+ ...impact.changes.map((c) => `${c.change} ${c.kind} ${c.name}${c.parts.length ? `: ${c.parts.join(", ")}` : ""}`),
84
+ `stale ${list(impact.stale)}`,
85
+ `proven ${list(impact.proven)}`,
86
+ ...(impact.unproven.length > 0 ? [`unproven ${list(impact.unproven)}`] : []),
87
+ ])];
88
+ export const Impact = { record, stamp, select, settle, of, lines };
@@ -0,0 +1,109 @@
1
+ import type { Effect } from "effect";
2
+ import type { Change, Depends, Model, Versioned } from "@orthograph/compiler";
3
+ import type { JourneyVerdict, Result } from "#modules/verdicts/types.js";
4
+ import type { Verdict } from "#modules/evals/types.js";
5
+ /** `.ortho/evidence/proven.json`: the model last proven, and each proven operation's dependencies then. */
6
+ export interface Ledger {
7
+ readonly model: Model;
8
+ readonly proven: Readonly<Record<string, Depends>>;
9
+ readonly verdicts?: Readonly<Record<string, {
10
+ readonly storyHash: string;
11
+ readonly journeys: ReadonlyArray<JourneyVerdict>;
12
+ }>>;
13
+ /** What `prove --changed` measures from: see `Proof`. */
14
+ readonly changed?: Proof;
15
+ }
16
+ /** What a journey or an operation rested on when it was last judged, and whether it passed. */
17
+ export interface Judged {
18
+ readonly inputs: string;
19
+ readonly passed: boolean;
20
+ }
21
+ /**
22
+ * The record of the last proof that `prove --changed` reads: a content hash, by relative path, of every file that can
23
+ * change a proof (blueprint/, src/, journeys/, the config, package.json, the lockfile, tsconfig, .env), and per journey
24
+ * and per operation the hash of the files it rests on with its last verdict.
25
+ */
26
+ export interface Proof {
27
+ readonly files: Readonly<Record<string, string>>;
28
+ readonly journeys: Readonly<Record<string, Judged>>;
29
+ readonly operations: Readonly<Record<string, Judged>>;
30
+ }
31
+ /**
32
+ * What a proof rests on, read once when the run begins: a hash of every file that can change a proof, the files the model
33
+ * places (reached by importing from an operation, a journey or a starting world), and each operation's and journey's inputs.
34
+ */
35
+ export interface Stamp {
36
+ readonly files: Readonly<Record<string, string>>;
37
+ readonly placed: ReadonlySet<string>;
38
+ readonly operations: Readonly<Record<string, string>>;
39
+ /** By the journey's file (names may repeat). */
40
+ readonly journeys: Readonly<Record<string, string>>;
41
+ }
42
+ /** What `prove --changed` will do, from the record and today's files. */
43
+ export interface Selection {
44
+ /** The journeys to run, by file (the key of `model.journeys`: names may repeat). */
45
+ readonly rerun: ReadonlyArray<string>;
46
+ readonly skipped: ReadonlyArray<string>;
47
+ /** The operations whose evals are judged again. */
48
+ readonly judge: ReadonlyArray<string>;
49
+ /** Set when it could not tell: every journey and every operation is then in `rerun` and `judge`. */
50
+ readonly fellBack: null | {
51
+ readonly reason: string;
52
+ readonly files: ReadonlyArray<string>;
53
+ };
54
+ }
55
+ /** What a run judged: each journey it ran and each operation whose evals it judged. */
56
+ export interface Ran {
57
+ readonly journeys: ReadonlyArray<{
58
+ readonly file: string;
59
+ readonly passed: boolean;
60
+ }>;
61
+ readonly operations: ReadonlyArray<{
62
+ readonly operation: string;
63
+ readonly passed: boolean;
64
+ }>;
65
+ }
66
+ export interface Impact {
67
+ /** What each mount provides and needs, printed first (M1-plugins section 7). */
68
+ readonly edges?: ReadonlyArray<string>;
69
+ /** What changed since the ledger's model. */
70
+ readonly changes: ReadonlyArray<Change>;
71
+ /** Proven once, but something its proof rests on has changed since. */
72
+ readonly stale: ReadonlyArray<string>;
73
+ /** Proven, and nothing it rests on has changed. */
74
+ readonly proven: ReadonlyArray<string>;
75
+ /** Never proven: new, or failing when last proven. */
76
+ readonly unproven: ReadonlyArray<string>;
77
+ }
78
+ /** What the logbook adds: the changes since the last release, the version they make, and what is proven and stale in staging and production. */
79
+ export interface Shipped {
80
+ /** The last production release's version, or null when there is none. */
81
+ readonly from: string | null;
82
+ readonly version: string;
83
+ readonly changes: ReadonlyArray<Versioned>;
84
+ readonly proven: ReadonlyArray<string>;
85
+ readonly stale: ReadonlyArray<{
86
+ readonly operation: string;
87
+ readonly environments: ReadonlyArray<string>;
88
+ }>;
89
+ }
90
+ export interface ImpactApi {
91
+ /** After a prove: operations whose evals all passed become proven at today's hashes; failing ones are dropped. */
92
+ readonly record: (root: string, model: Model, verdicts: ReadonlyArray<Verdict>, results?: ReadonlyArray<Result>) => Effect.Effect<void>;
93
+ /** Read what a proof rests on, once, before a run: `select` and `settle` both take it, so what is recorded is what the run began with. */
94
+ readonly stamp: (root: string, model: Model) => Effect.Effect<Stamp>;
95
+ /** Which journeys and evals `prove --changed` runs: what changed since the last proof's record, or everything with the reason. */
96
+ readonly select: (root: string, model: Model, stamp: Stamp) => Effect.Effect<Selection>;
97
+ /** After a prove: the record `--changed` measures from, with what the run judged as it judged it and the rest as it was. */
98
+ readonly settle: (root: string, model: Model, ran: Ran, stamp: Stamp) => Effect.Effect<void>;
99
+ /** Today's model against the ledger. With no ledger every operation is unproven. */
100
+ readonly of: (root: string, model: Model) => Effect.Effect<Impact>;
101
+ /**
102
+ * `changed operation allowance.spend: budget`, then `stale …`, `proven …` and `unproven …`, from the local ledger.
103
+ * With the logbook's word (`shipped`) it is the release's that is printed instead: `changes since 1.0.0` and a line per
104
+ * change (`added allowance.list minor`), `next <version>`, `stale <ops> in <envs>` (or `stale none`), `proven …`, and
105
+ * `unproven …` for what no shipped environment has a passing `main` verdict for. What the local ledger finds stale is
106
+ * then `locally stale …`, and only when there is some.
107
+ */
108
+ readonly lines: (impact: Impact, shipped?: Shipped) => ReadonlyArray<string>;
109
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,25 @@
1
+ import { Effect } from "effect";
2
+ import type { Assertion, Thing } from "orthograph";
3
+ import type { CallRecord, Facts } from "../types.ts";
4
+ /** Values as they travel: bigints as text, so `500n` and `"500"` compare equal. A value that holds itself reads `"[Circular]"` where it loops back. */
5
+ export declare const wireOf: (v: unknown, above?: ReadonlyArray<object>) => unknown;
6
+ export declare const show: (v: unknown) => string;
7
+ export declare const tagOfClass: (cls: unknown) => string;
8
+ /** One failed check: the sentence prove prints, and the two halves of it when it has them. */
9
+ export interface Finding {
10
+ readonly message: string;
11
+ readonly expected?: string;
12
+ readonly got?: string;
13
+ }
14
+ export declare const runChecks: (checks: ReadonlyArray<Assertion>, call: CallRecord, env: Readonly<Record<string, unknown>>, world: {
15
+ readonly facts: Facts;
16
+ readonly tableOf: (thing: Thing) => string | undefined;
17
+ readonly nameOf?: (operation: unknown) => string | undefined;
18
+ }) => Effect.Effect<{
19
+ failures: string[];
20
+ findings: Finding[];
21
+ spans: {
22
+ present: string[];
23
+ absent: string[];
24
+ };
25
+ }, never, never>;
@@ -0,0 +1,155 @@
1
+ // A step's checks against what its call got back and what the world now holds. Span checks wait for telemetry.
2
+ import { Effect } from "effect";
3
+ import { ErrorNames, EventNames, Scripting } from "orthograph/server";
4
+ import { stateOf } from "./world.js";
5
+ /** Values as they travel: bigints as text, so `500n` and `"500"` compare equal. A value that holds itself reads `"[Circular]"` where it loops back. */
6
+ export const wireOf = (v, above = []) => {
7
+ if (typeof v === "bigint")
8
+ return v.toString();
9
+ if (typeof v !== "object" || v === null)
10
+ return v;
11
+ if (above.includes(v))
12
+ return "[Circular]";
13
+ const path = [...above, v];
14
+ return Array.isArray(v) ? v.map((x) => wireOf(x, path)) : Object.fromEntries(Object.entries(v).map(([k, x]) => [k, wireOf(x, path)]));
15
+ };
16
+ export const show = (v) => JSON.stringify(wireOf(v));
17
+ export const tagOfClass = (cls) => ErrorNames.nameOf(cls) ?? String((new cls({}))._tag);
18
+ const pascal = (name) => name.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
19
+ /**
20
+ * A machine's first declared state, whichever shape `states` has. Today `states` is the declared array; ST1.14 (G5 section 1) makes it a record of state references and keeps the
21
+ * array as `declared`. This reads both, so the builder of ST1.14 does not touch this protected file. Once the record has landed it can read `declared[0]` alone.
22
+ */
23
+ const firstStateOf = (machine) => {
24
+ const shape = machine;
25
+ const declared = shape.declared ?? (Array.isArray(shape.states) ? shape.states : Object.keys((shape.states ?? {})));
26
+ return declared[0] ?? "";
27
+ };
28
+ /**
29
+ * A refusal check's tag: a declared error's class name, `<Thing>Not<FirstState>` for a machine's own refusal, or
30
+ * `<Thing>NotFound` for a missing instance (a thing's declared error of that name is the same tag, K16 M1.46).
31
+ */
32
+ const tagOfRefusal = (error, tableOf) => {
33
+ if (error.kind === "not-found")
34
+ return `${pascal(tableOf(error.thing) ?? "?")}NotFound`;
35
+ if (error.kind !== "not-from")
36
+ return tagOfClass(error);
37
+ const machine = error.machine;
38
+ return `${pascal(tableOf(machine.thing) ?? "?")}Not${pascal(firstStateOf(machine))}`;
39
+ };
40
+ const subset = (want, got) => typeof got === "object" && got !== null && Object.entries(want).every(([k, v]) => show(v) === show(got[k]));
41
+ /**
42
+ * Journey code (a `pick`, a refusal's class, a machine) runs inside `Effect.try`: a throw is the step's failure, with the error's name and message,
43
+ * and never a defect that ends the run (S-27).
44
+ */
45
+ const attempt = (f) => Effect.try({ try: f, catch: (e) => (e instanceof Error ? `${e.name}: ${e.message}` : String(e)) }).pipe(Effect.match({ onFailure: (threw) => ({ threw }), onSuccess: (value) => ({ value }) }));
46
+ /** The answer's top-level keys and never its values: an answer may hold a token, and the report is kept and shared. */
47
+ const keysOf = (answer) => typeof answer === "object" && answer !== null && !Array.isArray(answer) ? `keys [${Object.keys(answer).join(", ")}]` : `no keys (${Array.isArray(answer) ? "a list" : typeof answer})`;
48
+ /** What prove says of a check that threw: where, which keys the answer had and what the error said. No stack, no answer values. */
49
+ const threwMessage = (call, env, threw) => `journey "${call.journey}" step "${call.step}": a check threw on an answer with ${keysOf(env["last"])}: ${threw}`;
50
+ export const runChecks = (checks, call, env, world) => Effect.gen(function* () {
51
+ const failures = [];
52
+ // The same failures with what was expected and what came back, for prove's structured report.
53
+ const findings = [];
54
+ const bad = (message, expected, got) => {
55
+ failures.push(message);
56
+ findings.push({ message, ...(expected === undefined ? {} : { expected }), ...(got === undefined ? {} : { got }) });
57
+ };
58
+ const refused = typeof call.body === "object" && call.body !== null && call.status >= 400 ? call.body._tag : undefined;
59
+ const said = call.status === 200 ? "answered" : refused ? `refused with ${refused}` : `failed with ${call.status}`;
60
+ for (const c of checks) {
61
+ // Only the values inside a check are refs; the declarations it names must stay the very objects they are.
62
+ const refs = c.kind === "emits" || c.kind === "refuses" ? c.fields : c.kind === "is-in" ? c.id : undefined;
63
+ const resolved = Scripting.resolve(refs, env);
64
+ if (resolved.missing.length > 0) {
65
+ bad(`${c.kind}: nothing at ${resolved.missing.join(", ")}`);
66
+ continue;
67
+ }
68
+ const check = (c.kind === "emits" || c.kind === "refuses" ? { ...c, fields: resolved.value } : c.kind === "is-in" ? { ...c, id: resolved.value } : c);
69
+ if (check.kind === "expect") {
70
+ if (call.status !== 200)
71
+ bad(`expected an answer, ${said}`, "an answer", said);
72
+ else {
73
+ const tried = yield* attempt(() => check.pick(env["last"]));
74
+ if ("threw" in tried) {
75
+ bad(threwMessage(call, env, tried.threw));
76
+ continue;
77
+ }
78
+ const picked = tried.value;
79
+ if (!check.match.test(String(wireOf(picked))))
80
+ bad(`answer ${show(picked)} doesn't match ${check.match}`, String(check.match), show(picked));
81
+ }
82
+ }
83
+ else if (check.kind === "expect-equal") {
84
+ if (call.status !== 200)
85
+ bad(`expected an answer, ${said}`, "an answer", said);
86
+ else {
87
+ const tried = yield* attempt(() => check.pick(env["last"]));
88
+ if ("threw" in tried) {
89
+ bad(threwMessage(call, env, tried.threw));
90
+ continue;
91
+ }
92
+ const picked = tried.value;
93
+ // The expected value may name the script (`s.olga.person`): it means what the run gave it.
94
+ const value = Scripting.resolve(check.value, env).value;
95
+ if (show(picked) !== show(value))
96
+ bad(`answer ${show(picked)}, expected ${show(value)}`, show(value), show(picked));
97
+ }
98
+ }
99
+ else if (check.kind === "refuses") {
100
+ const named = yield* attempt(() => tagOfRefusal(check.error, world.tableOf));
101
+ if ("threw" in named) {
102
+ bad(`journey "${call.journey}" step "${call.step}": the refusal named in refuses() threw: ${named.threw}`);
103
+ continue;
104
+ }
105
+ const tag = named.value;
106
+ if (refused !== tag)
107
+ bad(`expected refused with ${tag}, ${said}`, `refused with ${tag}`, said);
108
+ else if (!subset(check.fields, call.body))
109
+ bad(`refused with ${tag} ${show(call.body)}, expected ${show(check.fields)}`, show(check.fields), show(call.body));
110
+ }
111
+ else if (check.kind === "emits") {
112
+ const name = EventNames.nameOf(check.event) ?? "?";
113
+ const found = call.journal.find((e) => e.event === name);
114
+ if (!found)
115
+ bad(`expected ${name}, journal has ${call.journal.map((e) => e.event).join(", ") || "nothing"}`, name, call.journal.map((e) => e.event).join(", ") || "nothing");
116
+ else if (!subset(check.fields, found.fields))
117
+ bad(`${name} ${show(found.fields)}, expected ${show(check.fields)}`, show(check.fields), show(found.fields));
118
+ }
119
+ else if (check.kind === "no-events") {
120
+ if (call.journal.length > 0)
121
+ bad(`expected no events, journal has ${call.journal.map((e) => e.event).join(", ")}`, "no events", call.journal.map((e) => e.event).join(", "));
122
+ }
123
+ else if (check.kind === "lacks" || check.kind === "has") {
124
+ // `lacks(...operations)` and `has(...operations)` on a `.tools()` call (M2.02, M2-auth fork 2): none of these is a tool, or all of them are. Neither can
125
+ // pass by saying nothing: the call must have answered a tools list, it must name at least one operation, and every operation it names must be one the project declares.
126
+ const verb = check.kind;
127
+ const asked = check.operations;
128
+ const listed = call.body?.tools;
129
+ const names = asked.map((op) => world.nameOf?.(op));
130
+ if (call.status !== 200 || !Array.isArray(listed))
131
+ bad(`expected a tools list, ${said}`, "a tools list", said);
132
+ else if (asked.length === 0)
133
+ bad(`${verb} names no operation`, "at least one operation", "none");
134
+ else if (names.some((n) => n === undefined))
135
+ bad(`${verb} names an operation the project does not declare`, "declared operations", `${names.filter((n) => n === undefined).length} undeclared`);
136
+ else {
137
+ const declared = names.filter((n) => n !== undefined);
138
+ const held = declared.filter((n) => listed.includes(n));
139
+ if (verb === "lacks" && held.length > 0)
140
+ bad(`tools list holds ${held.join(", ")}`, "none of them", held.join(", "));
141
+ const missing = declared.filter((n) => !held.includes(n));
142
+ if (verb === "has" && missing.length > 0)
143
+ bad(`tools list lacks ${missing.join(", ")}`, "all of them", missing.join(", "));
144
+ }
145
+ }
146
+ else if (check.kind === "is-in") {
147
+ const table = world.tableOf(check.thing);
148
+ const state = table ? yield* stateOf(world.facts, table, String(check.id)) : undefined;
149
+ if (state !== check.state)
150
+ bad(`${String(check.id)} is in ${state === undefined || state === null ? "no state" : `"${String(state)}"`}, expected "${check.state}"`, `"${check.state}"`, state === undefined || state === null ? "no state" : `"${String(state)}"`);
151
+ }
152
+ }
153
+ const spans = checks.filter((c) => c.kind === "spans");
154
+ return { failures, findings, spans: { present: spans.flatMap((c) => c.present), absent: spans.flatMap((c) => c.absent) } };
155
+ });
@@ -0,0 +1,10 @@
1
+ import type { Facts } from "../types.ts";
2
+ export interface D1Access {
3
+ readonly token: string;
4
+ readonly account: string;
5
+ /** Whether a database's name belongs to the run: the staging plan's own test of its prefix. */
6
+ readonly owns: (name: string) => boolean;
7
+ /** The API's base address; a test stands a local server in for Cloudflare. */
8
+ readonly api?: string;
9
+ }
10
+ export declare const d1Facts: ({ token, account, owns, api }: D1Access) => Facts;
@@ -0,0 +1,53 @@
1
+ // The facts of a deployed environment, read from its D1 databases through Cloudflare's query API with the operator's own credential (D3 #127, "the cloud pass").
2
+ // The databases are the ones the run's prefix owns, found by name, never by a typed id. Neither the token nor the account id is printed: every message cut from an answer
3
+ // has both replaced first.
4
+ import { Effect, Option, Schema } from "effect";
5
+ const parse = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
6
+ const NAME = /^[A-Za-z][A-Za-z0-9_-]*$/;
7
+ const API = "https://api.cloudflare.com/client/v4";
8
+ const PAGE = 100;
9
+ const PAGES_MAX = 50;
10
+ export const d1Facts = ({ token, account, owns, api = API }) => {
11
+ const redact = (text) => text.split(token).join("[token]").split(account).join("[account]").slice(0, 200);
12
+ const call = (method, path, body) => Effect.promise(() => fetch(`${api}/accounts/${account}${path}`, { method, headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) })
13
+ .then((r) => r.text().then((t) => ({ status: r.status, text: t })), (e) => ({ status: 0, text: String(e) }))).pipe(Effect.flatMap((r) => {
14
+ const parsed = Option.getOrUndefined(parse(r.text));
15
+ return parsed?.success === true
16
+ ? Effect.succeed(parsed.result)
17
+ : Effect.fail(redact(parsed?.errors?.map((e) => e.message ?? "").join("; ") || r.text || `no answer (${r.status})`));
18
+ }));
19
+ const die = (what) => (why) => Effect.die(new Error(`reading ${what} from D1 failed: ${why}`));
20
+ /** Every page of the account's databases: a shared account holds more than one page, and a database past the first must still be found. */
21
+ const databases = Effect.gen(function* () {
22
+ const owned = [];
23
+ for (let page = 1; page <= PAGES_MAX; page += 1) {
24
+ const r = yield* call("GET", `/d1/database?per_page=${PAGE}&page=${page}`);
25
+ const listed = Array.isArray(r) ? r : [];
26
+ for (const d of listed)
27
+ if (typeof d.uuid === "string" && typeof d.name === "string" && owns(d.name))
28
+ owned.push(d.uuid);
29
+ if (listed.length < PAGE)
30
+ return owned;
31
+ }
32
+ return yield* Effect.fail(`more than ${PAGE * PAGES_MAX} databases listed`);
33
+ }).pipe(Effect.catch(die("the databases")));
34
+ /** Every row `sql` returns in each of the run's databases; one without the table has none. */
35
+ const rows = (sql, params) => Effect.gen(function* () {
36
+ const found = [];
37
+ for (const id of yield* databases) {
38
+ const result = yield* call("POST", `/d1/database/${id}/query`, { sql, params }).pipe(Effect.catch((why) => (/no such table/i.test(why) ? Effect.succeed([]) : die("a row")(why))));
39
+ for (const part of Array.isArray(result) ? result : [])
40
+ found.push(...(part.results ?? []));
41
+ }
42
+ return found;
43
+ });
44
+ return {
45
+ record: (table, id) => (NAME.test(table) ? rows(`SELECT * FROM "${table}" WHERE "id" = ?`, [id]).pipe(Effect.map((r) => r[0] ?? null)) : Effect.succeed(null)),
46
+ journal: (trace) => rows(`SELECT * FROM "_journal" WHERE "trace" = ? ORDER BY "seq"`, [trace]).pipe(
47
+ // One trace's rows can sit in several of the run's databases; together they keep the journal's own order.
48
+ Effect.map((r) => [...r].sort((a, b) => Number(a["seq"]) - Number(b["seq"]))), Effect.flatMap((r) => Effect.forEach(r, (row) => Option.match(parse(String(row["fields"])), {
49
+ onNone: () => die("a journal row")(`its fields are not JSON (seq ${String(row["seq"])})`),
50
+ onSome: (fields) => Effect.succeed({ ...row, fields }),
51
+ }))), Effect.map((r) => r)),
52
+ };
53
+ };
@@ -0,0 +1,2 @@
1
+ import type { Facts } from "../types.ts";
2
+ export declare const databaseFacts: (state: string) => Facts;
@@ -0,0 +1,41 @@
1
+ // The facts of an environment that has closed `/_world/*` (staging, D3 #127): read from its database, never through the
2
+ // Worker. The environment's state folder holds D1's SQLite file; it is opened read-only for each read, so every read sees what
3
+ // the Worker last committed. In the cloud pass the same two reads go to D1's own API with the operator's credential.
4
+ import { existsSync, readdirSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { DatabaseSync } from "node:sqlite";
7
+ import { Effect } from "effect";
8
+ const D1_DIR = "v3/d1/miniflare-D1DatabaseObject";
9
+ const NAME = /^[A-Za-z][A-Za-z0-9_-]*$/;
10
+ /** D1's database file in the state folder: the one SQLite file that holds the journal. */
11
+ const databaseIn = (state) => {
12
+ const dir = join(state, D1_DIR);
13
+ if (!existsSync(dir))
14
+ return undefined;
15
+ return readdirSync(dir).filter((f) => f.endsWith(".sqlite") && f !== "metadata.sqlite").map((f) => join(dir, f)).find((file) => {
16
+ const db = new DatabaseSync(file, { readOnly: true });
17
+ try {
18
+ return db.prepare(`SELECT 1 FROM sqlite_master WHERE name = '_journal'`).get() !== undefined;
19
+ }
20
+ finally {
21
+ db.close();
22
+ }
23
+ });
24
+ };
25
+ const read = (state, query) => {
26
+ const file = databaseIn(state);
27
+ if (file === undefined)
28
+ throw new Error(`no D1 database in ${state}`);
29
+ const db = new DatabaseSync(file, { readOnly: true });
30
+ try {
31
+ return query(db);
32
+ }
33
+ finally {
34
+ db.close();
35
+ }
36
+ };
37
+ export const databaseFacts = (state) => ({
38
+ record: (table, id) => Effect.sync(() => (NAME.test(table) ? read(state, (db) => db.prepare(`SELECT * FROM "${table}" WHERE "id" = ?`).get(id)) ?? null : null)),
39
+ journal: (trace) => Effect.sync(() => read(state, (db) => db.prepare(`SELECT * FROM "_journal" WHERE "trace" = ? ORDER BY "seq"`).all(trace))
40
+ .map((r) => ({ ...r, fields: JSON.parse(r.fields) }))),
41
+ });
@@ -0,0 +1,16 @@
1
+ import { Effect } from "effect";
2
+ import type { Operation, Read } from "orthograph";
3
+ import { type OperationModel } from "@orthograph/compiler";
4
+ import type { DeviceHost, Project } from "../types.ts";
5
+ /** Whether this operation runs on a device, and so is called here rather than on the world's server. */
6
+ export declare const onDevice: (op: OperationModel | undefined) => op is OperationModel & {
7
+ readonly runs: "client";
8
+ };
9
+ export declare const callDevice: (project: Project, host: DeviceHost, name: string, declaration: Operation | Read, payload: Record<string, unknown>) => Effect.Effect<{
10
+ wire: Record<string, unknown>;
11
+ trace: string;
12
+ parent: string;
13
+ journal: readonly [];
14
+ status: number;
15
+ body: unknown;
16
+ }, never, never>;