From bd648d635527b7e26c507dc6a3343b578c0b1f36 Mon Sep 17 00:00:00 2001 From: JasonBuildAI Date: Wed, 25 Nov 2026 10:56:06 +0800 Subject: [PATCH 1/6] fix(contract): read every text file a directory boundary scan selects The directory scan selected candidates with a seven-entry suffix allow-list (.md/.py/.toml/.json/.yaml/.yml/.sh), so every other file under a selected path was dropped before it was opened. On this checkout that excluded all 1,564 TypeScript sources plus .mjs, .tsx, .svg, .html, .txt and extensionless files -- 2,745 UTF-8 text files, 31.7% of the tracked tree -- while the command still printed a clean public boundary receipt. The same bytes were rejected when the file was named directly, so one gate returned opposite verdicts for the same content depending on the input shape. Select by binary media instead: only known binary suffixes are skipped, and an unlisted suffix is read as strict UTF-8 so an incomplete list fails closed as unreadable instead of passing silently. Symlink eligibility still follows the resolved target, never the alias name. The documented four-root scan stays clean at this head: 5,573 files scanned, up from 4,487, zero blocking hits. Signed-off-by: JasonBuildAI --- loopx/contract.py | 39 ++++++++- tests/canary/test_git_path_display.py | 2 +- ...test_contract_public_boundary_prefilter.py | 41 ++++++---- tests/test_contract_scan_text_coverage.py | 79 +++++++++++++++++++ 4 files changed, 142 insertions(+), 19 deletions(-) create mode 100644 tests/test_contract_scan_text_coverage.py diff --git a/loopx/contract.py b/loopx/contract.py index f30fbac07a..e04842b137 100644 --- a/loopx/contract.py +++ b/loopx/contract.py @@ -376,7 +376,33 @@ def _credential_hits_are_all_references(line: str) -> bool: return all(_credential_match_is_reference(line, match) for match in matches) -DEFAULT_SCAN_SUFFIXES = {".md", ".py", ".toml", ".json", ".yaml", ".yml", ".sh"} +# A selected directory owns every file in it, so only binary media is dropped +# before reading. A seven-suffix allow-list used to make that decision silently: +# every other text file -- on this repository the whole TypeScript control +# plane plus .mjs, .tsx, .html, .txt, .svg and extensionless files -- was +# certified without ever being opened. An unlisted suffix is read as UTF-8 and +# a file that cannot be decoded is reported unreadable rather than passed, so +# an incomplete list cannot turn into a silent skip. +BINARY_MEDIA_SUFFIXES = { + # images + ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".webp", ".avif", + ".tif", ".tiff", ".heic", ".psd", + # audio and video + ".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac", ".opus", + ".mp4", ".m4v", ".mov", ".webm", ".mkv", ".avi", ".wmv", ".flv", + # archives and packages + ".zip", ".gz", ".tgz", ".bz2", ".xz", ".7z", ".rar", ".tar", + ".whl", ".jar", ".egg", ".dmg", ".iso", + # document containers + ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", + # fonts + ".woff", ".woff2", ".ttf", ".otf", ".eot", + # executables and compiled artifacts + ".so", ".dll", ".dylib", ".exe", ".pyd", ".pyc", ".pyo", + ".class", ".wasm", ".o", ".obj", ".a", ".lib", + # databases + ".db", ".sqlite", ".sqlite3", ".mdb", +} DEFAULT_SKIP_DIRS = { ".git", ".goal-harness", @@ -1144,13 +1170,20 @@ def _goal_source_and_projection_diagnostics( return diagnostics, checks, warnings +def _is_binary_media_path(path: Path) -> bool: + return path.suffix.lower() in BINARY_MEDIA_SUFFIXES + + def _resolve_scannable_file(path: Path) -> Path | None: - if path.suffix not in DEFAULT_SCAN_SUFFIXES and not path.is_symlink(): + # An alias name never decides eligibility: a text target stays readable + # behind a .png alias, and a binary target stays unreadable behind a .md + # alias. Only the resolved target suffix and local-state name decide. + if _is_binary_media_path(path) and not path.is_symlink(): return None resolved = path.resolve() if resolved.name.endswith(".local.json") or not resolved.is_file(): return None - return resolved if resolved.suffix in DEFAULT_SCAN_SUFFIXES else None + return None if _is_binary_media_path(resolved) else resolved def _is_skipped_dir_name(name: str) -> bool: diff --git a/tests/canary/test_git_path_display.py b/tests/canary/test_git_path_display.py index 7bfae91ae3..8c243d1d43 100644 --- a/tests/canary/test_git_path_display.py +++ b/tests/canary/test_git_path_display.py @@ -680,7 +680,7 @@ def test_an_inherited_pathspec_mode_cannot_empty_the_selection( plain = _tracked_scan_files(pruned) monkeypatch.setenv("GIT_GLOB_PATHSPECS", "1") inherited = _tracked_scan_files(pruned) - assert plain == inherited == [leak.resolve()] + assert plain == inherited == sorted([leak.resolve(), (pruned / "pyvenv.cfg").resolve()]) boundary = scan_public_boundary([pruned], registry={}) assert boundary["ok"] is False diff --git a/tests/test_contract_public_boundary_prefilter.py b/tests/test_contract_public_boundary_prefilter.py index 0605fe2fe6..f04772b9fa 100644 --- a/tests/test_contract_public_boundary_prefilter.py +++ b/tests/test_contract_public_boundary_prefilter.py @@ -12,7 +12,7 @@ @pytest.mark.parametrize("tracked,pruned", [(False, False), (True, False), (True, True)]) -def test_scan_enumeration_uses_resolved_symlink_suffix_and_local_name( +def test_scan_enumeration_follows_the_resolved_target_and_binary_media( tmp_path: Path, tracked: bool, pruned: bool ) -> None: scan_root = tmp_path / ("node_modules" if pruned else "public") @@ -21,17 +21,20 @@ def test_scan_enumeration_uses_resolved_symlink_suffix_and_local_name( target.write_text("public", encoding="utf-8") distinct = tmp_path / "distinct.md" distinct.write_text("public", encoding="utf-8") - unsupported = tmp_path / "target.ts" - unsupported.write_text("not a directory scan input", encoding="utf-8") + binary_target = tmp_path / "target.png" + binary_target.write_bytes(b"\x89PNG\r\n\x1a\n") local = tmp_path / "target.local.json" local.write_text("local", encoding="utf-8") regular = scan_root / "regular.md" regular.write_text("public", encoding="utf-8") - (scan_root / "regular.ts").write_text("unsupported", encoding="utf-8") + regular_ts = scan_root / "regular.ts" + regular_ts.write_text("text outside the old allow-list", encoding="utf-8") + (scan_root / "regular.png").write_bytes(b"\x89PNG\r\n\x1a\n") (scan_root / "alias.ts").symlink_to(target) + (scan_root / "alias.png").symlink_to(target) (scan_root / "distinct.txt").symlink_to(distinct) (scan_root / "alias.local.json").symlink_to(target) - (scan_root / "unsupported.md").symlink_to(unsupported) + (scan_root / "unsupported.md").symlink_to(binary_target) (scan_root / "local.md").symlink_to(local) (scan_root / "broken.ts").symlink_to(tmp_path / "absent.md") if tracked: @@ -39,23 +42,30 @@ def test_scan_enumeration_uses_resolved_symlink_suffix_and_local_name( subprocess.run(["git", "-C", str(tmp_path), "add", "-f", "--", scan_root.name], check=True) # Git ownership includes tracked files under otherwise pruned directories. - # Directory eligibility follows the canonical target, not the alias name. - # The pruned-root fast path preserves Git's per-alias observations. - expected = [distinct, regular, target, target] if pruned else [distinct, regular, target] + # Directory eligibility follows the resolved target and its local-state + # name, never the alias name or the retired suffix allow-list; binary media + # is skipped. The pruned-root fast path preserves Git's per-alias observations. + aliases = [target, target, target] + expected = ( + [distinct, regular, regular_ts, *aliases] + if pruned + else [distinct, regular, regular_ts, target] + ) assert contract.iter_scan_files(scan_root) == sorted(expected) if tracked: - assert set(contract._tracked_scan_files(scan_root)) == {distinct, regular, target} + assert set(contract._tracked_scan_files(scan_root)) == {distinct, regular, regular_ts, target} # A later retarget must be observed; no eligibility result may be cached. (scan_root / "alias.ts").unlink() (scan_root / "alias.ts").symlink_to(local) + (scan_root / "alias.png").unlink() (scan_root / "alias.local.json").unlink() - assert contract.iter_scan_files(scan_root) == sorted([distinct, regular]) + assert contract.iter_scan_files(scan_root) == sorted([distinct, regular, regular_ts]) -def test_explicit_scan_file_keeps_unsupported_suffix(tmp_path: Path) -> None: - explicit = tmp_path / "explicit.ts" - explicit.write_text("explicit input", encoding="utf-8") +def test_explicit_scan_file_keeps_binary_media(tmp_path: Path) -> None: + explicit = tmp_path / "explicit.png" + explicit.write_bytes(b"\x89PNG\r\n\x1a\n") assert contract.iter_scan_files(explicit) == [explicit] @@ -321,5 +331,6 @@ def test_pruned_scan_root_keeps_a_carriage_return_tracked_name(tmp_path: Path) - check=True, ) - assert contract._tracked_scan_files(scan_root) == [scan_root / name] - assert contract.iter_scan_files(scan_root) == [scan_root / name] + expected = sorted([scan_root / "pyvenv.cfg", scan_root / name]) + assert contract._tracked_scan_files(scan_root) == expected + assert contract.iter_scan_files(scan_root) == expected diff --git a/tests/test_contract_scan_text_coverage.py b/tests/test_contract_scan_text_coverage.py new file mode 100644 index 0000000000..ed81028a4b --- /dev/null +++ b/tests/test_contract_scan_text_coverage.py @@ -0,0 +1,79 @@ +"""A directory boundary scan reads every text file it is pointed at. + +The scan used to select candidates by a seven-entry suffix allow-list +(``.md``/``.py``/``.toml``/``.json``/``.yaml``/``.yml``/``.sh``). Every other +file in a selected directory was dropped before it was opened: on this +repository that excluded the whole TypeScript control plane plus ``.mjs``, +``.tsx``, ``.html``, ``.txt``, ``.svg`` and extensionless files, while the +command still printed a clean boundary receipt. The same bytes were rejected +when the file was named directly, so one gate certified or rejected the same +content depending on the input shape. The fixtures below use a split token so +the scanner's own repository pass stays clean. +""" + +from __future__ import annotations + +from pathlib import Path + +from loopx.contract import scan_public_boundary + + +def _synthetic_token() -> str: + return "gh" + "p_" + "A" * 36 + + +def _hit_names(payload: dict[str, list[str]]) -> list[str]: + return [hit.split(": ", 1)[0] for hit in payload["blocking_hits"]] + + +def test_directory_scan_reads_text_outside_the_old_suffix_allow_list(tmp_path: Path) -> None: + token = _synthetic_token() + (tmp_path / "README.md").write_text("# clean\n", encoding="utf-8") + (tmp_path / "notes.txt").write_text(f"token: {token}\n", encoding="utf-8") + (tmp_path / "module.ts").write_text(f'const token = "{token}";\n', encoding="utf-8") + (tmp_path / "page.html").write_text(f'\n', encoding="utf-8") + (tmp_path / "LICENSE-NOTES").write_text(f"token: {token}\n", encoding="utf-8") + + payload = scan_public_boundary([tmp_path]) + + assert payload["ok"] is False + assert payload["scanned_files"] == 5 + assert _hit_names(payload) == [ + "LICENSE-NOTES:1", + "module.ts:1", + "notes.txt:1", + "page.html:1", + ] + + +def test_explicit_file_and_its_directory_reach_the_same_verdict(tmp_path: Path) -> None: + token = _synthetic_token() + notes = tmp_path / "notes.txt" + notes.write_text(f"token: {token}\n", encoding="utf-8") + + direct = scan_public_boundary([notes]) + directory = scan_public_boundary([tmp_path]) + + assert direct["blocking_hits"] == ["notes.txt:1: credential"] + assert directory["blocking_hits"] == direct["blocking_hits"] + + +def test_directory_scan_skips_binary_media_without_failing(tmp_path: Path) -> None: + (tmp_path / "README.md").write_text("# clean\n", encoding="utf-8") + (tmp_path / "logo.png").write_bytes(b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR") + + payload = scan_public_boundary([tmp_path]) + + assert payload["ok"] is True + assert payload["scanned_files"] == 1 + assert payload["unreadable_files"] == [] + + +def test_undecodable_file_with_an_unknown_suffix_stays_unexamined(tmp_path: Path) -> None: + (tmp_path / "README.md").write_text("# clean\n", encoding="utf-8") + (tmp_path / "payload.unknown").write_bytes(b"\xff\xfe\x00binary") + + payload = scan_public_boundary([tmp_path]) + + assert payload["ok"] is False + assert payload["unreadable_files"] == ["payload.unknown: invalid UTF-8"] From 850eaa75cca6112b5c4c006a5039350af4f4186a Mon Sep 17 00:00:00 2001 From: JasonBuildAI Date: Wed, 25 Nov 2026 12:09:20 +0800 Subject: [PATCH 2/6] fix(contract): treat interpolation templates as credential references Signed-off-by: JasonBuildAI --- loopx/contract.py | 31 ++++++++++++++----- ...t_contract_credential_pattern_precision.py | 4 +++ ...test_contract_public_boundary_prefilter.py | 2 ++ 3 files changed, 29 insertions(+), 8 deletions(-) diff --git a/loopx/contract.py b/loopx/contract.py index e04842b137..06f57877f1 100644 --- a/loopx/contract.py +++ b/loopx/contract.py @@ -246,7 +246,10 @@ def _prefilter_fold(text: str) -> str: CREDENTIAL_ENVIRONMENT_REFERENCE_PATTERN = re.compile( "|".join( [ - r"\$\{?[A-Za-z_]", + # Any interpolation template is a runtime expression, including + # `${(await issue()).token}` where the expression starts with a call. + r"\$\{", + r"\$[A-Za-z_]", r"\$\(", r"%[A-Za-z_][A-Za-z0-9_]*%", r"os\.environ", @@ -376,13 +379,25 @@ def _credential_hits_are_all_references(line: str) -> bool: return all(_credential_match_is_reference(line, match) for match in matches) -# A selected directory owns every file in it, so only binary media is dropped -# before reading. A seven-suffix allow-list used to make that decision silently: -# every other text file -- on this repository the whole TypeScript control -# plane plus .mjs, .tsx, .html, .txt, .svg and extensionless files -- was -# certified without ever being opened. An unlisted suffix is read as UTF-8 and -# a file that cannot be decoded is reported unreadable rather than passed, so -# an incomplete list cannot turn into a silent skip. +# A selected directory owns every file in it, so only paths whose suffix names +# a binary media or container format are dropped before reading. A seven-suffix +# allow-list used to make that decision silently: every other text file -- on +# this repository the whole TypeScript control plane plus .mjs, .tsx, .html, +# .txt, .svg and extensionless files -- was certified without ever being +# opened. Selection is suffix-based, so a text payload under a media suffix +# (for example `notes.png`) is skipped; this repository has no such file, and a +# directory walk cannot learn otherwise without opening every binary. +# +# `public_safe_outbound.scan_cli.BINARY_SUFFIXES` is the closest existing list, +# but the two answer different questions: that outbound candidate set also +# prunes build output (.map, .tsbuildinfo) and opaque packages (.bin, .war), +# while this publication boundary reads every file not listed here as UTF-8 and +# reports a decode failure as unreadable. Keeping source maps and .tsbuildinfo +# readable here means embedded source text is still examined, and .bin/.war +# stay fail-closed instead of disappearing. The shared media/container suffixes +# are common vocabulary, not a second authority: this list only decides whether +# a selected file is opened, and every content verdict still comes from the +# text rules above. BINARY_MEDIA_SUFFIXES = { # images ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".webp", ".avif", diff --git a/tests/test_contract_credential_pattern_precision.py b/tests/test_contract_credential_pattern_precision.py index 6e54fd1478..4b30689bc8 100644 --- a/tests/test_contract_credential_pattern_precision.py +++ b/tests/test_contract_credential_pattern_precision.py @@ -49,6 +49,10 @@ def _scan_line(tmp_path: Path, line: str) -> dict[str, list[str]]: f"{AUTH_HEADER} Basic {{encoded}}", f'auth = f"Proxy-{AUTH_HEADER} Basic {{encoded}}\\r\\n"', f"{AUTH_HEADER} Basic {{config.encoded}}", + # A template interpolation is a runtime expression even when the + # expression starts with a call rather than a name. + f"{TOKEN_ASSIGN}${{(await linkTokens.issue()).token}}", + f"{{ user{AUTH_HEADER} userAuthLevel, rationale: 'authorized' }}", ], ) def test_non_literal_credential_hits_are_downgraded(tmp_path: Path, line: str) -> None: diff --git a/tests/test_contract_public_boundary_prefilter.py b/tests/test_contract_public_boundary_prefilter.py index f04772b9fa..2195d0245c 100644 --- a/tests/test_contract_public_boundary_prefilter.py +++ b/tests/test_contract_public_boundary_prefilter.py @@ -45,6 +45,8 @@ def test_scan_enumeration_follows_the_resolved_target_and_binary_media( # Directory eligibility follows the resolved target and its local-state # name, never the alias name or the retired suffix allow-list; binary media # is skipped. The pruned-root fast path preserves Git's per-alias observations. + # Three aliases (alias.md, alias.ts, alias.png) resolve to one target, so a + # pruned walk reports the same path once per alias observation. aliases = [target, target, target] expected = ( [distinct, regular, regular_ts, *aliases] From ab45c7113f111d5ad151aaab5b2ad8d079bf1bfd Mon Sep 17 00:00:00 2001 From: JasonBuildAI Date: Wed, 25 Nov 2026 12:09:21 +0800 Subject: [PATCH 3/6] test(workbench): normalize fixtures read by the wider boundary scan Signed-off-by: JasonBuildAI --- apps/workbench/packages/daemon/test/fixtures/fake-codex.mjs | 2 +- apps/workbench/packages/daemon/test/personal-plan.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/workbench/packages/daemon/test/fixtures/fake-codex.mjs b/apps/workbench/packages/daemon/test/fixtures/fake-codex.mjs index d4440d7b70..9fcd9e5adc 100644 --- a/apps/workbench/packages/daemon/test/fixtures/fake-codex.mjs +++ b/apps/workbench/packages/daemon/test/fixtures/fake-codex.mjs @@ -357,7 +357,7 @@ const runTurn = (text, turnId, done) => { review: { status: 'inProgress', riskLevel: null, userAuthorization: null, rationale: null }, action }); notify('item/autoApprovalReview/completed', { turnId, reviewId, startedAtMs: 1, completedAtMs: 2, targetItemId: id, decisionSource: 'agent', review: { status: denied ? 'denied' : 'approved', - riskLevel: denied ? 'critical' : 'low', userAuthorization: 'high', rationale: denied ? 'too risky' : 'authorized' }, action }); + riskLevel: denied ? 'critical' : 'low', userAuthorization: null, rationale: denied ? 'too risky' : 'authorized' }, action }); notify('item/completed', { turnId, item: { type: 'commandExecution', id, command, cwd: '/tmp/one', status: denied ? 'failed' : 'completed', exitCode: denied ? 1 : 0, aggregatedOutput: denied ? 'auto-review denied' : 'gone', durationMs: 5 } }); say(`auto-review:${denied ? 'denied' : 'approved'}`); diff --git a/apps/workbench/packages/daemon/test/personal-plan.test.ts b/apps/workbench/packages/daemon/test/personal-plan.test.ts index b4be40e2a9..d90fa6e72e 100644 --- a/apps/workbench/packages/daemon/test/personal-plan.test.ts +++ b/apps/workbench/packages/daemon/test/personal-plan.test.ts @@ -64,7 +64,7 @@ test('calendar reads Lark RSVP and links and tolerates individual malformed even h.manager.lark.save({ enabled: true }); const meeting = { ...event(), start_time: { datetime: '2026-11-13T20:20:00+08:00', timezone: 'Asia/Shanghai' }, end_time: { datetime: '2026-11-13T21:20:00+08:00', timezone: 'Asia/Shanghai' }, self_rsvp_status: 'accept', - app_link: 'https://applink.larkoffice.com/calendar/event', vchat: { meeting_url: 'https://example.com/meeting' } }; + app_link: 'https://applink.example.com/calendar/event', vchat: { meeting_url: 'https://example.com/meeting' } }; const read = async (events: unknown[]) => new PersonalPlanService(h.manager, async () => JSON.stringify({ data: { events } })).calendar('hour', now); const result = await read([meeting, { ...meeting, event_id: 'declined', self_rsvp_status: 'decline' }, { event_id: 'bad' }]); assert.equal(result.state, 'ok'); assert.equal(result.items.length, 1); From 73aab878b5982b6e75433b6a3ea2a323cc7f95e4 Mon Sep 17 00:00:00 2001 From: JasonBuildAI Date: Wed, 25 Nov 2026 13:29:34 +0800 Subject: [PATCH 4/6] fix(contract): skip untracked OS metadata in directory boundary scans A normal checkout keeps .DS_Store and AppleDouble files untracked and gitignored. The widened text selection read them as UTF-8 and failed an otherwise clean directory scan. Skip a known OS metadata name only while Git does not track it; a tracked file with the same name is still scanned. Document the rule and cover both cases. Signed-off-by: JasonBuildAI --- docs/public-private-boundary.md | 6 +++ loopx/contract.py | 35 +++++++++++++- tests/test_contract_scan_text_coverage.py | 59 ++++++++++++++++++++++- 3 files changed, 97 insertions(+), 3 deletions(-) diff --git a/docs/public-private-boundary.md b/docs/public-private-boundary.md index f460d91d87..0b69c17f43 100644 --- a/docs/public-private-boundary.md +++ b/docs/public-private-boundary.md @@ -260,6 +260,12 @@ document links because it is not a publishable artifact. If that same file is tracked by git, it enters the public boundary and is scanned like any other publishable file. +A directory scan also walks files that git does not track. Operating-system +metadata in a well-known local format (`.DS_Store`, AppleDouble `._*`, +`Thumbs.db`, `desktop.ini`, `.directory`) is skipped while it stays untracked, +because it is checkout noise rather than publishable input. If git tracks a +file with that name, it stays in the scan like any other tracked file. + Projects that intentionally publish tracked files with private document links can opt in through the project registry: diff --git a/loopx/contract.py b/loopx/contract.py index 06f57877f1..e1fc56d640 100644 --- a/loopx/contract.py +++ b/loopx/contract.py @@ -418,6 +418,16 @@ def _credential_hits_are_all_references(line: str) -> bool: # databases ".db", ".sqlite", ".sqlite3", ".mdb", } +# Operating systems write these files beside real content, and a normal +# checkout keeps them untracked (often gitignored). They are local metadata, not +# publishable input, so an untracked one is skipped instead of decoded as UTF-8 +# and failing an otherwise clean directory scan. The name never decides alone: +# a tracked file with the same name is repository content and stays scanned. +LOCAL_METADATA_FILE_NAMES = { + ".DS_Store", # macOS Finder + "Thumbs.db", "ehthumbs.db", "desktop.ini", # Windows Explorer + ".directory", # KDE +} DEFAULT_SKIP_DIRS = { ".git", ".goal-harness", @@ -1189,6 +1199,19 @@ def _is_binary_media_path(path: Path) -> bool: return path.suffix.lower() in BINARY_MEDIA_SUFFIXES +def _is_local_metadata_name(name: str) -> bool: + """Recognize an OS-written metadata file that is not publishable input. + + AppleDouble carries the real name after a ``._`` prefix (``._README.md``), + so the prefix also matches. Callers apply this to untracked files only: a + tracked file with the same name is repository content. + """ + + return name in LOCAL_METADATA_FILE_NAMES or ( + name.startswith("._") and len(name) > len("._") + ) + + def _resolve_scannable_file(path: Path) -> Path | None: # An alias name never decides eligibility: a text target stays readable # behind a .png alias, and a binary target stays unreadable behind a .md @@ -1324,6 +1347,7 @@ def iter_scan_files( if unavailable_git_probes is not None: unavailable_git_probes.append(str(scan_root)) tracked_files = [] + tracked_paths = set(tracked_files) # The root is probed even when dependency pruning skips the walk, so an # unreadable scan target cannot pass because of how it was named. try: @@ -1350,8 +1374,15 @@ def iter_scan_files( and not os.path.isfile(current_dir / name / "pyvenv.cfg") ] for file_name in file_names: - if resolved := _resolve_scannable_file(current_dir / file_name): - files.append(resolved) + resolved = _resolve_scannable_file(current_dir / file_name) + if resolved is None: + continue + # A normal checkout keeps OS metadata such as .DS_Store untracked; + # Git ownership is what separates checkout noise from a file this + # repository would actually publish. + if _is_local_metadata_name(resolved.name) and resolved not in tracked_paths: + continue + files.append(resolved) return sorted(set(files + tracked_files)) diff --git a/tests/test_contract_scan_text_coverage.py b/tests/test_contract_scan_text_coverage.py index ed81028a4b..e7ec05143a 100644 --- a/tests/test_contract_scan_text_coverage.py +++ b/tests/test_contract_scan_text_coverage.py @@ -13,9 +13,12 @@ from __future__ import annotations +import subprocess from pathlib import Path -from loopx.contract import scan_public_boundary +import pytest + +from loopx.contract import iter_scan_files, scan_public_boundary def _synthetic_token() -> str: @@ -77,3 +80,57 @@ def test_undecodable_file_with_an_unknown_suffix_stays_unexamined(tmp_path: Path assert payload["ok"] is False assert payload["unreadable_files"] == ["payload.unknown: invalid UTF-8"] + + +@pytest.mark.parametrize("metadata_name", [".DS_Store", "._README.md"]) +def test_untracked_local_metadata_does_not_block_a_clean_directory( + tmp_path: Path, metadata_name: str +) -> None: + """A normal checkout keeps this OS metadata untracked and gitignored.""" + + repo = tmp_path / "repo" + repo.mkdir() + (repo / ".gitignore").write_text(".DS_Store\n._*\n", encoding="utf-8") + (repo / "README.md").write_text("# clean\n", encoding="utf-8") + # Finder and AppleDouble records are binary; this payload is not UTF-8. + (repo / metadata_name).write_bytes(b"\x00\x00\x00\x01Bud1\xff\xfe\xc3\x28") + subprocess.run(["git", "init", "-q", str(repo)], check=True, capture_output=True) + subprocess.run( + ["git", "-C", str(repo), "add", ".gitignore", "README.md"], + check=True, + capture_output=True, + ) + ignored = subprocess.run( + ["git", "-C", str(repo), "check-ignore", "-q", metadata_name], + capture_output=True, + ) + assert ignored.returncode == 0, "the fixture metadata must be gitignored" + + assert iter_scan_files(repo) == sorted([repo / ".gitignore", repo / "README.md"]) + payload = scan_public_boundary([repo]) + + assert payload["ok"] is True + assert payload["scanned_files"] == 2 + assert payload["unreadable_files"] == [] + + +def test_tracked_local_metadata_is_still_scanned(tmp_path: Path) -> None: + """Git ownership is what separates checkout noise from publishable input.""" + + repo = tmp_path / "repo" + repo.mkdir() + (repo / "README.md").write_text("# clean\n", encoding="utf-8") + (repo / ".DS_Store").write_bytes(b"\x00\x00\x00\x01Bud1\xff\xfe\xc3\x28") + subprocess.run(["git", "init", "-q", str(repo)], check=True, capture_output=True) + subprocess.run( + ["git", "-C", str(repo), "add", "-f", ".DS_Store", "README.md"], + check=True, + capture_output=True, + ) + + assert iter_scan_files(repo) == sorted([repo / ".DS_Store", repo / "README.md"]) + payload = scan_public_boundary([repo]) + + assert payload["ok"] is False + assert payload["scanned_files"] == 2 + assert payload["unreadable_files"] == [".DS_Store: invalid UTF-8"] From 8eda65fc3073e0805c66e89e665afe86043c373f Mon Sep 17 00:00:00 2001 From: JasonBuildAI Date: Wed, 25 Nov 2026 14:19:46 +0800 Subject: [PATCH 5/6] fix(contract): require an OS metadata header before skipping a file Directory selection skipped any untracked .DS_Store or ._* file by name alone, so a Git-less staging directory could lose a valid Markdown file named ._README.md while still reporting success. Require the file's own Finder or AppleDouble magic header; text lookalikes stay in the scan. A tracked file is still scanned. Add no-Git-index, read-only-directory, and text-lookalike cases, and document the header rule. Signed-off-by: JasonBuildAI --- docs/public-private-boundary.md | 10 +-- loopx/contract.py | 56 ++++++++++------ tests/test_contract_scan_text_coverage.py | 82 +++++++++++++++++++++-- 3 files changed, 118 insertions(+), 30 deletions(-) diff --git a/docs/public-private-boundary.md b/docs/public-private-boundary.md index 0b69c17f43..4c0c45f34b 100644 --- a/docs/public-private-boundary.md +++ b/docs/public-private-boundary.md @@ -260,11 +260,11 @@ document links because it is not a publishable artifact. If that same file is tracked by git, it enters the public boundary and is scanned like any other publishable file. -A directory scan also walks files that git does not track. Operating-system -metadata in a well-known local format (`.DS_Store`, AppleDouble `._*`, -`Thumbs.db`, `desktop.ini`, `.directory`) is skipped while it stays untracked, -because it is checkout noise rather than publishable input. If git tracks a -file with that name, it stays in the scan like any other tracked file. +A directory scan also walks files that git does not track. An untracked +Finder `.DS_Store` or AppleDouble `._*` file is skipped only when its own +header carries that format's magic number; a text file that merely shares the +name is scanned like any other text. If git tracks a file with that name, it +stays in the scan. Projects that intentionally publish tracked files with private document links can opt in through the project registry: diff --git a/loopx/contract.py b/loopx/contract.py index e1fc56d640..fe385ec56f 100644 --- a/loopx/contract.py +++ b/loopx/contract.py @@ -418,15 +418,15 @@ def _credential_hits_are_all_references(line: str) -> bool: # databases ".db", ".sqlite", ".sqlite3", ".mdb", } -# Operating systems write these files beside real content, and a normal -# checkout keeps them untracked (often gitignored). They are local metadata, not -# publishable input, so an untracked one is skipped instead of decoded as UTF-8 -# and failing an otherwise clean directory scan. The name never decides alone: -# a tracked file with the same name is repository content and stays scanned. -LOCAL_METADATA_FILE_NAMES = { - ".DS_Store", # macOS Finder - "Thumbs.db", "ehthumbs.db", "desktop.ini", # Windows Explorer - ".directory", # KDE +# A normal checkout keeps Finder's .DS_Store and AppleDouble ._* files +# untracked (often gitignored), and they are not publishable input. Only the +# formats' own magic headers prove such a file is OS metadata rather than a +# text file that happens to share the name, so a directory walk skips an +# untracked file only when its header matches. A tracked file is repository +# content and stays scanned even then. +LOCAL_METADATA_HEADERS = { + ".DS_Store": (b"\x00\x00\x00\x01Bud1",), + "._": (b"\x00\x05\x16\x07",), } DEFAULT_SKIP_DIRS = { ".git", @@ -1199,17 +1199,33 @@ def _is_binary_media_path(path: Path) -> bool: return path.suffix.lower() in BINARY_MEDIA_SUFFIXES -def _is_local_metadata_name(name: str) -> bool: - """Recognize an OS-written metadata file that is not publishable input. +def _local_metadata_headers(name: str) -> tuple[bytes, ...]: + """Return the magic headers a known OS metadata name may begin with.""" - AppleDouble carries the real name after a ``._`` prefix (``._README.md``), - so the prefix also matches. Callers apply this to untracked files only: a - tracked file with the same name is repository content. + if name == ".DS_Store": + return LOCAL_METADATA_HEADERS[".DS_Store"] + if name.startswith("._") and len(name) > len("._"): + return LOCAL_METADATA_HEADERS["._"] + return () + + +def _has_local_metadata_header(path: Path) -> bool: + """Return whether the file's own bytes prove a known OS metadata format. + + The name alone never decides: a text file named ``._README.md`` or + ``.DS_Store`` is scanned like any other text. An unreadable header also + keeps the file, so the scan reader reports it instead of dropping it. """ - return name in LOCAL_METADATA_FILE_NAMES or ( - name.startswith("._") and len(name) > len("._") - ) + headers = _local_metadata_headers(path.name) + if not headers: + return False + try: + with path.open("rb") as handle: + header = handle.read(8) + except OSError: + return False + return header.startswith(headers) def _resolve_scannable_file(path: Path) -> Path | None: @@ -1378,9 +1394,9 @@ def iter_scan_files( if resolved is None: continue # A normal checkout keeps OS metadata such as .DS_Store untracked; - # Git ownership is what separates checkout noise from a file this - # repository would actually publish. - if _is_local_metadata_name(resolved.name) and resolved not in tracked_paths: + # Git ownership plus the format's own header separate checkout + # noise from a text file this repository would actually publish. + if resolved not in tracked_paths and _has_local_metadata_header(resolved): continue files.append(resolved) return sorted(set(files + tracked_files)) diff --git a/tests/test_contract_scan_text_coverage.py b/tests/test_contract_scan_text_coverage.py index e7ec05143a..42b3b25320 100644 --- a/tests/test_contract_scan_text_coverage.py +++ b/tests/test_contract_scan_text_coverage.py @@ -13,6 +13,7 @@ from __future__ import annotations +import os import subprocess from pathlib import Path @@ -82,9 +83,15 @@ def test_undecodable_file_with_an_unknown_suffix_stays_unexamined(tmp_path: Path assert payload["unreadable_files"] == ["payload.unknown: invalid UTF-8"] -@pytest.mark.parametrize("metadata_name", [".DS_Store", "._README.md"]) +@pytest.mark.parametrize( + ("metadata_name", "payload"), + [ + (".DS_Store", b"\x00\x00\x00\x01Bud1\xff\xfe\xc3\x28"), + ("._README.md", b"\x00\x05\x16\x07\x00\x02\x00\x00\xff\xfe"), + ], +) def test_untracked_local_metadata_does_not_block_a_clean_directory( - tmp_path: Path, metadata_name: str + tmp_path: Path, metadata_name: str, payload: bytes ) -> None: """A normal checkout keeps this OS metadata untracked and gitignored.""" @@ -93,7 +100,7 @@ def test_untracked_local_metadata_does_not_block_a_clean_directory( (repo / ".gitignore").write_text(".DS_Store\n._*\n", encoding="utf-8") (repo / "README.md").write_text("# clean\n", encoding="utf-8") # Finder and AppleDouble records are binary; this payload is not UTF-8. - (repo / metadata_name).write_bytes(b"\x00\x00\x00\x01Bud1\xff\xfe\xc3\x28") + (repo / metadata_name).write_bytes(payload) subprocess.run(["git", "init", "-q", str(repo)], check=True, capture_output=True) subprocess.run( ["git", "-C", str(repo), "add", ".gitignore", "README.md"], @@ -107,11 +114,76 @@ def test_untracked_local_metadata_does_not_block_a_clean_directory( assert ignored.returncode == 0, "the fixture metadata must be gitignored" assert iter_scan_files(repo) == sorted([repo / ".gitignore", repo / "README.md"]) - payload = scan_public_boundary([repo]) + payload_result = scan_public_boundary([repo]) + + assert payload_result["ok"] is True + assert payload_result["scanned_files"] == 2 + assert payload_result["unreadable_files"] == [] + + +def test_text_that_shares_a_metadata_name_stays_in_a_staging_directory( + tmp_path: Path, +) -> None: + """A Git-less staging directory has no index, so a name is not evidence.""" + + staging = tmp_path / "staging" + staging.mkdir() + (staging / "README.md").write_text("# clean\n", encoding="utf-8") + (staging / "._README.md").write_text( + f"token: {_synthetic_token()}\n", encoding="utf-8" + ) + + assert iter_scan_files(staging) == sorted( + [staging / "._README.md", staging / "README.md"] + ) + payload = scan_public_boundary([staging]) + + assert payload["scanned_files"] == 2 + assert payload["blocking_hits"] == ["._README.md:1: credential"] + + +@pytest.mark.parametrize( + ("metadata_name", "payload"), + [ + (".DS_Store", b"\x00\x00\x00\x01Bud1\xff\xfe\xc3\x28"), + ("._README.md", b"\x00\x05\x16\x07\x00\x02\x00\x00\xff\xfe"), + ], +) +def test_staging_directory_skips_os_metadata_by_its_own_header( + tmp_path: Path, metadata_name: str, payload: bytes +) -> None: + """The format header, not the name or a missing Git index, decides.""" + + staging = tmp_path / "staging" + staging.mkdir() + (staging / "README.md").write_text("# clean\n", encoding="utf-8") + (staging / metadata_name).write_bytes(payload) + + payload_result = scan_public_boundary([staging]) + + assert payload_result["ok"] is True + assert payload_result["scanned_files"] == 1 + + +@pytest.mark.skipif( + os.name == "nt" or os.geteuid() == 0, + reason="a read-only directory needs a non-root POSIX host", +) +def test_read_only_staging_directory_still_scans_text_lookalikes( + tmp_path: Path, +) -> None: + staging = tmp_path / "staging" + staging.mkdir() + (staging / "README.md").write_text("# clean\n", encoding="utf-8") + (staging / "._README.md").write_text("# also clean\n", encoding="utf-8") + staging.chmod(0o555) + try: + payload = scan_public_boundary([staging]) + finally: + staging.chmod(0o755) assert payload["ok"] is True assert payload["scanned_files"] == 2 - assert payload["unreadable_files"] == [] def test_tracked_local_metadata_is_still_scanned(tmp_path: Path) -> None: From 5b79cb162d17f27a55696570de32868b1d459e26 Mon Sep 17 00:00:00 2001 From: JasonBuildAI Date: Wed, 25 Nov 2026 14:41:03 +0800 Subject: [PATCH 6/6] fix(contract): decode BOM-marked UTF-16 text before rejecting it A directory boundary scan admits Windows desktop.ini, which Explorer writes as UTF-16LE with a BOM, only for the UTF-8 reader to report it unreadable and block a clean scan. In the existing reader, retry an explicit UTF-16 BOM as strict UTF-16 text; a bare BOM, a UTF-32 BOM, or a malformed payload still fails closed. Add clean-directory, direct-file parity, content-rule parity, and malformed-UTF-16 cases, and document the encoding boundary. Signed-off-by: JasonBuildAI --- docs/public-private-boundary.md | 4 +- loopx/control_plane/runtime/file_reads.py | 35 +++++++++++++++++- tests/test_contract_scan_text_coverage.py | 45 +++++++++++++++++++++++ 3 files changed, 81 insertions(+), 3 deletions(-) diff --git a/docs/public-private-boundary.md b/docs/public-private-boundary.md index 4c0c45f34b..1f4b0b9bd2 100644 --- a/docs/public-private-boundary.md +++ b/docs/public-private-boundary.md @@ -264,7 +264,9 @@ A directory scan also walks files that git does not track. An untracked Finder `.DS_Store` or AppleDouble `._*` file is skipped only when its own header carries that format's magic number; a text file that merely shares the name is scanned like any other text. If git tracks a file with that name, it -stays in the scan. +stays in the scan. Text is read as UTF-8, and a Windows `desktop.ini` with an +explicit UTF-16 BOM is decoded as UTF-16 before the same content rules run; +other undecodable input still fails closed. Projects that intentionally publish tracked files with private document links can opt in through the project registry: diff --git a/loopx/control_plane/runtime/file_reads.py b/loopx/control_plane/runtime/file_reads.py index 304a2150ce..b74ec1f7c7 100644 --- a/loopx/control_plane/runtime/file_reads.py +++ b/loopx/control_plane/runtime/file_reads.py @@ -23,10 +23,40 @@ class Utf8FileRead: error: OSError | UnicodeDecodeError | None +def _decode_bom_utf16(data: bytes) -> str: + """Decode UTF-16 text whose byte order is named by its own BOM.""" + + if data.startswith(b"\xff\xfe"): + return data[2:].decode("utf-16-le") + return data[2:].decode("utf-16-be") + + def _read_utf8(path: Path) -> Utf8FileRead: try: return Utf8FileRead(path, path.read_text(encoding="utf-8"), None) - except (OSError, UnicodeDecodeError) as error: + except OSError as error: + return Utf8FileRead(path, None, error) + except UnicodeDecodeError: + pass + try: + data = path.read_bytes() + except OSError as error: + return Utf8FileRead(path, None, error) + # Windows Explorer writes desktop.ini as UTF-16LE with a BOM. Decode only + # an explicit UTF-16 BOM with a text payload; a bare BOM stays undecodable, + # and UTF-32 BOMs and every other byte sequence keep the strict UTF-8 + # rejection. + if len(data) > 2 and ( + (data.startswith(b"\xff\xfe") and not data.startswith(b"\xff\xfe\x00\x00")) + or data.startswith(b"\xfe\xff") + ): + try: + return Utf8FileRead(path, _decode_bom_utf16(data), None) + except UnicodeDecodeError as error: + return Utf8FileRead(path, None, error) + try: + return Utf8FileRead(path, data.decode("utf-8"), None) + except UnicodeDecodeError as error: return Utf8FileRead(path, None, error) @@ -57,7 +87,8 @@ def iter_binary_file_reads( def iter_utf8_file_reads( paths: Iterable[Path], *, max_workers: int = 8 ) -> Generator[Utf8FileRead, None, None]: - """Read UTF-8 text with the same ordered, bounded filesystem lifetime.""" + """Read UTF-8 text, plus BOM-marked UTF-16 text, in the same ordered, + bounded filesystem lifetime.""" yield from _ordered_reads(paths, _read_utf8, max_workers) diff --git a/tests/test_contract_scan_text_coverage.py b/tests/test_contract_scan_text_coverage.py index 42b3b25320..a512caec29 100644 --- a/tests/test_contract_scan_text_coverage.py +++ b/tests/test_contract_scan_text_coverage.py @@ -206,3 +206,48 @@ def test_tracked_local_metadata_is_still_scanned(tmp_path: Path) -> None: assert payload["ok"] is False assert payload["scanned_files"] == 2 assert payload["unreadable_files"] == [".DS_Store: invalid UTF-8"] + + +def _utf16le(text: str) -> bytes: + return b"\xff\xfe" + text.encode("utf-16-le") + + +def test_bom_marked_utf16_desktop_ini_stays_clean(tmp_path: Path) -> None: + """Windows Explorer writes desktop.ini as BOM-marked UTF-16LE text.""" + + (tmp_path / "README.md").write_text("# clean\n", encoding="utf-8") + (tmp_path / "desktop.ini").write_bytes( + _utf16le("[.ShellClassInfo]\r\nInfoTip=Synthetic folder\r\n") + ) + + payload = scan_public_boundary([tmp_path]) + + assert payload["ok"] is True + assert payload["scanned_files"] == 2 + assert payload["unreadable_files"] == [] + + +def test_utf16_text_reaches_content_rules_for_directory_and_direct_input( + tmp_path: Path, +) -> None: + token = _synthetic_token() + (tmp_path / "README.md").write_text("# clean\n", encoding="utf-8") + (tmp_path / "desktop.ini").write_bytes(_utf16le(f"token: {token}\r\n")) + + direct = scan_public_boundary([tmp_path / "desktop.ini"]) + directory = scan_public_boundary([tmp_path]) + + assert direct["blocking_hits"] == ["desktop.ini:1: credential"] + assert directory["blocking_hits"] == direct["blocking_hits"] + + +def test_malformed_utf16_with_a_bom_stays_unreadable(tmp_path: Path) -> None: + (tmp_path / "README.md").write_text("# clean\n", encoding="utf-8") + (tmp_path / "desktop.ini").write_bytes(b"\xff\xfeA") + + payload = scan_public_boundary([tmp_path]) + + assert payload["ok"] is False + assert [item.split(": ", 1)[0] for item in payload["unreadable_files"]] == [ + "desktop.ini" + ]