lycheedev 1.2.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/LICENSE +49 -0
  2. package/README.md +45 -0
  3. package/THIRD_PARTY_NOTICES +812 -0
  4. package/bin/lycheedev.mjs +56 -0
  5. package/native/windows-amd64/lycheedev.exe +0 -0
  6. package/package.json +12 -33
  7. package/payload/addon/Bridge/CaptureWriter.lua +154 -0
  8. package/payload/addon/Bridge/Definitions.lua +3 -0
  9. package/payload/addon/Bridge/Identity.lua +127 -0
  10. package/{vendor/addon/Libs/AutomationQR.lua → payload/addon/Bridge/MatrixSymbol.lua} +23 -30
  11. package/payload/addon/Bridge/ProbeQueue.lua +136 -0
  12. package/payload/addon/Bridge/ProbeRunner.lua +128 -0
  13. package/payload/addon/Bridge/ReceiptView.lua +160 -0
  14. package/payload/addon/Bridge/Reentry.lua +192 -0
  15. package/payload/addon/Bridge/ReportStore.lua +153 -0
  16. package/payload/addon/Bridge/Session.lua +163 -0
  17. package/payload/addon/Clients/Evergreen.lua +2 -0
  18. package/payload/addon/Clients/Live.lua +2 -0
  19. package/payload/addon/Clients/Pandaria.lua +2 -0
  20. package/payload/addon/Clients/Titan.lua +2 -0
  21. package/payload/addon/Core/Compat.lua +59 -0
  22. package/payload/addon/Core/Controls.lua +168 -0
  23. package/{vendor/addon/Core/Bootstrap.lua → payload/addon/Core/Execute.lua} +12 -23
  24. package/{vendor → payload}/addon/Core/Inspector.lua +19 -235
  25. package/{vendor → payload}/addon/Core/Locale.lua +128 -93
  26. package/{vendor → payload}/addon/Core/Locale_enUS.lua +128 -95
  27. package/payload/addon/Core/Persistence.lua +58 -0
  28. package/payload/addon/Core/Platform.lua +58 -0
  29. package/payload/addon/Core/Runtime.lua +25 -0
  30. package/payload/addon/Core/Safety.lua +56 -0
  31. package/{vendor → payload}/addon/Core/Serializer.lua +18 -6
  32. package/payload/addon/Core/Stores.lua +611 -0
  33. package/payload/addon/Lychee Dev_Forever.toc +52 -0
  34. package/payload/addon/Lychee Dev_Mainline.toc +52 -0
  35. package/payload/addon/Lychee Dev_Mists.toc +52 -0
  36. package/payload/addon/Lychee Dev_Wrath.toc +52 -0
  37. package/payload/addon/Modules/AutomationView.lua +393 -0
  38. package/{vendor → payload}/addon/Modules/Diagnostics.lua +92 -36
  39. package/{vendor → payload}/addon/Modules/Events/Catalog.lua +9 -0
  40. package/{vendor → payload}/addon/Modules/Events/Monitor.lua +45 -5
  41. package/payload/addon/Modules/FunctionTrace.lua +150 -0
  42. package/{vendor → payload}/addon/Modules/ObjectInspector.lua +105 -31
  43. package/{vendor → payload}/addon/UI/Export.lua +64 -34
  44. package/{vendor → payload}/addon/UI/Pages/About.lua +26 -14
  45. package/payload/addon/UI/Pages/Automation.lua +446 -0
  46. package/payload/addon/UI/Pages/Diagnostics.lua +402 -0
  47. package/{vendor/addon/UI/Features.lua → payload/addon/UI/Pages/Events.lua} +192 -302
  48. package/{vendor → payload}/addon/UI/Pages/ExportRecords.lua +213 -132
  49. package/{vendor → payload}/addon/UI/Pages/Object.lua +229 -121
  50. package/payload/addon/UI/Pages/Run.lua +423 -0
  51. package/payload/addon/UI/Pages/Trace.lua +314 -0
  52. package/payload/addon/UI/TreeView.lua +246 -0
  53. package/{vendor/addon/UI/MainWindow.lua → payload/addon/UI/Widgets.lua} +89 -529
  54. package/payload/addon/UI/Window.lua +425 -0
  55. package/payload/skill/SKILL.md +87 -0
  56. package/payload/skill/agents/openai.yaml +7 -0
  57. package/payload/skill/references/addon-validation.md +42 -0
  58. package/payload/skill/references/asset-export.md +109 -0
  59. package/payload/skill/references/commands.md +169 -0
  60. package/payload/skill/references/data-investigation.md +242 -0
  61. package/payload/skill/references/error-diagnosis.md +41 -0
  62. package/payload/skill/references/installation.md +18 -0
  63. package/payload/skill/references/live-investigation.md +129 -0
  64. package/payload/skill/references/source-research.md +82 -0
  65. package/payload/skill/scripts/lycheedev.mjs +59 -0
  66. package/release.json +346 -0
  67. package/bin/lycheedev.js +0 -746
  68. package/src/addon.js +0 -95
  69. package/src/config.js +0 -68
  70. package/src/doctor.js +0 -126
  71. package/src/install.js +0 -145
  72. package/src/paths.js +0 -93
  73. package/src/py/instances.py +0 -165
  74. package/src/python.js +0 -111
  75. package/src/skill.js +0 -48
  76. package/src/wow.js +0 -541
  77. package/vendor/addon/Core/Clients/Forever.lua +0 -9
  78. package/vendor/addon/Core/Clients/Mainline.lua +0 -9
  79. package/vendor/addon/Core/Clients/Mists.lua +0 -9
  80. package/vendor/addon/Core/Clients/Titan.lua +0 -9
  81. package/vendor/addon/Core/Compatibility.lua +0 -43
  82. package/vendor/addon/Core/Database.lua +0 -859
  83. package/vendor/addon/Core/Safety.lua +0 -42
  84. package/vendor/addon/Lychee Dev_Forever.toc +0 -44
  85. package/vendor/addon/Lychee Dev_Mainline.toc +0 -44
  86. package/vendor/addon/Lychee Dev_Mists.toc +0 -44
  87. package/vendor/addon/Lychee Dev_Wrath.toc +0 -44
  88. package/vendor/addon/Modules/Automation/Controller.lua +0 -896
  89. package/vendor/addon/Modules/Automation/Reload.lua +0 -101
  90. package/vendor/addon/Modules/Automation/Report.lua +0 -409
  91. package/vendor/addon/Modules/Automation/auto/auto.lua +0 -12
  92. package/vendor/addon/Modules/FunctionTrace.lua +0 -85
  93. package/vendor/addon/UI/AutomationOverlay.lua +0 -253
  94. package/vendor/addon/UI/Pages/Automation.lua +0 -417
  95. package/vendor/addon/UI/Pages/Diagnostics.lua +0 -289
  96. package/vendor/addon/UI/Pages/Trace.lua +0 -165
  97. package/vendor/skill/SKILL.md +0 -44
  98. package/vendor/skill/agents/openai.yaml +0 -4
  99. package/vendor/skill/references/automation.md +0 -130
  100. package/vendor/skill/references/clients.md +0 -51
  101. package/vendor/skill/references/runtime-investigations.md +0 -104
  102. package/vendor/skill/scripts/automation/__init__.py +0 -1
  103. package/vendor/skill/scripts/automation/registry.py +0 -516
  104. package/vendor/skill/scripts/automation/reload.py +0 -121
  105. package/vendor/skill/scripts/automation/saved_variables.py +0 -438
  106. package/vendor/skill/scripts/automation/session.py +0 -207
  107. package/vendor/skill/scripts/automation/windows.py +0 -792
  108. package/vendor/skill/scripts/automation.py +0 -1067
  109. package/vendor/skill/scripts/requirements.txt +0 -13
  110. package/vendor/skill/scripts/selftest_offline.py +0 -1061
  111. package/vendor/skill/scripts/test_input_safety.py +0 -132
  112. package/vendor/skill/scripts/test_reload.py +0 -120
  113. /package/{vendor → payload}/addon/Media/GitHub.png +0 -0
  114. /package/{vendor → payload}/addon/Media/Logo.png +0 -0
  115. /package/{vendor → payload}/addon/Modules/Events/CatalogData_Forever.lua +0 -0
  116. /package/{vendor → payload}/addon/Modules/Events/CatalogData_Mainline.lua +0 -0
  117. /package/{vendor → payload}/addon/Modules/Events/CatalogData_Mists.lua +0 -0
  118. /package/{vendor → payload}/addon/Modules/Events/CatalogData_Titan.lua +0 -0
@@ -1,438 +0,0 @@
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,207 +0,0 @@
1
- """Host-side session state for the Lychee Dev automation loop.
2
-
3
- Everything the host must remember across script restarts lives here: the
4
- append-only host log, the ``(installation, requestId, ticket)`` reload dedup
5
- key, bounded waits for the game to write its SavedVariables file, and the
6
- per-ticket artifact directory. The host log and artifacts live under a local
7
- data directory and never inside the versioned skill sources or the addon ZIP.
8
-
9
- Every record carries its installation scope, and reads default to that scope so
10
- ``status``/``recover`` cannot mix two WoW installations or multi-account runs.
11
- Artifacts are written byte-for-byte: the recorded byte count and SHA-256 must
12
- describe the exact bytes on disk (no newline translation).
13
- """
14
-
15
- from __future__ import annotations
16
-
17
- import json
18
- import os
19
- import tempfile
20
- import time
21
- from dataclasses import dataclass, field
22
-
23
- ALL_INSTALLATIONS = "*"
24
-
25
-
26
- def default_data_dir() -> str:
27
- base = os.environ.get("LOCALAPPDATA") or os.path.expanduser("~")
28
- return os.path.join(base, "LycheeDev", "automation")
29
-
30
-
31
- @dataclass
32
- class Session:
33
- data_dir: str = field(default_factory=default_data_dir)
34
- installation: str = "default"
35
-
36
- def __post_init__(self) -> None:
37
- os.makedirs(self.data_dir, exist_ok=True)
38
- os.makedirs(self.received_dir, exist_ok=True)
39
-
40
- @property
41
- def log_path(self) -> str:
42
- return os.path.join(self.data_dir, "session.log.jsonl")
43
-
44
- @property
45
- def received_dir(self) -> str:
46
- return os.path.join(self.data_dir, "received")
47
-
48
- # --- host log ---------------------------------------------------------
49
-
50
- def log_event(self, event: str, **fields) -> None:
51
- record = {
52
- "ts": int(time.time()),
53
- "installation": self.installation,
54
- "event": event,
55
- }
56
- record.update(fields)
57
- line = json.dumps(record, ensure_ascii=False, sort_keys=True) + "\n"
58
- with open(self.log_path, "a", encoding="utf-8", newline="\n") as handle:
59
- handle.write(line)
60
-
61
- def read_events(self, event: str | None = None, *,
62
- installation: str | None = None) -> list[dict]:
63
- """Read host log records, scoped to one installation by default.
64
-
65
- ``installation`` defaults to this session's scope; pass
66
- ``ALL_INSTALLATIONS`` to read every scope, or another name to inspect a
67
- different one. A torn tail line is skipped, never fatal.
68
- """
69
-
70
- scope = self.installation if installation is None else installation
71
- if not os.path.exists(self.log_path):
72
- return []
73
- matches = []
74
- with open(self.log_path, "r", encoding="utf-8") as handle:
75
- for line in handle:
76
- line = line.strip()
77
- if not line:
78
- continue
79
- try:
80
- record = json.loads(line)
81
- except ValueError:
82
- continue # a torn tail line must not break recovery
83
- if not isinstance(record, dict):
84
- continue
85
- if event is not None and record.get("event") != event:
86
- continue
87
- if scope != ALL_INSTALLATIONS and record.get("installation") != scope:
88
- continue
89
- matches.append(record)
90
- return matches
91
-
92
- # --- reload dedup -----------------------------------------------------
93
-
94
- def reload_already_requested(self, request_id: str, ticket: str) -> bool:
95
- key = (self.installation, request_id, ticket)
96
- for record in self.read_events("reload_requested"):
97
- candidate = (record.get("installation"), record.get("requestId"),
98
- record.get("ticket"))
99
- if candidate == key:
100
- return True
101
- return False
102
-
103
- def mark_reload_requested(self, request_id: str, ticket: str, **fields) -> bool:
104
- """Persist the intent before sending /reload; returns False when the
105
- same static notice was already acted on (one notice, one reload)."""
106
-
107
- if self.reload_already_requested(request_id, ticket):
108
- return False
109
- self.log_event("reload_requested", requestId=request_id, ticket=ticket, **fields)
110
- return True
111
-
112
- # --- artifacts --------------------------------------------------------
113
-
114
- def artifact_dir(self, ticket: str) -> str:
115
- path = os.path.join(self.received_dir, ticket)
116
- os.makedirs(path, exist_ok=True)
117
- return path
118
-
119
- def save_artifact(self, ticket: str, name: str, content: str | bytes) -> str:
120
- """Write one artifact byte-for-byte, with no newline translation.
121
-
122
- The on-disk bytes are exactly ``content`` encoded as UTF-8 (or the
123
- bytes passed in), so a recorded byteCount/SHA-256 always matches.
124
- """
125
-
126
- data = content.encode("utf-8") if isinstance(content, str) else bytes(content)
127
- path = os.path.join(self.artifact_dir(ticket), name)
128
- with open(path, "wb") as handle:
129
- handle.write(data)
130
- return path
131
-
132
- # --- JSON state files -------------------------------------------------
133
-
134
- def state_path(self, name: str) -> str:
135
- return os.path.join(self.data_dir, name)
136
-
137
- def load_json(self, name: str):
138
- path = self.state_path(name)
139
- if not os.path.exists(path):
140
- return {}
141
- with open(path, "r", encoding="utf-8") as handle:
142
- return json.load(handle)
143
-
144
- def save_json(self, name: str, payload) -> str:
145
- """Atomically replace one JSON state file inside the data directory."""
146
-
147
- path = self.state_path(name)
148
- text = json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
149
- directory = os.path.dirname(path) or "."
150
- os.makedirs(directory, exist_ok=True)
151
- handle = tempfile.NamedTemporaryFile(
152
- "wb", dir=directory, delete=False, prefix=".state-", suffix=".tmp")
153
- try:
154
- with handle:
155
- handle.write(text.encode("utf-8"))
156
- handle.flush()
157
- os.fsync(handle.fileno())
158
- os.replace(handle.name, path)
159
- except BaseException:
160
- try:
161
- os.unlink(handle.name)
162
- except OSError:
163
- pass
164
- raise
165
- return path
166
-
167
- # --- waiting for the disk write ---------------------------------------
168
-
169
- def wait_for_saved_variables(
170
- self,
171
- sv_path: str,
172
- *,
173
- timeout: float = 120.0,
174
- poll_interval: float = 0.25,
175
- baseline: tuple[int, int, float] | None = None,
176
- ) -> bool:
177
- """Wait until the file's identity/size/mtime moves from the baseline.
178
-
179
- The change is only a wake-up hint, never proof of completion: callers
180
- must still verify the expected ticket inside the parsed file.
181
- """
182
-
183
- def snapshot() -> tuple[int, int, float]:
184
- info = os.stat(sv_path)
185
- return (info.st_dev, info.st_size, info.st_mtime)
186
-
187
- if baseline is None:
188
- try:
189
- baseline = snapshot()
190
- except OSError:
191
- baseline = (0, 0, 0.0)
192
- deadline = time.monotonic() + timeout
193
- while time.monotonic() < deadline:
194
- try:
195
- if snapshot() != baseline:
196
- return True
197
- except OSError:
198
- pass # replaced mid-write; keep polling until the deadline
199
- time.sleep(poll_interval)
200
- return False
201
-
202
- def file_snapshot(self, sv_path: str) -> tuple[int, int, float]:
203
- try:
204
- info = os.stat(sv_path)
205
- return (info.st_dev, info.st_size, info.st_mtime)
206
- except OSError:
207
- return (0, 0, 0.0)