@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,76 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { Effect, Option } from "effect";
4
+ import { Names } from "orthograph/server";
5
+ import { WarmFailed } from "./types.js";
6
+ import { fingerprint, newestChange } from "./internal/source.js";
7
+ const fileOf = (root) => resolve(root, Names.folder, "dev.json");
8
+ const alive = (pid) => Effect.try({ try: () => process.kill(pid, 0), catch: () => "gone" }).pipe(Effect.match({ onFailure: () => false, onSuccess: () => true }));
9
+ /** The world at `url` answers, and says this nonce: it is the world `ortho dev` made, not whatever took its port or its pid. */
10
+ const answers = (url, nonce) => Effect.tryPromise({ try: () => fetch(`${url}/_world/health`).then((r) => (r.ok ? r.json() : {})), catch: () => "silent" }).pipe(Effect.match({ onFailure: () => false, onSuccess: (body) => body.nonce === nonce }));
11
+ const isRecord = (x) => {
12
+ const r = x;
13
+ return typeof r === "object" && r !== null && typeof r.pid === "number" && typeof r.url === "string" && typeof r.collector === "string" && typeof r.telemetry === "string" && typeof r.startedAt === "number" && typeof r.sources === "string" && typeof r.nonce === "string";
14
+ };
15
+ const read = (root) => Effect.try({ try: () => JSON.parse(readFileSync(fileOf(root), "utf8")), catch: () => "unreadable" }).pipe(Effect.map((x) => (isRecord(x) ? Option.some(x) : Option.none())), Effect.orElseSucceed(() => Option.none()));
16
+ const lockOf = (root) => resolve(root, Names.folder, "warm.lock");
17
+ /** Create the lock file whole, so two proves cannot both think they made it. A lock whose process is gone is taken over. */
18
+ const take = (root) => Effect.gen(function* () {
19
+ const made = yield* Effect.try({
20
+ try: () => { mkdirSync(resolve(root, Names.folder), { recursive: true }); writeFileSync(lockOf(root), `${process.pid}\n`, { flag: "wx" }); },
21
+ catch: (e) => e,
22
+ }).pipe(Effect.match({ onFailure: (e) => e, onSuccess: () => undefined }));
23
+ if (made === undefined)
24
+ return true;
25
+ if (made.code !== "EEXIST")
26
+ return false;
27
+ const holder = yield* Effect.try({ try: () => Number(readFileSync(lockOf(root), "utf8").trim()), catch: () => "gone" }).pipe(Effect.orElseSucceed(() => 0));
28
+ if (holder !== 0 && (yield* alive(holder)))
29
+ return false;
30
+ // Left by a prove that was killed: remove it and try once more.
31
+ yield* Effect.sync(() => rmSync(lockOf(root), { force: true }));
32
+ return yield* Effect.try({ try: () => { writeFileSync(lockOf(root), `${process.pid}\n`, { flag: "wx" }); return true; }, catch: () => false }).pipe(Effect.orElseSucceed(() => false));
33
+ });
34
+ export const Warm = {
35
+ lock: (root) => Effect.acquireRelease(take(root), (held) => Effect.sync(() => { if (held)
36
+ rmSync(lockOf(root), { force: true }); })),
37
+ publish: (root, record) => Effect.acquireRelease(Effect.try({
38
+ try: () => {
39
+ mkdirSync(resolve(root, Names.folder), { recursive: true });
40
+ writeFileSync(fileOf(root), JSON.stringify(record, null, 2) + "\n");
41
+ },
42
+ catch: (e) => new WarmFailed({ message: `couldn't write ${fileOf(root)}: ${String(e)}` }),
43
+ }), () => Effect.sync(() => rmSync(fileOf(root), { force: true }))),
44
+ find: (root) => Effect.gen(function* () {
45
+ if (!existsSync(fileOf(root)))
46
+ return undefined;
47
+ const found = yield* read(root);
48
+ if (Option.isNone(found))
49
+ return undefined;
50
+ const record = found.value;
51
+ if (!(yield* alive(record.pid)) || !(yield* answers(record.url, record.nonce)))
52
+ return undefined;
53
+ // An edit is a newer file; an addition, a deletion or a rename is a different list of files.
54
+ return newestChange(root) > record.startedAt || fingerprint(root) !== record.sources ? undefined : record;
55
+ }),
56
+ reset: ({ url, telemetry, nonce }) =>
57
+ // The collector's files too: a run reads them whole, and the last run's spans would only be in its way. Each is replaced by an
58
+ // empty one made while the old still exists, so the new file never has the old one's inode (a file removed and made again can
59
+ // get the number back, and then a reader that tells files apart by it cannot tell a fresh file from the old one grown).
60
+ Effect.try({
61
+ try: () => {
62
+ if (!existsSync(telemetry))
63
+ return;
64
+ for (const entry of readdirSync(telemetry)) {
65
+ const file = join(telemetry, entry);
66
+ const fresh = join(telemetry, `.${entry}.fresh`);
67
+ writeFileSync(fresh, "");
68
+ renameSync(fresh, file);
69
+ }
70
+ },
71
+ catch: (e) => new WarmFailed({ message: `couldn't empty ${telemetry}: ${String(e)}` }),
72
+ }).pipe(Effect.andThen(Effect.tryPromise({
73
+ try: () => fetch(`${url}/_world/reset`, { method: "POST", headers: { "x-ortho-world": nonce } }).then((r) => (r.ok ? undefined : Promise.reject(new Error(`answered ${r.status}`)))),
74
+ catch: (e) => new WarmFailed({ message: `couldn't empty the world of ortho dev at ${url}: ${String(e)}` }),
75
+ }))),
76
+ };
@@ -0,0 +1,43 @@
1
+ import { type Effect, type Scope } from "effect";
2
+ declare const WarmFailed_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
3
+ readonly _tag: "WarmFailed";
4
+ } & Readonly<A>;
5
+ export declare class WarmFailed extends WarmFailed_base<{
6
+ readonly message: string;
7
+ }> {
8
+ }
9
+ /** What a live `ortho dev` keeps: its world, and the collector the world exports to. */
10
+ export interface DevRecord {
11
+ /** The `ortho dev` process: a record whose process is gone is stale. */
12
+ readonly pid: number;
13
+ /** The world's URL. */
14
+ readonly url: string;
15
+ /** The collector's OTLP/HTTP base URL: where a run's own spans (the journeys' roots) are exported. */
16
+ readonly collector: string;
17
+ /** The folder the collector writes, absolute (`.ortho/dev-telemetry`). */
18
+ readonly telemetry: string;
19
+ /** When `ortho dev` began, in milliseconds: the world serves the source as it was then. */
20
+ readonly startedAt: number;
21
+ /** Said by the world's health answer and required by its reset: a pid reused by another process, or another world on the port, has another. */
22
+ readonly nonce: string;
23
+ /** Which source files there were, and what each held, when dev began (`fingerprint`). */
24
+ readonly sources: string;
25
+ }
26
+ export interface WarmApi {
27
+ /** Write the record for as long as the scope is open; remove it when the scope closes. */
28
+ readonly publish: (root: string, record: DevRecord) => Effect.Effect<void, WarmFailed, Scope.Scope>;
29
+ /**
30
+ * The record of a live `ortho dev` whose world is fit to run a prove in, or `undefined`. Not fit: no record, a process that
31
+ * is gone (dev was killed), a world that does not answer, or source (src, blueprint, generated/server) changed since dev
32
+ * began (a file edited, added, deleted or renamed), because the world may not have reloaded it yet and a verdict must be the code on disk's.
33
+ */
34
+ readonly find: (root: string) => Effect.Effect<DevRecord | undefined>;
35
+ /**
36
+ * Take the right to run in the warm world, until the scope closes. `false` when another prove holds it (it would be reset under
37
+ * that prove): the caller starts a world of its own. A lock left by a process that is gone is not held.
38
+ */
39
+ readonly lock: (root: string) => Effect.Effect<boolean, never, Scope.Scope>;
40
+ /** Empty the world's databases and its cast, so a run never sees the last one's records. */
41
+ readonly reset: (record: DevRecord) => Effect.Effect<void, WarmFailed>;
42
+ }
43
+ export {};
@@ -0,0 +1,4 @@
1
+ // A warm world (ST1.24): what `ortho dev` leaves under `.ortho/` for `ortho prove` to find, and what prove asks of it.
2
+ import { Data } from "effect";
3
+ export class WarmFailed extends Data.TaggedError("WarmFailed") {
4
+ }
@@ -0,0 +1,20 @@
1
+ import { Effect } from "effect";
2
+ import type { EnvironmentModel } from "@orthograph/compiler";
3
+ import type { TraceSource } from "#modules/telemetry/types.js";
4
+ import type { Env, Reader } from "#modules/sinks/types.js";
5
+ import { WatchFailed, type SourceName } from "../types.ts";
6
+ export interface Chosen {
7
+ readonly reading: TraceSource;
8
+ /** `files .ortho/environments/staging/telemetry`, `axiom capxul-real-traces`. */
9
+ readonly from: string;
10
+ }
11
+ /** The environment's own Collector's folder: what `env up` made it record. `local` is what `prove --env local` wrote. */
12
+ export declare const folderOf: (environment: string) => string;
13
+ export declare const choose: (options: {
14
+ readonly root: string;
15
+ readonly environment: string;
16
+ readonly declared: EnvironmentModel;
17
+ readonly source: SourceName;
18
+ readonly env: Env;
19
+ readonly read?: Reader;
20
+ }) => Effect.Effect<Chosen, WatchFailed>;
@@ -0,0 +1,24 @@
1
+ // Which TraceSource a watch reads, and what to call it in the first line.
2
+ import { Names } from "orthograph/server";
3
+ import { existsSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { Effect } from "effect";
6
+ import { AxiomSource, FileSource } from "#modules/telemetry/service.js";
7
+ import { WatchFailed } from "../types.js";
8
+ const failed = (message) => new WatchFailed({ message });
9
+ /** The environment's own Collector's folder: what `env up` made it record. `local` is what `prove --env local` wrote. */
10
+ export const folderOf = (environment) => (environment === "local" ? `${Names.folder}/prove-telemetry` : `${Names.folder}/environments/${environment}/telemetry`);
11
+ export const choose = (options) => {
12
+ const { root, environment, declared, source, env, read } = options;
13
+ if (source === "file") {
14
+ const folder = folderOf(environment);
15
+ return existsSync(join(root, folder))
16
+ ? Effect.succeed({ reading: FileSource.open(join(root, folder)), from: `files ${folder}` })
17
+ : Effect.fail(failed(`${environment} has recorded no telemetry (${folder} is not there): \`ortho env up ${environment}\`, send it some traffic, then watch`));
18
+ }
19
+ const named = (declared.telemetry ?? []).find((s) => s.sink === "axiom");
20
+ if (named?.sink !== "axiom") {
21
+ return Effect.fail(failed(`${environment} sends nothing to Axiom: name \`Telemetry.sink.axiom({ group })\` in its telemetry list in blueprint/environments/${environment}.ts, or watch the files`));
22
+ }
23
+ return AxiomSource.open({ group: named.group, environment, env, ...(read ? { read } : {}) }).pipe(Effect.map((reading) => ({ reading, from: `axiom ${named.group}-traces` })), Effect.mapError((e) => failed(e.message)));
24
+ };
@@ -0,0 +1,9 @@
1
+ import type { Model } from "@orthograph/compiler";
2
+ import type { Evidence } from "#modules/evals/types.js";
3
+ import { type Trace } from "#modules/telemetry/types.js";
4
+ export interface Seen {
5
+ readonly evidence: ReadonlyArray<Evidence>;
6
+ /** Traces left out because a prove run made them. */
7
+ readonly left: number;
8
+ }
9
+ export declare const evidenceOf: (model: Model, traces: ReadonlyMap<string, Trace>) => Seen;
@@ -0,0 +1,26 @@
1
+ import { PROVE_SPAN_PREFIX } from "#modules/telemetry/types.js";
2
+ /** A trace prove made: a span of it points at a caller span prove made up. Prove judged it already. */
3
+ const madeByProve = (trace) => trace.spans.some((s) => s.parentSpanId.startsWith(PROVE_SPAN_PREFIX));
4
+ /** What the operation's span says happened: refused (a declared outcome), died (a defect), or answered. */
5
+ const statusOf = (span) => (typeof span.attrs["refusal"] === "string" ? 422 : span.status === 2 ? 500 : 200);
6
+ export const evidenceOf = (model, traces) => {
7
+ let left = 0;
8
+ const evidence = [];
9
+ for (const [id, trace] of traces) {
10
+ if (madeByProve(trace)) {
11
+ left += 1;
12
+ continue;
13
+ }
14
+ const opSpan = trace.spans.filter((s) => model.operations[s.name] !== undefined).sort((a, b) => a.start - b.start)[0];
15
+ if (!opSpan)
16
+ continue;
17
+ const refusal = typeof opSpan.attrs["refusal"] === "string" ? opSpan.attrs["refusal"] : undefined;
18
+ // Live there is no caller to ask: no actor, no payload, no answer body. The evals read the spans.
19
+ const call = {
20
+ journey: "watch", step: id, actor: "live", person: "live", operation: opSpan.name, payload: {}, status: statusOf(opSpan),
21
+ body: undefined, trace: id, parent: "", mayCall: true, journal: [],
22
+ };
23
+ evidence.push({ call, trace, opSpan, refusal, stored: undefined });
24
+ }
25
+ return { evidence, left };
26
+ };
@@ -0,0 +1,18 @@
1
+ import type { Model } from "@orthograph/compiler";
2
+ import type { Evidence } from "#modules/evals/types.js";
3
+ import { Evals } from "#modules/evals/service.js";
4
+ export interface Drifting {
5
+ readonly operation: string;
6
+ readonly p50: number;
7
+ readonly p95: number;
8
+ readonly budget: number;
9
+ readonly calls: number;
10
+ /** The slowest calls' trace ids, slowest first: what to read with `ortho telemetry trace`. */
11
+ readonly slowest: ReadonlyArray<string>;
12
+ }
13
+ export interface Judged {
14
+ readonly lines: ReadonlyArray<string>;
15
+ readonly drifting: ReadonlyArray<Drifting>;
16
+ readonly passed: boolean;
17
+ }
18
+ export declare const judge: (model: Model, project: Parameters<typeof Evals.judgeLive>[0], evidence: ReadonlyArray<Evidence>) => Judged;
@@ -0,0 +1,59 @@
1
+ import { Evals } from "#modules/evals/service.js";
2
+ const SHOWN = 5;
3
+ /** Calls needed before a p95 over budget is drift: below 20, the p95 is just the slowest call. */
4
+ const MIN_CALLS = 20;
5
+ /** The evals watch can judge, in the order they print. */
6
+ const LIVE_EVALS = ["answer shape", "declared errors", "steps", "explainability"];
7
+ const NOT_LIVE = "who may call, machine path, events, coverage";
8
+ const byOperation = (evidence) => {
9
+ const groups = new Map();
10
+ for (const e of evidence)
11
+ (groups.get(e.call.operation) ?? groups.set(e.call.operation, []).get(e.call.operation)).push(e);
12
+ return [...groups].sort(([a], [b]) => a.localeCompare(b));
13
+ };
14
+ const countsLine = (label, counts, show) => counts.size === 0
15
+ ? `${label}: none`
16
+ : `${label}: ${[...counts].sort(([a, x], [b, y]) => y - x || a.localeCompare(b)).map(([k, n]) => show(k, n)).join(" ")}`;
17
+ const tally = (keys) => keys.reduce((m, k) => m.set(k, (m.get(k) ?? 0) + 1), new Map());
18
+ /** The evals' failures, each as a line naming the eval and the operation. A long list is cut short and says by how much. */
19
+ const failureLines = (verdicts) => verdicts.flatMap((v) => v.failures.length === 0 ? [] : [
20
+ ...v.failures.slice(0, SHOWN).map((f) => `✘ ${v.eval} ${v.operation ?? ""} ${f}`),
21
+ ...(v.failures.length > SHOWN ? [`✘ ${v.eval} ${v.operation ?? ""} … and ${v.failures.length - SHOWN} more`] : []),
22
+ ]);
23
+ const evalsLine = (verdicts) => `evals: ${LIVE_EVALS.map((name) => {
24
+ const failed = verdicts.filter((v) => v.eval === name).reduce((n, v) => n + v.failures.length, 0);
25
+ return failed === 0 ? `${name} ✔` : `${name} ✘ ${failed}`;
26
+ }).join(" ")} (judged by prove only: ${NOT_LIVE})`;
27
+ export const judge = (model, project, evidence) => {
28
+ const drifting = [];
29
+ const thin = [];
30
+ const perOperation = byOperation(evidence).map(([name, calls]) => {
31
+ const times = calls.flatMap((e) => (e.opSpan ? [e.opSpan.ms] : [])).sort((a, b) => a - b);
32
+ const budget = model.operations[name]?.budget?.p95Ms ?? null;
33
+ const p95 = Math.ceil(Evals.percentile(times, 95));
34
+ const above = budget !== null && Evals.percentile(times, 95) > budget;
35
+ // A p95 over fewer than MIN_CALLS calls is the slowest call: a lone slow request is noise, not drift. It is said, and judged once there is traffic.
36
+ const over = above && calls.length >= MIN_CALLS;
37
+ if (above && !over)
38
+ thin.push(`${name} p95 ${p95}ms is over its budget of ${budget}ms but ${calls.length} calls are too few to call drift (${MIN_CALLS} needed)`);
39
+ if (over) {
40
+ const slowest = calls.filter((e) => e.opSpan).sort((a, b) => b.opSpan.ms - a.opSpan.ms).slice(0, 3).map((e) => e.call.trace);
41
+ drifting.push({ operation: name, p50: Math.ceil(Evals.percentile(times, 50)), p95, budget: budget, calls: calls.length, slowest });
42
+ }
43
+ return { name, calls: calls.length, line: `${name} p95 ${p95}ms (${budget === null ? "no budget" : `budget ${budget}ms`}) ${over ? "✘" : "✔"}` };
44
+ });
45
+ const verdicts = Evals.judgeLive(project, evidence);
46
+ const failures = failureLines(verdicts);
47
+ const refusals = evidence.flatMap((e) => (e.refusal ? [e.refusal] : []));
48
+ const defects = evidence.flatMap((e) => (e.call.status === 500 ? [e.call.operation] : []));
49
+ const lines = [
50
+ ...perOperation.map((o) => o.line),
51
+ `calls: ${perOperation.map((o) => `${o.name} ${o.calls}`).join(" ")}`,
52
+ countsLine("refusals", tally(refusals), (tag, n) => `${tag} ${n}${model.refusals[tag] ? ` (${model.refusals[tag]})` : ""}`),
53
+ countsLine("defects", tally(defects), (op, n) => `${op} ${n}`),
54
+ evalsLine(verdicts),
55
+ ...thin.map((t) => `thin: ${t}`),
56
+ ...failures,
57
+ ];
58
+ return { lines, drifting, passed: failures.length === 0 };
59
+ };
@@ -0,0 +1,5 @@
1
+ import { Effect } from "effect";
2
+ import type { Model } from "@orthograph/compiler";
3
+ import type { Drifting } from "./report.ts";
4
+ /** Write a task for each operation drifting now, remove the one of each operation that no longer does. Returns the paths written. */
5
+ export declare const syncTasks: (root: string, environment: string, model: Model, drifting: ReadonlyArray<Drifting>) => Effect.Effect<ReadonlyArray<string>>;
@@ -0,0 +1,35 @@
1
+ // Drift becomes a task (D3 #144): a file under `.ortho/tasks/`, written by a watch that finds an operation over its
2
+ // budget and removed by the first watch that finds it back under. `.ortho/` is where the project already keeps what
3
+ // ortho writes, and a task there is what `ortho brief` and an agent are pointed at.
4
+ import { Names } from "orthograph/server";
5
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
6
+ import { dirname, join } from "node:path";
7
+ import { Effect } from "effect";
8
+ const taskPath = (environment, operation) => `${Names.folder}/tasks/drift-${environment}-${operation}.md`;
9
+ const textOf = (environment, d, model) => {
10
+ const op = model.operations[d.operation];
11
+ return [
12
+ `# ${d.operation} is over its budget in ${environment}`,
13
+ "",
14
+ `Written by \`ortho watch --env ${environment}\`. The next watch that finds ${d.operation} back under its budget removes this file.`,
15
+ "",
16
+ `- p95 ${d.p95}ms against a budget of ${d.budget}ms (p50 ${d.p50}ms, over ${d.calls} calls in the window).`,
17
+ `- The slowest calls, to read as a tree: ${d.slowest.map((t) => `\`ortho telemetry trace ${t} --env ${environment}\``).join(", ")}.`,
18
+ `- What it must do, and what it must not touch: \`ortho brief ${d.operation}\`.${op ? ` Its handler is \`src/${op.thing}/${op.verb}.ts\`.` : ""}`,
19
+ "- The budget is the operation's `budget` in its declaration. Make the handler faster; loosening the budget is a decision that makes the operation's verdicts stale.",
20
+ "",
21
+ ].join("\n");
22
+ };
23
+ /** Write a task for each operation drifting now, remove the one of each operation that no longer does. Returns the paths written. */
24
+ export const syncTasks = (root, environment, model, drifting) => Effect.sync(() => {
25
+ const now = new Set(drifting.map((d) => d.operation));
26
+ for (const name of Object.keys(model.operations))
27
+ if (!now.has(name))
28
+ rmSync(join(root, taskPath(environment, name)), { force: true });
29
+ return drifting.map((d) => {
30
+ const path = taskPath(environment, d.operation);
31
+ mkdirSync(dirname(join(root, path)), { recursive: true });
32
+ writeFileSync(join(root, path), textOf(environment, d, model));
33
+ return path;
34
+ });
35
+ });
@@ -0,0 +1,2 @@
1
+ import { type WatchApi } from "./types.ts";
2
+ export declare const Watch: WatchApi;
@@ -0,0 +1,38 @@
1
+ import { resolve } from "node:path";
2
+ import { Effect } from "effect";
3
+ import { Compiler, nodeSource } from "@orthograph/compiler";
4
+ import { Journeys } from "#modules/journeys/service.js";
5
+ import { WatchFailed } from "./types.js";
6
+ import { choose } from "./internal/choose.js";
7
+ import { evidenceOf } from "./internal/evidence.js";
8
+ import { judge } from "./internal/report.js";
9
+ import { syncTasks } from "./internal/tasks.js";
10
+ const failed = (message) => new WatchFailed({ message });
11
+ const span = (ms) => (ms % 3_600_000 === 0 ? `${ms / 3_600_000}h` : ms % 60_000 === 0 ? `${ms / 60_000}m` : `${Math.ceil(ms / 1000)}s`);
12
+ export const Watch = {
13
+ run: ({ root: given, environment, source, since, env, read, use }) => Effect.gen(function* () {
14
+ const root = resolve(given);
15
+ const model = yield* Compiler.model.pipe(Effect.provide(nodeSource(root)), Effect.mapError((e) => failed(e._tag === "BlueprintInvalid" ? `the blueprint is invalid:\n - ${e.problems.join("\n - ")}` : e.message)));
16
+ const declared = model.environments?.[environment];
17
+ if (!declared)
18
+ return yield* failed(`no environment "${environment}" in blueprint/environments/ (there is ${Object.keys(model.environments ?? {}).join(", ") || "none"})`);
19
+ const project = yield* Journeys.load(root, model).pipe(Effect.mapError((e) => failed(e.message)));
20
+ const chosen = use ? { reading: use, from: "the given source" } : yield* choose({ root, environment, declared, source, env, ...(read ? { read } : {}) });
21
+ const traces = yield* chosen.reading.window(since).pipe(Effect.mapError((e) => failed(e.message)));
22
+ const seen = evidenceOf(model, traces);
23
+ const header = `watch ${environment} last ${span(since)} from ${chosen.from}${seen.left > 0 ? ` (${seen.left} traces from prove runs left out)` : ""}`;
24
+ if (seen.evidence.length === 0) {
25
+ const tasks = yield* syncTasks(root, environment, model, []);
26
+ return { lines: [header, "no calls in the window", "drift none"], drift: [], tasks, passed: true };
27
+ }
28
+ const judged = judge(model, project, seen.evidence);
29
+ const tasks = yield* syncTasks(root, environment, model, judged.drifting);
30
+ const drift = judged.drifting.map((d) => d.operation);
31
+ return {
32
+ lines: [header, ...judged.lines, ...tasks.map((t) => `task ${t}`), `drift ${drift.length === 0 ? "none" : drift.join(" ")}`],
33
+ drift,
34
+ tasks,
35
+ passed: judged.passed,
36
+ };
37
+ }),
38
+ };
@@ -0,0 +1,44 @@
1
+ import { type Effect } from "effect";
2
+ import type { Env, Reader } from "#modules/sinks/types.js";
3
+ import type { TraceSource } from "#modules/telemetry/types.js";
4
+ declare const WatchFailed_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
5
+ readonly _tag: "WatchFailed";
6
+ } & Readonly<A>;
7
+ export declare class WatchFailed extends WatchFailed_base<{
8
+ readonly message: string;
9
+ }> {
10
+ }
11
+ /** Where the traces come from: the environment's own Collector's files, or Axiom's query API. */
12
+ export type SourceName = "file" | "axiom";
13
+ export interface Watched {
14
+ /** What to print, one line each. */
15
+ readonly lines: ReadonlyArray<string>;
16
+ /** The operations whose p95 is over their budget. */
17
+ readonly drift: ReadonlyArray<string>;
18
+ /** The tasks written for them, relative to the project root. */
19
+ readonly tasks: ReadonlyArray<string>;
20
+ /** No eval failed. Drift is a task and a refusal an outcome: neither fails a watch. A defect is counted, never a failure of its own. */
21
+ readonly passed: boolean;
22
+ }
23
+ export interface WatchApi {
24
+ /**
25
+ * Judge the last `since` milliseconds of `environment`'s traffic. Reads through a `TraceSource`: `file` is the folder the
26
+ * environment's Collector writes (`.ortho/environments/<name>/telemetry`), `axiom` is Axiom's query API for the group of the
27
+ * `Telemetry.sink.axiom` the environment names (and fails, saying so, when it names none). Prints, for each operation seen, its
28
+ * p95 against its budget; the refusals by name and code; the defects; each live-judgeable eval; and the operations that drift,
29
+ * each of which becomes a task file under `.ortho/tasks/` (and a task whose operation is back under budget is removed).
30
+ * Calls that `prove` made (their caller span carries `PROVE_SPAN_PREFIX`) are not counted.
31
+ */
32
+ readonly run: (options: {
33
+ readonly root: string;
34
+ readonly environment: string;
35
+ readonly source: SourceName;
36
+ readonly since: number;
37
+ /** The process environment, for Axiom's query credentials; only an entry file reads it. */
38
+ readonly env: Env;
39
+ readonly read?: Reader;
40
+ /** A source to read instead of either: a test's. */
41
+ readonly use?: TraceSource;
42
+ }) => Effect.Effect<Watched, WatchFailed>;
43
+ }
44
+ export {};
@@ -0,0 +1,4 @@
1
+ // `ortho watch --env <name>`: the evals that telemetry can answer, run over what an environment has recorded (L2.09, O1).
2
+ import { Data } from "effect";
3
+ export class WatchFailed extends Data.TaggedError("WatchFailed") {
4
+ }
@@ -0,0 +1,8 @@
1
+ import { Effect } from "effect";
2
+ import { WorldFailed } from "../types.ts";
3
+ /**
4
+ * A port that is free on 127.0.0.1 now, which is what `port: 0` means. It is picked at random below the system's own range,
5
+ * where an outgoing connection or a worker's socket cannot take it in the seconds before the world binds it; the system's
6
+ * pick is the last resort. A failed listen on the last resort fails the effect.
7
+ */
8
+ export declare const anyPort: Effect.Effect<number, WorldFailed, never>;
@@ -0,0 +1,30 @@
1
+ import { randomInt } from "node:crypto";
2
+ import { createServer } from "node:net";
3
+ import { Effect } from "effect";
4
+ import { WorldFailed } from "../types.js";
5
+ /** Listen on `port` (0 for the system's pick) at 127.0.0.1, then let go: the port, or what stopped the listen. */
6
+ const tryListen = (port) => Effect.callback((resume) => {
7
+ const server = createServer();
8
+ server.once("error", (e) => resume(Effect.fail(new WorldFailed({ message: `no free port: ${e.message}` }))));
9
+ server.listen(port, "127.0.0.1", () => {
10
+ const got = server.address().port;
11
+ server.close(() => resume(Effect.succeed(got)));
12
+ });
13
+ });
14
+ /** Below the range the system hands out to outgoing connections and to wrangler's own sockets (32768 up on Linux, 49152 up on macOS). */
15
+ const LOW = 20_000;
16
+ const SPAN = 10_000;
17
+ const TRIES = 20;
18
+ /**
19
+ * A port that is free on 127.0.0.1 now, which is what `port: 0` means. It is picked at random below the system's own range,
20
+ * where an outgoing connection or a worker's socket cannot take it in the seconds before the world binds it; the system's
21
+ * pick is the last resort. A failed listen on the last resort fails the effect.
22
+ */
23
+ export const anyPort = Effect.gen(function* () {
24
+ for (let i = 0; i < TRIES; i++) {
25
+ const found = yield* tryListen(LOW + randomInt(SPAN)).pipe(Effect.option);
26
+ if (found._tag === "Some")
27
+ return found.value;
28
+ }
29
+ return yield* tryListen(0);
30
+ });
@@ -0,0 +1,46 @@
1
+ import { type ChildProcess } from "node:child_process";
2
+ import { Effect } from "effect";
3
+ import { WorldFailed } from "../types.ts";
4
+ /** The D1 bindings a config migrates: each `d1_databases` entry names its `migrations_dir`. The default is `DB`; each declared store (K3) has its own. */
5
+ export declare const databasesOf: (configText: string) => ReadonlyArray<string>;
6
+ /** Apply the generated migrations to each local database. `CI=1` stops wrangler asking to confirm. */
7
+ export declare const applyMigrations: (config: string, state: string) => Effect.Effect<void, WorldFailed, never>;
8
+ /** How to run one `wrangler dev`: its own state, its own inspector port, its output in `log`. */
9
+ export interface Wrangle {
10
+ readonly config: string;
11
+ readonly state: string;
12
+ readonly port: number;
13
+ readonly log: string;
14
+ /** Vars travel as arguments: only for a throwaway secret. A real one goes in `envFile`. */
15
+ readonly vars?: Readonly<Record<string, string>>;
16
+ /** A file of secrets (`NAME=value` lines), read by wrangler and never shown by `ps`. */
17
+ readonly envFile?: string;
18
+ /**
19
+ * Secrets that must never reach a file or an argument (a telemetry token): given to wrangler through its process
20
+ * environment, which wrangler hands to the Worker as secret bindings. wrangler then runs with a small allowlist of
21
+ * the caller's environment and not all of it, so nothing else in the shell becomes a binding of the Worker.
22
+ */
23
+ readonly secretEnv?: Readonly<Record<string, string>>;
24
+ /** Own process group, outliving this process: a long-lived environment. */
25
+ readonly detached?: boolean;
26
+ /** Written with the process id as soon as it exists, so a caller killed part-way can still find what it started. */
27
+ readonly pidFile?: string;
28
+ }
29
+ /**
30
+ * `wrangler dev`, its output appended to `log`. `--inspector-port 0` keeps two of them off the same inspector port (9229).
31
+ */
32
+ export declare const startWrangler: (w: Wrangle) => Effect.Effect<ChildProcess, never, never>;
33
+ export declare const stop: (child: ChildProcess) => Effect.Effect<void, never, never>;
34
+ /**
35
+ * Start wrangler and wait until `ready` answers. wrangler picks the worker's internal sockets itself, and two of them
36
+ * starting together can pick the same one; it then exits at once, so an early exit for a taken address starts it again.
37
+ * A process that never comes up is stopped. One that does is the caller's.
38
+ */
39
+ export declare const bringUp: (w: Wrangle, ready: string) => Effect.Effect<ChildProcess, WorldFailed, never>;
40
+ /** Whether workerd could not bind one of its sockets: another world took it first, and a fresh start picks again. */
41
+ export declare const taken: (log: string) => boolean;
42
+ /**
43
+ * What esbuild said when it could not build the worker, colour stripped: each `✘ [ERROR]` line and the line after it that
44
+ * names the importing file (`path:line:column:`). `undefined` while the log holds no build error.
45
+ */
46
+ export declare const buildErrors: (log: string) => string | undefined;
@@ -0,0 +1,112 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { existsSync, openSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { Effect, Schedule } from "effect";
6
+ import { WorldFailed } from "../types.js";
7
+ const bin = join(dirname(fileURLToPath(import.meta.resolve("wrangler/package.json"))), "bin/wrangler.js");
8
+ /** The D1 bindings a config migrates: each `d1_databases` entry names its `migrations_dir`. The default is `DB`; each declared store (K3) has its own. */
9
+ export const databasesOf = (configText) => [...configText.matchAll(/"binding"\s*:\s*"([A-Za-z0-9_]+)"[^}]*"migrations_dir"/g)].map((m) => m[1]);
10
+ /** Apply the generated migrations to each local database. `CI=1` stops wrangler asking to confirm. */
11
+ export const applyMigrations = (config, state) => Effect.try({
12
+ try: () => {
13
+ const found = databasesOf(readFileSync(config, "utf8"));
14
+ for (const binding of found.length > 0 ? found : ["DB"]) {
15
+ const run = spawnSync(process.execPath, [bin, "d1", "migrations", "apply", binding, "--local", "--config", config, "--persist-to", state], {
16
+ encoding: "utf8",
17
+ env: { ...process.env, CI: "1", WRANGLER_SEND_METRICS: "false" },
18
+ });
19
+ if (run.status !== 0)
20
+ throw new Error(run.stderr || run.stdout);
21
+ }
22
+ },
23
+ catch: (e) => new WorldFailed({ message: `the local database couldn't be made: ${String(e)}` }),
24
+ });
25
+ /**
26
+ * `wrangler dev`, its output appended to `log`. `--inspector-port 0` keeps two of them off the same inspector port (9229).
27
+ */
28
+ export const startWrangler = (w) => Effect.sync(() => {
29
+ const out = openSync(w.log, "a");
30
+ const args = [
31
+ bin, "dev", "--config", w.config, "--port", String(w.port), "--ip", "127.0.0.1", "--persist-to", w.state, "--inspector-port", "0",
32
+ ...(w.envFile ? ["--env-file", w.envFile] : []),
33
+ ...Object.entries(w.vars ?? {}).flatMap(([k, v]) => ["--var", `${k}:${v}`]),
34
+ ];
35
+ const child = spawn(process.execPath, args, { stdio: ["ignore", out, out], detached: w.detached === true, env: childEnv(w.secretEnv) });
36
+ if (w.detached)
37
+ child.unref();
38
+ if (w.pidFile)
39
+ writeFileSync(w.pidFile, `${child.pid}\n`);
40
+ return child;
41
+ });
42
+ /** What wrangler needs from the shell to run, and nothing it doesn't: no key of the user's reaches the Worker. */
43
+ const KEPT = /^(PATH|HOME|USER|LOGNAME|SHELL|TMPDIR|TERM|TZ|LANG|LC_[A-Z]+|XDG_[A-Z_]+|SSL_CERT_FILE|SSL_CERT_DIR|NODE_EXTRA_CA_CERTS|HTTPS?_PROXY|NO_PROXY|https?_proxy|no_proxy)$/;
44
+ /** The environment wrangler runs in: unchanged, unless there are secrets to hand it, and then the allowlist plus them. */
45
+ const childEnv = (secrets) => {
46
+ const base = { CI: "1", WRANGLER_SEND_METRICS: "false" };
47
+ if (secrets === undefined || Object.keys(secrets).length === 0)
48
+ return { ...process.env, ...base };
49
+ const kept = Object.fromEntries(Object.entries(process.env).filter(([k]) => KEPT.test(k)));
50
+ return { ...kept, ...base, ...secrets, CLOUDFLARE_INCLUDE_PROCESS_ENV: "true" };
51
+ };
52
+ export const stop = (child) => Effect.callback((resume) => {
53
+ if (child.exitCode !== null || child.signalCode !== null)
54
+ return resume(Effect.void);
55
+ child.once("exit", () => resume(Effect.void));
56
+ child.kill("SIGTERM");
57
+ });
58
+ /** One look at `url`, given up after a second: while the worker cannot build, wrangler takes the connection and never answers it. */
59
+ const answers = (url) => Effect.tryPromise({ try: () => fetch(url, { signal: AbortSignal.timeout(1000) }).then((r) => r.ok), catch: () => false }).pipe(Effect.flatMap((ok) => (ok ? Effect.void : Effect.fail(false))));
60
+ /**
61
+ * Start wrangler and wait until `ready` answers. wrangler picks the worker's internal sockets itself, and two of them
62
+ * starting together can pick the same one; it then exits at once, so an early exit for a taken address starts it again.
63
+ * A process that never comes up is stopped. One that does is the caller's.
64
+ */
65
+ export const bringUp = (w, ready) => {
66
+ const url = `http://127.0.0.1:${w.port}${ready}`;
67
+ const attempt = Effect.gen(function* () {
68
+ const from = readLog(w.log).length;
69
+ const child = yield* startWrangler(w);
70
+ // A worker that cannot be built (a missing file, an import of something not exported) leaves wrangler up, waiting for the
71
+ // file to change: it never exits and never answers. Its log holds esbuild's error, so the wait ends the moment that shows.
72
+ // A taken socket is told apart first: workerd's bind failure also prints a `✘ [ERROR]` line, and it is retried, not reported.
73
+ const up = Effect.suspend(() => {
74
+ const log = readLog(w.log).slice(from);
75
+ return taken(log) ? Effect.fail("taken")
76
+ : child.exitCode !== null ? Effect.fail("exited")
77
+ : buildErrors(log) !== undefined ? Effect.fail("unbuildable")
78
+ : answers(url).pipe(Effect.mapError(() => "silent"));
79
+ });
80
+ yield* up.pipe(Effect.retry({ schedule: Schedule.spaced("250 millis"), times: 480, while: (e) => e === "silent" }), Effect.tapError(() => stop(child)), Effect.mapError((e) => {
81
+ const log = readLog(w.log).slice(from);
82
+ const isTaken = e === "taken" || (e === "exited" && taken(log));
83
+ const built = isTaken ? undefined : buildErrors(log);
84
+ return new WorldFailed({
85
+ message: isTaken ? `the world's address was taken; see ${w.log}`
86
+ : built !== undefined ? `couldn't start the world: wrangler could not build the worker:\n${built}\nwrangler's output is in ${w.log}`
87
+ : e === "exited" ? `the world exited (${child.exitCode}); see ${w.log}` : `the world didn't answer within 120 s; see ${w.log}`,
88
+ taken: isTaken,
89
+ });
90
+ }));
91
+ return child;
92
+ });
93
+ return attempt.pipe(Effect.retry({ times: 3, while: (e) => e.taken === true }));
94
+ };
95
+ const readLog = (log) => (existsSync(log) ? readFileSync(log, "utf8") : "");
96
+ /** Whether workerd could not bind one of its sockets: another world took it first, and a fresh start picks again. */
97
+ export const taken = (log) => log.includes("Address already in use");
98
+ const colour = /\u001b\[[0-9;]*m/g;
99
+ /**
100
+ * What esbuild said when it could not build the worker, colour stripped: each `✘ [ERROR]` line and the line after it that
101
+ * names the importing file (`path:line:column:`). `undefined` while the log holds no build error.
102
+ */
103
+ export const buildErrors = (log) => {
104
+ const lines = log.replace(colour, "").split("\n");
105
+ const found = lines.flatMap((line, i) => {
106
+ if (!line.includes("✘ [ERROR]"))
107
+ return [];
108
+ const where = lines.slice(i + 1, i + 4).find((l) => /^\s+\S+:\d+:\d+:\s*$/.test(l));
109
+ return [where === undefined ? line.trim() : `${line.trim()}\n${where.trimEnd()}`];
110
+ });
111
+ return found.length === 0 ? undefined : found.slice(0, 5).join("\n");
112
+ };
@@ -0,0 +1,2 @@
1
+ import { type WorldsApi } from "./types.ts";
2
+ export declare const Worlds: WorldsApi;