lycheedev 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/bin/lycheedev.js +257 -0
  2. package/package.json +42 -0
  3. package/src/addon.js +87 -0
  4. package/src/config.js +64 -0
  5. package/src/doctor.js +100 -0
  6. package/src/install.js +131 -0
  7. package/src/paths.js +93 -0
  8. package/src/python.js +107 -0
  9. package/src/skill.js +48 -0
  10. package/src/wow.js +110 -0
  11. package/vendor/addon/Core/Bootstrap.lua +131 -0
  12. package/vendor/addon/Core/Clients/Mainline.lua +9 -0
  13. package/vendor/addon/Core/Clients/Mists.lua +9 -0
  14. package/vendor/addon/Core/Clients/Titan.lua +9 -0
  15. package/vendor/addon/Core/Compatibility.lua +43 -0
  16. package/vendor/addon/Core/Database.lua +859 -0
  17. package/vendor/addon/Core/Inspector.lua +647 -0
  18. package/vendor/addon/Core/Locale.lua +307 -0
  19. package/vendor/addon/Core/Locale_enUS.lua +318 -0
  20. package/vendor/addon/Core/Safety.lua +42 -0
  21. package/vendor/addon/Core/Serializer.lua +324 -0
  22. package/vendor/addon/Libs/AutomationQR.lua +1176 -0
  23. package/vendor/addon/Lychee Dev_Mainline.toc +43 -0
  24. package/vendor/addon/Lychee Dev_Mists.toc +43 -0
  25. package/vendor/addon/Lychee Dev_Wrath.toc +43 -0
  26. package/vendor/addon/Media/GitHub.png +0 -0
  27. package/vendor/addon/Media/Logo.png +0 -0
  28. package/vendor/addon/Modules/Automation/Controller.lua +757 -0
  29. package/vendor/addon/Modules/Automation/Report.lua +409 -0
  30. package/vendor/addon/Modules/Automation/auto/auto.lua +12 -0
  31. package/vendor/addon/Modules/Diagnostics.lua +238 -0
  32. package/vendor/addon/Modules/Events/Catalog.lua +184 -0
  33. package/vendor/addon/Modules/Events/CatalogData_Mainline.lua +1788 -0
  34. package/vendor/addon/Modules/Events/CatalogData_Mists.lua +1489 -0
  35. package/vendor/addon/Modules/Events/CatalogData_Titan.lua +1492 -0
  36. package/vendor/addon/Modules/Events/Monitor.lua +181 -0
  37. package/vendor/addon/Modules/FunctionTrace.lua +85 -0
  38. package/vendor/addon/Modules/ObjectInspector.lua +329 -0
  39. package/vendor/addon/UI/AutomationOverlay.lua +183 -0
  40. package/vendor/addon/UI/Export.lua +140 -0
  41. package/vendor/addon/UI/Features.lua +890 -0
  42. package/vendor/addon/UI/MainWindow.lua +1145 -0
  43. package/vendor/addon/UI/Pages/About.lua +223 -0
  44. package/vendor/addon/UI/Pages/Automation.lua +417 -0
  45. package/vendor/addon/UI/Pages/Diagnostics.lua +289 -0
  46. package/vendor/addon/UI/Pages/ExportRecords.lua +387 -0
  47. package/vendor/addon/UI/Pages/Object.lua +573 -0
  48. package/vendor/addon/UI/Pages/Trace.lua +165 -0
  49. package/vendor/skill/SKILL.md +94 -0
  50. package/vendor/skill/agents/openai.yaml +4 -0
  51. package/vendor/skill/references/automation.md +327 -0
  52. package/vendor/skill/references/runtime-investigations.md +97 -0
  53. package/vendor/skill/scripts/automation/__init__.py +1 -0
  54. package/vendor/skill/scripts/automation/registry.py +516 -0
  55. package/vendor/skill/scripts/automation/saved_variables.py +438 -0
  56. package/vendor/skill/scripts/automation/session.py +207 -0
  57. package/vendor/skill/scripts/automation/windows.py +573 -0
  58. package/vendor/skill/scripts/automation.py +865 -0
  59. package/vendor/skill/scripts/requirements.txt +13 -0
  60. package/vendor/skill/scripts/selftest_offline.py +981 -0
@@ -0,0 +1,97 @@
1
+ # Bounded memory and CPU investigations through Run
2
+
3
+ Use this reference when a Lychee Dev investigation concerns memory, CPU, stutter, startup or repeated operations. The output is a question-specific script and evidence interpretation, not a replacement background profiler.
4
+
5
+ ## Define the question before the probe
6
+
7
+ Read the target project's applicable performance rules, lifecycle design and existing raw evidence. Record the current task's authorization separately: diagnosis, proposal, implementation and deployment are different scopes. A design target is not a verified property.
8
+
9
+ Establish the symptom, reproduction action, target addon and companion packages, exact client/build, addon/source revisions, language, data scale, and current profiling/GC settings. Identify already available Tickets before requesting another run. State a falsifiable hypothesis and the observation that would distinguish it from alternatives.
10
+
11
+ Check actual third-party integrations and dependency versions. An installed or referenced addon is not automatically exercised by a probe. Use statuses such as `live`, `replay`, `missing_dependency`, `failed`, `timeout`, and `not_tested` per scenario. Preserve raw evidence and failed rounds rather than selecting the fastest result.
12
+
13
+ ## Measurement meanings
14
+
15
+ | Observation | Required interpretation |
16
+ | --- | --- |
17
+ | Memory before/after with natural GC | A live observation influenced by collection and unrelated client work; not cumulative allocation or retained bytes |
18
+ | Heap growth with GC suspended | Uncollected allocation within that measured scope; not a natural-running peak or target-addon attribution |
19
+ | Heap difference after controlled GC | Retained difference for the measured scope; report global collection separately and keep the original values |
20
+ | Peak | Maximum actually observed at a stated sampling frequency; unobserved peaks remain unknown |
21
+ | Whole Lua heap / process memory | Client-wide scopes; neither equals one addon's Lua tables or native UI cost |
22
+ | Addon memory counters | State whether refreshed or cached, include companion packages, and do not equate object counts with bytes |
23
+ | Reachable object or table counts | Structural evidence and ownership clues; shared roots, unreachable closures and native allocations prevent complete byte attribution |
24
+ | Warm repetition | Previously used code and caches; rebuilding a Lua catalog does not reset game-internal caches |
25
+ | First observed round | First in this test, unless a real fresh session and startup path were verified |
26
+
27
+ A negative post-GC delta may include earlier garbage. Report no observed retained growth and the raw delta; do not advertise negative memory usage. Count creation, allocation, retained growth and native object high-water marks separately. Hiding a Frame does not prove its memory is released.
28
+
29
+ ## Separate work and observer cost
30
+
31
+ Distinguish these phases when relevant: game API acquisition, temporary capture, normalized business records, SDK validation/copy/registration, indexing, query, UI construction/rendering, Lua source compilation, native addon loading and cleanup. Mark nested timings as inclusive or exclusive; do not add a parent interval to its children. Report total completion latency and the longest uninterrupted synchronous segment, with sample count and timer resolution.
32
+
33
+ Build a baseline without instrumentation first. Measure control/observer work separately: global memory refresh, full GC, hook installation and dispatch, traversal, timer scheduling, serialization and UI refresh. A global pause is not the target addon's exclusive CPU. A profiler's addon attribution may depend on execution/driver ownership; a source filename alone is insufficient evidence. Sampled frame percentiles do not describe all frames, and the sum of periodically sampled frame CPU values is not interval CPU.
34
+
35
+ Do not default to scanning `_G`, all Frames or every object on a timer. The removed Lychee Dev capture performed global Frame enumeration and global memory refresh during capture, showing how observation can scale with unrelated UI. Code-path counts demonstrate that work; they do not prove which native API caused all user-visible stutter. Add a broader or instrumented probe only to test a specific remaining hypothesis.
36
+
37
+ Use the same inputs, runtime, warmup and measurement boundaries for comparisons. Do not combine offline SDK/index timings with live acquisition timings to calculate game first-open latency. An instrumented hotspot experiment and an uninstrumented latency baseline answer different questions; show both without treating instrumentation overhead as application cost.
38
+
39
+ ## Ownership before execution
40
+
41
+ Identify the authoritative Provider/source, current registry/index, consumer-held snapshots, persistent data, queues, subscriptions, timers and UI/native roots. Prefer a private replay instance when exercising SDK or index operations. Validate that real Provider counts/identities, index generation, business records, settings and relevant saved data remain unchanged; a private instance must not retain or mutate live record tables by alias.
42
+
43
+ Do not unregister real Providers, clear a live index, overwrite callbacks, invoke business actions, or replace global APIs just to create an experiment. If safe isolation or exact restoration is unavailable, mark that scenario untested and use a different probe. A weak-reference recovery check must not keep the test's own strong references alive.
44
+
45
+ Do not install irreversible `hooksecurefunc`/Blizzard hooks for temporary profiling. Prefer existing counters or wrappers inside an isolated harness. Save and restore any owned hook/profiling state in all exit paths. A disabled guard on an irreversible hook is not equivalent to removing it. Avoid GC policy changes unless the initial state can be established and restored on this client; Lua 5.1 does not provide every modern Lua GC query. Full GC is a separately identified diagnostic intervention, never a proposed production close handler.
46
+
47
+ ## Choose the delivery surface before measuring
48
+
49
+ A complete study is not a giant pasted source bundle. Record the actual input's bytes, line count and longest line before delivery. Syntax and isolation checks do not test native EditBox paste/layout behavior at that size. Do not hide volume in compressed, encoded or obfuscated strings. Use only a size budget supported by actual input-path evidence; do not invent a universal safe threshold.
50
+
51
+ Use Run for compact, question-specific probes. When many source files or a complex scenario harness are needed, consider an independent, opt-in diagnostic addon/carrier with normal TOC loading and a short explicit start command. Explain installation, exact load/reload requirements, dependencies, output, stop/timeout behavior and cleanup. This is a scale-based choice, not the default for every diagnosis. Loading must use verified client capabilities; the game cannot be assumed to read arbitrary external files or hot-load newly written Lua. Do not install or enable such a carrier outside the current authorization.
52
+
53
+ If a user reports an immediate paste hang before Run was clicked, investigate the input path first. Lychee Dev's editable multiline box currently has no explicit input-size cap and requests scroll geometry updates on TextChanged; its cursor update is deferred. There is no syntax coloring, line-number pass, compile, execution or history save during paste. Native paste/layout may still be expensive; the Lua path alone does not establish the stall's exact cause. Stop giant-paste retries and choose a lighter entry point. Do not blame the script's business work or GC if it never ran.
54
+
55
+ Pasted text stays in the current process's edit box, including when the same window is reopened, but is not automatically persisted or executed. History is written after an explicit Run; the existing history-code truncation is a storage rule, not proof of safe paste size. A client restart/reload must not be described as automatically replaying pasted scripts.
56
+
57
+ ## One entry point, one bounded scenario matrix
58
+
59
+ Before writing code, enumerate the scenarios and how each is reached. A useful matrix contains:
60
+
61
+ ```text
62
+ scenario id | question | live/replay/dependency | input size | phases
63
+ precondition | work/duration/output limits | external action
64
+ correctness invariant | cleanup/restore checks | expected evidence
65
+ ```
66
+
67
+ Combine the agreed automatic scenarios into one coordinated Lua 5.1 test and one report, using the delivery surface chosen above. Use finite phases with both per-batch work limits and an overall deadline, bounded traversal depth/node counts and output/retention limits. Do not install a perpetual sampler. Check combat and cancellation at phase boundaries, invalidate late callbacks by run identity, and stop all owned work before final publication. A deadline cannot preempt one long native call; exclude it or disclose that limitation.
68
+
69
+ Avoid reentry: a second execution must reject an active run or safely cancel and clean it up. Preserve the last complete result until the next run can publish a complete replacement. Missing dependencies and failed phases are evidence, not reasons to silently return an empty successful report.
70
+
71
+ Keep measured work separate from report construction, equality checks and export serialization. Run validation outside measured intervals and record its result. Report collection/filter counts, source identities and business equivalence where needed, without executing live actions to check their payloads.
72
+
73
+ A synchronous Run return is serialized when execution returns. For staged/asynchronous work, inspect the installed runner/export source and validate a completion writer before starting; do not assume a global addon namespace or a stable private API. Use one final saveable result or Ticket. If the runner's size limits would truncate the report, use a verified full-evidence export path; an on-screen excerpt is not a complete artifact. Do not solve this by silently adding another paste step to an agreed one-paste workflow.
74
+
75
+ Cold login, real combat, manual user actions and external dependencies cannot be simulated into verified coverage. One script can orchestrate or label those boundaries, but it must report what actually occurred. If another task owns a pending game probe, coordinate the runtime slot rather than altering its script, clipboard or session.
76
+
77
+ ## Validate before giving the script to the user
78
+
79
+ Validate the actual delivery path and scale separately from execution. Use `luac -p <probe.lua>` or another Lua 5.1 parser, then run a bounded offline harness at the actual entry/completion seam. Exercise normal completion, missing dependencies, errors during phases, timeout, cancellation/combat, repeat execution, stale callbacks, live-state isolation, cleanup/restoration and complete export. A syntax check alone cannot prove any of these. Use controlled mocks for failure injection; do not reproduce a severe freeze in the live client as the first test.
80
+
81
+ Report actual validation results and limits. The harness can verify sequencing and work budgets; it cannot establish native API duration, WoW GC behavior, taint safety or real rendering. Use instrumented and uninstrumented runs separately. If the script cannot safely cover a requested scenario, narrow that scenario explicitly instead of shipping an unvalidated destructive fallback.
82
+
83
+ Announce clipboard delivery and verify readback if clipboard use is authorized. Keep the delivered version stable until executed or explicitly replaced. Inspect available computer-control capabilities before use; after one unsuccessful focus/state correction, deliver one manual paste rather than retrying blind game input. Ask only for the minimum external action that remains.
84
+
85
+ ## Read and decide
86
+
87
+ Use the exact Ticket received by the owning task. Validate record-level `schema`, `source` and `environment`, then read the entire `payload.content` and separately validate any embedded report schema, script version, scenario statuses and cleanup results. Metadata may be incomplete and is never a substitute. If persistence is pending, identify the one required `/reload` or logout step; do not misreport an in-memory Ticket as missing evidence.
88
+
89
+ Separate observed facts, causal hypotheses, feasible options and unverified goals. For a memory reduction proposal, include the fixed-cost floor, recoverable source, all-package retention, restoration latency, complete query results, business equivalence and UI experience. Moving costs between packages or hiding results cannot establish success. If a target is infeasible under current evidence, explain the retained roots and trade-offs rather than weakening correctness to make the number pass.
90
+
91
+ Choose a next experiment only if it resolves a specific uncertainty. Do not run an endless collection loop once the user can make the requested decision.
92
+
93
+ ## Reference discipline
94
+
95
+ - Read the target project's `PERFORMANCE.md`, lifecycle design and validation records as project policy/evidence, preserving their stated environment and verification status. Do not hard-code a past project's memory target, local paths, provisional SDK version or plan-only authorization into future tasks.
96
+ - EllesmereUI at commit `8da5dfe182c7809e3f61b5a9ca856d16b891726f` provides concrete references: [contribution criteria](https://github.com/EllesmereGaming/EllesmereUI/blob/8da5dfe182c7809e3f61b5a9ca856d16b891726f/.github/CONTRIBUTING.md#L22-L44) for opt-in/idle cost, and [ticker ownership and unsubscribe behavior](https://github.com/EllesmereGaming/EllesmereUI/blob/8da5dfe182c7809e3f61b5a9ca856d16b891726f/EllesmereUI_Ticker.lua#L8-L115). Treat its attribution comments as upstream evidence to verify for the measured build, not a universal engine guarantee. Its single-client policy does not override Lychee Dev's client matrix.
97
+ - Verify API facts against the target's locked client source using wowdoc when needed. Tags can move: retain and use the resolved immutable commit recorded by the project. A native API's existence does not prove a particular timing or memory attribution claim.
@@ -0,0 +1 @@
1
+ """Lychee Dev automation support package (task registry, SV reader, session)."""
@@ -0,0 +1,516 @@
1
+ """Task block registry for the Lychee Dev automation task file.
2
+
3
+ The task file (``Modules/Automation/auto/auto.lua``) only ever contains Lua
4
+ data: an empty ``ns.AutomationTaskDefinitions`` table plus optional task blocks
5
+ between generated markers. This module owns reading and updating that file:
6
+
7
+ - the whole installation directory is protected by an OS-level exclusive lock
8
+ file so concurrent writers cannot interleave,
9
+ - updates replace exactly one block and keep every other block and its order,
10
+ - generated Lua stays Lua 5.1 compatible and pure ASCII (quotes, backslashes,
11
+ newlines, non-ASCII bytes and marker text are escaped),
12
+ - writes go through a temp file in the same directory followed by an atomic
13
+ replace, so a crash leaves either the complete old or the complete new file,
14
+ - the new file's SHA-256 is recorded for every successful write,
15
+ - content outside the task blocks is preserved verbatim; only the block region
16
+ is regenerated,
17
+ - the installed path is resolved through symlinks/junctions before any read or
18
+ write, so two names for one directory cannot disagree,
19
+ - the parser only accepts the data syntax this module generates; it never
20
+ executes Lua.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import hashlib
26
+ import os
27
+ import re
28
+ import tempfile
29
+ import zlib
30
+ from contextlib import contextmanager
31
+
32
+ try: # Windows-only; the registry stays importable on other hosts for tests.
33
+ import msvcrt
34
+ except ImportError: # pragma: no cover - exercised only off-Windows
35
+ msvcrt = None
36
+
37
+ try:
38
+ import fcntl
39
+ except ImportError: # pragma: no cover
40
+ fcntl = None
41
+
42
+ TASK_ID_PATTERN = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
43
+ REQUEST_ID_PATTERN = re.compile(r"^[A-Za-z0-9_.-]{1,128}$")
44
+
45
+ REGISTRY_SCHEMA_VERSION = 1
46
+ REGISTRY_KINDS = ("lua", "bug_snapshot")
47
+
48
+ MAX_BLOCKS = 16
49
+ MAX_REGISTRY_BYTES = 1024 * 1024
50
+ MAX_SOURCE_BYTES = 256 * 1024
51
+
52
+ BEGIN_MARKER = "-- BEGIN LYCHEE DEV TASK "
53
+ END_MARKER = "-- END LYCHEE DEV TASK "
54
+
55
+ REGISTRY_HEADER = """local ADDON_NAME, ns = ...
56
+
57
+ -- Automation task registry. This file contains generated data only; loading it
58
+ -- must never execute task source. Task blocks are written between the
59
+ -- BEGIN/END markers by the Lychee Dev skill tooling and are removed before
60
+ -- release packaging ships an empty registry.
61
+
62
+ ns.AutomationTaskDefinitions = ns.AutomationTaskDefinitions or {}
63
+
64
+ -- Task blocks use exactly this marker shape (task id may not contain the
65
+ -- marker text): "-- BEGIN LYCHEE DEV TASK <task-id>" ... "-- END LYCHEE DEV TASK <task-id>".
66
+ -- The skill tooling inserts and replaces them; releases ship this file empty.
67
+ """
68
+
69
+
70
+ class RegistryError(Exception):
71
+ """Raised for every expected registry failure; the old file stays intact."""
72
+
73
+
74
+ def validate_task_id(task_id: str) -> str:
75
+ if not isinstance(task_id, str) or not TASK_ID_PATTERN.match(task_id):
76
+ raise RegistryError(f"invalid task id: {task_id!r}")
77
+ return task_id
78
+
79
+
80
+ def validate_request_id(request_id: str) -> str:
81
+ if not isinstance(request_id, str) or not REQUEST_ID_PATTERN.match(request_id):
82
+ raise RegistryError(f"invalid request id: {request_id!r}")
83
+ return request_id
84
+
85
+
86
+ def escape_lua_string(text: str) -> str:
87
+ """Encode text as one Lua 5.1 double-quoted literal, ASCII only."""
88
+
89
+ out = ['"']
90
+ for byte in text.encode("utf-8"):
91
+ char = chr(byte)
92
+ if char == '"':
93
+ out.append('\\"')
94
+ elif char == "\\":
95
+ out.append("\\\\")
96
+ elif char == "\n":
97
+ out.append("\\n")
98
+ elif char == "\r":
99
+ out.append("\\r")
100
+ elif char == "\t":
101
+ out.append("\\t")
102
+ elif 0x20 <= byte <= 0x7E:
103
+ out.append(char)
104
+ else:
105
+ out.append(f"\\{byte:03d}")
106
+ out.append('"')
107
+ return "".join(out)
108
+
109
+
110
+ def unescape_lua_string(literal: str) -> str:
111
+ """Decode a Lua 5.1 double-quoted literal (without the quotes) to text."""
112
+
113
+ if not literal.startswith('"') or not literal.endswith('"') or len(literal) < 2:
114
+ raise RegistryError("expected a double-quoted Lua string literal")
115
+ body = literal[1:-1]
116
+ out = bytearray()
117
+ index = 0
118
+ while index < len(body):
119
+ char = body[index]
120
+ if char != "\\":
121
+ byte_value = ord(char)
122
+ if byte_value > 0x7E:
123
+ raise RegistryError("non-ASCII byte in string literal")
124
+ out.append(byte_value)
125
+ index += 1
126
+ continue
127
+ index += 1
128
+ if index >= len(body):
129
+ raise RegistryError("dangling escape in string literal")
130
+ escape = body[index]
131
+ simple = {'"': '"', "\\": "\\", "n": "\n", "r": "\r", "t": "\t", "a": "\a",
132
+ "b": "\b", "f": "\f", "v": "\v"}
133
+ if escape in simple:
134
+ out.extend(simple[escape].encode("utf-8"))
135
+ index += 1
136
+ elif escape in "0123456789":
137
+ # Lua 5.1 \ddd takes one to three decimal digits and must fit a byte.
138
+ match = re.match(r"[0-9]{1,3}", body[index:])
139
+ digits = match.group(0)
140
+ value = int(digits)
141
+ if value > 255:
142
+ raise RegistryError(f"decimal escape too large: \\{digits}")
143
+ out.append(value)
144
+ index += len(digits)
145
+ else:
146
+ raise RegistryError(f"unsupported escape: \\{escape}")
147
+ return out.decode("utf-8")
148
+
149
+
150
+ def adler32_hex(text: str) -> str:
151
+ return format(zlib.adler32(text.encode("utf-8")) & 0xFFFFFFFF, "08x")
152
+
153
+
154
+ def build_block(
155
+ task_id: str,
156
+ *,
157
+ request_id: str,
158
+ revision: str,
159
+ source: str,
160
+ created_at: int,
161
+ expires_at: int = 0,
162
+ expected_interface: int | None = None,
163
+ output_limit: int | None = None,
164
+ ) -> list[str]:
165
+ validate_task_id(task_id)
166
+ validate_request_id(request_id)
167
+ if not isinstance(revision, str) or not 1 <= len(revision) <= 128:
168
+ raise RegistryError("revision must be a non-empty string of at most 128 chars")
169
+ source_bytes = source.encode("utf-8")
170
+ if not source_bytes:
171
+ raise RegistryError("task source must not be empty")
172
+ if len(source_bytes) > MAX_SOURCE_BYTES:
173
+ raise RegistryError(
174
+ f"task source exceeds the {MAX_SOURCE_BYTES} byte limit: {len(source_bytes)}")
175
+
176
+ lines = [
177
+ f"{BEGIN_MARKER}{task_id}",
178
+ f'ns.AutomationTaskDefinitions["{task_id}"] = {{',
179
+ " schema = 1,",
180
+ f" requestId = {escape_lua_string(request_id)},",
181
+ f" revision = {escape_lua_string(revision)},",
182
+ ' kind = "lua",',
183
+ f" createdAt = {int(created_at)},",
184
+ f" expiresAt = {int(expires_at or 0)},",
185
+ f" sourceBytes = {len(source_bytes)},",
186
+ f' sourceChecksum = "{adler32_hex(source)}",',
187
+ ]
188
+ if expected_interface:
189
+ lines.append(f" expectedClient = {{ interface = {int(expected_interface)} }},")
190
+ if output_limit:
191
+ lines.append(f" outputLimit = {int(output_limit)},")
192
+ lines.append(f" source = {escape_lua_string(source)},")
193
+ lines.append("}")
194
+ lines.append(f"{END_MARKER}{task_id}")
195
+ return lines
196
+
197
+
198
+ class _Block:
199
+ __slots__ = ("task_id", "lines")
200
+
201
+ def __init__(self, task_id: str, lines: list[str]):
202
+ self.task_id = task_id
203
+ self.lines = lines
204
+
205
+
206
+ FIELD_PATTERN = re.compile(r"^\s*(\w+) = (.+?),\s*$")
207
+
208
+
209
+ def _parse_field(block: _Block, field: str):
210
+ """Extract one field value from a generated block (data syntax only)."""
211
+
212
+ for line in block.lines:
213
+ match = FIELD_PATTERN.match(line)
214
+ if match and match.group(1) == field:
215
+ return match.group(2)
216
+ return None
217
+
218
+
219
+ def _decode_block(block: _Block) -> dict:
220
+ task_id = block.task_id
221
+ if block.lines[0] != f"{BEGIN_MARKER}{task_id}" or block.lines[-1] != f"{END_MARKER}{task_id}":
222
+ raise RegistryError(f"damaged markers in block {task_id}")
223
+ header = block.lines[1]
224
+ if header != f'ns.AutomationTaskDefinitions["{task_id}"] = {{':
225
+ raise RegistryError(f"unexpected block header in {task_id}")
226
+ if block.lines[-2] != "}":
227
+ raise RegistryError(f"unexpected block footer in {task_id}")
228
+ for index, line in enumerate(block.lines[2:-2], start=2):
229
+ if not FIELD_PATTERN.match(line):
230
+ raise RegistryError(
231
+ f"block {task_id} has an unexpected line {index + 1}: {line!r}")
232
+
233
+ definition: dict = {"taskId": task_id}
234
+ schema_raw = _parse_field(block, "schema")
235
+ if schema_raw is None or not schema_raw.strip().isdigit():
236
+ raise RegistryError(f"block {task_id} has a bad schema")
237
+ schema = int(schema_raw)
238
+ if schema != REGISTRY_SCHEMA_VERSION:
239
+ raise RegistryError(
240
+ f"block {task_id} uses unsupported schema {schema} "
241
+ f"(supported: {REGISTRY_SCHEMA_VERSION})")
242
+ definition["schema"] = schema
243
+ kind_raw = _parse_field(block, "kind")
244
+ if kind_raw is None:
245
+ raise RegistryError(f"block {task_id} is missing kind")
246
+ kind = unescape_lua_string(kind_raw) if kind_raw.startswith('"') else kind_raw
247
+ if kind not in REGISTRY_KINDS:
248
+ raise RegistryError(f"block {task_id} uses unsupported kind {kind!r}")
249
+ definition["kind"] = kind
250
+ for name in ("requestId", "revision"):
251
+ raw = _parse_field(block, name)
252
+ if raw is None:
253
+ raise RegistryError(f"block {task_id} is missing {name}")
254
+ definition[name] = unescape_lua_string(raw)
255
+ for name in ("createdAt", "expiresAt", "sourceBytes"):
256
+ raw = _parse_field(block, name)
257
+ if raw is None or not raw.lstrip("-").isdigit():
258
+ raise RegistryError(f"block {task_id} has a bad {name}")
259
+ definition[name] = int(raw)
260
+ checksum = _parse_field(block, "sourceChecksum")
261
+ if checksum is None or not re.match(r'^"[0-9a-f]{8}"$', checksum):
262
+ raise RegistryError(f"block {task_id} has a bad sourceChecksum")
263
+ definition["sourceChecksum"] = checksum.strip('"')
264
+ output_limit = _parse_field(block, "outputLimit")
265
+ if output_limit is not None:
266
+ definition["outputLimit"] = int(output_limit)
267
+ expected = _parse_field(block, "expectedClient")
268
+ if expected is not None:
269
+ match = re.match(r"^\{ interface = (\d+) \}$", expected)
270
+ if not match:
271
+ raise RegistryError(f"block {task_id} has a bad expectedClient")
272
+ definition["expectedClient"] = {"interface": int(match.group(1))}
273
+ source_raw = _parse_field(block, "source")
274
+ if source_raw is None:
275
+ raise RegistryError(f"block {task_id} has no source")
276
+ source = unescape_lua_string(source_raw)
277
+ encoded = source.encode("utf-8")
278
+ if len(encoded) != definition["sourceBytes"]:
279
+ raise RegistryError(f"block {task_id} sourceBytes mismatch")
280
+ if adler32_hex(source) != definition["sourceChecksum"]:
281
+ raise RegistryError(f"block {task_id} sourceChecksum mismatch")
282
+ definition["source"] = source
283
+ return definition
284
+
285
+
286
+ def parse_blocks(text: str) -> tuple[dict[str, dict], list[_Block]]:
287
+ """Parse the registry into decoded definitions plus ordered raw blocks."""
288
+
289
+ blocks: list[_Block] = []
290
+ current: _Block | None = None
291
+ for line in text.splitlines():
292
+ if line.startswith(BEGIN_MARKER):
293
+ if current is not None:
294
+ raise RegistryError("nested BEGIN marker inside a task block")
295
+ task_id = line[len(BEGIN_MARKER):].strip()
296
+ validate_task_id(task_id)
297
+ current = _Block(task_id, [line])
298
+ elif line.startswith(END_MARKER):
299
+ if current is None:
300
+ raise RegistryError("END marker without a matching BEGIN marker")
301
+ task_id = line[len(END_MARKER):].strip()
302
+ if task_id != current.task_id:
303
+ raise RegistryError("END marker task id does not match its BEGIN marker")
304
+ current.lines.append(line)
305
+ blocks.append(current)
306
+ current = None
307
+ elif current is not None:
308
+ if line.startswith(BEGIN_MARKER[:5]) and line.startswith("-- BEGIN"):
309
+ raise RegistryError("corrupted marker inside a task block")
310
+ current.lines.append(line)
311
+ if current is not None:
312
+ raise RegistryError("unterminated task block")
313
+ if not blocks and "ns.AutomationTaskDefinitions" not in text:
314
+ raise RegistryError("file does not look like a Lychee Dev task registry")
315
+
316
+ seen: dict[str, dict] = {}
317
+ for block in blocks:
318
+ if block.task_id in seen:
319
+ raise RegistryError(f"duplicate task block: {block.task_id}")
320
+ seen[block.task_id] = _decode_block(block)
321
+ return seen, blocks
322
+
323
+
324
+ @contextmanager
325
+ def _directory_lock(directory: str):
326
+ """Hold an exclusive lock file inside the installation directory."""
327
+
328
+ lock_path = os.path.join(directory, "auto.lua.lock")
329
+ lock = open(lock_path, "a+b")
330
+ try:
331
+ if msvcrt is not None:
332
+ msvcrt.locking(lock.fileno(), msvcrt.LK_LOCK, 1)
333
+ elif fcntl is not None:
334
+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
335
+ yield
336
+ finally:
337
+ try:
338
+ if msvcrt is not None:
339
+ lock.seek(0)
340
+ msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
341
+ elif fcntl is not None:
342
+ fcntl.flock(lock.fileno(), fcntl.LOCK_UN)
343
+ finally:
344
+ lock.close()
345
+
346
+
347
+ def resolve_registry_path(path: str) -> str:
348
+ """Resolve symlinks and directory junctions before any read or write.
349
+
350
+ Two paths that name the same file must lock, read and replace the same
351
+ file; ``realpath`` follows Windows junctions and symlinks so a shared
352
+ installation reached through a link cannot split the revision check.
353
+ """
354
+
355
+ return os.path.realpath(os.path.abspath(path))
356
+
357
+
358
+ def split_regions(text: str) -> tuple[str, str]:
359
+ """Return the verbatim text before the first block and after the last one.
360
+
361
+ The block region is the only part this module regenerates; anything a human
362
+ or another tool placed outside the markers stays byte-for-byte. The blank
363
+ separator lines right after the last END marker belong to the region so
364
+ repeated writes do not grow the file.
365
+ """
366
+
367
+ lines = text.splitlines(keepends=True)
368
+ first = None
369
+ last = None
370
+ for index, line in enumerate(lines):
371
+ if first is None and line.startswith(BEGIN_MARKER):
372
+ first = index
373
+ elif line.startswith(END_MARKER):
374
+ last = index
375
+ if first is None or last is None or last < first:
376
+ return text, ""
377
+ tail = last + 1
378
+ while tail < len(lines) and lines[tail].strip() == "":
379
+ tail += 1
380
+ return "".join(lines[:first]), "".join(lines[tail:])
381
+
382
+
383
+ def _atomic_write(path: str, data: bytes) -> None:
384
+ directory = os.path.dirname(os.path.abspath(path))
385
+ handle = tempfile.NamedTemporaryFile(
386
+ "wb", dir=directory, delete=False, prefix=".auto-", suffix=".tmp")
387
+ try:
388
+ with handle:
389
+ handle.write(data)
390
+ handle.flush()
391
+ os.fsync(handle.fileno())
392
+ os.replace(handle.name, path)
393
+ except BaseException:
394
+ try:
395
+ os.unlink(handle.name)
396
+ except OSError:
397
+ pass
398
+ raise
399
+
400
+
401
+ class TaskRegistry:
402
+ """Reader/writer for one installed auto.lua task registry."""
403
+
404
+ def __init__(self, path: str):
405
+ self.path = resolve_registry_path(path)
406
+ self.last_write_hash: str | None = None
407
+
408
+ def _read_text(self) -> str:
409
+ if not os.path.exists(self.path):
410
+ return REGISTRY_HEADER
411
+ with open(self.path, "r", encoding="utf-8") as handle:
412
+ return handle.read()
413
+
414
+ def read(self) -> dict[str, dict]:
415
+ text = self._read_text()
416
+ definitions, _ = parse_blocks(text)
417
+ return definitions
418
+
419
+ def _write(self, blocks: list[_Block], template: str | None = None) -> tuple[str, str]:
420
+ """Write the block region, preserving everything outside it.
421
+
422
+ Returns the written text and the SHA-256 of the exact bytes on disk.
423
+ """
424
+
425
+ if template is None:
426
+ template = self._read_text()
427
+ prefix, suffix = split_regions(template)
428
+ if prefix and not prefix.endswith("\n"):
429
+ prefix += "\n"
430
+ if blocks and prefix and not prefix.endswith("\n\n"):
431
+ prefix += "\n"
432
+ parts = [prefix]
433
+ for block in blocks:
434
+ for line in block.lines:
435
+ parts.append(line + "\n")
436
+ parts.append("\n")
437
+ parts.append(suffix)
438
+ text = "".join(parts)
439
+ encoded = text.encode("utf-8")
440
+ if len(encoded) > MAX_REGISTRY_BYTES:
441
+ raise RegistryError(
442
+ f"registry exceeds the {MAX_REGISTRY_BYTES} byte limit: {len(encoded)}")
443
+ if "\r" in text or any(ord(char) > 127 for char in text):
444
+ raise RegistryError("registry must stay ASCII with LF endings")
445
+ digest = hashlib.sha256(encoded).hexdigest()
446
+ _atomic_write(self.path, encoded)
447
+ self.last_write_hash = digest
448
+ return text, digest
449
+
450
+ def upsert(
451
+ self,
452
+ task_id: str,
453
+ *,
454
+ request_id: str,
455
+ revision: str,
456
+ source: str,
457
+ created_at: int,
458
+ expires_at: int = 0,
459
+ expected_interface: int | None = None,
460
+ output_limit: int | None = None,
461
+ expect_revision: str | None = None,
462
+ ) -> dict:
463
+ validate_task_id(task_id)
464
+ directory = os.path.dirname(self.path) or "."
465
+ os.makedirs(directory, exist_ok=True)
466
+ with _directory_lock(directory):
467
+ text = self._read_text()
468
+ definitions, blocks = parse_blocks(text)
469
+ if task_id in definitions and expect_revision is not None:
470
+ if definitions[task_id]["revision"] != expect_revision:
471
+ raise RegistryError(
472
+ f"revision conflict for {task_id}: expected {expect_revision!r}, "
473
+ f"found {definitions[task_id]['revision']!r}")
474
+ new_lines = build_block(
475
+ task_id,
476
+ request_id=request_id,
477
+ revision=revision,
478
+ source=source,
479
+ created_at=created_at,
480
+ expires_at=expires_at,
481
+ expected_interface=expected_interface,
482
+ output_limit=output_limit,
483
+ )
484
+ replaced = False
485
+ for index, block in enumerate(blocks):
486
+ if block.task_id == task_id:
487
+ blocks[index] = _Block(task_id, new_lines)
488
+ replaced = True
489
+ break
490
+ if not replaced:
491
+ if len(blocks) >= MAX_BLOCKS:
492
+ raise RegistryError(f"registry already holds {MAX_BLOCKS} task blocks")
493
+ blocks.append(_Block(task_id, new_lines))
494
+ written, file_hash = self._write(blocks, template=text)
495
+ parsed, _ = parse_blocks(written)
496
+ definition = dict(parsed[task_id])
497
+ definition["fileHash"] = file_hash
498
+ return definition
499
+
500
+ def remove(self, task_id: str, *, expect_revision: str | None = None) -> bool:
501
+ validate_task_id(task_id)
502
+ directory = os.path.dirname(self.path) or "."
503
+ if not os.path.exists(self.path):
504
+ return False
505
+ with _directory_lock(directory):
506
+ text = self._read_text()
507
+ definitions, blocks = parse_blocks(text)
508
+ if task_id not in definitions:
509
+ return False
510
+ if expect_revision is not None and definitions[task_id]["revision"] != expect_revision:
511
+ raise RegistryError(
512
+ f"revision conflict for {task_id}: expected {expect_revision!r}, "
513
+ f"found {definitions[task_id]['revision']!r}")
514
+ remaining = [block for block in blocks if block.task_id != task_id]
515
+ self._write(remaining, template=text)
516
+ return True