@orthograph/language-effect 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 (141) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +2 -2
  3. package/dist/device.d.ts +5 -0
  4. package/dist/device.js +6 -0
  5. package/dist/index.d.ts +30 -0
  6. package/dist/index.js +25 -0
  7. package/dist/modules/access/internal/path.d.ts +3 -0
  8. package/dist/modules/access/internal/path.js +11 -0
  9. package/dist/modules/access/service.d.ts +5 -0
  10. package/dist/modules/access/service.js +111 -0
  11. package/dist/modules/access/types.d.ts +38 -0
  12. package/dist/modules/access/types.js +3 -0
  13. package/dist/modules/auth/service.d.ts +4 -0
  14. package/dist/modules/auth/service.js +19 -0
  15. package/dist/modules/auth/types.d.ts +38 -0
  16. package/dist/modules/auth/types.js +8 -0
  17. package/dist/modules/calls/internal/run.d.ts +2 -0
  18. package/dist/modules/calls/internal/run.js +28 -0
  19. package/dist/modules/calls/service.d.ts +2 -0
  20. package/dist/modules/calls/service.js +2 -0
  21. package/dist/modules/calls/types.d.ts +32 -0
  22. package/dist/modules/calls/types.js +1 -0
  23. package/dist/modules/handler/internal/attributes.d.ts +17 -0
  24. package/dist/modules/handler/internal/attributes.js +46 -0
  25. package/dist/modules/handler/internal/call-id.d.ts +2 -0
  26. package/dist/modules/handler/internal/call-id.js +5 -0
  27. package/dist/modules/handler/internal/call-metrics.d.ts +17 -0
  28. package/dist/modules/handler/internal/call-metrics.js +35 -0
  29. package/dist/modules/handler/internal/decided.d.ts +14 -0
  30. package/dist/modules/handler/internal/decided.js +106 -0
  31. package/dist/modules/handler/internal/defect.d.ts +4 -0
  32. package/dist/modules/handler/internal/defect.js +19 -0
  33. package/dist/modules/handler/internal/derived.d.ts +21 -0
  34. package/dist/modules/handler/internal/derived.js +96 -0
  35. package/dist/modules/handler/internal/device.d.ts +3 -0
  36. package/dist/modules/handler/internal/device.js +46 -0
  37. package/dist/modules/handler/internal/digest.d.ts +3 -0
  38. package/dist/modules/handler/internal/digest.js +52 -0
  39. package/dist/modules/handler/internal/environment.d.ts +3 -0
  40. package/dist/modules/handler/internal/environment.js +3 -0
  41. package/dist/modules/handler/internal/invariants.d.ts +12 -0
  42. package/dist/modules/handler/internal/invariants.js +28 -0
  43. package/dist/modules/handler/internal/move.d.ts +32 -0
  44. package/dist/modules/handler/internal/move.js +84 -0
  45. package/dist/modules/handler/internal/prehandle.d.ts +23 -0
  46. package/dist/modules/handler/internal/prehandle.js +34 -0
  47. package/dist/modules/handler/internal/read.d.ts +3 -0
  48. package/dist/modules/handler/internal/read.js +79 -0
  49. package/dist/modules/handler/internal/signal.d.ts +3 -0
  50. package/dist/modules/handler/internal/signal.js +10 -0
  51. package/dist/modules/handler/internal/span.d.ts +8 -0
  52. package/dist/modules/handler/internal/span.js +14 -0
  53. package/dist/modules/handler/service.d.ts +7 -0
  54. package/dist/modules/handler/service.js +163 -0
  55. package/dist/modules/handler/types.d.ts +217 -0
  56. package/dist/modules/handler/types.js +24 -0
  57. package/dist/modules/ids/service.d.ts +2 -0
  58. package/dist/modules/ids/service.js +11 -0
  59. package/dist/modules/ids/types.d.ts +8 -0
  60. package/dist/modules/ids/types.js +1 -0
  61. package/dist/modules/journal/service.d.ts +6 -0
  62. package/dist/modules/journal/service.js +4 -0
  63. package/dist/modules/journal/types.d.ts +22 -0
  64. package/dist/modules/journal/types.js +5 -0
  65. package/dist/modules/mcp/internal/input.d.ts +15 -0
  66. package/dist/modules/mcp/internal/input.js +35 -0
  67. package/dist/modules/mcp/internal/output.d.ts +16 -0
  68. package/dist/modules/mcp/internal/output.js +50 -0
  69. package/dist/modules/mcp/internal/tool.d.ts +4 -0
  70. package/dist/modules/mcp/internal/tool.js +56 -0
  71. package/dist/modules/mcp/service.d.ts +2 -0
  72. package/dist/modules/mcp/service.js +38 -0
  73. package/dist/modules/mcp/types.d.ts +101 -0
  74. package/dist/modules/mcp/types.js +1 -0
  75. package/dist/modules/mount/internal/none.d.ts +2 -0
  76. package/dist/modules/mount/internal/none.js +1 -0
  77. package/dist/modules/mount/service.d.ts +2 -0
  78. package/dist/modules/mount/service.js +12 -0
  79. package/dist/modules/mount/types.d.ts +11 -0
  80. package/dist/modules/mount/types.js +4 -0
  81. package/dist/modules/principals/service.d.ts +4 -0
  82. package/dist/modules/principals/service.js +4 -0
  83. package/dist/modules/principals/types.d.ts +15 -0
  84. package/dist/modules/principals/types.js +4 -0
  85. package/dist/modules/records/internal/holder.d.ts +16 -0
  86. package/dist/modules/records/internal/holder.js +55 -0
  87. package/dist/modules/records/internal/list.d.ts +12 -0
  88. package/dist/modules/records/internal/list.js +65 -0
  89. package/dist/modules/records/internal/order.d.ts +18 -0
  90. package/dist/modules/records/internal/order.js +41 -0
  91. package/dist/modules/records/internal/unique.d.ts +31 -0
  92. package/dist/modules/records/internal/unique.js +49 -0
  93. package/dist/modules/records/internal/unit.d.ts +3 -0
  94. package/dist/modules/records/internal/unit.js +135 -0
  95. package/dist/modules/records/service.d.ts +22 -0
  96. package/dist/modules/records/service.js +102 -0
  97. package/dist/modules/records/types.d.ts +170 -0
  98. package/dist/modules/records/types.js +9 -0
  99. package/dist/modules/timers/internal/world.d.ts +4 -0
  100. package/dist/modules/timers/internal/world.js +64 -0
  101. package/dist/modules/timers/service.d.ts +18 -0
  102. package/dist/modules/timers/service.js +125 -0
  103. package/dist/modules/timers/types.d.ts +102 -0
  104. package/dist/modules/timers/types.js +40 -0
  105. package/dist/modules/versions/internal/handlers.d.ts +6 -0
  106. package/dist/modules/versions/internal/handlers.js +36 -0
  107. package/dist/modules/versions/internal/keep.d.ts +21 -0
  108. package/dist/modules/versions/internal/keep.js +36 -0
  109. package/dist/modules/versions/service.d.ts +2 -0
  110. package/dist/modules/versions/service.js +14 -0
  111. package/dist/modules/versions/types.d.ts +27 -0
  112. package/dist/modules/versions/types.js +1 -0
  113. package/dist/modules/visibility/internal/rule.d.ts +7 -0
  114. package/dist/modules/visibility/internal/rule.js +23 -0
  115. package/dist/modules/visibility/internal/schema.d.ts +5 -0
  116. package/dist/modules/visibility/internal/schema.js +12 -0
  117. package/dist/modules/visibility/service.d.ts +15 -0
  118. package/dist/modules/visibility/service.js +27 -0
  119. package/dist/modules/visibility/types.d.ts +60 -0
  120. package/dist/modules/visibility/types.js +1 -0
  121. package/dist/modules/wire/internal/call-telemetry.d.ts +15 -0
  122. package/dist/modules/wire/internal/call-telemetry.js +31 -0
  123. package/dist/modules/wire/internal/refused-payload.d.ts +7 -0
  124. package/dist/modules/wire/internal/refused-payload.js +25 -0
  125. package/dist/modules/wire/internal/shown.d.ts +9 -0
  126. package/dist/modules/wire/internal/shown.js +32 -0
  127. package/dist/modules/wire/service.d.ts +3 -0
  128. package/dist/modules/wire/service.js +14 -0
  129. package/dist/modules/wire/types.d.ts +30 -0
  130. package/dist/modules/wire/types.js +1 -0
  131. package/dist/modules/work/internal/fake-world.d.ts +17 -0
  132. package/dist/modules/work/internal/fake-world.js +43 -0
  133. package/dist/modules/work/internal/fibers.d.ts +2 -0
  134. package/dist/modules/work/internal/fibers.js +5 -0
  135. package/dist/modules/work/service.d.ts +6 -0
  136. package/dist/modules/work/service.js +249 -0
  137. package/dist/modules/work/types.d.ts +103 -0
  138. package/dist/modules/work/types.js +19 -0
  139. package/dist/visibility.d.ts +1 -0
  140. package/dist/visibility.js +3 -0
  141. package/package.json +34 -3
@@ -0,0 +1,101 @@
1
+ import type { Effect } from "effect";
2
+ import type { FieldsInput, Operation, Principal, Read, Thing } from "orthograph";
3
+ import type { Store } from "#modules/records/types.js";
4
+ /** What a tool calls: an operation, a read by id, or a list read (whose payload and answer differ from a read by id). */
5
+ export type McpOperation = Operation | Read<Thing, unknown, unknown>;
6
+ /** What the generated `mcp` catalog says of each operation and read, by its name (`allowance.get`). */
7
+ export interface McpEntry {
8
+ readonly description: string;
9
+ readonly operation: McpOperation;
10
+ /** The states of the thing's machine, when it has one: a `state` in the answer is one of them. */
11
+ readonly states?: ReadonlyArray<string>;
12
+ /** The move the operation makes, when it makes one: the tool lists it, so an agent knows which states a call moves between. */
13
+ readonly move?: McpMove;
14
+ }
15
+ /** A move of the thing's machine, as a tool lists it. */
16
+ export interface McpMove {
17
+ readonly key: string;
18
+ readonly from: ReadonlyArray<string>;
19
+ readonly to: ReadonlyArray<string>;
20
+ readonly emits: string;
21
+ }
22
+ /** One refusal's row of the generated `refusals` table: its code, the CLI's exit and the HTTP status (K16, M1.47). */
23
+ export interface McpRefusalRow {
24
+ readonly code: string;
25
+ readonly exit: number;
26
+ readonly status: number;
27
+ }
28
+ /** The refusals of a project: each one's code, the declared error's fields (a machine's own refusal has none declared), and the table. */
29
+ export interface McpRefusals {
30
+ readonly codes: {
31
+ readonly [tag: string]: string;
32
+ };
33
+ readonly declared: {
34
+ readonly [tag: string]: {
35
+ readonly fields: FieldsInput;
36
+ };
37
+ };
38
+ /** The generated `refusals` table: a refusal's result carries its row, so an agent tells a refusal from a defect without parsing. */
39
+ readonly table?: {
40
+ readonly [tag: string]: McpRefusalRow;
41
+ };
42
+ }
43
+ /** What a tool answers: MCP content, `isError` for a refusal. */
44
+ export interface McpResult {
45
+ readonly isError: boolean;
46
+ /** The answer as one line of JSON (bigints as text), or the refusal's `[AL-001] Name { field: value }`. */
47
+ readonly text: string;
48
+ /** The answer's shown fields; for a refusal, `{ refusal, code, exit, status }` and the fields the caller may see. */
49
+ readonly structured?: {
50
+ readonly [field: string]: unknown;
51
+ };
52
+ }
53
+ export interface McpTool<R> {
54
+ readonly name: string;
55
+ readonly description: string;
56
+ /** JSON Schema of the arguments: the operation's payload, from the model's declaration, its public fields only. */
57
+ readonly input: {
58
+ readonly [key: string]: unknown;
59
+ };
60
+ /** JSON Schema of the answer an agent is shown (M1.37); absent when the answer has no fields. */
61
+ readonly output?: {
62
+ readonly [key: string]: unknown;
63
+ };
64
+ /** The move the call makes (`_meta` in `tools/list`), when it makes one. */
65
+ readonly move?: McpMove;
66
+ /** A read changes nothing. */
67
+ readonly readOnly: boolean;
68
+ /** Some `allowed` entry admits an agent: only then is an agent shown the tool. Absent: shown. */
69
+ readonly agentTool?: boolean;
70
+ /** Never fails: a refusal is a result, and a defect is told as `[AR-500]` without its detail. */
71
+ readonly call: (args: {
72
+ readonly [field: string]: unknown;
73
+ }, principal: Principal) => Effect.Effect<McpResult, never, R>;
74
+ }
75
+ /** An operation or read served: `run` takes the payload already decoded, as the API's handlers do. */
76
+ export interface McpServed<R> {
77
+ readonly run: (payload: never, principal: Principal) => Effect.Effect<unknown, unknown, R>;
78
+ }
79
+ export interface McpApi {
80
+ /** One tool for each entry of the catalog, each calling its served operation. */
81
+ readonly tools: <R>(spec: {
82
+ readonly catalog: {
83
+ readonly [name: string]: McpEntry;
84
+ };
85
+ readonly served: {
86
+ readonly [name: string]: McpServed<R>;
87
+ };
88
+ readonly refusals: McpRefusals;
89
+ }) => ReadonlyArray<McpTool<R | Store>>;
90
+ /**
91
+ * Answer one MCP request, stateless: a server made for it and let go, the caller already known. `run` is how the host
92
+ * runs a tool's effect (its services, its tracing). Initialize, `tools/list` and `tools/call` are all it speaks.
93
+ */
94
+ readonly handle: <R>(spec: {
95
+ readonly name: string;
96
+ readonly version: string;
97
+ readonly tools: ReadonlyArray<McpTool<R>>;
98
+ readonly principal: Principal;
99
+ readonly run: (effect: Effect.Effect<McpResult, never, R>) => Promise<McpResult>;
100
+ }, request: Request) => Promise<Response>;
101
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import type { Mount } from "orthograph";
2
+ export declare const noMount: Pick<Mount, "verbs">;
@@ -0,0 +1 @@
1
+ export const noMount = { verbs: [] };
@@ -0,0 +1,2 @@
1
+ import { type MountApi } from "./types.ts";
2
+ export declare const Mount: MountApi;
@@ -0,0 +1,12 @@
1
+ import { Effect } from "effect";
2
+ import { Mounts } from "orthograph/server";
3
+ import { Mounted } from "./types.js";
4
+ import { noMount } from "./internal/none.js";
5
+ export const Mount = {
6
+ picked: (option) => Effect.gen(function* () {
7
+ const mount = yield* Mounted;
8
+ return Mounts.picked(mount ?? noMount, option);
9
+ }),
10
+ under: (mount) => (effect) => Effect.provideService(effect, Mounted, mount),
11
+ serving: (mount, handler) => (...args) => Effect.provideService(handler(...args), Mounted, mount),
12
+ };
@@ -0,0 +1,11 @@
1
+ import { Context, type Effect } from "effect";
2
+ import type { Mount as MountOf, Option } from "orthograph";
3
+ export declare const Mounted: Context.Reference<Pick<MountOf<import("orthograph").Plugin>, "verbs"> | undefined>;
4
+ export interface MountApi {
5
+ /** Whether the app that mounted this plugin picked `option`: by identity, never by a written name. */
6
+ readonly picked: (option: Option) => Effect.Effect<boolean>;
7
+ /** Run a plugin's handler under its app's mount: the generated server does this for each plugin operation. */
8
+ readonly under: (mount: Pick<MountOf, "verbs">) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
9
+ /** A plugin's handler, every call of it run under `mount`: what the generated server serves for a plugin operation. */
10
+ readonly serving: <P extends ReadonlyArray<unknown>, A, E, R>(mount: Pick<MountOf, "verbs">, handler: (...args: P) => Effect.Effect<A, E, R>) => (...args: P) => Effect.Effect<A, E, R>;
11
+ }
@@ -0,0 +1,4 @@
1
+ // The mount a plugin's handler runs under: which options the app picked. A reference, so it is never a requirement a
2
+ // handler has to declare; outside any mount (a plugin's own example app) every choice is at its first option.
3
+ import { Context } from "effect";
4
+ export const Mounted = Context.Reference("@orthograph/language-effect/Mounted", { defaultValue: () => undefined });
@@ -0,0 +1,4 @@
1
+ import { Layer } from "effect";
2
+ import { Principals } from "./types.ts";
3
+ /** Everyone is anonymous. The world's signed tokens replace it in `ortho dev` (L1.14); Better Auth in stage two. */
4
+ export declare const PrincipalsAnonymous: Layer.Layer<Principals, never, never>;
@@ -0,0 +1,4 @@
1
+ import { Effect, Layer } from "effect";
2
+ import { Principals } from "./types.js";
3
+ /** Everyone is anonymous. The world's signed tokens replace it in `ortho dev` (L1.14); Better Auth in stage two. */
4
+ export const PrincipalsAnonymous = Layer.succeed(Principals, Principals.of({ of: () => Effect.succeed({ kind: "anonymous" }) }));
@@ -0,0 +1,15 @@
1
+ import { Context, type Effect } from "effect";
2
+ import type { Principal } from "orthograph";
3
+ /** Where a request came in: the HTTP API, or the MCP server. */
4
+ export type PrincipalDoor = "api" | "mcp";
5
+ declare const Principals_base: Context.ServiceClass<Principals, "@orthograph/language-effect/Principals", {
6
+ /**
7
+ * The principal behind an `Authorization` header, or anonymous. A bad credential is anonymous, never an error. `door` is where the
8
+ * request came in (M2-auth, "Smaller calls" 3): at `mcp` every credential makes an agent for its person; at `api`, the default,
9
+ * a credential made for an agent is one, and the rest are people by the way they signed in.
10
+ */
11
+ readonly of: (authorization: string | undefined, door?: PrincipalDoor) => Effect.Effect<Principal>;
12
+ }>;
13
+ export declare class Principals extends Principals_base {
14
+ }
15
+ export {};
@@ -0,0 +1,4 @@
1
+ // Who is calling. The host turns a request's credentials into a principal before any role or handler sees it.
2
+ import { Context } from "effect";
3
+ export class Principals extends Context.Service()("@orthograph/language-effect/Principals") {
4
+ }
@@ -0,0 +1,16 @@
1
+ import { Effect } from "effect";
2
+ import type { Thing } from "orthograph";
3
+ import { type Rule } from "./unique.ts";
4
+ import type { Instance, Store } from "../types.ts";
5
+ /** The call's held rows by rule and key, in the order they were written: built once per check, so a lookup is one map read. */
6
+ export type HeldIndex = ReadonlyMap<string, ReadonlyMap<string, ReadonlyArray<string>>>;
7
+ /** Index every row this call wrote under each rule of its thing: a row is read once, and its key worked out once per rule. */
8
+ export declare const indexHeld: (rulesOf: (thing: Thing) => ReadonlyArray<Rule>, find: (thing: Thing, id: string) => Effect.Effect<Instance | undefined>, held: ReadonlyArray<{
9
+ readonly thing: Thing;
10
+ readonly id: string;
11
+ }>) => Effect.Effect<HeldIndex>;
12
+ /**
13
+ * `holder(rule, row, except)`: the instance holding the key `row` fixes under the rule, leaving out the one named `except` (the row asking). The store's
14
+ * candidates are asked for per state of the scope and judged as this call left them; then the rows this call wrote itself (through `index` when given).
15
+ */
16
+ export declare const holderOf: (store: Store["Service"], find: (thing: Thing, id: string) => Effect.Effect<Instance | undefined>, written: (thing: Thing) => ReadonlyArray<string>) => (rule: Rule, row: Instance, except: string | undefined, index?: HeldIndex) => Effect.Effect<Instance | undefined>;
@@ -0,0 +1,55 @@
1
+ // Who holds a key: the one instance in a rule's scope with this key, as one call's writes leave it, else as the store has it.
2
+ import { Effect } from "effect";
3
+ import { holds, inScope, ruleKey } from "./unique.js";
4
+ /** Index every row this call wrote under each rule of its thing: a row is read once, and its key worked out once per rule. */
5
+ export const indexHeld = (rulesOf, find, held) => Effect.gen(function* () {
6
+ const index = new Map();
7
+ for (const { thing, id } of held) {
8
+ const rules = rulesOf(thing);
9
+ if (rules.length === 0)
10
+ continue;
11
+ const current = yield* find(thing, id);
12
+ if (!current)
13
+ continue;
14
+ for (const rule of rules) {
15
+ if (!inScope(rule, current))
16
+ continue;
17
+ const byKey = index.get(rule.name) ?? index.set(rule.name, new Map()).get(rule.name);
18
+ const key = ruleKey(rule, current);
19
+ const ids = byKey.get(key);
20
+ if (ids)
21
+ ids.push(id);
22
+ else
23
+ byKey.set(key, [id]);
24
+ }
25
+ }
26
+ return index;
27
+ });
28
+ /**
29
+ * `holder(rule, row, except)`: the instance holding the key `row` fixes under the rule, leaving out the one named `except` (the row asking). The store's
30
+ * candidates are asked for per state of the scope and judged as this call left them; then the rows this call wrote itself (through `index` when given).
31
+ */
32
+ export const holderOf = (store, find, written) => (rule, row, except, index) => Effect.gen(function* () {
33
+ const key = ruleKey(rule, row);
34
+ const where = Object.fromEntries(rule.fields.map((f) => [f, row[f]]));
35
+ for (const state of rule.scope ?? [undefined]) {
36
+ // One more than asked for, so the row asking can be one of them and another still shows.
37
+ const { items } = yield* store.list({ thing: rule.thing, where, state, order: "oldest", limit: except === undefined ? 1 : 2, after: undefined });
38
+ for (const item of items) {
39
+ if (String(item["id"]) === except)
40
+ continue;
41
+ const current = yield* find(rule.thing, String(item["id"]));
42
+ if (current && holds(rule, current, key))
43
+ return current;
44
+ }
45
+ }
46
+ // With an index (one check's), the rows this call wrote under this key are one read away; without one, every written row is looked at.
47
+ for (const id of index ? (index.get(rule.name)?.get(key) ?? []) : written(rule.thing)) {
48
+ if (id === except)
49
+ continue;
50
+ const current = yield* find(rule.thing, id);
51
+ if (current && holds(rule, current, key))
52
+ return current;
53
+ }
54
+ return undefined;
55
+ });
@@ -0,0 +1,12 @@
1
+ import { Effect } from "effect";
2
+ import type { Thing } from "orthograph";
3
+ import type { Instance, ListQuery, ListRead, Listed, Store, Stored } from "../types.ts";
4
+ /** Does `instance` match `where` and `state`? A field compares by what the store writes; a key the thing has no field for, as text. */
5
+ export declare const matches: (thing: Thing, where: Instance, state: string | undefined, instance: Instance) => boolean;
6
+ export declare const listerOf: (store: Store["Service"], find: (thing: Thing, id: string) => Effect.Effect<Instance | undefined>, seen: (thing: Thing) => Map<string, Stored | undefined>, held: (thing: Thing) => ReadonlyArray<{
7
+ readonly id: string;
8
+ readonly kind: "insert" | "update";
9
+ }>) => {
10
+ list: ({ thing, where, state, order, limit, after }: ListQuery) => Effect.Effect<Listed>;
11
+ lists: Effect.Effect<readonly ListRead[], never, never>;
12
+ };
@@ -0,0 +1,65 @@
1
+ // #764: a list as one call sees it. The store is paged to the end, so every row the list matches is known, and each counts as read: the commit carries
2
+ // them, and the store refuses it when they moved. This call's own writes are laid over the rows the way `find` lays them over one; then the page is cut.
3
+ import { Effect } from "effect";
4
+ import { keyOf } from "./unique.js";
5
+ /** How many rows one store page asks for while the list pages to the end. */
6
+ const PAGE = 1000;
7
+ /** Does `instance` match `where` and `state`? A field compares by what the store writes; a key the thing has no field for, as text. */
8
+ export const matches = (thing, where, state, instance) => Object.entries(where).every(([k, v]) => (k in thing.fields ? keyOf(thing, k, instance[k]) === keyOf(thing, k, v) : String(instance[k]) === String(v)))
9
+ && (state === undefined || instance.state === state);
10
+ const cursorOf = ([own, n]) => (own === 0 ? String(n) : `new:${n}`);
11
+ const rankOf = (cursor) => (cursor.startsWith("new:") ? [1, Number(cursor.slice(4))] : [0, Number(cursor)]);
12
+ const earlier = (a, b) => (a[0] !== b[0] ? a[0] < b[0] : a[1] < b[1]);
13
+ /** The same list asked twice is guarded once, as it was first read. */
14
+ const keyOfRead = (thing, where, state) => [state ?? "", ...Object.keys(where).sort().map((k) => `${k}=${k in thing.fields ? keyOf(thing, k, where[k]) : String(where[k])}`)].join("\u0000");
15
+ export const listerOf = (store, find, seen, held) => {
16
+ const reads = new Map();
17
+ const list = ({ thing, where, state, order, limit, after }) => Effect.gen(function* () {
18
+ if (!Number.isInteger(limit) || limit < 1)
19
+ return yield* Effect.die(new Error(`a list's limit is a whole number of rows, at least 1: not ${limit}`));
20
+ // Every stored row the list matches, oldest first; a row read before keeps the version it was read at.
21
+ const cache = seen(thing);
22
+ const stored = [];
23
+ let cursor;
24
+ do {
25
+ const page = yield* store.list({ thing, where, state, order: "oldest", limit: PAGE, after: cursor });
26
+ page.items.forEach((instance, i) => {
27
+ const id = String(instance["id"]);
28
+ if (cache.get(id) === undefined)
29
+ cache.set(id, { instance, version: page.rows[i].version });
30
+ stored.push({ id, place: page.rows[i].place });
31
+ });
32
+ cursor = page.next ?? undefined;
33
+ } while (cursor !== undefined);
34
+ const byThing = reads.get(thing) ?? reads.set(thing, new Map()).get(thing);
35
+ const key = keyOfRead(thing, where, state);
36
+ if (!byThing.has(key))
37
+ byThing.set(key, { thing, where, state, rows: stored.map(({ id }) => ({ id, version: cache.get(id).version })) });
38
+ // The rows as this call leaves them: stored rows it didn't move out, stored rows it moved in (at their own place), then the rows it made.
39
+ const listed = new Set(stored.map((s) => s.id));
40
+ const own = held(thing);
41
+ const candidates = [
42
+ ...stored.map(({ id, place }) => ({ id, rank: [0, place] })),
43
+ ...own.flatMap((h, n) => (h.kind === "insert" ? [{ id: h.id, rank: [1, n] }] : listed.has(h.id) ? [] : [{ id: h.id, rank: undefined }])),
44
+ ];
45
+ const rows = [];
46
+ for (const { id, rank } of candidates) {
47
+ const instance = yield* find(thing, id);
48
+ if (instance === undefined || !matches(thing, where, state, instance))
49
+ continue;
50
+ // A stored row this call moved in keeps its own place, which the store says.
51
+ const place = rank === undefined ? yield* store.place(thing, id) : undefined;
52
+ if (rank === undefined && place === undefined)
53
+ continue;
54
+ rows.push({ instance, rank: rank ?? [0, place] });
55
+ }
56
+ rows.sort((a, b) => (earlier(a.rank, b.rank) ? -1 : 1));
57
+ if (order === "newest")
58
+ rows.reverse();
59
+ const from = after === undefined ? undefined : rankOf(after);
60
+ const rest = from === undefined ? rows : rows.filter((r) => (order === "newest" ? earlier(r.rank, from) : earlier(from, r.rank)));
61
+ const page = rest.slice(0, limit);
62
+ return { items: page.map((r) => r.instance), next: rest.length > limit ? cursorOf(page[page.length - 1].rank) : null };
63
+ });
64
+ return { list, lists: Effect.sync(() => [...reads.values()].flatMap((m) => [...m.values()])) };
65
+ };
@@ -0,0 +1,18 @@
1
+ import type { Thing } from "orthograph";
2
+ import { type Rules } from "./unique.ts";
3
+ import type { Instance, Write } from "../types.ts";
4
+ export interface Step {
5
+ readonly write: Write;
6
+ /** The row as the call found it; undefined for an insert. */
7
+ readonly before: Instance | undefined;
8
+ /** The row as the call leaves it. */
9
+ readonly after: Instance;
10
+ }
11
+ /** What a call cannot be written as: the rule, and why. */
12
+ export type Unwritable = {
13
+ readonly rule: string;
14
+ readonly thing: Thing;
15
+ readonly why: "clash" | "cycle";
16
+ };
17
+ /** The steps in an order the store can apply, or the rule that stops one. Rows that free and take nothing keep the order they were written in. */
18
+ export declare const orderSteps: (steps: ReadonlyArray<Step>, rules: Rules) => ReadonlyArray<Step> | Unwritable;
@@ -0,0 +1,41 @@
1
+ import { inScope, ruleKey } from "./unique.js";
2
+ const same = (a, b) => a.thing === b.thing && a.rule === b.rule && a.key === b.key;
3
+ const without = (keys, other) => keys.filter((k) => !other.some((o) => same(k, o)));
4
+ const slot = (k) => `${k.rule}\u0000${k.key}`;
5
+ const indexed = (keys) => {
6
+ const by = new Map();
7
+ keys.forEach((row, i) => row.forEach((k) => {
8
+ const at = by.get(k.thing) ?? by.set(k.thing, new Map()).get(k.thing);
9
+ at.set(slot(k), [...(at.get(slot(k)) ?? []), i]);
10
+ }));
11
+ return (k) => by.get(k.thing)?.get(slot(k)) ?? [];
12
+ };
13
+ /** The steps in an order the store can apply, or the rule that stops one. Rows that free and take nothing keep the order they were written in. */
14
+ export const orderSteps = (steps, rules) => {
15
+ const keysOf = (thing, instance) => instance === undefined ? [] : rules.of(thing).filter((r) => inScope(r, instance)).map((r) => ({ thing, rule: r.name, key: ruleKey(r, instance) }));
16
+ const held = steps.map((s) => keysOf(s.write.thing, s.after));
17
+ const holders = indexed(held);
18
+ for (let i = 0; i < steps.length; i++) {
19
+ const clash = held[i].find((k) => holders(k).some((j) => j !== i));
20
+ if (clash)
21
+ return { rule: clash.rule, thing: clash.thing, why: "clash" };
22
+ }
23
+ const frees = steps.map((s, i) => without(keysOf(s.write.thing, s.before), held[i]));
24
+ const takes = steps.map((s, i) => without(held[i], keysOf(s.write.thing, s.before)));
25
+ const freers = indexed(frees);
26
+ // Worked out once: `i` must be written after each `j` that frees a key `i` takes.
27
+ const blockers = takes.map((row, i) => [...new Set(row.flatMap((k) => freers(k)))].filter((j) => j !== i));
28
+ const done = new Set();
29
+ const ordered = [];
30
+ while (ordered.length < steps.length) {
31
+ const next = steps.findIndex((_, i) => !done.has(i) && blockers[i].every((j) => done.has(j)));
32
+ if (next === -1) {
33
+ const stuck = steps.findIndex((_, i) => !done.has(i));
34
+ const key = takes[stuck].find((k) => freers(k).some((j) => !done.has(j)));
35
+ return { rule: key.rule, thing: key.thing, why: "cycle" };
36
+ }
37
+ done.add(next);
38
+ ordered.push(steps[next]);
39
+ }
40
+ return ordered;
41
+ };
@@ -0,0 +1,31 @@
1
+ import type { Thing, Unique } from "orthograph";
2
+ import type { Instance, NamedRule } from "../types.ts";
3
+ /** One rule: its name, the thing it constrains, its key's fields, and the states it holds in (all of them when absent). */
4
+ export interface Rule {
5
+ readonly name: string;
6
+ readonly thing: Thing;
7
+ readonly fields: ReadonlyArray<string>;
8
+ readonly scope: ReadonlyArray<string> | undefined;
9
+ readonly declared: Unique;
10
+ }
11
+ /** The rules in force: the ones handed in. Read once per store or unit. */
12
+ export declare const rulesOf: (given: ReadonlyArray<NamedRule>) => {
13
+ of: (thing: Thing) => ReadonlyArray<Rule>;
14
+ named: (rule: Unique) => Rule | undefined;
15
+ };
16
+ export type Rules = ReturnType<typeof rulesOf>;
17
+ /** Is `instance` in the rule's scope: in one of its `while` states, or any state when it has none. */
18
+ export declare const inScope: (rule: Rule, instance: Instance) => boolean;
19
+ /** A field value as the store writes it: its schema's encoded form, as text, so a struct or an array compares by what it holds. */
20
+ export declare const keyOf: (thing: Thing, field: string, value: unknown) => string;
21
+ /** The key `instance` holds under the rule: its fields' encoded forms, in the order of the key. */
22
+ export declare const ruleKey: (rule: Rule, instance: Instance) => string;
23
+ /** Does `instance` hold the key (as `ruleKey` gave it), within the rule's scope? */
24
+ export declare const holds: (rule: Rule, instance: Instance, key: string) => boolean;
25
+ /** A `findBy` value as the fields it fixes: the value itself for a one-field key, an object of the fields for a composite one. */
26
+ export declare const rowOf: (rule: Rule, value: unknown) => Instance;
27
+ /** A per-rule count of the keys held within scope, over one thing's rows: a write moves one row's keys, and only those keys are checked. */
28
+ export declare const uniqueIndex: (rules: ReadonlyArray<Rule>, instances: ReadonlyArray<Instance>) => {
29
+ /** A row becomes `to` (from `from`, or new): true when it now holds a key another row holds. */
30
+ move: (from: Instance | undefined, to: Instance) => boolean;
31
+ };
@@ -0,0 +1,49 @@
1
+ // A thing's rules as the stores and the unit read them (G5): which instances are in a rule's scope, what key an instance holds under it, and whether a set
2
+ // of rows breaks one.
3
+ import { Option, Schema } from "effect";
4
+ const ofDeclared = ({ name, rule }) => ({
5
+ name, thing: rule.fields[0].of, fields: rule.fields.map((f) => f.key),
6
+ scope: rule.while?.map((s) => s.key), declared: rule,
7
+ });
8
+ /** The rules in force: the ones handed in. Read once per store or unit. */
9
+ export const rulesOf = (given) => {
10
+ const declared = given.map(ofDeclared);
11
+ const byThing = new Map();
12
+ return {
13
+ of: (thing) => byThing.get(thing) ?? byThing.set(thing, declared.filter((r) => r.thing === thing)).get(thing),
14
+ named: (rule) => declared.find((r) => r.declared === rule),
15
+ };
16
+ };
17
+ /** Is `instance` in the rule's scope: in one of its `while` states, or any state when it has none. */
18
+ export const inScope = (rule, instance) => rule.scope === undefined || (instance.state !== undefined && rule.scope.includes(instance.state));
19
+ /** A field value as the store writes it: its schema's encoded form, as text, so a struct or an array compares by what it holds. */
20
+ export const keyOf = (thing, field, value) => {
21
+ const encoded = Schema.encodeUnknownOption(thing.fields[field].value.schema)(value);
22
+ return JSON.stringify(Option.isSome(encoded) ? encoded.value : value, (_, v) => (typeof v === "bigint" ? v.toString() : v));
23
+ };
24
+ /** The key `instance` holds under the rule: its fields' encoded forms, in the order of the key. */
25
+ export const ruleKey = (rule, instance) => rule.fields.map((f) => keyOf(rule.thing, f, instance[f])).join("\u0000");
26
+ /** Does `instance` hold the key (as `ruleKey` gave it), within the rule's scope? */
27
+ export const holds = (rule, instance, key) => inScope(rule, instance) && ruleKey(rule, instance) === key;
28
+ /** A `findBy` value as the fields it fixes: the value itself for a one-field key, an object of the fields for a composite one. */
29
+ export const rowOf = (rule, value) => rule.fields.length === 1 ? { [rule.fields[0]]: value } : value;
30
+ /** A per-rule count of the keys held within scope, over one thing's rows: a write moves one row's keys, and only those keys are checked. */
31
+ export const uniqueIndex = (rules, instances) => {
32
+ const counts = new Map(rules.map((r) => [r.name, new Map()]));
33
+ const keysOf = (instance) => rules.filter((r) => inScope(r, instance)).map((r) => [r.name, ruleKey(r, instance)]);
34
+ const bump = (instance, by) => {
35
+ for (const [rule, key] of keysOf(instance))
36
+ counts.get(rule).set(key, (counts.get(rule).get(key) ?? 0) + by);
37
+ };
38
+ for (const instance of instances)
39
+ bump(instance, 1);
40
+ return {
41
+ /** A row becomes `to` (from `from`, or new): true when it now holds a key another row holds. */
42
+ move: (from, to) => {
43
+ if (from)
44
+ bump(from, -1);
45
+ bump(to, 1);
46
+ return keysOf(to).some(([rule, key]) => counts.get(rule).get(key) > 1);
47
+ },
48
+ };
49
+ };
@@ -0,0 +1,3 @@
1
+ import { Effect } from "effect";
2
+ import type { NamedRule, Store, Unit } from "../types.ts";
3
+ export declare const makeUnit: (store: Store["Service"], given?: ReadonlyArray<NamedRule>) => Effect.Effect<Unit>;
@@ -0,0 +1,135 @@
1
+ // One attempt at a call: reads go to the store and their versions are remembered; writes are held back, merged per
2
+ // instance, until the call commits them with its move.
3
+ import { Effect } from "effect";
4
+ import { orderSteps } from "./order.js";
5
+ import { holderOf, indexHeld } from "./holder.js";
6
+ import { listerOf } from "./list.js";
7
+ import { inScope, rowOf, ruleKey, rulesOf } from "./unique.js";
8
+ export const makeUnit = (store, given) => Effect.sync(() => {
9
+ const rules = rulesOf(given ?? store.rules ?? []);
10
+ const read = new Map();
11
+ const held = [];
12
+ const heldBy = new Map();
13
+ const heldFor = (thing, id) => heldBy.get(thing)?.get(id);
14
+ const hold = (h) => {
15
+ held.push(h);
16
+ const ids = heldBy.get(h.thing) ?? heldBy.set(h.thing, new Map()).get(h.thing);
17
+ if (!ids.has(h.id))
18
+ ids.set(h.id, h);
19
+ };
20
+ const seen = (thing) => read.get(thing) ?? read.set(thing, new Map()).get(thing);
21
+ // #1045: every row found by its id counts as read, at the version found; the commit carries them, and the store refuses it when one moved on.
22
+ const found = [];
23
+ const load = (thing, id) => Effect.gen(function* () {
24
+ const cache = seen(thing);
25
+ if (!cache.has(id)) {
26
+ const stored = yield* store.find(thing, id);
27
+ cache.set(id, stored);
28
+ if (stored !== undefined)
29
+ found.push({ thing, id, version: stored.version });
30
+ }
31
+ return cache.get(id);
32
+ });
33
+ const find = (thing, id) => Effect.gen(function* () {
34
+ const stored = yield* load(thing, id);
35
+ const h = heldFor(thing, id);
36
+ if (!h)
37
+ return stored?.instance;
38
+ const base = h.kind === "insert" ? {} : (stored?.instance ?? {});
39
+ return { ...base, ...h.fields, ...(h.state !== undefined ? { state: h.state } : {}) };
40
+ });
41
+ const lister = listerOf(store, find, seen, (thing) => held.filter((h) => h.thing === thing));
42
+ const holder = holderOf(store, find, (thing) => held.filter((h) => h.thing === thing).map((h) => h.id));
43
+ /** `findBy(rule, value)` (G5): the holder of a key, as this call's own writes left it, else the store's. */
44
+ const findBy = (rule, value) => Effect.gen(function* () {
45
+ const named = rules.named(rule);
46
+ if (!named)
47
+ return yield* Effect.die(new Error("findBy(rule, value): that rule is not one this store holds"));
48
+ return yield* holder(named, rowOf(named, value), undefined);
49
+ });
50
+ const change = (thing, id, fields, state) => Effect.gen(function* () {
51
+ const h = heldFor(thing, id);
52
+ if (h) {
53
+ Object.assign(h.fields, fields);
54
+ if (state !== undefined)
55
+ h.state = state;
56
+ return;
57
+ }
58
+ const stored = yield* load(thing, id);
59
+ if (!stored)
60
+ return yield* Effect.die(new Error(`${id} can't change: it was never stored`));
61
+ hold({ thing, id, kind: "update", version: stored.version, fields: { ...fields }, state });
62
+ });
63
+ /** Each held row with the row as the call found it and as it leaves it. */
64
+ const stepsOf = () => held.map((h) => {
65
+ const stored = read.get(h.thing)?.get(h.id)?.instance;
66
+ const base = h.kind === "insert" ? {} : (stored ?? {});
67
+ return {
68
+ write: h.kind === "insert"
69
+ ? { kind: "insert", thing: h.thing, fields: h.fields, state: h.state }
70
+ : { kind: "update", thing: h.thing, id: h.id, version: h.version, changes: h.fields, state: h.state },
71
+ before: h.kind === "insert" ? undefined : stored,
72
+ after: { ...base, ...h.fields, ...(h.state !== undefined ? { state: h.state } : {}) },
73
+ };
74
+ });
75
+ /** The first rule a row breaks by taking a key someone else holds. A row that already held its key (in scope, same key) takes nothing. */
76
+ const check = Effect.gen(function* () {
77
+ const steps = stepsOf();
78
+ const index = yield* indexHeld(rules.of, find, held);
79
+ // The call's own rows first (G5 section 6.2): two of them under one key is the handler's bug, whoever else holds it in the store.
80
+ const seenKeys = new Map();
81
+ for (const { write, after } of steps) {
82
+ for (const rule of rules.of(write.thing)) {
83
+ if (!inScope(rule, after))
84
+ continue;
85
+ const slot = `${rule.name}\u0000${ruleKey(rule, after)}`;
86
+ const seen = seenKeys.get(write.thing) ?? seenKeys.set(write.thing, new Set()).get(write.thing);
87
+ if (seen.has(slot))
88
+ return { rule: rule.name, refuse: rule.declared?.refuse, row: after, own: true };
89
+ seen.add(slot);
90
+ }
91
+ }
92
+ for (const { write, before, after } of steps) {
93
+ for (const rule of rules.of(write.thing)) {
94
+ if (!inScope(rule, after))
95
+ continue;
96
+ const key = ruleKey(rule, after);
97
+ if (before !== undefined && inScope(rule, before) && ruleKey(rule, before) === key)
98
+ continue;
99
+ const id = String(after["id"]);
100
+ const other = yield* holder(rule, after, id, index);
101
+ if (other !== undefined) {
102
+ return { rule: rule.name, refuse: rule.declared?.refuse, row: after, own: heldFor(rule.thing, String(other["id"])) !== undefined, retry: rule.declared?.retry === true };
103
+ }
104
+ }
105
+ }
106
+ return undefined;
107
+ });
108
+ return {
109
+ records: {
110
+ find,
111
+ findBy: findBy,
112
+ list: lister.list,
113
+ insert: (thing, fields, state) => Effect.sync(() => {
114
+ const id = String(fields["id"]);
115
+ hold({ thing, id, kind: "insert", version: 0, fields: { ...fields }, state });
116
+ }),
117
+ update: (thing, id, changes, state) => change(thing, id, changes, state),
118
+ },
119
+ read: find,
120
+ setState: (thing, id, state) => change(thing, id, {}, state),
121
+ check,
122
+ lists: lister.lists,
123
+ reads: Effect.sync(() => [...found]),
124
+ writes: Effect.suspend(() => {
125
+ const ordered = orderSteps(stepsOf(), rules);
126
+ if (!Array.isArray(ordered)) {
127
+ const { rule, why } = ordered;
128
+ return Effect.die(new Error(why === "clash"
129
+ ? `this call's own rows hold one value of the unique rule ${rule}: that is the handler's bug, not a race`
130
+ : `this call's writes cannot be put in an order: each must go after another, over the unique rule ${rule}`));
131
+ }
132
+ return Effect.succeed(ordered.map((s) => s.write));
133
+ }),
134
+ };
135
+ });