Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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'}`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
8 changes: 8 additions & 0 deletions docs/public-private-boundary.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,14 @@ 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. 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. 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:

Expand Down
107 changes: 101 additions & 6 deletions loopx/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -376,7 +379,55 @@ 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 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",
".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",
}
# 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",
".goal-harness",
Expand Down Expand Up @@ -1144,13 +1195,49 @@ 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 _local_metadata_headers(name: str) -> tuple[bytes, ...]:
"""Return the magic headers a known OS metadata name may begin with."""

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.
"""

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:
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():
Comment thread
huangruiteng marked this conversation as resolved.
Resolved
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:
Expand Down Expand Up @@ -1276,6 +1363,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:
Expand All @@ -1302,8 +1390,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 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))


Expand Down
35 changes: 33 additions & 2 deletions loopx/control_plane/runtime/file_reads.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down Expand Up @@ -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)


Expand Down
2 changes: 1 addition & 1 deletion tests/canary/test_git_path_display.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions tests/test_contract_credential_pattern_precision.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
43 changes: 28 additions & 15 deletions tests/test_contract_public_boundary_prefilter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -21,41 +21,53 @@ 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:
subprocess.run(["git", "init", "-q", str(tmp_path)], check=True)
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.
# 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]
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]


Expand Down Expand Up @@ -321,5 +333,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
Loading
Loading