@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,29 @@
1
+ const kebab = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
2
+ /** `grant-an-allowance "ada grants olga 500"`: where a failure happened. */
3
+ export const where = (e) => `${kebab(e.call.journey)} "${e.call.step}"`;
4
+ export const answered = (e) => e.call.status === 200;
5
+ /** Every span under the operation's span, itself included. */
6
+ export const subtree = (trace, root) => {
7
+ if (!root)
8
+ return [];
9
+ const out = [root];
10
+ for (let i = 0; i < out.length; i++)
11
+ out.push(...trace.spans.filter((s) => s.parentSpanId === out[i].spanId));
12
+ return out;
13
+ };
14
+ /** A span attribute anywhere in the operation's subtree: `move.to` is written on whichever span made the move. */
15
+ export const attr = (e, key) => subtree(e.trace, e.opSpan).find((s) => key in s.attrs)?.attrs[key];
16
+ const refusalOf = (call, opSpan) => {
17
+ const tag = call.status >= 400 && call.status < 500 && typeof call.body === "object" && call.body !== null ? call.body._tag : undefined;
18
+ if (typeof tag === "string")
19
+ return tag;
20
+ const onSpan = opSpan?.attrs["refusal"];
21
+ return typeof onSpan === "string" ? onSpan : undefined;
22
+ };
23
+ export const gather = (calls, traces) => calls.map((call) => {
24
+ const trace = traces.get(call.trace) ?? { spans: [], logs: [] };
25
+ const opSpan = trace.spans.find((s) => s.name === call.operation);
26
+ return { call, trace, opSpan, refusal: refusalOf(call, opSpan), stored: call.stored };
27
+ });
28
+ /** A call the server answered from a request it already committed: it ran nothing, so it moved nothing. */
29
+ export const replayed = (e) => attr(e, "request.replayed") === true;
@@ -0,0 +1,12 @@
1
+ import type { Model } from "@orthograph/compiler";
2
+ import type { Evidence, PerOperation, Verdict } from "../types.ts";
3
+ export declare const percentile: (sorted: ReadonlyArray<number>, p: number) => number;
4
+ /** 7. p50 and p95 of the operation's spans against its budget. Over 1.5 times the budget is a review, never a failure. */
5
+ export declare const performance: PerOperation;
6
+ /**
7
+ * 8. Coverage, per operation: called by some journey or starting world, its move made, every outcome reached and every
8
+ * declared error refused. The runtime's own refusals (NotAllowed, the machine's) are counted but never required; the run's line counts only those a journey can cause (not `IdempotencyConflict`: see `unreachable`).
9
+ */
10
+ export declare const coverage: PerOperation;
11
+ /** The run's coverage in one line: what was reached of everything declared. It never fails; each operation's does. */
12
+ export declare const coverageSummary: (model: Model, evidence: ReadonlyArray<Evidence>) => Verdict;
@@ -0,0 +1,85 @@
1
+ import { answered, attr } from "./evidence.js";
2
+ export const percentile = (sorted, p) => sorted[Math.min(sorted.length - 1, Math.ceil((p / 100) * sorted.length) - 1)] ?? 0;
3
+ const ms = (n) => `${Math.round(n)}ms`;
4
+ /** 7. p50 and p95 of the operation's spans against its budget. Over 1.5 times the budget is a review, never a failure. */
5
+ export const performance = (op, evidence) => {
6
+ const times = evidence.flatMap((e) => (e.opSpan ? [e.opSpan.ms] : [])).sort((a, b) => a - b);
7
+ const budget = op.budget?.p95Ms;
8
+ if (times.length === 0)
9
+ return { eval: "performance", operation: op.name, failures: [], notes: ["no timed calls"] };
10
+ const p50 = percentile(times, 50);
11
+ const p95 = percentile(times, 95);
12
+ const notes = [`p50 ${ms(p50)} p95 ${ms(p95)}${budget === undefined ? " (no budget)" : ` budget p95 ${ms(budget)}`}`];
13
+ if (budget !== undefined && p95 > 1.5 * budget)
14
+ notes.push(`review: p95 ${ms(p95)} is over 1.5x budget`);
15
+ return { eval: "performance", operation: op.name, failures: [], notes };
16
+ };
17
+ /** A rule's refusal is counted once for the rule, whichever operation broke it: its key is the rule's full name (`handle.oneHolderPerName`), never an operation's. */
18
+ const ruleKey = (rule) => `rule:${rule}`;
19
+ /** The rule a refused call was refused for: the span's `refusal.invariant`, else the rule the operation lists for that refusal. */
20
+ const ruleOf = (model, e) => {
21
+ const onSpan = attr(e, "refusal.invariant");
22
+ const rule = typeof onSpan === "string" ? onSpan : e.refusal === undefined ? undefined : model.operations[e.call.operation]?.invariants?.[e.refusal];
23
+ return rule === undefined ? [] : [ruleKey(rule)];
24
+ };
25
+ /** What the whole run reached: operations called, moves made, outcomes reached, refusals given. */
26
+ const reachedIn = (model, evidence) => {
27
+ const thingOf = (e) => model.operations[e.call.operation]?.thing;
28
+ const moving = evidence.filter((e) => answered(e) && attr(e, "move.to") !== undefined);
29
+ return {
30
+ called: new Set(evidence.map((e) => e.call.operation)),
31
+ moved: new Set(moving.map((e) => `${thingOf(e)}.${model.operations[e.call.operation]?.move?.key}`)),
32
+ reached: new Set(moving.map((e) => `${thingOf(e)}:${String(attr(e, "move.to"))}`)),
33
+ refused: new Set(evidence.flatMap((e) => (e.refusal ? [`${e.call.operation}:${e.refusal}`, ...ruleOf(model, e)] : []))),
34
+ };
35
+ };
36
+ /**
37
+ * The runtime's own refusals no journey can cause: every refusal the model codes under the runtime's prefix (`AR`, read from `NotAllowed`'s
38
+ * code) except `NotAllowed`, which a step reaches by naming a caller who may not. `IdempotencyConflict` is one: it needs a second payload under
39
+ * a held request key, and a journey step cannot send one. Counting it would leave it uncovered for ever (G3). The names come from the model.
40
+ *
41
+ * This is inferred from names ("every AR- refusal except NotAllowed"). When the next runtime refusal arrives, the model should carry a
42
+ * "reachable from a journey" flag per refusal and this should read it (design/later.md, "From prove's coverage").
43
+ */
44
+ const unreachable = (model) => {
45
+ const prefix = model.refusals?.["NotAllowed"]?.split("-")[0];
46
+ return new Set(prefix === undefined ? [] : Object.entries(model.refusals).filter(([name, code]) => name !== "NotAllowed" && code.startsWith(`${prefix}-`)).map(([name]) => name));
47
+ };
48
+ const required = (op, skip = new Set()) => ({
49
+ move: op.move ? [`${op.thing}.${op.move.key}`] : [],
50
+ outcomes: op.move ? op.move.to.map((s) => `${op.thing}:${s}`) : [],
51
+ errors: op.errors.map((x) => `${op.name}:${x}`),
52
+ // The rules this operation can break, each by its full name: the runtime's refusals for them are the rule's, counted with the declared ones.
53
+ rules: [...new Set(Object.values(op.invariants ?? {}))].map(ruleKey),
54
+ runtime: op.refusals.filter((r) => !op.errors.includes(r) && !(r in (op.invariants ?? {})) && !skip.has(r)).map((r) => `${op.name}:${r}`),
55
+ });
56
+ const gaps = (op, sets) => {
57
+ if (!sets.called.has(op.name))
58
+ return [`${op.name} reached by no journey`];
59
+ const r = required(op);
60
+ return [
61
+ ...r.move.filter((m) => !sets.moved.has(m)).map((m) => `move ${m} made by no journey`),
62
+ ...r.outcomes.filter((s) => !sets.reached.has(s)).map((s) => `outcome ${s.replace(":", " ")} reached by no journey`),
63
+ ...r.errors.filter((x) => !sets.refused.has(x)).map((x) => `${x.replace(":", " refusing ")} reached by no journey`),
64
+ ...r.rules.filter((x) => !sets.refused.has(x)).map((x) => `rule ${x.slice("rule:".length)} refused by no journey`),
65
+ ];
66
+ };
67
+ /**
68
+ * 8. Coverage, per operation: called by some journey or starting world, its move made, every outcome reached and every
69
+ * declared error refused. The runtime's own refusals (NotAllowed, the machine's) are counted but never required; the run's line counts only those a journey can cause (not `IdempotencyConflict`: see `unreachable`).
70
+ */
71
+ export const coverage = (op, _mine, { project, all }) => {
72
+ const failures = gaps(op, reachedIn(project.model, all));
73
+ return { eval: "coverage", operation: op.name, failures, notes: [] };
74
+ };
75
+ /** The run's coverage in one line: what was reached of everything declared. It never fails; each operation's does. */
76
+ export const coverageSummary = (model, evidence) => {
77
+ const sets = reachedIn(model, evidence);
78
+ const skip = unreachable(model);
79
+ const all = Object.values(model.operations).map((op) => required(op, skip));
80
+ const count = (xs, hit) => `${xs.filter((x) => hit.has(x)).length}/${xs.length}`;
81
+ const left = [...skip].filter((name) => Object.values(model.operations).some((op) => op.refusals.includes(name) && !op.errors.includes(name)));
82
+ const flat = (k) => [...new Set(all.flatMap((r) => r[k]))];
83
+ const notes = [`moves ${count(flat("move"), sets.moved)} · outcomes ${count(flat("outcomes"), sets.reached)} · refusals ${count([...flat("errors"), ...flat("rules")], sets.refused)} · runtime refusals ${count(flat("runtime"), sets.refused)}${left.length ? ` (not counted: ${left.join(", ")}, which no journey can cause: a step cannot send a second payload under a held request key)` : ""}`];
84
+ return { eval: "coverage", operation: undefined, failures: [], notes };
85
+ };
@@ -0,0 +1,5 @@
1
+ import type { OperationModel } from "@orthograph/compiler";
2
+ import type { Operation, Read } from "orthograph";
3
+ import type { Evidence } from "../types.ts";
4
+ /** Failures name the field and where it appeared, without including its value. */
5
+ export declare const secretsIn: (op: OperationModel, declared: Operation | Read | undefined, e: Evidence) => ReadonlyArray<string>;
@@ -0,0 +1,72 @@
1
+ import { Schema } from "effect";
2
+ import { traceable } from "orthograph/server";
3
+ import { where } from "./evidence.js";
4
+ /** A shorter value would match by chance; a value that short is caught by name only. */
5
+ const MIN = 8;
6
+ const spanMetadata = new Set(["operation", "attempt", "refusal", "defect"]);
7
+ const textOf = (v) => (typeof v === "string" ? v : typeof v === "bigint" ? v.toString() : JSON.stringify(v) ?? "");
8
+ const decodeItems = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Array(Schema.Unknown)));
9
+ const hasState = (item, state) => typeof item === "object" && item !== null && "state" in item && item.state === state;
10
+ /** An exact state also seen in the response is a returned machine label. Keep every other value searchable. */
11
+ const withoutReturnedStates = (attribute, returned, state) => {
12
+ const decoded = decodeItems(attribute);
13
+ if (decoded._tag === "None")
14
+ return attribute;
15
+ return decoded.value.map((item, index) => hasState(item, state) && hasState(returned[index], state) ? { ...item, state: undefined } : item);
16
+ };
17
+ const hiddenOf = (side, fields, declared, values) => Object.entries(fields).flatMap(([field, model]) => {
18
+ const spec = declared[field];
19
+ const reason = model.visibility !== undefined ? "not public" : spec !== undefined && !traceable(spec) ? "untraced text" : undefined;
20
+ return reason === undefined ? [] : [{ field, label: `${side}.${field}`, reason, value: textOf(values[field]) }];
21
+ });
22
+ /** Failures name the field and where it appeared, without including its value. */
23
+ export const secretsIn = (op, declared, e) => {
24
+ const body = e.call.status === 200 && typeof e.call.body === "object" && e.call.body !== null ? e.call.body : {};
25
+ const filter = e.call.payload["state"];
26
+ const items = body["items"];
27
+ const filteredList = declared?.kind === "read" && declared.by === "list" && typeof filter === "string" && Array.isArray(items)
28
+ ? { filter, items } : undefined;
29
+ const hidden = [
30
+ ...hiddenOf("payload", op.payload, declared?.payload ?? {}, e.call.payload),
31
+ ...hiddenOf("answer", op.answer, declared?.answer ?? {}, body),
32
+ ];
33
+ const names = new Map(hidden.flatMap((s) => [[s.label, s.reason], [s.field, s.reason]]));
34
+ const values = hidden.filter((s) => s.value.length >= MIN);
35
+ const found = [];
36
+ const at = (label, reason, where_) => found.push(`${where(e)}: ${label} (${reason}) appears in ${where_}`);
37
+ for (const span of e.trace.spans) {
38
+ for (const [key, v] of Object.entries(span.attrs)) {
39
+ // The operation label comes from the declaration, even if the caller happens to send the same text.
40
+ if (key === "operation" && v === op.name)
41
+ continue;
42
+ const reason = spanMetadata.has(key) ? undefined : names.get(key);
43
+ if (reason !== undefined)
44
+ at(key, reason, `span ${span.name} as the attribute ${key}`);
45
+ const returned = span === e.opSpan && key === "answer.items" && filteredList !== undefined
46
+ ? withoutReturnedStates(v, filteredList.items, filteredList.filter) : v;
47
+ for (const s of values) {
48
+ const value = s.label === "payload.state" && s.reason === "untraced text" ? returned : v;
49
+ if (textOf(value).includes(s.value))
50
+ at(s.label, s.reason, `span ${span.name}, attribute ${key}`);
51
+ }
52
+ }
53
+ }
54
+ for (const log of e.trace.logs) {
55
+ for (const s of values) {
56
+ if (log.body.includes(s.value))
57
+ at(s.label, s.reason, "a log line");
58
+ else if (Object.values(log.attrs).some((v) => textOf(v).includes(s.value)))
59
+ at(s.label, s.reason, "a log attribute");
60
+ }
61
+ for (const key of Object.keys(log.attrs)) {
62
+ const reason = names.get(key);
63
+ if (reason !== undefined)
64
+ at(key, reason, `a log attribute named ${key}`);
65
+ }
66
+ }
67
+ const journal = JSON.stringify(e.call.journal);
68
+ for (const s of values)
69
+ if (s.reason === "not public" && journal.includes(s.value))
70
+ at(s.label, s.reason, "a journal entry");
71
+ return found;
72
+ };
@@ -0,0 +1,2 @@
1
+ import type { EvalsApi } from "./types.ts";
2
+ export declare const Evals: EvalsApi;
@@ -0,0 +1,29 @@
1
+ import { answerShape, declaredErrors, events, explainability, machinePath, steps, whoMayCall } from "./internal/calls.js";
2
+ import { coverage, coverageSummary, percentile, performance } from "./internal/run.js";
3
+ import { gather, replayed, where } from "./internal/evidence.js";
4
+ /** The nine evals, in their numbered order, run for every operation. */
5
+ const PER_OPERATION = [answerShape, declaredErrors, machinePath, events, whoMayCall, steps, performance, coverage, explainability];
6
+ /**
7
+ * The evals that can be judged from telemetry alone, which is all `watch` has: no journey decided who may call, no world
8
+ * stored the state a move ended in, no journal was read, and coverage is what a whole run reached (L2.09, D3 #143).
9
+ */
10
+ const LIVE = [answerShape, declaredErrors, steps, performance, explainability];
11
+ export const Evals = {
12
+ gather,
13
+ percentile,
14
+ where: (call) => where({ call }),
15
+ judge: (project, evidence) => [
16
+ ...Object.values(project.model.operations).flatMap((op) => {
17
+ const mine = evidence.filter((e) => e.call.operation === op.name);
18
+ return PER_OPERATION.map((ev) => ev(op, mine, { project, all: evidence }));
19
+ }),
20
+ coverageSummary(project.model, evidence),
21
+ ],
22
+ judgeLive: (project, evidence) => Object.values(project.model.operations).flatMap((op) => {
23
+ const mine = evidence.filter((e) => e.call.operation === op.name);
24
+ if (mine.length === 0)
25
+ return [];
26
+ // A replayed call answers from the stored answer, not from a span: prove judges its shape.
27
+ return LIVE.map((ev) => ev(op, ev === answerShape ? mine.filter((e) => !replayed(e)) : mine, { project, all: evidence }));
28
+ }),
29
+ };
@@ -0,0 +1,12 @@
1
+ interface ModelView {
2
+ readonly refusals: Readonly<Record<string, string>>;
3
+ readonly operations: Readonly<Record<string, {
4
+ readonly errors: ReadonlyArray<string>;
5
+ readonly refusals: ReadonlyArray<string>;
6
+ }>>;
7
+ }
8
+ /** The runtime's refusals the model lists on an operation that no journey can cause: everything under `NotAllowed`'s prefix but `NotAllowed` (G3). */
9
+ export declare const leftOut: (model: ModelView) => ReadonlyArray<string>;
10
+ /** `coverage ✔ <totals>`, with the suffix when the model lists a refusal the count leaves out, and without it when it does not. */
11
+ export declare const coverageLine: (totals: string, model: ModelView) => string;
12
+ export {};
@@ -0,0 +1,15 @@
1
+ /** The runtime's refusals the model lists on an operation that no journey can cause: everything under `NotAllowed`'s prefix but `NotAllowed` (G3). */
2
+ export const leftOut = (model) => {
3
+ const prefix = model.refusals["NotAllowed"]?.split("-")[0];
4
+ if (prefix === undefined)
5
+ return [];
6
+ return Object.entries(model.refusals)
7
+ .filter(([name, code]) => name !== "NotAllowed" && code.startsWith(`${prefix}-`))
8
+ .map(([name]) => name)
9
+ .filter((name) => Object.values(model.operations).some((op) => op.refusals.includes(name) && !op.errors.includes(name)));
10
+ };
11
+ /** `coverage ✔ <totals>`, with the suffix when the model lists a refusal the count leaves out, and without it when it does not. */
12
+ export const coverageLine = (totals, model) => {
13
+ const left = leftOut(model);
14
+ return `coverage ✔ ${totals}${left.length ? ` (not counted: ${left.join(", ")}, which no journey can cause: a step cannot send a second payload under a held request key)` : ""}`;
15
+ };
@@ -0,0 +1,43 @@
1
+ import type { OperationModel } from "@orthograph/compiler";
2
+ import type { CallRecord, Project } from "#modules/journeys/types.js";
3
+ import type { Span, Trace } from "#modules/telemetry/types.js";
4
+ /** One call and everything known about it. */
5
+ export interface Evidence {
6
+ readonly call: CallRecord;
7
+ readonly trace: Trace;
8
+ /** The operation's own span, if it opened (a refused caller never opens it). */
9
+ readonly opSpan: Span | undefined;
10
+ /** The refusal's name: from the answer, or from the operation's span when the server died sending it. */
11
+ readonly refusal: string | undefined;
12
+ /** The stored state of the instance the call moved, read right after the call. */
13
+ readonly stored: string | undefined;
14
+ }
15
+ export interface Verdict {
16
+ /** `answer shape`, `declared errors`, …: the eval's name as reports print it. */
17
+ readonly eval: string;
18
+ readonly operation: string | undefined;
19
+ readonly failures: ReadonlyArray<string>;
20
+ /** Lines that inform without failing: performance numbers, reviews, coverage counts. */
21
+ readonly notes: ReadonlyArray<string>;
22
+ }
23
+ /** One eval of one operation: its own calls' evidence, and the whole run's, for the evals that look wider (coverage). */
24
+ export type PerOperation = (op: OperationModel, evidence: ReadonlyArray<Evidence>, run: {
25
+ readonly project: Project;
26
+ readonly all: ReadonlyArray<Evidence>;
27
+ }) => Verdict;
28
+ export interface EvalsApi {
29
+ /** How a failure names the call it is about: `grant-an-allowance "ada grants olga 500"`. Every failure line starts with it. */
30
+ readonly where: (call: CallRecord) => string;
31
+ /** Every eval over every operation, then coverage over the whole run. */
32
+ readonly judge: (project: Project, evidence: ReadonlyArray<Evidence>) => ReadonlyArray<Verdict>;
33
+ /**
34
+ * The evals that telemetry alone can answer, over the calls it saw: answer shape, declared errors, steps, performance and
35
+ * explainability, for each operation that has a call. Not who may call, machine path or events (they need the world's facts and
36
+ * the call's journal), and not coverage. A secret or private answer field is not checked (it is on no span).
37
+ */
38
+ readonly judgeLive: (project: Project, evidence: ReadonlyArray<Evidence>) => ReadonlyArray<Verdict>;
39
+ /** The nearest-rank percentile of an ascending list of numbers: what performance reports. */
40
+ readonly percentile: (sorted: ReadonlyArray<number>, p: number) => number;
41
+ /** The evidence for each call: its spans, its refusal and, for a move, the stored state of what moved, from the call record. */
42
+ readonly gather: (calls: ReadonlyArray<CallRecord>, traces: ReadonlyMap<string, Trace>) => ReadonlyArray<Evidence>;
43
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ import type { Model } from "@orthograph/compiler";
2
+ import type { Proof, Ran, Selection, Stamp } from "../types.ts";
3
+ /** What today's files (the stamp, taken before the run) say has to run again, measured from the record of the last proof. */
4
+ export declare const select: (stamp: Stamp, model: Model, prior: Proof | undefined, noRecord?: string) => Selection;
5
+ /** The record after a run, against the stamp taken before it: an edit made while it ran is a change the next run sees. */
6
+ export declare const settle: (stamp: Stamp, prior: Proof | undefined, ran: Ran) => Proof;
@@ -0,0 +1,34 @@
1
+ import { scenarioOf } from "#modules/verdicts/internal/proof.js";
2
+ import { differing } from "./files.js";
3
+ /** What today's files (the stamp, taken before the run) say has to run again, measured from the record of the last proof. */
4
+ export const select = (stamp, model, prior, noRecord = "no record of an earlier prove") => {
5
+ const all = Object.keys(stamp.journeys).sort();
6
+ const everything = (reason, files) => ({ rerun: all, skipped: [], judge: Object.keys(model.operations), fellBack: { reason, files } });
7
+ if (prior === undefined)
8
+ return everything(noRecord, []);
9
+ const lost = differing(prior.files, stamp.files).filter((path) => !stamp.placed.has(path));
10
+ if (lost.length > 0)
11
+ return everything(`cannot place ${lost.join(", ")}`, lost);
12
+ // An operation is judged again when what it rests on changed, or when it has not passed.
13
+ const judge = Object.keys(model.operations).filter((op) => prior.operations[op]?.inputs !== stamp.operations[op] || prior.operations[op]?.passed !== true);
14
+ const touched = new Set(judge);
15
+ const rerun = all.filter((file) => {
16
+ const record = prior.journeys[file];
17
+ return record === undefined || record.inputs !== stamp.journeys[file] || !record.passed || [...scenarioOf(model, model.journeys[file]).operationNames].some((op) => touched.has(op));
18
+ });
19
+ return { rerun, skipped: all.filter((file) => !rerun.includes(file)), judge, fellBack: null };
20
+ };
21
+ /** Each name's inputs as they were when the run began, and whether it passed: as this run judged it, else as the record had it. */
22
+ const entries = (inputs, was, now) => {
23
+ const judged = new Map(now);
24
+ return Object.fromEntries(Object.entries(inputs).flatMap(([name, hash]) => {
25
+ const passed = judged.get(name) ?? was?.[name]?.passed;
26
+ return passed === undefined ? [] : [[name, { inputs: hash, passed }]];
27
+ }));
28
+ };
29
+ /** The record after a run, against the stamp taken before it: an edit made while it ran is a change the next run sees. */
30
+ export const settle = (stamp, prior, ran) => ({
31
+ files: stamp.files,
32
+ journeys: entries(stamp.journeys, prior?.journeys, ran.journeys.map((j) => [j.file, j.passed])),
33
+ operations: entries(stamp.operations, prior?.operations, ran.operations.map((o) => [o.operation, o.passed])),
34
+ });
@@ -0,0 +1,12 @@
1
+ import { type Snapshot } from "./scan.ts";
2
+ export interface Closure {
3
+ readonly files: ReadonlySet<string>;
4
+ /** Files whose imports could not all be followed (an alias, a path outside the project, a file that is not there, a specifier that is not a literal). */
5
+ readonly opaque: ReadonlySet<string>;
6
+ /** Files that import or require something whose specifier is not a literal: what they reach could be any file, so what rests on them rests on every file. */
7
+ readonly wild: ReadonlySet<string>;
8
+ }
9
+ /** Every module specifier a source names, from imports, re-exports, `import()` and `require()`; a mention in a comment only adds an edge. */
10
+ export declare const specifiersOf: (source: string) => ReadonlyArray<string>;
11
+ /** A closure computer for a snapshot: each file's imports are read once. */
12
+ export declare const graphOf: (snap: Snapshot) => (roots: ReadonlyArray<string>) => Closure;
@@ -0,0 +1,69 @@
1
+ // The files a file can reach by importing, inside the project. Whatever cannot be followed is opaque, and a change to an
2
+ // opaque file is not placed: `prove --changed` then proves everything, naming it.
3
+ import { posix } from "node:path";
4
+ import { include } from "./scan.js";
5
+ const IMPORT = /\b(?:import|export)\s[^'"`;]*?\bfrom\s*['"]([^'"\n]+)['"]|\bimport\s*['"]([^'"\n]+)['"]|\bimport\(\s*['"]([^'"\n]+)['"]\s*\)|\brequire\(\s*['"]([^'"\n]+)['"]\s*\)/g;
6
+ const EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs", ".json"];
7
+ /** Every module specifier a source names, from imports, re-exports, `import()` and `require()`; a mention in a comment only adds an edge. */
8
+ export const specifiersOf = (source) => [...source.matchAll(IMPORT)].map((m) => m[1] ?? m[2] ?? m[3] ?? m[4]);
9
+ /** `import(x)` or `require(x)` whose argument is not a string literal: where it goes cannot be read. */
10
+ const DYNAMIC = /\b(?:import|require)\s*\(\s*(?!['"])/;
11
+ /** A file that reads files at runtime (`readFileSync(new URL("./x", import.meta.url))`, `fs`, a glob): what it reads is no import, so it rests on every file. */
12
+ const READS = /\bimport\.meta\.(?:url|dirname|filename|glob|resolve)\b|\b(?:readFile|readFileSync|readdir|readdirSync|createReadStream|readFileSync)\s*\(|\bfs\.promises\b|\bnew URL\(/;
13
+ /** The aliases a tsconfig's `paths` declares, as the prefix before their `*`: a specifier that starts with one is the project's, not a package's. */
14
+ const aliasesIn = (snap) => [...snap.sources].filter(([path]) => /(^|\/)tsconfig[^/]*\.json$/.test(path)).flatMap(([, source]) => {
15
+ const block = source.match(/"paths"\s*:\s*\{([^}]*)\}/)?.[1] ?? "";
16
+ return [...block.matchAll(/"([^"]+)"\s*:/g)].map((m) => m[1].replace(/\*.*$/, ""));
17
+ });
18
+ const candidates = (base) => {
19
+ const swapped = /\.[cm]?js$/.test(base) ? [base.replace(/\.js$/, ".ts"), base.replace(/\.js$/, ".tsx"), base.replace(/\.mjs$/, ".mts"), base.replace(/\.cjs$/, ".cts")] : [];
20
+ return [base, ...swapped, ...EXTENSIONS.map((e) => base + e), ...EXTENSIONS.map((e) => `${base}/index${e}`)];
21
+ };
22
+ const resolve = (snap, aliases, from, spec) => {
23
+ if (spec.startsWith("node:"))
24
+ return { kind: "package" };
25
+ if (!spec.startsWith("."))
26
+ return spec.startsWith("#") || spec.startsWith("~/") || spec.startsWith("@/") || aliases.some((a) => a !== "" && spec.startsWith(a)) ? { kind: "unknown" } : { kind: "package" };
27
+ const base = posix.normalize(posix.join(posix.dirname(from), spec));
28
+ if (base.startsWith("..") || posix.isAbsolute(base))
29
+ return { kind: "unknown" };
30
+ if (base.split("/").includes("node_modules"))
31
+ return { kind: "package" };
32
+ const path = candidates(base).find((candidate) => include(snap, candidate));
33
+ return path === undefined ? { kind: "unknown" } : { kind: "file", path };
34
+ };
35
+ /** A closure computer for a snapshot: each file's imports are read once. */
36
+ export const graphOf = (snap) => {
37
+ const aliases = aliasesIn(snap);
38
+ const memo = new Map();
39
+ const edges = (file) => {
40
+ const known = memo.get(file);
41
+ if (known !== undefined)
42
+ return known;
43
+ const source = snap.sources.get(file);
44
+ const found = (source === undefined ? [] : specifiersOf(source)).map((spec) => resolve(snap, aliases, file, spec));
45
+ const dynamic = source !== undefined && DYNAMIC.test(source);
46
+ const wild = dynamic || (source !== undefined && READS.test(source));
47
+ const made = { deps: found.flatMap((f) => (f.kind === "file" ? [f.path] : [])), opaque: dynamic || found.some((f) => f.kind === "unknown"), wild };
48
+ memo.set(file, made);
49
+ return made;
50
+ };
51
+ return (roots) => {
52
+ const files = new Set();
53
+ const opaque = new Set();
54
+ const wild = new Set();
55
+ const queue = roots.filter((r) => snap.hashes.has(r));
56
+ for (const file of queue) {
57
+ if (files.has(file))
58
+ continue;
59
+ files.add(file);
60
+ const { deps, opaque: lost, wild: loose } = edges(file);
61
+ if (lost)
62
+ opaque.add(file);
63
+ if (loose)
64
+ wild.add(file);
65
+ queue.push(...deps);
66
+ }
67
+ return { files, opaque, wild };
68
+ };
69
+ };
@@ -0,0 +1 @@
1
+ export declare const digest: (text: string | Uint8Array) => string;
@@ -0,0 +1,2 @@
1
+ import { createHash } from "node:crypto";
2
+ export const digest = (text) => createHash("sha256").update(text).digest("hex");
@@ -0,0 +1,11 @@
1
+ import { type Model } from "@orthograph/compiler";
2
+ import type { Stamp } from "../types.ts";
3
+ /**
4
+ * Take the stamp: hash every file that can change a proof, once. An operation rests on its declaration and its handler and
5
+ * every file they reach by importing (inside the project), and on what `Compare.dependsOn` tracks (things, mounts). A journey
6
+ * rests on its file, the starting worlds it stands on, what those reach, and the operations they call. A file that is in no
7
+ * such closure, or whose imports could not all be followed, is not placed: a change to it proves everything.
8
+ */
9
+ export declare const stampOf: (root: string, model: Model) => Stamp;
10
+ /** The files that differ between two records: changed, added or removed. */
11
+ export declare const differing: (was: Readonly<Record<string, string>>, now: Readonly<Record<string, string>>) => ReadonlyArray<string>;
@@ -0,0 +1,48 @@
1
+ // What a proof rests on, read once: the project's files by content hash, the files the model places (those some operation,
2
+ // journey or starting world reaches by importing), and each operation's and journey's inputs from them.
3
+ import { Compare, handlerFiles } from "@orthograph/compiler";
4
+ import { handlerHash, scenarioOf } from "#modules/verdicts/internal/proof.js";
5
+ import { graphOf } from "./closure.js";
6
+ import { digest, scan } from "./scan.js";
7
+ const sorted = (files) => [...files].sort();
8
+ /**
9
+ * Take the stamp: hash every file that can change a proof, once. An operation rests on its declaration and its handler and
10
+ * every file they reach by importing (inside the project), and on what `Compare.dependsOn` tracks (things, mounts). A journey
11
+ * rests on its file, the starting worlds it stands on, what those reach, and the operations they call. A file that is in no
12
+ * such closure, or whose imports could not all be followed, is not placed: a change to it proves everything.
13
+ */
14
+ export const stampOf = (root, model) => {
15
+ const snap = scan(root);
16
+ const closure = graphOf(snap);
17
+ // What reaches a file that imports by a specifier it cannot read rests on every file: its real target could be any of them.
18
+ const through = (reached) => sorted(reached.wild.size > 0 ? new Set(snap.hashes.keys()) : reached.files).map((file) => [file, snap.hashes.get(file) ?? null]);
19
+ const operations = new Map();
20
+ for (const [name, op] of Object.entries(model.operations)) {
21
+ const roots = [op.file, ...handlerFiles(op).map((h) => h.file)];
22
+ const reached = closure(roots);
23
+ // A plugin's declaration and handler live in its package, outside the project: what the model and the handler's hash say stands in.
24
+ const outside = roots.filter((r) => !snap.hashes.has(r)).map((r) => (r === op.file ? op.hash : handlerHash(root, op) ?? null));
25
+ operations.set(name, { closure: reached, inputs: digest(JSON.stringify([through(reached), outside, Compare.dependsOn(model, name)])) });
26
+ }
27
+ const journeys = new Map();
28
+ for (const journey of Object.values(model.journeys)) {
29
+ const scenario = scenarioOf(model, journey);
30
+ const roots = [journey.file, ...scenario.worlds.map((w) => w.file)];
31
+ const reached = closure(roots);
32
+ const outside = roots.filter((r) => !snap.hashes.has(r)).map((r) => (r === journey.file ? journey.sourceHash : scenario.worlds.find((w) => w.file === r)?.sourceHash) ?? null);
33
+ const calls = [...scenario.operationNames].sort().map((name) => operations.get(name)?.inputs ?? name);
34
+ journeys.set(journey.file, { closure: reached, inputs: digest(JSON.stringify([through(reached), outside, calls])) });
35
+ }
36
+ // The starting worlds are roots too, whether or not a journey stands on one.
37
+ const worlds = Object.values(model.startingWorlds).map((w) => closure([w.file]));
38
+ const closures = [...operations.values(), ...journeys.values()].map((x) => x.closure).concat(worlds);
39
+ const placed = new Set(closures.flatMap((c) => [...c.files].filter((file) => !c.opaque.has(file))));
40
+ return {
41
+ files: Object.fromEntries([...snap.hashes].sort(([a], [b]) => a.localeCompare(b))),
42
+ placed,
43
+ operations: Object.fromEntries([...operations].map(([name, x]) => [name, x.inputs])),
44
+ journeys: Object.fromEntries([...journeys].filter(([file]) => model.journeys[file]?.blanks === undefined).map(([file, x]) => [file, x.inputs])),
45
+ };
46
+ };
47
+ /** The files that differ between two records: changed, added or removed. */
48
+ export const differing = (was, now) => [...new Set([...Object.keys(was), ...Object.keys(now)])].filter((path) => was[path] !== now[path]).sort();
@@ -0,0 +1,5 @@
1
+ import type { Ledger } from "../types.ts";
2
+ export declare const ledgerPath: (root: string) => string;
3
+ /** The ledger on disk; a file that is not JSON, or not a ledger, is as good as none. A `changed` section that is malformed is dropped. */
4
+ export declare const readLedger: (root: string) => Ledger | undefined;
5
+ export declare const writeLedger: (root: string, ledger: Ledger) => void;
@@ -0,0 +1,25 @@
1
+ import { Names } from "orthograph/server";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { Effect } from "effect";
5
+ export const ledgerPath = (root) => join(root, Names.folder, "evidence/proven.json");
6
+ const record = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
7
+ const judged = (x) => record(x) && typeof x["inputs"] === "string" && typeof x["passed"] === "boolean";
8
+ const entries = (x, ok) => record(x) && Object.values(x).every(ok);
9
+ /** The `changed` section, or undefined when it is not one: a partial or old record is no record. */
10
+ const proofOf = (x) => record(x) && entries(x["files"], (v) => typeof v === "string") && entries(x["journeys"], judged) && entries(x["operations"], judged) ? x : undefined;
11
+ /** The ledger on disk; a file that is not JSON, or not a ledger, is as good as none. A `changed` section that is malformed is dropped. */
12
+ export const readLedger = (root) => {
13
+ if (!existsSync(ledgerPath(root)))
14
+ return undefined;
15
+ const read = Effect.runSync(Effect.try(() => JSON.parse(readFileSync(ledgerPath(root), "utf8"))).pipe(Effect.orElseSucceed(() => undefined)));
16
+ if (!record(read) || !record(read["model"]) || !record(read["proven"]))
17
+ return undefined;
18
+ const { changed, ...rest } = read;
19
+ const proof = proofOf(changed);
20
+ return { ...rest, ...(proof === undefined ? {} : { changed: proof }) };
21
+ };
22
+ export const writeLedger = (root, ledger) => {
23
+ mkdirSync(dirname(ledgerPath(root)), { recursive: true });
24
+ writeFileSync(ledgerPath(root), JSON.stringify(ledger, null, 2) + "\n");
25
+ };
@@ -0,0 +1,4 @@
1
+ /** What a record names a linked package's file by: the same wherever the project sits. */
2
+ export declare const packageKey: (name: string, path: string) => string;
3
+ /** The files of every linked package the project (and its workspace) depends on, by key, with a hash of each. */
4
+ export declare const linkedFiles: (root: string, workspace: string | undefined) => ReadonlyMap<string, string>;
@@ -0,0 +1,56 @@
1
+ // Packages the project runs from source it does not own: a workspace sibling, a `link:` or `file:` dependency, any symlink
2
+ // that leaves the package store. A lockfile does not change when their files do, so their files are hashed, and a change to
3
+ // one is never placed: `prove --changed` proves everything and names the package.
4
+ import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import { Effect } from "effect";
7
+ import { digest } from "./digest.js";
8
+ /** What a record names a linked package's file by: the same wherever the project sits. */
9
+ export const packageKey = (name, path) => `<package:${name}>/${path}`;
10
+ const LOCAL = /^(workspace|link|file):/;
11
+ const quiet = (name) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(name) || name.endsWith(".md");
12
+ const manifestOf = (dir) => Effect.runSync(Effect.try(() => JSON.parse(readFileSync(join(dir, "package.json"), "utf8"))).pipe(Effect.orElseSucceed(() => ({}))));
13
+ const declared = (dir) => {
14
+ const m = manifestOf(dir);
15
+ return Object.entries({ ...m.optionalDependencies, ...m.devDependencies, ...m.dependencies });
16
+ };
17
+ /** Where `name` is installed for a package at `from`: its own node_modules, then each folder above's, as node looks. */
18
+ const installed = (from, name) => {
19
+ for (let dir = from;; dir = dirname(dir)) {
20
+ const found = join(dir, "node_modules", name);
21
+ if (existsSync(found))
22
+ return found;
23
+ if (dir === dirname(dir))
24
+ return undefined;
25
+ }
26
+ };
27
+ const filesOf = (dir, within = "") => readdirSync(join(dir, within), { withFileTypes: true }).flatMap((entry) => {
28
+ if (entry.name === "node_modules" || entry.name.startsWith("."))
29
+ return [];
30
+ const path = within === "" ? entry.name : `${within}/${entry.name}`;
31
+ return entry.isDirectory() ? filesOf(dir, path) : entry.isFile() && !quiet(entry.name) ? [path] : [];
32
+ });
33
+ /** The files of every linked package the project (and its workspace) depends on, by key, with a hash of each. */
34
+ export const linkedFiles = (root, workspace) => {
35
+ const found = new Map();
36
+ const seen = new Set();
37
+ const visit = (from, name, spec) => {
38
+ const path = installed(from, name);
39
+ if (path === undefined)
40
+ return;
41
+ const real = realpathSync(path);
42
+ // A symlink into the package store is an installed package, and the lockfile says which; any other is source someone edits.
43
+ const linked = LOCAL.test(spec) || (lstatSync(path).isSymbolicLink() && !real.split("/").includes(".pnpm"));
44
+ if (!linked || seen.has(real))
45
+ return;
46
+ seen.add(real);
47
+ for (const file of filesOf(real))
48
+ found.set(packageKey(name, file), digest(readFileSync(join(real, file))));
49
+ for (const [dep, wanted] of declared(real))
50
+ visit(real, dep, wanted);
51
+ };
52
+ for (const dir of [root, ...(workspace === undefined ? [] : [workspace])])
53
+ for (const [name, spec] of declared(dir))
54
+ visit(root, name, spec);
55
+ return found;
56
+ };