interplane.Get Omega
Read in your language

hop

Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.

Brought by drakestapleton

branch main Branches Tags History

hop / Linux / tests / files_check.py

415 lines · 18563 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Independent native-Omega file-index oracle; all trees and caches are temporary."""
3from __future__ import annotations
4
5import argparse
6import fcntl
7import hashlib
8import json
9import os
10from pathlib import Path
11import resource
12import signal
13import struct
14import subprocess
15import tempfile
16
17ROOT = Path(__file__).resolve().parents[2]
18HEADER = """om2
19global lx_query uchar *
20global lx_rows uchar *
21global lx_qn ulong 1
22global lx_rn ulong 1
23global lx_pick ulong 1
24"""
25MAIN = """
26fn ft_setquery source view uchar * to void
27r = enlarge lx_query len source
28if lt r 0
29exit 1
30end
31for i ulong len source bound 131072
32put lx_query i get source i
33end
34put lx_qn 0 len source
35end
36fn ft_mode source view uchar * expected view uchar * to bool
37if ne len source len expected
38ret false
39end
40for i ulong len source bound 131072
41if ne get source i get expected i
42ret false
43end
44end
45ret true
46end
47text ft_reindex "--reindex"
48text ft_find "--find"
49text ft_ui "--ui"
50text ft_activate "--activate"
51text ft_default "find "
52fn main to int
53arg = new uchar 131072 0
54cwd0 = new uchar 4096 0
55cwd1 = new uchar 4096 0
56n0 = cwd cwd0 0 len cwd0
57if le n0 0
58ret 9
59end
60if eq argcnt 1
61ft_setquery ft_default
62r = ff_query
63if ne r 1
64ret 4
65end
66r = ff_activate
67k = write 1 lx_rows 0 get lx_rn 0
68ret 0
69end
70n = argread 1 arg 0 len arg
71if lt n 0
72ret 2
73end
74if ft_mode part arg 0 ulong n ft_reindex
75resultv = ff_cli 0
76n1 = cwd cwd1 0 len cwd1
77if ne n0 n1
78ret 9
79end
80for i ulong ulong n0 bound 4096
81if ne get cwd0 i get cwd1 i
82ret 9
83end
84end
85ret resultv
86end
87if ft_mode part arg 0 ulong n ft_find
88ret ff_cli 1
89end
90ui = ft_mode part arg 0 ulong n ft_ui
91activate = ft_mode part arg 0 ulong n ft_activate
92if not or ui activate
93ret 2
94end
95n = argread 2 arg 0 len arg
96if lt n 0
97ret 2
98end
99ft_setquery part arg 0 ulong n
100if ne ff_query 1
101ret 4
102end
103if activate
104pick = ulong 0
105if gt argcnt 3
106n = argread 3 arg 0 len arg
107if gt n 0
108pick = ulong sub get arg 0 48
109end
110end
111put lx_pick 0 pick
112resultv = ff_activate
113if ne resultv 1
114ret 5
115end
116ret 0
117end
118k = write 1 lx_rows 0 get lx_rn 0
119ret 0
120end
121"""
122
123
124def compiled(omc: Path, apps: str, files: str, out: Path) -> None:
125 source = HEADER + apps + (ROOT / "Linux/core.om").read_text() + files + MAIN
126 result = subprocess.run([str(omc)], input=source.encode(), capture_output=True)
127 if result.returncode:
128 raise AssertionError(f"compile {result.returncode}: {result.stderr.decode()}")
129 out.write_bytes(result.stdout)
130 out.chmod(0o755)
131
132
133def index_data(path: Path) -> tuple[dict[str, int], list[bytes]]:
134 data = path.read_bytes()
135 assert data[:8] == b"HOPFIND1" and len(data) >= 64
136 records, partial, body_bytes, directories = struct.unpack("<4Q", data[8:40])
137 assert data[40:64] == bytes(24)
138 body = data[64:]
139 assert len(body) == body_bytes
140 paths = body.split(b"\0")[:-1] if body else []
141 assert not body or body.endswith(b"\0")
142 assert len(paths) == records and all(p.startswith(b"/") and len(p) < 4096 for p in paths)
143 return dict(records=records, partial=partial, body_bytes=body_bytes, directories=directories), paths
144
145
146def packed_index(paths: list[bytes], partial: int = 0) -> bytes:
147 body = b"".join(p + b"\0" for p in paths)
148 return b"HOPFIND1" + struct.pack("<4Q", len(paths), partial, len(body), 1) + bytes(24) + body
149
150
151def main() -> None:
152 parser = argparse.ArgumentParser()
153 parser.add_argument("omc", type=Path)
154 parser.add_argument("--evidence", type=Path)
155 args = parser.parse_args()
156 omc = args.omc.resolve()
157 apps = (ROOT / "Linux/apps.om").read_text()
158 files = (ROOT / "Linux/files.om").read_text()
159 events: list[dict] = []
160 checks: list[str] = []
161
162 def check(condition: bool, message: str) -> None:
163 if not condition:
164 raise AssertionError(message)
165 checks.append(message)
166 print("PASS", message, flush=True)
167
168 with tempfile.TemporaryDirectory(prefix="hop-file-check-") as folder:
169 tmp = Path(folder)
170 exe = tmp / "files"
171 compiled(omc, apps, files, exe)
172 home = tmp / "home"
173 home.mkdir()
174 cache = tmp / "cache"
175 root = tmp / "root"
176 root.mkdir()
177 env = dict(PATH=os.defpath, HOME=str(home), XDG_CACHE_HOME=str(cache),
178 HOP_INDEX_ALARM_ENTRIES="2", HOP_API_KEY="private-fixture-model-key",
179 HOP_MODEL_URL="http://fixture.invalid/v1", DESKTOP_SESSION_TEST="preserve this variable")
180
181 def run(*argv: str, expected: int | None = 0, program: Path = exe,
182 run_env: dict[str, str] | None = None, **kwargs) -> subprocess.CompletedProcess:
183 result = subprocess.run([str(program), *map(str, argv)], env=run_env or env,
184 capture_output=True, timeout=30, **kwargs)
185 events.append(dict(args=list(map(str, argv)), exit=result.returncode,
186 stdout_sha256=hashlib.sha256(result.stdout).hexdigest(),
187 stderr=result.stderr.decode(errors="replace")))
188 if expected is not None:
189 assert result.returncode == expected, (argv, result.returncode, result.stderr)
190 return result
191
192 def query(text: str = "", **kwargs) -> list[str]:
193 return json.loads(run("--find", text, **kwargs).stdout)
194
195 # Missing state offers an action without touching the real home directory.
196 result = run("--ui", "find notes")
197 check(result.stdout == b"Build file list\n" and not cache.exists(),
198 "missing index offers one build action without creating or scanning anything")
199 run("--ui", "finder notes", expected=4)
200 check(not cache.exists(), "unrelated query is left to the other screens")
201
202 (root / "sub").mkdir()
203 (root / "Alpha notes.txt").write_text("one")
204 newline = root / "sub/target\nfile.txt"
205 newline.write_text("two")
206 emoji = root / "sub/Café 😀.txt"
207 emoji.write_text("three")
208 long_file = root / ("l" * 240)
209 long_file.touch()
210 bad_name = os.fsencode(root / "sub") + b"/bad-\xff-\xc0\xaf"
211 os.close(os.open(bad_name, os.O_CREAT | os.O_WRONLY, 0o600))
212 outside = tmp / "outside"
213 outside.mkdir()
214 (outside / "never-index-this.txt").touch()
215 (root / "outside-link").symlink_to(outside, target_is_directory=True)
216 (root / "sub/cycle").symlink_to(root, target_is_directory=True)
217 generated = [".git", ".hidden", "node_modules", "target", "build", "dist", "__pycache__",
218 "venv", ".venv", "site-packages"]
219 for name in generated:
220 (root / name).mkdir()
221 (root / name / "never-index-this.txt").touch()
222 result = run("--reindex", root)
223 index = cache / "hop/files.idx"
224 meta, paths = index_data(index)
225 wanted = {os.fsencode(p) for p in (root, root / "sub", root / "Alpha notes.txt", newline,
226 emoji, long_file, root / "outside-link", root / "sub/cycle")} | {bad_name}
227 check(set(paths) == wanted and len(paths) == len(wanted),
228 "NUL format preserves exact names, skips generated and hidden directories, and never follows symlink cycles")
229 check(meta["partial"] == 0 and meta["directories"] == 2,
230 "header independently accounts for records, bytes, attempted directories and complete coverage")
231 check(b"ALARM" in result.stderr and len(paths) > 2,
232 "entry threshold raises an alarm and continues instead of capping results")
233 decoded = query()
234 check({os.fsencode(p) for p in decoded} == wanted,
235 "CLI JSON round-trips newline, Unicode, supplementary Unicode and invalid filesystem bytes")
236 check(query("SUB target") == [str(newline)], "Find matches every typed word with ASCII case folding")
237 check(query("l" * 220) == [str(long_file)], "long search text is matched in full without an app-helper wire cap")
238 result = run("--ui", "find target")
239 check(result.stdout.splitlines() == [os.fsencode(newline).replace(b"\n", b"\\n")],
240 "UI escapes newline filenames into one row while keeping the underlying pathname intact")
241
242 # Roots are directory identities, so aliases and overlapping explicit roots do not duplicate entries.
243 run("--reindex", root, root / "sub", str(root) + "/./", str(root / "sub") + "/..", root)
244 meta2, paths2 = index_data(index)
245 check(set(paths2) == wanted and len(paths2) == len(wanted) and meta2["directories"] == 2,
246 "duplicate and overlapping roots are traversed once")
247 run("--reindex", "root/sub/..", cwd=tmp)
248 check(set(index_data(index)[1]) == wanted, "relative roots normalize against the original working directory")
249 run("--reindex", root / "node_modules")
250 check(index_data(index)[0]["records"] == 0,
251 "generated-directory exclusion also applies when that directory is supplied explicitly")
252 run("--reindex", root, root / "outside-link")
253 alias_meta, alias_paths = index_data(index)
254 check(alias_meta["partial"] > 0 and set(alias_paths) == wanted,
255 "explicit symlink root is not followed and its coverage warning preserves the readable root")
256
257 # Dynamic queue/hash table and multiple getdents chunks.
258 bulk = tmp / "bulk"
259 bulk.mkdir()
260 for i in range(3000):
261 (bulk / f"item-{i}.txt").touch()
262 for i in range(160):
263 (bulk / f"folder-{i}").mkdir()
264 (bulk / f"folder-{i}/inside.txt").touch()
265 run("--reindex", bulk)
266 bulk_meta, bulk_paths = index_data(index)
267 check(bulk_meta["records"] == 1 + 3000 + 160 + 160 and bulk_meta["directories"] == 161 and
268 len(set(bulk_paths)) == bulk_meta["records"],
269 "dynamic records, queue and directory identity hash grow across multiple directory reads")
270
271 # Known development scratch is skipped exactly; ordinary source directories remain searchable.
272 (home / "work/hive").mkdir(parents=True)
273 (home / "work/lanes").mkdir()
274 (home / "work/source").mkdir()
275 (home / "work/hive/skip.txt").touch()
276 (home / "work/lanes/skip.txt").touch()
277 (home / "work/source/keep.txt").touch()
278 run("--reindex")
279 default_paths = index_data(index)[1]
280 check(os.fsencode(home / "work/source/keep.txt") in default_paths and
281 not any(b"/work/hive" in p or b"/work/lanes" in p for p in default_paths),
282 "default home scan excludes exact scratch subtrees and keeps ordinary source folders")
283
284 # Permissions are a partial scan, not a reason to throw away obtainable records.
285 locked = root / "unreadable"
286 locked.mkdir()
287 (locked / "secret.txt").touch()
288 locked.chmod(0)
289 try:
290 assert os.geteuid() != 0, "Run this permissions oracle as the ordinary workspace user"
291 result = run("--reindex", root)
292 partial_meta, partial_paths = index_data(index)
293 check(partial_meta["partial"] > 0 and b"partial" in result.stderr and
294 os.fsencode(root / "Alpha notes.txt") in partial_paths and
295 os.fsencode(locked / "secret.txt") not in partial_paths,
296 "unreadable folder retains obtainable results and visibly records partial coverage")
297 result = run("--find", "Alpha")
298 check(json.loads(result.stdout) == [str(root / "Alpha notes.txt")] and b"partial" in result.stderr,
299 "partial results stay queryable with a visible warning")
300 result = run("--ui", "find Alpha")
301 check(len(result.stdout.splitlines()) == 2 and b"partial" in result.stdout.splitlines()[0],
302 "UI marks partial coverage beside its results")
303 partial_source = files.replace("if ok\nok = ff_publish\nend", "if ok\nif eq get ff_s 4 0\nok = ff_publish\nelse\nok = false\nend\nend")
304 check(partial_source != files, "discard-partial-results negative control applied")
305 mutant = tmp / "discard-partial"
306 compiled(omc, apps, partial_source, mutant)
307 before = index.read_bytes()
308 result = run("--reindex", root, program=mutant, expected=1)
309 check(index.read_bytes() == before,
310 "negative control reproduces the lost-partial-list bug and fails the successful-rebuild contract")
311 finally:
312 locked.chmod(0o700)
313
314 # Keep the previous usable snapshot on real output errors.
315 run("--reindex", root)
316 before = index.read_bytes()
317 lock = cache / "hop/files.lock"
318 with lock.open("r+") as held:
319 fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB)
320 result = run("--reindex", bulk, expected=3)
321 check(index.read_bytes() == before and b"already being built" in result.stderr,
322 "nonblocking lock excludes another rebuild and preserves the current snapshot")
323 (cache / "hop").chmod(0o500)
324 try:
325 result = run("--reindex", bulk, expected=1)
326 check(index.read_bytes() == before and b"previous list has been kept" in result.stderr,
327 "temporary-file creation failure preserves the previous usable index")
328 finally:
329 (cache / "hop").chmod(0o700)
330
331 def file_limit() -> None:
332 signal.signal(signal.SIGXFSZ, signal.SIG_IGN)
333 resource.setrlimit(resource.RLIMIT_FSIZE, (80, 80))
334
335 result = run("--reindex", bulk, expected=1, preexec_fn=file_limit)
336 check(index.read_bytes() == before and not list((cache / "hop").glob(".files.*.tmp")),
337 "actual short-write/disk-limit failure keeps the old index and removes its unique temporary file")
338 rename_source = files.replace("k = renames ff_rename 0 add add p 2 len ff_index 0",
339 "k = renames ff_rename 0 add add p 2 len ff_index 1")
340 check(rename_source != files, "rename-failure kernel fault injection applied")
341 rename_exe = tmp / "rename-fails"
342 compiled(omc, apps, rename_source, rename_exe)
343 run("--reindex", bulk, expected=1, program=rename_exe)
344 check(index.read_bytes() == before, "real rename EEXIST failure preserves the last good index")
345
346 # Using relative cache operations avoids a compiler packed-list limit on two absolute rename paths.
347 deep = tmp / "deep"
348 for i in range(23):
349 deep = deep / ("c" * 95 + str(i))
350 deep_env = dict(env, XDG_CACHE_HOME=str(deep))
351 run("--reindex", root, run_env=deep_env)
352 deep_index = deep / "hop/files.idx"
353 check(len(os.fsencode(deep_index)) * 2 > 4096 and index_data(deep_index)[0]["partial"] == 0,
354 "long cache paths publish atomically without imposing the compiler rename-packet bound")
355 check(str(newline) in query("target", run_env=deep_env), "long-cache lookup uses the same known location")
356
357 # Corrupt format inputs never produce a plausible truncated result.
358 saved = index.read_bytes()
359 base = packed_index([os.fsencode(newline)])
360 corruptions = [b"bad", b"BADMAGIC" + base[8:],
361 base[:8] + struct.pack("<Q", 2) + base[16:],
362 base[:24] + struct.pack("<Q", 1) + base[32:],
363 base[:40] + b"x" + base[41:],
364 packed_index([b"relative/path"]), packed_index([b""]),
365 packed_index([b"/" + b"a" * 4096]),
366 base[:-1], base + b"trailing"]
367 for damaged in corruptions:
368 index.write_bytes(damaged)
369 result = run("--find", "", expected=1)
370 assert b"damaged" in result.stderr and not result.stdout
371 index.write_bytes(saved)
372 check(True, "malformed header, counts, reserved bytes, path bounds and NUL framing are refused")
373
374 # A real child process records file-open arguments and only the permitted desktop environment.
375 marker = tmp / "opened.json"
376 fake_gio = tmp / "gio-oracle"
377 fake_gio.write_text("#!/usr/bin/python3\nimport os,sys,json\n"
378 "out={'args':sys.argv[1:],'env':dict(os.environ),"
379 "'cmdline':open('/proc/self/cmdline','rb').read().decode()}\n"
380 f"open({str(marker)!r},'w').write(json.dumps(out))\n")
381 fake_gio.chmod(0o755)
382 test_apps = apps.replace('text ha_gio "/usr/bin/gio"', f'text ha_gio "{fake_gio}"')
383 check(test_apps != apps, "file-open platform oracle applied")
384 opener = tmp / "opener"
385 compiled(omc, test_apps, files, opener)
386 run("--activate", "find target", "0", program=opener)
387 opened = json.loads(marker.read_text())
388 check(opened["args"] == ["open", str(newline)],
389 "file activation preserves the selected actual pathname, including its newline")
390 check(opened["env"]["DESKTOP_SESSION_TEST"] == env["DESKTOP_SESSION_TEST"] and
391 not any(k.startswith("HOP_") for k in opened["env"]) and
392 env["HOP_API_KEY"] not in opened["cmdline"] and
393 env["HOP_API_KEY"] not in marker.read_text(),
394 "file-open child receives desktop settings while private Hop settings reach neither environment nor command line")
395
396 # The missing-list action is tested with argc1, just as an ordinary graphical launch runs.
397 fresh_env = dict(env, XDG_CACHE_HOME=str(tmp / "fresh-cache"))
398 run(run_env=fresh_env)
399 check((tmp / "fresh-cache/hop/files.idx").is_file(),
400 "Build file list action actually creates and reloads the default-home index")
401 check(not list((cache / "hop").glob(".files.*.tmp")), "normal rebuilds leave no temporary indexes")
402
403 receipt = dict(status="PASS", checks=len(checks), names=checks,
404 compiler_sha256=hashlib.sha256(omc.read_bytes()).hexdigest(),
405 sources={name: hashlib.sha256((ROOT / name).read_bytes()).hexdigest()
406 for name in ("Linux/files.om", "Linux/apps.om", "Linux/tests/files_check.py")},
407 runs=events)
408 if args.evidence:
409 args.evidence.mkdir(parents=True, exist_ok=False)
410 (args.evidence / "RECEIPT.json").write_text(json.dumps(receipt, indent=2) + "\n")
411 print(f"HOP-LINUX-FILES PASS checks={len(checks)}")
412
413
414if __name__ == "__main__":
415 main()