@aitoroses/telar 0.0.0 → 0.2.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 (94) hide show
  1. package/README.md +457 -3
  2. package/dist/compile.d.ts +48 -0
  3. package/dist/compile.js +1240 -0
  4. package/dist/contract.d.ts +109 -0
  5. package/dist/contract.js +491 -0
  6. package/dist/evaluator.d.ts +23 -0
  7. package/dist/evaluator.js +40 -0
  8. package/dist/evidence.d.ts +23 -0
  9. package/dist/evidence.js +74 -0
  10. package/dist/guide.d.ts +8 -0
  11. package/dist/guide.js +16 -0
  12. package/dist/install.d.ts +104 -0
  13. package/dist/install.js +402 -0
  14. package/dist/iso.d.ts +10 -0
  15. package/dist/iso.js +73 -0
  16. package/dist/node/build.d.ts +2 -0
  17. package/dist/node/build.js +56 -0
  18. package/dist/node/telar-module.d.ts +2 -0
  19. package/dist/node/telar-module.js +28 -0
  20. package/dist/observer.d.ts +38 -0
  21. package/dist/observer.js +53 -0
  22. package/dist/pieces.d.ts +230 -0
  23. package/dist/pieces.js +178 -0
  24. package/dist/powers.d.ts +46 -0
  25. package/dist/powers.js +126 -0
  26. package/dist/protocol.d.ts +220 -0
  27. package/dist/protocol.js +243 -0
  28. package/dist/query.d.ts +67 -0
  29. package/dist/query.js +102 -0
  30. package/dist/read.d.ts +37 -0
  31. package/dist/read.js +27 -0
  32. package/dist/runner.d.ts +113 -0
  33. package/dist/runner.js +134 -0
  34. package/dist/scenario/builder.d.ts +25 -0
  35. package/dist/scenario/builder.js +603 -0
  36. package/dist/scenario/templates.d.ts +35 -0
  37. package/dist/scenario/templates.js +64 -0
  38. package/dist/scenario/types.d.ts +432 -0
  39. package/dist/scenario/types.js +10 -0
  40. package/dist/scenario/validate.d.ts +7 -0
  41. package/dist/scenario/validate.js +19 -0
  42. package/dist/scenario.d.ts +4 -0
  43. package/dist/scenario.js +4 -0
  44. package/dist/schema.d.ts +221 -0
  45. package/dist/schema.js +227 -0
  46. package/dist/seating.d.ts +47 -0
  47. package/dist/seating.js +26 -0
  48. package/dist/send-hook.d.ts +46 -0
  49. package/dist/send-hook.js +123 -0
  50. package/dist/show.d.ts +34 -0
  51. package/dist/show.js +1 -0
  52. package/dist/source.d.ts +85 -0
  53. package/dist/source.js +104 -0
  54. package/dist/spec.d.ts +21 -0
  55. package/dist/spec.js +18 -0
  56. package/dist/standard-schema.d.ts +21 -0
  57. package/dist/standard-schema.js +1 -0
  58. package/dist/std/accuracy.d.ts +12 -0
  59. package/dist/std/accuracy.js +122 -0
  60. package/dist/std/ack.d.ts +14 -0
  61. package/dist/std/ack.js +43 -0
  62. package/dist/std/actions.d.ts +105 -0
  63. package/dist/std/actions.js +153 -0
  64. package/dist/std/brief.d.ts +36 -0
  65. package/dist/std/brief.js +78 -0
  66. package/dist/std/claude-code.d.ts +9 -0
  67. package/dist/std/claude-code.js +113 -0
  68. package/dist/std/compare.d.ts +29 -0
  69. package/dist/std/compare.js +36 -0
  70. package/dist/std/git-workspace.d.ts +44 -0
  71. package/dist/std/git-workspace.js +184 -0
  72. package/dist/std/judgment.d.ts +85 -0
  73. package/dist/std/judgment.js +462 -0
  74. package/dist/std/observe-command.d.ts +23 -0
  75. package/dist/std/observe-command.js +151 -0
  76. package/dist/std/observe-github-checks.d.ts +24 -0
  77. package/dist/std/observe-github-checks.js +289 -0
  78. package/dist/std/observe-http-status.d.ts +27 -0
  79. package/dist/std/observe-http-status.js +193 -0
  80. package/dist/std/plan.d.ts +7 -0
  81. package/dist/std/plan.js +28 -0
  82. package/dist/std/queries.d.ts +31 -0
  83. package/dist/std/queries.js +318 -0
  84. package/dist/std/reading.d.ts +17 -0
  85. package/dist/std/reading.js +88 -0
  86. package/dist/std/schedule.d.ts +19 -0
  87. package/dist/std/schedule.js +122 -0
  88. package/dist/std.d.ts +15 -0
  89. package/dist/std.js +15 -0
  90. package/dist/types.d.ts +370 -0
  91. package/dist/types.js +1 -0
  92. package/dist/values.d.ts +81 -0
  93. package/dist/values.js +129 -0
  94. package/package.json +62 -5
@@ -0,0 +1,603 @@
1
+ import { compile } from "../spec.js";
2
+ import { ScenarioCompileError, } from "./types.js";
3
+ import { STEP_ID_RE, STEP_NOTE_RE } from "./validate.js";
4
+ const SCOPE_PREFIX_RE = /^[a-z0-9][a-z0-9_-]*$/;
5
+ export const absent = Object.freeze({ $absent: true });
6
+ export function contains(substring) {
7
+ return Object.freeze({ $contains: substring });
8
+ }
9
+ export function bindCase(protocol, opts) {
10
+ return Object.freeze({
11
+ kind: "case",
12
+ protocol,
13
+ ...(opts?.parent !== undefined ? { parent: opts.parent } : {}),
14
+ ...(opts?.forRole !== undefined ? { forRole: opts.forRole } : {}),
15
+ ...(opts?.scope !== undefined ? { scope: opts.scope } : {}),
16
+ ...(opts?.index !== undefined ? { index: opts.index } : {}),
17
+ });
18
+ }
19
+ export function bindSeatRef(role, opts) {
20
+ return Object.freeze({
21
+ kind: "seat",
22
+ role,
23
+ ...(opts?.case !== undefined ? { case: opts.case } : {}),
24
+ ...(opts?.scope !== undefined ? { scope: opts.scope } : {}),
25
+ ...(opts?.index !== undefined ? { index: opts.index } : {}),
26
+ });
27
+ }
28
+ export function bindMessage(messageKind, opts) {
29
+ return Object.freeze({
30
+ kind: "message",
31
+ messageKind,
32
+ ...(opts?.case !== undefined ? { case: opts.case } : {}),
33
+ ...(opts?.index !== undefined ? { index: opts.index } : {}),
34
+ });
35
+ }
36
+ function isRec(value) {
37
+ return typeof value === "object" && value !== null && !Array.isArray(value);
38
+ }
39
+ function resolveProtocol(p) {
40
+ return typeof p === "string" ? p : p.name;
41
+ }
42
+ function resolveRole(r) {
43
+ return typeof r === "string" ? r : r.name;
44
+ }
45
+ function resolveMessage(m) {
46
+ return typeof m === "string" ? m : m.name;
47
+ }
48
+ function resolveCheck(c) {
49
+ return typeof c === "string" ? c : c.id;
50
+ }
51
+ function resolveShape(s) {
52
+ return typeof s === "string" ? s : s.name;
53
+ }
54
+ function resolveSpec(spec) {
55
+ if (typeof spec === "string")
56
+ return spec;
57
+ if ("kind" in spec)
58
+ return compile(spec);
59
+ return spec;
60
+ }
61
+ function declAlias(a) {
62
+ if (!a.startsWith("$") || a.length === 1 || a[1] === "$") {
63
+ throw new ScenarioCompileError("alias", `invalid alias ${JSON.stringify(a)}`);
64
+ }
65
+ return a.slice(1);
66
+ }
67
+ function refAlias(a) {
68
+ return `$${declAlias(a)}`;
69
+ }
70
+ function addAliases(prev, items) {
71
+ const next = new Set(prev);
72
+ for (const a of items) {
73
+ const name = declAlias(a);
74
+ if (next.has(name)) {
75
+ throw new ScenarioCompileError("alias", `duplicate scenario alias $${name}`);
76
+ }
77
+ next.add(name);
78
+ }
79
+ return next;
80
+ }
81
+ function omitUndef(rec) {
82
+ return Object.fromEntries(Object.entries(rec).filter(([, v]) => v !== undefined));
83
+ }
84
+ function mapAliasKeys(rec, fn = (v) => v) {
85
+ if (rec === undefined)
86
+ return undefined;
87
+ const entries = [];
88
+ for (const [k, v] of Object.entries(rec)) {
89
+ if (v === undefined)
90
+ continue;
91
+ entries.push([refAlias(k), fn(v)]);
92
+ }
93
+ return Object.fromEntries(entries);
94
+ }
95
+ function normDebt(d) {
96
+ return omitUndef({
97
+ message: d.message !== undefined ? refAlias(d.message) : undefined,
98
+ shape: resolveShape(d.shape),
99
+ scope: d.scope,
100
+ variants: d.variants,
101
+ reason: d.reason,
102
+ instructions: d.instructions,
103
+ });
104
+ }
105
+ function isDebtArray(val) {
106
+ return Array.isArray(val);
107
+ }
108
+ function normRoleDebts(debts) {
109
+ const out = {};
110
+ for (const [roleName, val] of Object.entries(debts)) {
111
+ out[roleName] = isDebtArray(val) ? val.map(normDebt) : normDebt(val);
112
+ }
113
+ return out;
114
+ }
115
+ function normWorldConfig(world) {
116
+ if (world.seats === undefined)
117
+ return world;
118
+ const seats = {};
119
+ for (const [roleName, replies] of Object.entries(world.seats)) {
120
+ seats[roleName] = replies.map((r) => ({
121
+ ...(r.onCase !== undefined ? { onCase: r.onCase } : {}),
122
+ ...(r.onShape !== undefined ? { onShape: resolveShape(r.onShape) } : {}),
123
+ payload: r.payload,
124
+ }));
125
+ }
126
+ return { ...world, seats };
127
+ }
128
+ function normExpect(ex) {
129
+ if (ex === undefined)
130
+ return undefined;
131
+ const world = ex.world === undefined
132
+ ? undefined
133
+ : omitUndef({
134
+ awaitedChecks: ex.world.awaitedChecks?.map((c) => ({
135
+ check: resolveCheck(c.check),
136
+ args: c.args,
137
+ })),
138
+ calls: ex.world.calls,
139
+ });
140
+ return omitUndef({
141
+ result: ex.result,
142
+ states: mapAliasKeys(ex.states),
143
+ phases: mapAliasKeys(ex.phases),
144
+ data: mapAliasKeys(ex.data),
145
+ debts: mapAliasKeys(ex.debts, normRoleDebts),
146
+ seatDebts: mapAliasKeys(ex.seatDebts, (items) => items.map((it) => omitUndef({
147
+ case: refAlias(it.case),
148
+ shape: resolveShape(it.shape),
149
+ reason: it.reason,
150
+ }))),
151
+ views: mapAliasKeys(ex.views, (v) => omitUndef({
152
+ visibleCases: v.visibleCases?.map(refAlias),
153
+ hiddenCases: v.hiddenCases?.map(refAlias),
154
+ caseData: mapAliasKeys(v.caseData),
155
+ guides: mapAliasKeys(v.guides),
156
+ })),
157
+ trail: ex.trail,
158
+ world,
159
+ extensions: ex.extensions,
160
+ });
161
+ }
162
+ function normBind(bind) {
163
+ const entries = [];
164
+ for (const [alias, desc] of Object.entries(bind)) {
165
+ const bare = declAlias(alias);
166
+ if (desc.kind === "case") {
167
+ entries.push([
168
+ bare,
169
+ omitUndef({
170
+ kind: "case",
171
+ protocol: resolveProtocol(desc.protocol),
172
+ parent: desc.parent !== undefined ? refAlias(desc.parent) : undefined,
173
+ forRole: desc.forRole !== undefined ? resolveRole(desc.forRole) : undefined,
174
+ scope: desc.scope,
175
+ index: desc.index,
176
+ }),
177
+ ]);
178
+ }
179
+ else if (desc.kind === "seat") {
180
+ entries.push([
181
+ bare,
182
+ omitUndef({
183
+ kind: "seat",
184
+ role: resolveRole(desc.role),
185
+ case: desc.case !== undefined ? refAlias(desc.case) : undefined,
186
+ scope: desc.scope,
187
+ index: desc.index,
188
+ }),
189
+ ]);
190
+ }
191
+ else {
192
+ entries.push([
193
+ bare,
194
+ omitUndef({
195
+ kind: "message",
196
+ messageKind: resolveMessage(desc.messageKind),
197
+ case: desc.case !== undefined ? refAlias(desc.case) : undefined,
198
+ index: desc.index,
199
+ }),
200
+ ]);
201
+ }
202
+ }
203
+ return Object.fromEntries(entries);
204
+ }
205
+ function slug(v) {
206
+ const raw = typeof v === "string" || typeof v === "number" || typeof v === "boolean" ? String(v) : "";
207
+ const clean = raw
208
+ .replace(/^\$/, "")
209
+ .toLowerCase()
210
+ .replace(/[^a-z0-9/_.-]+/g, "-")
211
+ .replace(/^[^a-z0-9]+|[-_/.]+$/g, "");
212
+ return clean.length > 0 ? clean : "step";
213
+ }
214
+ function defaultStepIdBase(input) {
215
+ const kind = input["kind"];
216
+ if (kind === "open") {
217
+ return typeof input["as"] === "string"
218
+ ? `open-${slug(input["as"])}`
219
+ : `open-${slug(input["protocol"])}`;
220
+ }
221
+ if (kind === "bind-seat")
222
+ return `bind-${slug(input["as"])}`;
223
+ if (kind === "close-seat")
224
+ return `close-seat-${slug(input["seat"])}`;
225
+ if (kind === "runner-report")
226
+ return `runner-report-${slug(input["seat"])}`;
227
+ if (kind === "role-availability") {
228
+ return `role-${slug(input["role"])}-${input["available"] === true ? "available" : "away"}`;
229
+ }
230
+ if (kind === "answer") {
231
+ const c = slug(input["case"]);
232
+ const p = isRec(input["payload"]) ? input["payload"] : undefined;
233
+ if (p !== undefined && typeof p["_tag"] === "string")
234
+ return `answer-${c}-${slug(p["_tag"])}`;
235
+ if (p !== undefined && typeof p["option"] === "string") {
236
+ return `answer-${c}-${slug(p["option"])}`;
237
+ }
238
+ return `answer-${c}-${slug(input["seat"])}`;
239
+ }
240
+ if (kind === "message")
241
+ return `message-${slug(input["case"])}-${slug(input["messageKind"])}`;
242
+ if (kind === "read")
243
+ return `read-${slug(input["seat"])}-${slug(input["message"])}`;
244
+ if (kind === "cancel")
245
+ return `cancel-${slug(input["case"])}`;
246
+ if (kind === "adopt")
247
+ return "adopt-spec";
248
+ if (kind === "world-event") {
249
+ const ev = isRec(input["event"]) ? input["event"] : undefined;
250
+ if (ev?.["kind"] === "check") {
251
+ return `check-${slug(ev["check"])}-${ev["ok"] === true ? "ok" : "fail"}`;
252
+ }
253
+ if (ev?.["kind"] === "source")
254
+ return `source-${slug(ev["source"])}-${slug(ev["name"])}`;
255
+ return "world-event";
256
+ }
257
+ if (kind === "clock") {
258
+ return input["advanceMs"] !== undefined
259
+ ? `clock-advance-${slug(input["advanceMs"])}`
260
+ : "clock-at";
261
+ }
262
+ return `ext-${slug(kind)}`;
263
+ }
264
+ function assertValidStepId(id) {
265
+ if (!STEP_ID_RE.test(id)) {
266
+ throw new ScenarioCompileError("step.id", `invalid step id ${JSON.stringify(id)}`);
267
+ }
268
+ return id;
269
+ }
270
+ function formatStepNote(id, note) {
271
+ return note !== undefined && note.length > 0 ? `[id:${id}] ${note}` : `[id:${id}]`;
272
+ }
273
+ function allocateStepId(prev, input, explicitId) {
274
+ const next = new Set(prev);
275
+ if (explicitId !== undefined) {
276
+ const id = assertValidStepId(explicitId);
277
+ if (next.has(id)) {
278
+ throw new ScenarioCompileError("step.id", `duplicate scenario step id ${JSON.stringify(id)}`);
279
+ }
280
+ next.add(id);
281
+ return { id, next };
282
+ }
283
+ const base = assertValidStepId(defaultStepIdBase(input));
284
+ let candidate = base;
285
+ let n = 2;
286
+ while (next.has(candidate)) {
287
+ candidate = `${base}-${String(n)}`;
288
+ n += 1;
289
+ }
290
+ next.add(candidate);
291
+ return { id: candidate, next };
292
+ }
293
+ function rewriteAliasRef(val, map) {
294
+ if (!val.startsWith("$"))
295
+ return val;
296
+ const mapped = map.get(val.slice(1));
297
+ return mapped !== undefined ? `$${mapped}` : val;
298
+ }
299
+ function rewriteEmbedded(val, map) {
300
+ if (typeof val === "string") {
301
+ return rewriteAliasRef(val, map);
302
+ }
303
+ if (Array.isArray(val)) {
304
+ return val.map((el) => rewriteEmbedded(el, map));
305
+ }
306
+ if (!isRec(val))
307
+ return val;
308
+ const out = {};
309
+ for (const [k, v] of Object.entries(val)) {
310
+ if (k === "$absent" || k === "$contains") {
311
+ out[k] = v;
312
+ }
313
+ else {
314
+ const nextKey = k.startsWith("$") ? rewriteAliasRef(k, map) : k;
315
+ out[nextKey] = rewriteEmbedded(v, map);
316
+ }
317
+ }
318
+ return out;
319
+ }
320
+ function rewriteScopedStep(step, prefix, aliasMap) {
321
+ const match = typeof step.note === "string" ? STEP_NOTE_RE.exec(step.note) : null;
322
+ if (match?.[1] === undefined) {
323
+ throw new ScenarioCompileError("withScope", "scoped step is missing a step id");
324
+ }
325
+ const prefixedId = assertValidStepId(`${prefix}/${match[1]}`);
326
+ const inputEntries = [];
327
+ for (const [k, v] of Object.entries(step.input)) {
328
+ if (k === "as" && typeof v === "string") {
329
+ inputEntries.push([k, aliasMap.get(v) ?? v]);
330
+ }
331
+ else {
332
+ inputEntries.push([k, rewriteEmbedded(v, aliasMap)]);
333
+ }
334
+ }
335
+ const input = Object.fromEntries(inputEntries);
336
+ let bind;
337
+ if (step.bind !== undefined) {
338
+ const bindEntries = [];
339
+ for (const [k, v] of Object.entries(step.bind)) {
340
+ const nextAlias = aliasMap.get(k) ?? k;
341
+ const rewrittenDesc = rewriteEmbedded(v, aliasMap);
342
+ bindEntries.push([nextAlias, isRec(rewrittenDesc) ? rewrittenDesc : v]);
343
+ }
344
+ bind = Object.fromEntries(bindEntries);
345
+ }
346
+ const rewrittenExpect = step.expect !== undefined ? rewriteEmbedded(step.expect, aliasMap) : undefined;
347
+ const expectObj = isRec(rewrittenExpect) ? rewrittenExpect : undefined;
348
+ return {
349
+ id: prefixedId,
350
+ step: {
351
+ note: formatStepNote(prefixedId, match[2]),
352
+ input,
353
+ ...(bind !== undefined ? { bind } : {}),
354
+ ...(expectObj !== undefined ? { expect: expectObj } : {}),
355
+ },
356
+ };
357
+ }
358
+ const builderStates = new WeakMap();
359
+ function openWire(input, alias) {
360
+ return omitUndef({
361
+ kind: "open",
362
+ protocol: resolveProtocol(input.protocol),
363
+ parent: input.parent !== undefined ? refAlias(input.parent) : undefined,
364
+ forRole: input.forRole !== undefined ? resolveRole(input.forRole) : undefined,
365
+ scope: input.scope,
366
+ data: input.data,
367
+ as: alias !== undefined ? declAlias(alias) : undefined,
368
+ });
369
+ }
370
+ function bindSeatWire(input, alias) {
371
+ const base = {
372
+ kind: "bind-seat",
373
+ binding: input.binding,
374
+ role: resolveRole(input.role),
375
+ as: declAlias(alias),
376
+ ...(input.labels !== undefined ? { labels: input.labels } : {}),
377
+ };
378
+ if (input.binding === "case") {
379
+ return { ...base, case: refAlias(input.case) };
380
+ }
381
+ if (input.binding === "field") {
382
+ return { ...base, field: input.field, value: input.value };
383
+ }
384
+ if (input.binding === "ancestor") {
385
+ return { ...base, protocol: resolveProtocol(input.protocol), case: refAlias(input.case) };
386
+ }
387
+ return base;
388
+ }
389
+ function worldEventWire(event) {
390
+ if (event.kind === "check") {
391
+ return {
392
+ kind: "world-event",
393
+ event: omitUndef({
394
+ kind: "check",
395
+ check: resolveCheck(event.check),
396
+ args: event.args,
397
+ ok: event.ok,
398
+ hint: event.hint,
399
+ evidence: event.evidence,
400
+ }),
401
+ };
402
+ }
403
+ return { kind: "world-event", event: { kind: "source", instance: event.instance } };
404
+ }
405
+ function clockWire(input) {
406
+ return omitUndef({
407
+ kind: "clock",
408
+ at: "at" in input ? input.at : undefined,
409
+ advanceMs: "advanceMs" in input ? input.advanceMs : undefined,
410
+ });
411
+ }
412
+ function createBuilder(state) {
413
+ const pushStep = (input, options, extraAliases = []) => {
414
+ const bindAliases = options?.bind !== undefined ? Object.keys(options.bind) : [];
415
+ const nextAliases = extraAliases.length > 0 || bindAliases.length > 0
416
+ ? addAliases(state.aliases, [...extraAliases, ...bindAliases])
417
+ : state.aliases;
418
+ const { id, next: stepIds } = allocateStepId(state.stepIds, input, options?.id);
419
+ const bindWire = options?.bind !== undefined ? normBind(options.bind) : undefined;
420
+ const expectWire = normExpect(options?.expect);
421
+ const nextStep = {
422
+ note: formatStepNote(id, options?.note),
423
+ input,
424
+ ...(bindWire !== undefined ? { bind: bindWire } : {}),
425
+ ...(expectWire !== undefined ? { expect: expectWire } : {}),
426
+ };
427
+ return createBuilder({
428
+ ...state,
429
+ aliases: nextAliases,
430
+ stepIds,
431
+ steps: [...state.steps, nextStep],
432
+ });
433
+ };
434
+ function withScopeImpl(prefix, map, fn) {
435
+ if (!SCOPE_PREFIX_RE.test(prefix)) {
436
+ throw new ScenarioCompileError("withScope", `invalid scope prefix ${JSON.stringify(prefix)}`);
437
+ }
438
+ const aliasMap = new Map();
439
+ const localInit = new Set();
440
+ const allEntries = [
441
+ ...Object.entries(map.cases),
442
+ ...Object.entries(map.seats),
443
+ ...(map.messages !== undefined ? Object.entries(map.messages) : []),
444
+ ];
445
+ for (const [localAlias, outerAlias] of allEntries) {
446
+ const localName = declAlias(localAlias);
447
+ const outerName = declAlias(outerAlias);
448
+ if (!state.aliases.has(outerName)) {
449
+ throw new ScenarioCompileError("withScope", `unbound outer alias $${outerName} in withScope(${JSON.stringify(prefix)})`);
450
+ }
451
+ if (localInit.has(localName)) {
452
+ throw new ScenarioCompileError("withScope", `duplicate local alias $${localName} in withScope(${JSON.stringify(prefix)})`);
453
+ }
454
+ localInit.add(localName);
455
+ aliasMap.set(localName, outerName);
456
+ }
457
+ const sub = createBuilder({
458
+ ...state,
459
+ aliases: localInit,
460
+ stepIds: new Set(),
461
+ steps: [],
462
+ });
463
+ const result = fn(sub);
464
+ const inner = builderStates.get(result);
465
+ if (inner === undefined) {
466
+ throw new ScenarioCompileError("withScope", "withScope callback must return a builder derived from its argument");
467
+ }
468
+ const nextAliases = new Set(state.aliases);
469
+ for (const localName of inner.aliases) {
470
+ if (localInit.has(localName))
471
+ continue;
472
+ const wireName = `${prefix}_${localName}`;
473
+ if (nextAliases.has(wireName)) {
474
+ throw new ScenarioCompileError("withScope", `duplicate scenario alias $${wireName}`);
475
+ }
476
+ nextAliases.add(wireName);
477
+ aliasMap.set(localName, wireName);
478
+ }
479
+ const nextStepIds = new Set(state.stepIds);
480
+ const appended = [];
481
+ for (const step of inner.steps) {
482
+ const { step: rewritten, id } = rewriteScopedStep(step, prefix, aliasMap);
483
+ if (nextStepIds.has(id)) {
484
+ throw new ScenarioCompileError("withScope", `duplicate scenario step id ${JSON.stringify(id)}`);
485
+ }
486
+ nextStepIds.add(id);
487
+ appended.push(rewritten);
488
+ }
489
+ return createBuilder({
490
+ ...state,
491
+ aliases: nextAliases,
492
+ stepIds: nextStepIds,
493
+ steps: [...state.steps, ...appended],
494
+ });
495
+ }
496
+ const builder = {
497
+ world(world) {
498
+ return createBuilder({ ...state, world: normWorldConfig(world) });
499
+ },
500
+ config(config) {
501
+ return createBuilder({ ...state, config });
502
+ },
503
+ open(alias, input, options) {
504
+ return pushStep(openWire(input, alias), options, [alias]);
505
+ },
506
+ openUnbound(input, options) {
507
+ return pushStep(openWire(input), options);
508
+ },
509
+ bindSeat(alias, input, options) {
510
+ return pushStep(bindSeatWire(input, alias), options, [alias]);
511
+ },
512
+ closeSeat(seat, options) {
513
+ return pushStep({ kind: "close-seat", seat: refAlias(seat) }, options);
514
+ },
515
+ runnerReport(input, options) {
516
+ const r = input.report;
517
+ const report = omitUndef({ ref: r.ref, state: r.state, holder: r.holder, work: r.work });
518
+ return pushStep({ kind: "runner-report", seat: refAlias(input.seat), report }, options);
519
+ },
520
+ roleAvailability(input, options) {
521
+ return pushStep(omitUndef({
522
+ kind: "role-availability",
523
+ role: resolveRole(input.role),
524
+ available: input.available,
525
+ reason: input.reason,
526
+ }), options);
527
+ },
528
+ answer(input, options) {
529
+ return pushStep(omitUndef({
530
+ kind: "answer",
531
+ case: refAlias(input.case),
532
+ seat: refAlias(input.seat),
533
+ message: input.message !== undefined ? refAlias(input.message) : undefined,
534
+ payload: input.payload,
535
+ }), options);
536
+ },
537
+ message(input, options) {
538
+ return pushStep({
539
+ kind: "message",
540
+ case: refAlias(input.case),
541
+ seat: refAlias(input.seat),
542
+ toRole: resolveRole(input.toRole),
543
+ messageKind: resolveMessage(input.messageKind),
544
+ payload: input.payload,
545
+ }, options);
546
+ },
547
+ read(input, options) {
548
+ return pushStep({
549
+ kind: "read",
550
+ seat: refAlias(input.seat),
551
+ message: refAlias(input.message),
552
+ }, options);
553
+ },
554
+ worldEvent(event, options) {
555
+ return pushStep(worldEventWire(event), options);
556
+ },
557
+ clock(input, options) {
558
+ return pushStep(clockWire(input), options);
559
+ },
560
+ cancel(input, options) {
561
+ return pushStep({ kind: "cancel", case: refAlias(input.case), reason: input.reason }, options);
562
+ },
563
+ adopt(input, options) {
564
+ return pushStep(omitUndef({
565
+ kind: "adopt",
566
+ spec: resolveSpec(input.spec),
567
+ migration: input.migration,
568
+ }), options);
569
+ },
570
+ extension(input, options) {
571
+ return pushStep(input, options);
572
+ },
573
+ withScope: withScopeImpl,
574
+ build() {
575
+ const steps = Object.freeze([...state.steps]);
576
+ return Object.freeze({
577
+ format: "telar.scenario/1",
578
+ id: state.id,
579
+ title: state.title,
580
+ ...(state.stories !== undefined ? { stories: Object.freeze([...state.stories]) } : {}),
581
+ spec: state.spec,
582
+ ...(state.config !== undefined ? { config: state.config } : {}),
583
+ ...(state.world !== undefined ? { world: state.world } : {}),
584
+ steps,
585
+ });
586
+ },
587
+ };
588
+ builderStates.set(builder, state);
589
+ return builder;
590
+ }
591
+ export function scenario(init) {
592
+ return createBuilder({
593
+ id: init.id,
594
+ title: init.title,
595
+ stories: init.stories,
596
+ spec: resolveSpec(init.spec),
597
+ config: init.config,
598
+ world: init.world !== undefined ? normWorldConfig(init.world) : undefined,
599
+ aliases: new Set(),
600
+ stepIds: new Set(),
601
+ steps: [],
602
+ });
603
+ }
@@ -0,0 +1,35 @@
1
+ import type { NonEmpty } from "../spec.js";
2
+ import type { CheckInput, ProtocolInput, SpecInput, TelarScenarioV1 } from "./types.js";
3
+ type Rec = Readonly<Record<string, unknown>>;
4
+ export interface CheckGateStep {
5
+ readonly check: CheckInput;
6
+ readonly args: Rec;
7
+ readonly nextState: string;
8
+ readonly advanceMs?: number | undefined;
9
+ }
10
+ export interface CheckGateTemplateParams {
11
+ readonly id: string;
12
+ readonly title: string;
13
+ readonly spec: SpecInput;
14
+ readonly protocol: ProtocolInput;
15
+ readonly openData: Rec;
16
+ readonly startState: string;
17
+ readonly checks: NonEmpty<CheckGateStep>;
18
+ readonly clockStart?: string | undefined;
19
+ readonly stories?: NonEmpty<string> | undefined;
20
+ }
21
+ export declare function checkGateHappyPath(params: CheckGateTemplateParams): TelarScenarioV1;
22
+ export interface RefusalTemplateParams {
23
+ readonly id: string;
24
+ readonly title: string;
25
+ readonly spec: SpecInput;
26
+ readonly protocol: ProtocolInput;
27
+ readonly invalidData: Rec;
28
+ readonly expectedCode: string;
29
+ readonly reasonContains?: string | undefined;
30
+ readonly validData: Rec;
31
+ readonly startState: string;
32
+ readonly stories?: NonEmpty<string> | undefined;
33
+ }
34
+ export declare function refusalPreservesState(params: RefusalTemplateParams): TelarScenarioV1;
35
+ export {};
@@ -0,0 +1,64 @@
1
+ import { scenario } from "./builder.js";
2
+ export function checkGateHappyPath(params) {
3
+ let b = scenario({
4
+ id: params.id,
5
+ title: params.title,
6
+ spec: params.spec,
7
+ ...(params.stories !== undefined ? { stories: params.stories } : {}),
8
+ world: { clockStart: params.clockStart ?? "2026-01-01T00:00:00Z" },
9
+ }).open("$c1", { protocol: params.protocol, data: params.openData }, {
10
+ expect: {
11
+ result: { ok: true },
12
+ states: { $c1: params.startState },
13
+ phases: { $c1: "open" },
14
+ data: { $c1: params.openData },
15
+ },
16
+ });
17
+ for (const [index, step] of params.checks.entries()) {
18
+ if (step.advanceMs !== undefined) {
19
+ b = b.clock({ advanceMs: step.advanceMs });
20
+ }
21
+ const isFinal = index === params.checks.length - 1;
22
+ b = b.worldEvent({ kind: "check", check: step.check, args: step.args, ok: true }, {
23
+ expect: {
24
+ states: { $c1: step.nextState },
25
+ ...(isFinal ? { phases: { $c1: "closed" }, world: { awaitedChecks: [] } } : {}),
26
+ },
27
+ });
28
+ }
29
+ return b.build();
30
+ }
31
+ export function refusalPreservesState(params) {
32
+ return scenario({
33
+ id: params.id,
34
+ title: params.title,
35
+ spec: params.spec,
36
+ ...(params.stories !== undefined ? { stories: params.stories } : {}),
37
+ })
38
+ .openUnbound({ protocol: params.protocol, data: params.invalidData }, {
39
+ expect: {
40
+ result: {
41
+ ok: false,
42
+ code: params.expectedCode,
43
+ ...(params.reasonContains !== undefined
44
+ ? { reasonContains: params.reasonContains }
45
+ : {}),
46
+ },
47
+ trail: { absent: [{ kind: "case-opened" }] },
48
+ },
49
+ })
50
+ .open("$c1", { protocol: params.protocol, data: params.validData }, {
51
+ expect: {
52
+ result: { ok: true },
53
+ states: { $c1: params.startState },
54
+ phases: { $c1: "open" },
55
+ },
56
+ })
57
+ .cancel({ case: "$c1", reason: "template refusal cleanup" }, {
58
+ expect: {
59
+ result: { ok: true },
60
+ phases: { $c1: "cancelled" },
61
+ },
62
+ })
63
+ .build();
64
+ }