lycheedev 1.2.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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,1061 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """Offline self test for the Lychee Dev automation host tooling.
3
-
4
- Covers the registry writer, the restricted SavedVariables reader, the session
5
- log/dedup, artifact byte fidelity, notice validation/identity, the bounded read
6
- retry and the CLI exit behaviour. The real packages (windows-capture,
7
- zxing-cpp) are checked only when they are importable; everything else runs with
8
- no third-party dependency.
9
- """
10
-
11
- import argparse
12
- import contextlib
13
- import ctypes
14
- import hashlib
15
- import importlib.util
16
- import io
17
- import json
18
- import os
19
- import shutil
20
- import sys
21
- import tempfile
22
- import time
23
- import zlib
24
-
25
- sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
26
- from automation import registry as reg # noqa: E402
27
- from automation import saved_variables as sv # noqa: E402
28
- from automation import session as ses # noqa: E402
29
-
30
- HERE = os.path.dirname(os.path.abspath(__file__))
31
- SKILL_ROOT = os.path.dirname(HERE)
32
- WORKTREE = os.path.dirname(SKILL_ROOT)
33
-
34
- BS = chr(92)
35
-
36
-
37
- def _load_cli():
38
- """Load automation.py under its own name (a package shares the name)."""
39
-
40
- path = os.path.join(HERE, "automation.py")
41
- spec = importlib.util.spec_from_file_location("lychee_automation_cli", path)
42
- module = importlib.util.module_from_spec(spec)
43
- sys.modules[spec.name] = module
44
- spec.loader.exec_module(module)
45
- return module
46
-
47
-
48
- cli = _load_cli()
49
-
50
-
51
- def expect_failure(label, callback, errors):
52
- try:
53
- callback()
54
- except errors:
55
- return
56
- raise SystemExit("expected failure was not raised: " + label)
57
-
58
-
59
- report = {
60
- "schema": "lychee.automation.result.v1",
61
- "taskId": "inspect-example",
62
- "executionId": "req-20260912-000001-aaaaaa",
63
- "revision": "rev-1",
64
- "kind": "lua",
65
- "status": "succeeded",
66
- "startedAt": 1789207190,
67
- "finishedAt": 1789207200,
68
- "requestType": "task",
69
- "stdout": "line1\nline2\ttab \"quoted\" back" + BS + "slash unicode caf\u00e9 control \u0001",
70
- "returns": [{"ok": True, "nested": [1, 2.5, None]}],
71
- "error": None,
72
- "lifecycleLog": [],
73
- "lifecycleLogLimited": False,
74
- "bugSnapshot": None,
75
- "environment": {"clientId": "retail", "character": "Follen", "realm": "TestRealm"},
76
- "complete": True,
77
- "incompleteReasons": [],
78
- }
79
- content = json.dumps(report, ensure_ascii=False, separators=(",", ":"))
80
- checksum = format(zlib.adler32(content.encode("utf-8")) & 0xFFFFFFFF, "08x")
81
-
82
-
83
- def lua_q(s):
84
- out = ['"']
85
- for ch in s:
86
- if ch == '"':
87
- out.append(BS + '"')
88
- elif ch == BS:
89
- out.append(BS + BS)
90
- elif ch == "\n":
91
- out.append(BS + "n")
92
- elif ch == "\r":
93
- out.append(BS + "r")
94
- elif ch == "\t":
95
- out.append(BS + "t")
96
- elif ord(ch) < 32:
97
- out.append(BS + "%03d" % ord(ch))
98
- else:
99
- out.append(ch)
100
- out.append('"')
101
- return "".join(out)
102
-
103
-
104
- ticket = "LYCHEE-20260912-180000-0001"
105
- content_bytes = content.encode("utf-8")
106
- sv_text = (
107
- "LycheeDevDB = {\n"
108
- '\t["schemaVersion"] = 8,\n'
109
- '\t["history"] = {\n\t},\n'
110
- '\t["exports"] = {\n'
111
- '\t\t["version"] = 2,\n'
112
- '\t\t["nextId"] = 1,\n'
113
- "\t\t[\"totalBytes\"] = %d,\n"
114
- '\t\t["order"] = {\n\t\t\t"%s",\n\t\t},\n'
115
- '\t\t["records"] = {\n'
116
- '\t\t\t["%s"] = {\n'
117
- '\t\t\t\t["schema"] = "lychee.evidence.v1",\n'
118
- '\t\t\t\t["ticket"] = "%s",\n'
119
- "\t\t\t\t[\"createdAt\"] = 1789207200,\n"
120
- '\t\t\t\t["source"] = {\n\t\t\t\t\t["kind"] = "automation_result",\n\t\t\t\t\t["title"] = "inspect-example",\n\t\t\t\t},\n'
121
- '\t\t\t\t["payload"] = {\n'
122
- '\t\t\t\t\t["mediaType"] = "application/json",\n'
123
- '\t\t\t\t\t["encoding"] = "utf-8",\n'
124
- '\t\t\t\t\t["content"] = %s,\n'
125
- "\t\t\t\t\t[\"byteCount\"] = %d,\n"
126
- "\t\t\t\t},\n"
127
- '\t\t\t\t["metadata"] = {\n'
128
- '\t\t\t\t\t["taskId"] = "inspect-example",\n'
129
- '\t\t\t\t\t["executionId"] = "req-20260912-000001-aaaaaa",\n'
130
- '\t\t\t\t\t["revision"] = "rev-1",\n'
131
- '\t\t\t\t\t["resultSchema"] = "lychee.automation.result.v1",\n'
132
- '\t\t\t\t\t["status"] = "succeeded",\n'
133
- '\t\t\t\t\t["complete"] = true,\n'
134
- '\t\t\t\t\t["checksumAlgorithm"] = "adler32",\n'
135
- '\t\t\t\t\t["contentChecksum"] = "%s",\n'
136
- "\t\t\t\t},\n"
137
- "\t\t\t},\n"
138
- "\t\t},\n"
139
- "\t},\n"
140
- '\t["automation"] = {\n\t\t["version"] = 1,\n\t},\n'
141
- "}\n"
142
- ) % (len(content_bytes), ticket, ticket, ticket, lua_q(content),
143
- len(content_bytes), checksum)
144
-
145
- tmp = tempfile.mkdtemp()
146
- # The harness reuses one scratch directory per case, so drop stale state first.
147
- shutil.rmtree(tmp, ignore_errors=True)
148
- os.makedirs(tmp, exist_ok=True)
149
- path = os.path.join(tmp, "Lychee Dev.lua")
150
- with open(path, "wb") as f:
151
- f.write(sv_text.encode("utf-8"))
152
-
153
- db = sv.load_database(path)
154
- assert db["schemaVersion"] == 8
155
- record = sv.get_record(db, ticket)
156
- failures = sv.verify_evidence(
157
- record, ticket=ticket, created_at=1789207200, task_id="inspect-example",
158
- execution_id="req-20260912-000001-aaaaaa", revision="rev-1")
159
- assert failures == [], failures
160
- inner = sv.parse_inner_report(record["payload"]["content"])
161
- assert inner["status"] == "succeeded" and inner["complete"] is True
162
- assert inner["stdout"].startswith("line1\nline2\t")
163
- assert inner["returns"][0]["nested"] == [1, 2.5, None]
164
-
165
- for kwargs in ({"task_id": "other"}, {"execution_id": "wrong"},
166
- {"revision": "wrong"}, {"created_at": 1}):
167
- assert sv.verify_evidence(record, ticket=ticket, **kwargs), kwargs
168
-
169
- corrupt = dict(record)
170
- corrupt["payload"] = dict(record["payload"])
171
- corrupt["payload"]["content"] = record["payload"]["content"][:-1]
172
- assert sv.verify_evidence(corrupt, ticket=ticket), "checksum mismatch not detected"
173
-
174
- try:
175
- sv.get_record(db, "LYCHEE-DOES-NOT-EXIST")
176
- raise SystemExit("missing ticket not rejected")
177
- except sv.SavedVariablesError:
178
- pass
179
- try:
180
- sv.parse_lua_assignments("x = (function() end)")
181
- raise SystemExit("expression accepted")
182
- except sv.SavedVariablesError:
183
- pass
184
- try:
185
- sv.parse_lua_assignments('x = os.execute("evil")')
186
- raise SystemExit("call accepted")
187
- except sv.SavedVariablesError:
188
- pass
189
- try:
190
- sv.parse_lua_assignments('x = "unterminated')
191
- raise SystemExit("unterminated string accepted")
192
- except sv.SavedVariablesError:
193
- pass
194
- try:
195
- sv.parse_lua_assignments('x = "bad ' + BS + 'q escape"')
196
- raise SystemExit("bad escape accepted")
197
- except sv.SavedVariablesError:
198
- pass
199
-
200
- print("saved_variables base reader OK")
201
-
202
- # --- real client output: explicit nil for an absent global --------------------
203
- #
204
- # The client writes `DumperDB = nil` for a declared SavedVariables global that
205
- # does not exist, and a Lua table can carry `["key"] = nil`. Both mean absent.
206
-
207
- nil_doc = sv.parse_lua_assignments(
208
- 'LycheeDevDB = { ["a"] = 1, ["b"] = nil }\nDumperDB = nil\n')
209
- assert nil_doc == {"LycheeDevDB": {"a": 1}}, nil_doc
210
-
211
- # The exact trailer shape a real client file ends with.
212
- real_tail = 'LycheeDevDB = { ["schemaVersion"] = 8 }\nDumperDB = nil\n'
213
- assert sv.parse_lua_assignments(real_tail) == {"LycheeDevDB": {"schemaVersion": 8}}
214
-
215
- # nil must not weaken the data-only rule.
216
- try:
217
- sv.parse_lua_assignments('x = os.execute("evil")')
218
- raise SystemExit("call accepted after nil support")
219
- except sv.SavedVariablesError:
220
- pass
221
- print("client nil assignments (global and table key) OK")
222
-
223
- # --- Lua \ddd escapes take one to three digits --------------------------------
224
-
225
- assert sv.parse_lua_assignments('x = "' + BS + '12x"')["x"] == chr(12) + "x"
226
- assert sv.parse_lua_assignments('x = "' + BS + '65bc"')["x"] == "Abc"
227
- assert sv.parse_lua_assignments('x = "' + BS + '065"')["x"] == "A"
228
- assert sv.parse_lua_assignments('x = "' + BS + '0"')["x"] == chr(0)
229
- assert sv.parse_lua_assignments('x = "' + BS + '9"')["x"] == chr(9)
230
- assert sv.parse_lua_assignments('x = "' + BS + 'z \n\t y"')["x"] == "y"
231
- utf8_text = "\u00e9\u4e2d"
232
- utf8_escaped = "".join(BS + "%03d" % byte for byte in utf8_text.encode("utf-8"))
233
- assert sv.parse_lua_assignments('x = "' + utf8_escaped + '"')["x"] == utf8_text
234
- for bad_escape in (BS + "256", BS + "999", BS + "300"):
235
- expect_failure("decimal escape " + bad_escape,
236
- lambda bad=bad_escape: sv.parse_lua_assignments('x = "' + bad + '"'),
237
- sv.SavedVariablesError)
238
- assert reg.unescape_lua_string('"' + BS + '12x"') == chr(12) + "x"
239
- assert reg.unescape_lua_string('"' + BS + '65bc"') == "Abc"
240
- print("lua decimal escapes (1-3 digits, <=255) OK")
241
-
242
- # --- payload / metadata validation is no longer optional ----------------------
243
-
244
- def _mutated(mutate):
245
- copy = json.loads(json.dumps(record))
246
- mutate(copy)
247
- return copy
248
-
249
-
250
- def _fails(mutate, needle):
251
- reasons = sv.verify_evidence(_mutated(mutate), ticket=ticket)
252
- assert reasons, "mutation was accepted: " + needle
253
- assert any(needle in reason for reason in reasons), (needle, reasons)
254
-
255
-
256
- def _drop(field):
257
- def mutate(copy):
258
- copy["payload"].pop(field, None)
259
- return mutate
260
-
261
-
262
- def _drop_meta(field):
263
- def mutate(copy):
264
- copy["metadata"].pop(field, None)
265
- return mutate
266
-
267
-
268
- _fails(_drop("mediaType"), "mediaType")
269
- _fails(lambda copy: copy["payload"].__setitem__("mediaType", "text/plain"), "mediaType")
270
- _fails(_drop("encoding"), "encoding")
271
- _fails(lambda copy: copy["payload"].__setitem__("encoding", "utf-16"), "encoding")
272
- _fails(_drop("byteCount"), "byteCount")
273
- _fails(lambda copy: copy["payload"].__setitem__("byteCount", 1), "byteCount")
274
- _fails(_drop_meta("checksumAlgorithm"), "checksumAlgorithm")
275
- _fails(lambda copy: copy["metadata"].__setitem__("checksumAlgorithm", "sha256"),
276
- "checksumAlgorithm")
277
- _fails(_drop_meta("contentChecksum"), "contentChecksum")
278
- _fails(lambda copy: copy["metadata"].__setitem__("contentChecksum", "zzzz"), "contentChecksum")
279
- _fails(_drop_meta("resultSchema"), "resultSchema")
280
- _fails(_drop_meta("status"), "status")
281
- _fails(lambda copy: copy["metadata"].__setitem__("status", "running"), "status")
282
- _fails(_drop_meta("complete"), "complete")
283
- _fails(lambda copy: copy["metadata"].__setitem__("complete", "yes"), "complete")
284
-
285
-
286
- def _oversize(copy):
287
- big = "a" * (sv.MAX_REPORT_BYTES + 1)
288
- copy["payload"]["content"] = big
289
- copy["payload"]["byteCount"] = len(big.encode("utf-8"))
290
- copy["metadata"]["contentChecksum"] = format(
291
- zlib.adler32(big.encode("utf-8")) & 0xFFFFFFFF, "08x")
292
-
293
-
294
- _fails(_oversize, "report limit")
295
- print("payload mediaType/encoding/byteCount/checksum/limit checks OK")
296
- print("metadata resultSchema/status/complete/checksumAlgorithm checks OK")
297
-
298
- # --- inner report checks -------------------------------------------------------
299
-
300
- def _inner_fails(mutate, needle, base=None, **kwargs):
301
- body = json.loads(json.dumps(report if base is None else base))
302
- mutate(body)
303
- try:
304
- sv.parse_inner_report(json.dumps(body), **kwargs)
305
- except sv.SavedVariablesError as error:
306
- assert needle in str(error), (needle, str(error))
307
- return
308
- raise SystemExit("inner report mutation was accepted: " + needle)
309
-
310
-
311
- _inner_fails(lambda body: body.__setitem__("schema", "other"), "schema")
312
- _inner_fails(lambda body: body.__setitem__("status", "running"), "status")
313
- _inner_fails(lambda body: body.__setitem__("complete", "yes"), "complete")
314
- _inner_fails(lambda body: body.__setitem__("environment", None), "environment")
315
- _inner_fails(lambda body: body.pop("requestType"), "requestType")
316
- _inner_fails(lambda body: body.__setitem__("requestType", "other"), "requestType")
317
-
318
-
319
- def _mark_incomplete(body):
320
- body["complete"] = False
321
- body["incompleteReasons"] = None
322
-
323
-
324
- _inner_fails(_mark_incomplete, "incompleteReasons")
325
- _inner_fails(lambda body: body.__setitem__("taskId", "other"), "taskId",
326
- task_id="inspect-example")
327
-
328
- bug_body = json.loads(json.dumps(report))
329
- bug_body["requestType"] = "bug"
330
- bug_body["params"] = {"count": 3, "scope": "provider_storage"}
331
- sv.parse_inner_report(json.dumps(bug_body), request_type="bug")
332
- _inner_fails(lambda body: body.__setitem__("params", None), "params",
333
- base=bug_body, request_type="bug")
334
- _inner_fails(lambda body: body.__setitem__("params", {"scope": "x"}), "count",
335
- base=bug_body, request_type="bug")
336
- _inner_fails(lambda body: body.__setitem__("params", {"count": 3}), "scope",
337
- base=bug_body, request_type="bug")
338
- bug_meta = json.loads(json.dumps(record["metadata"]))
339
- bug_meta["status"] = "succeeded"
340
- assert sv.parse_inner_report(json.dumps(bug_body), request_type="bug",
341
- metadata=bug_meta)["requestType"] == "bug"
342
- tampered = dict(bug_meta, status="cancelled")
343
- expect_failure(
344
- "inner/metadata status disagreement",
345
- lambda: sv.parse_inner_report(json.dumps(bug_body), request_type="bug",
346
- metadata=tampered),
347
- sv.SavedVariablesError)
348
- print("inner report version/status/complete/environment/request checks OK")
349
-
350
- # --- session artifact byte fidelity and log scope -----------------------------
351
-
352
- data = os.path.join(tmp, "data")
353
- os.makedirs(data, exist_ok=True)
354
- s = ses.Session(data_dir=data, installation="retail-main")
355
-
356
- artifacts_payload = 'line1\nline2\ncaf\u00e9\r\nend\n'
357
- one = "LYCHEE-20260912-180000-0002"
358
- artifact = s.save_artifact(one, "content.json", artifacts_payload)
359
- raw = open(artifact, "rb").read()
360
- expected = artifacts_payload.encode("utf-8")
361
- assert raw == expected, (len(raw), len(expected))
362
- assert b"\r\n" in raw, "the CRLF that was in the content must survive"
363
- assert raw.count(b"\n") - raw.count(b"\r\n") == 3, "LF endings must not be rewritten"
364
- sha256 = hashlib.sha256(raw).hexdigest()
365
- s.log_event("received", ticket=one, byteCount=len(raw), sha256=sha256)
366
- received = s.read_events("received")[-1]
367
- assert received["byteCount"] == os.path.getsize(artifact) == len(expected)
368
- assert received["sha256"] == hashlib.sha256(open(artifact, "rb").read()).hexdigest()
369
- print("artifact byte fidelity (recorded byteCount/sha256 == on-disk bytes) OK")
370
-
371
- other = ses.Session(data_dir=data, installation="second-client")
372
- other.log_event("received", ticket="LYCHEE-OTHER")
373
- assert [r["ticket"] for r in s.read_events("received")] == [one], "scope leak"
374
- assert len(s.read_events("received", installation=ses.ALL_INSTALLATIONS)) == 2
375
- assert [r["ticket"] for r in other.read_events("received")] == ["LYCHEE-OTHER"]
376
- print("host log installation scope OK")
377
-
378
- assert not s.reload_already_requested("req-1", ticket)
379
- assert s.mark_reload_requested("req-1", ticket)
380
- assert not s.mark_reload_requested("req-1", ticket), "dedup failed"
381
- assert s.reload_already_requested("req-1", ticket)
382
- assert s.mark_reload_requested("req-1", ticket + "-other")
383
- assert not s.reload_already_requested("req-2", ticket)
384
- assert not s.wait_for_saved_variables(path, timeout=0.1)
385
- baseline = s.file_snapshot(path)
386
- os.utime(path, (time.time() + 5, time.time() + 5))
387
- assert s.wait_for_saved_variables(path, timeout=2, baseline=baseline)
388
- print("reload dedup + bounded SV wait OK")
389
-
390
- # --- bounded SV read retry -----------------------------------------------------
391
-
392
- def _succeed_after(failures_to_raise):
393
- state = {"calls": 0}
394
-
395
- def loader():
396
- state["calls"] += 1
397
- if state["calls"] <= failures_to_raise:
398
- raise sv.SavedVariablesError("torn file")
399
- return "value"
400
- return loader, state
401
-
402
-
403
- loader, state = _succeed_after(2)
404
- slept = []
405
- value, error, used = cli.retry_read(loader, attempts=4, delay=0.01,
406
- sleep=slept.append)
407
- assert (value, error, used) == ("value", None, 3), (value, error, used)
408
- assert state["calls"] == 3 and slept == [0.01, 0.01], (state, slept)
409
-
410
- loader, state = _succeed_after(99)
411
- value, error, used = cli.retry_read(loader, attempts=3, delay=0.01,
412
- sleep=slept.append)
413
- assert value is None and isinstance(error, sv.SavedVariablesError)
414
- assert used == 3 and state["calls"] == 3, (used, state)
415
- assert len(slept) == 4, slept
416
- print("bounded SV read retry OK")
417
-
418
- # --- CLI exit behaviour and defaults ------------------------------------------
419
-
420
- parser = cli.build_parser()
421
- capture_args = parser.parse_args(["capture", "--hwnd", "0x10"])
422
- assert capture_args.timeout == 120.0 and capture_args.interval == 0.1
423
- sv_defaults = parser.parse_args(["sv", "read", "--sv", path, "--ticket", ticket])
424
- assert sv_defaults.retries == 3 and sv_defaults.retry_delay == 0.5
425
- subparsers = next(action for action in parser._actions
426
- if isinstance(action, argparse._SubParsersAction))
427
- capture_help = subparsers.choices["capture"].format_help()
428
- assert "--timeout" in capture_help and "seconds" in capture_help
429
- assert "--interval" in capture_help
430
- run_help = subparsers.choices["run"].format_help()
431
- assert "--timeout" in run_help and "--interval" in run_help and "--sv" in run_help
432
- send_help = subparsers.choices["send"].format_help()
433
- assert "--request-id" in send_help and "--ticket" in send_help
434
- assert cli.main(["task", "upsert", "--install-dir", tmp, "--id", "x"]) == 1
435
- assert cli.main(["sv", "read", "--sv", os.path.join(tmp, "missing.lua"),
436
- "--ticket", ticket]) == 1
437
- assert cli.main(["sv", "find"]) == 1
438
- assert cli.main(["profile", "set", "--name", "p", "--wow-root", tmp,
439
- "--addon-dir", tmp]) == 1
440
- assert cli.main(["sv", "read", "--sv", path]) == 1
441
- print("CLI explicit errors (exit 1, no traceback) OK")
442
-
443
- # --- exit-code contract: window/input failures must map to 4, not 1 ------------
444
- #
445
- # Regression: a dead window used to exit 1 from capture/run/bugs while `send`
446
- # exited 4, and a missing optional dependency was reported as invalid usage.
447
-
448
- # automation.windows is imported lazily by the CLI, so import it explicitly for
449
- # the exception classes; the package module is the same one the CLI resolves.
450
- try:
451
- from automation import windows as windows_mod
452
- except Exception: # pragma: no cover - non-Windows hosts
453
- windows_mod = None
454
-
455
- if windows_mod is None: # pragma: no cover - non-Windows hosts
456
- print("CLI window/input exit codes (skipped: no windows module)")
457
- else:
458
- class _DeadWindowWindows:
459
- def __init__(self, error):
460
- self.error = error
461
-
462
- def open_notice_capture(self, *_args, **_kwargs):
463
- raise self.error
464
-
465
- real_window_module = cli._window_module
466
- try:
467
- for label, error, expected in (
468
- ("window identity", windows_mod.WindowIdentityError("dead window"), 4),
469
- ("missing dependency",
470
- windows_mod.CaptureDependencyError("no zxing-cpp"), 4),
471
- ("plain usage error", ValueError("bad argument"), 1),
472
- ):
473
- cli._window_module = lambda _error=error: _DeadWindowWindows(_error)
474
- code = cli.main(["--data-dir", tmp, "capture", "--hwnd", "0x10",
475
- "--timeout", "1"])
476
- assert code == expected, f"{label} exited {code}, expected {expected}"
477
- finally:
478
- cli._window_module = real_window_module
479
- print("CLI window/input exit codes (4 for window/dependency, 1 otherwise) OK")
480
-
481
- # --- input transaction regressions (no live game access) ----------------------
482
-
483
- try:
484
- from automation import windows as winmod
485
- except Exception: # pragma: no cover - non-Windows hosts
486
- winmod = None
487
-
488
- if winmod is None: # pragma: no cover - non-Windows hosts
489
- print("command delivery order (skipped: no windows module)")
490
- else:
491
- import unittest
492
- from test_input_safety import InputSafetyTests
493
- result = unittest.TextTestRunner().run(unittest.defaultTestLoader.loadTestsFromTestCase(InputSafetyTests))
494
- assert result.wasSuccessful(), "input transaction regressions failed"
495
-
496
- # The notice is drawn at the top-left corner of the game window, so the scan
497
- # area must cover that corner. A ROI that drifts back to another corner makes
498
- # the whole receipt path fail silently (capture finds no code, times out).
499
- top, left, bottom, right = winmod.NOTICE_ROI_FRACTIONS
500
- assert top == 0.0 and left == 0.0, (top, left)
501
- assert 0.0 < bottom <= 0.5 and 0.0 < right <= 0.5, (bottom, right)
502
- print("notice ROI covers the top-left corner OK")
503
-
504
- # Keep the Lua anchor and the Python ROI in sync: both corners must match.
505
- overlay = os.path.join(WORKTREE, "add-on", "UI", "AutomationOverlay.lua")
506
- if os.path.isfile(overlay):
507
- overlay_text = open(overlay, encoding="utf-8").read()
508
- assert 'noticeFrame:SetPoint("TOPLEFT", UIParent, "TOPLEFT"' in overlay_text, \
509
- "the Lua notice anchor is not TOPLEFT"
510
- assert "SetPoint(\"TOPRIGHT\", UIParent, \"TOPRIGHT\"" not in overlay_text, \
511
- "the Lua notice still anchors to TOPRIGHT while the ROI scans TOPLEFT"
512
- print("Lua notice anchor and Python ROI agree on the top-left corner OK")
513
-
514
- # The identity probe reads a marker from every running window so the caller
515
- # can name the window before typing into it. Probing must keep the input
516
- # order, isolate one bad window, and treat "no marker" as ordinary rather
517
- # than as an error.
518
- probe_delay = 0.3
519
-
520
- def fake_identity_reader(hwnd, **_kwargs):
521
- time.sleep(probe_delay)
522
- if hwnd == 3:
523
- raise winmod.WindowIdentityError("stale window")
524
- if hwnd == 4:
525
- return None
526
- return {"v": 1, "id": f"char{hwnd}", "realm": "realm", "client": "retail"}
527
-
528
- probe_windows = [{"hwnd": 1, "pid": 11}, {"hwnd": 2, "pid": 22},
529
- {"hwnd": 3, "pid": 33}, {"hwnd": 4, "pid": 44}]
530
- probe_start = time.monotonic()
531
- probe_results = winmod.read_identities(probe_windows, reader=fake_identity_reader)
532
- probe_elapsed = time.monotonic() - probe_start
533
-
534
- assert [entry["hwnd"] for entry in probe_results] == [1, 2, 3, 4], probe_results
535
- assert probe_results[0]["identity"]["id"] == "char1", probe_results[0]
536
- assert probe_results[1]["identity"]["id"] == "char2", probe_results[1]
537
- assert probe_results[2]["error"] == "stale window", probe_results[2]
538
- assert probe_results[2]["identity"] is None, probe_results[2]
539
- assert probe_results[3]["identity"] is None and probe_results[3]["error"] is None, \
540
- probe_results[3]
541
- # Windows are probed concurrently, so four delayed probes must cost far less
542
- # than four sequential waits.
543
- assert probe_elapsed < probe_delay * 2, probe_elapsed
544
- assert winmod.read_identities([]) == []
545
- # A found marker must return at once instead of waiting out the grace period.
546
- instant_start = time.monotonic()
547
- winmod.read_identities(probe_windows[:1],
548
- reader=lambda _hwnd, **_kw: {"v": 1, "id": "fast"})
549
- assert time.monotonic() - instant_start < probe_delay, "a found marker waited"
550
- # The waiting budget must stay small: it is paid per window on every probe.
551
- assert 0 < winmod.IDENTITY_FIRST_FRAME_GRACE <= 1.0, winmod.IDENTITY_FIRST_FRAME_GRACE
552
- assert 0 < winmod.IDENTITY_TIMEOUT <= 5.0, winmod.IDENTITY_TIMEOUT
553
- print("identity probe order, isolation and concurrency OK")
554
-
555
- # --- host read acknowledgement ------------------------------------------------
556
- #
557
- # The plugin cannot see whether the host read a result, so the host says so with
558
- # an in-game chat command through the already working delivery channel.
559
-
560
- assert cli.ack_command("LYCHEE-1", "received") == "/dev auto ack LYCHEE-1 received"
561
- assert cli.ack_command("LYCHEE-1", "failed") == "/dev auto ack LYCHEE-1 failed"
562
- for bad in ("ok", "RECEIVED", ""):
563
- try:
564
- cli.ack_command("LYCHEE-1", bad)
565
- raise SystemExit(f"ack accepted an invalid status: {bad!r}")
566
- except cli.CliError:
567
- pass
568
- ack_help = cli.build_parser()._subparsers._group_actions[0].choices["ack"].format_help()
569
- assert "--ticket" in ack_help and "--status" in ack_help
570
- assert "received" in ack_help
571
- print("ack command shape and status validation OK")
572
-
573
- # --- notice validation and identity -------------------------------------------
574
-
575
- def notice_json(**overrides):
576
- payload = {"v": 1, "ticket": ticket, "task": "inspect-example",
577
- "run": "req-20260912-000001-aaaaaa", "ts": 1789207200}
578
- payload.update(overrides)
579
- return json.dumps(payload)
580
-
581
-
582
- notice = cli.validate_notice(notice_json())
583
- assert cli.notice_identity_problems(notice, expected_task="inspect-example",
584
- expected_run=notice["run"]) == []
585
- assert cli.notice_identity_problems(notice, expected_task="other",
586
- expected_run=notice["run"])
587
- assert cli.notice_identity_problems(notice, expected_task=None,
588
- expected_run="stale-run")
589
- for bad in (json.dumps({"v": 2, "ticket": ticket, "task": "t", "run": "r", "ts": 1}),
590
- json.dumps({"ticket": ticket, "task": "t", "run": "r", "ts": 1}),
591
- notice_json(ts=0),
592
- notice_json(ts=True),
593
- notice_json(ticket="nope"),
594
- notice_json(task="bad/id"),
595
- notice_json(run="bad run"),
596
- notice_json(ticket="L" * 65),
597
- "",
598
- "not json"):
599
- expect_failure("bad notice " + str(bad)[:24],
600
- lambda payload=bad: cli.validate_notice(payload),
601
- sv.SavedVariablesError)
602
- print("notice validation + task/run identity checks OK")
603
-
604
-
605
- class _FakeCapture:
606
- def __init__(self):
607
- self.window_closed = False
608
- self.polls = 0
609
-
610
- def __enter__(self):
611
- return self
612
-
613
- def __exit__(self, *_exc):
614
- return False
615
-
616
- def latest_roi(self):
617
- self.polls += 1
618
- return self if self.polls <= 2 else None
619
-
620
-
621
- class _FakeWindows:
622
- def __init__(self, batches):
623
- self.batches = list(batches)
624
- self.opened = 0
625
-
626
- def open_notice_capture(self, hwnd, **kwargs):
627
- self.opened += 1
628
- return _FakeCapture()
629
-
630
- def decode_qr(self, roi):
631
- return self.batches.pop(0) if self.batches else []
632
-
633
-
634
- poll_args = argparse.Namespace(hwnd=1, timeout=1.0, interval=0.001, pid=None,
635
- exe_path=None)
636
- stale = notice_json(task="older-task", run="older-run",
637
- ticket="LYCHEE-20260912-170000-0009")
638
- fresh = notice_json()
639
- fake_session = ses.Session(data_dir=os.path.join(tmp, "poll"), installation="retry")
640
- fake_session_dirs = fake_session.data_dir
641
- os.makedirs(fake_session_dirs, exist_ok=True)
642
- fake_windows = _FakeWindows([[stale], [fresh]])
643
- resolved = cli.poll_notice(fake_windows, fake_session, poll_args,
644
- expected_task="inspect-example",
645
- expected_run="req-20260912-000001-aaaaaa")
646
- assert resolved is not None and resolved["ticket"] == ticket, resolved
647
- assert fake_windows.opened == 1, "one capture session must serve the whole poll"
648
- events = [r["event"] for r in fake_session.read_events()]
649
- assert "notice_identity_mismatch" in events and "notice_seen" in events, events
650
-
651
- timeout_session = ses.Session(data_dir=os.path.join(tmp, "poll-timeout"),
652
- installation="retry")
653
- os.makedirs(timeout_session.data_dir, exist_ok=True)
654
- timeout_args = argparse.Namespace(hwnd=1, timeout=0.2, interval=0.001, pid=None,
655
- exe_path=None)
656
- started = time.monotonic()
657
- assert cli.poll_notice(_FakeWindows([]), timeout_session, timeout_args,
658
- expected_task="x") is None
659
- assert 0.15 < time.monotonic() - started < 5.0
660
- timeout_events = [r["event"] for r in timeout_session.read_events()]
661
- assert "notice_seen" not in timeout_events
662
- print("poll_notice: stale notice rejected, fresh accepted, timeout bounded OK")
663
-
664
- # Acknowledgement receipts must match Ticket, nonce, task and outcome together.
665
- ack_good = notice_json(task="ack", run="ack-nonce", status="received")
666
- ack_stale = notice_json(task="ack", run="old-nonce", status="received")
667
- ack_wrong_ticket = notice_json(task="ack", run="ack-nonce", ticket="LYCHEE-other", status="received")
668
- ack_wrong_status = notice_json(task="ack", run="ack-nonce", status="failed")
669
- ack_resolved = cli.poll_notice(
670
- _FakeWindows([[ack_stale, ack_wrong_ticket, ack_wrong_status], [ack_good]]),
671
- fake_session, poll_args, expected_task="ack", expected_run="ack-nonce",
672
- expected_ticket=ticket, expected_status="received")
673
- assert ack_resolved and ack_resolved["status"] == "received"
674
- for bad_ticket in ("LYCHEE-1\n/reload", "LYCHEE-1 received", "bad"):
675
- expect_failure("ack ticket validation", lambda t=bad_ticket: cli.ack_command(t, "received"), cli.CliError)
676
- print("ack receipt exact identity and command validation OK")
677
-
678
- # --- registry: schema/kind rejection, hash, region preservation ---------------
679
-
680
- def registry_text(*blocks):
681
- return reg.REGISTRY_HEADER + "".join(blocks)
682
-
683
-
684
- block = "\n".join(reg.build_block(
685
- "inspect-example", request_id="req-1", revision="rev-1",
686
- source='print("hi")', created_at=1)) + "\n"
687
-
688
- expect_failure("schema 9 rejected",
689
- lambda: reg.parse_blocks(reg.REGISTRY_HEADER + block.replace(
690
- "schema = 1,", "schema = 9,")),
691
- reg.RegistryError)
692
- expect_failure("kind rejected",
693
- lambda: reg.parse_blocks(reg.REGISTRY_HEADER + block.replace(
694
- 'kind = "lua",', 'kind = "nope",')),
695
- reg.RegistryError)
696
- expect_failure("unterminated block rejected",
697
- lambda: reg.parse_blocks(reg.REGISTRY_HEADER + block.replace(
698
- reg.END_MARKER + "inspect-example\n", "")),
699
- reg.RegistryError)
700
- expect_failure("unexpected block footer rejected",
701
- lambda: reg.parse_blocks(reg.REGISTRY_HEADER + block.replace(
702
- "\n}\n" + reg.END_MARKER, "\n" + reg.END_MARKER)),
703
- reg.RegistryError)
704
- assert reg.split_regions("head\nbody\n") == ("head\nbody\n", "")
705
- assert reg.split_regions("pre\n" + block + "post\n") == ("pre\n", "post\n")
706
-
707
- regdir = os.path.join(tmp, "registry")
708
- os.makedirs(regdir, exist_ok=True)
709
- task_path = os.path.join(regdir, "auto.lua")
710
- prefix_note = "-- hand written note before the blocks\n"
711
- suffix_note = "-- hand written trailer kept verbatim\n"
712
- with open(task_path, "wb") as handle:
713
- handle.write((reg.REGISTRY_HEADER + prefix_note).encode("utf-8"))
714
-
715
- task_registry = reg.TaskRegistry(task_path)
716
- assert task_registry.path == reg.resolve_registry_path(task_path)
717
- definition = task_registry.upsert(
718
- "inspect-example", request_id="req-1", revision="rev-1",
719
- source='print("caf' + "\u00e9" + '")' + "\n", created_at=1)
720
- assert prefix_note in open(task_path, "r", encoding="ascii").read()
721
- disk = open(task_path, "rb").read()
722
- assert definition["sourceBytes"] == len(
723
- ('print("caf' + "\u00e9" + '")' + "\n").encode("utf-8"))
724
- assert definition["fileHash"] == hashlib.sha256(disk).hexdigest()
725
- assert all(byte < 128 for byte in disk), "registry must stay ASCII"
726
- assert b"\r" not in disk
727
- text = disk.decode("ascii")
728
- assert prefix_note in text, "content before the blocks lost"
729
- assert task_registry.read()["inspect-example"]["source"] == \
730
- 'print("caf' + "\u00e9" + '")' + "\n"
731
- assert "\\195\\169" in text, "non-ASCII source must be escaped as \\ddd"
732
-
733
- # A human trailer after the blocks must survive every later write.
734
- with open(task_path, "a", encoding="utf-8") as handle:
735
- handle.write(suffix_note)
736
- second = task_registry.upsert("second-task", request_id="req-2", revision="rev-2",
737
- source="return 1", created_at=2)
738
- assert second["fileHash"] == hashlib.sha256(open(task_path, "rb").read()).hexdigest()
739
- text = open(task_path, "r", encoding="ascii").read()
740
- assert prefix_note in text and suffix_note in text, "content outside blocks lost"
741
- assert text.startswith(reg.REGISTRY_HEADER + prefix_note)
742
- assert text.endswith(suffix_note), "trailer after the blocks was lost"
743
- assert list(task_registry.read()) == ["inspect-example", "second-task"]
744
- task_registry.upsert("second-task", request_id="req-3", revision="rev-3",
745
- source="return 2", created_at=3)
746
- definitions = task_registry.read()
747
- assert definitions["second-task"]["revision"] == "rev-3"
748
- assert definitions["inspect-example"]["revision"] == "rev-1"
749
- assert prefix_note in open(task_path, "r", encoding="ascii").read()
750
- expect_failure(
751
- "revision conflict",
752
- lambda: task_registry.upsert("second-task", request_id="req-4",
753
- revision="rev-4", source="return 3",
754
- created_at=4, expect_revision="rev-1"),
755
- reg.RegistryError)
756
- assert task_registry.remove("second-task")
757
- text_after_remove = open(task_path, "r", encoding="ascii").read()
758
- assert prefix_note in text_after_remove and suffix_note in text_after_remove
759
- assert list(task_registry.read()) == ["inspect-example"]
760
- assert not task_registry.remove("second-task")
761
- print("registry schema/kind rejection, fileHash, region preservation OK")
762
-
763
- link_path = os.path.join(tmp, "registry-link")
764
- linked = False
765
- try:
766
- os.symlink(regdir, link_path, target_is_directory=True)
767
- linked = True
768
- except (OSError, NotImplementedError, AttributeError):
769
- pass
770
- if not linked:
771
- # Junctions need no elevated privilege; used as the Windows fallback.
772
- linked = (os.system('cmd /c mklink /J "' + link_path + '" "' + regdir
773
- + '" >nul 2>nul') == 0 and os.path.isdir(link_path))
774
- if linked:
775
- resolved = reg.TaskRegistry(os.path.join(link_path, "auto.lua"))
776
- assert resolved.path == task_registry.path, (resolved.path, task_registry.path)
777
- assert resolved.read() == task_registry.read()
778
- print("symlink/junction path resolution OK")
779
- else:
780
- print("symlink/junction resolution check skipped (no link support)")
781
-
782
- # --- task upsert through the CLI (non-ASCII source, byte-exact sourceBytes) ---
783
-
784
- cli_dir = os.path.join(tmp, "cli-install")
785
- auto_dir = os.path.join(cli_dir, "Modules", "Automation", "auto")
786
- os.makedirs(auto_dir, exist_ok=True)
787
- source_file = os.path.join(tmp, "probe.lua")
788
- source_text = 'print("caf\u00e9")\r\nreturn { ok = true }\n'
789
- with open(source_file, "wb") as handle:
790
- handle.write(source_text.encode("utf-8"))
791
- auto_path = os.path.join(auto_dir, "auto.lua")
792
- code = cli.main(["task", "upsert", "--install-dir", cli_dir, "--id", "probe-one",
793
- "--source-file", source_file, "--request-id", "req-cli-1",
794
- "--revision", "rev-cli-1"])
795
- assert code == 0, code
796
- cli_registry = reg.TaskRegistry(auto_path)
797
- cli_definition = cli_registry.read()["probe-one"]
798
- assert cli_definition["source"] == source_text, "CRLF source bytes changed"
799
- assert cli_definition["sourceBytes"] == len(source_text.encode("utf-8"))
800
- assert all(byte < 128 for byte in open(auto_path, "rb").read())
801
- assert cli.main(["task", "list", "--install-dir", cli_dir]) == 0
802
- assert cli.main(["task", "remove", "--install-dir", cli_dir, "--id", "probe-one"]) == 0
803
- assert cli_registry.read() == {}
804
- print("CLI task upsert keeps non-ASCII/CRLF source byte-exact OK")
805
-
806
- # --- profile set + sv find resolve the client folder --------------------------
807
-
808
- wow_root = os.path.join(tmp, "wow")
809
- account_dir = os.path.join(wow_root, "_retail_", "WTF", "Account", "TESTACCOUNT",
810
- "SavedVariables")
811
- os.makedirs(account_dir, exist_ok=True)
812
- expected_sv = os.path.join(account_dir, "Lychee Dev.lua")
813
- with open(expected_sv, "wb") as handle:
814
- handle.write(b"LycheeDevDB = {}\n")
815
- addon_install = os.path.join(tmp, "addon-install")
816
- os.makedirs(addon_install, exist_ok=True)
817
- profile_data = os.path.join(tmp, "profile-data")
818
- assert cli.main(["--data-dir", profile_data, "profile", "set", "--name", "retail-main",
819
- "--client", "retail", "--wow-root", wow_root,
820
- "--addon-dir", addon_install, "--sv-path", expected_sv]) == 0
821
- out = io.StringIO()
822
- with contextlib.redirect_stdout(out):
823
- assert cli.main(["--data-dir", profile_data, "sv", "find",
824
- "--profile", "retail-main"]) == 0
825
- assert out.getvalue().strip() == expected_sv, out.getvalue()
826
-
827
- # A profile may point straight at the client folder instead of the WoW root.
828
- with contextlib.redirect_stdout(out):
829
- assert cli.main(["--data-dir", profile_data, "profile", "set", "--name", "direct",
830
- "--client", "retail",
831
- "--wow-root", os.path.join(wow_root, "_retail_"),
832
- "--addon-dir", addon_install]) == 0
833
- out = io.StringIO()
834
- with contextlib.redirect_stdout(out):
835
- assert cli.main(["--data-dir", profile_data, "sv", "find", "--profile", "direct"]) == 0
836
- assert out.getvalue().strip() == expected_sv, out.getvalue()
837
- assert cli.main(["--data-dir", profile_data, "sv", "find", "--profile", "missing"]) == 1
838
-
839
- # WoW: Forever lives in a reused test folder on the test track, so a profile for
840
- # it must resolve whichever accepted folder actually holds the account tree.
841
- assert cli.CLIENT_FOLDERS["forever"] == ("_classic_beta_", "_forever_"), \
842
- cli.CLIENT_FOLDERS["forever"]
843
- forever_account = os.path.join(wow_root, "_classic_beta_", "WTF", "Account",
844
- "TESTACCOUNT", "SavedVariables")
845
- os.makedirs(forever_account, exist_ok=True)
846
- forever_sv = os.path.join(forever_account, "Lychee Dev.lua")
847
- with open(forever_sv, "wb") as handle:
848
- handle.write(b"LycheeDevDB = {}\n")
849
- assert cli.main(["--data-dir", profile_data, "profile", "set", "--name", "forever-main",
850
- "--client", "forever", "--wow-root", wow_root,
851
- "--addon-dir", addon_install]) == 0
852
- out = io.StringIO()
853
- with contextlib.redirect_stdout(out):
854
- assert cli.main(["--data-dir", profile_data, "sv", "find",
855
- "--profile", "forever-main"]) == 0
856
- assert out.getvalue().strip() == forever_sv, out.getvalue()
857
-
858
- # The same profile must still resolve after the client moves to its own folder,
859
- # without rewriting the profile: the recorded folder is a hint, not the answer.
860
- os.rename(os.path.join(wow_root, "_classic_beta_"), os.path.join(wow_root, "_forever_"))
861
- out = io.StringIO()
862
- with contextlib.redirect_stdout(out):
863
- assert cli.main(["--data-dir", profile_data, "sv", "find",
864
- "--profile", "forever-main"]) == 0
865
- assert out.getvalue().strip() == os.path.join(
866
- wow_root, "_forever_", "WTF", "Account", "TESTACCOUNT", "SavedVariables",
867
- "Lychee Dev.lua"), out.getvalue()
868
-
869
- # The old bug: a profile that recorded `_classic_arena_` (which does not exist)
870
- # must still fall back to the client's real folders.
871
- stale = os.path.join(profile_data, "profiles.json")
872
- with open(stale, encoding="utf-8") as handle:
873
- stored = json.load(handle)
874
- stored["forever-main"]["clientFolder"] = "_classic_arena_"
875
- stored["forever-main"]["clientFolders"] = ["_classic_arena_"]
876
- with open(stale, "w", encoding="utf-8") as handle:
877
- json.dump(stored, handle)
878
- out = io.StringIO()
879
- with contextlib.redirect_stdout(out):
880
- assert cli.main(["--data-dir", profile_data, "sv", "find",
881
- "--profile", "forever-main"]) == 0, out.getvalue()
882
- assert out.getvalue().strip() == os.path.join(
883
- wow_root, "_forever_", "WTF", "Account", "TESTACCOUNT", "SavedVariables",
884
- "Lychee Dev.lua"), out.getvalue()
885
- print("profile set + sv find resolve the client folder OK")
886
-
887
- # --- send: host log first, reload dedup, explicit input failure ---------------
888
-
889
- send_data = os.path.join(tmp, "send-data")
890
-
891
-
892
- class _FakeSendWindows:
893
- class WindowIdentityError(Exception):
894
- pass
895
-
896
- class InputError(Exception):
897
- pass
898
-
899
- sent = []
900
- modes = []
901
-
902
- @classmethod
903
- def send_command(cls, hwnd, text, pid=None, exe_path=None, mode="foreground"):
904
- cls.sent.append((hwnd, text))
905
- cls.modes.append(mode)
906
-
907
-
908
- class _FailingSendWindows:
909
- class WindowIdentityError(Exception):
910
- pass
911
-
912
- class InputError(Exception):
913
- pass
914
-
915
- @staticmethod
916
- def send_command(hwnd, text, pid=None, exe_path=None, mode="foreground"):
917
- raise _FailingSendWindows.WindowIdentityError("window identity changed")
918
-
919
-
920
- original_window_module = cli._window_module
921
- try:
922
- cli._window_module = lambda: _FakeSendWindows
923
- reload_call = ["--data-dir", send_data, "--installation", "send-scope", "send",
924
- "--hwnd", "0x1", "--text", "/reload",
925
- "--request-id", "req-send-1", "--ticket", "LYCHEE-SEND-1"]
926
- assert cli.main(reload_call) == 0
927
- assert cli.main(reload_call) == 1, "second reload for one notice must be refused"
928
- assert cli.main(["--data-dir", send_data, "send", "--hwnd", "0x1",
929
- "--text", "/dev auto status x"]) == 0
930
- scoped = [r["event"] for r in
931
- ses.Session(data_dir=send_data, installation="send-scope").read_events()]
932
- assert scoped.count("reload_requested") == 1, scoped
933
- assert scoped.count("command_submitted") == 1, scoped
934
- every = ses.Session(data_dir=send_data).read_events(
935
- installation=ses.ALL_INSTALLATIONS)
936
- assert [r["event"] for r in every].count("command_submitted") == 2
937
- assert _FakeSendWindows.sent == [(1, "/reload"), (1, "/dev auto status x")]
938
- assert _FakeSendWindows.modes == ["messages", "messages"], _FakeSendWindows.modes
939
- assert cli.main(["--data-dir", send_data, "send", "--hwnd", "0x1",
940
- "--mode", "messages", "--text", "/dev"]) == 0
941
- assert _FakeSendWindows.modes[-1] == "messages", _FakeSendWindows.modes
942
-
943
- cli._window_module = lambda: _FailingSendWindows
944
- assert cli.main(["--data-dir", send_data, "send", "--hwnd", "0x1",
945
- "--text", "/dev"]) == 4
946
- failed = [r["event"] for r in ses.Session(data_dir=send_data).read_events(
947
- installation=ses.ALL_INSTALLATIONS)]
948
- assert "command_failed" in failed, failed
949
- finally:
950
- cli._window_module = original_window_module
951
- print("send host log + reload dedup + input failure exit OK")
952
-
953
- # Drive the actual CLI acknowledgement flow: submission alone is unresolved.
954
- from unittest.mock import patch
955
- ack_data = os.path.join(tmp, "ack-flow")
956
- ack_args = ["--data-dir", ack_data, "ack", "--hwnd", "1", "--ticket", "LYCHEE-1",
957
- "--status", "received", "--timeout", "0.1"]
958
- with patch.object(cli, "_window_module", return_value=_FakeSendWindows), \
959
- patch.object(cli, "poll_notice", return_value=None):
960
- assert cli.main(ack_args) == 5
961
- ack_events = [r["event"] for r in ses.Session(data_dir=ack_data).read_events()]
962
- assert "ticket_ack_unresolved" in ack_events and "ticket_ack_confirmed" not in ack_events
963
- with patch.object(cli, "_window_module", return_value=_FakeSendWindows), \
964
- patch.object(cli, "poll_notice", return_value={"status": "received"}) as poll, \
965
- patch.object(cli, "wait_ack_cleared", return_value=True):
966
- assert cli.main(ack_args) == 0
967
- sent_nonce = _FakeSendWindows.sent[-2][1].split()[-1]
968
- assert _FakeSendWindows.sent[-1][1] == f"/dev auto unidentify {sent_nonce}"
969
- assert poll.call_args.kwargs["expected_run"] == sent_nonce
970
- assert poll.call_args.kwargs["expected_ticket"] == "LYCHEE-1"
971
- assert poll.call_args.kwargs["expected_status"] == "received"
972
- with patch.object(cli, "_window_module", return_value=_FakeSendWindows), \
973
- patch.object(cli, "poll_notice", return_value={}) as poll, \
974
- patch.object(cli, "_notice_to_sv", return_value=0):
975
- assert cli.main(["--data-dir", ack_data, "bugs", "--hwnd", "1", "--count", "2",
976
- "--sv", "unused", "--request-id", "bug-proof-1"]) == 0
977
- assert _FakeSendWindows.sent[-1][1] == "/dev auto bug 2 bug-proof-1"
978
- assert poll.call_args.kwargs["expected_run"] == "bug-proof-1"
979
- # Cleanup requires observed frames, and a still-visible receipt must time out.
980
- cleanup_args = argparse.Namespace(hwnd=1, pid=None, exe_path=None, timeout=0.03, interval=0.001)
981
- assert cli.wait_ack_cleared(_FakeWindows([[], []]), cleanup_args, "cleanup-nonce")
982
- visible_receipt = notice_json(task="ack", run="cleanup-nonce", status="received")
983
- assert not cli.wait_ack_cleared(_FakeWindows([[visible_receipt], [visible_receipt]]),
984
- cleanup_args, "cleanup-nonce")
985
- class _NoFrameCapture(_FakeCapture):
986
- def latest_roi(self): return None
987
- no_frames = _FakeWindows([])
988
- no_frames.open_notice_capture = lambda *a, **k: _NoFrameCapture()
989
- assert not cli.wait_ack_cleared(no_frames, cleanup_args, "cleanup-nonce")
990
- print("ack CLI unresolved/confirmed lifecycle and bug request delivery OK")
991
-
992
-
993
- # --- packaging metadata -------------------------------------------------------
994
-
995
- requirements = os.path.join(HERE, "requirements.txt")
996
- assert os.path.isfile(requirements), requirements
997
- requirements_text = open(requirements, "r", encoding="utf-8").read()
998
- for pinned in ("zxing-cpp==3.1.1", "windows-capture==2.0.1", "numpy==2.5.3"):
999
- assert pinned in requirements_text, pinned
1000
- gitignore = open(os.path.join(WORKTREE, ".gitignore"), "r", encoding="utf-8").read()
1001
- assert "__pycache__/" in gitignore and "*.pyc" in gitignore
1002
- print("requirements.txt pins + .gitignore pycache entries OK")
1003
-
1004
- # --- real optional dependencies (only when importable) ------------------------
1005
-
1006
- try:
1007
- import inspect
1008
- import numpy as np
1009
- import windows_capture
1010
- import zxingcpp
1011
- from automation import windows as win
1012
- except ImportError as error:
1013
- print("optional live-window dependency checks skipped: " + str(error))
1014
- else:
1015
- assert callable(getattr(zxingcpp, "read_barcodes", None))
1016
- assert not hasattr(zxingcpp, "read_bars")
1017
- assert callable(getattr(windows_capture.WindowsCapture, "on_frame_arrived", None))
1018
- assert callable(getattr(windows_capture.WindowsCapture, "on_closed", None))
1019
- assert callable(getattr(windows_capture.WindowsCapture, "start_free_threaded", None))
1020
- assert callable(getattr(windows_capture.Frame, "convert_to_bgr", None))
1021
- assert callable(getattr(windows_capture.Frame, "crop", None))
1022
- capture_parameters = inspect.signature(
1023
- windows_capture.WindowsCapture.__init__).parameters
1024
- assert "window_hwnd" in capture_parameters
1025
- assert "minimum_update_interval" in capture_parameters
1026
- assert win.INPUT_SIZE == (40 if ctypes.sizeof(ctypes.c_void_p) == 8 else 28)
1027
- assert win.user32.GetClipboardData.restype is ctypes.c_void_p
1028
- assert win.kernel32.GlobalLock.restype is ctypes.c_void_p
1029
- assert win.kernel32.OpenProcess.restype is ctypes.c_void_p
1030
- assert win.user32.SendInput.argtypes[1] == ctypes.POINTER(win.INPUT)
1031
- barcode = zxingcpp.create_barcode(notice_json(), zxingcpp.BarcodeFormat.QRCode)
1032
- qr_image = np.asarray(zxingcpp.write_barcode_to_image(barcode))
1033
- assert win.decode_qr(qr_image, zxingcpp) == [notice_json()]
1034
- assert win.decode_qr(qr_image, None) == [notice_json()]
1035
-
1036
- class _FakeCaptureObject:
1037
- frame_handler = None
1038
- closed_handler = None
1039
-
1040
- # The real Frame class drives the exact ROI path used on live frames.
1041
- real_frame = windows_capture.Frame(np.zeros((20, 20, 4), dtype=np.uint8), 20, 20, 0)
1042
- capture = win.NoticeCapture(_FakeCaptureObject(), np, hwnd=0)
1043
- capture._on_frame(real_frame)
1044
- roi = capture.latest_roi()
1045
- assert capture.last_frame_error is None, capture.last_frame_error
1046
- # Derive the expected ROI from the configured fractions instead of freezing
1047
- # one shape: the corner the notice uses has changed once already.
1048
- expect_top, expect_left, expect_bottom, expect_right = win.NOTICE_ROI_FRACTIONS
1049
- expect_h = int(20 * expect_bottom) - int(20 * expect_top)
1050
- expect_w = int(20 * expect_right) - int(20 * expect_left)
1051
- assert roi is not None and roi.shape == (expect_h, expect_w, 3), (
1052
- roi.shape, (expect_h, expect_w, 3))
1053
- assert capture.window_closed is False
1054
- capture._on_closed()
1055
- assert capture.window_closed is True
1056
- assert "read_bars(" not in open(win.__file__, "r", encoding="utf-8").read()
1057
- print("real zxing-cpp/windows-capture API checks OK")
1058
-
1059
- print("saved_variables + session OK")
1060
-
1061
-