@aitoroses/telar 0.0.0 → 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 -3
  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 +62 -5
@@ -0,0 +1,318 @@
1
+ import { defineQuery, } from "../query.js";
2
+ const isRec = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3
+ const text = (value) => typeof value === "string"
4
+ ? value
5
+ : typeof value === "number" || typeof value === "boolean"
6
+ ? String(value)
7
+ : "";
8
+ function nonEmpty(row, key, issues) {
9
+ const value = row[key];
10
+ if (typeof value === "string" && value.length > 0)
11
+ return value;
12
+ issues.push({ message: "expected a non-empty string", path: [key] });
13
+ return "";
14
+ }
15
+ function int(row, key, min, issues) {
16
+ const value = row[key];
17
+ if (typeof value === "number" &&
18
+ Number.isSafeInteger(value) &&
19
+ (min === undefined || value >= min)) {
20
+ return value;
21
+ }
22
+ const bound = min === undefined ? "" : ` >= ${String(min)}`;
23
+ issues.push({ message: `expected an integer${bound}`, path: [key] });
24
+ return 0;
25
+ }
26
+ function phase(row, issues) {
27
+ switch (row["phase"]) {
28
+ case "open":
29
+ case "final-pending-effects":
30
+ case "closed":
31
+ case "cancelled":
32
+ return row["phase"];
33
+ default:
34
+ issues.push({ message: "expected a case phase", path: ["phase"] });
35
+ return "open";
36
+ }
37
+ }
38
+ function roles(row, issues) {
39
+ const raw = row["waitingOn"];
40
+ const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
41
+ if (Array.isArray(parsed) &&
42
+ parsed.every((role) => typeof role === "string" && role.length > 0)) {
43
+ return parsed.filter((role) => typeof role === "string");
44
+ }
45
+ issues.push({ message: "expected a JSON array of role names", path: ["waitingOn"] });
46
+ return [];
47
+ }
48
+ const schema = (decode) => ({
49
+ "~standard": {
50
+ version: 1,
51
+ vendor: "telar.std",
52
+ validate: (value) => {
53
+ if (!isRec(value))
54
+ return { issues: [{ message: "expected an object" }] };
55
+ const issues = [];
56
+ const row = decode(value, issues);
57
+ return issues.length > 0 ? { issues } : { value: row };
58
+ },
59
+ },
60
+ });
61
+ /** Decodes one row of `cases`: `waitingOn` arrives as JSON text. */
62
+ export const CasesRow = schema((row, issues) => {
63
+ const parent = row["parent"];
64
+ if (parent !== null && (typeof parent !== "string" || parent.length === 0)) {
65
+ issues.push({ message: "expected null or a case id", path: ["parent"] });
66
+ }
67
+ return {
68
+ case: nonEmpty(row, "case", issues),
69
+ protocol: nonEmpty(row, "protocol", issues),
70
+ state: nonEmpty(row, "state", issues),
71
+ phase: phase(row, issues),
72
+ parent: typeof parent === "string" ? parent : null,
73
+ enteredAt: int(row, "enteredAt", undefined, issues),
74
+ timeInStateMs: int(row, "timeInStateMs", 0, issues),
75
+ waitingOn: roles(row, issues),
76
+ };
77
+ });
78
+ const CASES_SQL = `
79
+ WITH spans AS (
80
+ SELECT o.case_id,
81
+ (SELECT x.at_ms FROM facts x
82
+ WHERE x.case_id = o.case_id AND x.kind IN ('case-opened', 'step-taken')
83
+ ORDER BY x.seq DESC LIMIT 1) AS entered,
84
+ (SELECT x.at_ms FROM facts x
85
+ WHERE x.case_id = o.case_id AND x.kind IN ('case-closed', 'case-cancelled')
86
+ ORDER BY x.seq DESC LIMIT 1) AS ended
87
+ FROM facts o WHERE o.kind = 'case-opened'
88
+ )
89
+ SELECT c.id AS "case", c.protocol, c.state, c.phase, c.parent,
90
+ s.entered AS enteredAt,
91
+ MAX(0, CASE WHEN c.phase IN ('closed', 'cancelled') THEN COALESCE(s.ended, s.entered)
92
+ ELSE (SELECT now_ms FROM clock) END - s.entered) AS timeInStateMs,
93
+ (SELECT json_group_array(role) FROM (
94
+ SELECT DISTINCT d.role FROM debts d WHERE d.case_id = c.id AND d.waiting ORDER BY d.role
95
+ )) AS waitingOn
96
+ FROM cases c JOIN spans s ON s.case_id = c.id
97
+ ORDER BY c.id
98
+ `;
99
+ /** Every case on the trail with its state, phase, time in state and the roles it waits on. */
100
+ export const cases = defineQuery({ name: "cases", sql: CASES_SQL, row: CasesRow });
101
+ const seatWho = (fact, seat) => fact.seatRole === null ? text(seat) : `${fact.seatRole} (${text(seat)})`;
102
+ function bindingText(binding) {
103
+ const b = isRec(binding) ? binding : {};
104
+ switch (b["kind"]) {
105
+ case "case":
106
+ return `case ${text(b["case_id"])}`;
107
+ case "field":
108
+ return `${text(b["field"])}=${text(b["value"])}`;
109
+ case "ancestor":
110
+ return `under ${text(b["protocol"])} ${text(b["case_id"])}`;
111
+ default:
112
+ return "all";
113
+ }
114
+ }
115
+ function openWhy(origin, method) {
116
+ const o = isRec(origin) ? origin : {};
117
+ switch (o["kind"]) {
118
+ case "child-effect":
119
+ return `step ${text(o["parent_step"])} on ${text(o["parent_case_id"])}`;
120
+ case "ack-missed":
121
+ return `ack missed on ${text(o["message"])} (attempt ${text(o["attempt"])})`;
122
+ case "source":
123
+ return `source ${text(o["instance"])} key ${text(o["key"])}`;
124
+ default:
125
+ return `external (${method})`;
126
+ }
127
+ }
128
+ function caseParts(f, p) {
129
+ const { source: src, method: meth } = f;
130
+ switch (f.kind) {
131
+ case "case-opened": {
132
+ const opened = `opened ${text(p["protocol"])} ${text(p["case_id"])}`;
133
+ const what = typeof p["parent"] === "string" ? `${opened} under ${p["parent"]}` : opened;
134
+ return [src, what, openWhy(p["origin"], meth)];
135
+ }
136
+ case "step-taken":
137
+ return [
138
+ src,
139
+ `step ${text(p["step"])}: ${text(p["from"])} -> ${text(p["to"])} (visit ${text(p["visit"])})`,
140
+ meth,
141
+ ];
142
+ case "case-closed":
143
+ return [src, `closed in state ${text(p["state"])}`, meth];
144
+ case "case-cancelled":
145
+ return [src, "cancelled case", text(p["reason"])];
146
+ case "child-ended":
147
+ return [
148
+ src,
149
+ `child ${text(p["child_case_id"])} (${text(p["protocol"])}) ${text(p["outcome"])}`,
150
+ meth,
151
+ ];
152
+ case "case-data-recorded":
153
+ return [
154
+ src,
155
+ `${p["mode"] === "append" ? "appended" : "set"} data field ${text(p["field"])}`,
156
+ meth,
157
+ ];
158
+ default:
159
+ return undefined;
160
+ }
161
+ }
162
+ function heldBy(holder) {
163
+ return Object.keys(holder)
164
+ .toSorted()
165
+ .map((key) => `${key}=${text(holder[key])}`)
166
+ .join(", ");
167
+ }
168
+ function seatParts(f, p) {
169
+ const meth = f.method;
170
+ switch (f.kind) {
171
+ case "seat-bound": {
172
+ const [seat, role] = [text(p["seat_id"]), text(p["role"])];
173
+ const holder = isRec(p["holder"]) ? p["holder"] : {};
174
+ const what = Object.keys(holder).length === 0
175
+ ? `bound seat ${seat} as ${role} (${bindingText(p["binding"])})`
176
+ : `seat ${seat} held by ${heldBy(holder)}`;
177
+ return [`${role} (${seat})`, what, meth];
178
+ }
179
+ case "answer-recorded":
180
+ return [`${text(p["role"])} (${text(p["seat_id"])})`, `answered ${text(p["shape"])}`, meth];
181
+ case "authorization-recorded": {
182
+ const what = typeof p["on_behalf_of"] === "string"
183
+ ? `authorized ${text(p["class"])} on behalf of ${p["on_behalf_of"]}`
184
+ : `authorized ${text(p["class"])}`;
185
+ return [`${text(p["by_role"])} (${text(p["by_seat"])})`, what, meth];
186
+ }
187
+ case "bound-limit-reached":
188
+ return [
189
+ text(p["owner_role"]),
190
+ `bound limit ${text(p["limit"])} reached on step ${text(p["step"])}`,
191
+ meth,
192
+ ];
193
+ case "bound-resolved":
194
+ return [
195
+ f.source,
196
+ `resolved bound on step ${text(p["step"])}: ${text(p["resolution"])}`,
197
+ text(p["note"]),
198
+ ];
199
+ default:
200
+ return undefined;
201
+ }
202
+ }
203
+ function messageParts(f, p) {
204
+ const { source: src, method: meth } = f;
205
+ const attempt = `(attempt ${text(p["attempt"])})`;
206
+ switch (f.kind) {
207
+ case "message-recorded": {
208
+ const origin = isRec(p["origin"]) ? p["origin"] : {};
209
+ const fromRole = typeof p["from_role"] === "string" ? p["from_role"] : undefined;
210
+ const direct = origin["kind"] === "direct-seat";
211
+ const who = direct
212
+ ? fromRole === undefined
213
+ ? seatWho(f, origin["from_seat"])
214
+ : `${fromRole} (${text(origin["from_seat"])})`
215
+ : (fromRole ?? src);
216
+ const why = direct ? `direct message (${meth})` : `effect of step ${text(origin["step"])}`;
217
+ return [who, `sent ${text(p["message_kind"])} to ${text(p["to_role"])}`, why];
218
+ }
219
+ case "message-delivered":
220
+ return [seatWho(f, p["seat_id"]), `delivered ${text(p["message"])} ${attempt}`, meth];
221
+ case "message-withheld":
222
+ return [
223
+ seatWho(f, p["seat_id"]),
224
+ `withheld ${text(p["message"])} ${attempt}`,
225
+ text(p["reason"]),
226
+ ];
227
+ case "message-read":
228
+ return [seatWho(f, p["seat_id"]), `read ${text(p["message"])}`, meth];
229
+ case "message-acked":
230
+ return [`${text(p["role"])} (${text(p["seat_id"])})`, `acked ${text(p["message"])}`, meth];
231
+ case "ack-missed":
232
+ return [src, `ack missed on ${text(p["message"])} ${attempt}: ${text(p["action"])}`, meth];
233
+ case "ack-miss-open-refused":
234
+ return [src, `ack-miss open refused on ${text(p["message"])} ${attempt}`, text(p["code"])];
235
+ default:
236
+ return undefined;
237
+ }
238
+ }
239
+ function worldParts(f, p) {
240
+ const { source: src, method: meth } = f;
241
+ switch (f.kind) {
242
+ case "check-observed": {
243
+ const method = isRec(p["method"]) ? p["method"] : undefined;
244
+ const who = method?.["kind"] === "computed" ? text(method["evaluator"]) : src;
245
+ const why = typeof p["hint"] === "string" ? p["hint"] : meth;
246
+ return [who, `check ${text(p["check"])} ${p["ok"] === true ? "passed" : "failed"}`, why];
247
+ }
248
+ case "action-requested":
249
+ return [src, `requested action ${text(p["action"])}`, `effect of step ${text(p["step"])}`];
250
+ case "action-completed": {
251
+ const verdict = p["ok"] === true ? "succeeded" : "failed";
252
+ const why = typeof p["code"] === "string" ? p["code"] : meth;
253
+ return [src, `action ${text(p["action"])} ${verdict} (request ${text(p["request"])})`, why];
254
+ }
255
+ default:
256
+ return undefined;
257
+ }
258
+ }
259
+ function describe(f) {
260
+ const p = f.payload;
261
+ return (caseParts(f, p) ??
262
+ seatParts(f, p) ??
263
+ messageParts(f, p) ??
264
+ worldParts(f, p) ?? [f.source, f.kind, f.method]);
265
+ }
266
+ /** Decodes one row of `case-story`: composes who, what and why from the fact's kind, provenance and payload. */
267
+ export const CaseStoryRow = schema((row, issues) => {
268
+ const raw = row["payload"];
269
+ const payload = typeof raw === "string" ? JSON.parse(raw) : raw;
270
+ if (!isRec(payload))
271
+ issues.push({ message: "expected a JSON object", path: ["payload"] });
272
+ const seatRole = row["seatRole"];
273
+ const fact = {
274
+ kind: nonEmpty(row, "kind", issues),
275
+ source: nonEmpty(row, "source", issues),
276
+ method: nonEmpty(row, "method", issues),
277
+ payload: isRec(payload) ? payload : {},
278
+ seatRole: typeof seatRole === "string" ? seatRole : null,
279
+ };
280
+ const [who, what, why] = describe(fact);
281
+ return {
282
+ seq: int(row, "seq", 1, issues),
283
+ id: nonEmpty(row, "id", issues),
284
+ when: int(row, "when", undefined, issues),
285
+ kind: fact.kind,
286
+ who,
287
+ what,
288
+ why,
289
+ };
290
+ });
291
+ const CASE_ID = /^c-[0-9]{6,}$/;
292
+ const caseId = {
293
+ "~standard": {
294
+ version: 1,
295
+ vendor: "telar.std",
296
+ validate: (value) => typeof value === "string" && CASE_ID.test(value)
297
+ ? { value }
298
+ : { issues: [{ message: "expected a case id such as c-000001" }] },
299
+ },
300
+ };
301
+ const CASE_STORY_SQL = `
302
+ SELECT f.seq, f.id, f.at_ms AS "when", f.kind, f.source, f.method, f.payload,
303
+ (SELECT json_extract(b.payload, '$.role') FROM facts b
304
+ WHERE b.kind = 'seat-bound'
305
+ AND json_extract(b.payload, '$.seat_id') =
306
+ COALESCE(json_extract(f.payload, '$.seat_id'), json_extract(f.payload, '$.origin.from_seat'))
307
+ ORDER BY b.seq LIMIT 1) AS seatRole
308
+ FROM facts f
309
+ WHERE f.case_id = :case
310
+ ORDER BY f.seq
311
+ `;
312
+ /** One case's facts in append order, each told as who did what and why. */
313
+ export const caseStory = defineQuery({
314
+ name: "case-story",
315
+ args: { case: { schema: caseId, description: "a case id, such as c-000001" } },
316
+ sql: CASE_STORY_SQL,
317
+ row: CaseStoryRow,
318
+ });
@@ -0,0 +1,17 @@
1
+ import { type AnyContract, type AnyRole, type Check, type Contract, type FieldRef, type FieldSchemaMap, type NonEmpty, type Protocol, type ProtocolDataInput, type UnionType } from "../spec.js";
2
+ import { type compareStringArgs } from "./compare.js";
3
+ export declare function verdictContract<const Name extends string, const V extends string>(name: Name, verdicts: NonEmpty<V>, fieldsPerVerdict?: FieldSchemaMap): Contract<Name, UnionType<Readonly<Record<V, FieldSchemaMap>>>, unknown, V>;
4
+ export interface BlindReaderSpec<V extends string = string> {
5
+ readonly role: AnyRole;
6
+ readonly answerShape: AnyContract;
7
+ readonly recordFields?: readonly FieldRef[] | undefined;
8
+ readonly verdictToState: Readonly<Record<V, string>>;
9
+ }
10
+ export declare function readingProtocol<const Name extends string, const F extends string>(def: {
11
+ readonly name: Name;
12
+ readonly data: ProtocolDataInput;
13
+ readonly finalStates: NonEmpty<F>;
14
+ readonly readerField?: FieldRef<string, string> | undefined;
15
+ readonly readers: NonEmpty<BlindReaderSpec>;
16
+ readonly compareStringCheck?: Check<string, typeof compareStringArgs> | undefined;
17
+ }): Protocol<Name, string, F>;
@@ -0,0 +1,88 @@
1
+ import { contract, protocol, roleView, set, step, t, } from "../spec.js";
2
+ import { compareString } from "./compare.js";
3
+ export function verdictContract(name, verdicts, fieldsPerVerdict = {}) {
4
+ const variants = {};
5
+ for (const v of verdicts) {
6
+ variants[v] = fieldsPerVerdict;
7
+ }
8
+ return contract(name, t.union(variants));
9
+ }
10
+ function verdictAnswerNeed(targetRole, shape, variant) {
11
+ const roles = Object.freeze([targetRole]);
12
+ const variants = Object.freeze([variant]);
13
+ return Object.freeze({
14
+ kind: "answer-need",
15
+ roles,
16
+ shape,
17
+ variants,
18
+ });
19
+ }
20
+ export function readingProtocol(def) {
21
+ const cmpStr = def.compareStringCheck ?? compareString;
22
+ const roleViews = def.readers.map((r) => roleView(r.role, "blind"));
23
+ const stepsList = [];
24
+ if (def.readers.length === 1 && def.readerField === undefined) {
25
+ const reader = def.readers[0];
26
+ for (const [variant, targetState] of Object.entries(reader.verdictToState)) {
27
+ const effects = (reader.recordFields ?? []).map((f) => set(f, { kind: "answer-ref", name: f.name }));
28
+ stepsList.push(step(`${reader.role.name}-${targetState}`, {
29
+ from: "reading",
30
+ to: targetState,
31
+ needs: [verdictAnswerNeed(reader.role, reader.answerShape, variant)],
32
+ then: effects,
33
+ }));
34
+ }
35
+ const [step0, ...stepRest] = stepsList;
36
+ if (step0 === undefined) {
37
+ throw new Error(`readingProtocol(${def.name}) requires at least one verdict`);
38
+ }
39
+ const states = ["reading", ...def.finalStates];
40
+ return protocol(def.name, {
41
+ states,
42
+ start: "reading",
43
+ final: def.finalStates,
44
+ data: def.data,
45
+ roleViews,
46
+ steps: [step0, ...stepRest],
47
+ });
48
+ }
49
+ if (def.readerField === undefined) {
50
+ throw new Error(`readingProtocol(${def.name}) with multiple readers requires readerField`);
51
+ }
52
+ const readerStates = [];
53
+ for (const reader of def.readers) {
54
+ const readingState = `reading-${reader.role.name}`;
55
+ readerStates.push(readingState);
56
+ stepsList.push(step(`assign-${reader.role.name}`, {
57
+ from: "opening",
58
+ to: readingState,
59
+ needs: [cmpStr({ left: def.readerField, op: "eq", right: reader.role.name })],
60
+ }));
61
+ for (const [variant, targetState] of Object.entries(reader.verdictToState)) {
62
+ const effects = (reader.recordFields ?? []).map((f) => set(f, { kind: "answer-ref", name: f.name }));
63
+ stepsList.push(step(`${reader.role.name}-${targetState}`, {
64
+ from: readingState,
65
+ to: targetState,
66
+ needs: [verdictAnswerNeed(reader.role, reader.answerShape, variant)],
67
+ then: effects,
68
+ }));
69
+ }
70
+ }
71
+ const [step0, ...stepRest] = stepsList;
72
+ if (step0 === undefined) {
73
+ throw new Error(`readingProtocol(${def.name}) requires at least one step`);
74
+ }
75
+ const states = [
76
+ "opening",
77
+ ...def.finalStates,
78
+ ...readerStates,
79
+ ];
80
+ return protocol(def.name, {
81
+ states,
82
+ start: "opening",
83
+ final: def.finalStates,
84
+ data: def.data,
85
+ roleViews,
86
+ steps: [step0, ...stepRest],
87
+ });
88
+ }
@@ -0,0 +1,19 @@
1
+ import type { StandardSchema } from "../standard-schema.js";
2
+ import { type Source } from "../source.js";
3
+ export type ScheduleDay = "sun" | "mon" | "tue" | "wed" | "thu" | "fri" | "sat";
4
+ /** Poll cadence (`every`), or a ritual on the calendar of an IANA zone (`at`, `tz`, `on`). */
5
+ export type ScheduleOptions = {
6
+ readonly every: string;
7
+ } | {
8
+ readonly at: string;
9
+ readonly tz: string;
10
+ readonly on?: readonly ScheduleDay[];
11
+ };
12
+ export declare const SCHEDULE_SOURCE_ID = "telar.std/source/schedule/1";
13
+ /**
14
+ * std's schedule, written on the public SDK like any installation's source.
15
+ * Missed slots collapse to the latest one, and each slot's key is its ISO-UTC instant.
16
+ */
17
+ export declare const schedule: Source<typeof SCHEDULE_SOURCE_ID, ScheduleOptions, {
18
+ readonly slot: StandardSchema<string>;
19
+ }>;
@@ -0,0 +1,122 @@
1
+ import { formatIsoUtc, parseIsoUtc, zoneOffset } from "../iso.js";
2
+ import { defineSource } from "../source.js";
3
+ export const SCHEDULE_SOURCE_ID = "telar.std/source/schedule/1";
4
+ const DAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
5
+ const MINUTE_MS = 60_000;
6
+ const DAY_MS = 86_400_000;
7
+ const EVERY_RE = /^([1-9][0-9]*)(m|h)$/;
8
+ const AT_RE = /^([01][0-9]|2[0-3]):([0-5][0-9])$/;
9
+ function isRec(value) {
10
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11
+ }
12
+ function issue(path, message) {
13
+ return [{ path: path.length > 0 ? [path] : [], message }];
14
+ }
15
+ function parseEvery(raw) {
16
+ const m = typeof raw === "string" ? EVERY_RE.exec(raw) : null;
17
+ if (m === null)
18
+ return issue("every", 'every must be "<n>m" or "<n>h"; use at and tz for a ritual');
19
+ const ms = Number(m[1]) * (m[2] === "h" ? 60 : 1) * MINUTE_MS;
20
+ return { kind: "every", ms, options: { every: m[0] } };
21
+ }
22
+ function parseOn(raw) {
23
+ if (raw === undefined)
24
+ return DAYS;
25
+ if (!Array.isArray(raw) || raw.length === 0)
26
+ return undefined;
27
+ const days = raw.map((d) => DAYS.find((name) => name === d));
28
+ return days.every((d) => d !== undefined) ? days : undefined;
29
+ }
30
+ function parseAt(raw) {
31
+ const m = typeof raw["at"] === "string" ? AT_RE.exec(raw["at"]) : null;
32
+ if (m === null)
33
+ return issue("at", 'at must be "HH:MM"');
34
+ const tz = raw["tz"];
35
+ if (typeof tz !== "string" || zoneOffset(tz, 0) === undefined) {
36
+ return issue("tz", "tz must be an IANA time zone, such as Europe/Madrid");
37
+ }
38
+ const on = parseOn(raw["on"]);
39
+ if (on === undefined)
40
+ return issue("on", `on must be a non-empty list of ${DAYS.join(", ")}`);
41
+ const days = new Set(on.map((d) => DAYS.indexOf(d)));
42
+ const options = { at: m[0], tz, ...(raw["on"] === undefined ? {} : { on }) };
43
+ return { kind: "at", minute: Number(m[1]) * 60 + Number(m[2]), tz, on: days, options };
44
+ }
45
+ function parseOptions(raw) {
46
+ if (!isRec(raw))
47
+ return issue("", "options must be an object");
48
+ const allowed = "every" in raw ? ["every"] : ["at", "tz", "on"];
49
+ const extra = Object.keys(raw).find((k) => !allowed.includes(k));
50
+ if (extra !== undefined)
51
+ return issue(extra, `${extra} is not an option of this form`);
52
+ return "every" in raw ? parseEvery(raw["every"]) : parseAt(raw);
53
+ }
54
+ const optionsSchema = {
55
+ "~standard": {
56
+ version: 1,
57
+ vendor: "telar.std",
58
+ validate: (raw) => {
59
+ const parsed = parseOptions(raw);
60
+ return "kind" in parsed ? { value: parsed.options } : { issues: parsed };
61
+ },
62
+ },
63
+ };
64
+ const slotSchema = {
65
+ "~standard": {
66
+ version: 1,
67
+ vendor: "telar.std",
68
+ validate: (raw) => typeof raw === "string" && parseIsoUtc(raw) !== undefined
69
+ ? { value: raw }
70
+ : { issues: [{ message: "slot must be an ISO-UTC instant" }] },
71
+ },
72
+ };
73
+ function offsetMs(tz, epochMs) {
74
+ return (zoneOffset(tz, epochMs) ?? 0) * MINUTE_MS;
75
+ }
76
+ /** The instant of a wall time in `tz`, with the "compatible" disambiguation of Temporal and RFC 5545. */
77
+ function wallToInstant(wallMs, tz) {
78
+ const before = wallMs - offsetMs(tz, wallMs - DAY_MS);
79
+ const after = wallMs - offsetMs(tz, wallMs + DAY_MS);
80
+ const fits = (t) => t + offsetMs(tz, t) === wallMs;
81
+ if (fits(before) && fits(after))
82
+ return Math.min(before, after);
83
+ if (fits(before))
84
+ return before;
85
+ if (fits(after))
86
+ return after;
87
+ return before;
88
+ }
89
+ function latestCalendarSlot(nowMs, at) {
90
+ const today = Math.floor((nowMs + offsetMs(at.tz, nowMs)) / DAY_MS);
91
+ for (let day = today; day >= today - 7; day -= 1) {
92
+ if (!at.on.has((((day + 4) % 7) + 7) % 7))
93
+ continue;
94
+ const slot = wallToInstant(day * DAY_MS + at.minute * MINUTE_MS, at.tz);
95
+ if (slot <= nowMs)
96
+ return slot;
97
+ }
98
+ return undefined;
99
+ }
100
+ /**
101
+ * std's schedule, written on the public SDK like any installation's source.
102
+ * Missed slots collapse to the latest one, and each slot's key is its ISO-UTC instant.
103
+ */
104
+ export const schedule = defineSource({
105
+ id: SCHEDULE_SOURCE_ID,
106
+ options: optionsSchema,
107
+ event: { slot: slotSchema },
108
+ poll: ({ now, last, options }) => {
109
+ const parsed = parseOptions(options);
110
+ const nowMs = parseIsoUtc(now);
111
+ if (!("kind" in parsed) || nowMs === undefined)
112
+ return [];
113
+ const slotMs = parsed.kind === "every"
114
+ ? Math.floor(nowMs / parsed.ms) * parsed.ms
115
+ : latestCalendarSlot(nowMs, parsed);
116
+ const lastMs = last === undefined ? undefined : parseIsoUtc(last.at);
117
+ if (slotMs === undefined || (lastMs !== undefined && slotMs <= lastMs))
118
+ return [];
119
+ const slot = formatIsoUtc(slotMs);
120
+ return [{ key: slot, at: slot, data: { slot } }];
121
+ },
122
+ });
package/dist/std.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ export { judgmentAccuracy, type JudgmentAccuracyRow } from "./std/accuracy.js";
2
+ export { HOUR_MS, defaultMissPolicy, missedAckAnswer, missedAckProtocol } from "./std/ack.js";
3
+ export { BRIEF_VALIDATOR_ID, ENGINEERING_TEXT_MAX, PROSE_VALIDATOR_ID, briefOption, briefRecommendation, briefUrgency, engineeringText, optionId, personText, stdBrief, typedRef, type StdBrief, type StdBriefOption, type StdBriefRecommendation, type StdBriefUrgency, type StdTypedRef, } from "./std/brief.js";
4
+ export { CLAUDE_CODE_RUNNER_ID, claudeCodeRunner, type ClaudeCodeRunnerId, type ClaudeCodeRunnerOptions, } from "./std/claude-code.js";
5
+ export { COMPARE_EVALUATOR_ID, compareBool, compareBoolArgs, compareNumber, compareNumberArgs, compareString, compareStringArgs, stdCompareChecks, type EqCompareOp, type OrderCompareOp, type StdCompareChecks, } from "./std/compare.js";
6
+ export { GIT_WORKSPACE_GRANT, GIT_WORKSPACE_LOCK_REF, GIT_WORKSPACE_LOCK_STALE_MS, GitWorkspaceError, gitWorkspace, type GitRepo, type GitWorkspace, type GitWorkspaceErrorCode, type GitWorkspaceRoots, type PreparedWorkspace, } from "./std/git-workspace.js";
7
+ export { LADDER_EVALUATOR_ID, choiceKind, compileJudgmentFragment, customKind, judgmentOverrideProtocol, judgmentProtocol, ladder, withRungLabels, type ChoiceKindDef, type CustomKindDef, type JudgmentFragment, type JudgmentInput, type JudgmentKindDef, type JudgmentPolicyDef, type JudgmentProtocolBundle, type JudgmentRung, type LadderPolicy, type LadderRung, } from "./std/judgment.js";
8
+ export { COMMAND_OBSERVER_ID, commandObserver, type CommandEntry, type CommandParams, } from "./std/observe-command.js";
9
+ export { GITHUB_CHECKS_OBSERVER_ID, githubChecksObserver, type GithubChecksEntry, type GithubChecksParams, } from "./std/observe-github-checks.js";
10
+ export { HTTP_STATUS_OBSERVER_ID, httpStatusObserver, type HttpStatusEntry, type HttpStatusParams, } from "./std/observe-http-status.js";
11
+ export { planProtocol } from "./std/plan.js";
12
+ export { CaseStoryRow, CasesRow, caseStory, cases } from "./std/queries.js";
13
+ export { readingProtocol, verdictContract, type BlindReaderSpec } from "./std/reading.js";
14
+ export { SCHEDULE_SOURCE_ID, schedule, type ScheduleDay, type ScheduleOptions, } from "./std/schedule.js";
15
+ export { stdActions, type StdActions } from "./std/actions.js";
package/dist/std.js ADDED
@@ -0,0 +1,15 @@
1
+ export { judgmentAccuracy } from "./std/accuracy.js";
2
+ export { HOUR_MS, defaultMissPolicy, missedAckAnswer, missedAckProtocol } from "./std/ack.js";
3
+ export { BRIEF_VALIDATOR_ID, ENGINEERING_TEXT_MAX, PROSE_VALIDATOR_ID, briefOption, briefRecommendation, briefUrgency, engineeringText, optionId, personText, stdBrief, typedRef, } from "./std/brief.js";
4
+ export { CLAUDE_CODE_RUNNER_ID, claudeCodeRunner, } from "./std/claude-code.js";
5
+ export { COMPARE_EVALUATOR_ID, compareBool, compareBoolArgs, compareNumber, compareNumberArgs, compareString, compareStringArgs, stdCompareChecks, } from "./std/compare.js";
6
+ export { GIT_WORKSPACE_GRANT, GIT_WORKSPACE_LOCK_REF, GIT_WORKSPACE_LOCK_STALE_MS, GitWorkspaceError, gitWorkspace, } from "./std/git-workspace.js";
7
+ export { LADDER_EVALUATOR_ID, choiceKind, compileJudgmentFragment, customKind, judgmentOverrideProtocol, judgmentProtocol, ladder, withRungLabels, } from "./std/judgment.js";
8
+ export { COMMAND_OBSERVER_ID, commandObserver, } from "./std/observe-command.js";
9
+ export { GITHUB_CHECKS_OBSERVER_ID, githubChecksObserver, } from "./std/observe-github-checks.js";
10
+ export { HTTP_STATUS_OBSERVER_ID, httpStatusObserver, } from "./std/observe-http-status.js";
11
+ export { planProtocol } from "./std/plan.js";
12
+ export { CaseStoryRow, CasesRow, caseStory, cases } from "./std/queries.js";
13
+ export { readingProtocol, verdictContract } from "./std/reading.js";
14
+ export { SCHEDULE_SOURCE_ID, schedule, } from "./std/schedule.js";
15
+ export { stdActions } from "./std/actions.js";