@aitoroses/telar 0.0.0-stage → 0.1.0

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 (92) hide show
  1. package/README.md +453 -2
  2. package/dist/compile.d.ts +48 -0
  3. package/dist/compile.js +1238 -0
  4. package/dist/contract.d.ts +109 -0
  5. package/dist/contract.js +497 -0
  6. package/dist/evaluator.d.ts +23 -0
  7. package/dist/evaluator.js +40 -0
  8. package/dist/guide.d.ts +8 -0
  9. package/dist/guide.js +16 -0
  10. package/dist/install.d.ts +104 -0
  11. package/dist/install.js +402 -0
  12. package/dist/iso.d.ts +8 -0
  13. package/dist/iso.js +68 -0
  14. package/dist/node/build.d.ts +1 -0
  15. package/dist/node/build.js +34 -0
  16. package/dist/node/telar-module.d.ts +2 -0
  17. package/dist/node/telar-module.js +28 -0
  18. package/dist/observer.d.ts +47 -0
  19. package/dist/observer.js +53 -0
  20. package/dist/pieces.d.ts +230 -0
  21. package/dist/pieces.js +178 -0
  22. package/dist/powers.d.ts +46 -0
  23. package/dist/powers.js +126 -0
  24. package/dist/protocol.d.ts +212 -0
  25. package/dist/protocol.js +236 -0
  26. package/dist/query.d.ts +67 -0
  27. package/dist/query.js +102 -0
  28. package/dist/read.d.ts +37 -0
  29. package/dist/read.js +27 -0
  30. package/dist/runner.d.ts +112 -0
  31. package/dist/runner.js +134 -0
  32. package/dist/scenario/builder.d.ts +25 -0
  33. package/dist/scenario/builder.js +603 -0
  34. package/dist/scenario/templates.d.ts +35 -0
  35. package/dist/scenario/templates.js +64 -0
  36. package/dist/scenario/types.d.ts +441 -0
  37. package/dist/scenario/types.js +10 -0
  38. package/dist/scenario/validate.d.ts +7 -0
  39. package/dist/scenario/validate.js +19 -0
  40. package/dist/scenario.d.ts +4 -0
  41. package/dist/scenario.js +4 -0
  42. package/dist/schema.d.ts +219 -0
  43. package/dist/schema.js +221 -0
  44. package/dist/seating.d.ts +49 -0
  45. package/dist/seating.js +26 -0
  46. package/dist/send-hook.d.ts +46 -0
  47. package/dist/send-hook.js +123 -0
  48. package/dist/show.d.ts +34 -0
  49. package/dist/show.js +1 -0
  50. package/dist/source.d.ts +85 -0
  51. package/dist/source.js +104 -0
  52. package/dist/spec.d.ts +20 -0
  53. package/dist/spec.js +17 -0
  54. package/dist/standard-schema.d.ts +21 -0
  55. package/dist/standard-schema.js +1 -0
  56. package/dist/std/accuracy.d.ts +12 -0
  57. package/dist/std/accuracy.js +122 -0
  58. package/dist/std/ack.d.ts +14 -0
  59. package/dist/std/ack.js +43 -0
  60. package/dist/std/actions.d.ts +106 -0
  61. package/dist/std/actions.js +154 -0
  62. package/dist/std/brief.d.ts +36 -0
  63. package/dist/std/brief.js +78 -0
  64. package/dist/std/claude-code.d.ts +9 -0
  65. package/dist/std/claude-code.js +106 -0
  66. package/dist/std/compare.d.ts +29 -0
  67. package/dist/std/compare.js +36 -0
  68. package/dist/std/git-workspace.d.ts +44 -0
  69. package/dist/std/git-workspace.js +184 -0
  70. package/dist/std/judgment.d.ts +85 -0
  71. package/dist/std/judgment.js +462 -0
  72. package/dist/std/observe-command.d.ts +23 -0
  73. package/dist/std/observe-command.js +151 -0
  74. package/dist/std/observe-github-checks.d.ts +26 -0
  75. package/dist/std/observe-github-checks.js +299 -0
  76. package/dist/std/observe-http-status.d.ts +27 -0
  77. package/dist/std/observe-http-status.js +181 -0
  78. package/dist/std/plan.d.ts +7 -0
  79. package/dist/std/plan.js +28 -0
  80. package/dist/std/queries.d.ts +31 -0
  81. package/dist/std/queries.js +318 -0
  82. package/dist/std/reading.d.ts +17 -0
  83. package/dist/std/reading.js +88 -0
  84. package/dist/std/schedule.d.ts +19 -0
  85. package/dist/std/schedule.js +122 -0
  86. package/dist/std.d.ts +15 -0
  87. package/dist/std.js +15 -0
  88. package/dist/types.d.ts +366 -0
  89. package/dist/types.js +1 -0
  90. package/dist/values.d.ts +81 -0
  91. package/dist/values.js +129 -0
  92. package/package.json +65 -3
@@ -0,0 +1,109 @@
1
+ import { type AnyEvaluator, type EvaluatorArgs } from "./evaluator.js";
2
+ import { type AnyObserver } from "./observer.js";
3
+ import { type RunnableAction } from "./pieces.js";
4
+ import { type WorldPowers } from "./powers.js";
5
+ import { type Query, type QueryArgInput, type QueryArgs, type QueryParam } from "./query.js";
6
+ import { type RunnerEndInput, type RunnerOptionValidation, type RunnerPollInput, type RunnerReport, type RunnerSeatRef, type RunnerWakeInput } from "./runner.js";
7
+ import { type AnySource } from "./source.js";
8
+ export interface ContractViolation {
9
+ readonly rule: string;
10
+ readonly message: string;
11
+ }
12
+ export interface SourceFixture {
13
+ readonly options: unknown;
14
+ /** Options the source refuses, each with the path its first issue names. */
15
+ readonly invalidOptions?: readonly {
16
+ readonly options: unknown;
17
+ readonly path: readonly string[];
18
+ }[];
19
+ readonly clock: readonly string[];
20
+ /** How many events the walk must yield, so a source that never fires cannot pass. */
21
+ readonly events: number;
22
+ readonly powers?: WorldPowers;
23
+ }
24
+ /**
25
+ * The source contract: the behaviour telar's host relies on from every source, std or not.
26
+ * Walks the fixture's clock as the host would, feeding each poll's newest event back as `last`.
27
+ */
28
+ export declare function checkSource(source: AnySource, fixture: SourceFixture): ContractViolation[];
29
+ export interface ObserverCase {
30
+ readonly check: string;
31
+ readonly args: Readonly<Record<string, unknown>>;
32
+ /** The world this case observes, such as a fake process power. */
33
+ readonly powers?: WorldPowers;
34
+ readonly ok: boolean | null;
35
+ }
36
+ export interface ObserverFixture {
37
+ readonly params: unknown;
38
+ readonly invalidParams?: readonly {
39
+ readonly params: unknown;
40
+ readonly path: readonly string[];
41
+ }[];
42
+ readonly cases: readonly ObserverCase[];
43
+ }
44
+ /**
45
+ * The observer contract: the behaviour telar's host relies on from every observer, std or not.
46
+ * Each case observes one check in a world the case supplies, and names the answer it expects.
47
+ */
48
+ export declare function checkObserver(observer: AnyObserver, fixture: ObserverFixture): ContractViolation[];
49
+ export interface RunnerSubject<Options = unknown> {
50
+ readonly id: string;
51
+ readonly admitOptions: (raw: unknown) => RunnerOptionValidation<unknown>;
52
+ readonly wake: (input: RunnerWakeInput<Options>, powers: WorldPowers) => RunnerReport;
53
+ readonly poll: (input: RunnerPollInput<Options>, powers: WorldPowers) => RunnerReport;
54
+ readonly end: (input: RunnerEndInput<Options>, powers: WorldPowers) => void;
55
+ }
56
+ export interface RunnerFixture<Options = unknown> {
57
+ readonly options: Options;
58
+ readonly invalidOptions?: readonly {
59
+ readonly options: unknown;
60
+ readonly path: readonly string[];
61
+ }[];
62
+ readonly seat?: RunnerSeatRef;
63
+ readonly powers?: WorldPowers;
64
+ readonly onPhase?: (phase: "work" | "ended") => void;
65
+ readonly expectedWork?: number;
66
+ }
67
+ /** Runner contract (interfaces.md §4.1): wake/ref, resume, poll work once by id, ended -> end, GRANT_REFUSED. */
68
+ export declare function checkRunner<Options>(runner: RunnerSubject<Options>, fixture: RunnerFixture<Options>): ContractViolation[];
69
+ export interface EvaluatorFixture {
70
+ readonly cases: readonly {
71
+ readonly args: EvaluatorArgs;
72
+ readonly holds: boolean;
73
+ }[];
74
+ }
75
+ /** Evaluator contract (W67.5): the host records one call's {holds, evidence?} and replay trusts it. */
76
+ export declare function checkEvaluator(evaluator: AnyEvaluator, fixture: EvaluatorFixture): ContractViolation[];
77
+ type QueryParams = Readonly<Record<string, QueryParam>>;
78
+ type ArgStrings = Readonly<Record<string, string>>;
79
+ export interface QueryFixture<A extends QueryArgs = QueryArgs> {
80
+ /** Runs one statement on a trail, refusing a named parameter the SQL does not name, as `node:sqlite` does. */
81
+ readonly select: (sql: string, params: QueryParams) => readonly unknown[];
82
+ readonly args: QueryArgInput<A>;
83
+ /** The decoded rows the query must return. At least one, so a query that returns nothing cannot pass. */
84
+ readonly rows: readonly unknown[];
85
+ readonly invalidArgs?: readonly {
86
+ readonly args: ArgStrings;
87
+ readonly path: readonly string[];
88
+ }[];
89
+ }
90
+ /**
91
+ * The query contract: the behaviour telar relies on from every declared query, std or not.
92
+ * `select` runs the SQL, so the suite needs no runtime of its own.
93
+ */
94
+ export declare function checkQuery<Row, A extends QueryArgs>(typed: Query<Row, A>, typedFixture: QueryFixture<A>): ContractViolation[];
95
+ export interface ActionCase {
96
+ readonly input: Readonly<Record<string, unknown>>;
97
+ readonly powers?: WorldPowers;
98
+ /** The code the call refuses with; absent when the call succeeds. */
99
+ readonly code?: string;
100
+ }
101
+ export interface ActionFixture {
102
+ readonly cases: readonly ActionCase[];
103
+ }
104
+ /**
105
+ * The action contract: what the host relies on when it runs an action and records its outcome.
106
+ * Each case runs one input in a world the case supplies and names the code it refuses with, if any.
107
+ */
108
+ export declare function checkAction(action: RunnableAction, fixture: ActionFixture): ContractViolation[];
109
+ export {};
@@ -0,0 +1,497 @@
1
+ import { decodeEvaluation, isValidEvaluatorId, } from "./evaluator.js";
2
+ import { isValidObserverId } from "./observer.js";
3
+ import { isValidActionId } from "./pieces.js";
4
+ import { fakeRead } from "./read.js";
5
+ import { PowerError, hostWorldPowers } from "./powers.js";
6
+ import { bindQuery, decodeQueryRows, issueText, } from "./query.js";
7
+ import { isValidRunnerId, } from "./runner.js";
8
+ import { isValidSourceId, } from "./source.js";
9
+ function poll(source, fixture, now, last) {
10
+ const args = { source: source.id, now, options: fixture.options, ...(last ? { last } : {}) };
11
+ return source.dispatch(args, fixture.powers ?? hostWorldPowers());
12
+ }
13
+ function checkOptions(source, fixture) {
14
+ const out = [];
15
+ if (!isValidSourceId(source.id)) {
16
+ out.push({
17
+ rule: "id",
18
+ message: `${source.id} does not match <installation>/source/<name>/<v>`,
19
+ });
20
+ }
21
+ if (!source.admitOptions(fixture.options).ok) {
22
+ out.push({ rule: "options", message: "the fixture's options are refused" });
23
+ }
24
+ for (const bad of fixture.invalidOptions ?? []) {
25
+ const checked = source.admitOptions(bad.options);
26
+ const path = checked.ok ? undefined : checked.issues[0]?.path.join(".");
27
+ if (path !== bad.path.join(".")) {
28
+ out.push({
29
+ rule: "options",
30
+ message: `${JSON.stringify(bad.options)} must be refused at ${bad.path.join(".") || "<root>"}, got ${path ?? "admitted"}`,
31
+ });
32
+ }
33
+ }
34
+ return out;
35
+ }
36
+ /**
37
+ * The source contract: the behaviour telar's host relies on from every source, std or not.
38
+ * Walks the fixture's clock as the host would, feeding each poll's newest event back as `last`.
39
+ */
40
+ export function checkSource(source, fixture) {
41
+ const out = checkOptions(source, fixture);
42
+ const seen = new Set();
43
+ let last;
44
+ for (const now of fixture.clock) {
45
+ const reply = poll(source, fixture, now, last);
46
+ const again = poll(source, fixture, now, last);
47
+ if (JSON.stringify(again) !== JSON.stringify(reply)) {
48
+ out.push({ rule: "pure", message: `two polls at ${now} with the same input differ` });
49
+ }
50
+ for (const issue of reply.invalid) {
51
+ out.push({ rule: "event", message: `event ${JSON.stringify(issue.key)}: ${issue.message}` });
52
+ }
53
+ for (const event of reply.events) {
54
+ if (seen.has(event.key)) {
55
+ out.push({ rule: "once", message: `event ${JSON.stringify(event.key)} repeats at ${now}` });
56
+ }
57
+ seen.add(event.key);
58
+ if (last === undefined || event.at >= last.at) {
59
+ last = { key: event.key, at: event.at };
60
+ }
61
+ }
62
+ }
63
+ if (seen.size !== fixture.events) {
64
+ out.push({
65
+ rule: "fires",
66
+ message: `the walk yields ${String(seen.size)} events, expected ${String(fixture.events)}`,
67
+ });
68
+ }
69
+ return out;
70
+ }
71
+ function evidenceProblems(evidence) {
72
+ const out = [];
73
+ for (const ref of evidence.refs ?? []) {
74
+ if (typeof ref.kind !== "string" || ref.kind.length === 0)
75
+ out.push("a ref needs a kind");
76
+ }
77
+ const { status, durationMs, readings } = evidence;
78
+ if (status !== undefined && (!Number.isInteger(status) || status < 100 || status > 599)) {
79
+ out.push(`status ${String(status)} is not an HTTP status`);
80
+ }
81
+ if (durationMs !== undefined && (!Number.isInteger(durationMs) || durationMs < 0)) {
82
+ out.push(`durationMs ${String(durationMs)} is not a non-negative integer`);
83
+ }
84
+ for (const [name, value] of Object.entries(readings ?? {})) {
85
+ if (!Number.isFinite(value))
86
+ out.push(`reading ${name} is not a finite number`);
87
+ }
88
+ return out;
89
+ }
90
+ /**
91
+ * The observer contract: the behaviour telar's host relies on from every observer, std or not.
92
+ * Each case observes one check in a world the case supplies, and names the answer it expects.
93
+ */
94
+ export function checkObserver(observer, fixture) {
95
+ const out = [];
96
+ if (!isValidObserverId(observer.id)) {
97
+ out.push({
98
+ rule: "id",
99
+ message: `${observer.id} does not match <namespace>/observe/<name>/<v>`,
100
+ });
101
+ }
102
+ if (!observer.admitParams(fixture.params).ok) {
103
+ out.push({ rule: "params", message: "the fixture's params are refused" });
104
+ }
105
+ for (const bad of fixture.invalidParams ?? []) {
106
+ const checked = observer.admitParams(bad.params);
107
+ const path = checked.ok ? undefined : checked.issues[0]?.path.join(".");
108
+ if (path !== bad.path.join(".")) {
109
+ out.push({
110
+ rule: "params",
111
+ message: `${JSON.stringify(bad.params)} must be refused at ${bad.path.join(".") || "<root>"}, got ${path ?? "admitted"}`,
112
+ });
113
+ }
114
+ }
115
+ for (const c of fixture.cases) {
116
+ const powers = c.powers ?? hostWorldPowers();
117
+ const call = () => observer.dispatch({ observer: observer.id, check: c.check, args: c.args, params: fixture.params }, powers);
118
+ const answer = call();
119
+ const where = `${c.check} ${JSON.stringify(c.args)}`;
120
+ if (answer.ok !== c.ok) {
121
+ out.push({
122
+ rule: "answer",
123
+ message: `${where}: ok is ${String(answer.ok)}, expected ${String(c.ok)}`,
124
+ });
125
+ }
126
+ if (answer.ok === null && answer.evidence !== undefined) {
127
+ out.push({ rule: "evidence", message: `${where}: "not yet" carries no evidence` });
128
+ }
129
+ for (const problem of answer.evidence === undefined ? [] : evidenceProblems(answer.evidence)) {
130
+ out.push({ rule: "evidence", message: `${where}: ${problem}` });
131
+ }
132
+ if (JSON.stringify(call()) !== JSON.stringify(answer)) {
133
+ out.push({ rule: "pure", message: `${where}: two observations of the same world differ` });
134
+ }
135
+ }
136
+ const poweredCase = fixture.cases.find((c) => c.powers !== undefined);
137
+ if (poweredCase !== undefined) {
138
+ try {
139
+ observer.dispatch({
140
+ observer: observer.id,
141
+ check: poweredCase.check,
142
+ args: poweredCase.args,
143
+ params: fixture.params,
144
+ }, UNGRANTED_POWERS);
145
+ out.push({ rule: "grant", message: "observer succeeded with ungranted powers" });
146
+ }
147
+ catch (err) {
148
+ const code = typeof err === "object" && err !== null ? Reflect.get(err, "code") : undefined;
149
+ if (code !== "GRANT_REFUSED") {
150
+ out.push({ rule: "grant", message: `expected GRANT_REFUSED, got ${String(code ?? err)}` });
151
+ }
152
+ }
153
+ }
154
+ return out;
155
+ }
156
+ const DEFAULT_SEAT = {
157
+ installation: "contract",
158
+ seat: "s-000001",
159
+ role: "worker",
160
+ binding: { kind: "case", case_id: "c-000001" },
161
+ };
162
+ const RUNNER_STATES = new Set(["working", "idle", "ended"]);
163
+ const REPORT_KEYS = new Set(["ref", "state", "holder", "work"]);
164
+ const WORK_KEYS = new Set(["id", "startedAt", "endedAt", "readings"]);
165
+ const refuseRead = () => {
166
+ throw new PowerError("GRANT_REFUSED", "read is not granted");
167
+ };
168
+ const UNGRANTED_POWERS = {
169
+ roots: {},
170
+ process: (req) => {
171
+ throw new PowerError("GRANT_REFUSED", `process ${req.executable} is not granted`);
172
+ },
173
+ network: (req) => {
174
+ throw new PowerError("GRANT_REFUSED", `network ${req.url} is not granted`);
175
+ },
176
+ read: { case: refuseRead, lineage: refuseRead, seats: refuseRead, query: refuseRead },
177
+ };
178
+ const isRec = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
179
+ function checkKeys(obj, allowed, rule, out) {
180
+ for (const k of Object.keys(obj)) {
181
+ if (!allowed.has(k))
182
+ out.push({ rule, message: `unknown key ${JSON.stringify(k)}` });
183
+ }
184
+ }
185
+ function checkWorkItem(item, seen, out) {
186
+ if (!isRec(item))
187
+ return void out.push({ rule: "work", message: "work item must be an object" });
188
+ checkKeys(item, WORK_KEYS, "work", out);
189
+ const { id, startedAt, endedAt, readings } = item;
190
+ if (typeof id !== "string" || !id)
191
+ return void out.push({ rule: "work", message: "work item requires non-empty id" });
192
+ if (typeof startedAt !== "string" || !startedAt || typeof endedAt !== "string" || !endedAt)
193
+ out.push({ rule: "work", message: `${id} requires non-empty startedAt and endedAt` });
194
+ if (readings !== undefined && !isRec(readings))
195
+ out.push({ rule: "work", message: `${id} readings must be an object` });
196
+ else if (readings !== undefined) {
197
+ for (const [k, v] of Object.entries(readings)) {
198
+ if (!k || typeof v !== "number" || !Number.isFinite(v))
199
+ out.push({ rule: "work", message: `${id} reading ${JSON.stringify(k)} must be finite` });
200
+ }
201
+ }
202
+ seen.add(id);
203
+ }
204
+ function checkRunnerReport(rule, r, seen, out) {
205
+ if (!isRec(r))
206
+ return void out.push({ rule, message: `${rule} report must be an object` });
207
+ checkKeys(r, REPORT_KEYS, "report", out);
208
+ if (typeof r.ref !== "string" || !r.ref)
209
+ out.push({ rule, message: `${rule} empty ref` });
210
+ const state = r.state;
211
+ if (typeof state !== "string" || !RUNNER_STATES.has(state))
212
+ out.push({ rule, message: `${rule} invalid state ${String(state)}` });
213
+ if (r.holder !== undefined && !isRec(r.holder))
214
+ out.push({ rule: "holder", message: `${rule} holder must be an object` });
215
+ else if (r.holder !== undefined) {
216
+ for (const [k, v] of Object.entries(r.holder)) {
217
+ if (k === "ref")
218
+ out.push({ rule: "holder", message: `${rule} holder.ref is reserved for telar` });
219
+ else if (!k || typeof v !== "string" || !v)
220
+ out.push({ rule: "holder", message: `${rule} holder[${JSON.stringify(k)}] empty` });
221
+ }
222
+ }
223
+ if (r.work !== undefined && !Array.isArray(r.work))
224
+ out.push({ rule: "work", message: `${rule} work must be an array` });
225
+ else
226
+ for (const item of r.work ?? [])
227
+ checkWorkItem(item, seen, out);
228
+ }
229
+ /** Runner contract (interfaces.md §4.1): wake/ref, resume, poll work once by id, ended -> end, GRANT_REFUSED. */
230
+ export function checkRunner(runner, fixture) {
231
+ const out = [];
232
+ const add = (rule, message) => out.push({ rule, message });
233
+ if (!isValidRunnerId(runner.id))
234
+ add("id", `invalid id ${runner.id}`);
235
+ if (!runner.admitOptions(fixture.options).ok)
236
+ add("options", "fixture options refused");
237
+ for (const bad of fixture.invalidOptions ?? []) {
238
+ const res = runner.admitOptions(bad.options);
239
+ const got = res.ok ? "admitted" : (res.issues[0]?.path.join(".") ?? "");
240
+ const want = bad.path.join(".");
241
+ if (res.ok || got !== want)
242
+ add("options", `expected ${want || "<root>"}, got ${got}`);
243
+ }
244
+ const seat = fixture.seat ?? DEFAULT_SEAT;
245
+ const powers = fixture.powers ?? hostWorldPowers();
246
+ const seen = new Set();
247
+ const woke = runner.wake({ seat, prompt: "first", options: fixture.options }, powers);
248
+ checkRunnerReport("wake", woke, seen, out);
249
+ if (typeof woke.ref === "string" && woke.ref) {
250
+ const ref = woke.ref;
251
+ fixture.onPhase?.("work");
252
+ checkRunnerReport("poll", runner.poll({ ref, options: fixture.options }, powers), seen, out);
253
+ checkRunnerReport("poll", runner.poll({ ref, options: fixture.options }, powers), seen, out);
254
+ if (seen.size !== (fixture.expectedWork ?? 1))
255
+ add("work", `observed ${String(seen.size)} work ids`);
256
+ const resumed = runner.wake({ seat, prompt: "resume", ref, options: fixture.options }, powers);
257
+ checkRunnerReport("resume", resumed, seen, out);
258
+ if (resumed.ref !== ref)
259
+ add("resume", `resume changed ref to ${resumed.ref}`);
260
+ fixture.onPhase?.("ended");
261
+ const ending = runner.poll({ ref, options: fixture.options }, powers);
262
+ checkRunnerReport("end", ending, seen, out);
263
+ if (fixture.onPhase !== undefined && ending.state !== "ended")
264
+ add("end", `expected ended, got ${ending.state}`);
265
+ try {
266
+ runner.end({ ref, options: fixture.options }, powers);
267
+ }
268
+ catch (err) {
269
+ add("end", `end threw: ${String(err)}`);
270
+ }
271
+ }
272
+ try {
273
+ runner.wake({ seat, prompt: "ungranted", options: fixture.options }, UNGRANTED_POWERS);
274
+ add("grant", "ungranted wake succeeded");
275
+ }
276
+ catch (err) {
277
+ const code = typeof err === "object" && err !== null ? Reflect.get(err, "code") : undefined;
278
+ if (code !== "GRANT_REFUSED")
279
+ add("grant", `expected GRANT_REFUSED, got ${String(code ?? err)}`);
280
+ }
281
+ return out;
282
+ }
283
+ /** Evaluator contract (W67.5): the host records one call's {holds, evidence?} and replay trusts it. */
284
+ export function checkEvaluator(evaluator, fixture) {
285
+ const out = [];
286
+ if (!isValidEvaluatorId(evaluator.id)) {
287
+ out.push({
288
+ rule: "id",
289
+ message: `${evaluator.id} does not match <installation>/evaluator/<name>/<v>`,
290
+ });
291
+ }
292
+ const outcomes = new Set();
293
+ for (const { args, holds } of fixture.cases) {
294
+ const at = JSON.stringify(args);
295
+ try {
296
+ const result = decodeEvaluation(evaluator.id, evaluator.evaluate(args));
297
+ const again = decodeEvaluation(evaluator.id, evaluator.evaluate(args));
298
+ outcomes.add(result.holds);
299
+ if (JSON.stringify(again) !== JSON.stringify(result)) {
300
+ out.push({ rule: "pure", message: `two evaluations of ${at} differ` });
301
+ }
302
+ if (result.holds !== holds) {
303
+ out.push({
304
+ rule: "decides",
305
+ message: `${at} holds ${String(result.holds)}, expected ${String(holds)}`,
306
+ });
307
+ }
308
+ }
309
+ catch (err) {
310
+ out.push({ rule: "shape", message: `${at}: ${String(err)}` });
311
+ }
312
+ }
313
+ if (outcomes.size < 2) {
314
+ out.push({
315
+ rule: "decides",
316
+ message: "the fixture must reach both a holding and a failing result",
317
+ });
318
+ }
319
+ return out;
320
+ }
321
+ const QUERY_NAME = /^[a-z][a-z0-9-]*$/;
322
+ const EXTRA_ARG = "notAnArgument";
323
+ function canonical(value) {
324
+ if (Array.isArray(value))
325
+ return `[${value.map(canonical).join(",")}]`;
326
+ if (isRec(value)) {
327
+ const keys = Object.keys(value).toSorted();
328
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonical(value[k])}`).join(",")}}`;
329
+ }
330
+ return JSON.stringify(value) ?? "undefined";
331
+ }
332
+ function refusedAt(query, args) {
333
+ const bound = bindQuery(query, args);
334
+ return bound.ok ? undefined : (bound.issues[0]?.path ?? []).map(String).join(".");
335
+ }
336
+ function argCases(query, fixture) {
337
+ const omit = (name) => Object.fromEntries(Object.entries(fixture.args).filter(([k]) => k !== name));
338
+ return [
339
+ ...(fixture.invalidArgs ?? []).map((bad) => ({ args: bad.args, path: [...bad.path] })),
340
+ { args: { ...fixture.args, [EXTRA_ARG]: "x" }, path: [EXTRA_ARG] },
341
+ ...Object.keys(query.args).map((name) => ({ args: omit(name), path: [name] })),
342
+ ];
343
+ }
344
+ function sqlParamCount(fixture, sql, params) {
345
+ return fixture
346
+ .select(`EXPLAIN ${sql}`, params)
347
+ .filter((op) => isRec(op) && op["opcode"] === "Variable")
348
+ .reduce((most, op) => Math.max(most, isRec(op) ? Number(op["p1"]) : 0), 0);
349
+ }
350
+ function runRows(query, fixture, sql, params) {
351
+ return canonical(decodeQueryRows(query, fixture.select(sql, params)));
352
+ }
353
+ function checkRun(query, fixture, sql, params) {
354
+ const declared = Object.keys(params).length;
355
+ let named;
356
+ try {
357
+ named = sqlParamCount(fixture, sql, params);
358
+ }
359
+ catch (err) {
360
+ return [{ rule: "params", message: err instanceof Error ? err.message : String(err) }];
361
+ }
362
+ if (named !== declared) {
363
+ const message = `the SQL names ${String(named)} parameter(s), and ${String(declared)} argument(s) are declared`;
364
+ return [{ rule: "params", message }];
365
+ }
366
+ const out = [];
367
+ const first = runRows(query, fixture, sql, params);
368
+ if (first !== canonical(fixture.rows)) {
369
+ out.push({ rule: "rows", message: `got ${first}, expected ${canonical(fixture.rows)}` });
370
+ }
371
+ if (runRows(query, fixture, sql, params) !== first) {
372
+ out.push({ rule: "pure", message: "two runs with the same args return different rows" });
373
+ }
374
+ return out;
375
+ }
376
+ /**
377
+ * The query contract: the behaviour telar relies on from every declared query, std or not.
378
+ * `select` runs the SQL, so the suite needs no runtime of its own.
379
+ */
380
+ export function checkQuery(typed, typedFixture) {
381
+ const query = typed;
382
+ const fixture = typedFixture;
383
+ const out = [];
384
+ if (!QUERY_NAME.test(query.name)) {
385
+ out.push({ rule: "name", message: `${query.name} does not match ${String(QUERY_NAME)}` });
386
+ }
387
+ if (fixture.rows.length === 0) {
388
+ out.push({
389
+ rule: "rows",
390
+ message: "the fixture expects no rows, so an empty query would pass",
391
+ });
392
+ }
393
+ for (const bad of argCases(query, fixture)) {
394
+ const got = refusedAt(query, bad.args);
395
+ const want = bad.path.join(".");
396
+ if (got !== want) {
397
+ const message = `${JSON.stringify(bad.args)} must be refused at ${want || "<root>"}, got ${got ?? "bound"}`;
398
+ out.push({ rule: "args", message });
399
+ }
400
+ }
401
+ const bound = bindQuery(query, fixture.args);
402
+ if (!bound.ok) {
403
+ const message = `the fixture's args are refused: ${bound.issues.map(issueText).join("; ")}`;
404
+ return [...out, { rule: "args", message }];
405
+ }
406
+ try {
407
+ return [...out, ...checkRun(query, fixture, bound.sql, bound.params)];
408
+ }
409
+ catch (err) {
410
+ return [...out, { rule: "rows", message: err instanceof Error ? err.message : String(err) }];
411
+ }
412
+ }
413
+ const ERROR_CODE_RE = /^[A-Z][A-Z0-9_]*$/;
414
+ function attempt(action, input, powers) {
415
+ try {
416
+ return { kind: "ok", output: action.run(input, powers) };
417
+ }
418
+ catch (err) {
419
+ const code = typeof err === "object" && err !== null ? Reflect.get(err, "code") : undefined;
420
+ if (typeof code === "string" && ERROR_CODE_RE.test(code))
421
+ return { kind: "refused", code };
422
+ return { kind: "bare", message: String(err) };
423
+ }
424
+ }
425
+ function outcomeText(outcome) {
426
+ return outcome.kind === "ok"
427
+ ? "success"
428
+ : outcome.kind === "refused"
429
+ ? outcome.code
430
+ : "a bare error";
431
+ }
432
+ function ungrantedPowers() {
433
+ let touched = false;
434
+ const powers = Object.freeze({
435
+ roots: {},
436
+ process: () => {
437
+ touched = true;
438
+ throw new PowerError("GRANT_REFUSED", "the contract grants no process power");
439
+ },
440
+ network: () => {
441
+ touched = true;
442
+ throw new PowerError("GRANT_REFUSED", "the contract grants no network power");
443
+ },
444
+ read: fakeRead(),
445
+ });
446
+ return { powers, touched: () => touched };
447
+ }
448
+ /**
449
+ * The action contract: what the host relies on when it runs an action and records its outcome.
450
+ * Each case runs one input in a world the case supplies and names the code it refuses with, if any.
451
+ */
452
+ export function checkAction(action, fixture) {
453
+ const out = [];
454
+ if (!isValidActionId(action.id)) {
455
+ out.push({ rule: "id", message: `${action.id} does not match <namespace>/action/<name>/<v>` });
456
+ }
457
+ for (const c of fixture.cases) {
458
+ const where = JSON.stringify(c.input);
459
+ const powers = c.powers ?? hostWorldPowers();
460
+ const first = attempt(action, c.input, powers);
461
+ if (first.kind === "bare") {
462
+ out.push({
463
+ rule: "outcome",
464
+ message: `${where}: threw ${first.message} without an UPPER_SNAKE code`,
465
+ });
466
+ }
467
+ if (first.kind === "ok" &&
468
+ JSON.stringify(JSON.parse(JSON.stringify(first.output))) !== JSON.stringify(first.output)) {
469
+ out.push({
470
+ rule: "outcome",
471
+ message: `${where}: the output does not round-trip through JSON`,
472
+ });
473
+ }
474
+ if (outcomeText(first) !== (c.code ?? "success")) {
475
+ out.push({
476
+ rule: "outcome",
477
+ message: `${where}: ${outcomeText(first)}, expected ${c.code ?? "success"}`,
478
+ });
479
+ }
480
+ const again = attempt(action, c.input, powers);
481
+ if (outcomeText(again) !== outcomeText(first)) {
482
+ out.push({
483
+ rule: "repeat",
484
+ message: `${where}: ${outcomeText(first)}, then ${outcomeText(again)}`,
485
+ });
486
+ }
487
+ const ungranted = ungrantedPowers();
488
+ const refused = attempt(action, c.input, ungranted.powers);
489
+ if (ungranted.touched() && outcomeText(refused) !== "GRANT_REFUSED") {
490
+ out.push({
491
+ rule: "grant",
492
+ message: `${where}: with no grant it ended in ${outcomeText(refused)}, not GRANT_REFUSED`,
493
+ });
494
+ }
495
+ }
496
+ return out;
497
+ }
@@ -0,0 +1,23 @@
1
+ export type EvaluatorId = `${string}/evaluator/${string}/${number}`;
2
+ export type StdEvaluatorId = `telar.std/${string}/${number}`;
3
+ export interface Evaluation {
4
+ readonly holds: boolean;
5
+ readonly evidence?: string;
6
+ }
7
+ export type EvaluatorArgs = Readonly<Record<string, unknown>>;
8
+ export interface Evaluator<Id extends EvaluatorId = EvaluatorId> {
9
+ readonly id: Id;
10
+ readonly evaluate: (args: EvaluatorArgs) => Evaluation;
11
+ }
12
+ export type AnyEvaluator = Evaluator;
13
+ export declare class EvaluatorError extends Error {
14
+ readonly name: string;
15
+ readonly code: string;
16
+ constructor(code: string, message: string);
17
+ }
18
+ export declare function isValidEvaluatorId(id: string): boolean;
19
+ export declare function decodeEvaluation(id: string, raw: unknown): Evaluation;
20
+ export declare function defineEvaluator<const Id extends EvaluatorId>(input: {
21
+ readonly id: Id;
22
+ readonly evaluate: (args: EvaluatorArgs) => Evaluation;
23
+ }): Evaluator<Id>;
@@ -0,0 +1,40 @@
1
+ export class EvaluatorError extends Error {
2
+ name = "EvaluatorError";
3
+ code;
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.code = code;
7
+ }
8
+ }
9
+ const EVALUATOR_ID_RE = /^[a-z][a-z0-9-]*\/evaluator\/[a-z][a-z0-9-]*\/[1-9][0-9]*$/;
10
+ export function isValidEvaluatorId(id) {
11
+ return EVALUATOR_ID_RE.test(id);
12
+ }
13
+ function isRec(value) {
14
+ return typeof value === "object" && value !== null && !Array.isArray(value);
15
+ }
16
+ export function decodeEvaluation(id, raw) {
17
+ const bad = (why) => {
18
+ throw new EvaluatorError("INVALID_EVALUATION", `evaluator ${id} ${why}`);
19
+ };
20
+ if (!isRec(raw))
21
+ return bad("must return {holds, evidence?}");
22
+ const extra = Object.keys(raw).find((k) => k !== "holds" && k !== "evidence");
23
+ if (extra !== undefined)
24
+ return bad(`returned unknown key ${JSON.stringify(extra)}`);
25
+ const { holds, evidence } = raw;
26
+ if (typeof holds !== "boolean")
27
+ return bad("must return a boolean holds");
28
+ if (evidence === undefined)
29
+ return { holds };
30
+ if (typeof evidence !== "string" || evidence.length === 0) {
31
+ return bad("evidence must be a non-empty string");
32
+ }
33
+ return { holds, evidence };
34
+ }
35
+ export function defineEvaluator(input) {
36
+ if (!isValidEvaluatorId(input.id)) {
37
+ throw new EvaluatorError("INVALID_EVALUATOR", `evaluator id ${JSON.stringify(input.id)} must match <installation>/evaluator/<name>/<v>`);
38
+ }
39
+ return Object.freeze({ id: input.id, evaluate: input.evaluate });
40
+ }
@@ -0,0 +1,8 @@
1
+ import type { FieldRef } from "./values.js";
2
+ export interface Guide {
3
+ readonly kind: "guide";
4
+ readonly text: readonly string[];
5
+ readonly holes: readonly FieldRef[];
6
+ readonly template: string;
7
+ }
8
+ export declare function guide(text: TemplateStringsArray, ...holes: readonly FieldRef[]): Guide;