From 2e1fac604647ae85e9977db61a0cc4e62b46c4de Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 11:41:06 -0700 Subject: [PATCH 01/42] fix: recognize explicit Bash destinations and preserve link entries --- docs/safety/hooks.md | 45 +++ .../execution/headless/_headless_recovery.py | 2 +- .../hooks/_runtime/_command_classification.py | 23 +- .../hooks/_runtime/_path_identity.py | 8 + .../hooks/_runtime/_write_target_scan.py | 301 +++++++++++++++++- src/autoskillit/hooks/guards/git_ops_guard.py | 28 +- .../guards/installation_integrity_guard.py | 48 ++- src/autoskillit/hooks/guards/write_guard.py | 30 +- src/autoskillit/server/lifecycle/_guards.py | 18 +- tests/arch/test_hook_path_identity_guard.py | 5 +- .../test_skill_write_target_conformance.py | 2 +- .../execution/headless/test_headless_scan.py | 11 + tests/hooks/test_command_classification.py | 34 ++ .../test_installation_integrity_guard.py | 91 ++++++ tests/hooks/test_path_identity.py | 21 ++ tests/hooks/test_write_guard.py | 231 ++++++++++++++ tests/hooks/test_write_target_scan.py | 221 +++++++++++++ tests/infra/test_git_ops_guard.py | 137 ++++++++ tests/server/test_guards_module.py | 140 +++++++- 19 files changed, 1339 insertions(+), 57 deletions(-) diff --git a/docs/safety/hooks.md b/docs/safety/hooks.md index 228421f375..0a3c7bf588 100644 --- a/docs/safety/hooks.md +++ b/docs/safety/hooks.md @@ -425,6 +425,51 @@ plugin generations, uv tool installs, and uv cache archives. This protection applies in every session class and backend. An unresolved write target is denied with guidance to put a literal path in the command. +### Bounded Bash destinations + +The shared scanner supplies Bash destinations to the write-prefix, installation, +Git-ref, and `run_cmd` guards. Supported explicit forms include +`npm install --prefix DIR pkg`, `npm install --prefix=DIR pkg`, and +`npm --prefix DIR install pkg`. The prefix is a content destination. Literal read +commands retain their existing policy; an unresolved supported destination is +distinct from a command with no detected write. + +For `ln TARGET LINK`, including separate or combined `-s`/`-f`, the destination is +the link entry, not the source. `-t DIR`, `-tDIR`, and detached/equals +`--target-directory` forms derive `DIR/basename(TARGET)` for each source. A lone +source derives an entry in cwd. An existing final directory, including a symlink +to a directory, normally receives a derived child; `-T` selects the final operand +itself, and `-n` prevents following a final symlink to a directory while retaining +ordinary-directory handling. GNU `install` target-directory forms similarly +produce each actual child content destination. Missing required values, unknown +destination-affecting options, and contradictory `-t`/`-T` are unresolved writes. + +Content writes follow final symlinks. Entry replacement resolves the parent and +retains the final basename: replacing an allowed link that points outside is +separate from later writing through that link. A symlinked parent still affects +the entry's physical location. Entry targets such as `/dev/null` remain visible +even where content writes to pseudo-devices are suppressed. + +An npm prefix does not describe all npm writes. The independently configured +[cache](https://docs.npmjs.com/cli/v11/using-npm/config/#cache) and dependency +[lifecycle scripts](https://docs.npmjs.com/cli/v11/using-npm/scripts/) can cause +additional writes; the scanner models neither cache writes nor script side +effects. Installed dependencies' scripts are distinct from hooks in the prefix +project. In [npm 12.2.1's install implementation](https://github.com/npm/cli/blob/v12.2.1/lib/commands/install.js), +the ordinary root install lifecycle sequence requires a local install, no +effective package arguments, and scripts enabled. That sequence does not apply +to `npm install --prefix DIR pkg`; this does not imply that every other project +hook is disabled. These behaviors depend on npm version and configuration, and +an install need not write an external cache. + +Canonical containment is a point-in-time check: an ancestor or symlink can change +between scanning and execution. Separately, `ln` chooses directory versus entry +semantics from filesystem state; changing the final operand into a directory or +a symlink to one before execution can change the child entry it creates. These +time-of-check-to-time-of-use weaknesses mean the checks provide neither race +immunity nor OS-level confinement. Creating a link entry and accessing its +referent require separate validation. + ### `recipe_write_advisor.py` **Matched tools:** `Write`, `Edit` Non-blocking advisory: suggests `/autoskillit:write-recipe` or diff --git a/src/autoskillit/execution/headless/_headless_recovery.py b/src/autoskillit/execution/headless/_headless_recovery.py index 844637df21..3e7a84ad24 100644 --- a/src/autoskillit/execution/headless/_headless_recovery.py +++ b/src/autoskillit/execution/headless/_headless_recovery.py @@ -104,7 +104,7 @@ def _tool_write_path_warnings( "Bash command contained a write target that could not be statically resolved. " + UNRESOLVED_WRITE_TARGET_REMEDIATION ) - for path in scan.targets: + for path in (*scan.targets, *scan.entry_targets): if _is_path_outside_cwd(path, cwd): normalized = os.path.normpath(path) warnings.append( diff --git a/src/autoskillit/hooks/_runtime/_command_classification.py b/src/autoskillit/hooks/_runtime/_command_classification.py index be409faf69..42867ea1c4 100644 --- a/src/autoskillit/hooks/_runtime/_command_classification.py +++ b/src/autoskillit/hooks/_runtime/_command_classification.py @@ -232,6 +232,21 @@ def _non_option_indices(argv: list[str], argv_tokens: Sequence[ArgvToken] | None ] +def _consume_destination_option( + argv: list[str], + argv_tokens: Sequence[ArgvToken] | None, + index: int, + spec: dict[str, _FlagArity], +) -> tuple[str | None, str | None, int, bool]: + if argv_tokens is None: + value, next_index, recognized = _consume_str_flag(argv, index, spec) + return value, None, next_index, recognized + value_token, next_index, recognized = _consume_argv_flag(argv_tokens, index, spec) + if value_token is None: + return None, None, next_index, recognized + return value_token.text, value_token.raw_span.strip(), next_index, recognized + + def _write_verb_operand_indices( verb: str, argv: list[str], argv_tokens: Sequence[ArgvToken] | None ) -> list[int]: @@ -243,14 +258,6 @@ def _write_verb_operand_indices( return operands[-1:] if verb in {"mv", "cp"}: return operands[-1:] if len(operands) >= 2 else [] - if verb == "install": - # GNU install's -t/--target-directory form takes its destination - # from a flag; otherwise the last operand is the destination. - if "-t" in argv[1:] or "--target-directory" in argv[1:]: - return operands[:1] - if len(operands) < 2: - return [] - return operands[-1:] if verb == "patch": return operands[:1] return operands diff --git a/src/autoskillit/hooks/_runtime/_path_identity.py b/src/autoskillit/hooks/_runtime/_path_identity.py index 78d41109e4..a34da53b9f 100644 --- a/src/autoskillit/hooks/_runtime/_path_identity.py +++ b/src/autoskillit/hooks/_runtime/_path_identity.py @@ -37,6 +37,14 @@ def hooks_relative_key(script_identity: str | os.PathLike[str], hooks_dir: Path) ) from exc +def destination_location(destination: str | os.PathLike[str]) -> Path: + """Resolve a destination's parent without following its final component.""" + path = Path(destination) + if not path.name: + return path.resolve() + return path.parent.resolve() / path.name + + def realpath_within(candidate: str | os.PathLike[str], root: str | os.PathLike[str]) -> bool: """Return whether *candidate* lies at or under *root* after resolving both.""" try: diff --git a/src/autoskillit/hooks/_runtime/_write_target_scan.py b/src/autoskillit/hooks/_runtime/_write_target_scan.py index 55375672ab..a5c44f69b9 100644 --- a/src/autoskillit/hooks/_runtime/_write_target_scan.py +++ b/src/autoskillit/hooks/_runtime/_write_target_scan.py @@ -13,9 +13,7 @@ from autoskillit.hooks._classification._tokenizer import ArgvToken -WRITE_VERBS: frozenset[str] = frozenset( - {"sed", "tee", "mv", "cp", "patch", "install", "rm", "unlink"} -) +WRITE_VERBS: frozenset[str] = frozenset({"sed", "tee", "mv", "cp", "patch", "rm", "unlink"}) _PSEUDO_DEVICE_PATHS: frozenset[str] = frozenset( {"/dev/null", "/dev/zero", "/dev/stdout", "/dev/stderr", "/dev/stdin"} ) @@ -32,12 +30,13 @@ class WriteTargetScan: unresolved: bool parseable: bool has_write: bool + entry_targets: tuple[str, ...] = () def __post_init__(self) -> None: - if not self.parseable and self.targets: - raise ValueError("WriteTargetScan.targets must be empty when parseable is False") - if not self.has_write and self.targets: - raise ValueError("WriteTargetScan.targets must be empty when has_write is False") + if not self.parseable and (self.targets or self.entry_targets): + raise ValueError("WriteTargetScan targets must be empty when parseable is False") + if not self.has_write and (self.targets or self.entry_targets): + raise ValueError("WriteTargetScan targets must be empty when has_write is False") @dataclass(slots=True) @@ -56,6 +55,264 @@ def _classification_module() -> ModuleType: return standalone_classification +def _destination_operands( + verb: str, + argv: list[str], + argv_tokens: Sequence[ArgvToken] | None, +) -> tuple[list[int], tuple[str, str | None] | None, bool, bool, bool, bool]: + """Parse the supported ln/install options and positional operands.""" + _classification = _classification_module() + value = _classification._FlagArity.VALUE + if verb == "ln": + value_spec = { + "-t": value, + "--target-directory": value, + "-S": value, + "--suffix": value, + } + boolean_long = { + "--symbolic", + "--force", + "--no-dereference", + "--no-target-directory", + "--verbose", + } + boolean_short = frozenset("sfnTv") + else: + value_spec = { + "-t": value, + "--target-directory": value, + "-m": value, + "--mode": value, + "-o": value, + "--owner": value, + "-g": value, + "--group": value, + "-S": value, + "--suffix": value, + } + boolean_long = { + "--compare", + "--directory", + "--preserve-timestamps", + "--strip", + "--no-target-directory", + "--verbose", + } + boolean_short = frozenset("cCDdpsTvbZ") + + operands: list[int] = [] + target_directory: tuple[str, str | None] | None = None + no_target_directory = False + no_dereference = False + directory_mode = False + invalid = False + options = True + index = 1 + while index < len(argv): + token = argv[index] + if options and token == "--": + options = False + index += 1 + continue + if options and token.startswith("-") and token != "-": + option_value, source, next_index, recognized = ( + _classification._consume_destination_option(argv, argv_tokens, index, value_spec) + ) + if recognized: + option = _classification._spec_key_for_token(token, value_spec) + if option_value is None or option_value == "--": + invalid = True + elif option in {"-t", "--target-directory"}: + target_directory = (option_value, source) + index = next_index + continue + if token in boolean_long or ( + not token.startswith("--") and all(char in boolean_short for char in token[1:]) + ): + no_target_directory |= token in {"-T", "--no-target-directory"} or ( + not token.startswith("--") and "T" in token[1:] + ) + no_dereference |= token in {"-n", "--no-dereference"} or ( + not token.startswith("--") and "n" in token[1:] + ) + directory_mode |= token in {"-d", "--directory"} or ( + verb == "install" and not token.startswith("--") and "d" in token[1:] + ) + index += 1 + continue + invalid = True + index += 1 + continue + operands.append(index) + index += 1 + invalid |= target_directory is not None and no_target_directory + return ( + operands, + target_directory, + no_target_directory, + no_dereference, + directory_mode, + invalid, + ) + + +def _resolved_operand( + argv: list[str], + index: int, + cwd: str, + argv_tokens: Sequence[ArgvToken] | None, +) -> str | None: + _classification = _classification_module() + return _classification.resolve_write_target( + argv[index], + cwd, + shell_source=_classification._shell_source(argv_tokens, index), + ) + + +def _source_basename( + argv: list[str], + index: int, + cwd: str, + argv_tokens: Sequence[ArgvToken] | None, +) -> str | None: + source = _resolved_operand(argv, index, cwd, argv_tokens) + if source is None: + return None + return os.path.basename(source.rstrip(os.sep)) or None + + +def _directory_children( + directory: str, + source_indices: list[int], + argv: list[str], + cwd: str, + argv_tokens: Sequence[ArgvToken] | None, +) -> tuple[list[str], bool]: + targets: list[str] = [] + unresolved = False + for index in source_indices: + basename = _source_basename(argv, index, cwd, argv_tokens) + if basename is None: + unresolved = True + else: + targets.append(os.path.join(directory, basename)) + return targets, unresolved + + +def _install_targets( + argv: list[str], + cwd: str, + argv_tokens: Sequence[ArgvToken] | None, +) -> tuple[list[str], bool]: + _classification = _classification_module() + operands, target_directory, no_target, _no_deref, directory_mode, invalid = ( + _destination_operands("install", argv, argv_tokens) + ) + if invalid or not operands: + return [], True + if directory_mode: + if target_directory is not None: + return [], True + targets = [_resolved_operand(argv, index, cwd, argv_tokens) for index in operands] + return [target for target in targets if target is not None], any( + target is None for target in targets + ) + if target_directory is not None: + value, source = target_directory + directory = _classification.resolve_write_target(value, cwd, shell_source=source) + if directory is None: + return [], True + return _directory_children(directory, operands, argv, cwd, argv_tokens) + if len(operands) < 2: + return [], True + + destination = _resolved_operand(argv, operands[-1], cwd, argv_tokens) + if destination is None: + return [], True + sources = operands[:-1] + if no_target: + return ([destination], False) if len(sources) == 1 else ([], True) + if len(sources) > 1 or os.path.isdir(destination): + return _directory_children(destination, sources, argv, cwd, argv_tokens) + return [destination], False + + +def _ln_entry_targets( + argv: list[str], + cwd: str, + argv_tokens: Sequence[ArgvToken] | None, +) -> tuple[list[str], bool]: + _classification = _classification_module() + operands, target_directory, no_target, no_deref, _directory_mode, invalid = ( + _destination_operands("ln", argv, argv_tokens) + ) + if invalid or not operands: + return [], True + if target_directory is not None: + value, source = target_directory + directory = _classification.resolve_write_target(value, cwd, shell_source=source) + if directory is None: + return [], True + return _directory_children(directory, operands, argv, cwd, argv_tokens) + if len(operands) == 1: + basename = _source_basename(argv, operands[0], cwd, argv_tokens) + return ([os.path.join(cwd, basename)], False) if cwd and basename else ([], True) + + destination = _resolved_operand(argv, operands[-1], cwd, argv_tokens) + if destination is None: + return [], True + sources = operands[:-1] + if no_target and len(sources) > 1: + return [], True + follows_directory = not no_target and os.path.isdir(destination) + if no_deref and os.path.islink(destination): + follows_directory = False + if follows_directory or len(sources) > 1: + return _directory_children(destination, sources, argv, cwd, argv_tokens) + return [destination], False + + +def _npm_install_targets( + argv: list[str], + cwd: str, + argv_tokens: Sequence[ArgvToken] | None, +) -> tuple[list[str], bool, bool]: + _classification = _classification_module() + prefix_spec = {"--prefix": _classification._FlagArity.VALUE} + separator = argv.index("--") if "--" in argv[1:] else len(argv) + prefix: tuple[str, str | None] | None = None + missing_prefix = False + command_index: int | None = None + index = 1 + while index < separator: + token = argv[index] + if token.startswith("--prefix"): + value, source, next_index, recognized = _classification._consume_destination_option( + argv, argv_tokens, index, prefix_spec + ) + if not recognized: + return [], True, True + if value is None or value == "--": + missing_prefix = True + else: + prefix = (value, source) + index = next_index + continue + if command_index is None and token == "install": + command_index = index + elif command_index is None and not token.startswith("-"): + return [], False, False + index += 1 + if command_index is None or (prefix is None and not missing_prefix): + return [], False, False + if missing_prefix or prefix is None: + return [], True, True + target = _classification.resolve_write_target(prefix[0], cwd, shell_source=prefix[1]) + return ([target], False, True) if target is not None else ([], True, True) + + def _ensure_scope_state( scopes: dict[tuple[int, ...], _ShellDirectoryState], path: tuple[int, ...] ) -> _ShellDirectoryState: @@ -283,7 +540,7 @@ def _scan_executable( argv_tokens: Sequence[ArgvToken] | None, state: _ShellDirectoryState, path: tuple[int, ...] | None, -) -> tuple[list[str], bool, bool, _ShellDirectoryState | None]: +) -> tuple[list[str], list[str], bool, bool, _ShellDirectoryState | None]: _classification = _classification_module() start = _classification._verb_start_index(executable) @@ -292,30 +549,37 @@ def _scan_executable( if setting is not None: state.cdpath_unknown = setting[0] if start is None: - return [], False, False, None + return [], [], False, False, None handled = _apply_shell_builtin(executable, start, argv_tokens, state) if setting is not None and setting[1]: state.cdpath_unknown = previous_cdpath - if handled: - return [], False, False, None - if _classification.is_gh_command(executable): - return [], False, False, None + if handled or _classification.is_gh_command(executable): + return [], [], False, False, None argv = executable[start:] verb = argv[0] verb_cwd = _classification._wrapped_verb_cwd(executable, start, state.cwd, argv_tokens) invoked = _invoked_child_state(verb, verb_cwd, state, path) verb_tokens = None if argv_tokens is None else argv_tokens[start:] + if verb == "npm": + targets, unresolved, has_write = _npm_install_targets(argv, verb_cwd, verb_tokens) + return targets, [], unresolved, has_write, invoked + if verb == "ln": + targets, unresolved = _ln_entry_targets(argv, verb_cwd, verb_tokens) + return [], targets, unresolved, True, invoked + if verb == "install": + targets, unresolved = _install_targets(argv, verb_cwd, verb_tokens) + return targets, [], unresolved, True, invoked if verb in WRITE_VERBS: targets, unresolved = _classification.extract_write_verb_targets( verb, argv, verb_cwd, argv_tokens=verb_tokens ) - return targets, unresolved, True, invoked + return targets, [], unresolved, True, invoked if verb == "git" or verb.endswith("/git"): targets, unresolved, has_write = _classification._git_write_targets( argv, verb_cwd, executable[:start], verb_tokens ) - return targets, unresolved, has_write, invoked - return [], False, False, invoked + return targets, [], unresolved, has_write, invoked + return [], [], False, False, invoked def scan_write_targets(command: str, cwd: str) -> WriteTargetScan: @@ -329,6 +593,7 @@ def scan_write_targets(command: str, cwd: str) -> WriteTargetScan: return WriteTargetScan((), False, False, False) targets: list[str] = [] + entry_targets: list[str] = [] unresolved = False has_write = False scopes: dict[tuple[int, ...], _ShellDirectoryState] = { @@ -356,10 +621,11 @@ def scan_write_targets(command: str, cwd: str) -> WriteTargetScan: if record.argv_tokens is None else [record.argv_tokens[index] for index in partition.segments] ) - verb_targets, verb_unresolved, verb_has_write, invoked = _scan_executable( + verb_targets, verb_entries, verb_unresolved, verb_has_write, invoked = _scan_executable( executable, executable_tokens, state, record.subshell_path ) targets.extend(verb_targets) + entry_targets.extend(verb_entries) targets.extend(partition.targets) unresolved |= verb_unresolved has_write |= verb_has_write @@ -370,6 +636,7 @@ def scan_write_targets(command: str, cwd: str) -> WriteTargetScan: unresolved, True, has_write, + tuple(dict.fromkeys(entry_targets)), ) diff --git a/src/autoskillit/hooks/guards/git_ops_guard.py b/src/autoskillit/hooks/guards/git_ops_guard.py index e80d976095..c1208960c6 100644 --- a/src/autoskillit/hooks/guards/git_ops_guard.py +++ b/src/autoskillit/hooks/guards/git_ops_guard.py @@ -72,6 +72,7 @@ hook_session_shape, read_merged_hook_config, ) +from _path_identity import destination_location # noqa: E402 GIT_OPS_DENY_TRIGGER: str = DENY_TRIGGER_BY_GUARD["git_ops_guard"] CHECKED_OUT_REF_DENY_PREFIX: str = "Checked-out ref mutation blocked: " @@ -83,9 +84,7 @@ # only the destructive headless operation phase below. _DESTRUCTIVE_OP_EXEMPT_TIERS: frozenset[str] = frozenset({"orchestrator"}) -_RAW_WRITE_VERBS = frozenset( - {"cp", "mv", "install", "tee", "truncate", "rm", "unlink", "sed", "dd"} -) +_RAW_WRITE_VERBS = frozenset({"cp", "mv", "tee", "truncate", "rm", "unlink", "sed", "dd"}) # Git subcommands that can mutate checked-out refs (the same set # _classify_git_segment recognises). Used by _deny_outer_git_mutations @@ -204,9 +203,10 @@ def _raw_write_targets( additional_segments: list[list[str]], additional_owners: list[int | None], interpreter_cwd: str, -) -> tuple[list[tuple[str, str]], bool]: +) -> tuple[list[tuple[str, str]], list[tuple[str, str]], bool]: scan = scan_write_targets(text, initial_cwd) targets = [(target, initial_cwd) for target in scan.targets] + entry_targets = [(target, initial_cwd) for target in scan.entry_targets] ambiguous = scan.unresolved outer_cwds = _compute_outer_cwds(outer_segments, initial_cwd) segments_with_cwds = list(zip(outer_segments, outer_cwds)) @@ -238,7 +238,7 @@ def _raw_write_targets( ambiguous = True elif interpreter_paths: targets.extend((path, interpreter_cwd) for path in interpreter_paths) - return (targets, ambiguous) + return (targets, entry_targets, ambiguous) def _raw_target_mutations( @@ -251,7 +251,7 @@ def _raw_target_mutations( interpreter_cwd: str, context: dict[str, object] | None, ) -> list[tuple[str, str, bool]]: - targets, ambiguous = _raw_write_targets( + targets, entry_targets, ambiguous = _raw_write_targets( text, initial_cwd, outer_segments, @@ -262,13 +262,14 @@ def _raw_target_mutations( if ambiguous: return [("", "", True)] resolved_targets: list[Path] = [] - for raw_target, target_cwd in targets: - target = Path(raw_target) - if not target.is_absolute(): - if not target_cwd: - return [("", "", True)] - target = Path(target_cwd) / target - resolved_targets.append(target.resolve()) + for raw_targets, is_entry in ((targets, False), (entry_targets, True)): + for raw_target, target_cwd in raw_targets: + target = Path(raw_target) + if not target.is_absolute(): + if not target_cwd: + return [("", "", True)] + target = Path(target_cwd) / target + resolved_targets.append(destination_location(target) if is_entry else target.resolve()) if context is None: return [] common = Path(str(context["common_git_dir"])).resolve() @@ -381,6 +382,7 @@ def _is_structural_mutation( r"reset\b|fetch\b|push\b|symbolic-ref\s+HEAD)\b", live_text, ) + or scan_write_targets(live_text, "").has_write or any( os.path.basename(command_verb_and_args(segment)[0]) in _RAW_WRITE_VERBS for segment in [*outer, *additional] diff --git a/src/autoskillit/hooks/guards/installation_integrity_guard.py b/src/autoskillit/hooks/guards/installation_integrity_guard.py index 067853647f..e88651a443 100644 --- a/src/autoskillit/hooks/guards/installation_integrity_guard.py +++ b/src/autoskillit/hooks/guards/installation_integrity_guard.py @@ -5,6 +5,7 @@ import json import os +import stat import sys from pathlib import Path from typing import TYPE_CHECKING, NoReturn @@ -32,7 +33,7 @@ normalize_payload_cwd, parse_hook_command, ) -from _path_identity import realpath_within # noqa: E402 +from _path_identity import destination_location, realpath_within # noqa: E402 from _policy_event import ( # noqa: E402 PolicyEvent, render_provenance_prefix, @@ -139,9 +140,34 @@ def _is_protected_target(path: str) -> bool: return _matches_protected_inode(normalized) -def _bash_targets(command: str, cwd: str) -> tuple[list[str], bool]: +def _is_protected_entry_target(path: str) -> bool: + try: + location = destination_location(Path(path)) + except (OSError, RuntimeError, ValueError): + return True + if _has_install_layout(str(location)): + return True + for root in _known_roots(): + try: + root_locations = {destination_location(root), root.resolve()} + except (OSError, RuntimeError, ValueError): + return True + for root_location in root_locations: + if location == root_location or str(location).startswith(str(root_location) + os.sep): + return True + try: + entry = os.lstat(path) + except OSError: + return False + if stat.S_ISLNK(entry.st_mode): + return False + return _matches_protected_inode(str(location)) + + +def _bash_targets(command: str, cwd: str) -> tuple[list[str], list[str], bool]: scan = scan_write_targets(command, cwd) targets = list(scan.targets) + entry_targets = list(scan.entry_targets) unresolved_target = scan.unresolved or not scan.parseable interpreter_paths = extract_interpreter_write_paths(command) # ``extract_interpreter_write_paths``: None=non-write, []=interpreter write @@ -156,10 +182,10 @@ def _bash_targets(command: str, cwd: str) -> tuple[list[str], bool]: unresolved_target = True else: targets.append(resolved) - return targets, unresolved_target + return targets, entry_targets, unresolved_target -def _resolve_targets(paths: list[str], cwd: str) -> tuple[list[str], bool]: +def _resolve_targets(paths: list[str], cwd: str) -> tuple[list[str], list[str], bool]: targets: list[str] = [] unresolved_target = False for path in paths: @@ -168,13 +194,13 @@ def _resolve_targets(paths: list[str], cwd: str) -> tuple[list[str], bool]: unresolved_target = True else: targets.append(resolved) - return targets, unresolved_target + return targets, [], unresolved_target -def _collect_write_targets(data: dict[str, object]) -> tuple[list[str], bool]: +def _collect_write_targets(data: dict[str, object]) -> tuple[list[str], list[str], bool]: tool_name = data.get("tool_name") if not isinstance(tool_name, str): - return [], False + return [], [], False payload_cwd = normalize_payload_cwd(data.get("cwd")) edit_paths = edit_target_paths(data) if edit_paths: @@ -182,7 +208,7 @@ def _collect_write_targets(data: dict[str, object]) -> tuple[list[str], bool]: parsed = parse_hook_command(data) if parsed.tool_kind in {"bash", "run_cmd"}: return _bash_targets(parsed.command or "", parsed.execution_cwd) - return [], False + return [], [], False def main() -> None: @@ -193,14 +219,16 @@ def main() -> None: if not isinstance(data, dict): sys.exit(0) - targets, unresolved_target = _collect_write_targets(data) + targets, entry_targets, unresolved_target = _collect_write_targets(data) if unresolved_target: _deny( "unresolved-write-target", "Write target could not be resolved safely. " + UNRESOLVED_WRITE_TARGET_REMEDIATION, ) - if any(_is_protected_target(path) for path in targets): + if any(_is_protected_target(path) for path in targets) or any( + _is_protected_entry_target(path) for path in entry_targets + ): _deny( "protected-installation-target", f"Writing a {INSTALLATION_INTEGRITY_DENY_TRIGGER} is prohibited.", diff --git a/src/autoskillit/hooks/guards/write_guard.py b/src/autoskillit/hooks/guards/write_guard.py index b715694328..1356c0e432 100644 --- a/src/autoskillit/hooks/guards/write_guard.py +++ b/src/autoskillit/hooks/guards/write_guard.py @@ -36,6 +36,7 @@ from _guard_decision_diagnostics import ( # noqa: E402 record_guard_decision, ) +from _path_identity import destination_location # noqa: E402 if TYPE_CHECKING: from .._runtime._hook_output import deny_tool_use @@ -131,9 +132,12 @@ def _bash_validation_error( f"Write/Edit/apply_patch blocked: {WRITE_GUARD_DENY_TRIGGER} " "(unresolved write target). " + UNRESOLVED_WRITE_TARGET_REMEDIATION ) - if not scan.targets: + if not scan.targets and not scan.entry_targets: return None - return _paths_validation_error(list(scan.targets), norm_prefixes, display_prefix) + content_error = _paths_validation_error(list(scan.targets), norm_prefixes, display_prefix) + if content_error is not None: + return content_error + return _entry_paths_validation_error(list(scan.entry_targets), norm_prefixes, display_prefix) def _record(data: object, *, activation: str, scope: str, decision: str, reason: str) -> None: @@ -323,6 +327,28 @@ def _paths_validation_error( return None +def _entry_paths_validation_error( + paths: list[str], norm_prefixes: list[str], display_prefix: str +) -> str | None: + for path in paths: + try: + location = str(destination_location(Path(path))) + except (OSError, RuntimeError, ValueError): + return ( + f"Write/Edit/apply_patch blocked: {WRITE_GUARD_DENY_TRIGGER}. " + f"Only writes to {display_prefix} are permitted." + ) + if not any( + location.startswith(prefix) or location == prefix.rstrip("/") + for prefix in norm_prefixes + ): + return ( + f"Write/Edit/apply_patch blocked: {WRITE_GUARD_DENY_TRIGGER}. " + f"Only writes to {display_prefix} are permitted." + ) + return None + + def _direct_path_validation_error( file_path: str, norm_prefixes: list[str], display_prefix: str ) -> str | None: diff --git a/src/autoskillit/server/lifecycle/_guards.py b/src/autoskillit/server/lifecycle/_guards.py index 068a1ca7ee..fdb68bc012 100644 --- a/src/autoskillit/server/lifecycle/_guards.py +++ b/src/autoskillit/server/lifecycle/_guards.py @@ -15,6 +15,7 @@ BackendPinResolution, FaultDomain, InputContractResolver, + destination_location, extract_path_arg, extract_positional_args, extract_skill_name, @@ -155,12 +156,25 @@ def _check_write_target_boundary( "run_cmd write target could not be resolved safely. " + UNRESOLVED_WRITE_TARGET_REMEDIATION ) - if not scan.targets: + if not scan.targets and not scan.entry_targets: return None normalized = tuple(os.path.realpath(p).rstrip("/") + "/" for p in allowed_prefixes) for target in scan.targets: resolved = os.path.realpath(target) - if not any(resolved.startswith(pfx) for pfx in normalized): + if not any(resolved.startswith(pfx) or resolved == pfx.rstrip("/") for pfx in normalized): + return gate_error_result( + f"run_cmd write target {target!r} is outside allowed write prefixes: " + f"{', '.join(allowed_prefixes)}" + ) + for target in scan.entry_targets: + try: + location = str(destination_location(Path(target))) + except (OSError, RuntimeError, ValueError): + return gate_error_result( + "run_cmd write target could not be resolved safely. " + + UNRESOLVED_WRITE_TARGET_REMEDIATION + ) + if not any(location.startswith(pfx) or location == pfx.rstrip("/") for pfx in normalized): return gate_error_result( f"run_cmd write target {target!r} is outside allowed write prefixes: " f"{', '.join(allowed_prefixes)}" diff --git a/tests/arch/test_hook_path_identity_guard.py b/tests/arch/test_hook_path_identity_guard.py index e73e079f6c..df6c6bf941 100644 --- a/tests/arch/test_hook_path_identity_guard.py +++ b/tests/arch/test_hook_path_identity_guard.py @@ -31,8 +31,9 @@ _ALLOWLISTED_SITES: dict[SiteKey, str] = { ("guards/git_ops_guard.py", "_relative_to"): ( - "target, common and worktree_git are each .resolve()d by _raw_target_mutations " - "before _classify_raw_write_target receives them, so both operands are canonical." + "_raw_target_mutations canonicalizes content targets with .resolve(), entry " + "targets with destination_location (resolved parent plus literal basename), " + "and common/worktree_git roots with .resolve() before classification." ), ("formatters/_fmt_response_spill.py", "_response_spill_artifact_is_trusted"): ( "resolved comes from artifact.resolve(strict=True) inline and project_temp from " diff --git a/tests/contracts/test_skill_write_target_conformance.py b/tests/contracts/test_skill_write_target_conformance.py index 26d87de979..d0bdcceae9 100644 --- a/tests/contracts/test_skill_write_target_conformance.py +++ b/tests/contracts/test_skill_write_target_conformance.py @@ -124,7 +124,7 @@ def _assert_allowed(command: str, tool: str, checkout: Path, monkeypatch: pytest denials = _guard_denials(event, monkeypatch) scan = scan_write_targets(command, str(checkout)) assert not denials, ( - f"targets={scan.targets}; {'; '.join(denials)}; " + f"targets={scan.targets}; entry_targets={scan.entry_targets}; {'; '.join(denials)}; " "see skills_extended/AGENTS.md § Literal write targets" ) diff --git a/tests/execution/headless/test_headless_scan.py b/tests/execution/headless/test_headless_scan.py index 33861e9d6b..795f28d3c0 100644 --- a/tests/execution/headless/test_headless_scan.py +++ b/tests/execution/headless/test_headless_scan.py @@ -74,11 +74,22 @@ class TestScanJsonlWriteWarnings: "Bash command contained write target '/outside/y' outside session cwd '{cwd}'", id="outside-cwd-target", ), + pytest.param( + "ln -sf /opt/tools/jq /outside/jq", + "Bash command contained write target '/outside/jq' outside session cwd '{cwd}'", + id="outside-cwd-link-entry", + ), + pytest.param( + 'ln -sf /opt/tools/jq "$LINK_NAME"', + GENERIC_UNRESOLVED_WARNING, + id="unresolved-link-entry", + ), pytest.param("printf '> q' > inside.txt", None, id="quoted-redirect-operator"), ], ) def test_bash_jsonl_write_warnings(self, tmp_path, monkeypatch, command, expected_warning): monkeypatch.delenv("F", raising=False) + monkeypatch.delenv("LINK_NAME", raising=False) cwd = str(tmp_path) line = _make_tool_use_line("Bash", {"command": command}) diff --git a/tests/hooks/test_command_classification.py b/tests/hooks/test_command_classification.py index f39e0724d6..9937e125f5 100644 --- a/tests/hooks/test_command_classification.py +++ b/tests/hooks/test_command_classification.py @@ -1543,6 +1543,40 @@ def test_chained_write_bytes_on_open_not_double_counted(self): class TestScanWriteTargets: + def test_scan_result_entry_targets_is_last_and_defaults_empty(self) -> None: + fields = dataclasses.fields(command_classification.WriteTargetScan) + + assert fields[-1].name == "entry_targets" + assert fields[-1].default == () + assert command_classification.WriteTargetScan((), False, True, False).entry_targets == () + + def test_entry_only_scan_is_a_write(self) -> None: + scan = command_classification.WriteTargetScan( + targets=(), + unresolved=False, + parseable=True, + has_write=True, + entry_targets=("/tmp/link",), + ) + + assert scan.targets == () + assert scan.entry_targets == ("/tmp/link",) + + @pytest.mark.parametrize( + ("parseable", "has_write"), + [(False, True), (True, False)], + ids=("unparseable", "not-a-write"), + ) + def test_entry_targets_obey_scan_invariants(self, parseable: bool, has_write: bool) -> None: + with pytest.raises(ValueError): + command_classification.WriteTargetScan( + targets=(), + unresolved=False, + parseable=parseable, + has_write=has_write, + entry_targets=("/tmp/link",), + ) + @pytest.mark.parametrize( ("command", "targets", "unresolved", "parseable", "has_write"), [ diff --git a/tests/hooks/test_installation_integrity_guard.py b/tests/hooks/test_installation_integrity_guard.py index 3808671b07..17d383aa61 100644 --- a/tests/hooks/test_installation_integrity_guard.py +++ b/tests/hooks/test_installation_integrity_guard.py @@ -308,6 +308,97 @@ def test_blocks_hardlink_alias_of_uv_tool_file(tmp_path: Path) -> None: assert _decision(stdout) == "deny" +def test_blocks_ln_replacement_of_hardlink_alias_of_uv_tool_file(tmp_path: Path) -> None: + home = tmp_path / "home" + original = home / ".local/share/uv/tools/autoskillit/lib/site-packages/autoskillit/core.py" + original.parent.mkdir(parents=True) + original.write_text("source", encoding="utf-8") + alias = tmp_path / "ordinary-project" / "linked.py" + alias.parent.mkdir() + os.link(original, alias) + + code, stdout = _run( + _bash(f"ln -f {tmp_path / 'replacement.py'} {alias}"), + env={"HOME": str(home)}, + ) + + assert code == 0 + assert _decision(stdout) == "deny" + + +@pytest.mark.parametrize( + "command_template", + [ + "npm install --prefix {target} package", + "ln -sf /tmp/source {target}", + ], + ids=["npm-prefix", "ln-entry"], +) +def test_blocks_explicit_install_tree_destinations(tmp_path: Path, command_template: str) -> None: + target = tmp_path / "lib/python3.13/site-packages/autoskillit/destination" + + code, stdout = _run(_bash(command_template.format(target=target))) + + assert code == 0 + assert _decision(stdout) == "deny" + assert ( + "code=protected-installation-target" + in json.loads(stdout)["hookSpecificOutput"]["permissionDecisionReason"] + ) + + +@pytest.mark.parametrize( + "command", + [ + 'npm install --prefix "$DESTINATION" package', + 'ln -sf /tmp/source "$DESTINATION"', + ], + ids=["npm-prefix", "ln-entry"], +) +def test_blocks_unresolved_explicit_destinations( + command: str, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.delenv("DESTINATION", raising=False) + code, stdout = _run(_bash(command)) + + assert code == 0 + assert _decision(stdout) == "deny" + assert ( + "code=unresolved-write-target" + in json.loads(stdout)["hookSpecificOutput"]["permissionDecisionReason"] + ) + + +def test_ln_entry_location_does_not_follow_outside_symlink_into_install_tree( + tmp_path: Path, +) -> None: + protected = tmp_path / "lib/python3.13/site-packages/autoskillit/core.py" + protected.parent.mkdir(parents=True) + protected.write_text("protected", encoding="utf-8") + outside_link = tmp_path / "ordinary-project/core.py" + outside_link.parent.mkdir() + outside_link.symlink_to(protected) + + code, stdout = _run(_bash(f"ln -sf {tmp_path / 'replacement.py'} {outside_link}")) + + assert code == 0 + assert stdout == "" + + +def test_ln_entry_location_protects_symlink_inside_install_tree(tmp_path: Path) -> None: + protected_link = tmp_path / "lib/python3.13/site-packages/autoskillit/core.py" + protected_link.parent.mkdir(parents=True) + outside = tmp_path / "ordinary-project/core.py" + outside.parent.mkdir() + outside.write_text("outside", encoding="utf-8") + protected_link.symlink_to(outside) + + code, stdout = _run(_bash(f"ln -sf {tmp_path / 'replacement.py'} {protected_link}")) + + assert code == 0 + assert _decision(stdout) == "deny" + + def test_blocks_shell_local_variable_target(tmp_path: Path) -> None: target = tmp_path / "lib/python3.13/site-packages/autoskillit/__init__.py" code, stdout = _run(_bash(f"FOO={target.parent}; cat > $FOO/__init__.py <<'EOF'\nEOF")) diff --git a/tests/hooks/test_path_identity.py b/tests/hooks/test_path_identity.py index 1495f44f2f..435e3c3523 100644 --- a/tests/hooks/test_path_identity.py +++ b/tests/hooks/test_path_identity.py @@ -8,6 +8,7 @@ from autoskillit.hooks._runtime._path_identity import ( PathIdentityError, + destination_location, hooks_relative_key, realpath_within, ) @@ -73,3 +74,23 @@ def test_realpath_within_matches_commonpath_containment(tmp_path: Path) -> None: ) for candidate, container, expected in cases: assert realpath_within(candidate, container) is expected, candidate + + +def test_destination_location_resolves_parent_but_not_final_component(tmp_path: Path) -> None: + real_parent = tmp_path / "real-parent" + real_parent.mkdir() + linked_parent = tmp_path / "linked-parent" + linked_parent.symlink_to(real_parent, target_is_directory=True) + + assert destination_location(linked_parent / "entry") == real_parent / "entry" + + +def test_destination_location_preserves_dangling_final_symlink(tmp_path: Path) -> None: + dangling = tmp_path / "dangling" + dangling.symlink_to(tmp_path / "missing") + + assert destination_location(dangling) == dangling + + +def test_destination_location_handles_root_destination() -> None: + assert destination_location(Path("/")) == Path("/") diff --git a/tests/hooks/test_write_guard.py b/tests/hooks/test_write_guard.py index a8872f46e5..3d1321dc54 100644 --- a/tests/hooks/test_write_guard.py +++ b/tests/hooks/test_write_guard.py @@ -590,6 +590,237 @@ def test_bash_no_prefix_allows_all(self, monkeypatch: pytest.MonkeyPatch, tmp_pa _assert_installation_floor_denies(tmp_path) +def _assert_bash_scope_decision( + monkeypatch: pytest.MonkeyPatch, + *, + command: str, + cwd, + allowed, + permitted: bool, + unresolved: bool = False, +) -> None: + monkeypatch.setenv("AUTOSKILLIT_HEADLESS", "1") + monkeypatch.setenv("AUTOSKILLIT_AGENT_BACKEND", "claude-code") + monkeypatch.setenv("AUTOSKILLIT_ALLOWED_WRITE_PREFIX", str(allowed)) + monkeypatch.setenv("AUTOSKILLIT_CWD", str(cwd)) + + result = _run_hook(_build_bash_event(command)) + + if permitted: + assert result == "" + return + output = json.loads(result)["hookSpecificOutput"] + assert output["permissionDecision"] == "deny" + if unresolved: + assert UNRESOLVED_WRITE_TARGET_REMEDIATION in output["permissionDecisionReason"] + + +@pytest.mark.parametrize( + ("command_template", "destination", "permitted", "unresolved"), + [ + pytest.param( + "npm install --prefix {destination} node-jq", + "allowed", + True, + False, + id="npm-allowed-prefix", + ), + pytest.param( + "npm --prefix={destination} install node-jq", + "outside", + False, + False, + id="npm-outside-prefix", + ), + pytest.param( + 'npm install --prefix "$NPM_PREFIX" node-jq', + "unresolved", + False, + True, + id="npm-unresolved-prefix", + ), + pytest.param( + "ln -sf /opt/tools/jq {destination}/jq", + "allowed", + True, + False, + id="ln-external-source-allowed-entry", + ), + pytest.param( + "ln -sf /opt/tools/jq {destination}/jq", + "outside", + False, + False, + id="ln-outside-entry", + ), + pytest.param( + 'ln -sf /opt/tools/jq "$LINK_NAME"', + "unresolved", + False, + True, + id="ln-unresolved-entry", + ), + ], +) +def test_npm_and_ln_destinations_reach_bash_scope_policy( + monkeypatch: pytest.MonkeyPatch, + tmp_path, + command_template: str, + destination: str, + permitted: bool, + unresolved: bool, +) -> None: + monkeypatch.delenv("NPM_PREFIX", raising=False) + monkeypatch.delenv("LINK_NAME", raising=False) + allowed = tmp_path / "project" / ".autoskillit" / "temp" / "review-pr" + outside = tmp_path / "outside" + allowed.mkdir(parents=True) + outside.mkdir() + selected = allowed if destination == "allowed" else outside + command = command_template.format(destination=selected) + + _assert_bash_scope_decision( + monkeypatch, + command=command, + cwd=tmp_path / "project", + allowed=allowed, + permitted=permitted, + unresolved=unresolved, + ) + + +@pytest.mark.parametrize( + "command", + [ + "cd /tmp && npm install --prefix /tmp/jqinst node-jq", + "ln -sf /tmp/jqinst/node_modules/node-jq/bin/jq /usr/local/bin/jq", + ], + ids=["observed-npm-install", "observed-ln-install"], +) +def test_incident_commands_are_denied_by_project_temp_scope( + monkeypatch: pytest.MonkeyPatch, tmp_path, command: str +) -> None: + project = tmp_path / "project" + allowed = project / ".autoskillit" / "temp" / "review-pr" + allowed.mkdir(parents=True) + + _assert_bash_scope_decision( + monkeypatch, + command=command, + cwd=project, + allowed=allowed, + permitted=False, + ) + + +def test_ln_entry_location_does_not_follow_final_symlink( + monkeypatch: pytest.MonkeyPatch, tmp_path +) -> None: + allowed = tmp_path / "allowed" + outside = tmp_path / "outside" + allowed.mkdir() + outside.mkdir() + inside_file = allowed / "inside" + outside_file = outside / "outside" + inside_file.write_text("inside", encoding="utf-8") + outside_file.write_text("outside", encoding="utf-8") + outside_link = outside / "link" + inside_link = allowed / "link" + outside_link.symlink_to(inside_file) + inside_link.symlink_to(outside_file) + + _assert_bash_scope_decision( + monkeypatch, + command=f"ln -sf /opt/tools/jq {outside_link}", + cwd=tmp_path, + allowed=allowed, + permitted=False, + ) + _assert_bash_scope_decision( + monkeypatch, + command=f"ln -sf /opt/tools/jq {inside_link}", + cwd=tmp_path, + allowed=allowed, + permitted=True, + ) + + result = _run_hook(_build_event("Write", str(inside_link))) + assert json.loads(result)["hookSpecificOutput"]["permissionDecision"] == "deny" + + +@pytest.mark.parametrize("entry_flag", ["-sfT", "-sfn"]) +def test_ln_no_directory_dereference_replaces_allowed_symlink_entry( + monkeypatch: pytest.MonkeyPatch, tmp_path, entry_flag: str +) -> None: + allowed = tmp_path / "allowed" + outside_dir = tmp_path / "outside-dir" + allowed.mkdir() + outside_dir.mkdir() + directory_link = allowed / "directory-link" + directory_link.symlink_to(outside_dir, target_is_directory=True) + + _assert_bash_scope_decision( + monkeypatch, + command=f"ln {entry_flag} /opt/tools/jq {directory_link}", + cwd=tmp_path, + allowed=allowed, + permitted=True, + ) + + +def test_ln_ordinary_directory_semantics_follow_final_directory_symlink( + monkeypatch: pytest.MonkeyPatch, tmp_path +) -> None: + allowed = tmp_path / "allowed" + outside_dir = tmp_path / "outside-dir" + allowed.mkdir() + outside_dir.mkdir() + directory_link = allowed / "directory-link" + directory_link.symlink_to(outside_dir, target_is_directory=True) + + _assert_bash_scope_decision( + monkeypatch, + command=f"ln -s /opt/tools/jq {directory_link}", + cwd=tmp_path, + allowed=allowed, + permitted=False, + ) + + +def test_ln_directory_child_entry_does_not_follow_existing_child_symlink( + monkeypatch: pytest.MonkeyPatch, tmp_path +) -> None: + allowed = tmp_path / "allowed" + outside = tmp_path / "outside" + allowed.mkdir() + outside.mkdir() + (allowed / "jq").symlink_to(outside / "referent") + + _assert_bash_scope_decision( + monkeypatch, + command=f"ln -sf /opt/tools/jq {allowed}", + cwd=tmp_path, + allowed=allowed, + permitted=True, + ) + + +def test_ln_entry_resolves_symlinked_parent(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None: + allowed = tmp_path / "allowed" + outside = tmp_path / "outside" + allowed.mkdir() + outside.mkdir() + (allowed / "escaped-parent").symlink_to(outside, target_is_directory=True) + + _assert_bash_scope_decision( + monkeypatch, + command=f"ln -sf /opt/tools/jq {allowed / 'escaped-parent' / 'jq'}", + cwd=tmp_path, + allowed=allowed, + permitted=False, + ) + + @pytest.mark.parametrize("command", ['echo x > "$F"', 'cp a "$F"']) def test_denies_unresolved_bash_write_target( monkeypatch: pytest.MonkeyPatch, tmp_path, command: str diff --git a/tests/hooks/test_write_target_scan.py b/tests/hooks/test_write_target_scan.py index 7f67463ac4..4e26f66a44 100644 --- a/tests/hooks/test_write_target_scan.py +++ b/tests/hooks/test_write_target_scan.py @@ -2,6 +2,8 @@ from __future__ import annotations +from pathlib import Path + import pytest from autoskillit.hooks import scan_write_targets @@ -140,3 +142,222 @@ def test_scan_write_target_expectations( assert result.targets == expected_targets, f"targets for {command!r}" assert result.unresolved is expected_unresolved, f"unresolved status for {command!r}" + + +@pytest.mark.parametrize( + ("command", "targets", "unresolved", "has_write"), + [ + ("npm install --prefix /opt/app pkg", ("/opt/app",), False, True), + ("npm install --prefix=/opt/app pkg", ("/opt/app",), False, True), + ("npm --prefix /opt/app install pkg", ("/opt/app",), False, True), + ("npm install --prefix 'relative app' pkg", ("/workspace/relative app",), False, True), + ('npm install --prefix="$NPM_PREFIX" pkg', ("/resolved/npm",), False, True), + ("npm install --prefix='$NPM_UNKNOWN' pkg", ("/workspace/$NPM_UNKNOWN",), False, True), + ('npm install --prefix="$NPM_UNKNOWN" pkg', (), True, True), + ("npm install --prefix", (), True, True), + ("npm install -- --prefix /opt/app", (), False, False), + ], + ids=( + "detached-after-install", + "equals-after-install", + "detached-before-install", + "quoted-relative", + "attached-known-variable", + "attached-single-quoted-variable", + "attached-unknown-variable", + "missing-prefix-value", + "option-terminator", + ), +) +def test_npm_install_explicit_prefix( + command: str, + targets: tuple[str, ...], + unresolved: bool, + has_write: bool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("NPM_PREFIX", "/resolved/npm") + monkeypatch.delenv("NPM_UNKNOWN", raising=False) + + result = scan_write_targets(command, _WORKSPACE) + + assert result.targets == targets + assert result.entry_targets == () + assert result.unresolved is unresolved + assert result.has_write is has_write + + +@pytest.mark.parametrize( + ("command", "entry_targets"), + [ + ("ln source link", ("/workspace/link",)), + ("ln -s source link", ("/workspace/link",)), + ("ln -f source link", ("/workspace/link",)), + ("ln -sf source link", ("/workspace/link",)), + ("ln source", ("/workspace/source",)), + ("ln -t /links path/to/source", ("/links/source",)), + ("ln --target-directory /links source", ("/links/source",)), + ("ln --target-directory=/links source", ("/links/source",)), + ("ln -t/links source", ("/links/source",)), + ("ln -t /links one/a two/b", ("/links/a", "/links/b")), + ], +) +def test_ln_literal_entry_destinations(command: str, entry_targets: tuple[str, ...]) -> None: + result = scan_write_targets(command, _WORKSPACE) + + assert result.targets == () + assert result.entry_targets == entry_targets + assert result.unresolved is False + assert result.has_write is True + + +def test_ln_directory_and_final_symlink_semantics( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + directory = tmp_path / "directory" + directory.mkdir() + directory_link = tmp_path / "directory-link" + directory_link.symlink_to(directory, target_is_directory=True) + monkeypatch.delenv("LN_SOURCE", raising=False) + cases = ( + (f"ln source {directory}", (str(directory / "source"),), False), + (f"ln source {directory_link}", (str(directory_link / "source"),), False), + (f'ln -T "$LN_SOURCE" {directory_link}', (str(directory_link),), False), + (f'ln -n "$LN_SOURCE" {directory_link}', (str(directory_link),), False), + (f"ln -n source {directory}", (str(directory / "source"),), False), + (f'ln "$LN_SOURCE" {directory}', (), True), + ) + + for command, entries, unresolved in cases: + result = scan_write_targets(command, str(tmp_path)) + assert result.entry_targets == entries, command + assert result.unresolved is unresolved, command + assert result.has_write is True, command + + +@pytest.mark.parametrize( + "command", + [ + "ln --unknown value source link", + "ln -t /links -T source", + "ln --target-directory /links", + "ln source --target-directory", + "install -t /dest -T source", + "install source --target-directory", + "install --target-directory /dest", + ], +) +def test_unsupported_or_incomplete_destination_grammar_is_unresolved(command: str) -> None: + result = scan_write_targets(command, _WORKSPACE) + + assert result.targets == () + assert result.entry_targets == () + assert result.unresolved is True + assert result.has_write is True + + +@pytest.mark.parametrize( + ("command", "targets"), + [ + ("install -t /dest path/to/source", ("/dest/source",)), + ("install path/to/source -t /dest", ("/dest/source",)), + ("install -t/dest path/to/source", ("/dest/source",)), + ("install --target-directory=/dest path/to/source", ("/dest/source",)), + ("install --target-directory /dest one/a two/b", ("/dest/a", "/dest/b")), + ], +) +def test_install_target_directory_emits_child_content_destinations( + command: str, targets: tuple[str, ...] +) -> None: + result = scan_write_targets(command, _WORKSPACE) + + assert result.targets == targets + assert result.entry_targets == () + assert result.unresolved is False + assert result.has_write is True + + +@pytest.mark.parametrize( + ("command", "targets", "entry_targets"), + [ + ( + 'ln --target-directory="$TARGET_DIRECTORY" source', + (), + ("/resolved/target/source",), + ), + ( + "ln --target-directory='$UNKNOWN_DIRECTORY' source", + (), + ("/workspace/$UNKNOWN_DIRECTORY/source",), + ), + ( + 'install --target-directory="$TARGET_DIRECTORY" path/to/source', + ("/resolved/target/source",), + (), + ), + ], +) +def test_attached_target_directory_preserves_value_provenance( + command: str, + targets: tuple[str, ...], + entry_targets: tuple[str, ...], + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("TARGET_DIRECTORY", "/resolved/target") + monkeypatch.delenv("UNKNOWN_DIRECTORY", raising=False) + + result = scan_write_targets(command, _WORKSPACE) + + assert result.targets == targets + assert result.entry_targets == entry_targets + assert result.unresolved is False + assert result.has_write is True + + +def test_install_derived_child_preserves_spelling_and_requires_source_basename( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + destination = tmp_path / "dest" + destination.mkdir() + child = destination / "source" + child.symlink_to(tmp_path / "outside") + monkeypatch.delenv("INSTALL_SOURCE", raising=False) + + literal = scan_write_targets(f"install -t {destination} path/to/source", str(tmp_path)) + unresolved = scan_write_targets(f'install -t {destination} "$INSTALL_SOURCE"', str(tmp_path)) + + assert literal.targets == (str(child),) + assert unresolved.targets == () + assert unresolved.unresolved is True + assert unresolved.has_write is True + + +@pytest.mark.parametrize( + ("command", "targets", "entry_targets"), + [ + ( + "cd /tmp && npm install --prefix /tmp/jqinst node-jq 2>&1 | tail -10; " + "ls /tmp/jqinst/node_modules/node-jq/bin 2>/dev/null", + ("/tmp/jqinst",), + (), + ), + ( + "ln -sf /tmp/jqinst/node_modules/node-jq/bin/jq /usr/local/bin/jq 2>&1; " + "jq --version 2>&1", + (), + ("/usr/local/bin/jq",), + ), + ("echo x > /tmp/same; ln source /tmp/same", ("/tmp/same",), ("/tmp/same",)), + ("echo x > /dev/null; ln -f source /dev/null", (), ("/dev/null",)), + ], + ids=("npm-incident", "ln-incident", "same-spelling-dual-role", "entry-pseudo-device"), +) +def test_content_and_entry_aggregation( + command: str, targets: tuple[str, ...], entry_targets: tuple[str, ...] +) -> None: + result = scan_write_targets(command, _WORKSPACE) + + assert result.targets == targets + assert result.entry_targets == entry_targets + assert result.unresolved is False + assert result.has_write is True diff --git a/tests/infra/test_git_ops_guard.py b/tests/infra/test_git_ops_guard.py index b90bc99f6e..1ebb691da9 100644 --- a/tests/infra/test_git_ops_guard.py +++ b/tests/infra/test_git_ops_guard.py @@ -933,6 +933,93 @@ def test_denies_static_raw_ref_writes( after = ref_path.read_bytes() if ref_path.exists() else None assert after == before + @pytest.mark.parametrize( + ("source_name", "destination_relative"), + [("HEAD", "."), ("develop", "refs/heads")], + ids=["head", "checked-out-branch"], + ) + def test_denies_ln_directory_entry_for_checked_out_ref( + self, + linked_repo: dict[str, Path | str], + tmp_path: Path, + source_name: str, + destination_relative: str, + ) -> None: + linked = linked_repo["linked"] + assert isinstance(linked, Path) + source = tmp_path / "sources" / source_name + source.parent.mkdir() + source.write_text("replacement", encoding="utf-8") + destination = Path(str(linked_repo["common_git_dir"])) / destination_relative + + out = _run_guard( + f"ln -sf {shlex.quote(str(source))} {shlex.quote(str(destination))}", + kitchen_open=True, + tmpdir=linked, + ) + + assert _is_denied(out) + + def test_denies_npm_prefix_targeting_checked_out_ref( + self, linked_repo: dict[str, Path | str] + ) -> None: + linked = linked_repo["linked"] + assert isinstance(linked, Path) + target = Path(str(linked_repo["common_git_dir"])) / "refs/heads/develop" + + out = _run_guard( + f"npm install --prefix {shlex.quote(str(target))} package", + kitchen_open=True, + tmpdir=linked, + ) + + assert _is_denied(out) + + @pytest.mark.parametrize("target_first", [True, False], ids=["target-first", "target-last"]) + def test_denies_install_target_directory_checked_out_ref_child( + self, + linked_repo: dict[str, Path | str], + tmp_path: Path, + target_first: bool, + ) -> None: + linked = linked_repo["linked"] + assert isinstance(linked, Path) + destination = Path(str(linked_repo["common_git_dir"])) / "refs/heads" + source = tmp_path / "sources/develop" + source.parent.mkdir() + source.write_text("replacement", encoding="utf-8") + operands = ( + f"-t {shlex.quote(str(destination))} {shlex.quote(str(source))}" + if target_first + else f"{shlex.quote(str(source))} -t {shlex.quote(str(destination))}" + ) + + out = _run_guard(f"install {operands}", kitchen_open=True, tmpdir=linked) + + assert _is_denied(out) + + @pytest.mark.parametrize("target_first", [True, False], ids=["target-first", "target-last"]) + def test_allows_install_from_protected_source_to_unprotected_directory( + self, + linked_repo: dict[str, Path | str], + tmp_path: Path, + target_first: bool, + ) -> None: + linked = linked_repo["linked"] + assert isinstance(linked, Path) + source = Path(str(linked_repo["common_git_dir"])) / "refs/heads/develop" + destination = tmp_path / "allowed" + destination.mkdir() + operands = ( + f"-t {shlex.quote(str(destination))} {shlex.quote(str(source))}" + if target_first + else f"{shlex.quote(str(source))} -t {shlex.quote(str(destination))}" + ) + + out = _run_guard(f"install {operands}", kitchen_open=True, tmpdir=linked) + + assert out.strip() == "" + class TestCheckedOutRefAmbiguity: @pytest.mark.parametrize( @@ -1036,6 +1123,56 @@ def test_valid_mutation_without_execution_cwd_fails_closed( ) assert _is_denied(out) + @pytest.mark.parametrize( + "command", + [ + 'npm install --prefix "$DESTINATION" package', + 'ln -sf /tmp/source "$DESTINATION"', + ], + ids=["npm-prefix", "ln-entry"], + ) + def test_unresolved_explicit_write_destination_fails_closed( + self, + linked_repo: dict[str, Path | str], + monkeypatch: pytest.MonkeyPatch, + command: str, + ) -> None: + monkeypatch.delenv("DESTINATION", raising=False) + linked = linked_repo["linked"] + assert isinstance(linked, Path) + + out = _run_guard(command, kitchen_open=True, tmpdir=linked) + + assert _is_denied(out) + assert _checked_out_ref_result(out)["attempted_value"] == "" + + @pytest.mark.parametrize( + "command_builder", + [ + lambda root: f"npm install --prefix {shlex.quote(str(root / 'npm-root'))} package", + lambda root: f"ln -sf /tmp/source {shlex.quote(str(root / 'link'))}", + lambda root: f"install -t {shlex.quote(str(root / 'install-root'))} /tmp/source", + ], + ids=["npm-prefix", "ln-entry", "install-target-directory"], + ) + def test_structural_write_without_execution_cwd_fails_closed( + self, + linked_repo: dict[str, Path | str], + command_builder, + ) -> None: + linked = linked_repo["linked"] + assert isinstance(linked, Path) + + out = _run_guard( + command_builder(linked), + kitchen_open=True, + tmpdir=linked, + include_execution_cwd=False, + ) + + assert _is_denied(out) + assert _checked_out_ref_result(out)["attempted_value"] == "" + class TestCheckedOutRefWriteTargets: @pytest.mark.parametrize( diff --git a/tests/server/test_guards_module.py b/tests/server/test_guards_module.py index e08e5d0a82..f98679506d 100644 --- a/tests/server/test_guards_module.py +++ b/tests/server/test_guards_module.py @@ -2,7 +2,7 @@ import pytest -from autoskillit.hooks import UNRESOLVED_WRITE_TARGET_REMEDIATION +from autoskillit.hooks import UNRESOLVED_WRITE_TARGET_REMEDIATION, WriteTargetScan pytestmark = [pytest.mark.layer("server"), pytest.mark.small] @@ -79,6 +79,144 @@ def test_check_write_target_boundary_cases( assert result is None +@pytest.mark.parametrize( + ("command_template", "destination", "expected_message"), + [ + pytest.param( + "npm install --prefix {destination} node-jq", + "allowed", + None, + id="npm-prefix-equals-allowed-root", + ), + pytest.param( + "npm --prefix={destination} install node-jq", + "outside", + "outside allowed write prefixes", + id="npm-outside-prefix", + ), + pytest.param( + 'npm install --prefix "$NPM_PREFIX" node-jq', + "unresolved", + UNRESOLVED_WRITE_TARGET_REMEDIATION, + id="npm-unresolved-prefix", + ), + pytest.param( + "ln -sfT /opt/tools/jq {destination}", + "allowed", + None, + id="ln-entry-equals-allowed-root", + ), + pytest.param( + "ln -sf /opt/tools/jq {destination}/jq", + "outside", + "outside allowed write prefixes", + id="ln-outside-entry", + ), + pytest.param( + 'ln -sf /opt/tools/jq "$LINK_NAME"', + "unresolved", + UNRESOLVED_WRITE_TARGET_REMEDIATION, + id="ln-unresolved-entry", + ), + ], +) +def test_run_cmd_boundary_covers_npm_and_ln_destinations( + tmp_path, monkeypatch, command_template, destination, expected_message +) -> None: + from autoskillit.server.lifecycle._guards import _check_write_target_boundary + + monkeypatch.delenv("NPM_PREFIX", raising=False) + monkeypatch.delenv("LINK_NAME", raising=False) + allowed = tmp_path / "allowed" + outside = tmp_path / "outside" + allowed.mkdir() + outside.mkdir() + selected = allowed if destination == "allowed" else outside + command = command_template.format(destination=selected) + + result = _check_write_target_boundary(command, str(tmp_path), (str(allowed),)) + + if expected_message is None: + assert result is None + else: + assert result is not None + assert expected_message in result + + +def test_run_cmd_boundary_does_not_early_allow_location_only_scan(tmp_path, monkeypatch) -> None: + from autoskillit.server.lifecycle import _guards + + allowed = tmp_path / "allowed" + outside = tmp_path / "outside" + allowed.mkdir() + outside.mkdir() + monkeypatch.setattr( + _guards, + "scan_write_targets", + lambda _cmd, _cwd: WriteTargetScan( + targets=(), + unresolved=False, + parseable=True, + has_write=True, + entry_targets=(str(outside / "link"),), + ), + ) + + result = _guards._check_write_target_boundary("ln", str(tmp_path), (str(allowed),)) + + assert result is not None + assert str(outside / "link") in result + + +def test_run_cmd_entry_check_uses_link_location_not_referent(tmp_path) -> None: + from autoskillit.server.lifecycle._guards import _check_write_target_boundary + + allowed = tmp_path / "allowed" + outside = tmp_path / "outside" + allowed.mkdir() + outside.mkdir() + inside = allowed / "inside" + inside.write_text("inside", encoding="utf-8") + outside_link = outside / "link" + outside_link.symlink_to(inside) + + result = _check_write_target_boundary( + f"ln -sfT /opt/tools/jq {outside_link}", str(tmp_path), (str(allowed),) + ) + + assert result is not None + assert str(outside_link) in result + + +def test_run_cmd_empty_prefixes_still_disable_new_destination_checks(tmp_path) -> None: + from autoskillit.server.lifecycle._guards import _check_write_target_boundary + + assert ( + _check_write_target_boundary('ln -sf /opt/tools/jq "$LINK_NAME"', str(tmp_path), ()) + is None + ) + + +def test_run_cmd_content_target_still_follows_final_symlink(tmp_path) -> None: + from autoskillit.server.lifecycle._guards import _check_write_target_boundary + + allowed = tmp_path / "allowed" + outside = tmp_path / "outside" + allowed.mkdir() + outside.mkdir() + outside_file = outside / "file" + outside_file.write_text("outside", encoding="utf-8") + content_link = allowed / "content-link" + content_link.symlink_to(outside_file) + + result = _check_write_target_boundary( + f"echo changed > {content_link}", str(tmp_path), (str(allowed),) + ) + + assert result is not None + assert str(content_link) in result + + def test_check_recipe_read_prohibition_importable(): from autoskillit.server.lifecycle._guards import _check_recipe_read_prohibition From 11ef3a3eb9125ce23d9082421d8be30ce159831f Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 11:43:21 -0700 Subject: [PATCH 02/42] test: separate inert stdin from unresolved output writes --- tests/infra/test_git_ops_guard.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/infra/test_git_ops_guard.py b/tests/infra/test_git_ops_guard.py index 1ebb691da9..d5a82cf766 100644 --- a/tests/infra/test_git_ops_guard.py +++ b/tests/infra/test_git_ops_guard.py @@ -562,7 +562,7 @@ def test_allows_inert_herestring_git_push(self, tmp_path, include_execution_cwd: _git(tmp_path, "add", "f.txt") _git(tmp_path, "commit", "-m", "initial") out = _run_guard( - "cat > f.md <<< 'git push --force origin main'", + "cat <<< 'git push --force origin main'", kitchen_open=True, tmpdir=tmp_path, include_execution_cwd=include_execution_cwd, @@ -1152,8 +1152,9 @@ def test_unresolved_explicit_write_destination_fails_closed( lambda root: f"npm install --prefix {shlex.quote(str(root / 'npm-root'))} package", lambda root: f"ln -sf /tmp/source {shlex.quote(str(root / 'link'))}", lambda root: f"install -t {shlex.quote(str(root / 'install-root'))} /tmp/source", + lambda _root: "cat > f.md <<< 'git push --force origin main'", ], - ids=["npm-prefix", "ln-entry", "install-target-directory"], + ids=["npm-prefix", "ln-entry", "install-target-directory", "relative-redirect"], ) def test_structural_write_without_execution_cwd_fails_closed( self, From ff0116778c9c0b188aa4fac54675ed712e342a0d Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 13:32:45 -0700 Subject: [PATCH 03/42] test: cover incident commands and sibling destination paths --- tests/hooks/test_write_guard.py | 5 +++-- tests/hooks/test_write_target_scan.py | 2 ++ tests/server/test_guards_module.py | 25 +++++++++++++++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/tests/hooks/test_write_guard.py b/tests/hooks/test_write_guard.py index 3d1321dc54..ae4bd4283a 100644 --- a/tests/hooks/test_write_guard.py +++ b/tests/hooks/test_write_guard.py @@ -692,8 +692,9 @@ def test_npm_and_ln_destinations_reach_bash_scope_policy( @pytest.mark.parametrize( "command", [ - "cd /tmp && npm install --prefix /tmp/jqinst node-jq", - "ln -sf /tmp/jqinst/node_modules/node-jq/bin/jq /usr/local/bin/jq", + "cd /tmp && npm install --prefix /tmp/jqinst node-jq 2>&1 | tail -10; " + "ls /tmp/jqinst/node_modules/node-jq/bin 2>/dev/null", + "ln -sf /tmp/jqinst/node_modules/node-jq/bin/jq /usr/local/bin/jq 2>&1; jq --version 2>&1", ], ids=["observed-npm-install", "observed-ln-install"], ) diff --git a/tests/hooks/test_write_target_scan.py b/tests/hooks/test_write_target_scan.py index 4e26f66a44..b1f59d2c33 100644 --- a/tests/hooks/test_write_target_scan.py +++ b/tests/hooks/test_write_target_scan.py @@ -240,9 +240,11 @@ def test_ln_directory_and_final_symlink_semantics( [ "ln --unknown value source link", "ln -t /links -T source", + "ln --target-directory /links --no-target-directory source", "ln --target-directory /links", "ln source --target-directory", "install -t /dest -T source", + "install --target-directory /dest --no-target-directory source", "install source --target-directory", "install --target-directory /dest", ], diff --git a/tests/server/test_guards_module.py b/tests/server/test_guards_module.py index f98679506d..115cf8ea09 100644 --- a/tests/server/test_guards_module.py +++ b/tests/server/test_guards_module.py @@ -143,6 +143,31 @@ def test_run_cmd_boundary_covers_npm_and_ln_destinations( assert expected_message in result +@pytest.mark.parametrize( + "command_template", + ["echo changed > {destination}", "ln -sfT /opt/tools/jq {destination}"], + ids=["content-target", "entry-target"], +) +def test_run_cmd_boundary_denies_sibling_path_sharing_root_prefix( + tmp_path, command_template: str +) -> None: + from autoskillit.server.lifecycle._guards import _check_write_target_boundary + + allowed = tmp_path / "allowed" + sibling = tmp_path / "allowed_extra" + allowed.mkdir() + sibling.mkdir() + destination = sibling / "target" + + result = _check_write_target_boundary( + command_template.format(destination=destination), str(tmp_path), (str(allowed),) + ) + + assert result is not None + assert "outside allowed write prefixes" in result + assert str(destination) in result + + def test_run_cmd_boundary_does_not_early_allow_location_only_scan(tmp_path, monkeypatch) -> None: from autoskillit.server.lifecycle import _guards From 4a9a57b4a8e5ceaf93dbc7d968beb6959b3eff31 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:13:51 -0700 Subject: [PATCH 04/42] fix(review): retain explicit npm prefixes across subcommand parsing --- src/autoskillit/hooks/_runtime/_write_target_scan.py | 9 +++++---- tests/hooks/test_write_target_scan.py | 10 ++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/autoskillit/hooks/_runtime/_write_target_scan.py b/src/autoskillit/hooks/_runtime/_write_target_scan.py index a5c44f69b9..685610b64d 100644 --- a/src/autoskillit/hooks/_runtime/_write_target_scan.py +++ b/src/autoskillit/hooks/_runtime/_write_target_scan.py @@ -285,6 +285,7 @@ def _npm_install_targets( prefix: tuple[str, str | None] | None = None missing_prefix = False command_index: int | None = None + uncertain_command = False index = 1 while index < separator: token = argv[index] @@ -300,14 +301,14 @@ def _npm_install_targets( prefix = (value, source) index = next_index continue - if command_index is None and token == "install": + if command_index is None and token in {"install", "i", "add", "ci"}: command_index = index elif command_index is None and not token.startswith("-"): - return [], False, False + uncertain_command = True index += 1 - if command_index is None or (prefix is None and not missing_prefix): + if prefix is None and not missing_prefix: return [], False, False - if missing_prefix or prefix is None: + if command_index is None or uncertain_command or missing_prefix or prefix is None: return [], True, True target = _classification.resolve_write_target(prefix[0], cwd, shell_source=prefix[1]) return ([target], False, True) if target is not None else ([], True, True) diff --git a/tests/hooks/test_write_target_scan.py b/tests/hooks/test_write_target_scan.py index b1f59d2c33..1c5837ab05 100644 --- a/tests/hooks/test_write_target_scan.py +++ b/tests/hooks/test_write_target_scan.py @@ -156,6 +156,11 @@ def test_scan_write_target_expectations( ('npm install --prefix="$NPM_UNKNOWN" pkg', (), True, True), ("npm install --prefix", (), True, True), ("npm install -- --prefix /opt/app", (), False, False), + ("npm ci --prefix /opt/app", ("/opt/app",), False, True), + ("npm --prefix /opt/app i pkg", ("/opt/app",), False, True), + ("npm add pkg --prefix=/opt/app", ("/opt/app",), False, True), + ("npm --registry https://example install --prefix /opt/app pkg", (), True, True), + ("npm --prefix /opt/app unsupported", (), True, True), ], ids=( "detached-after-install", @@ -167,6 +172,11 @@ def test_scan_write_target_expectations( "attached-unknown-variable", "missing-prefix-value", "option-terminator", + "clean-install-prefix", + "install-alias-prefix", + "add-alias-prefix", + "uncertain-global-option-value", + "unsupported-prefixed-command", ), ) def test_npm_install_explicit_prefix( From 4e2f5b22091f15407c6e100dc577fdde15ffbeda Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:16:01 -0700 Subject: [PATCH 05/42] fix(review): detect path-qualified destination commands --- .../hooks/_runtime/_write_target_scan.py | 7 ++++--- tests/hooks/test_write_target_scan.py | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/autoskillit/hooks/_runtime/_write_target_scan.py b/src/autoskillit/hooks/_runtime/_write_target_scan.py index 685610b64d..18e1793cc5 100644 --- a/src/autoskillit/hooks/_runtime/_write_target_scan.py +++ b/src/autoskillit/hooks/_runtime/_write_target_scan.py @@ -561,13 +561,14 @@ def _scan_executable( verb_cwd = _classification._wrapped_verb_cwd(executable, start, state.cwd, argv_tokens) invoked = _invoked_child_state(verb, verb_cwd, state, path) verb_tokens = None if argv_tokens is None else argv_tokens[start:] - if verb == "npm": + verb_name = os.path.basename(verb) + if verb_name == "npm": targets, unresolved, has_write = _npm_install_targets(argv, verb_cwd, verb_tokens) return targets, [], unresolved, has_write, invoked - if verb == "ln": + if verb_name == "ln": targets, unresolved = _ln_entry_targets(argv, verb_cwd, verb_tokens) return [], targets, unresolved, True, invoked - if verb == "install": + if verb_name == "install": targets, unresolved = _install_targets(argv, verb_cwd, verb_tokens) return targets, [], unresolved, True, invoked if verb in WRITE_VERBS: diff --git a/tests/hooks/test_write_target_scan.py b/tests/hooks/test_write_target_scan.py index 1c5837ab05..0cfb21570f 100644 --- a/tests/hooks/test_write_target_scan.py +++ b/tests/hooks/test_write_target_scan.py @@ -197,6 +197,23 @@ def test_npm_install_explicit_prefix( assert result.has_write is has_write +@pytest.mark.parametrize( + ("command", "targets", "entry_targets"), + [ + ("/usr/bin/npm install --prefix /opt/app pkg", ("/opt/app",), ()), + ("/usr/bin/install source /opt/app", ("/opt/app",), ()), + ("/bin/ln -s source /opt/link", (), ("/opt/link",)), + ], +) +def test_path_qualified_destination_verbs( + command: str, targets: tuple[str, ...], entry_targets: tuple[str, ...] +) -> None: + result = scan_write_targets(command, _WORKSPACE) + assert result.targets == targets + assert result.entry_targets == entry_targets + assert result.has_write and not result.unresolved + + @pytest.mark.parametrize( ("command", "entry_targets"), [ From 61cb2b80e95a2e4e7c35a8050c4355d66da01a1b Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:17:55 -0700 Subject: [PATCH 06/42] fix(review): recognize supported GNU link options --- .../hooks/_runtime/_write_target_scan.py | 16 +++++++++++++--- tests/hooks/test_write_target_scan.py | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/autoskillit/hooks/_runtime/_write_target_scan.py b/src/autoskillit/hooks/_runtime/_write_target_scan.py index 18e1793cc5..0cf01f54ef 100644 --- a/src/autoskillit/hooks/_runtime/_write_target_scan.py +++ b/src/autoskillit/hooks/_runtime/_write_target_scan.py @@ -71,13 +71,19 @@ def _destination_operands( "--suffix": value, } boolean_long = { + "--backup", + "--directory", + "--interactive", + "--logical", + "--physical", + "--relative", "--symbolic", "--force", "--no-dereference", "--no-target-directory", "--verbose", } - boolean_short = frozenset("sfnTv") + boolean_short = frozenset("sfnTvbdiFLPr") else: value_spec = { "-t": value, @@ -127,8 +133,12 @@ def _destination_operands( target_directory = (option_value, source) index = next_index continue - if token in boolean_long or ( - not token.startswith("--") and all(char in boolean_short for char in token[1:]) + if ( + token in boolean_long + or (verb == "ln" and token.startswith("--backup=")) + or ( + not token.startswith("--") and all(char in boolean_short for char in token[1:]) + ) ): no_target_directory |= token in {"-T", "--no-target-directory"} or ( not token.startswith("--") and "T" in token[1:] diff --git a/tests/hooks/test_write_target_scan.py b/tests/hooks/test_write_target_scan.py index 0cfb21570f..56420988a1 100644 --- a/tests/hooks/test_write_target_scan.py +++ b/tests/hooks/test_write_target_scan.py @@ -238,6 +238,25 @@ def test_ln_literal_entry_destinations(command: str, entry_targets: tuple[str, . assert result.has_write is True +@pytest.mark.parametrize( + "option", + [ + "-b", + "-di", + "--backup", + "--backup=numbered", + "--interactive", + "--logical", + "--physical", + "--relative", + ], +) +def test_ln_options_preserve_entry_destination(option: str) -> None: + result = scan_write_targets(f"ln {option} source link", _WORKSPACE) + assert result.entry_targets == ("/workspace/link",) + assert not result.unresolved + + def test_ln_directory_and_final_symlink_semantics( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: From 486a1ee7b0d3d171cbd299dac9dc09d20ad2e9d8 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:19:30 -0700 Subject: [PATCH 07/42] refactor(review): name parsed destination option fields --- .../hooks/_runtime/_write_target_scan.py | 57 +++++++++++-------- 1 file changed, 34 insertions(+), 23 deletions(-) diff --git a/src/autoskillit/hooks/_runtime/_write_target_scan.py b/src/autoskillit/hooks/_runtime/_write_target_scan.py index 0cf01f54ef..8b48c82ed8 100644 --- a/src/autoskillit/hooks/_runtime/_write_target_scan.py +++ b/src/autoskillit/hooks/_runtime/_write_target_scan.py @@ -55,11 +55,21 @@ def _classification_module() -> ModuleType: return standalone_classification +@dataclass(frozen=True, slots=True) +class _DestinationOperands: + operands: list[int] + target_directory: tuple[str, str | None] | None + no_target_directory: bool + no_dereference: bool + create_directories: bool + invalid: bool + + def _destination_operands( verb: str, argv: list[str], argv_tokens: Sequence[ArgvToken] | None, -) -> tuple[list[int], tuple[str, str | None] | None, bool, bool, bool, bool]: +) -> _DestinationOperands: """Parse the supported ln/install options and positional operands.""" _classification = _classification_module() value = _classification._FlagArity.VALUE @@ -146,8 +156,9 @@ def _destination_operands( no_dereference |= token in {"-n", "--no-dereference"} or ( not token.startswith("--") and "n" in token[1:] ) - directory_mode |= token in {"-d", "--directory"} or ( - verb == "install" and not token.startswith("--") and "d" in token[1:] + directory_mode |= verb == "install" and ( + token in {"-d", "--directory"} + or (not token.startswith("--") and "d" in token[1:]) ) index += 1 continue @@ -157,13 +168,13 @@ def _destination_operands( operands.append(index) index += 1 invalid |= target_directory is not None and no_target_directory - return ( - operands, - target_directory, - no_target_directory, - no_dereference, - directory_mode, - invalid, + return _DestinationOperands( + operands=operands, + target_directory=target_directory, + no_target_directory=no_target_directory, + no_dereference=no_dereference, + create_directories=directory_mode, + invalid=invalid, ) @@ -217,12 +228,12 @@ def _install_targets( argv_tokens: Sequence[ArgvToken] | None, ) -> tuple[list[str], bool]: _classification = _classification_module() - operands, target_directory, no_target, _no_deref, directory_mode, invalid = ( - _destination_operands("install", argv, argv_tokens) - ) - if invalid or not operands: + options = _destination_operands("install", argv, argv_tokens) + operands = options.operands + target_directory = options.target_directory + if options.invalid or not operands: return [], True - if directory_mode: + if options.create_directories: if target_directory is not None: return [], True targets = [_resolved_operand(argv, index, cwd, argv_tokens) for index in operands] @@ -242,7 +253,7 @@ def _install_targets( if destination is None: return [], True sources = operands[:-1] - if no_target: + if options.no_target_directory: return ([destination], False) if len(sources) == 1 else ([], True) if len(sources) > 1 or os.path.isdir(destination): return _directory_children(destination, sources, argv, cwd, argv_tokens) @@ -255,10 +266,10 @@ def _ln_entry_targets( argv_tokens: Sequence[ArgvToken] | None, ) -> tuple[list[str], bool]: _classification = _classification_module() - operands, target_directory, no_target, no_deref, _directory_mode, invalid = ( - _destination_operands("ln", argv, argv_tokens) - ) - if invalid or not operands: + options = _destination_operands("ln", argv, argv_tokens) + operands = options.operands + target_directory = options.target_directory + if options.invalid or not operands: return [], True if target_directory is not None: value, source = target_directory @@ -274,10 +285,10 @@ def _ln_entry_targets( if destination is None: return [], True sources = operands[:-1] - if no_target and len(sources) > 1: + if options.no_target_directory and len(sources) > 1: return [], True - follows_directory = not no_target and os.path.isdir(destination) - if no_deref and os.path.islink(destination): + follows_directory = not options.no_target_directory and os.path.isdir(destination) + if options.no_dereference and os.path.islink(destination): follows_directory = False if follows_directory or len(sources) > 1: return _directory_children(destination, sources, argv, cwd, argv_tokens) From e75abf44a6c2fb7b36639ede689b89d5908915a7 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:20:54 -0700 Subject: [PATCH 08/42] refactor(review): reuse named write scans in executable dispatch --- .../hooks/_runtime/_write_target_scan.py | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/autoskillit/hooks/_runtime/_write_target_scan.py b/src/autoskillit/hooks/_runtime/_write_target_scan.py index 8b48c82ed8..a48eec9cde 100644 --- a/src/autoskillit/hooks/_runtime/_write_target_scan.py +++ b/src/autoskillit/hooks/_runtime/_write_target_scan.py @@ -562,7 +562,7 @@ def _scan_executable( argv_tokens: Sequence[ArgvToken] | None, state: _ShellDirectoryState, path: tuple[int, ...] | None, -) -> tuple[list[str], list[str], bool, bool, _ShellDirectoryState | None]: +) -> tuple[WriteTargetScan, _ShellDirectoryState | None]: _classification = _classification_module() start = _classification._verb_start_index(executable) @@ -571,12 +571,12 @@ def _scan_executable( if setting is not None: state.cdpath_unknown = setting[0] if start is None: - return [], [], False, False, None + return WriteTargetScan((), False, True, False), None handled = _apply_shell_builtin(executable, start, argv_tokens, state) if setting is not None and setting[1]: state.cdpath_unknown = previous_cdpath if handled or _classification.is_gh_command(executable): - return [], [], False, False, None + return WriteTargetScan((), False, True, False), None argv = executable[start:] verb = argv[0] verb_cwd = _classification._wrapped_verb_cwd(executable, start, state.cwd, argv_tokens) @@ -585,24 +585,24 @@ def _scan_executable( verb_name = os.path.basename(verb) if verb_name == "npm": targets, unresolved, has_write = _npm_install_targets(argv, verb_cwd, verb_tokens) - return targets, [], unresolved, has_write, invoked + return WriteTargetScan(tuple(targets), unresolved, True, has_write), invoked if verb_name == "ln": targets, unresolved = _ln_entry_targets(argv, verb_cwd, verb_tokens) - return [], targets, unresolved, True, invoked + return WriteTargetScan((), unresolved, True, True, entry_targets=tuple(targets)), invoked if verb_name == "install": targets, unresolved = _install_targets(argv, verb_cwd, verb_tokens) - return targets, [], unresolved, True, invoked + return WriteTargetScan(tuple(targets), unresolved, True, True), invoked if verb in WRITE_VERBS: targets, unresolved = _classification.extract_write_verb_targets( verb, argv, verb_cwd, argv_tokens=verb_tokens ) - return targets, [], unresolved, True, invoked + return WriteTargetScan(tuple(targets), unresolved, True, True), invoked if verb == "git" or verb.endswith("/git"): targets, unresolved, has_write = _classification._git_write_targets( argv, verb_cwd, executable[:start], verb_tokens ) - return targets, [], unresolved, has_write, invoked - return [], [], False, False, invoked + return WriteTargetScan(tuple(targets), unresolved, True, has_write), invoked + return WriteTargetScan((), False, True, False), invoked def scan_write_targets(command: str, cwd: str) -> WriteTargetScan: @@ -644,14 +644,14 @@ def scan_write_targets(command: str, cwd: str) -> WriteTargetScan: if record.argv_tokens is None else [record.argv_tokens[index] for index in partition.segments] ) - verb_targets, verb_entries, verb_unresolved, verb_has_write, invoked = _scan_executable( + verb_scan, invoked = _scan_executable( executable, executable_tokens, state, record.subshell_path ) - targets.extend(verb_targets) - entry_targets.extend(verb_entries) + targets.extend(verb_scan.targets) + entry_targets.extend(verb_scan.entry_targets) targets.extend(partition.targets) - unresolved |= verb_unresolved - has_write |= verb_has_write + unresolved |= verb_scan.unresolved + has_write |= verb_scan.has_write if record.subshell_path is not None: pending_children[record.subshell_path] = (pre_command_state, invoked) return WriteTargetScan( From e45cc464c757af8ac7abafada393bece5b40c428 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:22:30 -0700 Subject: [PATCH 09/42] fix(review): normalize terminal parent destinations in both runtimes --- src/autoskillit/core/io/paths.py | 2 +- src/autoskillit/hooks/_runtime/_path_identity.py | 2 +- tests/hooks/test_path_identity.py | 15 +++++++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/autoskillit/core/io/paths.py b/src/autoskillit/core/io/paths.py index 8d1cbe8fb8..1a2abd7445 100644 --- a/src/autoskillit/core/io/paths.py +++ b/src/autoskillit/core/io/paths.py @@ -93,7 +93,7 @@ def destination_location(destination: Path) -> Path: existing artifacts rather than future write targets. """ destination = Path(destination) - if not destination.name: + if not destination.name or destination.name == "..": return destination.resolve() return destination.parent.resolve() / destination.name diff --git a/src/autoskillit/hooks/_runtime/_path_identity.py b/src/autoskillit/hooks/_runtime/_path_identity.py index a34da53b9f..8d57fcd5d5 100644 --- a/src/autoskillit/hooks/_runtime/_path_identity.py +++ b/src/autoskillit/hooks/_runtime/_path_identity.py @@ -40,7 +40,7 @@ def hooks_relative_key(script_identity: str | os.PathLike[str], hooks_dir: Path) def destination_location(destination: str | os.PathLike[str]) -> Path: """Resolve a destination's parent without following its final component.""" path = Path(destination) - if not path.name: + if not path.name or path.name == "..": return path.resolve() return path.parent.resolve() / path.name diff --git a/tests/hooks/test_path_identity.py b/tests/hooks/test_path_identity.py index 435e3c3523..a8039b5b71 100644 --- a/tests/hooks/test_path_identity.py +++ b/tests/hooks/test_path_identity.py @@ -6,6 +6,7 @@ import pytest +from autoskillit.core import destination_location as core_destination_location from autoskillit.hooks._runtime._path_identity import ( PathIdentityError, destination_location, @@ -94,3 +95,17 @@ def test_destination_location_preserves_dangling_final_symlink(tmp_path: Path) - def test_destination_location_handles_root_destination() -> None: assert destination_location(Path("/")) == Path("/") + + +@pytest.mark.parametrize("name", ["entry", "final-link", "..", "."]) +def test_destination_location_core_and_hook_conformance(tmp_path: Path, name: str) -> None: + real_parent = tmp_path / "real" + real_parent.mkdir() + linked_parent = tmp_path / "linked" + linked_parent.symlink_to(real_parent, target_is_directory=True) + (real_parent / "final-link").symlink_to(tmp_path / "missing") + destination = linked_parent / name + expected = tmp_path if name == ".." else real_parent / name + + for resolve_location in (destination_location, core_destination_location): + assert resolve_location(destination) == expected From 05a576997c680e36ddc15166783f5905e5a52c93 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:24:11 -0700 Subject: [PATCH 10/42] refactor(review): share physical entry containment across guards --- src/autoskillit/hooks/__init__.py | 2 ++ src/autoskillit/hooks/_runtime/_path_identity.py | 5 +++++ .../hooks/guards/installation_integrity_guard.py | 8 +++----- src/autoskillit/hooks/guards/write_guard.py | 9 +++------ src/autoskillit/server/lifecycle/_guards.py | 6 +++--- tests/hooks/test_path_identity.py | 16 +++++++++++++++- 6 files changed, 31 insertions(+), 15 deletions(-) diff --git a/src/autoskillit/hooks/__init__.py b/src/autoskillit/hooks/__init__.py index c77af911f7..44fef79b90 100644 --- a/src/autoskillit/hooks/__init__.py +++ b/src/autoskillit/hooks/__init__.py @@ -78,6 +78,7 @@ enforce_session_scope, hook_session_shape, ) +from autoskillit.hooks._runtime._path_identity import destination_within from autoskillit.hooks._session_binding import LoadedSkillEntry from autoskillit.hooks.formatters._fmt_primitives import _HOOK_CONFIG_PATH_COMPONENTS from autoskillit.hooks.guards.branch_protection_guard import BRANCH_PROTECTION_DENY_TRIGGER @@ -95,6 +96,7 @@ del _HOOK_REGISTRY_LIST __all__ = [ + "destination_within", "BRANCH_PROTECTION_DENY_TRIGGER", "CODEX_AUTO_COMPACTION_DENIED_REASON", "DENY_REASON_BY_GUARD", diff --git a/src/autoskillit/hooks/_runtime/_path_identity.py b/src/autoskillit/hooks/_runtime/_path_identity.py index 8d57fcd5d5..8ec8e70a7f 100644 --- a/src/autoskillit/hooks/_runtime/_path_identity.py +++ b/src/autoskillit/hooks/_runtime/_path_identity.py @@ -45,6 +45,11 @@ def destination_location(destination: str | os.PathLike[str]) -> Path: return path.parent.resolve() / path.name +def destination_within(candidate: str | os.PathLike[str], root: str | os.PathLike[str]) -> bool: + """Compare an entry's physical location with a resolved directory boundary.""" + return destination_location(candidate).is_relative_to(Path(root).resolve()) + + def realpath_within(candidate: str | os.PathLike[str], root: str | os.PathLike[str]) -> bool: """Return whether *candidate* lies at or under *root* after resolving both.""" try: diff --git a/src/autoskillit/hooks/guards/installation_integrity_guard.py b/src/autoskillit/hooks/guards/installation_integrity_guard.py index e88651a443..7914bbe483 100644 --- a/src/autoskillit/hooks/guards/installation_integrity_guard.py +++ b/src/autoskillit/hooks/guards/installation_integrity_guard.py @@ -33,7 +33,7 @@ normalize_payload_cwd, parse_hook_command, ) -from _path_identity import destination_location, realpath_within # noqa: E402 +from _path_identity import destination_location, destination_within, realpath_within # noqa: E402 from _policy_event import ( # noqa: E402 PolicyEvent, render_provenance_prefix, @@ -149,12 +149,10 @@ def _is_protected_entry_target(path: str) -> bool: return True for root in _known_roots(): try: - root_locations = {destination_location(root), root.resolve()} + if location == destination_location(root) or destination_within(path, root): + return True except (OSError, RuntimeError, ValueError): return True - for root_location in root_locations: - if location == root_location or str(location).startswith(str(root_location) + os.sep): - return True try: entry = os.lstat(path) except OSError: diff --git a/src/autoskillit/hooks/guards/write_guard.py b/src/autoskillit/hooks/guards/write_guard.py index 1356c0e432..518a86919e 100644 --- a/src/autoskillit/hooks/guards/write_guard.py +++ b/src/autoskillit/hooks/guards/write_guard.py @@ -36,7 +36,7 @@ from _guard_decision_diagnostics import ( # noqa: E402 record_guard_decision, ) -from _path_identity import destination_location # noqa: E402 +from _path_identity import destination_within # noqa: E402 if TYPE_CHECKING: from .._runtime._hook_output import deny_tool_use @@ -332,16 +332,13 @@ def _entry_paths_validation_error( ) -> str | None: for path in paths: try: - location = str(destination_location(Path(path))) + allowed = any(destination_within(path, prefix) for prefix in norm_prefixes) except (OSError, RuntimeError, ValueError): return ( f"Write/Edit/apply_patch blocked: {WRITE_GUARD_DENY_TRIGGER}. " f"Only writes to {display_prefix} are permitted." ) - if not any( - location.startswith(prefix) or location == prefix.rstrip("/") - for prefix in norm_prefixes - ): + if not allowed: return ( f"Write/Edit/apply_patch blocked: {WRITE_GUARD_DENY_TRIGGER}. " f"Only writes to {display_prefix} are permitted." diff --git a/src/autoskillit/server/lifecycle/_guards.py b/src/autoskillit/server/lifecycle/_guards.py index fdb68bc012..7017ba3000 100644 --- a/src/autoskillit/server/lifecycle/_guards.py +++ b/src/autoskillit/server/lifecycle/_guards.py @@ -15,7 +15,6 @@ BackendPinResolution, FaultDomain, InputContractResolver, - destination_location, extract_path_arg, extract_positional_args, extract_skill_name, @@ -28,6 +27,7 @@ PROTECTED_SOURCE_PATH_PATTERNS, UNRESOLVED_WRITE_TARGET_REMEDIATION, command_has_blocked_protected_path_read, + destination_within, scan_write_targets, ) from autoskillit.pipeline import gate_error_result @@ -168,13 +168,13 @@ def _check_write_target_boundary( ) for target in scan.entry_targets: try: - location = str(destination_location(Path(target))) + allowed = any(destination_within(target, prefix) for prefix in allowed_prefixes) except (OSError, RuntimeError, ValueError): return gate_error_result( "run_cmd write target could not be resolved safely. " + UNRESOLVED_WRITE_TARGET_REMEDIATION ) - if not any(location.startswith(pfx) or location == pfx.rstrip("/") for pfx in normalized): + if not allowed: return gate_error_result( f"run_cmd write target {target!r} is outside allowed write prefixes: " f"{', '.join(allowed_prefixes)}" diff --git a/tests/hooks/test_path_identity.py b/tests/hooks/test_path_identity.py index a8039b5b71..33c30221b8 100644 --- a/tests/hooks/test_path_identity.py +++ b/tests/hooks/test_path_identity.py @@ -10,6 +10,7 @@ from autoskillit.hooks._runtime._path_identity import ( PathIdentityError, destination_location, + destination_within, hooks_relative_key, realpath_within, ) @@ -105,7 +106,20 @@ def test_destination_location_core_and_hook_conformance(tmp_path: Path, name: st linked_parent.symlink_to(real_parent, target_is_directory=True) (real_parent / "final-link").symlink_to(tmp_path / "missing") destination = linked_parent / name - expected = tmp_path if name == ".." else real_parent / name + expected = tmp_path if name == ".." else linked_parent if name == "." else real_parent / name for resolve_location in (destination_location, core_destination_location): assert resolve_location(destination) == expected + + +def test_destination_within_uses_physical_parent_and_preserves_final_link(tmp_path: Path) -> None: + allowed = tmp_path / "allowed" + allowed.mkdir() + outside = tmp_path / "outside" + outside.mkdir() + (allowed / "parent").symlink_to(outside, target_is_directory=True) + (allowed / "link").symlink_to(outside / "target") + assert destination_within(allowed / "link", allowed) + assert not destination_within(allowed / "parent" / "entry", allowed) + assert not destination_within(allowed / "..", allowed) + assert not destination_within(tmp_path / "allowed-neighbor" / "entry", allowed) From decfc5de89a17e4148cac1e176685ff2f98df61d Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:25:31 -0700 Subject: [PATCH 11/42] refactor(review): share write boundary denial text --- src/autoskillit/hooks/guards/write_guard.py | 22 ++++++++++----------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/src/autoskillit/hooks/guards/write_guard.py b/src/autoskillit/hooks/guards/write_guard.py index 518a86919e..b2ff4e2fe4 100644 --- a/src/autoskillit/hooks/guards/write_guard.py +++ b/src/autoskillit/hooks/guards/write_guard.py @@ -314,16 +314,20 @@ def _write_prefix_policy(data: dict[str, object], headless: bool) -> _WritePolic return _WritePolicy("active", tuple(norm_prefixes), ", ".join(raw_prefixes), "") +def _write_boundary_message(display_prefix: str) -> str: + return ( + f"Write/Edit/apply_patch blocked: {WRITE_GUARD_DENY_TRIGGER}. " + f"Only writes to {display_prefix} are permitted." + ) + + def _paths_validation_error( paths: list[str], norm_prefixes: list[str], display_prefix: str ) -> str | None: for path in paths: resolved = os.path.realpath(path) if not any(resolved.startswith(np) or resolved == np.rstrip("/") for np in norm_prefixes): - return ( - f"Write/Edit/apply_patch blocked: {WRITE_GUARD_DENY_TRIGGER}. " - f"Only writes to {display_prefix} are permitted." - ) + return _write_boundary_message(display_prefix) return None @@ -334,15 +338,9 @@ def _entry_paths_validation_error( try: allowed = any(destination_within(path, prefix) for prefix in norm_prefixes) except (OSError, RuntimeError, ValueError): - return ( - f"Write/Edit/apply_patch blocked: {WRITE_GUARD_DENY_TRIGGER}. " - f"Only writes to {display_prefix} are permitted." - ) + return _write_boundary_message(display_prefix) if not allowed: - return ( - f"Write/Edit/apply_patch blocked: {WRITE_GUARD_DENY_TRIGGER}. " - f"Only writes to {display_prefix} are permitted." - ) + return _write_boundary_message(display_prefix) return None From 259e91fc7cc3ba7fa9302c24ce706b3947e97677 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:27:03 -0700 Subject: [PATCH 12/42] refactor(review): reuse the git preflight write scan --- src/autoskillit/hooks/guards/git_ops_guard.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/autoskillit/hooks/guards/git_ops_guard.py b/src/autoskillit/hooks/guards/git_ops_guard.py index c1208960c6..c70d9365a4 100644 --- a/src/autoskillit/hooks/guards/git_ops_guard.py +++ b/src/autoskillit/hooks/guards/git_ops_guard.py @@ -33,6 +33,7 @@ from _command_classification import ( # noqa: E402 _GIT_GLOBAL_FLAG_SPEC, StdinConsumer, + WriteTargetScan, _consume_str_flag, _extract_interpreter_segment_specs, command_verb_and_args, @@ -203,8 +204,8 @@ def _raw_write_targets( additional_segments: list[list[str]], additional_owners: list[int | None], interpreter_cwd: str, + scan: WriteTargetScan, ) -> tuple[list[tuple[str, str]], list[tuple[str, str]], bool]: - scan = scan_write_targets(text, initial_cwd) targets = [(target, initial_cwd) for target in scan.targets] entry_targets = [(target, initial_cwd) for target in scan.entry_targets] ambiguous = scan.unresolved @@ -250,6 +251,7 @@ def _raw_target_mutations( additional_owners: list[int | None], interpreter_cwd: str, context: dict[str, object] | None, + scan: WriteTargetScan, ) -> list[tuple[str, str, bool]]: targets, entry_targets, ambiguous = _raw_write_targets( text, @@ -258,6 +260,7 @@ def _raw_target_mutations( additional_segments, additional_owners, interpreter_cwd, + scan, ) if ambiguous: return [("", "", True)] @@ -374,7 +377,7 @@ def _preflight_segments( def _is_structural_mutation( - live_text: str, outer: list[list[str]], additional: list[list[str]] + live_text: str, outer: list[list[str]], additional: list[list[str]], *, has_write: bool ) -> bool: return bool( re.search( @@ -382,7 +385,7 @@ def _is_structural_mutation( r"reset\b|fetch\b|push\b|symbolic-ref\s+HEAD)\b", live_text, ) - or scan_write_targets(live_text, "").has_write + or has_write or any( os.path.basename(command_verb_and_args(segment)[0]) in _RAW_WRITE_VERBS for segment in [*outer, *additional] @@ -493,7 +496,10 @@ def _preflight_checked_out_ref_mutation( # "git push --force" as prose no longer matches, while a heredoc/pipe-fed # shell that actually runs it still does. live_text = live_command_text(command) - structural_mutation = _is_structural_mutation(live_text, outer_segments, additional_segments) + scan = scan_write_targets(live_text, execution_cwd) + structural_mutation = _is_structural_mutation( + live_text, outer_segments, additional_segments, has_write=scan.has_write + ) if not execution_cwd: if structural_mutation: _deny_checked_out_ref( @@ -525,6 +531,7 @@ def _preflight_checked_out_ref_mutation( additional_owners=additional_owners, interpreter_cwd=current_cwd, context=raw_context, + scan=scan, ) ) if interpreter_unresolved and structural_mutation: From ae5512e35b1b7c6403ef195d986af91f763e378b Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:28:40 -0700 Subject: [PATCH 13/42] fix(review): deny git mutations with unresolved entry parents --- src/autoskillit/hooks/guards/git_ops_guard.py | 7 ++++++- tests/infra/test_git_ops_guard.py | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/autoskillit/hooks/guards/git_ops_guard.py b/src/autoskillit/hooks/guards/git_ops_guard.py index c70d9365a4..d1be6e921d 100644 --- a/src/autoskillit/hooks/guards/git_ops_guard.py +++ b/src/autoskillit/hooks/guards/git_ops_guard.py @@ -272,7 +272,12 @@ def _raw_target_mutations( if not target_cwd: return [("", "", True)] target = Path(target_cwd) / target - resolved_targets.append(destination_location(target) if is_entry else target.resolve()) + try: + resolved_targets.append( + destination_location(target) if is_entry else target.resolve() + ) + except (OSError, RuntimeError, ValueError): + return [("", "", True)] if context is None: return [] common = Path(str(context["common_git_dir"])).resolve() diff --git a/tests/infra/test_git_ops_guard.py b/tests/infra/test_git_ops_guard.py index d5a82cf766..b987d68086 100644 --- a/tests/infra/test_git_ops_guard.py +++ b/tests/infra/test_git_ops_guard.py @@ -1175,6 +1175,20 @@ def test_structural_write_without_execution_cwd_fails_closed( assert _checked_out_ref_result(out)["attempted_value"] == "" +def test_link_entry_parent_loop_fails_closed(linked_repo: dict[str, Path | str]) -> None: + linked = linked_repo["linked"] + assert isinstance(linked, Path) + loop = linked / "loop" + loop.symlink_to(loop) + + out = _run_guard( + f"ln -s source {shlex.quote(str(loop / 'entry'))}", kitchen_open=True, tmpdir=linked + ) + + assert _is_denied(out) + assert _checked_out_ref_result(out)["attempted_value"] == "" + + class TestCheckedOutRefWriteTargets: @pytest.mark.parametrize( "command", From bcab145a0c549d18223eccd988655d29cbf0ee76 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:30:14 -0700 Subject: [PATCH 14/42] fix(review): fail closed on uncertain installation entry stats --- .../guards/installation_integrity_guard.py | 5 ++-- .../test_installation_integrity_guard.py | 25 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/autoskillit/hooks/guards/installation_integrity_guard.py b/src/autoskillit/hooks/guards/installation_integrity_guard.py index 7914bbe483..f9121891b3 100644 --- a/src/autoskillit/hooks/guards/installation_integrity_guard.py +++ b/src/autoskillit/hooks/guards/installation_integrity_guard.py @@ -3,6 +3,7 @@ from __future__ import annotations +import errno import json import os import stat @@ -155,8 +156,8 @@ def _is_protected_entry_target(path: str) -> bool: return True try: entry = os.lstat(path) - except OSError: - return False + except OSError as exc: + return exc.errno not in {errno.ENOENT, errno.ENOTDIR} if stat.S_ISLNK(entry.st_mode): return False return _matches_protected_inode(str(location)) diff --git a/tests/hooks/test_installation_integrity_guard.py b/tests/hooks/test_installation_integrity_guard.py index 17d383aa61..23ab473e29 100644 --- a/tests/hooks/test_installation_integrity_guard.py +++ b/tests/hooks/test_installation_integrity_guard.py @@ -2,6 +2,7 @@ from __future__ import annotations +import errno import json import os import subprocess @@ -290,6 +291,30 @@ def test_blocks_interpreter_write_into_install_tree(tmp_path: Path) -> None: assert _decision(stdout) == "deny" +@pytest.mark.parametrize( + "error", [errno.ENOENT, errno.ENOTDIR, errno.EACCES, errno.ELOOP, errno.EIO] +) +def test_entry_stat_errors_only_allow_absent_entries( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, error: int +) -> None: + from autoskillit.hooks.guards import installation_integrity_guard as guard + + target = tmp_path / "entry" + original_lstat = os.lstat + + def lstat(path, *args, **kwargs): + if os.fspath(path) == str(target): + raise OSError(error, "injected stat failure") + return original_lstat(path, *args, **kwargs) + + monkeypatch.setattr(guard, "_known_roots", lambda: ()) + monkeypatch.setattr(guard.os, "lstat", lstat) + + assert guard._is_protected_entry_target(str(target)) is ( + error not in {errno.ENOENT, errno.ENOTDIR} + ) + + def test_blocks_hardlink_alias_of_uv_tool_file(tmp_path: Path) -> None: home = tmp_path / "home" original = home / ".local/share/uv/tools/autoskillit/lib/site-packages/autoskillit/core.py" From 4e008b66dc88b25994f54d103eb01d99b05c3e38 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:31:46 -0700 Subject: [PATCH 15/42] fix(review): resolve link parents in headless write advisories --- .../execution/headless/_headless_recovery.py | 16 ++++++++++--- .../execution/headless/test_headless_scan.py | 23 +++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/src/autoskillit/execution/headless/_headless_recovery.py b/src/autoskillit/execution/headless/_headless_recovery.py index 3e7a84ad24..6af7572919 100644 --- a/src/autoskillit/execution/headless/_headless_recovery.py +++ b/src/autoskillit/execution/headless/_headless_recovery.py @@ -19,6 +19,7 @@ SkillResult, TokenMeasure, TurnTokenEntry, + destination_location, get_logger, is_parent_assistant_record, ) @@ -99,13 +100,22 @@ def _tool_write_path_warnings( command = inputs.get("command", "") if isinstance(command, str): scan = scan_write_targets(command, cwd) - if scan.unresolved or not scan.parseable: + unresolved = scan.unresolved or not scan.parseable + paths = [(path, cwd) for path in scan.targets] + for path in scan.entry_targets: + try: + location = str(destination_location(Path(path))) + physical_cwd = str(Path(cwd).resolve()) if os.path.isabs(cwd) else cwd + paths.append((location, physical_cwd)) + except (OSError, RuntimeError, ValueError): + unresolved = True + if unresolved: warnings.append( "Bash command contained a write target that could not be statically resolved. " + UNRESOLVED_WRITE_TARGET_REMEDIATION ) - for path in (*scan.targets, *scan.entry_targets): - if _is_path_outside_cwd(path, cwd): + for path, comparison_cwd in paths: + if _is_path_outside_cwd(path, comparison_cwd): normalized = os.path.normpath(path) warnings.append( f"Bash command contained write target '{normalized}'" diff --git a/tests/execution/headless/test_headless_scan.py b/tests/execution/headless/test_headless_scan.py index 795f28d3c0..64c03d6b18 100644 --- a/tests/execution/headless/test_headless_scan.py +++ b/tests/execution/headless/test_headless_scan.py @@ -11,6 +11,29 @@ pytestmark = [pytest.mark.layer("execution"), pytest.mark.small] +@pytest.mark.parametrize("symlinked_parent", [False, True]) +def test_entry_advisory_resolves_parent_but_not_final_symlink(tmp_path, symlinked_parent): + cwd = tmp_path / "cwd" + cwd.mkdir() + outside = tmp_path / "outside" + outside.mkdir() + if symlinked_parent: + (cwd / "parent").symlink_to(outside, target_is_directory=True) + destination = cwd / "parent" / "entry" + else: + destination = cwd / "entry" + destination.symlink_to(outside / "target") + line = _make_tool_use_line("Bash", {"command": f"ln -sT source {destination}"}) + + warnings = _scan_jsonl_write_paths(line, str(cwd)) + + if symlinked_parent: + assert len(warnings) == 1 + assert str(outside / "entry") in warnings[0] + else: + assert warnings == [] + + class TestScanJsonlCustomToolNames: CWD = "/clone/worktree" From d6121ef86006bc32838a5b3f1fc8b93da2019c00 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:33:22 -0700 Subject: [PATCH 16/42] test(review): assert scan behavior without field-order coupling --- tests/hooks/test_command_classification.py | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/tests/hooks/test_command_classification.py b/tests/hooks/test_command_classification.py index 9937e125f5..eb25358aed 100644 --- a/tests/hooks/test_command_classification.py +++ b/tests/hooks/test_command_classification.py @@ -1543,25 +1543,9 @@ def test_chained_write_bytes_on_open_not_double_counted(self): class TestScanWriteTargets: - def test_scan_result_entry_targets_is_last_and_defaults_empty(self) -> None: - fields = dataclasses.fields(command_classification.WriteTargetScan) - - assert fields[-1].name == "entry_targets" - assert fields[-1].default == () + def test_scan_result_entry_targets_defaults_empty(self) -> None: assert command_classification.WriteTargetScan((), False, True, False).entry_targets == () - def test_entry_only_scan_is_a_write(self) -> None: - scan = command_classification.WriteTargetScan( - targets=(), - unresolved=False, - parseable=True, - has_write=True, - entry_targets=("/tmp/link",), - ) - - assert scan.targets == () - assert scan.entry_targets == ("/tmp/link",) - @pytest.mark.parametrize( ("parseable", "has_write"), [(False, True), (True, False)], From 51abda33c0fafe297b83231b1beb69b8cbc1e5be Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:34:46 -0700 Subject: [PATCH 17/42] test(review): assert write scope denial reasons --- tests/hooks/test_write_guard.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/hooks/test_write_guard.py b/tests/hooks/test_write_guard.py index ae4bd4283a..972cb5da46 100644 --- a/tests/hooks/test_write_guard.py +++ b/tests/hooks/test_write_guard.py @@ -613,6 +613,10 @@ def _assert_bash_scope_decision( assert output["permissionDecision"] == "deny" if unresolved: assert UNRESOLVED_WRITE_TARGET_REMEDIATION in output["permissionDecisionReason"] + else: + reason = output["permissionDecisionReason"] + assert write_guard.WRITE_GUARD_DENY_TRIGGER in reason + assert f"Only writes to {allowed} are permitted." in reason @pytest.mark.parametrize( From f998efaa56a423672af3435fd12500fd6c3adb2a Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:35:32 -0700 Subject: [PATCH 18/42] test(review): rely on real entry boundary coverage --- tests/server/test_guards_module.py | 27 +-------------------------- 1 file changed, 1 insertion(+), 26 deletions(-) diff --git a/tests/server/test_guards_module.py b/tests/server/test_guards_module.py index 115cf8ea09..e27928c4b6 100644 --- a/tests/server/test_guards_module.py +++ b/tests/server/test_guards_module.py @@ -2,7 +2,7 @@ import pytest -from autoskillit.hooks import UNRESOLVED_WRITE_TARGET_REMEDIATION, WriteTargetScan +from autoskillit.hooks import UNRESOLVED_WRITE_TARGET_REMEDIATION pytestmark = [pytest.mark.layer("server"), pytest.mark.small] @@ -168,31 +168,6 @@ def test_run_cmd_boundary_denies_sibling_path_sharing_root_prefix( assert str(destination) in result -def test_run_cmd_boundary_does_not_early_allow_location_only_scan(tmp_path, monkeypatch) -> None: - from autoskillit.server.lifecycle import _guards - - allowed = tmp_path / "allowed" - outside = tmp_path / "outside" - allowed.mkdir() - outside.mkdir() - monkeypatch.setattr( - _guards, - "scan_write_targets", - lambda _cmd, _cwd: WriteTargetScan( - targets=(), - unresolved=False, - parseable=True, - has_write=True, - entry_targets=(str(outside / "link"),), - ), - ) - - result = _guards._check_write_target_boundary("ln", str(tmp_path), (str(allowed),)) - - assert result is not None - assert str(outside / "link") in result - - def test_run_cmd_entry_check_uses_link_location_not_referent(tmp_path) -> None: from autoskillit.server.lifecycle._guards import _check_write_target_boundary From c1118d3d27442729f57905cb60f0d54f6794fb44 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:36:19 -0700 Subject: [PATCH 19/42] test(review): restore known-cwd herestring redirect coverage --- tests/infra/test_git_ops_guard.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/tests/infra/test_git_ops_guard.py b/tests/infra/test_git_ops_guard.py index b987d68086..cb06e27dd3 100644 --- a/tests/infra/test_git_ops_guard.py +++ b/tests/infra/test_git_ops_guard.py @@ -552,8 +552,16 @@ def test_allows_inert_backtick_heredoc_git_push(self, tmp_path) -> None: ) assert out.strip() == "" - @pytest.mark.parametrize("include_execution_cwd", [True, False]) - def test_allows_inert_herestring_git_push(self, tmp_path, include_execution_cwd: bool) -> None: + @pytest.mark.parametrize( + ("command", "include_execution_cwd"), + [ + ("cat > f.md <<< 'git push --force origin main'", True), + ("cat <<< 'git push --force origin main'", False), + ], + ) + def test_allows_inert_herestring_git_push( + self, tmp_path, command: str, include_execution_cwd: bool + ) -> None: """A `cat` herestring containing an inert git push must not deny.""" _git(tmp_path, "init", "-b", "develop") _git(tmp_path, "config", "user.name", "Guard Test") @@ -562,7 +570,7 @@ def test_allows_inert_herestring_git_push(self, tmp_path, include_execution_cwd: _git(tmp_path, "add", "f.txt") _git(tmp_path, "commit", "-m", "initial") out = _run_guard( - "cat <<< 'git push --force origin main'", + command, kitchen_open=True, tmpdir=tmp_path, include_execution_cwd=include_execution_cwd, From 0f8d4233404a7401cdba825bd6c3be1080c7b75c Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 14:50:34 -0700 Subject: [PATCH 20/42] fix(review): keep write advisory evidence within module budgets --- .../execution/headless/_headless_evidence.py | 45 +++++++++++++++++++ .../execution/headless/_headless_recovery.py | 44 +----------------- 2 files changed, 46 insertions(+), 43 deletions(-) diff --git a/src/autoskillit/execution/headless/_headless_evidence.py b/src/autoskillit/execution/headless/_headless_evidence.py index 96ea7afffb..b100765478 100644 --- a/src/autoskillit/execution/headless/_headless_evidence.py +++ b/src/autoskillit/execution/headless/_headless_evidence.py @@ -4,7 +4,9 @@ import dataclasses import json +import os from datetime import UTC, datetime +from pathlib import Path from typing import TYPE_CHECKING, Any from autoskillit.core import ( @@ -18,11 +20,14 @@ SessionTelemetry, SkillResult, SubagentModelOutcomeDict, + destination_location, get_logger, is_parent_assistant_record, ) +from autoskillit.execution.headless._headless_path_tokens import _is_path_outside_cwd from autoskillit.execution.session._exit_classification import _CODEX_ERROR_CODE_API_STATUS from autoskillit.execution.session._session_model import ClaudeSessionResult +from autoskillit.hooks import UNRESOLVED_WRITE_TARGET_REMEDIATION, scan_write_targets if TYPE_CHECKING: from autoskillit.core import AuditLog, CodingAgentBackend, GitHubApiLog @@ -176,6 +181,46 @@ def _stdout_mentions_write_tools(stdout: str) -> bool: return False +def _tool_write_path_warnings( + tool_name: Any, + inputs: dict[str, Any], + cwd: str, + write_tool_names: frozenset[str], + bash_tool_name: str, +) -> list[str]: + warnings: list[str] = [] + if tool_name == bash_tool_name: + command = inputs.get("command", "") + if isinstance(command, str): + scan = scan_write_targets(command, cwd) + unresolved = scan.unresolved or not scan.parseable + paths = [(path, cwd) for path in scan.targets] + for path in scan.entry_targets: + try: + location = str(destination_location(Path(path))) + physical_cwd = str(Path(cwd).resolve()) if os.path.isabs(cwd) else cwd + paths.append((location, physical_cwd)) + except (OSError, RuntimeError, ValueError): + unresolved = True + if unresolved: + warnings.append( + "Bash command contained a write target that could not be statically resolved. " + + UNRESOLVED_WRITE_TARGET_REMEDIATION + ) + for path, comparison_cwd in paths: + if _is_path_outside_cwd(path, comparison_cwd): + normalized = os.path.normpath(path) + warnings.append( + f"Bash command contained write target '{normalized}'" + f" outside session cwd '{cwd}'" + ) + elif tool_name in write_tool_names: + file_path = inputs.get("file_path", "") + if isinstance(file_path, str) and _is_path_outside_cwd(file_path, cwd): + warnings.append(f"{tool_name} tool targeted '{file_path}' outside session cwd '{cwd}'") + return warnings + + def _build_session_telemetry( *, skill_result: SkillResult, diff --git a/src/autoskillit/execution/headless/_headless_recovery.py b/src/autoskillit/execution/headless/_headless_recovery.py index 6af7572919..948b47b87b 100644 --- a/src/autoskillit/execution/headless/_headless_recovery.py +++ b/src/autoskillit/execution/headless/_headless_recovery.py @@ -19,14 +19,13 @@ SkillResult, TokenMeasure, TurnTokenEntry, - destination_location, get_logger, is_parent_assistant_record, ) from autoskillit.execution.backends._codex_parse import extract_codex_turn_usage +from autoskillit.execution.headless._headless_evidence import _tool_write_path_warnings from autoskillit.execution.headless._headless_path_tokens import ( _RECOVERABLE_PATH_TOKENS, - _is_path_outside_cwd, ) from autoskillit.execution.process import _marker_is_standalone from autoskillit.execution.session import ( @@ -41,7 +40,6 @@ merge_turn_usage, valid_token_count, ) -from autoskillit.hooks import UNRESOLVED_WRITE_TARGET_REMEDIATION, scan_write_targets if TYPE_CHECKING: from autoskillit.core import ResultParser @@ -88,46 +86,6 @@ def _is_path_capture_pattern(pattern: str) -> str | None: return token_name -def _tool_write_path_warnings( - tool_name: Any, - inputs: dict[str, Any], - cwd: str, - write_tool_names: frozenset[str], - bash_tool_name: str, -) -> list[str]: - warnings: list[str] = [] - if tool_name == bash_tool_name: - command = inputs.get("command", "") - if isinstance(command, str): - scan = scan_write_targets(command, cwd) - unresolved = scan.unresolved or not scan.parseable - paths = [(path, cwd) for path in scan.targets] - for path in scan.entry_targets: - try: - location = str(destination_location(Path(path))) - physical_cwd = str(Path(cwd).resolve()) if os.path.isabs(cwd) else cwd - paths.append((location, physical_cwd)) - except (OSError, RuntimeError, ValueError): - unresolved = True - if unresolved: - warnings.append( - "Bash command contained a write target that could not be statically resolved. " - + UNRESOLVED_WRITE_TARGET_REMEDIATION - ) - for path, comparison_cwd in paths: - if _is_path_outside_cwd(path, comparison_cwd): - normalized = os.path.normpath(path) - warnings.append( - f"Bash command contained write target '{normalized}'" - f" outside session cwd '{cwd}'" - ) - elif tool_name in write_tool_names: - file_path = inputs.get("file_path", "") - if isinstance(file_path, str) and _is_path_outside_cwd(file_path, cwd): - warnings.append(f"{tool_name} tool targeted '{file_path}' outside session cwd '{cwd}'") - return warnings - - def _scan_jsonl_write_paths( stdout: str, cwd: str, From 88859f38a4f48e6fde4fe7e438330c5b3c527694 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 15:04:22 -0700 Subject: [PATCH 21/42] test(review): track the actual headless scanner consumer --- tests/arch/test_write_target_single_authority.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/arch/test_write_target_single_authority.py b/tests/arch/test_write_target_single_authority.py index 9e5162a695..3c3dd2ef91 100644 --- a/tests/arch/test_write_target_single_authority.py +++ b/tests/arch/test_write_target_single_authority.py @@ -17,12 +17,12 @@ def test_write_target_consumers_share_hooks_scanner() -> None: import autoskillit.core as core import autoskillit.core.git as core_git - import autoskillit.execution.headless._headless_recovery as recovery + import autoskillit.execution.headless._headless_evidence as evidence import autoskillit.hooks as hooks import autoskillit.server.lifecycle._guards as guards assert guards.scan_write_targets is hooks.scan_write_targets - assert recovery.scan_write_targets is hooks.scan_write_targets + assert evidence.scan_write_targets is hooks.scan_write_targets assert not hasattr(core, "extract_bash_write_targets") assert not hasattr(core_git, "extract_bash_write_targets") From 8b9702c52bc3a7461893640bb5b5b58640c6881d Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 16:21:08 -0700 Subject: [PATCH 22/42] fix(review): share write destination identity across hooks and core --- src/autoskillit/_destination_paths.py | 14 +++++++++++++ src/autoskillit/core/io/paths.py | 21 ++----------------- .../hooks/_runtime/_path_identity.py | 18 +++++++++------- .../_installed/_projection_assets.py | 1 + tests/contracts/test_package_gateways.py | 1 + tests/hooks/test_path_identity.py | 1 + 6 files changed, 29 insertions(+), 27 deletions(-) create mode 100644 src/autoskillit/_destination_paths.py diff --git a/src/autoskillit/_destination_paths.py b/src/autoskillit/_destination_paths.py new file mode 100644 index 0000000000..9f019ddfa0 --- /dev/null +++ b/src/autoskillit/_destination_paths.py @@ -0,0 +1,14 @@ +"""Stdlib-only write-destination identity shared by hooks and in-process callers.""" + +from __future__ import annotations + +import os +from pathlib import Path + + +def destination_location(destination: str | os.PathLike[str]) -> Path: + """Resolve the parent of a write destination, preserving its final symlink entry.""" + path = Path(destination) + if not path.name or path.name == "..": + return path.resolve() + return path.parent.resolve() / path.name diff --git a/src/autoskillit/core/io/paths.py b/src/autoskillit/core/io/paths.py index 1a2abd7445..c7783acb07 100644 --- a/src/autoskillit/core/io/paths.py +++ b/src/autoskillit/core/io/paths.py @@ -23,6 +23,8 @@ from pathlib import Path from typing import NamedTuple +from autoskillit._destination_paths import destination_location as destination_location + from .._install_binding import resolve_install_binding from ..fs_observation import safe_mtime @@ -79,25 +81,6 @@ def pkg_root() -> Path: return resolve_install_binding().root -def destination_location(destination: Path) -> Path: - """Resolve a write destination's location without following a final-component symlink. - - ``Path.resolve()`` follows the final component, so a destination that is - *currently* a symlink resolves to its target. For a write destination that - is the wrong question: the destination is about to be replaced, so what - matters is where it lives, not what it happens to point at right now. - Every containment check over a write destination must use this helper. - - ``core/path_containment.py`` is the read-side counterpart and deliberately - does the opposite (``strict=True``, symlinks rejected) — it validates - existing artifacts rather than future write targets. - """ - destination = Path(destination) - if not destination.name or destination.name == "..": - return destination.resolve() - return destination.parent.resolve() / destination.name - - def resolve_project_dir() -> Path: """Resolve the project root: git toplevel, falling back to cwd. diff --git a/src/autoskillit/hooks/_runtime/_path_identity.py b/src/autoskillit/hooks/_runtime/_path_identity.py index 8ec8e70a7f..24c9325477 100644 --- a/src/autoskillit/hooks/_runtime/_path_identity.py +++ b/src/autoskillit/hooks/_runtime/_path_identity.py @@ -10,7 +10,17 @@ from __future__ import annotations import os +import sys from pathlib import Path +from typing import TYPE_CHECKING + +if TYPE_CHECKING or __package__: + from autoskillit._destination_paths import destination_location +else: + _PACKAGE_DIR = str(Path(__file__).resolve().parents[2]) + if _PACKAGE_DIR not in sys.path: + sys.path.insert(0, _PACKAGE_DIR) + from _destination_paths import destination_location class PathIdentityError(ValueError): @@ -37,14 +47,6 @@ def hooks_relative_key(script_identity: str | os.PathLike[str], hooks_dir: Path) ) from exc -def destination_location(destination: str | os.PathLike[str]) -> Path: - """Resolve a destination's parent without following its final component.""" - path = Path(destination) - if not path.name or path.name == "..": - return path.resolve() - return path.parent.resolve() / path.name - - def destination_within(candidate: str | os.PathLike[str], root: str | os.PathLike[str]) -> bool: """Compare an entry's physical location with a resolved directory boundary.""" return destination_location(candidate).is_relative_to(Path(root).resolve()) diff --git a/src/autoskillit/workspace/_installed/_projection_assets.py b/src/autoskillit/workspace/_installed/_projection_assets.py index ba971b1887..58b93cdb4c 100644 --- a/src/autoskillit/workspace/_installed/_projection_assets.py +++ b/src/autoskillit/workspace/_installed/_projection_assets.py @@ -20,6 +20,7 @@ { ".claude-plugin", ".mcp.json", + "_destination_paths.py", "_measure_aggregation.py", "_parent_assistant_turns.py", "_recipe_delivery_framing.py", diff --git a/tests/contracts/test_package_gateways.py b/tests/contracts/test_package_gateways.py index d201b9e6b7..e57c90b149 100644 --- a/tests/contracts/test_package_gateways.py +++ b/tests/contracts/test_package_gateways.py @@ -408,6 +408,7 @@ def test_root_module_allowlist() -> None: { "__init__.py", "__main__.py", + "_destination_paths.py", "_llm_triage.py", "_measure_aggregation.py", "_parent_assistant_turns.py", diff --git a/tests/hooks/test_path_identity.py b/tests/hooks/test_path_identity.py index 33c30221b8..8132faa4bf 100644 --- a/tests/hooks/test_path_identity.py +++ b/tests/hooks/test_path_identity.py @@ -100,6 +100,7 @@ def test_destination_location_handles_root_destination() -> None: @pytest.mark.parametrize("name", ["entry", "final-link", "..", "."]) def test_destination_location_core_and_hook_conformance(tmp_path: Path, name: str) -> None: + assert destination_location is core_destination_location real_parent = tmp_path / "real" real_parent.mkdir() linked_parent = tmp_path / "linked" From d0d1e1a3b2719ee92cfcdf30fd4eb7c4322ec346 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 16:22:46 -0700 Subject: [PATCH 23/42] refactor(review): share explicit target directory resolution --- .../hooks/_runtime/_write_target_scan.py | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/src/autoskillit/hooks/_runtime/_write_target_scan.py b/src/autoskillit/hooks/_runtime/_write_target_scan.py index a48eec9cde..86586fa9b4 100644 --- a/src/autoskillit/hooks/_runtime/_write_target_scan.py +++ b/src/autoskillit/hooks/_runtime/_write_target_scan.py @@ -222,12 +222,25 @@ def _directory_children( return targets, unresolved +def _target_directory_children( + target_directory: tuple[str, str | None], + source_indices: list[int], + argv: list[str], + cwd: str, + argv_tokens: Sequence[ArgvToken] | None, +) -> tuple[list[str], bool]: + value, source = target_directory + directory = _classification_module().resolve_write_target(value, cwd, shell_source=source) + if directory is None: + return [], True + return _directory_children(directory, source_indices, argv, cwd, argv_tokens) + + def _install_targets( argv: list[str], cwd: str, argv_tokens: Sequence[ArgvToken] | None, ) -> tuple[list[str], bool]: - _classification = _classification_module() options = _destination_operands("install", argv, argv_tokens) operands = options.operands target_directory = options.target_directory @@ -241,11 +254,7 @@ def _install_targets( target is None for target in targets ) if target_directory is not None: - value, source = target_directory - directory = _classification.resolve_write_target(value, cwd, shell_source=source) - if directory is None: - return [], True - return _directory_children(directory, operands, argv, cwd, argv_tokens) + return _target_directory_children(target_directory, operands, argv, cwd, argv_tokens) if len(operands) < 2: return [], True @@ -265,18 +274,13 @@ def _ln_entry_targets( cwd: str, argv_tokens: Sequence[ArgvToken] | None, ) -> tuple[list[str], bool]: - _classification = _classification_module() options = _destination_operands("ln", argv, argv_tokens) operands = options.operands target_directory = options.target_directory if options.invalid or not operands: return [], True if target_directory is not None: - value, source = target_directory - directory = _classification.resolve_write_target(value, cwd, shell_source=source) - if directory is None: - return [], True - return _directory_children(directory, operands, argv, cwd, argv_tokens) + return _target_directory_children(target_directory, operands, argv, cwd, argv_tokens) if len(operands) == 1: basename = _source_basename(argv, operands[0], cwd, argv_tokens) return ([os.path.join(cwd, basename)], False) if cwd and basename else ([], True) From 61aa8e2db07edfaef4f62cc0d89639938ac1d0ac Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 16:27:40 -0700 Subject: [PATCH 24/42] fix(review): recognize coreutils informational and backup options --- .../hooks/_runtime/_write_target_scan.py | 38 ++++++++++++++----- tests/hooks/test_write_target_scan.py | 22 +++++++++++ 2 files changed, 51 insertions(+), 9 deletions(-) diff --git a/src/autoskillit/hooks/_runtime/_write_target_scan.py b/src/autoskillit/hooks/_runtime/_write_target_scan.py index 86586fa9b4..48c8fbaf27 100644 --- a/src/autoskillit/hooks/_runtime/_write_target_scan.py +++ b/src/autoskillit/hooks/_runtime/_write_target_scan.py @@ -62,6 +62,7 @@ class _DestinationOperands: no_target_directory: bool no_dereference: bool create_directories: bool + read_only: bool invalid: bool @@ -108,6 +109,7 @@ def _destination_operands( "--suffix": value, } boolean_long = { + "--backup", "--compare", "--directory", "--preserve-timestamps", @@ -123,6 +125,7 @@ def _destination_operands( no_dereference = False directory_mode = False invalid = False + read_only = False options = True index = 1 while index < len(argv): @@ -132,6 +135,10 @@ def _destination_operands( index += 1 continue if options and token.startswith("-") and token != "-": + if token in {"--help", "--version"}: + read_only = True + index += 1 + continue option_value, source, next_index, recognized = ( _classification._consume_destination_option(argv, argv_tokens, index, value_spec) ) @@ -145,7 +152,7 @@ def _destination_operands( continue if ( token in boolean_long - or (verb == "ln" and token.startswith("--backup=")) + or token.startswith("--backup=") or ( not token.startswith("--") and all(char in boolean_short for char in token[1:]) ) @@ -174,6 +181,7 @@ def _destination_operands( no_target_directory=no_target_directory, no_dereference=no_dereference, create_directories=directory_mode, + read_only=read_only, invalid=invalid, ) @@ -240,8 +248,8 @@ def _install_targets( argv: list[str], cwd: str, argv_tokens: Sequence[ArgvToken] | None, + options: _DestinationOperands, ) -> tuple[list[str], bool]: - options = _destination_operands("install", argv, argv_tokens) operands = options.operands target_directory = options.target_directory if options.invalid or not operands: @@ -273,8 +281,8 @@ def _ln_entry_targets( argv: list[str], cwd: str, argv_tokens: Sequence[ArgvToken] | None, + options: _DestinationOperands, ) -> tuple[list[str], bool]: - options = _destination_operands("ln", argv, argv_tokens) operands = options.operands target_directory = options.target_directory if options.invalid or not operands: @@ -561,6 +569,22 @@ def _invoked_child_state( return None +def _scan_destination_command( + verb: str, + argv: list[str], + cwd: str, + argv_tokens: Sequence[ArgvToken] | None, +) -> WriteTargetScan: + options = _destination_operands(verb, argv, argv_tokens) + if options.read_only: + return WriteTargetScan((), False, True, False) + if verb == "ln": + targets, unresolved = _ln_entry_targets(argv, cwd, argv_tokens, options) + return WriteTargetScan((), unresolved, True, True, entry_targets=tuple(targets)) + targets, unresolved = _install_targets(argv, cwd, argv_tokens, options) + return WriteTargetScan(tuple(targets), unresolved, True, True) + + def _scan_executable( executable: list[str], argv_tokens: Sequence[ArgvToken] | None, @@ -590,12 +614,8 @@ def _scan_executable( if verb_name == "npm": targets, unresolved, has_write = _npm_install_targets(argv, verb_cwd, verb_tokens) return WriteTargetScan(tuple(targets), unresolved, True, has_write), invoked - if verb_name == "ln": - targets, unresolved = _ln_entry_targets(argv, verb_cwd, verb_tokens) - return WriteTargetScan((), unresolved, True, True, entry_targets=tuple(targets)), invoked - if verb_name == "install": - targets, unresolved = _install_targets(argv, verb_cwd, verb_tokens) - return WriteTargetScan(tuple(targets), unresolved, True, True), invoked + if verb_name in {"ln", "install"}: + return _scan_destination_command(verb_name, argv, verb_cwd, verb_tokens), invoked if verb in WRITE_VERBS: targets, unresolved = _classification.extract_write_verb_targets( verb, argv, verb_cwd, argv_tokens=verb_tokens diff --git a/tests/hooks/test_write_target_scan.py b/tests/hooks/test_write_target_scan.py index 56420988a1..f0b8b19363 100644 --- a/tests/hooks/test_write_target_scan.py +++ b/tests/hooks/test_write_target_scan.py @@ -257,6 +257,28 @@ def test_ln_options_preserve_entry_destination(option: str) -> None: assert not result.unresolved +@pytest.mark.parametrize("command", ["ln --help", "install --version"]) +def test_coreutils_informational_options_do_not_write(command: str) -> None: + result = scan_write_targets(command, _WORKSPACE) + assert not result.has_write + assert not result.unresolved + + +@pytest.mark.parametrize("command", ["ln -t --help source", "ln -- --help source"]) +def test_help_spelling_as_an_operand_still_writes(command: str) -> None: + result = scan_write_targets(command, _WORKSPACE) + assert result.has_write + assert result.entry_targets + assert not result.unresolved + + +@pytest.mark.parametrize("option", ["--backup", "--backup=numbered"]) +def test_install_backup_option_preserves_destination(option: str) -> None: + result = scan_write_targets(f"install {option} source destination", _WORKSPACE) + assert result.targets == ("/workspace/destination",) + assert not result.unresolved + + def test_ln_directory_and_final_symlink_semantics( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: From 3a388da8bfd62515049c584134ad778489fe9a9b Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 16:29:42 -0700 Subject: [PATCH 25/42] refactor(review): make parsed destination operands immutable --- src/autoskillit/hooks/_runtime/_write_target_scan.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/autoskillit/hooks/_runtime/_write_target_scan.py b/src/autoskillit/hooks/_runtime/_write_target_scan.py index 48c8fbaf27..721532c822 100644 --- a/src/autoskillit/hooks/_runtime/_write_target_scan.py +++ b/src/autoskillit/hooks/_runtime/_write_target_scan.py @@ -57,7 +57,7 @@ def _classification_module() -> ModuleType: @dataclass(frozen=True, slots=True) class _DestinationOperands: - operands: list[int] + operands: tuple[int, ...] target_directory: tuple[str, str | None] | None no_target_directory: bool no_dereference: bool @@ -176,7 +176,7 @@ def _destination_operands( index += 1 invalid |= target_directory is not None and no_target_directory return _DestinationOperands( - operands=operands, + operands=tuple(operands), target_directory=target_directory, no_target_directory=no_target_directory, no_dereference=no_dereference, @@ -214,7 +214,7 @@ def _source_basename( def _directory_children( directory: str, - source_indices: list[int], + source_indices: Sequence[int], argv: list[str], cwd: str, argv_tokens: Sequence[ArgvToken] | None, @@ -232,7 +232,7 @@ def _directory_children( def _target_directory_children( target_directory: tuple[str, str | None], - source_indices: list[int], + source_indices: Sequence[int], argv: list[str], cwd: str, argv_tokens: Sequence[ArgvToken] | None, From e781cd10972c2eda14c6bbff02bfac93c861e965 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 16:31:01 -0700 Subject: [PATCH 26/42] fix(review): identify both target fields in scan invariant errors --- src/autoskillit/hooks/_runtime/_write_target_scan.py | 8 ++++++-- tests/hooks/test_command_classification.py | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/autoskillit/hooks/_runtime/_write_target_scan.py b/src/autoskillit/hooks/_runtime/_write_target_scan.py index 721532c822..23d17f3627 100644 --- a/src/autoskillit/hooks/_runtime/_write_target_scan.py +++ b/src/autoskillit/hooks/_runtime/_write_target_scan.py @@ -34,9 +34,13 @@ class WriteTargetScan: def __post_init__(self) -> None: if not self.parseable and (self.targets or self.entry_targets): - raise ValueError("WriteTargetScan targets must be empty when parseable is False") + raise ValueError( + "WriteTargetScan targets and entry_targets must be empty when parseable is False" + ) if not self.has_write and (self.targets or self.entry_targets): - raise ValueError("WriteTargetScan targets must be empty when has_write is False") + raise ValueError( + "WriteTargetScan targets and entry_targets must be empty when has_write is False" + ) @dataclass(slots=True) diff --git a/tests/hooks/test_command_classification.py b/tests/hooks/test_command_classification.py index eb25358aed..4ac1ce4ab1 100644 --- a/tests/hooks/test_command_classification.py +++ b/tests/hooks/test_command_classification.py @@ -1552,7 +1552,7 @@ def test_scan_result_entry_targets_defaults_empty(self) -> None: ids=("unparseable", "not-a-write"), ) def test_entry_targets_obey_scan_invariants(self, parseable: bool, has_write: bool) -> None: - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="targets and entry_targets"): command_classification.WriteTargetScan( targets=(), unresolved=False, From e553f9f5f3e36c30ea87a1679363192f17fed10c Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 16:32:50 -0700 Subject: [PATCH 27/42] fix(review): retain install mutation detection for piped shell bodies --- src/autoskillit/hooks/guards/git_ops_guard.py | 2 +- tests/infra/test_git_ops_guard.py | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/autoskillit/hooks/guards/git_ops_guard.py b/src/autoskillit/hooks/guards/git_ops_guard.py index d1be6e921d..30508e2a91 100644 --- a/src/autoskillit/hooks/guards/git_ops_guard.py +++ b/src/autoskillit/hooks/guards/git_ops_guard.py @@ -392,7 +392,7 @@ def _is_structural_mutation( ) or has_write or any( - os.path.basename(command_verb_and_args(segment)[0]) in _RAW_WRITE_VERBS + os.path.basename(command_verb_and_args(segment)[0]) in _RAW_WRITE_VERBS | {"install"} for segment in [*outer, *additional] ) ) diff --git a/tests/infra/test_git_ops_guard.py b/tests/infra/test_git_ops_guard.py index cb06e27dd3..4f723721bd 100644 --- a/tests/infra/test_git_ops_guard.py +++ b/tests/infra/test_git_ops_guard.py @@ -536,6 +536,15 @@ def test_denies_raw_write_verb_via_heredoc_preflight( ) assert _is_denied(out) + def test_denies_piped_install_heredoc_without_execution_cwd(self, tmp_path) -> None: + out = _run_guard( + "cat <<'EOF' | bash\ninstall source destination\nEOF", + kitchen_open=True, + tmpdir=tmp_path, + include_execution_cwd=False, + ) + assert _checked_out_ref_result(out)["execution_cwd"] == "" + def test_allows_inert_backtick_heredoc_git_push(self, tmp_path) -> None: """cat-redirect-heredoc-inline-backtick: an inert `cat` body mentioning `git push --force` inside a single backtick pair must not deny.""" From a6a58d1cc623895650bbdb8ec7a49038095c2428 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 16:34:37 -0700 Subject: [PATCH 28/42] fix(review): distinguish unresolved link entries from protected installs --- .../guards/installation_integrity_guard.py | 22 +++++++++--------- .../test_installation_integrity_guard.py | 23 +++++++++++++++++++ 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/src/autoskillit/hooks/guards/installation_integrity_guard.py b/src/autoskillit/hooks/guards/installation_integrity_guard.py index f9121891b3..5245f364b4 100644 --- a/src/autoskillit/hooks/guards/installation_integrity_guard.py +++ b/src/autoskillit/hooks/guards/installation_integrity_guard.py @@ -142,17 +142,11 @@ def _is_protected_target(path: str) -> bool: def _is_protected_entry_target(path: str) -> bool: - try: - location = destination_location(Path(path)) - except (OSError, RuntimeError, ValueError): - return True + location = destination_location(Path(path)) if _has_install_layout(str(location)): return True for root in _known_roots(): - try: - if location == destination_location(root) or destination_within(path, root): - return True - except (OSError, RuntimeError, ValueError): + if location == destination_location(root) or destination_within(path, root): return True try: entry = os.lstat(path) @@ -225,9 +219,15 @@ def main() -> None: "unresolved-write-target", "Write target could not be resolved safely. " + UNRESOLVED_WRITE_TARGET_REMEDIATION, ) - if any(_is_protected_target(path) for path in targets) or any( - _is_protected_entry_target(path) for path in entry_targets - ): + try: + protected_entry = any(_is_protected_entry_target(path) for path in entry_targets) + except (OSError, RuntimeError, ValueError): + _deny( + "unresolved-write-target", + "Link entry destination could not be resolved safely. " + "Check its path components and symlinks.", + ) + if any(_is_protected_target(path) for path in targets) or protected_entry: _deny( "protected-installation-target", f"Writing a {INSTALLATION_INTEGRITY_DENY_TRIGGER} is prohibited.", diff --git a/tests/hooks/test_installation_integrity_guard.py b/tests/hooks/test_installation_integrity_guard.py index 23ab473e29..aec08c2650 100644 --- a/tests/hooks/test_installation_integrity_guard.py +++ b/tests/hooks/test_installation_integrity_guard.py @@ -3,6 +3,7 @@ from __future__ import annotations import errno +import io import json import os import subprocess @@ -315,6 +316,28 @@ def lstat(path, *args, **kwargs): ) +@pytest.mark.parametrize("failure_site", ["destination_location", "destination_within"]) +def test_entry_resolution_failure_has_unresolved_reason( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys, failure_site: str +) -> None: + from autoskillit.hooks.guards import installation_integrity_guard as guard + + def fail_resolution(*args): + raise RuntimeError("injected resolution failure") + + event = _bash(f"ln -s source {tmp_path / 'entry'}") + event["cwd"] = str(tmp_path) + monkeypatch.setattr(guard, "_known_roots", lambda: (tmp_path / "protected",)) + monkeypatch.setattr(guard, failure_site, fail_resolution) + monkeypatch.setattr(sys, "stdin", io.StringIO(json.dumps(event))) + with pytest.raises(SystemExit) as result: + guard.main() + assert result.value.code == 0 + output = json.loads(capsys.readouterr().out)["hookSpecificOutput"] + assert output["permissionDecision"] == "deny" + assert "code=unresolved-write-target" in output["permissionDecisionReason"] + + def test_blocks_hardlink_alias_of_uv_tool_file(tmp_path: Path) -> None: home = tmp_path / "home" original = home / ".local/share/uv/tools/autoskillit/lib/site-packages/autoskillit/core.py" From 99baaf32c2d5c701a135e845818db0f31b7243d1 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 16:36:22 -0700 Subject: [PATCH 29/42] fix(review): explain entry path resolution failures in write guard --- src/autoskillit/hooks/guards/write_guard.py | 5 ++++- tests/hooks/test_write_guard.py | 13 +++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/autoskillit/hooks/guards/write_guard.py b/src/autoskillit/hooks/guards/write_guard.py index b2ff4e2fe4..87b929b131 100644 --- a/src/autoskillit/hooks/guards/write_guard.py +++ b/src/autoskillit/hooks/guards/write_guard.py @@ -338,7 +338,10 @@ def _entry_paths_validation_error( try: allowed = any(destination_within(path, prefix) for prefix in norm_prefixes) except (OSError, RuntimeError, ValueError): - return _write_boundary_message(display_prefix) + return ( + f"Write/Edit/apply_patch blocked: {WRITE_GUARD_DENY_TRIGGER} " + f"(unresolved write target {path!r}). Check its path components and symlinks." + ) if not allowed: return _write_boundary_message(display_prefix) return None diff --git a/tests/hooks/test_write_guard.py b/tests/hooks/test_write_guard.py index 972cb5da46..6c717efcca 100644 --- a/tests/hooks/test_write_guard.py +++ b/tests/hooks/test_write_guard.py @@ -826,6 +826,19 @@ def test_ln_entry_resolves_symlinked_parent(monkeypatch: pytest.MonkeyPatch, tmp ) +def test_entry_resolution_failure_reports_unresolved_target(monkeypatch, tmp_path) -> None: + def fail_resolution(*args): + raise RuntimeError("injected resolution failure") + + monkeypatch.setattr(write_guard, "destination_within", fail_resolution) + reason = write_guard._bash_validation_error( + f"ln -s source {tmp_path / 'entry'}", str(tmp_path), [str(tmp_path)], str(tmp_path) + ) + assert reason is not None + assert "unresolved write target" in reason + assert "path components and symlinks" in reason + + @pytest.mark.parametrize("command", ['echo x > "$F"', 'cp a "$F"']) def test_denies_unresolved_bash_write_target( monkeypatch: pytest.MonkeyPatch, tmp_path, command: str From 0133e374e8f6c7404e1804758d426580d427ee0c Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 16:37:52 -0700 Subject: [PATCH 30/42] style(review): place destination helper with lowercase hook exports --- src/autoskillit/hooks/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/autoskillit/hooks/__init__.py b/src/autoskillit/hooks/__init__.py index 44fef79b90..0824bd38e3 100644 --- a/src/autoskillit/hooks/__init__.py +++ b/src/autoskillit/hooks/__init__.py @@ -96,7 +96,6 @@ del _HOOK_REGISTRY_LIST __all__ = [ - "destination_within", "BRANCH_PROTECTION_DENY_TRIGGER", "CODEX_AUTO_COMPACTION_DENIED_REASON", "DENY_REASON_BY_GUARD", @@ -140,6 +139,7 @@ "capture_store_stats", "command_has_blocked_protected_path_read", "consume_exploration_request_record", + "destination_within", "generate_hooks_json", "is_terminal_outcome", "mark_assignment_running", From 344e07557a40c77586dd6fac9848d281c5ddcd12 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 16:39:31 -0700 Subject: [PATCH 31/42] refactor(review): keep write path warnings with headless path helpers --- .../execution/headless/_headless_evidence.py | 45 ------------------ .../headless/_headless_path_tokens.py | 46 ++++++++++++++++++- .../execution/headless/_headless_recovery.py | 2 +- 3 files changed, 45 insertions(+), 48 deletions(-) diff --git a/src/autoskillit/execution/headless/_headless_evidence.py b/src/autoskillit/execution/headless/_headless_evidence.py index b100765478..96ea7afffb 100644 --- a/src/autoskillit/execution/headless/_headless_evidence.py +++ b/src/autoskillit/execution/headless/_headless_evidence.py @@ -4,9 +4,7 @@ import dataclasses import json -import os from datetime import UTC, datetime -from pathlib import Path from typing import TYPE_CHECKING, Any from autoskillit.core import ( @@ -20,14 +18,11 @@ SessionTelemetry, SkillResult, SubagentModelOutcomeDict, - destination_location, get_logger, is_parent_assistant_record, ) -from autoskillit.execution.headless._headless_path_tokens import _is_path_outside_cwd from autoskillit.execution.session._exit_classification import _CODEX_ERROR_CODE_API_STATUS from autoskillit.execution.session._session_model import ClaudeSessionResult -from autoskillit.hooks import UNRESOLVED_WRITE_TARGET_REMEDIATION, scan_write_targets if TYPE_CHECKING: from autoskillit.core import AuditLog, CodingAgentBackend, GitHubApiLog @@ -181,46 +176,6 @@ def _stdout_mentions_write_tools(stdout: str) -> bool: return False -def _tool_write_path_warnings( - tool_name: Any, - inputs: dict[str, Any], - cwd: str, - write_tool_names: frozenset[str], - bash_tool_name: str, -) -> list[str]: - warnings: list[str] = [] - if tool_name == bash_tool_name: - command = inputs.get("command", "") - if isinstance(command, str): - scan = scan_write_targets(command, cwd) - unresolved = scan.unresolved or not scan.parseable - paths = [(path, cwd) for path in scan.targets] - for path in scan.entry_targets: - try: - location = str(destination_location(Path(path))) - physical_cwd = str(Path(cwd).resolve()) if os.path.isabs(cwd) else cwd - paths.append((location, physical_cwd)) - except (OSError, RuntimeError, ValueError): - unresolved = True - if unresolved: - warnings.append( - "Bash command contained a write target that could not be statically resolved. " - + UNRESOLVED_WRITE_TARGET_REMEDIATION - ) - for path, comparison_cwd in paths: - if _is_path_outside_cwd(path, comparison_cwd): - normalized = os.path.normpath(path) - warnings.append( - f"Bash command contained write target '{normalized}'" - f" outside session cwd '{cwd}'" - ) - elif tool_name in write_tool_names: - file_path = inputs.get("file_path", "") - if isinstance(file_path, str) and _is_path_outside_cwd(file_path, cwd): - warnings.append(f"{tool_name} tool targeted '{file_path}' outside session cwd '{cwd}'") - return warnings - - def _build_session_telemetry( *, skill_result: SkillResult, diff --git a/src/autoskillit/execution/headless/_headless_path_tokens.py b/src/autoskillit/execution/headless/_headless_path_tokens.py index b6d1d95643..960143af2d 100644 --- a/src/autoskillit/execution/headless/_headless_path_tokens.py +++ b/src/autoskillit/execution/headless/_headless_path_tokens.py @@ -11,12 +11,14 @@ from __future__ import annotations import os -from typing import NewType +from pathlib import Path +from typing import Any, NewType import regex as re -from autoskillit.core import get_logger, load_yaml, pkg_root +from autoskillit.core import destination_location, get_logger, load_yaml, pkg_root from autoskillit.execution.session._session_content import _normalize_model_output +from autoskillit.hooks import UNRESOLVED_WRITE_TARGET_REMEDIATION, scan_write_targets logger = get_logger(__name__) NormalizedMessages = NewType("NormalizedMessages", list[str]) @@ -185,3 +187,43 @@ def _validate_output_paths(extracted_paths: dict[str, str], cwd: str) -> str | N if _is_path_outside_cwd(path, cwd, allow_relative=False) ] return "; ".join(violations) if violations else None + + +def _tool_write_path_warnings( + tool_name: Any, + inputs: dict[str, Any], + cwd: str, + write_tool_names: frozenset[str], + bash_tool_name: str, +) -> list[str]: + warnings: list[str] = [] + if tool_name == bash_tool_name: + command = inputs.get("command", "") + if isinstance(command, str): + scan = scan_write_targets(command, cwd) + unresolved = scan.unresolved or not scan.parseable + paths = [(path, cwd) for path in scan.targets] + for path in scan.entry_targets: + try: + location = str(destination_location(Path(path))) + physical_cwd = str(Path(cwd).resolve()) if os.path.isabs(cwd) else cwd + paths.append((location, physical_cwd)) + except (OSError, RuntimeError, ValueError): + unresolved = True + if unresolved: + warnings.append( + "Bash command contained a write target that could not be statically resolved. " + + UNRESOLVED_WRITE_TARGET_REMEDIATION + ) + for path, comparison_cwd in paths: + if _is_path_outside_cwd(path, comparison_cwd): + normalized = os.path.normpath(path) + warnings.append( + f"Bash command contained write target '{normalized}'" + f" outside session cwd '{cwd}'" + ) + elif tool_name in write_tool_names: + file_path = inputs.get("file_path", "") + if isinstance(file_path, str) and _is_path_outside_cwd(file_path, cwd): + warnings.append(f"{tool_name} tool targeted '{file_path}' outside session cwd '{cwd}'") + return warnings diff --git a/src/autoskillit/execution/headless/_headless_recovery.py b/src/autoskillit/execution/headless/_headless_recovery.py index 948b47b87b..cadf2c6f8d 100644 --- a/src/autoskillit/execution/headless/_headless_recovery.py +++ b/src/autoskillit/execution/headless/_headless_recovery.py @@ -23,9 +23,9 @@ is_parent_assistant_record, ) from autoskillit.execution.backends._codex_parse import extract_codex_turn_usage -from autoskillit.execution.headless._headless_evidence import _tool_write_path_warnings from autoskillit.execution.headless._headless_path_tokens import ( _RECOVERABLE_PATH_TOKENS, + _tool_write_path_warnings, ) from autoskillit.execution.process import _marker_is_standalone from autoskillit.execution.session import ( From 34104038232b034ce9bf5af990e7d73ed1ade49e Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 16:40:26 -0700 Subject: [PATCH 32/42] docs(review): focus npm guidance on scanner write boundaries --- docs/safety/hooks.md | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/docs/safety/hooks.md b/docs/safety/hooks.md index 0a3c7bf588..ebed93e6db 100644 --- a/docs/safety/hooks.md +++ b/docs/safety/hooks.md @@ -455,12 +455,7 @@ An npm prefix does not describe all npm writes. The independently configured [lifecycle scripts](https://docs.npmjs.com/cli/v11/using-npm/scripts/) can cause additional writes; the scanner models neither cache writes nor script side effects. Installed dependencies' scripts are distinct from hooks in the prefix -project. In [npm 12.2.1's install implementation](https://github.com/npm/cli/blob/v12.2.1/lib/commands/install.js), -the ordinary root install lifecycle sequence requires a local install, no -effective package arguments, and scripts enabled. That sequence does not apply -to `npm install --prefix DIR pkg`; this does not imply that every other project -hook is disabled. These behaviors depend on npm version and configuration, and -an install need not write an external cache. +project. Canonical containment is a point-in-time check: an ancestor or symlink can change between scanning and execution. Separately, `ln` chooses directory versus entry From 01dbb7e49c1680765a5881847d2e9a8c47d5e8e3 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 16:41:28 -0700 Subject: [PATCH 33/42] test(review): scope injected lstat errors to the guard module --- tests/hooks/test_installation_integrity_guard.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/hooks/test_installation_integrity_guard.py b/tests/hooks/test_installation_integrity_guard.py index aec08c2650..8e3370acde 100644 --- a/tests/hooks/test_installation_integrity_guard.py +++ b/tests/hooks/test_installation_integrity_guard.py @@ -9,6 +9,7 @@ import subprocess import sys from pathlib import Path +from types import SimpleNamespace import pytest @@ -309,7 +310,7 @@ def lstat(path, *args, **kwargs): return original_lstat(path, *args, **kwargs) monkeypatch.setattr(guard, "_known_roots", lambda: ()) - monkeypatch.setattr(guard.os, "lstat", lstat) + monkeypatch.setattr(guard, "os", SimpleNamespace(**(vars(os) | {"lstat": lstat}))) assert guard._is_protected_entry_target(str(target)) is ( error not in {errno.ENOENT, errno.ENOTDIR} From 4ddb7027848b3500dcdb9bf6979f3f22fa8ca595 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 16:42:10 -0700 Subject: [PATCH 34/42] test(review): cover install directory and single-destination modes --- tests/hooks/test_write_target_scan.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/hooks/test_write_target_scan.py b/tests/hooks/test_write_target_scan.py index f0b8b19363..a335a09be3 100644 --- a/tests/hooks/test_write_target_scan.py +++ b/tests/hooks/test_write_target_scan.py @@ -347,6 +347,27 @@ def test_install_target_directory_emits_child_content_destinations( assert result.has_write is True +@pytest.mark.parametrize( + ("command", "children"), + [ + ("install -d {dest}/one {dest}/two", ("one", "two")), + ("install -T source {dest}/entry", ("entry",)), + ("install source {dest}", ("source",)), + ], + ids=("create-directories", "no-target-directory", "existing-directory"), +) +def test_install_destination_modes( + tmp_path: Path, command: str, children: tuple[str, ...] +) -> None: + destination = tmp_path / "destination" + destination.mkdir() + result = scan_write_targets(command.format(dest=destination), _WORKSPACE) + assert result.targets == tuple(str(destination / child) for child in children) + assert result.entry_targets == () + assert result.has_write + assert not result.unresolved + + @pytest.mark.parametrize( ("command", "targets", "entry_targets"), [ From 381bffbe49a3cbb73303bc270ecdf15fb97508f7 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 16:42:44 -0700 Subject: [PATCH 35/42] test(review): remove redundant scan dataclass default assertion --- tests/hooks/test_command_classification.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/tests/hooks/test_command_classification.py b/tests/hooks/test_command_classification.py index 4ac1ce4ab1..143886b5fb 100644 --- a/tests/hooks/test_command_classification.py +++ b/tests/hooks/test_command_classification.py @@ -1543,9 +1543,6 @@ def test_chained_write_bytes_on_open_not_double_counted(self): class TestScanWriteTargets: - def test_scan_result_entry_targets_defaults_empty(self) -> None: - assert command_classification.WriteTargetScan((), False, True, False).entry_targets == () - @pytest.mark.parametrize( ("parseable", "has_write"), [(False, True), (True, False)], From 5a12b8c233e1697bc6ab63fec11f7a5500f3f43d Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 16:43:39 -0700 Subject: [PATCH 36/42] test(review): assert the checked-out refs threatened by explicit destinations --- tests/infra/test_git_ops_guard.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/tests/infra/test_git_ops_guard.py b/tests/infra/test_git_ops_guard.py index 4f723721bd..4d301658f3 100644 --- a/tests/infra/test_git_ops_guard.py +++ b/tests/infra/test_git_ops_guard.py @@ -975,7 +975,10 @@ def test_denies_ln_directory_entry_for_checked_out_ref( tmpdir=linked, ) - assert _is_denied(out) + threatened = _checked_out_ref_result(out)["threatened_refs"] + assert isinstance(threatened, list) + expected_ref = "HEAD" if source_name == "HEAD" else f"refs/heads/{source_name}" + assert {row["target_ref"] for row in threatened} == {expected_ref} def test_denies_npm_prefix_targeting_checked_out_ref( self, linked_repo: dict[str, Path | str] @@ -990,7 +993,9 @@ def test_denies_npm_prefix_targeting_checked_out_ref( tmpdir=linked, ) - assert _is_denied(out) + threatened = _checked_out_ref_result(out)["threatened_refs"] + assert isinstance(threatened, list) + assert {row["target_ref"] for row in threatened} == {"refs/heads/develop"} @pytest.mark.parametrize("target_first", [True, False], ids=["target-first", "target-last"]) def test_denies_install_target_directory_checked_out_ref_child( @@ -1013,7 +1018,9 @@ def test_denies_install_target_directory_checked_out_ref_child( out = _run_guard(f"install {operands}", kitchen_open=True, tmpdir=linked) - assert _is_denied(out) + threatened = _checked_out_ref_result(out)["threatened_refs"] + assert isinstance(threatened, list) + assert {row["target_ref"] for row in threatened} == {"refs/heads/develop"} @pytest.mark.parametrize("target_first", [True, False], ids=["target-first", "target-last"]) def test_allows_install_from_protected_source_to_unprotected_directory( From 0a6ae721c8eaaa54440777afe514836e9a28d52e Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 17:00:17 -0700 Subject: [PATCH 37/42] fix(review): complete shared destination helper hook integration --- .../hooks/_runtime/_path_identity.py | 2 +- tests/_test_filter.py | 28 +++++++++++++++++++ tests/core/test_resolve_temp_dir.py | 4 +-- tests/hooks/_interactive_guard_harness.py | 1 + tests/hooks/test_hook_scope_authority.py | 1 + tests/hooks/test_path_identity.py | 1 - 6 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/autoskillit/hooks/_runtime/_path_identity.py b/src/autoskillit/hooks/_runtime/_path_identity.py index 24c9325477..73b62b9169 100644 --- a/src/autoskillit/hooks/_runtime/_path_identity.py +++ b/src/autoskillit/hooks/_runtime/_path_identity.py @@ -14,7 +14,7 @@ from pathlib import Path from typing import TYPE_CHECKING -if TYPE_CHECKING or __package__: +if TYPE_CHECKING: from autoskillit._destination_paths import destination_location else: _PACKAGE_DIR = str(Path(__file__).resolve().parents[2]) diff --git a/tests/_test_filter.py b/tests/_test_filter.py index e14485a094..dbf9f847e1 100644 --- a/tests/_test_filter.py +++ b/tests/_test_filter.py @@ -1129,6 +1129,20 @@ class SourceMapRejection(enum.StrEnum): # --------------------------------------------------------------------------- LAYER_CASCADE_CONSERVATIVE: dict[str, frozenset[str]] = { + "_destination_paths": frozenset( + { + "arch", + "cli", + "contracts", + "core", + "execution", + "hooks", + "infra", + "server", + "skills", + "workspace", + } + ), "quota_constraints": frozenset({"core", "execution", "hooks", "server"}), # L0 — imported by everything "core": frozenset( @@ -1743,6 +1757,20 @@ class SourceMapRejection(enum.StrEnum): } LAYER_CASCADE_AGGRESSIVE: dict[str, frozenset[str]] = { + "_destination_paths": frozenset( + { + "arch", + "cli", + "contracts", + "core", + "execution", + "hooks", + "infra", + "server", + "skills", + "workspace", + } + ), "quota_constraints": frozenset({"core", "execution", "hooks", "server"}), "core": frozenset({"core"}), "config": frozenset({"config"}), diff --git a/tests/core/test_resolve_temp_dir.py b/tests/core/test_resolve_temp_dir.py index 0d252bb94b..67799cf3d5 100644 --- a/tests/core/test_resolve_temp_dir.py +++ b/tests/core/test_resolve_temp_dir.py @@ -31,7 +31,7 @@ def test_resolve_temp_dir_empty_string_raises_value_error() -> None: def test_resolve_temp_dir_no_autoskillit_imports() -> None: - """core.io may import core and the stdlib-only measure authority, not higher layers. + """core.io may import core and its stdlib-only root authorities, not higher layers. Runs in an isolated subprocess so the destructive ``sys.modules`` clear cannot leak into other xdist tests sharing the same worker process. @@ -51,7 +51,7 @@ def test_resolve_temp_dir_no_autoskillit_imports() -> None: for m in sys.modules if m.startswith("autoskillit.") and not m.startswith("autoskillit.core") - and m != "autoskillit._measure_aggregation" + and m not in {"autoskillit._measure_aggregation", "autoskillit._destination_paths"} ] if leaked: print("LEAKED:" + ",".join(sorted(leaked))) diff --git a/tests/hooks/_interactive_guard_harness.py b/tests/hooks/_interactive_guard_harness.py index c53a139e7c..431c99257b 100644 --- a/tests/hooks/_interactive_guard_harness.py +++ b/tests/hooks/_interactive_guard_harness.py @@ -83,6 +83,7 @@ def make_runtime(tmp_path: Path, entries: Mapping[str, Mapping[str, object]]) -> (project / ".autoskillit" / "temp").mkdir(parents=True) plugin = tmp_path / "plugin" shutil.copytree(HOOKS_DIR, plugin / "hooks") + shutil.copy2(HOOKS_DIR.parent / "_destination_paths.py", plugin) manifest_path = tmp_path / ".plugin.autoskillit-projection.json" manifest_path.write_text( json.dumps( diff --git a/tests/hooks/test_hook_scope_authority.py b/tests/hooks/test_hook_scope_authority.py index c1f85ac92e..6173d26647 100644 --- a/tests/hooks/test_hook_scope_authority.py +++ b/tests/hooks/test_hook_scope_authority.py @@ -61,6 +61,7 @@ def _run_copied_guard( else: copied_hooks = tmp_path / "hooks" shutil.copytree(HOOKS_DIR, copied_hooks, ignore=ignore) + shutil.copy2(HOOKS_DIR.parent / "_destination_paths.py", copied_hooks.parent) table_path = copied_hooks / "_runtime" / "_hook_scope_table.py" if table_content is None: table_path.unlink() diff --git a/tests/hooks/test_path_identity.py b/tests/hooks/test_path_identity.py index 8132faa4bf..33c30221b8 100644 --- a/tests/hooks/test_path_identity.py +++ b/tests/hooks/test_path_identity.py @@ -100,7 +100,6 @@ def test_destination_location_handles_root_destination() -> None: @pytest.mark.parametrize("name", ["entry", "final-link", "..", "."]) def test_destination_location_core_and_hook_conformance(tmp_path: Path, name: str) -> None: - assert destination_location is core_destination_location real_parent = tmp_path / "real" real_parent.mkdir() linked_parent = tmp_path / "linked" From 492d844bb4a275e958b0c757b1b062dbca4fecfb Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 17:02:10 -0700 Subject: [PATCH 38/42] fix(review): keep write advisories cohesive within headless size limits --- .../execution/headless/__init__.py | 4 +- .../headless/_headless_adjudication.py | 2 +- .../headless/_headless_path_tokens.py | 46 +-------- .../execution/headless/_headless_recovery.py | 45 --------- .../headless/_headless_write_paths.py | 93 +++++++++++++++++++ .../test_write_target_single_authority.py | 4 +- 6 files changed, 101 insertions(+), 93 deletions(-) create mode 100644 src/autoskillit/execution/headless/_headless_write_paths.py diff --git a/src/autoskillit/execution/headless/__init__.py b/src/autoskillit/execution/headless/__init__.py index 72bdefd9ca..078c1b047b 100644 --- a/src/autoskillit/execution/headless/__init__.py +++ b/src/autoskillit/execution/headless/__init__.py @@ -91,12 +91,14 @@ _parse_single_enum_binding, # noqa: F401 _recover_block_from_assistant_messages, # noqa: F401 _recover_from_separate_marker, # noqa: F401 - _scan_jsonl_write_paths, # noqa: F401 _synthesize_from_write_artifacts, # noqa: F401 ) from autoskillit.execution.headless._headless_result import ( _build_skill_result, # noqa: F401 ) +from autoskillit.execution.headless._headless_write_paths import ( + _scan_jsonl_write_paths, # noqa: F401 +) from autoskillit.execution.headless._managed import ( _headless_plugin_load_mode, _ManagedLineageObserver, diff --git a/src/autoskillit/execution/headless/_headless_adjudication.py b/src/autoskillit/execution/headless/_headless_adjudication.py index 95a6964fbc..4972a8d31c 100644 --- a/src/autoskillit/execution/headless/_headless_adjudication.py +++ b/src/autoskillit/execution/headless/_headless_adjudication.py @@ -50,7 +50,7 @@ _select_output_path_tokens, _validate_output_paths, ) -from autoskillit.execution.headless._headless_recovery import _scan_jsonl_write_paths +from autoskillit.execution.headless._headless_write_paths import _scan_jsonl_write_paths from autoskillit.execution.session._session_content import _check_expected_patterns from autoskillit.execution.session._session_model import ( ClaudeSessionResult, diff --git a/src/autoskillit/execution/headless/_headless_path_tokens.py b/src/autoskillit/execution/headless/_headless_path_tokens.py index 960143af2d..b6d1d95643 100644 --- a/src/autoskillit/execution/headless/_headless_path_tokens.py +++ b/src/autoskillit/execution/headless/_headless_path_tokens.py @@ -11,14 +11,12 @@ from __future__ import annotations import os -from pathlib import Path -from typing import Any, NewType +from typing import NewType import regex as re -from autoskillit.core import destination_location, get_logger, load_yaml, pkg_root +from autoskillit.core import get_logger, load_yaml, pkg_root from autoskillit.execution.session._session_content import _normalize_model_output -from autoskillit.hooks import UNRESOLVED_WRITE_TARGET_REMEDIATION, scan_write_targets logger = get_logger(__name__) NormalizedMessages = NewType("NormalizedMessages", list[str]) @@ -187,43 +185,3 @@ def _validate_output_paths(extracted_paths: dict[str, str], cwd: str) -> str | N if _is_path_outside_cwd(path, cwd, allow_relative=False) ] return "; ".join(violations) if violations else None - - -def _tool_write_path_warnings( - tool_name: Any, - inputs: dict[str, Any], - cwd: str, - write_tool_names: frozenset[str], - bash_tool_name: str, -) -> list[str]: - warnings: list[str] = [] - if tool_name == bash_tool_name: - command = inputs.get("command", "") - if isinstance(command, str): - scan = scan_write_targets(command, cwd) - unresolved = scan.unresolved or not scan.parseable - paths = [(path, cwd) for path in scan.targets] - for path in scan.entry_targets: - try: - location = str(destination_location(Path(path))) - physical_cwd = str(Path(cwd).resolve()) if os.path.isabs(cwd) else cwd - paths.append((location, physical_cwd)) - except (OSError, RuntimeError, ValueError): - unresolved = True - if unresolved: - warnings.append( - "Bash command contained a write target that could not be statically resolved. " - + UNRESOLVED_WRITE_TARGET_REMEDIATION - ) - for path, comparison_cwd in paths: - if _is_path_outside_cwd(path, comparison_cwd): - normalized = os.path.normpath(path) - warnings.append( - f"Bash command contained write target '{normalized}'" - f" outside session cwd '{cwd}'" - ) - elif tool_name in write_tool_names: - file_path = inputs.get("file_path", "") - if isinstance(file_path, str) and _is_path_outside_cwd(file_path, cwd): - warnings.append(f"{tool_name} tool targeted '{file_path}' outside session cwd '{cwd}'") - return warnings diff --git a/src/autoskillit/execution/headless/_headless_recovery.py b/src/autoskillit/execution/headless/_headless_recovery.py index cadf2c6f8d..d851ce841d 100644 --- a/src/autoskillit/execution/headless/_headless_recovery.py +++ b/src/autoskillit/execution/headless/_headless_recovery.py @@ -3,8 +3,6 @@ from __future__ import annotations import dataclasses -import json -import os from collections.abc import Sequence from pathlib import Path from typing import TYPE_CHECKING, Any, NamedTuple @@ -20,12 +18,10 @@ TokenMeasure, TurnTokenEntry, get_logger, - is_parent_assistant_record, ) from autoskillit.execution.backends._codex_parse import extract_codex_turn_usage from autoskillit.execution.headless._headless_path_tokens import ( _RECOVERABLE_PATH_TOKENS, - _tool_write_path_warnings, ) from autoskillit.execution.process import _marker_is_standalone from autoskillit.execution.session import ( @@ -86,47 +82,6 @@ def _is_path_capture_pattern(pattern: str) -> str | None: return token_name -def _scan_jsonl_write_paths( - stdout: str, - cwd: str, - *, - write_tool_names: frozenset[str] = frozenset({"Write", "Edit"}), - bash_tool_name: str = "Bash", -) -> list[str]: - """Scan raw JSONL stdout for Write/Edit/Bash tool calls outside cwd.""" - if not stdout.strip() or not cwd or not os.path.isabs(cwd): - return [] - - warnings: list[str] = [] - for raw_line in stdout.strip().splitlines(): - line = raw_line.strip() - if not line: - continue - try: - obj = json.loads(line) - except json.JSONDecodeError: - continue - if not isinstance(obj, dict) or not is_parent_assistant_record(obj): - continue - msg = obj.get("message") - if not isinstance(msg, dict): - continue - content = msg.get("content", []) - if not isinstance(content, list): - continue - for block in content: - if not isinstance(block, dict) or block.get("type") != "tool_use": - continue - tool_name = block.get("name", "") - inputs = block.get("input") or {} - if not isinstance(inputs, dict): - continue - warnings.extend( - _tool_write_path_warnings(tool_name, inputs, cwd, write_tool_names, bash_tool_name) - ) - return warnings - - def _recover_from_separate_marker( session: ClaudeSessionResult, completion_marker: str, diff --git a/src/autoskillit/execution/headless/_headless_write_paths.py b/src/autoskillit/execution/headless/_headless_write_paths.py new file mode 100644 index 0000000000..beb836a785 --- /dev/null +++ b/src/autoskillit/execution/headless/_headless_write_paths.py @@ -0,0 +1,93 @@ +"""Write-path advisories from parent-assistant tool calls.""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from typing import Any + +from autoskillit.core import destination_location, is_parent_assistant_record +from autoskillit.execution.headless._headless_path_tokens import _is_path_outside_cwd +from autoskillit.hooks import UNRESOLVED_WRITE_TARGET_REMEDIATION, scan_write_targets + + +def _tool_write_path_warnings( + tool_name: Any, + inputs: dict[str, Any], + cwd: str, + write_tool_names: frozenset[str], + bash_tool_name: str, +) -> list[str]: + warnings: list[str] = [] + if tool_name == bash_tool_name: + command = inputs.get("command", "") + if isinstance(command, str): + scan = scan_write_targets(command, cwd) + unresolved = scan.unresolved or not scan.parseable + paths = [(path, cwd) for path in scan.targets] + for path in scan.entry_targets: + try: + location = str(destination_location(Path(path))) + physical_cwd = str(Path(cwd).resolve()) if os.path.isabs(cwd) else cwd + paths.append((location, physical_cwd)) + except (OSError, RuntimeError, ValueError): + unresolved = True + if unresolved: + warnings.append( + "Bash command contained a write target that could not be statically resolved. " + + UNRESOLVED_WRITE_TARGET_REMEDIATION + ) + for path, comparison_cwd in paths: + if _is_path_outside_cwd(path, comparison_cwd): + normalized = os.path.normpath(path) + warnings.append( + f"Bash command contained write target '{normalized}'" + f" outside session cwd '{cwd}'" + ) + elif tool_name in write_tool_names: + file_path = inputs.get("file_path", "") + if isinstance(file_path, str) and _is_path_outside_cwd(file_path, cwd): + warnings.append(f"{tool_name} tool targeted '{file_path}' outside session cwd '{cwd}'") + return warnings + + +def _scan_jsonl_write_paths( + stdout: str, + cwd: str, + *, + write_tool_names: frozenset[str] = frozenset({"Write", "Edit"}), + bash_tool_name: str = "Bash", +) -> list[str]: + """Scan raw JSONL stdout for Write/Edit/Bash tool calls outside cwd.""" + if not stdout.strip() or not cwd or not os.path.isabs(cwd): + return [] + + warnings: list[str] = [] + for raw_line in stdout.strip().splitlines(): + line = raw_line.strip() + if not line: + continue + try: + obj = json.loads(line) + except json.JSONDecodeError: + continue + if not isinstance(obj, dict) or not is_parent_assistant_record(obj): + continue + msg = obj.get("message") + if not isinstance(msg, dict): + continue + content = msg.get("content", []) + if not isinstance(content, list): + continue + for block in content: + if not isinstance(block, dict) or block.get("type") != "tool_use": + continue + tool_name = block.get("name", "") + inputs = block.get("input") or {} + if not isinstance(inputs, dict): + continue + warnings.extend( + _tool_write_path_warnings(tool_name, inputs, cwd, write_tool_names, bash_tool_name) + ) + return warnings diff --git a/tests/arch/test_write_target_single_authority.py b/tests/arch/test_write_target_single_authority.py index 3c3dd2ef91..1d267b29fb 100644 --- a/tests/arch/test_write_target_single_authority.py +++ b/tests/arch/test_write_target_single_authority.py @@ -17,12 +17,12 @@ def test_write_target_consumers_share_hooks_scanner() -> None: import autoskillit.core as core import autoskillit.core.git as core_git - import autoskillit.execution.headless._headless_evidence as evidence + import autoskillit.execution.headless._headless_write_paths as write_paths import autoskillit.hooks as hooks import autoskillit.server.lifecycle._guards as guards assert guards.scan_write_targets is hooks.scan_write_targets - assert evidence.scan_write_targets is hooks.scan_write_targets + assert write_paths.scan_write_targets is hooks.scan_write_targets assert not hasattr(core, "extract_bash_write_targets") assert not hasattr(core_git, "extract_bash_write_targets") From 42efe4be4d0937cd82a95faa4a16598a225819cb Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 17:19:36 -0700 Subject: [PATCH 39/42] fix(review): preserve constrained headless module boundaries --- .../execution/headless/__init__.py | 4 +- .../headless/_headless_adjudication.py | 2 +- .../execution/headless/_headless_evidence.py | 45 +++++++++ .../execution/headless/_headless_recovery.py | 45 +++++++++ .../headless/_headless_write_paths.py | 93 ------------------- .../test_write_target_single_authority.py | 4 +- 6 files changed, 94 insertions(+), 99 deletions(-) delete mode 100644 src/autoskillit/execution/headless/_headless_write_paths.py diff --git a/src/autoskillit/execution/headless/__init__.py b/src/autoskillit/execution/headless/__init__.py index 078c1b047b..72bdefd9ca 100644 --- a/src/autoskillit/execution/headless/__init__.py +++ b/src/autoskillit/execution/headless/__init__.py @@ -91,14 +91,12 @@ _parse_single_enum_binding, # noqa: F401 _recover_block_from_assistant_messages, # noqa: F401 _recover_from_separate_marker, # noqa: F401 + _scan_jsonl_write_paths, # noqa: F401 _synthesize_from_write_artifacts, # noqa: F401 ) from autoskillit.execution.headless._headless_result import ( _build_skill_result, # noqa: F401 ) -from autoskillit.execution.headless._headless_write_paths import ( - _scan_jsonl_write_paths, # noqa: F401 -) from autoskillit.execution.headless._managed import ( _headless_plugin_load_mode, _ManagedLineageObserver, diff --git a/src/autoskillit/execution/headless/_headless_adjudication.py b/src/autoskillit/execution/headless/_headless_adjudication.py index 4972a8d31c..95a6964fbc 100644 --- a/src/autoskillit/execution/headless/_headless_adjudication.py +++ b/src/autoskillit/execution/headless/_headless_adjudication.py @@ -50,7 +50,7 @@ _select_output_path_tokens, _validate_output_paths, ) -from autoskillit.execution.headless._headless_write_paths import _scan_jsonl_write_paths +from autoskillit.execution.headless._headless_recovery import _scan_jsonl_write_paths from autoskillit.execution.session._session_content import _check_expected_patterns from autoskillit.execution.session._session_model import ( ClaudeSessionResult, diff --git a/src/autoskillit/execution/headless/_headless_evidence.py b/src/autoskillit/execution/headless/_headless_evidence.py index 96ea7afffb..b100765478 100644 --- a/src/autoskillit/execution/headless/_headless_evidence.py +++ b/src/autoskillit/execution/headless/_headless_evidence.py @@ -4,7 +4,9 @@ import dataclasses import json +import os from datetime import UTC, datetime +from pathlib import Path from typing import TYPE_CHECKING, Any from autoskillit.core import ( @@ -18,11 +20,14 @@ SessionTelemetry, SkillResult, SubagentModelOutcomeDict, + destination_location, get_logger, is_parent_assistant_record, ) +from autoskillit.execution.headless._headless_path_tokens import _is_path_outside_cwd from autoskillit.execution.session._exit_classification import _CODEX_ERROR_CODE_API_STATUS from autoskillit.execution.session._session_model import ClaudeSessionResult +from autoskillit.hooks import UNRESOLVED_WRITE_TARGET_REMEDIATION, scan_write_targets if TYPE_CHECKING: from autoskillit.core import AuditLog, CodingAgentBackend, GitHubApiLog @@ -176,6 +181,46 @@ def _stdout_mentions_write_tools(stdout: str) -> bool: return False +def _tool_write_path_warnings( + tool_name: Any, + inputs: dict[str, Any], + cwd: str, + write_tool_names: frozenset[str], + bash_tool_name: str, +) -> list[str]: + warnings: list[str] = [] + if tool_name == bash_tool_name: + command = inputs.get("command", "") + if isinstance(command, str): + scan = scan_write_targets(command, cwd) + unresolved = scan.unresolved or not scan.parseable + paths = [(path, cwd) for path in scan.targets] + for path in scan.entry_targets: + try: + location = str(destination_location(Path(path))) + physical_cwd = str(Path(cwd).resolve()) if os.path.isabs(cwd) else cwd + paths.append((location, physical_cwd)) + except (OSError, RuntimeError, ValueError): + unresolved = True + if unresolved: + warnings.append( + "Bash command contained a write target that could not be statically resolved. " + + UNRESOLVED_WRITE_TARGET_REMEDIATION + ) + for path, comparison_cwd in paths: + if _is_path_outside_cwd(path, comparison_cwd): + normalized = os.path.normpath(path) + warnings.append( + f"Bash command contained write target '{normalized}'" + f" outside session cwd '{cwd}'" + ) + elif tool_name in write_tool_names: + file_path = inputs.get("file_path", "") + if isinstance(file_path, str) and _is_path_outside_cwd(file_path, cwd): + warnings.append(f"{tool_name} tool targeted '{file_path}' outside session cwd '{cwd}'") + return warnings + + def _build_session_telemetry( *, skill_result: SkillResult, diff --git a/src/autoskillit/execution/headless/_headless_recovery.py b/src/autoskillit/execution/headless/_headless_recovery.py index d851ce841d..948b47b87b 100644 --- a/src/autoskillit/execution/headless/_headless_recovery.py +++ b/src/autoskillit/execution/headless/_headless_recovery.py @@ -3,6 +3,8 @@ from __future__ import annotations import dataclasses +import json +import os from collections.abc import Sequence from pathlib import Path from typing import TYPE_CHECKING, Any, NamedTuple @@ -18,8 +20,10 @@ TokenMeasure, TurnTokenEntry, get_logger, + is_parent_assistant_record, ) from autoskillit.execution.backends._codex_parse import extract_codex_turn_usage +from autoskillit.execution.headless._headless_evidence import _tool_write_path_warnings from autoskillit.execution.headless._headless_path_tokens import ( _RECOVERABLE_PATH_TOKENS, ) @@ -82,6 +86,47 @@ def _is_path_capture_pattern(pattern: str) -> str | None: return token_name +def _scan_jsonl_write_paths( + stdout: str, + cwd: str, + *, + write_tool_names: frozenset[str] = frozenset({"Write", "Edit"}), + bash_tool_name: str = "Bash", +) -> list[str]: + """Scan raw JSONL stdout for Write/Edit/Bash tool calls outside cwd.""" + if not stdout.strip() or not cwd or not os.path.isabs(cwd): + return [] + + warnings: list[str] = [] + for raw_line in stdout.strip().splitlines(): + line = raw_line.strip() + if not line: + continue + try: + obj = json.loads(line) + except json.JSONDecodeError: + continue + if not isinstance(obj, dict) or not is_parent_assistant_record(obj): + continue + msg = obj.get("message") + if not isinstance(msg, dict): + continue + content = msg.get("content", []) + if not isinstance(content, list): + continue + for block in content: + if not isinstance(block, dict) or block.get("type") != "tool_use": + continue + tool_name = block.get("name", "") + inputs = block.get("input") or {} + if not isinstance(inputs, dict): + continue + warnings.extend( + _tool_write_path_warnings(tool_name, inputs, cwd, write_tool_names, bash_tool_name) + ) + return warnings + + def _recover_from_separate_marker( session: ClaudeSessionResult, completion_marker: str, diff --git a/src/autoskillit/execution/headless/_headless_write_paths.py b/src/autoskillit/execution/headless/_headless_write_paths.py deleted file mode 100644 index beb836a785..0000000000 --- a/src/autoskillit/execution/headless/_headless_write_paths.py +++ /dev/null @@ -1,93 +0,0 @@ -"""Write-path advisories from parent-assistant tool calls.""" - -from __future__ import annotations - -import json -import os -from pathlib import Path -from typing import Any - -from autoskillit.core import destination_location, is_parent_assistant_record -from autoskillit.execution.headless._headless_path_tokens import _is_path_outside_cwd -from autoskillit.hooks import UNRESOLVED_WRITE_TARGET_REMEDIATION, scan_write_targets - - -def _tool_write_path_warnings( - tool_name: Any, - inputs: dict[str, Any], - cwd: str, - write_tool_names: frozenset[str], - bash_tool_name: str, -) -> list[str]: - warnings: list[str] = [] - if tool_name == bash_tool_name: - command = inputs.get("command", "") - if isinstance(command, str): - scan = scan_write_targets(command, cwd) - unresolved = scan.unresolved or not scan.parseable - paths = [(path, cwd) for path in scan.targets] - for path in scan.entry_targets: - try: - location = str(destination_location(Path(path))) - physical_cwd = str(Path(cwd).resolve()) if os.path.isabs(cwd) else cwd - paths.append((location, physical_cwd)) - except (OSError, RuntimeError, ValueError): - unresolved = True - if unresolved: - warnings.append( - "Bash command contained a write target that could not be statically resolved. " - + UNRESOLVED_WRITE_TARGET_REMEDIATION - ) - for path, comparison_cwd in paths: - if _is_path_outside_cwd(path, comparison_cwd): - normalized = os.path.normpath(path) - warnings.append( - f"Bash command contained write target '{normalized}'" - f" outside session cwd '{cwd}'" - ) - elif tool_name in write_tool_names: - file_path = inputs.get("file_path", "") - if isinstance(file_path, str) and _is_path_outside_cwd(file_path, cwd): - warnings.append(f"{tool_name} tool targeted '{file_path}' outside session cwd '{cwd}'") - return warnings - - -def _scan_jsonl_write_paths( - stdout: str, - cwd: str, - *, - write_tool_names: frozenset[str] = frozenset({"Write", "Edit"}), - bash_tool_name: str = "Bash", -) -> list[str]: - """Scan raw JSONL stdout for Write/Edit/Bash tool calls outside cwd.""" - if not stdout.strip() or not cwd or not os.path.isabs(cwd): - return [] - - warnings: list[str] = [] - for raw_line in stdout.strip().splitlines(): - line = raw_line.strip() - if not line: - continue - try: - obj = json.loads(line) - except json.JSONDecodeError: - continue - if not isinstance(obj, dict) or not is_parent_assistant_record(obj): - continue - msg = obj.get("message") - if not isinstance(msg, dict): - continue - content = msg.get("content", []) - if not isinstance(content, list): - continue - for block in content: - if not isinstance(block, dict) or block.get("type") != "tool_use": - continue - tool_name = block.get("name", "") - inputs = block.get("input") or {} - if not isinstance(inputs, dict): - continue - warnings.extend( - _tool_write_path_warnings(tool_name, inputs, cwd, write_tool_names, bash_tool_name) - ) - return warnings diff --git a/tests/arch/test_write_target_single_authority.py b/tests/arch/test_write_target_single_authority.py index 1d267b29fb..3c3dd2ef91 100644 --- a/tests/arch/test_write_target_single_authority.py +++ b/tests/arch/test_write_target_single_authority.py @@ -17,12 +17,12 @@ def test_write_target_consumers_share_hooks_scanner() -> None: import autoskillit.core as core import autoskillit.core.git as core_git - import autoskillit.execution.headless._headless_write_paths as write_paths + import autoskillit.execution.headless._headless_evidence as evidence import autoskillit.hooks as hooks import autoskillit.server.lifecycle._guards as guards assert guards.scan_write_targets is hooks.scan_write_targets - assert write_paths.scan_write_targets is hooks.scan_write_targets + assert evidence.scan_write_targets is hooks.scan_write_targets assert not hasattr(core, "extract_bash_write_targets") assert not hasattr(core_git, "extract_bash_write_targets") From 10c469ed12cac6fe233240c86e2713b24311f4d2 Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 18:04:27 -0700 Subject: [PATCH 40/42] fix(review): normalize path-qualified legacy write verbs --- src/autoskillit/hooks/_runtime/_write_target_scan.py | 4 ++-- tests/hooks/test_write_target_scan.py | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/autoskillit/hooks/_runtime/_write_target_scan.py b/src/autoskillit/hooks/_runtime/_write_target_scan.py index 23d17f3627..b04acf5435 100644 --- a/src/autoskillit/hooks/_runtime/_write_target_scan.py +++ b/src/autoskillit/hooks/_runtime/_write_target_scan.py @@ -620,9 +620,9 @@ def _scan_executable( return WriteTargetScan(tuple(targets), unresolved, True, has_write), invoked if verb_name in {"ln", "install"}: return _scan_destination_command(verb_name, argv, verb_cwd, verb_tokens), invoked - if verb in WRITE_VERBS: + if verb_name in WRITE_VERBS: targets, unresolved = _classification.extract_write_verb_targets( - verb, argv, verb_cwd, argv_tokens=verb_tokens + verb_name, argv, verb_cwd, argv_tokens=verb_tokens ) return WriteTargetScan(tuple(targets), unresolved, True, True), invoked if verb == "git" or verb.endswith("/git"): diff --git a/tests/hooks/test_write_target_scan.py b/tests/hooks/test_write_target_scan.py index a335a09be3..48c30fecff 100644 --- a/tests/hooks/test_write_target_scan.py +++ b/tests/hooks/test_write_target_scan.py @@ -18,8 +18,10 @@ ("/autoskillit:test-skill-flat", _WORKSPACE, (), False), ("gh api /repos/owner/repo", _WORKSPACE, (), False), ("cp source.txt /path/dest.txt", _WORKSPACE, ("/path/dest.txt",), False), + ("/bin/cp /outside/source /workspace/dest", _WORKSPACE, ("/workspace/dest",), False), ("install -m 644 a /workspace/dest", _WORKSPACE, ("/workspace/dest",), False), ("sed -i 's/a/b/' /path/file.txt", _WORKSPACE, ("/path/file.txt",), False), + ("/usr/bin/sed -i 's/a/b/' /path/file.txt", _WORKSPACE, ("/path/file.txt",), False), ("mv /old/file /new/file", _WORKSPACE, ("/new/file",), False), ("cat /a | grep foo > /b", _WORKSPACE, ("/b",), False), ("cmd 2>/dev/null", _WORKSPACE, (), False), From 953189930ccdbe2c9fbc74201e6749a279d298ad Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 18:07:19 -0700 Subject: [PATCH 41/42] fix(review): deny unresolved npm writes without an explicit prefix --- docs/safety/hooks.md | 7 +++--- .../hooks/_runtime/_write_target_scan.py | 12 +++++++++- tests/hooks/test_write_target_scan.py | 22 +++++++++++++++++-- 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/docs/safety/hooks.md b/docs/safety/hooks.md index ebed93e6db..6a5d05603e 100644 --- a/docs/safety/hooks.md +++ b/docs/safety/hooks.md @@ -430,9 +430,10 @@ with guidance to put a literal path in the command. The shared scanner supplies Bash destinations to the write-prefix, installation, Git-ref, and `run_cmd` guards. Supported explicit forms include `npm install --prefix DIR pkg`, `npm install --prefix=DIR pkg`, and -`npm --prefix DIR install pkg`. The prefix is a content destination. Literal read -commands retain their existing policy; an unresolved supported destination is -distinct from a command with no detected write. +`npm --prefix DIR install pkg`. The prefix is a content destination. Without +`--prefix`, npm commands are unresolved writes except for recognized usage, +help/version, metadata, and `config get`/`config list` queries. An unresolved +destination is distinct from a command with no detected write. For `ln TARGET LINK`, including separate or combined `-s`/`-f`, the destination is the link entry, not the source. `-t DIR`, `-tDIR`, and detached/equals diff --git a/src/autoskillit/hooks/_runtime/_write_target_scan.py b/src/autoskillit/hooks/_runtime/_write_target_scan.py index b04acf5435..01f21f6985 100644 --- a/src/autoskillit/hooks/_runtime/_write_target_scan.py +++ b/src/autoskillit/hooks/_runtime/_write_target_scan.py @@ -311,6 +311,15 @@ def _ln_entry_targets( return [destination], False +def _npm_read_only_command(argv: list[str]) -> bool: + return ( + len(argv) == 1 + or argv[1:] in (["--help"], ["--version"], ["-h"], ["-v"]) + or argv[1] in {"help", "info", "list", "ls", "prefix", "root", "show", "view"} + or argv[1:3] in (["config", "get"], ["config", "ls"], ["config", "list"]) + ) + + def _npm_install_targets( argv: list[str], cwd: str, @@ -344,7 +353,8 @@ def _npm_install_targets( uncertain_command = True index += 1 if prefix is None and not missing_prefix: - return [], False, False + unresolved = not _npm_read_only_command(argv) + return [], unresolved, unresolved if command_index is None or uncertain_command or missing_prefix or prefix is None: return [], True, True target = _classification.resolve_write_target(prefix[0], cwd, shell_source=prefix[1]) diff --git a/tests/hooks/test_write_target_scan.py b/tests/hooks/test_write_target_scan.py index 48c30fecff..4113da5204 100644 --- a/tests/hooks/test_write_target_scan.py +++ b/tests/hooks/test_write_target_scan.py @@ -157,12 +157,21 @@ def test_scan_write_target_expectations( ("npm install --prefix='$NPM_UNKNOWN' pkg", ("/workspace/$NPM_UNKNOWN",), False, True), ('npm install --prefix="$NPM_UNKNOWN" pkg', (), True, True), ("npm install --prefix", (), True, True), - ("npm install -- --prefix /opt/app", (), False, False), + ("npm install -- --prefix /opt/app", (), True, True), ("npm ci --prefix /opt/app", ("/opt/app",), False, True), ("npm --prefix /opt/app i pkg", ("/opt/app",), False, True), ("npm add pkg --prefix=/opt/app", ("/opt/app",), False, True), ("npm --registry https://example install --prefix /opt/app pkg", (), True, True), ("npm --prefix /opt/app unsupported", (), True, True), + ("npm install pkg", (), True, True), + ("npm run build", (), True, True), + ("npm --registry https://example run build", (), True, True), + ("npm", (), False, False), + ("npm --version", (), False, False), + ("npm help install", (), False, False), + ("npm ls", (), False, False), + ("npm config get prefix", (), False, False), + ("npm config set prefix /outside", (), True, True), ], ids=( "detached-after-install", @@ -179,9 +188,18 @@ def test_scan_write_target_expectations( "add-alias-prefix", "uncertain-global-option-value", "unsupported-prefixed-command", + "unprefixed-install", + "unprefixed-script", + "unmodelled-leading-options", + "usage", + "version", + "help-for-write-command", + "package-list", + "config-read", + "config-write", ), ) -def test_npm_install_explicit_prefix( +def test_npm_write_target_policy( command: str, targets: tuple[str, ...], unresolved: bool, From 22f2c73c8e847ea24723110216eaf16de31912ac Mon Sep 17 00:00:00 2001 From: Trecek Date: Mon, 26 Oct 2026 18:24:05 -0700 Subject: [PATCH 42/42] test(review): verify npm read-only and unresolved script policy --- tests/infra/test_git_ops_guard.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/infra/test_git_ops_guard.py b/tests/infra/test_git_ops_guard.py index 4d301658f3..3e16357a83 100644 --- a/tests/infra/test_git_ops_guard.py +++ b/tests/infra/test_git_ops_guard.py @@ -351,10 +351,13 @@ def test_allows_when_kitchen_closed(self, tmp_path): out = _run_guard("git commit --amend", kitchen_open=False, tmpdir=tmp_path) assert out.strip() == "" - def test_allows_unrelated_command(self, tmp_path): - out = _run_guard("npm run build", kitchen_open=True, tmpdir=tmp_path) + def test_npm_read_only_and_script_policy(self, tmp_path): + out = _run_guard("npm --version", kitchen_open=True, tmpdir=tmp_path) assert out.strip() == "" + out = _run_guard("npm run build", kitchen_open=True, tmpdir=tmp_path) + assert _checked_out_ref_result(out)["attempted_value"] == "" + # --------------------------------------------------------------------------- # Bash tool format