@tsplc/tmp-debug 0.0.0-stage → 0.6.2

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 (78) hide show
  1. package/README.md +38 -2
  2. package/dist/api.js +744 -0
  3. package/dist/api.js.map +12 -0
  4. package/dist/constant.js +33 -0
  5. package/dist/constant.js.map +10 -0
  6. package/dist/explain-file.js +468 -0
  7. package/dist/explain-file.js.map +11 -0
  8. package/dist/explain.js +1310 -0
  9. package/dist/explain.js.map +19 -0
  10. package/dist/format.js +214 -0
  11. package/dist/format.js.map +12 -0
  12. package/dist/index.js +4066 -0
  13. package/dist/index.js.map +44 -0
  14. package/dist/manifest.js +240 -0
  15. package/dist/manifest.js.map +10 -0
  16. package/dist/paths.js +242 -0
  17. package/dist/paths.js.map +10 -0
  18. package/package.json +72 -4
  19. package/src/adapter.ts +77 -0
  20. package/src/api.ts +446 -0
  21. package/src/app-server.ts +151 -0
  22. package/src/build-files.ts +46 -0
  23. package/src/constant.ts +41 -0
  24. package/src/debugger.ts +237 -0
  25. package/src/errors.ts +13 -0
  26. package/src/explain-expressions.ts +484 -0
  27. package/src/explain-file.ts +325 -0
  28. package/src/explain-frames.ts +155 -0
  29. package/src/explain-loops.ts +151 -0
  30. package/src/explain-operations.ts +232 -0
  31. package/src/explain-tables.ts +345 -0
  32. package/src/explain-value.ts +203 -0
  33. package/src/explain-verdicts.ts +548 -0
  34. package/src/explain.ts +82 -0
  35. package/src/hardware.ts +159 -0
  36. package/src/http.ts +218 -0
  37. package/src/index.ts +44 -0
  38. package/src/jobs.ts +139 -0
  39. package/src/login-value.ts +165 -0
  40. package/src/login.ts +315 -0
  41. package/src/manifest.ts +328 -0
  42. package/src/opcua.ts +80 -0
  43. package/src/paths.ts +363 -0
  44. package/src/requests.ts +99 -0
  45. package/src/server-cursor.ts +22 -0
  46. package/src/shown.ts +229 -0
  47. package/src/telemetry.ts +125 -0
  48. package/src/timeline.ts +148 -0
  49. package/src/trace.ts +62 -0
  50. package/src/ui/bits.ts +48 -0
  51. package/src/ui/client.ts +87 -0
  52. package/src/ui/dom.ts +61 -0
  53. package/src/ui/explain-read.ts +105 -0
  54. package/src/ui/format.ts +261 -0
  55. package/src/ui/hardware.ts +425 -0
  56. package/src/ui/header.ts +207 -0
  57. package/src/ui/health.ts +64 -0
  58. package/src/ui/index.ts +27 -0
  59. package/src/ui/jobs.ts +263 -0
  60. package/src/ui/links.ts +59 -0
  61. package/src/ui/live-value.ts +85 -0
  62. package/src/ui/main.ts +76 -0
  63. package/src/ui/overview.ts +178 -0
  64. package/src/ui/page.ts +286 -0
  65. package/src/ui/pages.ts +64 -0
  66. package/src/ui/recent-window.ts +49 -0
  67. package/src/ui/recent.ts +355 -0
  68. package/src/ui/request-trace.ts +38 -0
  69. package/src/ui/requests.ts +80 -0
  70. package/src/ui/routes.ts +98 -0
  71. package/src/ui/store.ts +295 -0
  72. package/src/ui/success-cache.ts +11 -0
  73. package/src/ui/tree.ts +162 -0
  74. package/src/ui/variables.ts +597 -0
  75. package/src/ui/why-watch.ts +11 -0
  76. package/src/ui/why.ts +694 -0
  77. package/src/values.ts +170 -0
  78. package/src/watch.ts +32 -0
@@ -0,0 +1,1310 @@
1
+ // packages/debug/src/explain-value.ts
2
+ import {
3
+ elementaryType,
4
+ isIntegerValued,
5
+ nanosecondsPerMillisecond as nanosecondsPerMillisecond2
6
+ } from "@tsplc/iec";
7
+
8
+ // packages/debug/src/constant.ts
9
+ import { nanosecondsPerMillisecond } from "@tsplc/iec";
10
+ var decodeConstant = (value) => {
11
+ if (typeof value === "number" && Number.isInteger(value)) {
12
+ return { kind: "integer", value: BigInt(value) };
13
+ }
14
+ if (typeof value !== "string") {
15
+ return;
16
+ }
17
+ if (/^-?\d+$/.test(value)) {
18
+ return { kind: "integer", value: BigInt(value) };
19
+ }
20
+ const milliseconds = /^(-?\d+)ms$/.exec(value)?.[1];
21
+ return milliseconds === undefined ? undefined : {
22
+ kind: "duration",
23
+ nanoseconds: BigInt(milliseconds) * nanosecondsPerMillisecond
24
+ };
25
+ };
26
+
27
+ // packages/debug/src/paths.ts
28
+ import { isWithin } from "@tsplc/iec/st";
29
+ import {
30
+ arrayIndex,
31
+ joinPath,
32
+ symbolPathSegments
33
+ } from "@tsplc/opcua/contract";
34
+ var anyIndex = "[*]";
35
+ var pathSegments = (path) => path.split(anyIndex).flatMap((part, index) => [
36
+ ...index > 0 ? [anyIndex] : [],
37
+ ...symbolPathSegments(part)
38
+ ]);
39
+ var typeOf = (manifest, id) => manifest.types[id] ?? { kind: "scalar", iec: id };
40
+
41
+ // packages/debug/src/explain-value.ts
42
+ var unknown = (reason, estimate = []) => ({
43
+ known: false,
44
+ reason,
45
+ estimate
46
+ });
47
+ var known = (value, estimate = []) => ({
48
+ known: true,
49
+ value,
50
+ estimate
51
+ });
52
+ var withEstimate = (outcome, estimate) => estimate.length ? { ...outcome, estimate: [...new Set([...outcome.estimate, ...estimate])] } : outcome;
53
+ var merge = (...lists) => [
54
+ ...new Set(lists.flat())
55
+ ];
56
+ var and = (truths) => {
57
+ if (truths.includes("false")) {
58
+ return "false";
59
+ }
60
+ if (truths.includes("unknown")) {
61
+ return "unknown";
62
+ }
63
+ return truths.includes("candidate") ? "candidate" : "true";
64
+ };
65
+ var fromConstant = (scalar) => ({
66
+ kind: "integer",
67
+ value: scalar.kind === "integer" ? scalar.value : scalar.nanoseconds
68
+ });
69
+ var sampleValue = (manifest, type, decoded) => {
70
+ const declared = typeOf(manifest, type);
71
+ if (declared.kind === "enum") {
72
+ const member = typeof decoded === "string" ? declared.members[decoded] : undefined;
73
+ if (typeof member === "number") {
74
+ return { kind: "integer", value: BigInt(member) };
75
+ }
76
+ return typeof decoded === "number" || typeof decoded === "bigint" ? { kind: "integer", value: BigInt(decoded) } : undefined;
77
+ }
78
+ const scalar = declared.kind === "scalar" ? elementaryType(declared.iec) : undefined;
79
+ const constant = decodeConstant(decoded);
80
+ if (isIntegerValued(scalar)) {
81
+ if (typeof decoded === "bigint") {
82
+ return { kind: "integer", value: decoded };
83
+ }
84
+ return constant?.kind === "integer" ? fromConstant(constant) : undefined;
85
+ }
86
+ switch (scalar?.family) {
87
+ case "bool":
88
+ if (typeof decoded === "boolean") {
89
+ return { kind: "bool", value: decoded };
90
+ }
91
+ return typeof decoded === "number" ? { kind: "bool", value: decoded !== 0 } : undefined;
92
+ case "real":
93
+ return typeof decoded === "number" ? { kind: "float", value: decoded } : undefined;
94
+ case "duration":
95
+ if (typeof decoded === "number") {
96
+ return {
97
+ kind: "integer",
98
+ value: BigInt(Math.round(decoded * Number(nanosecondsPerMillisecond2)))
99
+ };
100
+ }
101
+ return typeof decoded === "string" && constant?.kind === "duration" ? fromConstant(constant) : undefined;
102
+ case "string":
103
+ return typeof decoded === "string" ? { kind: "text", value: decoded } : undefined;
104
+ default:
105
+ return;
106
+ }
107
+ };
108
+ var constantAggregate = (value) => {
109
+ if (Array.isArray(value)) {
110
+ return known({
111
+ kind: "array",
112
+ lower: 0,
113
+ items: value.map((item) => constantAggregate(item))
114
+ });
115
+ }
116
+ if (typeof value === "object" && value !== null) {
117
+ return known({
118
+ kind: "record",
119
+ fields: Object.fromEntries(Object.entries(value).map(([name, item]) => [
120
+ name,
121
+ constantAggregate(item)
122
+ ]))
123
+ });
124
+ }
125
+ if (typeof value === "boolean") {
126
+ return known({ kind: "bool", value });
127
+ }
128
+ if (typeof value !== "number" && typeof value !== "string") {
129
+ return unknown("a constant this debugger can't show");
130
+ }
131
+ const constant = decodeConstant(value);
132
+ if (constant) {
133
+ return known(fromConstant(constant));
134
+ }
135
+ return known(typeof value === "number" ? { kind: "float", value } : { kind: "text", value });
136
+ };
137
+ var equalValues = (left, right) => {
138
+ if (left.kind === "float" || right.kind === "float") {
139
+ const leftNumber = left.kind === "float" || left.kind === "integer" ? Number(left.value) : Number.NaN;
140
+ const rightNumber = right.kind === "float" || right.kind === "integer" ? Number(right.value) : Number.NaN;
141
+ return Math.abs(leftNumber - rightNumber) <= Math.max(Math.abs(leftNumber), Math.abs(rightNumber)) * 0.000001 + 0.000000001;
142
+ }
143
+ if (left.kind === "bool" && right.kind === "bool") {
144
+ return left.value === right.value;
145
+ }
146
+ if (left.kind === "integer" && right.kind === "integer") {
147
+ return left.value === right.value;
148
+ }
149
+ if (left.kind === "text" && right.kind === "text") {
150
+ return left.value === right.value;
151
+ }
152
+ if (left.kind === "instance" && right.kind === "instance") {
153
+ return left.path === right.path;
154
+ }
155
+ return;
156
+ };
157
+
158
+ // packages/debug/src/explain-frames.ts
159
+ var compareOrder = (left, right) => {
160
+ for (let index = 0;index < Math.min(left.length, right.length); index++) {
161
+ const difference = (left[index] ?? 0) - (right[index] ?? 0);
162
+ if (difference !== 0) {
163
+ return difference;
164
+ }
165
+ }
166
+ return left.length - right.length;
167
+ };
168
+ var frameKey = (frame) => `${frame.row}:${frame.caller ? `${frame.caller.call}@${frameKey(frame.caller.frame)}` : ""}:${[...frame.counters].join(",")}`;
169
+ var callFrame = (row, call, position, frame) => ({
170
+ row,
171
+ caller: { call, frame },
172
+ task: frame.task,
173
+ order: [...frame.order, position],
174
+ counters: new Map
175
+ });
176
+ var rootFrame = ({ file, tables }, chain) => {
177
+ const start = {
178
+ row: chain.entry,
179
+ caller: null,
180
+ task: chain.task,
181
+ order: [tables.entries.get(chain.entry)?.order ?? 0],
182
+ counters: new Map
183
+ };
184
+ return chain.calls.reduce((frame, call) => {
185
+ const record = file.calls[call];
186
+ const callee = record ? tables.calleesOf(record)[0]?.row : undefined;
187
+ return callFrame(callee ?? frame.row, call, record?.position ?? 0, frame);
188
+ }, start);
189
+ };
190
+ var calleeFrame = (evaluation, call, frame) => {
191
+ const record = evaluation.file.calls[call];
192
+ if (!record) {
193
+ return unknown("a call that isn't traced");
194
+ }
195
+ const callees = evaluation.tables.calleesOf(record);
196
+ if (record.receiver.kind === "pattern") {
197
+ const indexes = record.receiver.indexes.map((item) => evaluation.expression(item, frame));
198
+ const values = indexes.flatMap((item) => item.known && item.value.kind === "integer" ? [item.value.value] : []);
199
+ if (values.length !== indexes.length) {
200
+ return unknown("depends on which instance the call runs on", merge(...indexes.map((item) => item.estimate)));
201
+ }
202
+ const match = callees.find((callee) => callee.indexes.every((value, position) => value === values[position]));
203
+ return match ? callFrame(match.row, call, record.position, frame) : unknown("an instance this build doesn't have");
204
+ }
205
+ const [only] = callees;
206
+ return only && callees.length === 1 ? callFrame(only.row, call, record.position, frame) : unknown("a call this debugger can't follow");
207
+ };
208
+
209
+ // packages/debug/src/explain-loops.ts
210
+ import { loopIterations } from "@tsplc/iec/arithmetic";
211
+ var maxLoopIterations = 64;
212
+ var firstOf = (evaluation, loop, frame) => {
213
+ const record = evaluation.file.loops[loop];
214
+ return record ? evaluation.expression(record.first, frame) : unknown("a loop this debugger can't follow");
215
+ };
216
+ var executeLoop = (evaluation, loop, frame, watch) => {
217
+ const { file, tables } = evaluation;
218
+ const record = file.loops[loop];
219
+ if (!record) {
220
+ return {
221
+ kind: "unknown",
222
+ reason: "a loop this debugger can't follow",
223
+ estimate: []
224
+ };
225
+ }
226
+ if (record.parent !== null && !frame.counters.has(record.parent)) {
227
+ return {
228
+ kind: "unknown",
229
+ reason: "a loop inside another loop",
230
+ estimate: []
231
+ };
232
+ }
233
+ const bounds = [record.first, record.limit, record.step].map((index) => evaluation.expression(index, frame));
234
+ const estimate = merge(...bounds.map((item) => item.estimate));
235
+ const missing = bounds.find((item) => !item.known);
236
+ if (missing) {
237
+ return { kind: "unknown", reason: missing.reason, estimate };
238
+ }
239
+ const [first, limit, step] = bounds.map((item) => item.known && item.value.kind === "integer" ? item.value.value : undefined);
240
+ if (first === undefined || limit === undefined || step === undefined || step === 0n) {
241
+ return {
242
+ kind: "unknown",
243
+ reason: "a loop this debugger can't follow",
244
+ estimate
245
+ };
246
+ }
247
+ const iterations = loopIterations(first, limit, record.exclusive, step);
248
+ if (iterations > BigInt(Math.min(record.maxIterations, maxLoopIterations))) {
249
+ return { kind: "unknown", reason: "loop too long", estimate };
250
+ }
251
+ const returns = file.returns.filter((item) => item.routine === frame.row && tables.conditionList(item.conditions).some((part) => part.kind === "loop" && tables.loopAt(frame.row, part.loop) === loop));
252
+ let ran = null;
253
+ const seen = [...estimate];
254
+ for (let iteration = 0n;iteration < iterations; iteration++) {
255
+ const inner = {
256
+ ...frame,
257
+ counters: new Map([...frame.counters, [loop, first + iteration * step]])
258
+ };
259
+ if (watch !== null) {
260
+ const truth = watch(inner);
261
+ seen.push(...truth.estimate);
262
+ if (truth.truth === "true") {
263
+ ran = inner;
264
+ } else if (truth.truth !== "false") {
265
+ return {
266
+ kind: "unknown",
267
+ reason: "depends on a condition inside the loop",
268
+ estimate: merge(seen)
269
+ };
270
+ }
271
+ }
272
+ const breaks = record.breaks.map((all) => and(all.map((part) => evaluation.conditionTruth(part, inner).truth)));
273
+ const returned = returns.map((item) => evaluation.conditionsTruth(item.conditions, inner).truth);
274
+ const stops = [...breaks, ...returned];
275
+ if (stops.includes("true")) {
276
+ return {
277
+ kind: "run",
278
+ ran,
279
+ returned: returned.includes("true"),
280
+ estimate: merge(seen)
281
+ };
282
+ }
283
+ if (stops.includes("unknown") || stops.includes("candidate")) {
284
+ return {
285
+ kind: "unknown",
286
+ reason: "can't tell whether the loop stopped",
287
+ estimate: merge(seen)
288
+ };
289
+ }
290
+ }
291
+ return { kind: "run", ran, returned: false, estimate: merge(seen) };
292
+ };
293
+
294
+ // packages/debug/src/explain-operations.ts
295
+ import { elementaryType as elementaryType2, isIntegerValued as isIntegerValued2 } from "@tsplc/iec";
296
+ import {
297
+ applyIntegerPolicy,
298
+ compare,
299
+ floatArithmetic,
300
+ floatUnary,
301
+ integerArithmetic,
302
+ integerUnary,
303
+ isElementary,
304
+ roundFloat,
305
+ saturateFloatToInteger
306
+ } from "@tsplc/iec/arithmetic";
307
+ var integerLayout = (type) => {
308
+ const scalar = elementaryType2(type);
309
+ return isIntegerValued2(scalar) ? { bits: scalar.bits, signed: scalar.signed } : undefined;
310
+ };
311
+ var floatLayout = (type) => {
312
+ const scalar = elementaryType2(type);
313
+ return scalar?.family === "real" ? { bits: scalar.bits } : undefined;
314
+ };
315
+ var typed = (value, type, policy = "wrap") => {
316
+ const layout = integerLayout(type);
317
+ return {
318
+ kind: "integer",
319
+ value: layout ? applyIntegerPolicy(value, layout, policy) : value
320
+ };
321
+ };
322
+ var binary = (node, left, right) => {
323
+ if (left.kind === "interval" || right.kind === "interval") {
324
+ return intervalBinary(node, left, right);
325
+ }
326
+ if (left.kind === "instance" || right.kind === "instance") {
327
+ const id = (value) => value.kind === "instance" ? { kind: "integer", value: value.id } : value;
328
+ return binary(node, id(left), id(right));
329
+ }
330
+ if (left.kind === "bool" && right.kind === "bool") {
331
+ const compared = compare(node.operator, Number(left.value), Number(right.value));
332
+ return compared === undefined ? unknown("an operation this debugger can't evaluate") : known({ kind: "bool", value: compared });
333
+ }
334
+ if (left.kind === "integer" && right.kind === "integer") {
335
+ const compared = compare(node.operator, left.value, right.value);
336
+ if (compared !== undefined) {
337
+ return known({ kind: "bool", value: compared });
338
+ }
339
+ const result = integerArithmetic(node.operator, left.value, right.value);
340
+ if (result === undefined) {
341
+ return unknown(right.value === 0n ? "a division by zero" : "an operation this debugger can't evaluate");
342
+ }
343
+ return known(typed(result, node.type, node.policy));
344
+ }
345
+ const leftNumber = left.kind === "float" || left.kind === "integer" ? Number(left.value) : undefined;
346
+ const rightNumber = right.kind === "float" || right.kind === "integer" ? Number(right.value) : undefined;
347
+ if (leftNumber === undefined || rightNumber === undefined) {
348
+ if (left.kind === "text" && right.kind === "text") {
349
+ const compared = compare(node.operator, left.value, right.value);
350
+ return compared === undefined ? unknown("an operation on text") : known({ kind: "bool", value: compared });
351
+ }
352
+ return unknown("an operation this debugger can't evaluate");
353
+ }
354
+ const compared = compare(node.operator, leftNumber, rightNumber);
355
+ if (compared !== undefined) {
356
+ return known({ kind: "bool", value: compared }, [
357
+ "a comparison of REAL values"
358
+ ]);
359
+ }
360
+ const result = floatArithmetic(node.operator, leftNumber, rightNumber);
361
+ const layout = floatLayout(node.type);
362
+ return result === undefined ? unknown("an operation this debugger can't evaluate") : known({
363
+ kind: "float",
364
+ value: layout ? roundFloat(result, layout) : result
365
+ });
366
+ };
367
+ var intervalBinary = (node, left, right) => {
368
+ const ends = (value) => {
369
+ if (value.kind === "interval") {
370
+ return [value.low, value.high];
371
+ }
372
+ return value.kind === "integer" ? [value.value, value.value] : undefined;
373
+ };
374
+ const leftEnds = ends(left);
375
+ const rightEnds = ends(right);
376
+ if (!leftEnds || !rightEnds) {
377
+ return unknown("an operation on the clock");
378
+ }
379
+ const low = binary(node, { kind: "integer", value: leftEnds[0] }, { kind: "integer", value: rightEnds[0] });
380
+ const high = binary(node, { kind: "integer", value: leftEnds[1] }, { kind: "integer", value: rightEnds[1] });
381
+ if (!low.known || !high.known) {
382
+ return unknown("an operation on the clock");
383
+ }
384
+ if (low.value.kind === "bool" && high.value.kind === "bool") {
385
+ return low.value.value === high.value.value ? known(low.value) : unknown("within one scan of the limit");
386
+ }
387
+ if (low.value.kind === "integer" && high.value.kind === "integer") {
388
+ const monotonic = node.operator === "add" || node.operator === "subtract";
389
+ const [from, to] = node.operator === "subtract" && right.kind === "interval" ? [high.value.value, low.value.value] : [low.value.value, high.value.value];
390
+ return monotonic && from <= to ? known({ kind: "interval", low: from, high: to }) : unknown("within one scan of the clock");
391
+ }
392
+ return unknown("an operation on the clock");
393
+ };
394
+ var unary = (node, operand) => {
395
+ if (node.operator === "not" && operand.kind === "bool") {
396
+ return known({ kind: "bool", value: !operand.value });
397
+ }
398
+ if (operand.kind === "integer") {
399
+ const result = integerUnary(node.operator, operand.value);
400
+ if (result !== undefined) {
401
+ return known(typed(result, node.type));
402
+ }
403
+ }
404
+ if (operand.kind === "float") {
405
+ const result = floatUnary(node.operator, operand.value);
406
+ if (result === undefined) {
407
+ return unknown("an operation this debugger can't evaluate");
408
+ }
409
+ if (node.operator === "truncate") {
410
+ return known(typed(BigInt(result), node.type));
411
+ }
412
+ const layout = floatLayout(node.type);
413
+ return known({
414
+ kind: "float",
415
+ value: layout && isElementary(node.operator) ? roundFloat(result, layout) : result
416
+ });
417
+ }
418
+ return unknown("an operation this debugger can't evaluate");
419
+ };
420
+ var convert = (node, operand) => {
421
+ const integer = integerLayout(node.type);
422
+ const float = floatLayout(node.type);
423
+ if (operand.kind === "integer" && integer) {
424
+ return known({
425
+ kind: "integer",
426
+ value: node.policy === "exact" ? operand.value : applyIntegerPolicy(operand.value, integer, node.policy)
427
+ });
428
+ }
429
+ if (operand.kind === "integer" && float) {
430
+ return known({
431
+ kind: "float",
432
+ value: roundFloat(Number(operand.value), float)
433
+ });
434
+ }
435
+ if (operand.kind === "float" && integer && node.policy === "saturate") {
436
+ return known({
437
+ kind: "integer",
438
+ value: saturateFloatToInteger(operand.value, integer)
439
+ });
440
+ }
441
+ if (operand.kind === "float" && float) {
442
+ return known({
443
+ kind: "float",
444
+ value: roundFloat(operand.value, float)
445
+ });
446
+ }
447
+ if (operand.kind === "interval" && integer) {
448
+ return known(operand);
449
+ }
450
+ return node.policy === "exact" ? known(operand) : unknown("a conversion this debugger can't evaluate");
451
+ };
452
+
453
+ // packages/debug/src/explain-expressions.ts
454
+ var nodeBudget = 20000;
455
+ var maxDepth = 400;
456
+ var sampleOutcome = ({ manifest, tables, read, needs }, path, type) => {
457
+ const flags = tables.flagsOf(path);
458
+ if (flags.constantTable && flags.initial !== null) {
459
+ const value = sampleValue(manifest, type, flags.initial);
460
+ return value ? known(value) : unknown("a constant this debugger can't show");
461
+ }
462
+ const sample = read.sample(path);
463
+ if (!sample) {
464
+ needs.add(path);
465
+ return unknown("reading");
466
+ }
467
+ if (sample.quality !== "good") {
468
+ return unknown(`read ${sample.quality}`);
469
+ }
470
+ const value = sampleValue(manifest, type, sample.value);
471
+ return value ? known(value) : unknown("a value this debugger can't evaluate");
472
+ };
473
+ var writtenAfter = ({ file, tables }, path, frame, at) => {
474
+ const here = [...frame.order, at];
475
+ return tables.writersOf(path).some((writer) => {
476
+ const assignment = file.assignments[writer.assignment];
477
+ return assignment !== undefined && writer.chains.some((chain) => chain.task === frame.task && compareOrder(tables.writeOrder(chain, assignment.position), here) > 0);
478
+ });
479
+ };
480
+ var stored = (evaluation, path, type, capturedAt, frame, interleaved) => {
481
+ const outcome = sampleOutcome(evaluation, path, type);
482
+ const flags = evaluation.tables.flagsOf(path);
483
+ const estimate = [
484
+ ...flags.writerTasks.some((task) => task !== frame.task) ? ["also written by another task"] : [],
485
+ ...writtenAfter(evaluation, path, frame, capturedAt) ? ["from the previous scan"] : [],
486
+ ...interleaved && evaluation.tables.writersOf(path).length ? ["a call between its read and its use may have changed it"] : []
487
+ ];
488
+ return withEstimate(outcome, estimate);
489
+ };
490
+ var project = (outcome, path) => {
491
+ const [first, ...rest] = path;
492
+ if (first === undefined || !outcome.known) {
493
+ return outcome;
494
+ }
495
+ const { value } = outcome;
496
+ if (value.kind === "record") {
497
+ const field = value.fields[first];
498
+ return field ? project(withEstimate(field, outcome.estimate), rest) : unknown("a field this value lacks");
499
+ }
500
+ if (value.kind === "array") {
501
+ const item = value.items[Number(first) - value.lower];
502
+ return item ? project(withEstimate(item, outcome.estimate), rest) : unknown("an element this value lacks");
503
+ }
504
+ return unknown("a part of a scalar");
505
+ };
506
+ var clock = ({ read }, frame) => {
507
+ const own = read.clock(frame.task);
508
+ return own ? known({ kind: "interval", low: own.low, high: own.high }) : unknown("no PLC clock in this build");
509
+ };
510
+ var definitionsBefore = ({ file }, local, at) => (file.locals[local]?.definitions ?? []).filter((definition) => definition.position < at).sort((a, b) => b.position - a.position);
511
+ var localValue = (evaluation, local, path, at, frame) => {
512
+ const { file, tables } = evaluation;
513
+ for (const [loop, value] of frame.counters) {
514
+ if (tables.loopCounterLocal(loop) === local) {
515
+ return known({ kind: "integer", value });
516
+ }
517
+ }
518
+ for (const definition of file.locals[local]?.definitions ?? []) {
519
+ const counter = definition.loop === null ? undefined : frame.counters.get(definition.loop);
520
+ if (definition.position < at || definition.loop === null || counter === undefined) {
521
+ continue;
522
+ }
523
+ const first = firstOf(evaluation, definition.loop, frame);
524
+ if (!first.known) {
525
+ return unknown(first.reason, first.estimate);
526
+ }
527
+ if (first.value.kind !== "integer" || counter !== first.value.value) {
528
+ return unknown("changed inside this loop");
529
+ }
530
+ }
531
+ for (const definition of definitionsBefore(evaluation, local, at)) {
532
+ const prefix = definition.path.every((name, index) => path[index] === name);
533
+ const part = !prefix && path.every((name, index) => definition.path[index] === name);
534
+ if (!prefix && !part) {
535
+ continue;
536
+ }
537
+ const truth = evaluation.conditionsTruth(definition.conditions, frame);
538
+ if (truth.truth === "false") {
539
+ continue;
540
+ }
541
+ const site = tables.siteText(definition.site);
542
+ if (truth.truth !== "true") {
543
+ return unknown(`depends on whether ${site} ran`, truth.estimate);
544
+ }
545
+ if (part) {
546
+ return unknown(`partly set by ${site}`, truth.estimate);
547
+ }
548
+ if (definition.kind === "borrowed") {
549
+ return unknown(`changed by the call ${site}`, truth.estimate);
550
+ }
551
+ if (definition.kind === "counter" || definition.value === null) {
552
+ return unknown(`set by the loop ${site}`, truth.estimate);
553
+ }
554
+ return withEstimate(project(expression(evaluation, definition.value, frame), path.slice(definition.path.length)), truth.estimate);
555
+ }
556
+ return;
557
+ };
558
+ var callResult = (evaluation, call, frame) => {
559
+ const inner = calleeFrame(evaluation, call, frame);
560
+ if ("known" in inner) {
561
+ return inner;
562
+ }
563
+ const returns = evaluation.file.returns.filter((item) => item.routine === inner.row).sort((a, b) => a.position - b.position);
564
+ for (const returned of returns) {
565
+ const truth = evaluation.conditionsTruth(returned.conditions, inner);
566
+ if (truth.truth === "false") {
567
+ continue;
568
+ }
569
+ if (truth.truth !== "true" || returned.value === null) {
570
+ return unknown(`depends on whether ${evaluation.tables.siteText(returned.site)} returned`, truth.estimate);
571
+ }
572
+ return withEstimate(expression(evaluation, returned.value, inner), truth.estimate);
573
+ }
574
+ return unknown("returns nothing this debugger can follow");
575
+ };
576
+ var expression = (evaluation, index, frame) => {
577
+ const { memo, budget } = evaluation;
578
+ const key = `${index}|${frameKey(frame)}`;
579
+ const cached = memo.get(key);
580
+ if (cached) {
581
+ return cached;
582
+ }
583
+ budget.spent += 1;
584
+ if (budget.spent > nodeBudget || budget.depth >= maxDepth) {
585
+ return unknown("too deep");
586
+ }
587
+ budget.depth += 1;
588
+ try {
589
+ const outcome = evaluate(evaluation, index, frame);
590
+ memo.set(key, outcome);
591
+ return outcome;
592
+ } finally {
593
+ budget.depth -= 1;
594
+ }
595
+ };
596
+ var evaluate = (evaluation, index, frame) => {
597
+ const { manifest, file, tables } = evaluation;
598
+ const node = file.expressions[index];
599
+ if (!node) {
600
+ return unknown("not traced");
601
+ }
602
+ switch (node.kind) {
603
+ case "read": {
604
+ const path = tables.pathAt(frame.row, node.path);
605
+ const bound = [...frame.counters].find(([loop]) => tables.loopCounterPath(loop) === path)?.[1];
606
+ return bound === undefined ? stored(evaluation, path, node.type, node.capturedAt, frame, node.interleaved === true) : known({ kind: "integer", value: bound });
607
+ }
608
+ case "pattern": {
609
+ const indexes = node.indexes.map((item) => expression(evaluation, item, frame));
610
+ const estimate = merge(...indexes.map((item) => item.estimate));
611
+ const missing = indexes.find((item) => !item.known);
612
+ if (missing) {
613
+ return unknown(missing.reason, estimate);
614
+ }
615
+ const values = indexes.flatMap((item) => item.known && item.value.kind === "integer" ? [item.value.value] : []);
616
+ if (values.length !== indexes.length) {
617
+ return unknown("an index this debugger can't evaluate", estimate);
618
+ }
619
+ const path = tables.pathAt(frame.row, node.path).split(anyIndex).reduce((built, part, position) => `${built}${position ? `[${values[position - 1]}]` : ""}${part}`, "");
620
+ return withEstimate(stored(evaluation, path, node.type, node.capturedAt, frame, node.interleaved === true), estimate);
621
+ }
622
+ case "constant": {
623
+ const value = sampleValue(manifest, node.type, node.value);
624
+ return value ? known(value) : constantAggregate(node.value);
625
+ }
626
+ case "record":
627
+ return known({
628
+ kind: "record",
629
+ fields: Object.fromEntries(Object.entries(node.fields).map(([name, field]) => [
630
+ name,
631
+ expression(evaluation, field, frame)
632
+ ]))
633
+ });
634
+ case "array":
635
+ return known({
636
+ kind: "array",
637
+ lower: node.lower,
638
+ items: node.items.map((item) => expression(evaluation, item, frame))
639
+ });
640
+ case "local":
641
+ return localValue(evaluation, tables.localAt(frame.row, node.local), node.path, node.at, frame) ?? unknown("no value before this point");
642
+ case "parameter": {
643
+ const own = node.local === null ? undefined : localValue(evaluation, tables.localAt(frame.row, node.local), node.path, node.at, frame);
644
+ if (own) {
645
+ return own;
646
+ }
647
+ const caller = frame.caller;
648
+ const call = caller ? file.calls[caller.call] : undefined;
649
+ const argument = call?.arguments[node.parameter];
650
+ if (!caller || argument === undefined) {
651
+ return unknown("depends on the call");
652
+ }
653
+ return project(expression(evaluation, argument, caller.frame), node.path);
654
+ }
655
+ case "call":
656
+ return project(callResult(evaluation, tables.callAt(frame.row, node.call), frame), node.path);
657
+ case "clock":
658
+ return clock(evaluation, frame);
659
+ case "reference": {
660
+ const operand = expression(evaluation, node.operand, frame);
661
+ if (!operand.known) {
662
+ return operand;
663
+ }
664
+ if (operand.value.kind !== "integer") {
665
+ return unknown("a reference this debugger can't follow", operand.estimate);
666
+ }
667
+ const id = operand.value.value;
668
+ const path = id < 0n ? null : file.paths[file.references[String(id)] ?? -1];
669
+ return known({ kind: "instance", id, path: path ?? null }, operand.estimate);
670
+ }
671
+ case "unary": {
672
+ const operand = expression(evaluation, node.operand, frame);
673
+ return operand.known ? withEstimate(unary(node, operand.value), operand.estimate) : operand;
674
+ }
675
+ case "convert": {
676
+ const operand = expression(evaluation, node.operand, frame);
677
+ return operand.known ? withEstimate(convert(node, operand.value), operand.estimate) : operand;
678
+ }
679
+ case "binary": {
680
+ const left = expression(evaluation, node.left, frame);
681
+ const right = expression(evaluation, node.right, frame);
682
+ const estimate = merge(left.estimate, right.estimate);
683
+ if (!left.known) {
684
+ return withEstimate(left, right.estimate);
685
+ }
686
+ if (!right.known) {
687
+ return withEstimate(right, left.estimate);
688
+ }
689
+ return withEstimate(binary(node, left.value, right.value), estimate);
690
+ }
691
+ case "logical": {
692
+ const left = expression(evaluation, node.left, frame);
693
+ const decided = node.operator === "or";
694
+ if (left.known && left.value.kind === "bool" && left.value.value === decided) {
695
+ return left;
696
+ }
697
+ const right = expression(evaluation, node.right, frame);
698
+ if (right.known && right.value.kind === "bool" && right.value.value === decided) {
699
+ return withEstimate(right, left.estimate);
700
+ }
701
+ if (!left.known) {
702
+ return withEstimate(left, right.estimate);
703
+ }
704
+ return withEstimate(right, left.estimate);
705
+ }
706
+ case "select": {
707
+ const condition = expression(evaluation, node.condition, frame);
708
+ if (condition.known && condition.value.kind === "bool") {
709
+ return withEstimate(expression(evaluation, condition.value.value ? node.then : node.else, frame), condition.estimate);
710
+ }
711
+ const then = expression(evaluation, node.then, frame);
712
+ const otherwise = expression(evaluation, node.else, frame);
713
+ if (then.known && otherwise.known && equalValues(then.value, otherwise.value)) {
714
+ return withEstimate(then, merge(condition.estimate, otherwise.estimate));
715
+ }
716
+ return unknown(condition.known ? "a condition this debugger can't evaluate" : condition.reason, condition.estimate);
717
+ }
718
+ case "opaque":
719
+ return unknown(`not traced: ${tables.text(node.text) ?? ""}`);
720
+ }
721
+ };
722
+
723
+ // packages/debug/src/explain-tables.ts
724
+ import { arrayIndex as arrayIndex2, joinPath as joinPath2 } from "@tsplc/opcua/contract";
725
+ var maxChains = 16;
726
+ var matchPattern = (pattern, path) => {
727
+ const segments = pathSegments(path);
728
+ const indexes = [];
729
+ for (const [position, part] of pattern.entries()) {
730
+ const segment = segments[position];
731
+ if (segment === undefined) {
732
+ return;
733
+ }
734
+ if (part === anyIndex) {
735
+ const index = arrayIndex2(segment);
736
+ if (index === undefined) {
737
+ return;
738
+ }
739
+ indexes.push(BigInt(index));
740
+ } else if (part !== segment) {
741
+ return;
742
+ }
743
+ }
744
+ return { indexes, exact: segments.length === pattern.length };
745
+ };
746
+ var createExplainTables = (manifest, file) => {
747
+ const text = (index) => index === null ? null : file.texts[index] ?? null;
748
+ const siteText = (site) => {
749
+ const found = site === null ? undefined : file.sites[site];
750
+ const source = found ? text(found.text) : null;
751
+ const sourceFile = found ? manifest.sources[found.range.file] : undefined;
752
+ const where = found && sourceFile ? `${sourceFile.split("/").at(-1)}:${found.range.line}` : "";
753
+ return [source, where && `at ${where}`].filter(Boolean).join(" ");
754
+ };
755
+ const byPath = new Map;
756
+ const patterns = [];
757
+ file.assignments.forEach((assignment, index) => {
758
+ const written = file.paths[assignment.writes.path] ?? "";
759
+ if (assignment.writes.kind === "pattern") {
760
+ patterns.push({
761
+ assignment: index,
762
+ segments: pathSegments(written),
763
+ whole: assignment.whole
764
+ });
765
+ return;
766
+ }
767
+ byPath.set(written, [...byPath.get(written) ?? [], index]);
768
+ });
769
+ const flagsByPath = new Map(file.flags.map((item) => [file.paths[item.path] ?? "", item]));
770
+ const rowsByKey = new Map;
771
+ file.routines.forEach((row, index) => {
772
+ rowsByKey.set(row.key, [...rowsByKey.get(row.key) ?? [], index]);
773
+ });
774
+ const slots = (row) => file.routines[row];
775
+ const pathAt = (row, slot) => file.paths[slots(row)?.paths[slot] ?? -1] ?? "";
776
+ const localAt = (row, slot) => slots(row)?.locals[slot] ?? -1;
777
+ const callAt = (row, slot) => slots(row)?.calls[slot] ?? -1;
778
+ const loopAt = (row, slot) => slots(row)?.loops[slot] ?? -1;
779
+ const loopSlot = (row, loop) => slots(row)?.loops.indexOf(loop) ?? -1;
780
+ const instanceOf = (row) => {
781
+ const instance = file.routines[row]?.instance;
782
+ return instance === null || instance === undefined ? null : file.paths[instance] ?? null;
783
+ };
784
+ const calleesOf = (call) => {
785
+ const rows = rowsByKey.get(call.callee) ?? [];
786
+ const { receiver } = call;
787
+ if (receiver.kind === "none") {
788
+ return rows.filter((row) => instanceOf(row) === null).map((row) => ({ row, indexes: [] }));
789
+ }
790
+ const target = file.paths[receiver.path] ?? "";
791
+ if (receiver.kind === "path") {
792
+ return rows.filter((row) => instanceOf(row) === target).map((row) => ({ row, indexes: [] }));
793
+ }
794
+ const pattern = pathSegments(target);
795
+ return rows.flatMap((row) => {
796
+ const match = matchPattern(pattern, instanceOf(row) ?? "");
797
+ return match?.exact ? [{ row, indexes: match.indexes }] : [];
798
+ });
799
+ };
800
+ const callers = new Map;
801
+ file.calls.forEach((call, index) => {
802
+ for (const { row } of calleesOf(call)) {
803
+ callers.set(row, [...callers.get(row) ?? [], index]);
804
+ }
805
+ });
806
+ const entries = new Map(file.entries.map((entry) => [entry.routine, entry]));
807
+ const chainsTo = (row) => {
808
+ const found = [];
809
+ const walk = (current, below, seen) => {
810
+ if (found.length >= maxChains) {
811
+ return;
812
+ }
813
+ const entry = entries.get(current);
814
+ if (entry) {
815
+ found.push({ task: entry.task, entry: current, calls: below });
816
+ }
817
+ for (const call of callers.get(current) ?? []) {
818
+ const caller = file.calls[call]?.routine;
819
+ if (caller !== undefined && !seen.has(caller)) {
820
+ walk(caller, [call, ...below], new Set([...seen, caller]));
821
+ }
822
+ }
823
+ };
824
+ walk(row, [], new Set([row]));
825
+ return found;
826
+ };
827
+ const chainCache = new Map;
828
+ const chains = (row) => {
829
+ const cached = chainCache.get(row);
830
+ if (cached) {
831
+ return cached;
832
+ }
833
+ const computed = chainsTo(row);
834
+ chainCache.set(row, computed);
835
+ return computed;
836
+ };
837
+ const writerChains = (assignment) => {
838
+ const outermost = assignment.via.at(-1);
839
+ if (outermost === undefined) {
840
+ return chains(assignment.routine);
841
+ }
842
+ const passing = [...assignment.via].reverse();
843
+ return chains(file.calls[outermost]?.routine ?? -1).map((chain) => ({
844
+ ...chain,
845
+ calls: [...chain.calls, ...passing]
846
+ }));
847
+ };
848
+ const flagsOf = (path) => {
849
+ const merged = {
850
+ input: null,
851
+ clientWritable: false,
852
+ hmiControl: null,
853
+ retained: false,
854
+ constantTable: false,
855
+ writerTasks: [],
856
+ service: null,
857
+ initial: null,
858
+ reference: false
859
+ };
860
+ let prefix = "";
861
+ for (const segment of pathSegments(path)) {
862
+ prefix = joinPath2(prefix, segment);
863
+ const item = flagsByPath.get(prefix);
864
+ if (!item) {
865
+ continue;
866
+ }
867
+ merged.input ??= item.input;
868
+ merged.clientWritable ||= item.clientWritable;
869
+ merged.hmiControl ??= item.hmiControl;
870
+ merged.retained ||= item.retained;
871
+ merged.constantTable ||= item.constantTable;
872
+ merged.writerTasks = merge(merged.writerTasks, item.writerTasks);
873
+ merged.service ??= item.service;
874
+ merged.reference ||= item.reference;
875
+ if (prefix === path) {
876
+ merged.initial = item.initial;
877
+ }
878
+ }
879
+ return merged;
880
+ };
881
+ const writersOf = (path) => {
882
+ const found = [];
883
+ const segments = pathSegments(path);
884
+ let prefix = "";
885
+ for (const [position, segment] of segments.entries()) {
886
+ prefix = joinPath2(prefix, segment);
887
+ const last = position === segments.length - 1;
888
+ for (const assignment of byPath.get(prefix) ?? []) {
889
+ if (last || file.assignments[assignment]?.whole) {
890
+ found.push({ assignment, indexes: [] });
891
+ }
892
+ }
893
+ }
894
+ for (const pattern of patterns) {
895
+ const match = matchPattern(pattern.segments, path);
896
+ if (match && (match.exact || pattern.whole)) {
897
+ found.push({ assignment: pattern.assignment, indexes: match.indexes });
898
+ }
899
+ }
900
+ return found.map((item) => {
901
+ const assignment = file.assignments[item.assignment];
902
+ return {
903
+ ...item,
904
+ chains: assignment ? writerChains(assignment) : []
905
+ };
906
+ });
907
+ };
908
+ const writeOrder = (chain, position) => [
909
+ entries.get(chain.entry)?.order ?? 0,
910
+ ...chain.calls.map((call) => file.calls[call]?.position ?? 0),
911
+ position
912
+ ];
913
+ const conditionList = (entry) => {
914
+ const list = [];
915
+ for (let current = entry;current !== null; current = file.conditions[current]?.parent ?? null) {
916
+ const item = file.conditions[current];
917
+ if (item) {
918
+ list.unshift(item.condition);
919
+ }
920
+ }
921
+ return list;
922
+ };
923
+ const counterNode = (loop) => {
924
+ const record = file.loops[loop];
925
+ const node = record ? file.expressions[record.counter] : undefined;
926
+ return record && node && { routine: record.routine, node };
927
+ };
928
+ const loopCounterLocal = (loop) => {
929
+ const counter = counterNode(loop);
930
+ return counter?.node.kind === "local" ? localAt(counter.routine, counter.node.local) : undefined;
931
+ };
932
+ const loopCounterPath = (loop) => {
933
+ const counter = counterNode(loop);
934
+ return counter?.node.kind === "read" ? pathAt(counter.routine, counter.node.path) : undefined;
935
+ };
936
+ return {
937
+ text,
938
+ siteText,
939
+ slots,
940
+ pathAt,
941
+ localAt,
942
+ callAt,
943
+ loopAt,
944
+ loopSlot,
945
+ calleesOf,
946
+ entries,
947
+ flagsOf,
948
+ writersOf,
949
+ writeOrder,
950
+ conditionList,
951
+ loopCounterLocal,
952
+ loopCounterPath,
953
+ explain: (path) => ({
954
+ path,
955
+ writers: writersOf(path),
956
+ flags: flagsOf(path),
957
+ io: manifest.io.find((item) => item.path === path) ?? null
958
+ })
959
+ };
960
+ };
961
+
962
+ // packages/debug/src/explain-verdicts.ts
963
+ var jobTruth = ({ manifest, read }, job, step, result) => {
964
+ const state = read.job(job);
965
+ const declared = manifest.jobs.find((item) => item.id === job);
966
+ const steps = declared?.steps ?? [];
967
+ const stepText = steps.find((item) => item.step === step)?.text ?? `step ${step}`;
968
+ if (!state || state.busy === null) {
969
+ return result("unknown", ["the job's state isn't known"]);
970
+ }
971
+ if (state.unread) {
972
+ return result("unknown", ["over the jobs read per poll"]);
973
+ }
974
+ const current = steps.find((item) => item.step === state.step);
975
+ const cancelling = state.cancelling ? ["the job is being cancelled"] : [];
976
+ if (state.busy && state.step === step && current?.kind === "await") {
977
+ return result("true", [`waiting at ${stepText}`], ["a job's step can change between scans", ...cancelling]);
978
+ }
979
+ return result("candidate", [
980
+ `ran when job ${declared?.name ?? `job ${job}`} passed ${stepText}, this scan or earlier`
981
+ ], cancelling);
982
+ };
983
+ var conditionTruth = (evaluation, condition, frame) => {
984
+ const { tables, read } = evaluation;
985
+ const result = (truth, reasons = [], estimate = []) => ({
986
+ condition,
987
+ row: frame.row,
988
+ truth,
989
+ reasons,
990
+ estimate
991
+ });
992
+ switch (condition.kind) {
993
+ case "test": {
994
+ const outcome = evaluation.expression(condition.test, frame);
995
+ if (!outcome.known) {
996
+ return result("unknown", [outcome.reason], outcome.estimate);
997
+ }
998
+ if (outcome.value.kind !== "bool") {
999
+ return result("unknown", ["a condition this debugger can't evaluate"], outcome.estimate);
1000
+ }
1001
+ return result(outcome.value.value === condition.holds ? "true" : "false", [], outcome.estimate);
1002
+ }
1003
+ case "cases": {
1004
+ const outcome = evaluation.expression(condition.test, frame);
1005
+ if (!outcome.known) {
1006
+ return result("unknown", [outcome.reason], outcome.estimate);
1007
+ }
1008
+ const member = condition.values.some((value) => {
1009
+ const constant = constantAggregate(value);
1010
+ return constant.known && equalValues(constant.value, outcome.value) === true;
1011
+ });
1012
+ return result(member === condition.member ? "true" : "false", [], outcome.estimate);
1013
+ }
1014
+ case "exits": {
1015
+ const parts = condition.any.map((all) => all.map((part) => conditionTruth(evaluation, part, frame)));
1016
+ const any = parts.map((all) => and(all.map((part) => part.truth)));
1017
+ const estimate = merge(...parts.flat().map((part) => part.estimate));
1018
+ if (any.includes("true")) {
1019
+ return result("false", [], estimate);
1020
+ }
1021
+ if (any.includes("unknown") || any.includes("candidate")) {
1022
+ return result("unknown", ["depends on whether an earlier statement left"], estimate);
1023
+ }
1024
+ return result("true", [], estimate);
1025
+ }
1026
+ case "loop":
1027
+ return frame.counters.has(tables.loopAt(frame.row, condition.loop)) ? result("true") : result("unknown", ["inside a loop"]);
1028
+ case "loopReturns": {
1029
+ const run = executeLoop(evaluation, tables.loopAt(frame.row, condition.loop), frame, null);
1030
+ if (run.kind === "unknown") {
1031
+ return result("unknown", [run.reason], run.estimate);
1032
+ }
1033
+ return result(run.returned ? "false" : "true", [], run.estimate);
1034
+ }
1035
+ case "job":
1036
+ return jobTruth(evaluation, tables.slots(frame.row)?.job ?? -1, condition.step, result);
1037
+ case "jobBusy": {
1038
+ const state = read.job(tables.slots(frame.row)?.job ?? -1);
1039
+ if (!state || state.busy === null) {
1040
+ return result("unknown", ["the job's state isn't known"]);
1041
+ }
1042
+ return state.busy ? result("true", [], ["the job may have moved on since"]) : result("candidate", ["the job isn't running now"]);
1043
+ }
1044
+ }
1045
+ };
1046
+ var conditionsTruth = (evaluation, entry, frame) => {
1047
+ const results = evaluation.tables.conditionList(entry).map((condition) => conditionTruth(evaluation, condition, frame));
1048
+ return {
1049
+ truth: and(results.map((item) => item.truth)),
1050
+ results,
1051
+ estimate: merge(...results.map((item) => item.estimate))
1052
+ };
1053
+ };
1054
+ var indexTruth = (outcome, wanted) => {
1055
+ if (!outcome.known) {
1056
+ return "unknown";
1057
+ }
1058
+ return outcome.value.kind === "integer" && outcome.value.value === wanted ? "true" : "false";
1059
+ };
1060
+ var loopResult = (run) => {
1061
+ if (run.kind === "unknown") {
1062
+ return { truth: "unknown", reasons: [run.reason] };
1063
+ }
1064
+ return run.ran ? { truth: "true", reasons: [] } : { truth: "false", reasons: ["no iteration ran it"] };
1065
+ };
1066
+ var states = {
1067
+ true: "runs",
1068
+ false: "blocked",
1069
+ unknown: "unknown",
1070
+ candidate: "candidate"
1071
+ };
1072
+ var verdict = (evaluation, writer, chain) => {
1073
+ const { file, tables } = evaluation;
1074
+ const assignment = file.assignments[writer.assignment];
1075
+ if (!assignment) {
1076
+ return {
1077
+ writer,
1078
+ chain,
1079
+ state: "unknown",
1080
+ reasons: ["not traced"],
1081
+ estimate: [],
1082
+ conditions: [],
1083
+ value: null
1084
+ };
1085
+ }
1086
+ const results = [];
1087
+ let frame = rootFrame(evaluation, { ...chain, calls: [] });
1088
+ const reasons = [];
1089
+ for (const call of chain.calls) {
1090
+ const record = file.calls[call];
1091
+ if (!record) {
1092
+ continue;
1093
+ }
1094
+ if (record.loop !== null) {
1095
+ reasons.push("called inside a loop");
1096
+ results.push({
1097
+ condition: {
1098
+ kind: "loop",
1099
+ loop: tables.loopSlot(frame.row, record.loop)
1100
+ },
1101
+ row: frame.row,
1102
+ truth: "unknown",
1103
+ reasons: ["called inside a loop"],
1104
+ estimate: []
1105
+ });
1106
+ } else {
1107
+ results.push(...conditionsTruth(evaluation, record.conditions, frame).results);
1108
+ }
1109
+ const next = calleeFrame(evaluation, call, frame);
1110
+ if ("known" in next) {
1111
+ return {
1112
+ writer,
1113
+ chain,
1114
+ state: "unknown",
1115
+ reasons: [next.reason],
1116
+ estimate: [...next.estimate],
1117
+ conditions: results,
1118
+ value: null
1119
+ };
1120
+ }
1121
+ frame = next;
1122
+ }
1123
+ const namingFrame = (inner) => assignment.via.reduce((frame) => frame.caller?.frame ?? frame, inner);
1124
+ const indexMatch = (inner) => assignment.writes.kind === "pattern" ? assignment.writes.indexes.map((index, position) => {
1125
+ const outcome = evaluation.expression(index, namingFrame(inner));
1126
+ return {
1127
+ condition: {
1128
+ kind: "test",
1129
+ test: index,
1130
+ holds: true,
1131
+ at: assignment.position,
1132
+ text: null
1133
+ },
1134
+ row: namingFrame(inner).row,
1135
+ truth: indexTruth(outcome, writer.indexes[position]),
1136
+ reasons: outcome.known ? [] : [outcome.reason],
1137
+ estimate: outcome.estimate
1138
+ };
1139
+ }) : [];
1140
+ const reaches = (inner) => {
1141
+ const own = conditionsTruth(evaluation, assignment.conditions, inner);
1142
+ const matched = indexMatch(inner);
1143
+ return {
1144
+ truth: and([own.truth, ...matched.map((item) => item.truth)]),
1145
+ estimate: merge(own.estimate, ...matched.map((item) => item.estimate)),
1146
+ results: [...own.results, ...matched]
1147
+ };
1148
+ };
1149
+ if (assignment.loop !== null) {
1150
+ const run = executeLoop(evaluation, assignment.loop, frame, reaches);
1151
+ results.push({
1152
+ condition: {
1153
+ kind: "loop",
1154
+ loop: tables.loopSlot(frame.row, assignment.loop)
1155
+ },
1156
+ row: frame.row,
1157
+ ...loopResult(run),
1158
+ estimate: run.estimate
1159
+ });
1160
+ if (run.kind === "run" && run.ran) {
1161
+ frame = run.ran;
1162
+ }
1163
+ } else {
1164
+ results.push(...reaches(frame).results);
1165
+ }
1166
+ const truth = and(results.map((item) => item.truth));
1167
+ return {
1168
+ writer,
1169
+ chain,
1170
+ state: states[truth],
1171
+ reasons: [
1172
+ ...reasons,
1173
+ ...results.filter((item) => item.truth === truth && truth !== "true").flatMap((item) => item.reasons)
1174
+ ],
1175
+ estimate: merge(...results.map((item) => item.estimate)),
1176
+ conditions: results,
1177
+ value: truth === "true" && assignment.value !== null ? evaluation.expression(assignment.value, frame) : null
1178
+ };
1179
+ };
1180
+ var answer = (evaluation, explanation, type) => {
1181
+ const { manifest, file, tables, read, needs } = evaluation;
1182
+ const current = sampleOutcome(evaluation, explanation.path, type);
1183
+ const verdicts = explanation.writers.flatMap((writer) => writer.chains.length ? writer.chains.map((chain) => verdict(evaluation, writer, chain)) : [
1184
+ {
1185
+ writer,
1186
+ chain: { task: "", entry: -1, calls: [] },
1187
+ state: "blocked",
1188
+ reasons: ["no task reaches it"],
1189
+ estimate: [],
1190
+ conditions: [],
1191
+ value: null
1192
+ }
1193
+ ]);
1194
+ const slot = read.slot(explanation.path);
1195
+ const slotted = verdicts.filter((item) => slot?.assignments?.includes(item.writer.assignment));
1196
+ const result = (answer) => ({
1197
+ answer,
1198
+ verdicts,
1199
+ clientWritable: explanation.flags.clientWritable,
1200
+ hmiControl: explanation.flags.hmiControl,
1201
+ retained: explanation.flags.retained,
1202
+ writerTasks: explanation.flags.writerTasks,
1203
+ needs: [...needs],
1204
+ hint: slot && !slot.exact ? slotted : []
1205
+ });
1206
+ if (read.forced?.has(explanation.path)) {
1207
+ return result({ kind: "forced", value: current });
1208
+ }
1209
+ if (slot?.exact) {
1210
+ return result({
1211
+ kind: "exact",
1212
+ writer: slot.assignments === null ? null : slotted.find((item) => item.state === "runs") ?? slotted[0] ?? null
1213
+ });
1214
+ }
1215
+ if (explanation.io?.direction === "input") {
1216
+ return result({ kind: "input", io: explanation.io, value: current });
1217
+ }
1218
+ const orderOf = (item) => tables.writeOrder(item.chain, file.assignments[item.writer.assignment]?.position ?? 0);
1219
+ const ordered = [...verdicts].sort((a, b) => compareOrder(orderOf(a), orderOf(b)));
1220
+ const consistent = (item) => {
1221
+ if (!item.value?.known || item.value.estimate.length || !current.known) {
1222
+ return true;
1223
+ }
1224
+ return equalValues(item.value.value, current.value) !== false;
1225
+ };
1226
+ const running = ordered.filter((item) => item.state === "runs");
1227
+ const excluded = running.filter((item) => !consistent(item));
1228
+ const candidates = running.filter((item) => consistent(item));
1229
+ const last = candidates.at(-1);
1230
+ if (last) {
1231
+ const tasks = new Set(running.map((item) => item.chain.task));
1232
+ const later = ordered.slice(ordered.indexOf(last) + 1).filter((item) => item.state === "unknown" || item.state === "candidate" || item.state === "runs" && item.chain.task !== last.chain.task);
1233
+ const others = tasks.size > 1 ? running.filter((item) => item !== last && item.chain.task !== last.chain.task) : [];
1234
+ const unless = [...new Set([...later, ...others])];
1235
+ return result({
1236
+ kind: "set",
1237
+ writer: last,
1238
+ unless,
1239
+ estimate: merge(last.estimate, unless.length ? ["another writer may have run after it"] : [], excluded.some((item) => ordered.indexOf(item) > ordered.indexOf(last)) ? ["a later writer's value didn't match"] : [])
1240
+ });
1241
+ }
1242
+ if (excluded.length) {
1243
+ return result({ kind: "changed", writers: excluded });
1244
+ }
1245
+ if (verdicts.every((item) => item.state === "blocked" || item.state === "candidate")) {
1246
+ const could = verdicts.filter((item) => {
1247
+ const assignment = file.assignments[item.writer.assignment];
1248
+ const constant = assignment?.value === null || assignment?.value === undefined ? undefined : file.expressions[assignment.value];
1249
+ if (constant?.kind !== "constant" || !current.known) {
1250
+ return true;
1251
+ }
1252
+ const value = sampleValue(manifest, constant.type, constant.value);
1253
+ return !value || equalValues(value, current.value) !== false;
1254
+ });
1255
+ const jobs = verdicts.filter((item) => item.state === "candidate");
1256
+ return result({
1257
+ kind: "held",
1258
+ writers: could,
1259
+ estimate: jobs.length ? ["set by a job step, this scan or earlier"] : []
1260
+ });
1261
+ }
1262
+ const open = verdicts.filter((item) => item.state === "unknown");
1263
+ return result({
1264
+ kind: "unknown",
1265
+ writers: open,
1266
+ reasons: merge(...open.map((item) => item.reasons))
1267
+ });
1268
+ };
1269
+
1270
+ // packages/debug/src/explain.ts
1271
+ var createExplainer = (manifest, file) => {
1272
+ const tables = createExplainTables(manifest, file);
1273
+ const evaluation = (read) => {
1274
+ const context = {
1275
+ manifest,
1276
+ file,
1277
+ tables,
1278
+ read,
1279
+ needs: new Set,
1280
+ memo: new Map,
1281
+ budget: { spent: 0, depth: 0 },
1282
+ expression: (index, frame) => expression(context, index, frame),
1283
+ conditionTruth: (condition, frame) => conditionTruth(context, condition, frame),
1284
+ conditionsTruth: (entry, frame) => conditionsTruth(context, entry, frame)
1285
+ };
1286
+ return context;
1287
+ };
1288
+ return {
1289
+ explain: tables.explain,
1290
+ answer: (explanation, type, read) => answer(evaluation(read), explanation, type),
1291
+ evaluate: (index, chain, read, row) => {
1292
+ const run = evaluation(read);
1293
+ const frames = chain.calls.map((_, depth) => rootFrame(run, { ...chain, calls: chain.calls.slice(0, depth + 1) }));
1294
+ const frame = [rootFrame(run, { ...chain, calls: [] }), ...frames].reverse().find((item) => item.row === row) ?? rootFrame(run, chain);
1295
+ return expression(run, index, frame);
1296
+ },
1297
+ pathAt: tables.pathAt,
1298
+ file
1299
+ };
1300
+ };
1301
+ export {
1302
+ createExplainer,
1303
+ maxDepth,
1304
+ maxLoopIterations,
1305
+ nodeBudget,
1306
+ sampleValue
1307
+ };
1308
+
1309
+ //# debugId=560EA78AC92AA17564756E2164756E21
1310
+ //# sourceMappingURL=explain.js.map