@giljae/pi-pstack 0.0.0-stage → 0.0.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 (142) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +67 -2
  3. package/agents/comment-sicko.md +35 -0
  4. package/agents/poteto-agent.md +12 -0
  5. package/harness/pi.md +87 -0
  6. package/package.json +37 -4
  7. package/skills/architect/SKILL.md +14 -0
  8. package/skills/arena/SKILL.md +51 -0
  9. package/skills/automate-me/SKILL.md +107 -0
  10. package/skills/benchmark-checklist/SKILL.md +42 -0
  11. package/skills/blast-radius/SKILL.md +53 -0
  12. package/skills/bro/SKILL.md +10 -0
  13. package/skills/correct/SKILL.md +35 -0
  14. package/skills/create-formal-verification-skill/SKILL.md +46 -0
  15. package/skills/create-verification-skill/SKILL.md +47 -0
  16. package/skills/create-verification-skill/references/feature-map-example/README.md +47 -0
  17. package/skills/create-verification-skill/references/feature-map-example/create-note.md +39 -0
  18. package/skills/create-verification-skill/references/feature-map-example/search.md +45 -0
  19. package/skills/figure-it-out/SKILL.md +55 -0
  20. package/skills/how/SKILL.md +24 -0
  21. package/skills/in-your-own-words/SKILL.md +10 -0
  22. package/skills/interrogate/SKILL.md +34 -0
  23. package/skills/ketchup/SKILL.md +46 -0
  24. package/skills/ketchup-video/SKILL.md +32 -0
  25. package/skills/maintain-formal-verification-skill/SKILL.md +61 -0
  26. package/skills/maintain-verification-skill/SKILL.md +42 -0
  27. package/skills/make-bot-ui/SKILL.md +118 -0
  28. package/skills/no-comments/SKILL.md +27 -0
  29. package/skills/poteto-help/SKILL.md +165 -0
  30. package/skills/poteto-help/references/prompting.md +51 -0
  31. package/skills/poteto-help/references/recipes.md +51 -0
  32. package/skills/poteto-mode/SKILL.md +111 -0
  33. package/skills/poteto-mode/playbooks/authoring-a-skill.md +12 -0
  34. package/skills/poteto-mode/playbooks/autonomous-run.md +13 -0
  35. package/skills/poteto-mode/playbooks/autopilot-full.md +25 -0
  36. package/skills/poteto-mode/playbooks/autopilot-stack.md +8 -0
  37. package/skills/poteto-mode/playbooks/babysit.md +10 -0
  38. package/skills/poteto-mode/playbooks/bug-fix.md +15 -0
  39. package/skills/poteto-mode/playbooks/eval.md +25 -0
  40. package/skills/poteto-mode/playbooks/feature.md +21 -0
  41. package/skills/poteto-mode/playbooks/hillclimb.md +21 -0
  42. package/skills/poteto-mode/playbooks/investigation.md +14 -0
  43. package/skills/poteto-mode/playbooks/multi-phase-plan.md +11 -0
  44. package/skills/poteto-mode/playbooks/opening-a-pr.md +9 -0
  45. package/skills/poteto-mode/playbooks/pause-safely.md +10 -0
  46. package/skills/poteto-mode/playbooks/perf-issue.md +25 -0
  47. package/skills/poteto-mode/playbooks/prototype.md +14 -0
  48. package/skills/poteto-mode/playbooks/refactoring.md +16 -0
  49. package/skills/poteto-mode/playbooks/runtime-forensics.md +11 -0
  50. package/skills/poteto-mode/playbooks/session-pickup.md +11 -0
  51. package/skills/poteto-mode/playbooks/shipping.md +12 -0
  52. package/skills/poteto-mode/playbooks/trace-forensics.md +14 -0
  53. package/skills/poteto-mode/playbooks/visual-parity.md +11 -0
  54. package/skills/poteto-mode/playbooks/worktree-cleanup.md +12 -0
  55. package/skills/poteto-mode/references/bugbot-triage.md +142 -0
  56. package/skills/poteto-mode/scripts/bootstrap.ts +62 -0
  57. package/skills/poteto-mode/scripts/bun.lock +67 -0
  58. package/skills/poteto-mode/scripts/package.json +16 -0
  59. package/skills/poteto-mode/scripts/watch-pr/cli.test.ts +224 -0
  60. package/skills/poteto-mode/scripts/watch-pr/cli.ts +223 -0
  61. package/skills/poteto-mode/scripts/watch-pr/fakes.test-helper.ts +129 -0
  62. package/skills/poteto-mode/scripts/watch-pr/github.test.ts +498 -0
  63. package/skills/poteto-mode/scripts/watch-pr/github.ts +726 -0
  64. package/skills/poteto-mode/scripts/watch-pr/policy.test.ts +482 -0
  65. package/skills/poteto-mode/scripts/watch-pr/policy.ts +842 -0
  66. package/skills/poteto-mode/scripts/watch-pr/render.ts +169 -0
  67. package/skills/poteto-mode/scripts/watch-pr/tsconfig.json +13 -0
  68. package/skills/poteto-mode/scripts/watch-pr/types.compile.ts +93 -0
  69. package/skills/poteto-mode/scripts/watch-pr/types.ts +414 -0
  70. package/skills/poteto-mode/scripts/watch-pr/watch-pr +6 -0
  71. package/skills/poteto-mode/scripts/worktree-audit.sh +134 -0
  72. package/skills/poteto-mode/worker.md +11 -0
  73. package/skills/principle-attack-the-premise/SKILL.md +18 -0
  74. package/skills/principle-boundary-discipline/SKILL.md +14 -0
  75. package/skills/principle-build-the-lever/SKILL.md +17 -0
  76. package/skills/principle-encode-lessons-in-structure/SKILL.md +14 -0
  77. package/skills/principle-exhaust-the-design-space/SKILL.md +12 -0
  78. package/skills/principle-experience-first/SKILL.md +22 -0
  79. package/skills/principle-explain-the-number/SKILL.md +17 -0
  80. package/skills/principle-fix-root-causes/SKILL.md +17 -0
  81. package/skills/principle-foundational-thinking/SKILL.md +16 -0
  82. package/skills/principle-guard-the-context-window/SKILL.md +15 -0
  83. package/skills/principle-laziness-protocol/SKILL.md +13 -0
  84. package/skills/principle-make-operations-idempotent/SKILL.md +18 -0
  85. package/skills/principle-migrate-callers-then-delete-legacy-apis/SKILL.md +17 -0
  86. package/skills/principle-minimize-reader-load/SKILL.md +18 -0
  87. package/skills/principle-model-the-domain/SKILL.md +18 -0
  88. package/skills/principle-never-block-on-the-human/SKILL.md +18 -0
  89. package/skills/principle-outcome-oriented-execution/SKILL.md +24 -0
  90. package/skills/principle-prove-it-works/SKILL.md +14 -0
  91. package/skills/principle-redesign-from-first-principles/SKILL.md +19 -0
  92. package/skills/principle-separate-before-serializing-shared-state/SKILL.md +14 -0
  93. package/skills/principle-sequence-verifiable-units/SKILL.md +16 -0
  94. package/skills/principle-subtract-before-you-add/SKILL.md +21 -0
  95. package/skills/principle-test-behavior-not-implementation/SKILL.md +19 -0
  96. package/skills/principle-type-system-discipline/SKILL.md +18 -0
  97. package/skills/recall/SKILL.md +38 -0
  98. package/skills/reflect/SKILL.md +20 -0
  99. package/skills/setup-pstack/SKILL.md +81 -0
  100. package/skills/sharpen/SKILL.md +19 -0
  101. package/skills/show-me-your-work/SKILL.md +85 -0
  102. package/skills/show-me-your-work/references/decision-log-template.tsv +1 -0
  103. package/skills/show-me-your-work/scripts/log.sh +42 -0
  104. package/skills/statechart/SKILL.md +85 -0
  105. package/skills/statechart/references/render.md +93 -0
  106. package/skills/statechart/scripts/backends/cfg.ts +33 -0
  107. package/skills/statechart/scripts/backends/mermaid.ts +249 -0
  108. package/skills/statechart/scripts/backends/plain-text.ts +72 -0
  109. package/skills/statechart/scripts/backends/report.ts +177 -0
  110. package/skills/statechart/scripts/frontends/config.ts +276 -0
  111. package/skills/statechart/scripts/frontends/dot.ts +74 -0
  112. package/skills/statechart/scripts/frontends/marks.ts +93 -0
  113. package/skills/statechart/scripts/frontends/messages.ts +52 -0
  114. package/skills/statechart/scripts/frontends/spec.ts +114 -0
  115. package/skills/statechart/scripts/frontends/trace.ts +24 -0
  116. package/skills/statechart/scripts/frontends/value.ts +166 -0
  117. package/skills/statechart/scripts/frontends/verdict.ts +40 -0
  118. package/skills/statechart/scripts/frontends/view.ts +119 -0
  119. package/skills/statechart/scripts/ir.ts +547 -0
  120. package/skills/statechart/scripts/package.json +11 -0
  121. package/skills/statechart/scripts/passes/annotate.ts +128 -0
  122. package/skills/statechart/scripts/passes/label.ts +269 -0
  123. package/skills/statechart/scripts/passes/lift.ts +85 -0
  124. package/skills/statechart/scripts/passes/loop-check.ts +68 -0
  125. package/skills/statechart/scripts/passes/paths.ts +60 -0
  126. package/skills/statechart/scripts/passes/reach.ts +135 -0
  127. package/skills/statechart/scripts/passes/region-check.ts +97 -0
  128. package/skills/statechart/scripts/passes/regions.ts +295 -0
  129. package/skills/statechart/scripts/pipeline.ts +76 -0
  130. package/skills/statechart/scripts/run.ts +506 -0
  131. package/skills/statechart/scripts/statechart +29 -0
  132. package/skills/statechart/scripts/statechart.ts +164 -0
  133. package/skills/statechart/scripts/tsconfig.json +11 -0
  134. package/skills/statechart/scripts/worker.ts +35 -0
  135. package/skills/swarm/SKILL.md +44 -0
  136. package/skills/tdd/SKILL.md +45 -0
  137. package/skills/teach/SKILL.md +24 -0
  138. package/skills/technical-writing/SKILL.md +73 -0
  139. package/skills/typescript-best-practices/SKILL.md +33 -0
  140. package/skills/typescript-best-practices/references/patterns.md +328 -0
  141. package/skills/unslop/SKILL.md +43 -0
  142. package/skills/why/SKILL.md +12 -0
@@ -0,0 +1,547 @@
1
+ export type Value =
2
+ | boolean
3
+ | number
4
+ | string
5
+ | { kind: "model"; name: string }
6
+ | { kind: "set"; members: Value[] }
7
+ | { kind: "interval"; lo: number; hi: number }
8
+ | { kind: "function"; printedAs: "tuple" | "record" | "pairs"; keys: Value[]; values: Value[] };
9
+
10
+ export type Vars = { [name: string]: Value };
11
+
12
+ export type Rule = { kind: "invariant" | "deadlock" | "property"; name: string };
13
+
14
+ type StateBase = { vars: Vars; start: boolean; breaks: Rule[] };
15
+
16
+ export type PastState = StateBase & { ends: Rule[]; past: true; excluded: boolean };
17
+
18
+ export type State =
19
+ | (StateBase & { ends?: Rule[]; past?: undefined; excluded?: undefined })
20
+ | PastState;
21
+
22
+ export type Step = { from: string; to: string; action: string };
23
+
24
+ export type Graph = { states: Map<string, State>; steps: Step[] };
25
+
26
+ export type PathStep = { action: string; state: string; step: Step };
27
+
28
+ export type Output = Iterable<Uint8Array>;
29
+
30
+ export type Lasso = {
31
+ start: string;
32
+ path: PathStep[];
33
+ loop: number | undefined;
34
+ stutters: boolean;
35
+ };
36
+
37
+ export type Mark = { values: Value[]; broken: string[] };
38
+
39
+ export type Past = Map<string, Set<Rule>>;
40
+
41
+ export type TraceState = { action: string; vars: Vars };
42
+
43
+ export type Trace = {
44
+ seq: { action: string; vars: Vars | undefined }[];
45
+ loop: number | undefined;
46
+ };
47
+
48
+ export type Find<Id> = (values: Value[]) => Id | undefined;
49
+
50
+ export type Bug = {
51
+ rule: Rule;
52
+ start: string;
53
+ path: PathStep[];
54
+ loop?: number;
55
+ stutters?: boolean;
56
+ };
57
+
58
+ export type ConfigSection = { key: string; line: number; tokens: string[] };
59
+
60
+ export type Config = {
61
+ sections: ConfigSection[];
62
+ invariants: string[];
63
+ properties: string[];
64
+ constraints: string[];
65
+ actionConstraints: string[];
66
+ checkDeadlock?: boolean;
67
+ init?: string;
68
+ next?: string;
69
+ spec?: string;
70
+ view?: string;
71
+ symmetry?: string;
72
+ type?: string;
73
+ typeConstraint?: string;
74
+ };
75
+
76
+ export type Spec = {
77
+ module: string;
78
+ variables: string[];
79
+ invariants: string[];
80
+ properties: string[];
81
+ deadlock: boolean;
82
+ written: ConfigSection[];
83
+ };
84
+
85
+ export type Message = { code: number; level: number; body: Part[]; beforeMarker?: string };
86
+
87
+ export type Line = string;
88
+
89
+ export type Part = Line | Message;
90
+
91
+ export const EC = {
92
+ TLC_INVARIANT_VIOLATED_INITIAL: 2107,
93
+ TLC_PROPERTY_VIOLATED_INITIAL: 2108,
94
+ TLC_INVARIANT_VIOLATED_BEHAVIOR: 2110,
95
+ TLC_ACTION_PROPERTY_VIOLATED_BEHAVIOR: 2112,
96
+ TLC_DEADLOCK_REACHED: 2114,
97
+ TLC_TEMPORAL_PROPERTY_VIOLATED: 2116,
98
+ TLC_BACK_TO_STATE: 2122,
99
+ TLC_FINISHED: 2186,
100
+ TLC_INIT_GENERATED1: 2190,
101
+ TLC_INIT_GENERATED2: 2191,
102
+ TLC_STATS: 2199,
103
+ TLC_PROGRESS_STATS: 2200,
104
+ TLC_STATE_PRINT2: 2217,
105
+ TLC_STATE_PRINT3: 2218,
106
+ TLC_SANY_END: 2219,
107
+ TLC_SANY_START: 2220,
108
+ } as const;
109
+
110
+ export const LEVEL = { NONE: 0, ERROR: 1, TLCBUG: 2, WARNING: 3, STATE: 4 } as const;
111
+
112
+ export type Outcome = "broken" | "holds" | "not checked";
113
+
114
+ export type Verdict = {
115
+ rule: Rule;
116
+ outcome: Outcome;
117
+ messages: Iterable<Part> | undefined;
118
+ };
119
+
120
+ export type Property = Verdict & { bug: Lasso | undefined; initialOnly: boolean };
121
+
122
+ export type Stop = { status: number | null; message: string };
123
+
124
+ export type CheckResult = {
125
+ spec: Spec & { folder: string };
126
+ graph: Graph;
127
+ paths: Bug[] | undefined;
128
+ rules: Verdict[];
129
+ properties: Property[];
130
+ exit: 0 | 1 | 2;
131
+ stop: Stop | undefined;
132
+ drawing: { status: number | null } | undefined;
133
+ states: { distinct: number; initial: number; complete: boolean; cut: boolean };
134
+ messages: Iterable<Part>;
135
+ };
136
+
137
+ export const RERUN_STATES = 100_000;
138
+
139
+ export const CHART_STATES = 500;
140
+
141
+ export type View = {
142
+ state?: (vars: Vars) => unknown;
143
+ step?: (action: string, from: Vars, to: Vars) => unknown;
144
+ group?: (vars: Vars) => unknown;
145
+ colors?: { [group: string]: string };
146
+ title?: string;
147
+ };
148
+
149
+ export const checked = Symbol("checked");
150
+
151
+ export type CheckedView = View & { readonly [checked]: true };
152
+
153
+ export type Shape = { [region: string]: string[] };
154
+
155
+ export type Walk = {
156
+ ids: string[];
157
+ states: State[];
158
+ index: Map<string, number>;
159
+ nameOf: string[];
160
+ nameRank: Int32Array;
161
+ from: Int32Array;
162
+ to: Int32Array;
163
+ action: Int32Array;
164
+ depth: Int32Array;
165
+ via: Int32Array;
166
+ reached: Int32Array;
167
+ starts: number[];
168
+ };
169
+
170
+ export type Hidden = null;
171
+
172
+ export type Answers = {
173
+ names: string[];
174
+ shapes: Shape[];
175
+ labels: (string | Hidden)[];
176
+ group: (i: number) => unknown;
177
+ };
178
+
179
+ export type Labels = Answers & {
180
+ drawnLabels: string[];
181
+ keys: string[][];
182
+ kinds: Int32Array[];
183
+ sizes: number[];
184
+ sorted: Int32Array;
185
+ pathStepIndex: Map<Step, number>;
186
+ pathSteps: Uint8Array;
187
+ together: Set<string>;
188
+ notes: string[];
189
+ };
190
+
191
+ export type Story = { step?: string; state: Shape }[];
192
+
193
+ export type ChartState = {
194
+ path: string[];
195
+ start: boolean;
196
+ members: number[];
197
+ works: boolean;
198
+ lead: boolean;
199
+ repeats: boolean;
200
+ breaks: { rule: Rule; always: boolean }[];
201
+ group: unknown;
202
+ };
203
+
204
+ export type Condition =
205
+ | { kind: "and" | "or"; otherKeys: Set<string>[] }
206
+ | { kind: "tuples"; otherTuples: Set<string> };
207
+
208
+ export type Arrow = {
209
+ from: string;
210
+ to: string;
211
+ label: string;
212
+ condition: Condition;
213
+ when?: string;
214
+ };
215
+
216
+ export type ChartStep = {
217
+ from: string[];
218
+ to: string[];
219
+ label: string;
220
+ when: string | undefined;
221
+ };
222
+
223
+ export type Region = {
224
+ name: string;
225
+ states: ChartState[];
226
+ steps: ChartStep[];
227
+ arrows: Arrow[];
228
+ };
229
+
230
+ export type Chart = {
231
+ title: string | undefined;
232
+ regions: Region[];
233
+ notes: string[];
234
+ inside: number;
235
+ quiet: number;
236
+ colors: { [group: string]: string };
237
+ paths: string[];
238
+ loops: string[];
239
+ lie?: string;
240
+ };
241
+
242
+ export const isRecord = (v: unknown): v is { [key: string]: unknown } =>
243
+ typeof v === "object" && v !== null && !Array.isArray(v);
244
+
245
+ export const isStrings = (v: unknown): v is string[] =>
246
+ Array.isArray(v) && v.every((s) => typeof s === "string");
247
+
248
+ export const PART = 1 << 24;
249
+
250
+ export const byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
251
+
252
+ export const list = (items: string[], and = "and") =>
253
+ items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} ${and} ${items.at(-1)}`;
254
+
255
+ const ESCAPES: { [c: string]: string } = {
256
+ '"': '\\"',
257
+ "\\": "\\\\",
258
+ "\n": "\\n",
259
+ "\t": "\\t",
260
+ "\r": "\\r",
261
+ "\f": "\\f",
262
+ };
263
+ const quote = (s: string) => `"${s.replace(/["\\\n\t\r\f]/g, (c) => ESCAPES[c])}"`;
264
+
265
+ const joined = (items: Value[], sep: string) => {
266
+ let s = "";
267
+ for (let i = 0; i < items.length; i++) s += (i ? sep : "") + show(items[i]);
268
+ return s;
269
+ };
270
+
271
+ export const show = (v: Value): string => {
272
+ switch (typeof v) {
273
+ case "boolean":
274
+ return v ? "TRUE" : "FALSE";
275
+ case "number":
276
+ return String(v);
277
+ case "string":
278
+ return quote(v);
279
+ }
280
+ switch (v.kind) {
281
+ case "model":
282
+ return v.name;
283
+ case "interval":
284
+ return `${v.lo}..${v.hi}`;
285
+ case "set":
286
+ return `{${joined(v.members, ", ")}}`;
287
+ case "function": {
288
+ if (v.printedAs === "tuple") return `<<${joined(v.values, ", ")}>>`;
289
+ const record = v.printedAs === "record";
290
+ let s = record ? "[" : "(";
291
+ for (let i = 0; i < v.keys.length; i++)
292
+ s += record
293
+ ? `${i ? ", " : ""}${String(v.keys[i])} |-> ${show(v.values[i])}`
294
+ : `${i ? " @@ " : ""}${show(v.keys[i])} :> ${show(v.values[i])}`;
295
+ return s + (record ? "]" : ")");
296
+ }
297
+ }
298
+ };
299
+
300
+ export const must = <K, V>(map: ReadonlyMap<K, V>, key: K): V => {
301
+ const value = map.get(key);
302
+ if (value === undefined) throw new Error(`The chart lost track of ${JSON.stringify(key)}.`);
303
+ return value;
304
+ };
305
+
306
+ export const append = <K, V>(groups: Map<K, V[]>, key: K, item: V) => {
307
+ const group = groups.get(key);
308
+ if (group) group.push(item);
309
+ else groups.set(key, [item]);
310
+ };
311
+
312
+ export const seqOf = (bug: Bug, index: ReadonlyMap<string, number>) => {
313
+ const seq = [must(index, bug.start)];
314
+ for (const p of bug.path) seq.push(must(index, p.state));
315
+ return seq;
316
+ };
317
+
318
+ export const loopOf = (bug: Bug, index: ReadonlyMap<string, number>) =>
319
+ new Set(bug.loop === undefined ? [] : seqOf(bug, index).slice(bug.loop));
320
+
321
+ export const defaultState = (vars: Vars) => {
322
+ const entries = Object.entries(vars);
323
+ if (entries.length === 1) return show(entries[0][1]);
324
+ const parts: string[] = [];
325
+ for (const [k, v] of entries) parts.push(`${k}=${show(v)}`);
326
+ return parts.join(" ");
327
+ };
328
+
329
+ export const stateText = (vars: Vars) => {
330
+ const parts: string[] = [];
331
+ for (const [k, v] of Object.entries(vars)) parts.push(`${k} = ${show(v)}`);
332
+ return parts.join(" /\\ ");
333
+ };
334
+
335
+ export const count = (n: number) => {
336
+ const items = new Int32Array(n);
337
+ for (let i = 0; i < n; i++) items[i] = i;
338
+ return items;
339
+ };
340
+
341
+ export const sortBy = (items: Int32Array, keys: Int32Array[]) => {
342
+ for (let k = keys.length - 1; k >= 0; k--) {
343
+ const key = keys[k];
344
+ let size = 0;
345
+ for (let p = 0; p < items.length; p++) if (key[items[p]] >= size) size = key[items[p]] + 1;
346
+ const start = new Int32Array(size + 1);
347
+ for (let p = 0; p < items.length; p++) start[key[items[p]] + 1]++;
348
+ for (let v = 0; v < size; v++) start[v + 1] += start[v];
349
+ const sorted = new Int32Array(items.length);
350
+ for (let p = 0; p < items.length; p++) sorted[start[key[items[p]]]++] = items[p];
351
+ items = sorted;
352
+ }
353
+ return items;
354
+ };
355
+
356
+ export const tupleKey = (parts: unknown[]) => JSON.stringify(parts);
357
+ export const unkey = (k: string) => {
358
+ const parts: unknown = JSON.parse(k);
359
+ if (!isStrings(parts)) throw new Error(`The chart cannot read the key ${k}.`);
360
+ return parts;
361
+ };
362
+
363
+ export function holds(condition: Condition, others: string[]) {
364
+ switch (condition.kind) {
365
+ case "and":
366
+ for (let j = 0; j < others.length; j++)
367
+ if (!condition.otherKeys[j].has(others[j])) return false;
368
+ return true;
369
+ case "or":
370
+ for (let j = 0; j < others.length; j++)
371
+ if (condition.otherKeys[j].has(others[j])) return true;
372
+ return false;
373
+ case "tuples":
374
+ return condition.otherTuples.has(tupleKey(others));
375
+ }
376
+ }
377
+
378
+ export const ruleKey = (rule: Rule) => tupleKey([rule.kind, rule.name]);
379
+
380
+ export const hasRule = (rules: Rule[], rule: Rule) => {
381
+ for (const r of rules) if (r.kind === rule.kind && r.name === rule.name) return true;
382
+ return false;
383
+ };
384
+
385
+ const ascending = (keys: string[]) => {
386
+ for (let i = 1; i < keys.length; i++) if (keys[i - 1] > keys[i]) return false;
387
+ return true;
388
+ };
389
+
390
+ const span = (lo: number, hi: number) => (hi > lo ? `${lo}..${hi}` : String(lo));
391
+
392
+ const setKey = (members: Value[]) => {
393
+ const ints: number[] = [];
394
+ let others: string[] = [];
395
+ for (const m of members)
396
+ if (typeof m === "number") ints.push(m);
397
+ else others.push(key(m));
398
+ for (let i = 1; i < ints.length; i++)
399
+ if (ints[i - 1] >= ints[i]) {
400
+ ints.sort((a, b) => a - b);
401
+ break;
402
+ }
403
+ if (!ascending(others)) others = others.sort(byText);
404
+ let s = "{";
405
+ for (let i = 0; i < ints.length;) {
406
+ let j = i;
407
+ while (j + 1 < ints.length && ints[j + 1] - ints[j] <= 1) j++;
408
+ s += `${s.length > 1 ? "," : ""}${span(ints[i], ints[j])}`;
409
+ i = j + 1;
410
+ }
411
+ for (let i = 0; i < others.length; i++)
412
+ if (!i || others[i] !== others[i - 1]) s += (s.length > 1 ? "," : "") + others[i];
413
+ return s + "}";
414
+ };
415
+
416
+ const functionKey = ({ keys, values }: { keys: Value[]; values: Value[] }) => {
417
+ const order: number[] = [];
418
+ const keyTexts: string[] = [];
419
+ let ints = 0;
420
+ for (let i = 0; i < keys.length; i++) {
421
+ order.push(i);
422
+ keyTexts.push(key(keys[i]));
423
+ if (typeof keys[i] === "number") ints++;
424
+ }
425
+ const rank = (i: number) => (typeof keys[i] === "number" ? (keys[i] as number) : Infinity);
426
+ order.sort((a, b) => rank(a) - rank(b) || byText(keyTexts[a], keyTexts[b]) || a - b);
427
+ let tuple = ints === keys.length;
428
+ for (let i = 0; tuple && i < order.length; i++) tuple = keys[order[i]] === i + 1;
429
+ let s = tuple ? "<<" : "(";
430
+ for (let i = 0, kept = 0; i < order.length; i++) {
431
+ const k = order[i];
432
+ if (i && keyTexts[k] === keyTexts[order[i - 1]]) continue;
433
+ const v = key(values[k]);
434
+ s += tuple ? `${kept++ ? "," : ""}${v}` : `${kept++ ? "@@" : ""}${keyTexts[k]}:>${v}`;
435
+ }
436
+ return s + (tuple ? ">>" : ")");
437
+ };
438
+
439
+ const keys = new WeakMap<object, string>();
440
+
441
+ export const key = (v: Value): string => {
442
+ switch (typeof v) {
443
+ case "boolean":
444
+ return v ? "TRUE" : "FALSE";
445
+ case "number":
446
+ return String(v);
447
+ case "string":
448
+ return JSON.stringify(v);
449
+ }
450
+ if (v.kind === "model") return v.name;
451
+ let k = keys.get(v);
452
+ if (k === undefined) {
453
+ k =
454
+ v.kind === "interval"
455
+ ? `{${v.lo > v.hi ? "" : span(v.lo, v.hi)}}`
456
+ : v.kind === "set"
457
+ ? setKey(v.members)
458
+ : functionKey(v);
459
+ keys.set(v, k);
460
+ }
461
+ return k;
462
+ };
463
+
464
+ export const stateKey = (values: Value[]) => {
465
+ let k = "";
466
+ for (let i = 0; i < values.length; i++) k += (i ? "," : "") + key(values[i]);
467
+ return k;
468
+ };
469
+
470
+ export const memo = <K, V>(make: (k: K) => V, limit = 1 << 16) => {
471
+ const cache = new Map<K, V>();
472
+ return (k: K) => {
473
+ let v = cache.get(k);
474
+ if (v === undefined) {
475
+ if (cache.size >= limit) cache.clear();
476
+ cache.set(k, (v = make(k)));
477
+ }
478
+ return v;
479
+ };
480
+ };
481
+
482
+ export const valuesOf = (vars: Vars, names: string[]) => {
483
+ const values: Value[] = [];
484
+ for (const n of names) values.push(vars[n]);
485
+ return values;
486
+ };
487
+
488
+ export const findTrace = <Id>(
489
+ counterexample: TraceState[],
490
+ names: string[],
491
+ rule: Rule,
492
+ find: Find<Id>,
493
+ ) => {
494
+ const trace: (TraceState & { values: Value[]; id: Id | undefined })[] = [];
495
+ for (const { action, vars } of counterexample) {
496
+ const values = valuesOf(vars, names);
497
+ trace.push({ action, vars, values, id: find(values) });
498
+ }
499
+ const end = trace.length - 1;
500
+ if (end < 0) throw new Error(`TLC's trace for ${rule.name} has no states.`);
501
+ for (let i = 0; i < end; i++)
502
+ if (trace[i].id === undefined)
503
+ throw new Error(
504
+ `TLC's trace for ${rule.name} has a state before its last that the dump does not list.`,
505
+ );
506
+ return trace;
507
+ };
508
+
509
+ export const findLoop = <Id>({ seq, loop }: Trace, names: string[], find: Find<Id>) => {
510
+ const found: { action: string; id: Id | undefined }[] = [];
511
+ for (const { action, vars } of seq)
512
+ found.push({ action, id: vars && find(valuesOf(vars, names)) });
513
+ return { seq: found, loop };
514
+ };
515
+
516
+ export const pastState = (
517
+ vars: Vars,
518
+ start: boolean,
519
+ marked: Iterable<Rule>,
520
+ excluded: boolean,
521
+ ): PastState => {
522
+ const breaks: Rule[] = [];
523
+ for (const r of marked) if (!hasRule(breaks, r)) breaks.push(r);
524
+ return { vars, start, breaks, ends: [], past: true, excluded };
525
+ };
526
+
527
+ export const CHECK_DEADLOCK = "CHECK_DEADLOCK";
528
+
529
+ const deadlockRule = ({ invariants, properties }: Spec): Rule => ({
530
+ kind: "deadlock",
531
+ name:
532
+ invariants.includes("NoDeadlock") || properties.includes("NoDeadlock")
533
+ ? CHECK_DEADLOCK
534
+ : "NoDeadlock",
535
+ });
536
+
537
+ export const hasSection = ({ written }: Spec, ...keys: string[]) => {
538
+ for (const s of written) if (keys.includes(s.key)) return true;
539
+ return false;
540
+ };
541
+
542
+ export const stateRules = (spec: Spec) => {
543
+ const rules: Rule[] = [];
544
+ for (const name of spec.invariants) rules.push({ kind: "invariant", name });
545
+ if (spec.deadlock) rules.push(deadlockRule(spec));
546
+ return rules;
547
+ };
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "@cursor-skill/statechart",
3
+ "private": true,
4
+ "type": "module",
5
+ "scripts": {
6
+ "test": "node --disable-warning=ExperimentalWarning --test test/*.test.ts"
7
+ },
8
+ "devDependencies": {
9
+ "fast-check": "4.5.3"
10
+ }
11
+ }
@@ -0,0 +1,128 @@
1
+ import {
2
+ findLoop,
3
+ findTrace,
4
+ type Graph,
5
+ hasRule,
6
+ type Lasso,
7
+ type Mark,
8
+ must,
9
+ type Past,
10
+ pastState,
11
+ type PathStep,
12
+ type Rule,
13
+ stateKey,
14
+ type Step,
15
+ type Trace,
16
+ type TraceState,
17
+ type Value,
18
+ valuesOf,
19
+ } from "../ir.ts";
20
+
21
+ export const finder = (graph: Graph, names: string[]) => {
22
+ let ids: Map<string, string> | undefined;
23
+ const find = (values: Value[]) => {
24
+ if (!ids) {
25
+ ids = new Map();
26
+ for (const [id, s] of graph.states)
27
+ if (!s.excluded) ids.set(stateKey(valuesOf(s.vars, names)), id);
28
+ }
29
+ return ids.get(stateKey(values));
30
+ };
31
+ find.add = (id: string, values: Value[]) => ids?.set(stateKey(values), id);
32
+ return find;
33
+ };
34
+
35
+ export function mark(
36
+ graph: Graph,
37
+ marks: Iterable<Mark>,
38
+ names: string[],
39
+ rules: Rule[],
40
+ find = finder(graph, names),
41
+ ) {
42
+ const byName = new Map<string, Rule>();
43
+ for (const rule of rules) byName.set(rule.name, rule);
44
+ const past: Past = new Map();
45
+ for (const { values, broken } of marks) {
46
+ const id = find(values);
47
+ const state = id === undefined ? undefined : graph.states.get(id);
48
+ for (const name of broken) {
49
+ const rule = must(byName, name);
50
+ if (state) state.breaks.push(rule);
51
+ else past.set(stateKey(values), (past.get(stateKey(values)) ?? new Set()).add(rule));
52
+ }
53
+ }
54
+ return past;
55
+ }
56
+
57
+ export function deadEnds(graph: Graph, rule: Rule) {
58
+ const from = new Set<string>();
59
+ for (const t of graph.steps) from.add(t.from);
60
+ for (const [id, s] of graph.states) if (!s.past && !from.has(id)) s.breaks.push(rule);
61
+ }
62
+
63
+ export function addPast(
64
+ graph: Graph,
65
+ counterexample: TraceState[],
66
+ names: string[],
67
+ rule: Rule,
68
+ past: Past,
69
+ excludes: boolean,
70
+ find = finder(graph, names),
71
+ ) {
72
+ const trace = findTrace(counterexample, names, rule, find);
73
+ const end = trace.length - 1;
74
+ const from = trace[end - 1]?.id;
75
+ const action = trace[end].action;
76
+ const taken = (to: string | undefined) => {
77
+ for (const t of graph.steps)
78
+ if (t.from === from && t.to === to && t.action === action) return true;
79
+ return false;
80
+ };
81
+ let to = trace[end].id;
82
+ const reached = to === undefined ? undefined : graph.states.get(to);
83
+ const excluded = excludes && reached !== undefined && end > 0 && !reached.past && !taken(to);
84
+ if (excluded) to = `past ${to} ${action} ${from}`;
85
+ to ??= `past ${graph.states.size}`;
86
+ let last = graph.states.get(to);
87
+ if (!last) {
88
+ const marked = excluded ? reached.breaks : (past.get(stateKey(trace[end].values)) ?? []);
89
+ last = pastState(trace[end].vars, end === 0, marked, excluded);
90
+ graph.states.set(to, last);
91
+ if (!excluded) find.add(to, trace[end].values);
92
+ }
93
+ if (!hasRule(last.breaks, rule)) last.breaks.push(rule);
94
+ (last.ends ??= []).push(rule);
95
+ if (from !== undefined && last.past && !taken(to)) graph.steps.push({ from, to, action });
96
+ }
97
+
98
+ export function lasso(
99
+ graph: Graph,
100
+ trace: Trace,
101
+ names: string[],
102
+ find = finder(graph, names),
103
+ ): Lasso | undefined {
104
+ const { seq, loop } = findLoop(trace, names, find);
105
+ const start = seq[0]?.id;
106
+ if (start === undefined) return undefined;
107
+ const out = new Map<string | undefined, Step[]>();
108
+ for (const s of seq) out.set(s.id, []);
109
+ for (const t of graph.steps) out.get(t.from)?.push(t);
110
+ const route: PathStep[] = [];
111
+ for (let i = 1; i < seq.length; i++) {
112
+ let step: Step | undefined;
113
+ for (const t of out.get(seq[i - 1].id) ?? [])
114
+ if (t.to === seq[i].id && t.action === seq[i].action) {
115
+ step = t;
116
+ break;
117
+ }
118
+ if (!step) return undefined;
119
+ route.push({ action: step.action, state: step.to, step });
120
+ }
121
+ const stutters = loop === seq.length - 1;
122
+ return {
123
+ start,
124
+ path: route,
125
+ loop,
126
+ stutters,
127
+ };
128
+ }