lycheedev 1.0.0 → 1.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 (50) hide show
  1. package/bin/lycheedev.js +21 -6
  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,981 +1,981 @@
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
- # --- command delivery order: open chat, paste, submit ------------------------
482
- #
483
- # Regression: the sequence used to paste BEFORE opening the chat box, so the
484
- # client opened an empty chat and no command ran. Reference behaviour is
485
- # Return -> Ctrl+V -> Return.
486
-
487
- try:
488
- from automation import windows as winmod
489
- except Exception: # pragma: no cover - non-Windows hosts
490
- winmod = None
491
-
492
- if winmod is None: # pragma: no cover - non-Windows hosts
493
- print("command delivery order (skipped: no windows module)")
494
- else:
495
- class _RecordingClipboard:
496
- def __init__(self):
497
- self.value = None
498
- self.writes = []
499
-
500
- def read_text(self):
501
- return self.value
502
-
503
- def copy_text(self, text):
504
- self.value = text
505
- self.writes.append(text)
506
-
507
- def clear(self):
508
- self.value = None
509
-
510
- pressed = []
511
- real_send_key = winmod._send_key
512
- real_set_fg = winmod.user32.SetForegroundWindow
513
- real_is_foreground = winmod.is_foreground
514
- real_confirm = winmod.confirm_window
515
- real_sleep = winmod.time.sleep
516
- try:
517
- def fake_send_key(vk, *, ctrl=False):
518
- pressed.append(("ctrl+v" if ctrl else "key") + ":%#x" % vk)
519
-
520
- winmod._send_key = fake_send_key
521
- winmod.user32.SetForegroundWindow = lambda _hwnd: 1
522
- winmod.is_foreground = lambda _hwnd: True
523
- winmod.confirm_window = lambda *a, **k: None
524
- winmod.time.sleep = lambda _seconds: None
525
-
526
- delivery_clipboard = _RecordingClipboard()
527
- winmod.send_command(1, "/reload", clipboard=delivery_clipboard)
528
- expected = ["key:0xd", "ctrl+v:0x56", "key:0xd"]
529
- assert pressed == expected, f"delivery order was {pressed}, expected {expected}"
530
- assert delivery_clipboard.writes[0] == "/reload", delivery_clipboard.writes
531
- finally:
532
- winmod._send_key = real_send_key
533
- winmod.user32.SetForegroundWindow = real_set_fg
534
- winmod.is_foreground = real_is_foreground
535
- winmod.confirm_window = real_confirm
536
- winmod.time.sleep = real_sleep
537
- print("command delivery order (Return, Ctrl+V, Return) OK")
538
-
539
- posted = []
540
- real_post = winmod.user32.PostMessageW
541
- real_sleep_messages = winmod.time.sleep
542
- try:
543
- winmod.user32.PostMessageW = (
544
- lambda hwnd, msg, wparam, lparam: posted.append((msg, wparam)) or 1)
545
- winmod.time.sleep = lambda _seconds: None
546
- winmod.send_command_messages(1, "/reload")
547
- finally:
548
- winmod.user32.PostMessageW = real_post
549
- winmod.time.sleep = real_sleep_messages
550
-
551
- chars = "".join(chr(w) for m, w in posted if m == winmod.WM_CHAR)
552
- assert chars == "/reload", chars
553
- down = [w for m, w in posted if m == winmod.WM_KEYDOWN]
554
- assert down == [winmod.VK_RETURN], down
555
- assert all(m in (winmod.WM_CHAR, winmod.WM_KEYDOWN, winmod.WM_KEYUP)
556
- for m, _w in posted), posted
557
- print("command delivery via posted messages (no foreground) OK")
558
-
559
- # The notice is drawn at the top-left corner of the game window, so the scan
560
- # area must cover that corner. A ROI that drifts back to another corner makes
561
- # the whole receipt path fail silently (capture finds no code, times out).
562
- top, left, bottom, right = winmod.NOTICE_ROI_FRACTIONS
563
- assert top == 0.0 and left == 0.0, (top, left)
564
- assert 0.0 < bottom <= 0.5 and 0.0 < right <= 0.5, (bottom, right)
565
- print("notice ROI covers the top-left corner OK")
566
-
567
- # Keep the Lua anchor and the Python ROI in sync: both corners must match.
568
- overlay = os.path.join(WORKTREE, "add-on", "UI", "AutomationOverlay.lua")
569
- if os.path.isfile(overlay):
570
- overlay_text = open(overlay, encoding="utf-8").read()
571
- assert 'noticeFrame:SetPoint("TOPLEFT", UIParent, "TOPLEFT"' in overlay_text, \
572
- "the Lua notice anchor is not TOPLEFT"
573
- assert "SetPoint(\"TOPRIGHT\", UIParent, \"TOPRIGHT\"" not in overlay_text, \
574
- "the Lua notice still anchors to TOPRIGHT while the ROI scans TOPLEFT"
575
- print("Lua notice anchor and Python ROI agree on the top-left corner OK")
576
-
577
- # --- host read acknowledgement ------------------------------------------------
578
- #
579
- # The plugin cannot see whether the host read a result, so the host says so with
580
- # an in-game chat command through the already working delivery channel.
581
-
582
- assert cli.ack_command("LYCHEE-1", "received") == "/dev auto ack LYCHEE-1 received"
583
- assert cli.ack_command("LYCHEE-1", "failed") == "/dev auto ack LYCHEE-1 failed"
584
- for bad in ("ok", "RECEIVED", ""):
585
- try:
586
- cli.ack_command("LYCHEE-1", bad)
587
- raise SystemExit(f"ack accepted an invalid status: {bad!r}")
588
- except cli.CliError:
589
- pass
590
- ack_help = cli.build_parser()._subparsers._group_actions[0].choices["ack"].format_help()
591
- assert "--ticket" in ack_help and "--status" in ack_help
592
- assert "received" in ack_help
593
- print("ack command shape and status validation OK")
594
-
595
- # --- notice validation and identity -------------------------------------------
596
-
597
- def notice_json(**overrides):
598
- payload = {"v": 1, "ticket": ticket, "task": "inspect-example",
599
- "run": "req-20260912-000001-aaaaaa", "ts": 1789207200}
600
- payload.update(overrides)
601
- return json.dumps(payload)
602
-
603
-
604
- notice = cli.validate_notice(notice_json())
605
- assert cli.notice_identity_problems(notice, expected_task="inspect-example",
606
- expected_run=notice["run"]) == []
607
- assert cli.notice_identity_problems(notice, expected_task="other",
608
- expected_run=notice["run"])
609
- assert cli.notice_identity_problems(notice, expected_task=None,
610
- expected_run="stale-run")
611
- for bad in (json.dumps({"v": 2, "ticket": ticket, "task": "t", "run": "r", "ts": 1}),
612
- json.dumps({"ticket": ticket, "task": "t", "run": "r", "ts": 1}),
613
- notice_json(ts=0),
614
- notice_json(ts=True),
615
- notice_json(ticket="nope"),
616
- notice_json(task="bad/id"),
617
- notice_json(run="bad run"),
618
- notice_json(ticket="L" * 65),
619
- "",
620
- "not json"):
621
- expect_failure("bad notice " + str(bad)[:24],
622
- lambda payload=bad: cli.validate_notice(payload),
623
- sv.SavedVariablesError)
624
- print("notice validation + task/run identity checks OK")
625
-
626
-
627
- class _FakeCapture:
628
- def __init__(self):
629
- self.window_closed = False
630
- self.polls = 0
631
-
632
- def __enter__(self):
633
- return self
634
-
635
- def __exit__(self, *_exc):
636
- return False
637
-
638
- def latest_roi(self):
639
- self.polls += 1
640
- return self if self.polls <= 2 else None
641
-
642
-
643
- class _FakeWindows:
644
- def __init__(self, batches):
645
- self.batches = list(batches)
646
- self.opened = 0
647
-
648
- def open_notice_capture(self, hwnd, **kwargs):
649
- self.opened += 1
650
- return _FakeCapture()
651
-
652
- def decode_qr(self, roi):
653
- return self.batches.pop(0) if self.batches else []
654
-
655
-
656
- poll_args = argparse.Namespace(hwnd=1, timeout=1.0, interval=0.001, pid=None,
657
- exe_path=None)
658
- stale = notice_json(task="older-task", run="older-run",
659
- ticket="LYCHEE-20260912-170000-0009")
660
- fresh = notice_json()
661
- fake_session = ses.Session(data_dir=os.path.join(tmp, "poll"), installation="retry")
662
- fake_session_dirs = fake_session.data_dir
663
- os.makedirs(fake_session_dirs, exist_ok=True)
664
- fake_windows = _FakeWindows([[stale], [fresh]])
665
- resolved = cli.poll_notice(fake_windows, fake_session, poll_args,
666
- expected_task="inspect-example",
667
- expected_run="req-20260912-000001-aaaaaa")
668
- assert resolved is not None and resolved["ticket"] == ticket, resolved
669
- assert fake_windows.opened == 1, "one capture session must serve the whole poll"
670
- events = [r["event"] for r in fake_session.read_events()]
671
- assert "notice_identity_mismatch" in events and "notice_seen" in events, events
672
-
673
- timeout_session = ses.Session(data_dir=os.path.join(tmp, "poll-timeout"),
674
- installation="retry")
675
- os.makedirs(timeout_session.data_dir, exist_ok=True)
676
- timeout_args = argparse.Namespace(hwnd=1, timeout=0.2, interval=0.001, pid=None,
677
- exe_path=None)
678
- started = time.monotonic()
679
- assert cli.poll_notice(_FakeWindows([]), timeout_session, timeout_args,
680
- expected_task="x") is None
681
- assert 0.15 < time.monotonic() - started < 5.0
682
- timeout_events = [r["event"] for r in timeout_session.read_events()]
683
- assert "notice_seen" not in timeout_events
684
- print("poll_notice: stale notice rejected, fresh accepted, timeout bounded OK")
685
-
686
- # --- registry: schema/kind rejection, hash, region preservation ---------------
687
-
688
- def registry_text(*blocks):
689
- return reg.REGISTRY_HEADER + "".join(blocks)
690
-
691
-
692
- block = "\n".join(reg.build_block(
693
- "inspect-example", request_id="req-1", revision="rev-1",
694
- source='print("hi")', created_at=1)) + "\n"
695
-
696
- expect_failure("schema 9 rejected",
697
- lambda: reg.parse_blocks(reg.REGISTRY_HEADER + block.replace(
698
- "schema = 1,", "schema = 9,")),
699
- reg.RegistryError)
700
- expect_failure("kind rejected",
701
- lambda: reg.parse_blocks(reg.REGISTRY_HEADER + block.replace(
702
- 'kind = "lua",', 'kind = "nope",')),
703
- reg.RegistryError)
704
- expect_failure("unterminated block rejected",
705
- lambda: reg.parse_blocks(reg.REGISTRY_HEADER + block.replace(
706
- reg.END_MARKER + "inspect-example\n", "")),
707
- reg.RegistryError)
708
- expect_failure("unexpected block footer rejected",
709
- lambda: reg.parse_blocks(reg.REGISTRY_HEADER + block.replace(
710
- "\n}\n" + reg.END_MARKER, "\n" + reg.END_MARKER)),
711
- reg.RegistryError)
712
- assert reg.split_regions("head\nbody\n") == ("head\nbody\n", "")
713
- assert reg.split_regions("pre\n" + block + "post\n") == ("pre\n", "post\n")
714
-
715
- regdir = os.path.join(tmp, "registry")
716
- os.makedirs(regdir, exist_ok=True)
717
- task_path = os.path.join(regdir, "auto.lua")
718
- prefix_note = "-- hand written note before the blocks\n"
719
- suffix_note = "-- hand written trailer kept verbatim\n"
720
- with open(task_path, "wb") as handle:
721
- handle.write((reg.REGISTRY_HEADER + prefix_note).encode("utf-8"))
722
-
723
- task_registry = reg.TaskRegistry(task_path)
724
- assert task_registry.path == reg.resolve_registry_path(task_path)
725
- definition = task_registry.upsert(
726
- "inspect-example", request_id="req-1", revision="rev-1",
727
- source='print("caf' + "\u00e9" + '")' + "\n", created_at=1)
728
- assert prefix_note in open(task_path, "r", encoding="ascii").read()
729
- disk = open(task_path, "rb").read()
730
- assert definition["sourceBytes"] == len(
731
- ('print("caf' + "\u00e9" + '")' + "\n").encode("utf-8"))
732
- assert definition["fileHash"] == hashlib.sha256(disk).hexdigest()
733
- assert all(byte < 128 for byte in disk), "registry must stay ASCII"
734
- assert b"\r" not in disk
735
- text = disk.decode("ascii")
736
- assert prefix_note in text, "content before the blocks lost"
737
- assert task_registry.read()["inspect-example"]["source"] == \
738
- 'print("caf' + "\u00e9" + '")' + "\n"
739
- assert "\\195\\169" in text, "non-ASCII source must be escaped as \\ddd"
740
-
741
- # A human trailer after the blocks must survive every later write.
742
- with open(task_path, "a", encoding="utf-8") as handle:
743
- handle.write(suffix_note)
744
- second = task_registry.upsert("second-task", request_id="req-2", revision="rev-2",
745
- source="return 1", created_at=2)
746
- assert second["fileHash"] == hashlib.sha256(open(task_path, "rb").read()).hexdigest()
747
- text = open(task_path, "r", encoding="ascii").read()
748
- assert prefix_note in text and suffix_note in text, "content outside blocks lost"
749
- assert text.startswith(reg.REGISTRY_HEADER + prefix_note)
750
- assert text.endswith(suffix_note), "trailer after the blocks was lost"
751
- assert list(task_registry.read()) == ["inspect-example", "second-task"]
752
- task_registry.upsert("second-task", request_id="req-3", revision="rev-3",
753
- source="return 2", created_at=3)
754
- definitions = task_registry.read()
755
- assert definitions["second-task"]["revision"] == "rev-3"
756
- assert definitions["inspect-example"]["revision"] == "rev-1"
757
- assert prefix_note in open(task_path, "r", encoding="ascii").read()
758
- expect_failure(
759
- "revision conflict",
760
- lambda: task_registry.upsert("second-task", request_id="req-4",
761
- revision="rev-4", source="return 3",
762
- created_at=4, expect_revision="rev-1"),
763
- reg.RegistryError)
764
- assert task_registry.remove("second-task")
765
- text_after_remove = open(task_path, "r", encoding="ascii").read()
766
- assert prefix_note in text_after_remove and suffix_note in text_after_remove
767
- assert list(task_registry.read()) == ["inspect-example"]
768
- assert not task_registry.remove("second-task")
769
- print("registry schema/kind rejection, fileHash, region preservation OK")
770
-
771
- link_path = os.path.join(tmp, "registry-link")
772
- linked = False
773
- try:
774
- os.symlink(regdir, link_path, target_is_directory=True)
775
- linked = True
776
- except (OSError, NotImplementedError, AttributeError):
777
- pass
778
- if not linked:
779
- # Junctions need no elevated privilege; used as the Windows fallback.
780
- linked = (os.system('cmd /c mklink /J "' + link_path + '" "' + regdir
781
- + '" >nul 2>nul') == 0 and os.path.isdir(link_path))
782
- if linked:
783
- resolved = reg.TaskRegistry(os.path.join(link_path, "auto.lua"))
784
- assert resolved.path == task_registry.path, (resolved.path, task_registry.path)
785
- assert resolved.read() == task_registry.read()
786
- print("symlink/junction path resolution OK")
787
- else:
788
- print("symlink/junction resolution check skipped (no link support)")
789
-
790
- # --- task upsert through the CLI (non-ASCII source, byte-exact sourceBytes) ---
791
-
792
- cli_dir = os.path.join(tmp, "cli-install")
793
- auto_dir = os.path.join(cli_dir, "Modules", "Automation", "auto")
794
- os.makedirs(auto_dir, exist_ok=True)
795
- source_file = os.path.join(tmp, "probe.lua")
796
- source_text = 'print("caf\u00e9")\r\nreturn { ok = true }\n'
797
- with open(source_file, "wb") as handle:
798
- handle.write(source_text.encode("utf-8"))
799
- auto_path = os.path.join(auto_dir, "auto.lua")
800
- code = cli.main(["task", "upsert", "--install-dir", cli_dir, "--id", "probe-one",
801
- "--source-file", source_file, "--request-id", "req-cli-1",
802
- "--revision", "rev-cli-1"])
803
- assert code == 0, code
804
- cli_registry = reg.TaskRegistry(auto_path)
805
- cli_definition = cli_registry.read()["probe-one"]
806
- assert cli_definition["source"] == source_text, "CRLF source bytes changed"
807
- assert cli_definition["sourceBytes"] == len(source_text.encode("utf-8"))
808
- assert all(byte < 128 for byte in open(auto_path, "rb").read())
809
- assert cli.main(["task", "list", "--install-dir", cli_dir]) == 0
810
- assert cli.main(["task", "remove", "--install-dir", cli_dir, "--id", "probe-one"]) == 0
811
- assert cli_registry.read() == {}
812
- print("CLI task upsert keeps non-ASCII/CRLF source byte-exact OK")
813
-
814
- # --- profile set + sv find resolve the client folder --------------------------
815
-
816
- wow_root = os.path.join(tmp, "wow")
817
- account_dir = os.path.join(wow_root, "_retail_", "WTF", "Account", "TESTACCOUNT",
818
- "SavedVariables")
819
- os.makedirs(account_dir, exist_ok=True)
820
- expected_sv = os.path.join(account_dir, "Lychee Dev.lua")
821
- with open(expected_sv, "wb") as handle:
822
- handle.write(b"LycheeDevDB = {}\n")
823
- addon_install = os.path.join(tmp, "addon-install")
824
- os.makedirs(addon_install, exist_ok=True)
825
- profile_data = os.path.join(tmp, "profile-data")
826
- assert cli.main(["--data-dir", profile_data, "profile", "set", "--name", "retail-main",
827
- "--client", "retail", "--wow-root", wow_root,
828
- "--addon-dir", addon_install, "--sv-path", expected_sv]) == 0
829
- out = io.StringIO()
830
- with contextlib.redirect_stdout(out):
831
- assert cli.main(["--data-dir", profile_data, "sv", "find",
832
- "--profile", "retail-main"]) == 0
833
- assert out.getvalue().strip() == expected_sv, out.getvalue()
834
-
835
- # A profile may point straight at the client folder instead of the WoW root.
836
- with contextlib.redirect_stdout(out):
837
- assert cli.main(["--data-dir", profile_data, "profile", "set", "--name", "direct",
838
- "--client", "retail",
839
- "--wow-root", os.path.join(wow_root, "_retail_"),
840
- "--addon-dir", addon_install]) == 0
841
- with contextlib.redirect_stdout(out):
842
- assert cli.main(["--data-dir", profile_data, "sv", "find", "--profile", "direct"]) == 0
843
- assert expected_sv in out.getvalue()
844
- assert cli.main(["--data-dir", profile_data, "sv", "find", "--profile", "missing"]) == 1
845
- print("profile set + sv find resolve the client folder OK")
846
-
847
- # --- send: host log first, reload dedup, explicit input failure ---------------
848
-
849
- send_data = os.path.join(tmp, "send-data")
850
-
851
-
852
- class _FakeSendWindows:
853
- class WindowIdentityError(Exception):
854
- pass
855
-
856
- class InputError(Exception):
857
- pass
858
-
859
- sent = []
860
- modes = []
861
-
862
- @classmethod
863
- def send_command(cls, hwnd, text, pid=None, exe_path=None, mode="foreground"):
864
- cls.sent.append((hwnd, text))
865
- cls.modes.append(mode)
866
-
867
-
868
- class _FailingSendWindows:
869
- class WindowIdentityError(Exception):
870
- pass
871
-
872
- class InputError(Exception):
873
- pass
874
-
875
- @staticmethod
876
- def send_command(hwnd, text, pid=None, exe_path=None, mode="foreground"):
877
- raise _FailingSendWindows.WindowIdentityError("window identity changed")
878
-
879
-
880
- original_window_module = cli._window_module
881
- try:
882
- cli._window_module = lambda: _FakeSendWindows
883
- reload_call = ["--data-dir", send_data, "--installation", "send-scope", "send",
884
- "--hwnd", "0x1", "--text", "/reload",
885
- "--request-id", "req-send-1", "--ticket", "LYCHEE-SEND-1"]
886
- assert cli.main(reload_call) == 0
887
- assert cli.main(reload_call) == 1, "second reload for one notice must be refused"
888
- assert cli.main(["--data-dir", send_data, "send", "--hwnd", "0x1",
889
- "--text", "/dev auto status x"]) == 0
890
- scoped = [r["event"] for r in
891
- ses.Session(data_dir=send_data, installation="send-scope").read_events()]
892
- assert scoped.count("reload_requested") == 1, scoped
893
- assert scoped.count("command_sent") == 1, scoped
894
- every = ses.Session(data_dir=send_data).read_events(
895
- installation=ses.ALL_INSTALLATIONS)
896
- assert [r["event"] for r in every].count("command_sent") == 2
897
- assert _FakeSendWindows.sent == [(1, "/reload"), (1, "/dev auto status x")]
898
- assert _FakeSendWindows.modes == ["foreground", "foreground"], _FakeSendWindows.modes
899
- assert cli.main(["--data-dir", send_data, "send", "--hwnd", "0x1",
900
- "--mode", "messages", "--text", "hi"]) == 0
901
- assert _FakeSendWindows.modes[-1] == "messages", _FakeSendWindows.modes
902
-
903
- cli._window_module = lambda: _FailingSendWindows
904
- assert cli.main(["--data-dir", send_data, "send", "--hwnd", "0x1",
905
- "--text", "/dev"]) == 4
906
- failed = [r["event"] for r in ses.Session(data_dir=send_data).read_events(
907
- installation=ses.ALL_INSTALLATIONS)]
908
- assert "command_failed" in failed, failed
909
- finally:
910
- cli._window_module = original_window_module
911
- print("send host log + reload dedup + input failure exit OK")
912
-
913
- # --- packaging metadata -------------------------------------------------------
914
-
915
- requirements = os.path.join(HERE, "requirements.txt")
916
- assert os.path.isfile(requirements), requirements
917
- requirements_text = open(requirements, "r", encoding="utf-8").read()
918
- for pinned in ("zxing-cpp==3.1.1", "windows-capture==2.0.1", "numpy==2.5.3"):
919
- assert pinned in requirements_text, pinned
920
- gitignore = open(os.path.join(WORKTREE, ".gitignore"), "r", encoding="utf-8").read()
921
- assert "__pycache__/" in gitignore and "*.pyc" in gitignore
922
- print("requirements.txt pins + .gitignore pycache entries OK")
923
-
924
- # --- real optional dependencies (only when importable) ------------------------
925
-
926
- try:
927
- import inspect
928
- import numpy as np
929
- import windows_capture
930
- import zxingcpp
931
- from automation import windows as win
932
- except ImportError as error:
933
- print("optional live-window dependency checks skipped: " + str(error))
934
- else:
935
- assert callable(getattr(zxingcpp, "read_barcodes", None))
936
- assert not hasattr(zxingcpp, "read_bars")
937
- assert callable(getattr(windows_capture.WindowsCapture, "on_frame_arrived", None))
938
- assert callable(getattr(windows_capture.WindowsCapture, "on_closed", None))
939
- assert callable(getattr(windows_capture.WindowsCapture, "start_free_threaded", None))
940
- assert callable(getattr(windows_capture.Frame, "convert_to_bgr", None))
941
- assert callable(getattr(windows_capture.Frame, "crop", None))
942
- capture_parameters = inspect.signature(
943
- windows_capture.WindowsCapture.__init__).parameters
944
- assert "window_hwnd" in capture_parameters
945
- assert "minimum_update_interval" in capture_parameters
946
- assert win.INPUT_SIZE == (40 if ctypes.sizeof(ctypes.c_void_p) == 8 else 28)
947
- assert win.user32.GetClipboardData.restype is ctypes.c_void_p
948
- assert win.kernel32.GlobalLock.restype is ctypes.c_void_p
949
- assert win.kernel32.OpenProcess.restype is ctypes.c_void_p
950
- assert win.user32.SendInput.argtypes[1] == ctypes.POINTER(win.INPUT)
951
- barcode = zxingcpp.create_barcode(notice_json(), zxingcpp.BarcodeFormat.QRCode)
952
- qr_image = np.asarray(zxingcpp.write_barcode_to_image(barcode))
953
- assert win.decode_qr(qr_image, zxingcpp) == [notice_json()]
954
- assert win.decode_qr(qr_image, None) == [notice_json()]
955
-
956
- class _FakeCaptureObject:
957
- frame_handler = None
958
- closed_handler = None
959
-
960
- # The real Frame class drives the exact ROI path used on live frames.
961
- real_frame = windows_capture.Frame(np.zeros((20, 20, 4), dtype=np.uint8), 20, 20, 0)
962
- capture = win.NoticeCapture(_FakeCaptureObject(), np, hwnd=0)
963
- capture._on_frame(real_frame)
964
- roi = capture.latest_roi()
965
- assert capture.last_frame_error is None, capture.last_frame_error
966
- # Derive the expected ROI from the configured fractions instead of freezing
967
- # one shape: the corner the notice uses has changed once already.
968
- expect_top, expect_left, expect_bottom, expect_right = win.NOTICE_ROI_FRACTIONS
969
- expect_h = int(20 * expect_bottom) - int(20 * expect_top)
970
- expect_w = int(20 * expect_right) - int(20 * expect_left)
971
- assert roi is not None and roi.shape == (expect_h, expect_w, 3), (
972
- roi.shape, (expect_h, expect_w, 3))
973
- assert capture.window_closed is False
974
- capture._on_closed()
975
- assert capture.window_closed is True
976
- assert "read_bars(" not in open(win.__file__, "r", encoding="utf-8").read()
977
- print("real zxing-cpp/windows-capture API checks OK")
978
-
979
- print("saved_variables + session OK")
980
-
981
-
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
+ # --- command delivery order: open chat, paste, submit ------------------------
482
+ #
483
+ # Regression: the sequence used to paste BEFORE opening the chat box, so the
484
+ # client opened an empty chat and no command ran. Reference behaviour is
485
+ # Return -> Ctrl+V -> Return.
486
+
487
+ try:
488
+ from automation import windows as winmod
489
+ except Exception: # pragma: no cover - non-Windows hosts
490
+ winmod = None
491
+
492
+ if winmod is None: # pragma: no cover - non-Windows hosts
493
+ print("command delivery order (skipped: no windows module)")
494
+ else:
495
+ class _RecordingClipboard:
496
+ def __init__(self):
497
+ self.value = None
498
+ self.writes = []
499
+
500
+ def read_text(self):
501
+ return self.value
502
+
503
+ def copy_text(self, text):
504
+ self.value = text
505
+ self.writes.append(text)
506
+
507
+ def clear(self):
508
+ self.value = None
509
+
510
+ pressed = []
511
+ real_send_key = winmod._send_key
512
+ real_set_fg = winmod.user32.SetForegroundWindow
513
+ real_is_foreground = winmod.is_foreground
514
+ real_confirm = winmod.confirm_window
515
+ real_sleep = winmod.time.sleep
516
+ try:
517
+ def fake_send_key(vk, *, ctrl=False):
518
+ pressed.append(("ctrl+v" if ctrl else "key") + ":%#x" % vk)
519
+
520
+ winmod._send_key = fake_send_key
521
+ winmod.user32.SetForegroundWindow = lambda _hwnd: 1
522
+ winmod.is_foreground = lambda _hwnd: True
523
+ winmod.confirm_window = lambda *a, **k: None
524
+ winmod.time.sleep = lambda _seconds: None
525
+
526
+ delivery_clipboard = _RecordingClipboard()
527
+ winmod.send_command(1, "/reload", clipboard=delivery_clipboard)
528
+ expected = ["key:0xd", "ctrl+v:0x56", "key:0xd"]
529
+ assert pressed == expected, f"delivery order was {pressed}, expected {expected}"
530
+ assert delivery_clipboard.writes[0] == "/reload", delivery_clipboard.writes
531
+ finally:
532
+ winmod._send_key = real_send_key
533
+ winmod.user32.SetForegroundWindow = real_set_fg
534
+ winmod.is_foreground = real_is_foreground
535
+ winmod.confirm_window = real_confirm
536
+ winmod.time.sleep = real_sleep
537
+ print("command delivery order (Return, Ctrl+V, Return) OK")
538
+
539
+ posted = []
540
+ real_post = winmod.user32.PostMessageW
541
+ real_sleep_messages = winmod.time.sleep
542
+ try:
543
+ winmod.user32.PostMessageW = (
544
+ lambda hwnd, msg, wparam, lparam: posted.append((msg, wparam)) or 1)
545
+ winmod.time.sleep = lambda _seconds: None
546
+ winmod.send_command_messages(1, "/reload")
547
+ finally:
548
+ winmod.user32.PostMessageW = real_post
549
+ winmod.time.sleep = real_sleep_messages
550
+
551
+ chars = "".join(chr(w) for m, w in posted if m == winmod.WM_CHAR)
552
+ assert chars == "/reload", chars
553
+ down = [w for m, w in posted if m == winmod.WM_KEYDOWN]
554
+ assert down == [winmod.VK_RETURN], down
555
+ assert all(m in (winmod.WM_CHAR, winmod.WM_KEYDOWN, winmod.WM_KEYUP)
556
+ for m, _w in posted), posted
557
+ print("command delivery via posted messages (no foreground) OK")
558
+
559
+ # The notice is drawn at the top-left corner of the game window, so the scan
560
+ # area must cover that corner. A ROI that drifts back to another corner makes
561
+ # the whole receipt path fail silently (capture finds no code, times out).
562
+ top, left, bottom, right = winmod.NOTICE_ROI_FRACTIONS
563
+ assert top == 0.0 and left == 0.0, (top, left)
564
+ assert 0.0 < bottom <= 0.5 and 0.0 < right <= 0.5, (bottom, right)
565
+ print("notice ROI covers the top-left corner OK")
566
+
567
+ # Keep the Lua anchor and the Python ROI in sync: both corners must match.
568
+ overlay = os.path.join(WORKTREE, "add-on", "UI", "AutomationOverlay.lua")
569
+ if os.path.isfile(overlay):
570
+ overlay_text = open(overlay, encoding="utf-8").read()
571
+ assert 'noticeFrame:SetPoint("TOPLEFT", UIParent, "TOPLEFT"' in overlay_text, \
572
+ "the Lua notice anchor is not TOPLEFT"
573
+ assert "SetPoint(\"TOPRIGHT\", UIParent, \"TOPRIGHT\"" not in overlay_text, \
574
+ "the Lua notice still anchors to TOPRIGHT while the ROI scans TOPLEFT"
575
+ print("Lua notice anchor and Python ROI agree on the top-left corner OK")
576
+
577
+ # --- host read acknowledgement ------------------------------------------------
578
+ #
579
+ # The plugin cannot see whether the host read a result, so the host says so with
580
+ # an in-game chat command through the already working delivery channel.
581
+
582
+ assert cli.ack_command("LYCHEE-1", "received") == "/dev auto ack LYCHEE-1 received"
583
+ assert cli.ack_command("LYCHEE-1", "failed") == "/dev auto ack LYCHEE-1 failed"
584
+ for bad in ("ok", "RECEIVED", ""):
585
+ try:
586
+ cli.ack_command("LYCHEE-1", bad)
587
+ raise SystemExit(f"ack accepted an invalid status: {bad!r}")
588
+ except cli.CliError:
589
+ pass
590
+ ack_help = cli.build_parser()._subparsers._group_actions[0].choices["ack"].format_help()
591
+ assert "--ticket" in ack_help and "--status" in ack_help
592
+ assert "received" in ack_help
593
+ print("ack command shape and status validation OK")
594
+
595
+ # --- notice validation and identity -------------------------------------------
596
+
597
+ def notice_json(**overrides):
598
+ payload = {"v": 1, "ticket": ticket, "task": "inspect-example",
599
+ "run": "req-20260912-000001-aaaaaa", "ts": 1789207200}
600
+ payload.update(overrides)
601
+ return json.dumps(payload)
602
+
603
+
604
+ notice = cli.validate_notice(notice_json())
605
+ assert cli.notice_identity_problems(notice, expected_task="inspect-example",
606
+ expected_run=notice["run"]) == []
607
+ assert cli.notice_identity_problems(notice, expected_task="other",
608
+ expected_run=notice["run"])
609
+ assert cli.notice_identity_problems(notice, expected_task=None,
610
+ expected_run="stale-run")
611
+ for bad in (json.dumps({"v": 2, "ticket": ticket, "task": "t", "run": "r", "ts": 1}),
612
+ json.dumps({"ticket": ticket, "task": "t", "run": "r", "ts": 1}),
613
+ notice_json(ts=0),
614
+ notice_json(ts=True),
615
+ notice_json(ticket="nope"),
616
+ notice_json(task="bad/id"),
617
+ notice_json(run="bad run"),
618
+ notice_json(ticket="L" * 65),
619
+ "",
620
+ "not json"):
621
+ expect_failure("bad notice " + str(bad)[:24],
622
+ lambda payload=bad: cli.validate_notice(payload),
623
+ sv.SavedVariablesError)
624
+ print("notice validation + task/run identity checks OK")
625
+
626
+
627
+ class _FakeCapture:
628
+ def __init__(self):
629
+ self.window_closed = False
630
+ self.polls = 0
631
+
632
+ def __enter__(self):
633
+ return self
634
+
635
+ def __exit__(self, *_exc):
636
+ return False
637
+
638
+ def latest_roi(self):
639
+ self.polls += 1
640
+ return self if self.polls <= 2 else None
641
+
642
+
643
+ class _FakeWindows:
644
+ def __init__(self, batches):
645
+ self.batches = list(batches)
646
+ self.opened = 0
647
+
648
+ def open_notice_capture(self, hwnd, **kwargs):
649
+ self.opened += 1
650
+ return _FakeCapture()
651
+
652
+ def decode_qr(self, roi):
653
+ return self.batches.pop(0) if self.batches else []
654
+
655
+
656
+ poll_args = argparse.Namespace(hwnd=1, timeout=1.0, interval=0.001, pid=None,
657
+ exe_path=None)
658
+ stale = notice_json(task="older-task", run="older-run",
659
+ ticket="LYCHEE-20260912-170000-0009")
660
+ fresh = notice_json()
661
+ fake_session = ses.Session(data_dir=os.path.join(tmp, "poll"), installation="retry")
662
+ fake_session_dirs = fake_session.data_dir
663
+ os.makedirs(fake_session_dirs, exist_ok=True)
664
+ fake_windows = _FakeWindows([[stale], [fresh]])
665
+ resolved = cli.poll_notice(fake_windows, fake_session, poll_args,
666
+ expected_task="inspect-example",
667
+ expected_run="req-20260912-000001-aaaaaa")
668
+ assert resolved is not None and resolved["ticket"] == ticket, resolved
669
+ assert fake_windows.opened == 1, "one capture session must serve the whole poll"
670
+ events = [r["event"] for r in fake_session.read_events()]
671
+ assert "notice_identity_mismatch" in events and "notice_seen" in events, events
672
+
673
+ timeout_session = ses.Session(data_dir=os.path.join(tmp, "poll-timeout"),
674
+ installation="retry")
675
+ os.makedirs(timeout_session.data_dir, exist_ok=True)
676
+ timeout_args = argparse.Namespace(hwnd=1, timeout=0.2, interval=0.001, pid=None,
677
+ exe_path=None)
678
+ started = time.monotonic()
679
+ assert cli.poll_notice(_FakeWindows([]), timeout_session, timeout_args,
680
+ expected_task="x") is None
681
+ assert 0.15 < time.monotonic() - started < 5.0
682
+ timeout_events = [r["event"] for r in timeout_session.read_events()]
683
+ assert "notice_seen" not in timeout_events
684
+ print("poll_notice: stale notice rejected, fresh accepted, timeout bounded OK")
685
+
686
+ # --- registry: schema/kind rejection, hash, region preservation ---------------
687
+
688
+ def registry_text(*blocks):
689
+ return reg.REGISTRY_HEADER + "".join(blocks)
690
+
691
+
692
+ block = "\n".join(reg.build_block(
693
+ "inspect-example", request_id="req-1", revision="rev-1",
694
+ source='print("hi")', created_at=1)) + "\n"
695
+
696
+ expect_failure("schema 9 rejected",
697
+ lambda: reg.parse_blocks(reg.REGISTRY_HEADER + block.replace(
698
+ "schema = 1,", "schema = 9,")),
699
+ reg.RegistryError)
700
+ expect_failure("kind rejected",
701
+ lambda: reg.parse_blocks(reg.REGISTRY_HEADER + block.replace(
702
+ 'kind = "lua",', 'kind = "nope",')),
703
+ reg.RegistryError)
704
+ expect_failure("unterminated block rejected",
705
+ lambda: reg.parse_blocks(reg.REGISTRY_HEADER + block.replace(
706
+ reg.END_MARKER + "inspect-example\n", "")),
707
+ reg.RegistryError)
708
+ expect_failure("unexpected block footer rejected",
709
+ lambda: reg.parse_blocks(reg.REGISTRY_HEADER + block.replace(
710
+ "\n}\n" + reg.END_MARKER, "\n" + reg.END_MARKER)),
711
+ reg.RegistryError)
712
+ assert reg.split_regions("head\nbody\n") == ("head\nbody\n", "")
713
+ assert reg.split_regions("pre\n" + block + "post\n") == ("pre\n", "post\n")
714
+
715
+ regdir = os.path.join(tmp, "registry")
716
+ os.makedirs(regdir, exist_ok=True)
717
+ task_path = os.path.join(regdir, "auto.lua")
718
+ prefix_note = "-- hand written note before the blocks\n"
719
+ suffix_note = "-- hand written trailer kept verbatim\n"
720
+ with open(task_path, "wb") as handle:
721
+ handle.write((reg.REGISTRY_HEADER + prefix_note).encode("utf-8"))
722
+
723
+ task_registry = reg.TaskRegistry(task_path)
724
+ assert task_registry.path == reg.resolve_registry_path(task_path)
725
+ definition = task_registry.upsert(
726
+ "inspect-example", request_id="req-1", revision="rev-1",
727
+ source='print("caf' + "\u00e9" + '")' + "\n", created_at=1)
728
+ assert prefix_note in open(task_path, "r", encoding="ascii").read()
729
+ disk = open(task_path, "rb").read()
730
+ assert definition["sourceBytes"] == len(
731
+ ('print("caf' + "\u00e9" + '")' + "\n").encode("utf-8"))
732
+ assert definition["fileHash"] == hashlib.sha256(disk).hexdigest()
733
+ assert all(byte < 128 for byte in disk), "registry must stay ASCII"
734
+ assert b"\r" not in disk
735
+ text = disk.decode("ascii")
736
+ assert prefix_note in text, "content before the blocks lost"
737
+ assert task_registry.read()["inspect-example"]["source"] == \
738
+ 'print("caf' + "\u00e9" + '")' + "\n"
739
+ assert "\\195\\169" in text, "non-ASCII source must be escaped as \\ddd"
740
+
741
+ # A human trailer after the blocks must survive every later write.
742
+ with open(task_path, "a", encoding="utf-8") as handle:
743
+ handle.write(suffix_note)
744
+ second = task_registry.upsert("second-task", request_id="req-2", revision="rev-2",
745
+ source="return 1", created_at=2)
746
+ assert second["fileHash"] == hashlib.sha256(open(task_path, "rb").read()).hexdigest()
747
+ text = open(task_path, "r", encoding="ascii").read()
748
+ assert prefix_note in text and suffix_note in text, "content outside blocks lost"
749
+ assert text.startswith(reg.REGISTRY_HEADER + prefix_note)
750
+ assert text.endswith(suffix_note), "trailer after the blocks was lost"
751
+ assert list(task_registry.read()) == ["inspect-example", "second-task"]
752
+ task_registry.upsert("second-task", request_id="req-3", revision="rev-3",
753
+ source="return 2", created_at=3)
754
+ definitions = task_registry.read()
755
+ assert definitions["second-task"]["revision"] == "rev-3"
756
+ assert definitions["inspect-example"]["revision"] == "rev-1"
757
+ assert prefix_note in open(task_path, "r", encoding="ascii").read()
758
+ expect_failure(
759
+ "revision conflict",
760
+ lambda: task_registry.upsert("second-task", request_id="req-4",
761
+ revision="rev-4", source="return 3",
762
+ created_at=4, expect_revision="rev-1"),
763
+ reg.RegistryError)
764
+ assert task_registry.remove("second-task")
765
+ text_after_remove = open(task_path, "r", encoding="ascii").read()
766
+ assert prefix_note in text_after_remove and suffix_note in text_after_remove
767
+ assert list(task_registry.read()) == ["inspect-example"]
768
+ assert not task_registry.remove("second-task")
769
+ print("registry schema/kind rejection, fileHash, region preservation OK")
770
+
771
+ link_path = os.path.join(tmp, "registry-link")
772
+ linked = False
773
+ try:
774
+ os.symlink(regdir, link_path, target_is_directory=True)
775
+ linked = True
776
+ except (OSError, NotImplementedError, AttributeError):
777
+ pass
778
+ if not linked:
779
+ # Junctions need no elevated privilege; used as the Windows fallback.
780
+ linked = (os.system('cmd /c mklink /J "' + link_path + '" "' + regdir
781
+ + '" >nul 2>nul') == 0 and os.path.isdir(link_path))
782
+ if linked:
783
+ resolved = reg.TaskRegistry(os.path.join(link_path, "auto.lua"))
784
+ assert resolved.path == task_registry.path, (resolved.path, task_registry.path)
785
+ assert resolved.read() == task_registry.read()
786
+ print("symlink/junction path resolution OK")
787
+ else:
788
+ print("symlink/junction resolution check skipped (no link support)")
789
+
790
+ # --- task upsert through the CLI (non-ASCII source, byte-exact sourceBytes) ---
791
+
792
+ cli_dir = os.path.join(tmp, "cli-install")
793
+ auto_dir = os.path.join(cli_dir, "Modules", "Automation", "auto")
794
+ os.makedirs(auto_dir, exist_ok=True)
795
+ source_file = os.path.join(tmp, "probe.lua")
796
+ source_text = 'print("caf\u00e9")\r\nreturn { ok = true }\n'
797
+ with open(source_file, "wb") as handle:
798
+ handle.write(source_text.encode("utf-8"))
799
+ auto_path = os.path.join(auto_dir, "auto.lua")
800
+ code = cli.main(["task", "upsert", "--install-dir", cli_dir, "--id", "probe-one",
801
+ "--source-file", source_file, "--request-id", "req-cli-1",
802
+ "--revision", "rev-cli-1"])
803
+ assert code == 0, code
804
+ cli_registry = reg.TaskRegistry(auto_path)
805
+ cli_definition = cli_registry.read()["probe-one"]
806
+ assert cli_definition["source"] == source_text, "CRLF source bytes changed"
807
+ assert cli_definition["sourceBytes"] == len(source_text.encode("utf-8"))
808
+ assert all(byte < 128 for byte in open(auto_path, "rb").read())
809
+ assert cli.main(["task", "list", "--install-dir", cli_dir]) == 0
810
+ assert cli.main(["task", "remove", "--install-dir", cli_dir, "--id", "probe-one"]) == 0
811
+ assert cli_registry.read() == {}
812
+ print("CLI task upsert keeps non-ASCII/CRLF source byte-exact OK")
813
+
814
+ # --- profile set + sv find resolve the client folder --------------------------
815
+
816
+ wow_root = os.path.join(tmp, "wow")
817
+ account_dir = os.path.join(wow_root, "_retail_", "WTF", "Account", "TESTACCOUNT",
818
+ "SavedVariables")
819
+ os.makedirs(account_dir, exist_ok=True)
820
+ expected_sv = os.path.join(account_dir, "Lychee Dev.lua")
821
+ with open(expected_sv, "wb") as handle:
822
+ handle.write(b"LycheeDevDB = {}\n")
823
+ addon_install = os.path.join(tmp, "addon-install")
824
+ os.makedirs(addon_install, exist_ok=True)
825
+ profile_data = os.path.join(tmp, "profile-data")
826
+ assert cli.main(["--data-dir", profile_data, "profile", "set", "--name", "retail-main",
827
+ "--client", "retail", "--wow-root", wow_root,
828
+ "--addon-dir", addon_install, "--sv-path", expected_sv]) == 0
829
+ out = io.StringIO()
830
+ with contextlib.redirect_stdout(out):
831
+ assert cli.main(["--data-dir", profile_data, "sv", "find",
832
+ "--profile", "retail-main"]) == 0
833
+ assert out.getvalue().strip() == expected_sv, out.getvalue()
834
+
835
+ # A profile may point straight at the client folder instead of the WoW root.
836
+ with contextlib.redirect_stdout(out):
837
+ assert cli.main(["--data-dir", profile_data, "profile", "set", "--name", "direct",
838
+ "--client", "retail",
839
+ "--wow-root", os.path.join(wow_root, "_retail_"),
840
+ "--addon-dir", addon_install]) == 0
841
+ with contextlib.redirect_stdout(out):
842
+ assert cli.main(["--data-dir", profile_data, "sv", "find", "--profile", "direct"]) == 0
843
+ assert expected_sv in out.getvalue()
844
+ assert cli.main(["--data-dir", profile_data, "sv", "find", "--profile", "missing"]) == 1
845
+ print("profile set + sv find resolve the client folder OK")
846
+
847
+ # --- send: host log first, reload dedup, explicit input failure ---------------
848
+
849
+ send_data = os.path.join(tmp, "send-data")
850
+
851
+
852
+ class _FakeSendWindows:
853
+ class WindowIdentityError(Exception):
854
+ pass
855
+
856
+ class InputError(Exception):
857
+ pass
858
+
859
+ sent = []
860
+ modes = []
861
+
862
+ @classmethod
863
+ def send_command(cls, hwnd, text, pid=None, exe_path=None, mode="foreground"):
864
+ cls.sent.append((hwnd, text))
865
+ cls.modes.append(mode)
866
+
867
+
868
+ class _FailingSendWindows:
869
+ class WindowIdentityError(Exception):
870
+ pass
871
+
872
+ class InputError(Exception):
873
+ pass
874
+
875
+ @staticmethod
876
+ def send_command(hwnd, text, pid=None, exe_path=None, mode="foreground"):
877
+ raise _FailingSendWindows.WindowIdentityError("window identity changed")
878
+
879
+
880
+ original_window_module = cli._window_module
881
+ try:
882
+ cli._window_module = lambda: _FakeSendWindows
883
+ reload_call = ["--data-dir", send_data, "--installation", "send-scope", "send",
884
+ "--hwnd", "0x1", "--text", "/reload",
885
+ "--request-id", "req-send-1", "--ticket", "LYCHEE-SEND-1"]
886
+ assert cli.main(reload_call) == 0
887
+ assert cli.main(reload_call) == 1, "second reload for one notice must be refused"
888
+ assert cli.main(["--data-dir", send_data, "send", "--hwnd", "0x1",
889
+ "--text", "/dev auto status x"]) == 0
890
+ scoped = [r["event"] for r in
891
+ ses.Session(data_dir=send_data, installation="send-scope").read_events()]
892
+ assert scoped.count("reload_requested") == 1, scoped
893
+ assert scoped.count("command_sent") == 1, scoped
894
+ every = ses.Session(data_dir=send_data).read_events(
895
+ installation=ses.ALL_INSTALLATIONS)
896
+ assert [r["event"] for r in every].count("command_sent") == 2
897
+ assert _FakeSendWindows.sent == [(1, "/reload"), (1, "/dev auto status x")]
898
+ assert _FakeSendWindows.modes == ["foreground", "foreground"], _FakeSendWindows.modes
899
+ assert cli.main(["--data-dir", send_data, "send", "--hwnd", "0x1",
900
+ "--mode", "messages", "--text", "hi"]) == 0
901
+ assert _FakeSendWindows.modes[-1] == "messages", _FakeSendWindows.modes
902
+
903
+ cli._window_module = lambda: _FailingSendWindows
904
+ assert cli.main(["--data-dir", send_data, "send", "--hwnd", "0x1",
905
+ "--text", "/dev"]) == 4
906
+ failed = [r["event"] for r in ses.Session(data_dir=send_data).read_events(
907
+ installation=ses.ALL_INSTALLATIONS)]
908
+ assert "command_failed" in failed, failed
909
+ finally:
910
+ cli._window_module = original_window_module
911
+ print("send host log + reload dedup + input failure exit OK")
912
+
913
+ # --- packaging metadata -------------------------------------------------------
914
+
915
+ requirements = os.path.join(HERE, "requirements.txt")
916
+ assert os.path.isfile(requirements), requirements
917
+ requirements_text = open(requirements, "r", encoding="utf-8").read()
918
+ for pinned in ("zxing-cpp==3.1.1", "windows-capture==2.0.1", "numpy==2.5.3"):
919
+ assert pinned in requirements_text, pinned
920
+ gitignore = open(os.path.join(WORKTREE, ".gitignore"), "r", encoding="utf-8").read()
921
+ assert "__pycache__/" in gitignore and "*.pyc" in gitignore
922
+ print("requirements.txt pins + .gitignore pycache entries OK")
923
+
924
+ # --- real optional dependencies (only when importable) ------------------------
925
+
926
+ try:
927
+ import inspect
928
+ import numpy as np
929
+ import windows_capture
930
+ import zxingcpp
931
+ from automation import windows as win
932
+ except ImportError as error:
933
+ print("optional live-window dependency checks skipped: " + str(error))
934
+ else:
935
+ assert callable(getattr(zxingcpp, "read_barcodes", None))
936
+ assert not hasattr(zxingcpp, "read_bars")
937
+ assert callable(getattr(windows_capture.WindowsCapture, "on_frame_arrived", None))
938
+ assert callable(getattr(windows_capture.WindowsCapture, "on_closed", None))
939
+ assert callable(getattr(windows_capture.WindowsCapture, "start_free_threaded", None))
940
+ assert callable(getattr(windows_capture.Frame, "convert_to_bgr", None))
941
+ assert callable(getattr(windows_capture.Frame, "crop", None))
942
+ capture_parameters = inspect.signature(
943
+ windows_capture.WindowsCapture.__init__).parameters
944
+ assert "window_hwnd" in capture_parameters
945
+ assert "minimum_update_interval" in capture_parameters
946
+ assert win.INPUT_SIZE == (40 if ctypes.sizeof(ctypes.c_void_p) == 8 else 28)
947
+ assert win.user32.GetClipboardData.restype is ctypes.c_void_p
948
+ assert win.kernel32.GlobalLock.restype is ctypes.c_void_p
949
+ assert win.kernel32.OpenProcess.restype is ctypes.c_void_p
950
+ assert win.user32.SendInput.argtypes[1] == ctypes.POINTER(win.INPUT)
951
+ barcode = zxingcpp.create_barcode(notice_json(), zxingcpp.BarcodeFormat.QRCode)
952
+ qr_image = np.asarray(zxingcpp.write_barcode_to_image(barcode))
953
+ assert win.decode_qr(qr_image, zxingcpp) == [notice_json()]
954
+ assert win.decode_qr(qr_image, None) == [notice_json()]
955
+
956
+ class _FakeCaptureObject:
957
+ frame_handler = None
958
+ closed_handler = None
959
+
960
+ # The real Frame class drives the exact ROI path used on live frames.
961
+ real_frame = windows_capture.Frame(np.zeros((20, 20, 4), dtype=np.uint8), 20, 20, 0)
962
+ capture = win.NoticeCapture(_FakeCaptureObject(), np, hwnd=0)
963
+ capture._on_frame(real_frame)
964
+ roi = capture.latest_roi()
965
+ assert capture.last_frame_error is None, capture.last_frame_error
966
+ # Derive the expected ROI from the configured fractions instead of freezing
967
+ # one shape: the corner the notice uses has changed once already.
968
+ expect_top, expect_left, expect_bottom, expect_right = win.NOTICE_ROI_FRACTIONS
969
+ expect_h = int(20 * expect_bottom) - int(20 * expect_top)
970
+ expect_w = int(20 * expect_right) - int(20 * expect_left)
971
+ assert roi is not None and roi.shape == (expect_h, expect_w, 3), (
972
+ roi.shape, (expect_h, expect_w, 3))
973
+ assert capture.window_closed is False
974
+ capture._on_closed()
975
+ assert capture.window_closed is True
976
+ assert "read_bars(" not in open(win.__file__, "r", encoding="utf-8").read()
977
+ print("real zxing-cpp/windows-capture API checks OK")
978
+
979
+ print("saved_variables + session OK")
980
+
981
+