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
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,7 @@ jobs:
tests/quality/test_cli_docs_surface.py \
tests/quality/test_journey_index.py \
tests/quality/test_generated_obligations.py \
tests/quality/test_oracle_user_writes.py \
tests/quality/test_cli_command_literals.py

test-architecture-scaling:
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/main-architecture-ratchets.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,5 @@ jobs:
tests/quality/test_cli_docs_surface.py \
tests/quality/test_journey_index.py \
tests/quality/test_generated_obligations.py \
tests/quality/test_oracle_user_writes.py \
tests/quality/test_cli_command_literals.py
9 changes: 8 additions & 1 deletion tests/lifecycle/generator/covering.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,14 @@ def context_cells(scalar: Mapping[str, str], units: Sequence[Mapping[str, str]])


def simulate(plan: Plan, steps: Sequence[Step], targets: Sequence[str]) -> list[set[str]]:
"""Cells each step visits, in order."""
"""Cells each step visits, in order.

TGT is <shape>-<change>. The shape is the declared target set BEFORE the step
(one target is single, two or more are multi). narrowed = the step drops at
least one previously declared target; it may add others (a switch counts as
narrowed); widened = it adds at least one and drops none.
A covering row keeps its targets, so every step it simulates is *-unchanged.
"""
state = _State()
tgt = "multi-unchanged" if len(targets) > 1 else "single-unchanged"
visited: list[set[str]] = []
Expand Down
4 changes: 4 additions & 0 deletions tests/lifecycle/generator/factors.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@
# The executable domain of the gate (commands/approve.py:255).
EXECUTABLE_PRIMS = ("hook", "mcp", "lsp", "bin", "canvas")
PRIMS = (*PLAIN_PRIMS, *EXECUTABLE_PRIMS)
# TGT is <shape>-<change>. The shape is the declared target set BEFORE the step
# (one target is single, two or more are multi). narrowed = the step drops at
# least one previously declared target; it may add others (a switch counts as
# narrowed); widened = it adds at least one and drops none.
TARGET_CHANGES = tuple(
f"{shape}-{change}"
for shape in ("single", "multi")
Expand Down
36 changes: 4 additions & 32 deletions tests/lifecycle/machines/test_m_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,37 +331,9 @@ def _mcp_servers(observation: Observation) -> frozenset[str]:
return frozenset(json.loads(path.read_text(encoding="utf-8")).get("mcpServers") or {})


# The cache marker a git-sourced p-skill leaves behind (src/apm_cli/install/cache_pin.py).
_STALE_PIN = "apm_modules/lifecycle/p-skill/.apm-pin"
_STALE_PIN_ISSUE = "#4572"


def _stale_pin(machine, op, before=None, after=None, result=None) -> bool:
"""A registry p-skill keeps the git source's .apm-pin until ``install --update`` drops it."""
del after
return (
result is not None
and result.returncode == 0
and op.name == "install"
and "--update" in result.command
and machine.converged
and machine.network != "offline"
and machine.slots.get("remote-skill") is _REGISTRY_SKILL
and before is not None
and _STALE_PIN in before.artifacts.snapshot("project").paths
)


# Strict known cells this machine discharges; #4214 is fixed (LSP-only packages survive uninstall).
KNOWN_CELLS = (
KnownCell(
"registry-source-switch-stale-pin",
"I2",
_STALE_PIN_ISSUE,
rf"^converged install rewrote files: \['project:{re.escape(_STALE_PIN)}'\]$",
_stale_pin,
),
)
# Strict known cells this machine discharges; #4214 and #4572 are fixed (LSP-only
# packages survive uninstall; a git -> registry switch drops the stale .apm-pin).
KNOWN_CELLS: tuple[KnownCell, ...] = ()


class SourceMachine(MachineBase):
Expand Down Expand Up @@ -876,4 +848,4 @@ def test_source_generated_sequences_keep_cross_cutting_laws(


# T3/T5 cells whose oracle fails on main -> tracking issue (a strict known cell discharges them).
KNOWN_CELLS_BY_ID: dict[str, str] = {"X|install|pkg-registry|UPDATE=on": _STALE_PIN_ISSUE}
KNOWN_CELLS_BY_ID: dict[str, str] = {}
101 changes: 90 additions & 11 deletions tests/lifecycle/oracles.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,22 @@ class OracleLaw:


ORACLE_LAWS: Mapping[str, OracleLaw] = {
"I1": OracleLaw("lock and deployed files agree", ("outcome.status_matches_state",)),
"I1": OracleLaw(
"lock and deployed files agree "
"(I1-X2: a path holding exactly the bytes a scenario declared as a user write "
"is exempt from lock==disk and earns no I1 receipt; APM must keep those bytes)",
("outcome.status_matches_state",),
),
"I2": OracleLaw("a converged operation repeats as a byte no-op", ("idempotency.byte_stable",)),
"I3": OracleLaw(
"install --frozen succeeds iff audit --ci is clean",
("outcome.status_matches_state", "lockfile.frozen_preserves_bytes"),
),
"I4": OracleLaw(
"deny, revoke and tightening never widen what is deployed",
"deny, revoke and tightening never widen what is deployed "
"(I4-X2: a gate surface whose every deployed path holds exactly declared user "
"bytes (Scenario.user_write) is exempt from I4 only if the step announces the "
"keep AND audit --ci fails naming the path; it earns no I4 receipt)",
("routing.authorized_targets_only",),
),
"I5": OracleLaw(
Expand Down Expand Up @@ -133,6 +141,14 @@ class Observation:
surface_paths: Mapping[str, frozenset[str]] = field(default_factory=dict)
# True when deploy_root is the user deploy root, where native plugin roots live.
user_scope: bool = False
# I1-X2: deploy-root-relative path -> sha256 of the bytes a scenario wrote
# there as a declared user write (Scenario.user_write).
user_bytes: Mapping[str, str] = field(default_factory=dict)
# I4-X2: deployed cell -> the deploy-root-relative paths found for it.
cell_paths: Mapping[str, frozenset[str]] = field(default_factory=dict)
# I4-X2: (exit code, output) of ``audit --ci`` run right after the step,
# when a cell the gate does not allow holds only declared user bytes.
audit_ci: tuple[int, str] | None = None


@dataclass(frozen=True)
Expand Down Expand Up @@ -390,8 +406,9 @@ def _i1_lock_deployed(
) -> list[Violation] | None:
del before, result, model, op
lock = after.lock
found, user = _user_write_violations(after)
if lock is None and not after.managed_paths and not after.services:
return None
return found or None
recorded: dict[str, str | None] = {}
if lock is not None:
for record in lock.deployment_ledger.records.values():
Expand All @@ -400,22 +417,41 @@ def _i1_lock_deployed(
for dependency in lock.get_package_dependencies():
recorded.update(dependency.deployed_file_hashes)
recorded.update(lock.local_deployed_file_hashes)
found = []
for relative, digest in sorted(recorded.items()):
path = after.deploy_root / relative
# A record without a hash may be a directory (a deployed skill); it must exist.
if not (path.is_file() if digest else path.exists()):
found.append(Violation("I1", f"recorded file is missing: {relative}"))
# The lock records line-ending-normalized hashes (apm#1952), so CRLF on Windows matches.
elif digest and digest != compute_file_hash(path):
elif digest and digest != compute_file_hash(path) and relative not in user:
found.append(Violation("I1", f"recorded hash does not match disk: {relative}"))
native, native_found = _native_plugin_recorded(after)
found.extend(native_found)
for relative in sorted(after.managed_paths - set(recorded) - native):
for relative in sorted(after.managed_paths - set(recorded) - native - user):
if (after.deploy_root / relative).exists():
found.append(Violation("I1", f"deployed file is not in the lock: {relative}"))
found.extend(_service_claim_violations(after))
return found
# An exempted path earns no I1 receipt for the step (I1-X2).
return found if found or not user else None


def _user_write_violations(after: Observation) -> tuple[list[Violation], set[str]]:
"""I1-X2: (violations, exempt paths) of the scenario's declared user writes.

A declared path is the user's while it holds exactly the declared bytes;
APM must keep them, so any other content (or a removal) is a violation.
"""
found: list[Violation] = []
exempt: set[str] = set()
for relative, declared in sorted(after.user_bytes.items()):
path = after.deploy_root / relative
if not path.is_file():
found.append(Violation("I1", f"I1-X2: the user's file was removed: {relative}"))
elif hashlib.sha256(path.read_bytes()).hexdigest() != declared:
found.append(Violation("I1", f"I1-X2: the user's bytes were changed: {relative}"))
else:
exempt.add(relative)
return found, exempt


def _native_plugin_recorded(after: Observation) -> tuple[set[str], list[Violation]]:
Expand Down Expand Up @@ -532,10 +568,53 @@ def _i4_gate_monotonicity(
del before
if not op.mutating or (result is not None and result.returncode != 0):
return None
return [
Violation("I4", f"{surface} still deployed but not allowed")
for surface in sorted(after.deployed - model.allowed_surfaces())
]
output = "" if result is None else f"{result.stdout}\n{result.stderr}"
found: list[Violation] = []
exempt = False
for surface in sorted(after.deployed - model.allowed_surfaces()):
gap = _i4_keep_gap(surface, after, output)
if gap is None:
exempt = True
else:
found.append(Violation("I4", f"{surface} still deployed but not allowed{gap}"))
# An exempted surface earns no I4 receipt for the step (I4-X2).
return found if found or not exempt else None


def user_kept_cells(after: Observation, allowed: frozenset[str]) -> frozenset[str]:
"""I4-X2: deployed cells the gate does not allow whose every path holds user bytes."""
return frozenset(
cell
for cell in after.deployed - allowed
if after.cell_paths.get(cell)
and all(_holds_user_bytes(after, path) for path in after.cell_paths[cell])
)


def _holds_user_bytes(after: Observation, relative: str) -> bool:
declared = after.user_bytes.get(relative)
path = after.deploy_root / relative
return (
declared is not None
and path.is_file()
and hashlib.sha256(path.read_bytes()).hexdigest() == declared
)


def _i4_keep_gap(surface: str, after: Observation, output: str) -> str | None:
"""I4-X2: None for an announced, detected keep of user bytes; else what is missing."""
if surface not in user_kept_cells(after, frozenset()):
return ""
paths = sorted(after.cell_paths[surface])
silent = [p for p in paths if not re.search(rf"\bKept\b[^\n]*{re.escape(p)}", output)]
if silent:
return f" (I4-X2: the keep is not announced: {silent})"
code, text = after.audit_ci or (0, "")
flat = " ".join(text.split())
unnamed = [p for p in paths if p not in flat]
if code == 0 or unnamed:
return f" (I4-X2: an undetected keep: audit --ci exited {code}, not naming {unnamed})"
return None


def _i5_write_set(
Expand Down
Loading