lycheedev 1.0.0 → 1.0.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 (50) hide show
  1. package/bin/lycheedev.js +58 -8
  2. package/package.json +1 -1
  3. package/vendor/addon/Core/Bootstrap.lua +131 -131
  4. package/vendor/addon/Core/Clients/Mainline.lua +9 -9
  5. package/vendor/addon/Core/Clients/Mists.lua +9 -9
  6. package/vendor/addon/Core/Clients/Titan.lua +9 -9
  7. package/vendor/addon/Core/Compatibility.lua +43 -43
  8. package/vendor/addon/Core/Database.lua +859 -859
  9. package/vendor/addon/Core/Inspector.lua +647 -647
  10. package/vendor/addon/Core/Locale.lua +307 -307
  11. package/vendor/addon/Core/Locale_enUS.lua +318 -318
  12. package/vendor/addon/Core/Safety.lua +42 -42
  13. package/vendor/addon/Core/Serializer.lua +324 -324
  14. package/vendor/addon/Libs/AutomationQR.lua +1176 -1176
  15. package/vendor/addon/Lychee Dev_Mainline.toc +43 -43
  16. package/vendor/addon/Lychee Dev_Mists.toc +43 -43
  17. package/vendor/addon/Lychee Dev_Wrath.toc +43 -43
  18. package/vendor/addon/Modules/Automation/Controller.lua +757 -757
  19. package/vendor/addon/Modules/Automation/Report.lua +409 -409
  20. package/vendor/addon/Modules/Automation/auto/auto.lua +12 -12
  21. package/vendor/addon/Modules/Diagnostics.lua +238 -238
  22. package/vendor/addon/Modules/Events/Catalog.lua +184 -184
  23. package/vendor/addon/Modules/Events/CatalogData_Mainline.lua +1788 -1788
  24. package/vendor/addon/Modules/Events/CatalogData_Mists.lua +1489 -1489
  25. package/vendor/addon/Modules/Events/CatalogData_Titan.lua +1492 -1492
  26. package/vendor/addon/Modules/Events/Monitor.lua +181 -181
  27. package/vendor/addon/Modules/FunctionTrace.lua +85 -85
  28. package/vendor/addon/Modules/ObjectInspector.lua +329 -329
  29. package/vendor/addon/UI/AutomationOverlay.lua +183 -183
  30. package/vendor/addon/UI/Export.lua +140 -140
  31. package/vendor/addon/UI/Features.lua +890 -890
  32. package/vendor/addon/UI/MainWindow.lua +1145 -1145
  33. package/vendor/addon/UI/Pages/About.lua +223 -223
  34. package/vendor/addon/UI/Pages/Automation.lua +417 -417
  35. package/vendor/addon/UI/Pages/Diagnostics.lua +289 -289
  36. package/vendor/addon/UI/Pages/ExportRecords.lua +387 -387
  37. package/vendor/addon/UI/Pages/Object.lua +573 -573
  38. package/vendor/addon/UI/Pages/Trace.lua +165 -165
  39. package/vendor/skill/SKILL.md +94 -94
  40. package/vendor/skill/agents/openai.yaml +4 -4
  41. package/vendor/skill/references/automation.md +327 -327
  42. package/vendor/skill/references/runtime-investigations.md +97 -97
  43. package/vendor/skill/scripts/automation/__init__.py +1 -1
  44. package/vendor/skill/scripts/automation/registry.py +516 -516
  45. package/vendor/skill/scripts/automation/saved_variables.py +438 -438
  46. package/vendor/skill/scripts/automation/session.py +207 -207
  47. package/vendor/skill/scripts/automation/windows.py +573 -573
  48. package/vendor/skill/scripts/automation.py +865 -865
  49. package/vendor/skill/scripts/requirements.txt +13 -13
  50. package/vendor/skill/scripts/selftest_offline.py +981 -981
@@ -1,438 +1,438 @@
1
- """Restricted reader and verifier for Lychee Dev SavedVariables.
2
-
3
- The SavedVariables file is data, never code: this module parses it with a
4
- bounded recursive-descent parser that only accepts WoW's stored assignment
5
- syntax (``Name = { ... }`` with ``["key"] = value`` pairs, strings, numbers and
6
- booleans). It refuses and never evaluates functions, calls, operators or any
7
- other expression, so a hostile or truncated file cannot execute anything.
8
-
9
- Verification follows the design's fixed order: exact ticket lookup under
10
- ``LycheeDevDB.exports.records``, envelope checks, metadata identity against the
11
- host's delivery log, byte counts and the Adler-32 content checksum, then the
12
- inner ``lychee.automation.result.v1`` JSON report.
13
- """
14
-
15
- from __future__ import annotations
16
-
17
- import json
18
- import re
19
- import zlib
20
-
21
- EVIDENCE_SCHEMA = "lychee.evidence.v1"
22
- RESULT_SCHEMA = "lychee.automation.result.v1"
23
- ADLER_ALGORITHM = "adler32"
24
- MEDIA_TYPE = "application/json"
25
- ENCODING = "utf-8"
26
- TICKET_PATTERN = re.compile(r"^LYCHEE-[A-Za-z0-9-]+$")
27
-
28
- # The client emits an explicit ``nil`` for a declared-but-absent SavedVariables
29
- # global (``DumperDB = nil``), and Lua tables can hold ``["key"] = nil``. Both
30
- # mean "not there", so the parser returns this sentinel instead of a value.
31
- NIL = object()
32
-
33
- # Terminal states the Lua side may record (design section 8).
34
- TERMINAL_STATUSES = ("succeeded", "failed", "cancelled", "interrupted")
35
- REQUEST_TYPES = ("task", "bug")
36
-
37
- # Parser limits: generous enough for a 16 MiB evidence budget with escaping
38
- # overhead, strict enough to bound memory and reject runaway files.
39
- MAX_FILE_BYTES = 256 * 1024 * 1024
40
- MAX_DEPTH = 200
41
- MAX_ENTRIES = 2_000_000
42
- MAX_STRING_BYTES = 64 * 1024 * 1024
43
- # A single automation report is capped at 1 MiB after serialization.
44
- MAX_REPORT_BYTES = 1024 * 1024
45
-
46
- STRING_ESCAPES = {'"': '"', "\\": "\\", "n": "\n", "r": "\r", "t": "\t",
47
- "a": "\a", "b": "\b", "f": "\f", "v": "\v", "'": "'"}
48
- DIGITS = "0123456789"
49
- DECIMAL_ESCAPE = re.compile(r"[0-9]{1,3}")
50
- ADLER_PATTERN = re.compile(r"^[0-9a-f]{8}$")
51
-
52
-
53
- class SavedVariablesError(Exception):
54
- """Raised for parse failures, identity conflicts and verification failures."""
55
-
56
-
57
- class _Tokenizer:
58
- def __init__(self, text: str):
59
- self.text = text
60
- self.pos = 0
61
- self.length = len(text)
62
- self.entries = 0
63
-
64
- def skip_ws(self) -> None:
65
- while self.pos < self.length and self.text[self.pos] in " \t\r\n":
66
- self.pos += 1
67
-
68
- def peek(self) -> str:
69
- if self.pos >= self.length:
70
- return ""
71
- return self.text[self.pos]
72
-
73
- def expect(self, char: str) -> None:
74
- self.skip_ws()
75
- if self.peek() != char:
76
- raise SavedVariablesError(
77
- f"expected {char!r} at offset {self.pos}, found {self.peek()!r}")
78
- self.pos += 1
79
-
80
- def read_name(self) -> str:
81
- self.skip_ws()
82
- match = re.match(r"[A-Za-z_][A-Za-z0-9_]*", self.text[self.pos:])
83
- if not match:
84
- raise SavedVariablesError(f"expected a name at offset {self.pos}")
85
- self.pos += match.end()
86
- return match.group(0)
87
-
88
- def read_string(self) -> str:
89
- """Read one quoted string, preserving its exact bytes.
90
-
91
- WoW stores strings with Lua 5.1 escapes; ``\\ddd`` takes one to three
92
- decimal digits (not exactly three), and multi-byte UTF-8 may arrive as
93
- literal text or as consecutive ``\\ddd`` bytes. Bytes are accumulated and
94
- only decoded at the end, so the original content survives untouched.
95
- """
96
-
97
- self.expect('"')
98
- out = bytearray()
99
- while True:
100
- if self.pos >= self.length:
101
- raise SavedVariablesError("unterminated string literal")
102
- char = self.text[self.pos]
103
- if char == '"':
104
- self.pos += 1
105
- try:
106
- return out.decode("utf-8")
107
- except UnicodeDecodeError as error:
108
- raise SavedVariablesError(
109
- f"string literal is not valid UTF-8: {error}") from error
110
- if char == "\\":
111
- self.pos += 1
112
- if self.pos >= self.length:
113
- raise SavedVariablesError("dangling escape in string literal")
114
- escape = self.text[self.pos]
115
- if escape in STRING_ESCAPES:
116
- out.extend(STRING_ESCAPES[escape].encode("utf-8"))
117
- self.pos += 1
118
- elif escape in DIGITS:
119
- match = DECIMAL_ESCAPE.match(self.text, self.pos)
120
- digits = match.group(0)
121
- value = int(digits)
122
- if value > 255:
123
- raise SavedVariablesError(
124
- f"decimal escape too large: \\{digits}")
125
- out.append(value)
126
- self.pos += len(digits)
127
- elif escape == "z":
128
- # Lua 5.1 \z skips the following whitespace.
129
- self.pos += 1
130
- while self.pos < self.length and self.text[self.pos] in " \t\r\n":
131
- self.pos += 1
132
- else:
133
- raise SavedVariablesError(f"unsupported escape: \\{escape}")
134
- if len(out) > MAX_STRING_BYTES:
135
- raise SavedVariablesError("string literal exceeds the size limit")
136
- continue
137
- if char == "\n" or char == "\r":
138
- raise SavedVariablesError("raw newline inside a string literal")
139
- if ord(char) > 0x7E:
140
- # Literal non-ASCII text was decoded from UTF-8; put the same
141
- # bytes back so byte counts stay exact.
142
- out.extend(char.encode("utf-8"))
143
- else:
144
- out.append(ord(char))
145
- self.pos += 1
146
- if len(out) > MAX_STRING_BYTES:
147
- raise SavedVariablesError("string literal exceeds the size limit")
148
-
149
- def read_number(self) -> float | int:
150
- self.skip_ws()
151
- match = re.match(r"-?\d+\.\d+(?:[eE][+-]?\d+)?|-?\d+(?:[eE][+-]?\d+)?|-?\.\d+",
152
- self.text[self.pos:])
153
- if not match:
154
- raise SavedVariablesError(f"expected a number at offset {self.pos}")
155
- self.pos += match.end()
156
- token = match.group(0)
157
- if re.fullmatch(r"-?\d+", token):
158
- return int(token)
159
- return float(token)
160
-
161
- def count_entry(self) -> None:
162
- self.entries += 1
163
- if self.entries > MAX_ENTRIES:
164
- raise SavedVariablesError("entry limit exceeded while parsing")
165
-
166
-
167
- def parse_lua_assignments(text: str) -> dict:
168
- """Parse a SavedVariables document into {globalName: value}.
169
-
170
- The client writes an explicit ``nil`` for a declared SavedVariables global
171
- that does not exist in this session (for example ``DumperDB = nil``), so
172
- ``nil`` is accepted as data and means "this global is absent".
173
- """
174
-
175
- if len(text.encode("utf-8", errors="replace")) > MAX_FILE_BYTES:
176
- raise SavedVariablesError("saved variables file exceeds the size limit")
177
- tokenizer = _Tokenizer(text)
178
- document: dict = {}
179
- tokenizer.skip_ws()
180
- while tokenizer.pos < tokenizer.length:
181
- name = tokenizer.read_name()
182
- tokenizer.expect("=")
183
- value = _parse_value(tokenizer, 0)
184
- if value is NIL:
185
- document.pop(name, None)
186
- else:
187
- document[name] = value
188
- tokenizer.skip_ws()
189
- return document
190
-
191
-
192
- def _parse_value(tokenizer: _Tokenizer, depth: int):
193
- if depth > MAX_DEPTH:
194
- raise SavedVariablesError("table nesting limit exceeded")
195
- tokenizer.skip_ws()
196
- char = tokenizer.peek()
197
- if char == "{":
198
- return _parse_table(tokenizer, depth)
199
- if char == '"':
200
- return tokenizer.read_string()
201
- if char == "-" or char.isdigit():
202
- return tokenizer.read_number()
203
- name = tokenizer.read_name()
204
- if name == "true":
205
- return True
206
- if name == "false":
207
- return False
208
- if name == "nil":
209
- return NIL
210
- raise SavedVariablesError(
211
- f"unsupported value {name!r}; saved variables are data, not code")
212
-
213
-
214
- def _parse_table(tokenizer: _Tokenizer, depth: int) -> dict:
215
- tokenizer.expect("{")
216
- table: dict = {}
217
- array_index = 0
218
- tokenizer.skip_ws()
219
- if tokenizer.peek() == "}":
220
- tokenizer.pos += 1
221
- return table
222
- while True:
223
- tokenizer.count_entry()
224
- tokenizer.skip_ws()
225
- char = tokenizer.peek()
226
- if char == "}": # trailing separator before the closing brace
227
- tokenizer.pos += 1
228
- return table
229
- if char == "[":
230
- tokenizer.pos += 1
231
- key = _parse_value(tokenizer, depth + 1)
232
- tokenizer.expect("]")
233
- tokenizer.expect("=")
234
- value = _parse_value(tokenizer, depth + 1)
235
- if value is not NIL: # a nil value leaves the key absent in Lua
236
- table[key if isinstance(key, str) else f"#{key}"] = value
237
- else:
238
- first = _parse_value(tokenizer, depth + 1)
239
- tokenizer.skip_ws()
240
- if tokenizer.peek() == "=":
241
- tokenizer.pos += 1
242
- value = _parse_value(tokenizer, depth + 1)
243
- if value is not NIL:
244
- table[first if isinstance(first, str) else f"#{first}"] = value
245
- else:
246
- # Bare array entry: { "a", "b" }.
247
- array_index += 1
248
- table[f"#{array_index}"] = first
249
- tokenizer.skip_ws()
250
- char = tokenizer.peek()
251
- if char == "," or char == ";":
252
- tokenizer.pos += 1
253
- continue
254
- if char == "}":
255
- tokenizer.pos += 1
256
- return table
257
- raise SavedVariablesError(
258
- f"expected ',', ';' or '}}' at offset {tokenizer.pos}")
259
-
260
-
261
- def load_database(path: str) -> dict:
262
- """Read one SavedVariables file and return its LycheeDevDB table."""
263
-
264
- with open(path, "rb") as handle:
265
- raw = handle.read(MAX_FILE_BYTES + 1)
266
- if len(raw) > MAX_FILE_BYTES:
267
- raise SavedVariablesError("saved variables file exceeds the size limit")
268
- text = raw.decode("utf-8", errors="strict")
269
- document = parse_lua_assignments(text)
270
- database = document.get("LycheeDevDB")
271
- if not isinstance(database, dict):
272
- raise SavedVariablesError("LycheeDevDB table not found in the file")
273
- return database
274
-
275
-
276
- def get_record(database: dict, ticket: str) -> dict:
277
- """Exactly locate exports.records[TICKET]; no nearest-record fallback."""
278
-
279
- if not isinstance(ticket, str) or not TICKET_PATTERN.match(ticket):
280
- raise SavedVariablesError(f"invalid ticket format: {ticket!r}")
281
- exports = database.get("exports")
282
- records = exports.get("records") if isinstance(exports, dict) else None
283
- if not isinstance(records, dict):
284
- raise SavedVariablesError("exports.records table not found")
285
- record = records.get(ticket)
286
- if record is None:
287
- raise SavedVariablesError(f"ticket {ticket} not found in saved variables")
288
- if not isinstance(record, dict):
289
- raise SavedVariablesError(f"ticket {ticket} does not hold a record table")
290
- return record
291
-
292
-
293
- def verify_evidence(
294
- record: dict,
295
- *,
296
- ticket: str,
297
- created_at: int | None = None,
298
- task_id: str | None = None,
299
- execution_id: str | None = None,
300
- revision: str | None = None,
301
- ) -> list[str]:
302
- """Validate the evidence envelope and identity; returns failure reasons.
303
-
304
- Follows the design's verification order: envelope, payload media type,
305
- encoding, real UTF-8 byte count against ``byteCount``, metadata identity
306
- against the host's delivery log, then the Adler-32 content checksum. A
307
- missing field is a failure, never a silent pass.
308
- """
309
-
310
- failures: list[str] = []
311
- if record.get("schema") != EVIDENCE_SCHEMA:
312
- failures.append(f"schema mismatch: {record.get('schema')!r}")
313
- if record.get("ticket") != ticket:
314
- failures.append(f"envelope ticket mismatch: {record.get('ticket')!r}")
315
- if created_at is not None and record.get("createdAt") != created_at:
316
- failures.append(
317
- f"createdAt mismatch: {record.get('createdAt')!r} != {created_at!r}")
318
- payload = record.get("payload")
319
- if not isinstance(payload, dict) or not isinstance(payload.get("content"), str):
320
- failures.append("payload.content is missing or not a string")
321
- return failures
322
- if payload.get("mediaType") != MEDIA_TYPE:
323
- failures.append(f"unexpected payload mediaType: {payload.get('mediaType')!r}")
324
- if payload.get("encoding") != ENCODING:
325
- failures.append(f"unexpected payload encoding: {payload.get('encoding')!r}")
326
- content_bytes = payload["content"].encode("utf-8")
327
- byte_count = len(content_bytes)
328
- declared = payload.get("byteCount")
329
- if not isinstance(declared, int) or isinstance(declared, bool) or declared != byte_count:
330
- failures.append(f"byteCount mismatch: {declared!r} != {byte_count}")
331
- if byte_count > MAX_REPORT_BYTES:
332
- failures.append(
333
- f"payload content exceeds the {MAX_REPORT_BYTES} byte report limit: {byte_count}")
334
- metadata = record.get("metadata")
335
- if not isinstance(metadata, dict):
336
- failures.append("metadata is missing or not a table")
337
- metadata = {}
338
- if task_id is not None and metadata.get("taskId") != task_id:
339
- failures.append(
340
- f"metadata taskId mismatch: {metadata.get('taskId')!r} != {task_id!r}")
341
- if execution_id is not None and metadata.get("executionId") != execution_id:
342
- failures.append(
343
- f"metadata executionId mismatch: {metadata.get('executionId')!r} != {execution_id!r}")
344
- if revision is not None and metadata.get("revision") != revision:
345
- failures.append(
346
- f"metadata revision mismatch: {metadata.get('revision')!r} != {revision!r}")
347
- if metadata.get("resultSchema") != RESULT_SCHEMA:
348
- failures.append(f"unexpected resultSchema: {metadata.get('resultSchema')!r}")
349
- if metadata.get("status") not in TERMINAL_STATUSES:
350
- failures.append(f"unexpected metadata status: {metadata.get('status')!r}")
351
- if not isinstance(metadata.get("complete"), bool):
352
- failures.append(f"metadata complete is not a boolean: {metadata.get('complete')!r}")
353
- if metadata.get("checksumAlgorithm") != ADLER_ALGORITHM:
354
- failures.append(
355
- f"unsupported checksumAlgorithm: {metadata.get('checksumAlgorithm')!r}")
356
- checksum = metadata.get("contentChecksum")
357
- if not isinstance(checksum, str) or not ADLER_PATTERN.match(checksum):
358
- failures.append(f"contentChecksum is missing or malformed: {checksum!r}")
359
- else:
360
- actual = format(zlib.adler32(content_bytes) & 0xFFFFFFFF, "08x")
361
- if checksum != actual:
362
- failures.append(f"contentChecksum mismatch: {checksum} != {actual}")
363
- return failures
364
-
365
-
366
- def parse_inner_report(
367
- content: str,
368
- *,
369
- task_id: str | None = None,
370
- execution_id: str | None = None,
371
- revision: str | None = None,
372
- request_type: str | None = None,
373
- metadata: dict | None = None,
374
- ) -> dict:
375
- """Strictly parse and verify the inner automation report JSON.
376
-
377
- Design section 7.3 step 5 requires the report version, terminal status,
378
- ``complete`` flag, client/character environment and the request type and
379
- parameters to be verified, not just the schema. When ``metadata`` is given,
380
- the report identity must agree with the stored evidence metadata.
381
- """
382
-
383
- try:
384
- report = json.loads(content)
385
- except (ValueError, UnicodeDecodeError) as error:
386
- raise SavedVariablesError(f"inner report is not valid JSON: {error}") from error
387
- if not isinstance(report, dict):
388
- raise SavedVariablesError("inner report is not a JSON object")
389
- if report.get("schema") != RESULT_SCHEMA:
390
- raise SavedVariablesError(
391
- f"unexpected inner report schema: {report.get('schema')!r}")
392
- if report.get("status") not in TERMINAL_STATUSES:
393
- raise SavedVariablesError(
394
- f"inner report has a non-terminal status: {report.get('status')!r}")
395
- if not isinstance(report.get("complete"), bool):
396
- raise SavedVariablesError("inner report lacks a boolean complete flag")
397
- if report["complete"] is False and not isinstance(report.get("incompleteReasons"), list):
398
- raise SavedVariablesError(
399
- "incomplete inner report does not list incompleteReasons")
400
- report_type = report.get("requestType")
401
- if report_type not in REQUEST_TYPES:
402
- raise SavedVariablesError(
403
- f"inner report has an unknown requestType: {report_type!r}")
404
- environment = report.get("environment")
405
- if not isinstance(environment, dict) or not environment:
406
- raise SavedVariablesError("inner report lacks a client/character environment")
407
- params = report.get("params")
408
- if report_type == "bug":
409
- if not isinstance(params, dict):
410
- raise SavedVariablesError("bug report lacks its request params")
411
- if not isinstance(params.get("count"), int) or isinstance(params.get("count"), bool):
412
- raise SavedVariablesError("bug report params.count is not an integer")
413
- if not isinstance(params.get("scope"), str):
414
- raise SavedVariablesError("bug report params.scope is not a string")
415
- elif params is not None and not isinstance(params, dict):
416
- raise SavedVariablesError("inner report params are not a table")
417
-
418
- expected = {
419
- "taskId": task_id,
420
- "executionId": execution_id,
421
- "revision": revision,
422
- "requestType": request_type,
423
- }
424
- for key, value in expected.items():
425
- if value is not None and report.get(key) != value:
426
- raise SavedVariablesError(
427
- f"inner report {key} mismatch: {report.get(key)!r} != {value!r}")
428
- if metadata is not None:
429
- for key in ("taskId", "executionId", "revision", "status"):
430
- if key in metadata and metadata.get(key) != report.get(key):
431
- raise SavedVariablesError(
432
- f"inner report {key} disagrees with the evidence metadata: "
433
- f"{report.get(key)!r} != {metadata.get(key)!r}")
434
- if "complete" in metadata and bool(metadata.get("complete")) != report["complete"]:
435
- raise SavedVariablesError(
436
- "inner report complete flag disagrees with the evidence metadata")
437
- return report
438
-
1
+ """Restricted reader and verifier for Lychee Dev SavedVariables.
2
+
3
+ The SavedVariables file is data, never code: this module parses it with a
4
+ bounded recursive-descent parser that only accepts WoW's stored assignment
5
+ syntax (``Name = { ... }`` with ``["key"] = value`` pairs, strings, numbers and
6
+ booleans). It refuses and never evaluates functions, calls, operators or any
7
+ other expression, so a hostile or truncated file cannot execute anything.
8
+
9
+ Verification follows the design's fixed order: exact ticket lookup under
10
+ ``LycheeDevDB.exports.records``, envelope checks, metadata identity against the
11
+ host's delivery log, byte counts and the Adler-32 content checksum, then the
12
+ inner ``lychee.automation.result.v1`` JSON report.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import re
19
+ import zlib
20
+
21
+ EVIDENCE_SCHEMA = "lychee.evidence.v1"
22
+ RESULT_SCHEMA = "lychee.automation.result.v1"
23
+ ADLER_ALGORITHM = "adler32"
24
+ MEDIA_TYPE = "application/json"
25
+ ENCODING = "utf-8"
26
+ TICKET_PATTERN = re.compile(r"^LYCHEE-[A-Za-z0-9-]+$")
27
+
28
+ # The client emits an explicit ``nil`` for a declared-but-absent SavedVariables
29
+ # global (``DumperDB = nil``), and Lua tables can hold ``["key"] = nil``. Both
30
+ # mean "not there", so the parser returns this sentinel instead of a value.
31
+ NIL = object()
32
+
33
+ # Terminal states the Lua side may record (design section 8).
34
+ TERMINAL_STATUSES = ("succeeded", "failed", "cancelled", "interrupted")
35
+ REQUEST_TYPES = ("task", "bug")
36
+
37
+ # Parser limits: generous enough for a 16 MiB evidence budget with escaping
38
+ # overhead, strict enough to bound memory and reject runaway files.
39
+ MAX_FILE_BYTES = 256 * 1024 * 1024
40
+ MAX_DEPTH = 200
41
+ MAX_ENTRIES = 2_000_000
42
+ MAX_STRING_BYTES = 64 * 1024 * 1024
43
+ # A single automation report is capped at 1 MiB after serialization.
44
+ MAX_REPORT_BYTES = 1024 * 1024
45
+
46
+ STRING_ESCAPES = {'"': '"', "\\": "\\", "n": "\n", "r": "\r", "t": "\t",
47
+ "a": "\a", "b": "\b", "f": "\f", "v": "\v", "'": "'"}
48
+ DIGITS = "0123456789"
49
+ DECIMAL_ESCAPE = re.compile(r"[0-9]{1,3}")
50
+ ADLER_PATTERN = re.compile(r"^[0-9a-f]{8}$")
51
+
52
+
53
+ class SavedVariablesError(Exception):
54
+ """Raised for parse failures, identity conflicts and verification failures."""
55
+
56
+
57
+ class _Tokenizer:
58
+ def __init__(self, text: str):
59
+ self.text = text
60
+ self.pos = 0
61
+ self.length = len(text)
62
+ self.entries = 0
63
+
64
+ def skip_ws(self) -> None:
65
+ while self.pos < self.length and self.text[self.pos] in " \t\r\n":
66
+ self.pos += 1
67
+
68
+ def peek(self) -> str:
69
+ if self.pos >= self.length:
70
+ return ""
71
+ return self.text[self.pos]
72
+
73
+ def expect(self, char: str) -> None:
74
+ self.skip_ws()
75
+ if self.peek() != char:
76
+ raise SavedVariablesError(
77
+ f"expected {char!r} at offset {self.pos}, found {self.peek()!r}")
78
+ self.pos += 1
79
+
80
+ def read_name(self) -> str:
81
+ self.skip_ws()
82
+ match = re.match(r"[A-Za-z_][A-Za-z0-9_]*", self.text[self.pos:])
83
+ if not match:
84
+ raise SavedVariablesError(f"expected a name at offset {self.pos}")
85
+ self.pos += match.end()
86
+ return match.group(0)
87
+
88
+ def read_string(self) -> str:
89
+ """Read one quoted string, preserving its exact bytes.
90
+
91
+ WoW stores strings with Lua 5.1 escapes; ``\\ddd`` takes one to three
92
+ decimal digits (not exactly three), and multi-byte UTF-8 may arrive as
93
+ literal text or as consecutive ``\\ddd`` bytes. Bytes are accumulated and
94
+ only decoded at the end, so the original content survives untouched.
95
+ """
96
+
97
+ self.expect('"')
98
+ out = bytearray()
99
+ while True:
100
+ if self.pos >= self.length:
101
+ raise SavedVariablesError("unterminated string literal")
102
+ char = self.text[self.pos]
103
+ if char == '"':
104
+ self.pos += 1
105
+ try:
106
+ return out.decode("utf-8")
107
+ except UnicodeDecodeError as error:
108
+ raise SavedVariablesError(
109
+ f"string literal is not valid UTF-8: {error}") from error
110
+ if char == "\\":
111
+ self.pos += 1
112
+ if self.pos >= self.length:
113
+ raise SavedVariablesError("dangling escape in string literal")
114
+ escape = self.text[self.pos]
115
+ if escape in STRING_ESCAPES:
116
+ out.extend(STRING_ESCAPES[escape].encode("utf-8"))
117
+ self.pos += 1
118
+ elif escape in DIGITS:
119
+ match = DECIMAL_ESCAPE.match(self.text, self.pos)
120
+ digits = match.group(0)
121
+ value = int(digits)
122
+ if value > 255:
123
+ raise SavedVariablesError(
124
+ f"decimal escape too large: \\{digits}")
125
+ out.append(value)
126
+ self.pos += len(digits)
127
+ elif escape == "z":
128
+ # Lua 5.1 \z skips the following whitespace.
129
+ self.pos += 1
130
+ while self.pos < self.length and self.text[self.pos] in " \t\r\n":
131
+ self.pos += 1
132
+ else:
133
+ raise SavedVariablesError(f"unsupported escape: \\{escape}")
134
+ if len(out) > MAX_STRING_BYTES:
135
+ raise SavedVariablesError("string literal exceeds the size limit")
136
+ continue
137
+ if char == "\n" or char == "\r":
138
+ raise SavedVariablesError("raw newline inside a string literal")
139
+ if ord(char) > 0x7E:
140
+ # Literal non-ASCII text was decoded from UTF-8; put the same
141
+ # bytes back so byte counts stay exact.
142
+ out.extend(char.encode("utf-8"))
143
+ else:
144
+ out.append(ord(char))
145
+ self.pos += 1
146
+ if len(out) > MAX_STRING_BYTES:
147
+ raise SavedVariablesError("string literal exceeds the size limit")
148
+
149
+ def read_number(self) -> float | int:
150
+ self.skip_ws()
151
+ match = re.match(r"-?\d+\.\d+(?:[eE][+-]?\d+)?|-?\d+(?:[eE][+-]?\d+)?|-?\.\d+",
152
+ self.text[self.pos:])
153
+ if not match:
154
+ raise SavedVariablesError(f"expected a number at offset {self.pos}")
155
+ self.pos += match.end()
156
+ token = match.group(0)
157
+ if re.fullmatch(r"-?\d+", token):
158
+ return int(token)
159
+ return float(token)
160
+
161
+ def count_entry(self) -> None:
162
+ self.entries += 1
163
+ if self.entries > MAX_ENTRIES:
164
+ raise SavedVariablesError("entry limit exceeded while parsing")
165
+
166
+
167
+ def parse_lua_assignments(text: str) -> dict:
168
+ """Parse a SavedVariables document into {globalName: value}.
169
+
170
+ The client writes an explicit ``nil`` for a declared SavedVariables global
171
+ that does not exist in this session (for example ``DumperDB = nil``), so
172
+ ``nil`` is accepted as data and means "this global is absent".
173
+ """
174
+
175
+ if len(text.encode("utf-8", errors="replace")) > MAX_FILE_BYTES:
176
+ raise SavedVariablesError("saved variables file exceeds the size limit")
177
+ tokenizer = _Tokenizer(text)
178
+ document: dict = {}
179
+ tokenizer.skip_ws()
180
+ while tokenizer.pos < tokenizer.length:
181
+ name = tokenizer.read_name()
182
+ tokenizer.expect("=")
183
+ value = _parse_value(tokenizer, 0)
184
+ if value is NIL:
185
+ document.pop(name, None)
186
+ else:
187
+ document[name] = value
188
+ tokenizer.skip_ws()
189
+ return document
190
+
191
+
192
+ def _parse_value(tokenizer: _Tokenizer, depth: int):
193
+ if depth > MAX_DEPTH:
194
+ raise SavedVariablesError("table nesting limit exceeded")
195
+ tokenizer.skip_ws()
196
+ char = tokenizer.peek()
197
+ if char == "{":
198
+ return _parse_table(tokenizer, depth)
199
+ if char == '"':
200
+ return tokenizer.read_string()
201
+ if char == "-" or char.isdigit():
202
+ return tokenizer.read_number()
203
+ name = tokenizer.read_name()
204
+ if name == "true":
205
+ return True
206
+ if name == "false":
207
+ return False
208
+ if name == "nil":
209
+ return NIL
210
+ raise SavedVariablesError(
211
+ f"unsupported value {name!r}; saved variables are data, not code")
212
+
213
+
214
+ def _parse_table(tokenizer: _Tokenizer, depth: int) -> dict:
215
+ tokenizer.expect("{")
216
+ table: dict = {}
217
+ array_index = 0
218
+ tokenizer.skip_ws()
219
+ if tokenizer.peek() == "}":
220
+ tokenizer.pos += 1
221
+ return table
222
+ while True:
223
+ tokenizer.count_entry()
224
+ tokenizer.skip_ws()
225
+ char = tokenizer.peek()
226
+ if char == "}": # trailing separator before the closing brace
227
+ tokenizer.pos += 1
228
+ return table
229
+ if char == "[":
230
+ tokenizer.pos += 1
231
+ key = _parse_value(tokenizer, depth + 1)
232
+ tokenizer.expect("]")
233
+ tokenizer.expect("=")
234
+ value = _parse_value(tokenizer, depth + 1)
235
+ if value is not NIL: # a nil value leaves the key absent in Lua
236
+ table[key if isinstance(key, str) else f"#{key}"] = value
237
+ else:
238
+ first = _parse_value(tokenizer, depth + 1)
239
+ tokenizer.skip_ws()
240
+ if tokenizer.peek() == "=":
241
+ tokenizer.pos += 1
242
+ value = _parse_value(tokenizer, depth + 1)
243
+ if value is not NIL:
244
+ table[first if isinstance(first, str) else f"#{first}"] = value
245
+ else:
246
+ # Bare array entry: { "a", "b" }.
247
+ array_index += 1
248
+ table[f"#{array_index}"] = first
249
+ tokenizer.skip_ws()
250
+ char = tokenizer.peek()
251
+ if char == "," or char == ";":
252
+ tokenizer.pos += 1
253
+ continue
254
+ if char == "}":
255
+ tokenizer.pos += 1
256
+ return table
257
+ raise SavedVariablesError(
258
+ f"expected ',', ';' or '}}' at offset {tokenizer.pos}")
259
+
260
+
261
+ def load_database(path: str) -> dict:
262
+ """Read one SavedVariables file and return its LycheeDevDB table."""
263
+
264
+ with open(path, "rb") as handle:
265
+ raw = handle.read(MAX_FILE_BYTES + 1)
266
+ if len(raw) > MAX_FILE_BYTES:
267
+ raise SavedVariablesError("saved variables file exceeds the size limit")
268
+ text = raw.decode("utf-8", errors="strict")
269
+ document = parse_lua_assignments(text)
270
+ database = document.get("LycheeDevDB")
271
+ if not isinstance(database, dict):
272
+ raise SavedVariablesError("LycheeDevDB table not found in the file")
273
+ return database
274
+
275
+
276
+ def get_record(database: dict, ticket: str) -> dict:
277
+ """Exactly locate exports.records[TICKET]; no nearest-record fallback."""
278
+
279
+ if not isinstance(ticket, str) or not TICKET_PATTERN.match(ticket):
280
+ raise SavedVariablesError(f"invalid ticket format: {ticket!r}")
281
+ exports = database.get("exports")
282
+ records = exports.get("records") if isinstance(exports, dict) else None
283
+ if not isinstance(records, dict):
284
+ raise SavedVariablesError("exports.records table not found")
285
+ record = records.get(ticket)
286
+ if record is None:
287
+ raise SavedVariablesError(f"ticket {ticket} not found in saved variables")
288
+ if not isinstance(record, dict):
289
+ raise SavedVariablesError(f"ticket {ticket} does not hold a record table")
290
+ return record
291
+
292
+
293
+ def verify_evidence(
294
+ record: dict,
295
+ *,
296
+ ticket: str,
297
+ created_at: int | None = None,
298
+ task_id: str | None = None,
299
+ execution_id: str | None = None,
300
+ revision: str | None = None,
301
+ ) -> list[str]:
302
+ """Validate the evidence envelope and identity; returns failure reasons.
303
+
304
+ Follows the design's verification order: envelope, payload media type,
305
+ encoding, real UTF-8 byte count against ``byteCount``, metadata identity
306
+ against the host's delivery log, then the Adler-32 content checksum. A
307
+ missing field is a failure, never a silent pass.
308
+ """
309
+
310
+ failures: list[str] = []
311
+ if record.get("schema") != EVIDENCE_SCHEMA:
312
+ failures.append(f"schema mismatch: {record.get('schema')!r}")
313
+ if record.get("ticket") != ticket:
314
+ failures.append(f"envelope ticket mismatch: {record.get('ticket')!r}")
315
+ if created_at is not None and record.get("createdAt") != created_at:
316
+ failures.append(
317
+ f"createdAt mismatch: {record.get('createdAt')!r} != {created_at!r}")
318
+ payload = record.get("payload")
319
+ if not isinstance(payload, dict) or not isinstance(payload.get("content"), str):
320
+ failures.append("payload.content is missing or not a string")
321
+ return failures
322
+ if payload.get("mediaType") != MEDIA_TYPE:
323
+ failures.append(f"unexpected payload mediaType: {payload.get('mediaType')!r}")
324
+ if payload.get("encoding") != ENCODING:
325
+ failures.append(f"unexpected payload encoding: {payload.get('encoding')!r}")
326
+ content_bytes = payload["content"].encode("utf-8")
327
+ byte_count = len(content_bytes)
328
+ declared = payload.get("byteCount")
329
+ if not isinstance(declared, int) or isinstance(declared, bool) or declared != byte_count:
330
+ failures.append(f"byteCount mismatch: {declared!r} != {byte_count}")
331
+ if byte_count > MAX_REPORT_BYTES:
332
+ failures.append(
333
+ f"payload content exceeds the {MAX_REPORT_BYTES} byte report limit: {byte_count}")
334
+ metadata = record.get("metadata")
335
+ if not isinstance(metadata, dict):
336
+ failures.append("metadata is missing or not a table")
337
+ metadata = {}
338
+ if task_id is not None and metadata.get("taskId") != task_id:
339
+ failures.append(
340
+ f"metadata taskId mismatch: {metadata.get('taskId')!r} != {task_id!r}")
341
+ if execution_id is not None and metadata.get("executionId") != execution_id:
342
+ failures.append(
343
+ f"metadata executionId mismatch: {metadata.get('executionId')!r} != {execution_id!r}")
344
+ if revision is not None and metadata.get("revision") != revision:
345
+ failures.append(
346
+ f"metadata revision mismatch: {metadata.get('revision')!r} != {revision!r}")
347
+ if metadata.get("resultSchema") != RESULT_SCHEMA:
348
+ failures.append(f"unexpected resultSchema: {metadata.get('resultSchema')!r}")
349
+ if metadata.get("status") not in TERMINAL_STATUSES:
350
+ failures.append(f"unexpected metadata status: {metadata.get('status')!r}")
351
+ if not isinstance(metadata.get("complete"), bool):
352
+ failures.append(f"metadata complete is not a boolean: {metadata.get('complete')!r}")
353
+ if metadata.get("checksumAlgorithm") != ADLER_ALGORITHM:
354
+ failures.append(
355
+ f"unsupported checksumAlgorithm: {metadata.get('checksumAlgorithm')!r}")
356
+ checksum = metadata.get("contentChecksum")
357
+ if not isinstance(checksum, str) or not ADLER_PATTERN.match(checksum):
358
+ failures.append(f"contentChecksum is missing or malformed: {checksum!r}")
359
+ else:
360
+ actual = format(zlib.adler32(content_bytes) & 0xFFFFFFFF, "08x")
361
+ if checksum != actual:
362
+ failures.append(f"contentChecksum mismatch: {checksum} != {actual}")
363
+ return failures
364
+
365
+
366
+ def parse_inner_report(
367
+ content: str,
368
+ *,
369
+ task_id: str | None = None,
370
+ execution_id: str | None = None,
371
+ revision: str | None = None,
372
+ request_type: str | None = None,
373
+ metadata: dict | None = None,
374
+ ) -> dict:
375
+ """Strictly parse and verify the inner automation report JSON.
376
+
377
+ Design section 7.3 step 5 requires the report version, terminal status,
378
+ ``complete`` flag, client/character environment and the request type and
379
+ parameters to be verified, not just the schema. When ``metadata`` is given,
380
+ the report identity must agree with the stored evidence metadata.
381
+ """
382
+
383
+ try:
384
+ report = json.loads(content)
385
+ except (ValueError, UnicodeDecodeError) as error:
386
+ raise SavedVariablesError(f"inner report is not valid JSON: {error}") from error
387
+ if not isinstance(report, dict):
388
+ raise SavedVariablesError("inner report is not a JSON object")
389
+ if report.get("schema") != RESULT_SCHEMA:
390
+ raise SavedVariablesError(
391
+ f"unexpected inner report schema: {report.get('schema')!r}")
392
+ if report.get("status") not in TERMINAL_STATUSES:
393
+ raise SavedVariablesError(
394
+ f"inner report has a non-terminal status: {report.get('status')!r}")
395
+ if not isinstance(report.get("complete"), bool):
396
+ raise SavedVariablesError("inner report lacks a boolean complete flag")
397
+ if report["complete"] is False and not isinstance(report.get("incompleteReasons"), list):
398
+ raise SavedVariablesError(
399
+ "incomplete inner report does not list incompleteReasons")
400
+ report_type = report.get("requestType")
401
+ if report_type not in REQUEST_TYPES:
402
+ raise SavedVariablesError(
403
+ f"inner report has an unknown requestType: {report_type!r}")
404
+ environment = report.get("environment")
405
+ if not isinstance(environment, dict) or not environment:
406
+ raise SavedVariablesError("inner report lacks a client/character environment")
407
+ params = report.get("params")
408
+ if report_type == "bug":
409
+ if not isinstance(params, dict):
410
+ raise SavedVariablesError("bug report lacks its request params")
411
+ if not isinstance(params.get("count"), int) or isinstance(params.get("count"), bool):
412
+ raise SavedVariablesError("bug report params.count is not an integer")
413
+ if not isinstance(params.get("scope"), str):
414
+ raise SavedVariablesError("bug report params.scope is not a string")
415
+ elif params is not None and not isinstance(params, dict):
416
+ raise SavedVariablesError("inner report params are not a table")
417
+
418
+ expected = {
419
+ "taskId": task_id,
420
+ "executionId": execution_id,
421
+ "revision": revision,
422
+ "requestType": request_type,
423
+ }
424
+ for key, value in expected.items():
425
+ if value is not None and report.get(key) != value:
426
+ raise SavedVariablesError(
427
+ f"inner report {key} mismatch: {report.get(key)!r} != {value!r}")
428
+ if metadata is not None:
429
+ for key in ("taskId", "executionId", "revision", "status"):
430
+ if key in metadata and metadata.get(key) != report.get(key):
431
+ raise SavedVariablesError(
432
+ f"inner report {key} disagrees with the evidence metadata: "
433
+ f"{report.get(key)!r} != {metadata.get(key)!r}")
434
+ if "complete" in metadata and bool(metadata.get("complete")) != report["complete"]:
435
+ raise SavedVariablesError(
436
+ "inner report complete flag disagrees with the evidence metadata")
437
+ return report
438
+