Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
2e1fac6
fix: recognize explicit Bash destinations and preserve link entries
Trecek Oct 26, 2026
11ef3a3
test: separate inert stdin from unresolved output writes
Trecek Oct 26, 2026
ff01167
test: cover incident commands and sibling destination paths
Trecek Oct 26, 2026
4a9a57b
fix(review): retain explicit npm prefixes across subcommand parsing
Trecek Oct 26, 2026
4e2f5b2
fix(review): detect path-qualified destination commands
Trecek Oct 26, 2026
61cb2b8
fix(review): recognize supported GNU link options
Trecek Oct 26, 2026
486a1ee
refactor(review): name parsed destination option fields
Trecek Oct 26, 2026
e75abf4
refactor(review): reuse named write scans in executable dispatch
Trecek Oct 26, 2026
e45cc46
fix(review): normalize terminal parent destinations in both runtimes
Trecek Oct 26, 2026
05a5769
refactor(review): share physical entry containment across guards
Trecek Oct 26, 2026
decfc5d
refactor(review): share write boundary denial text
Trecek Oct 26, 2026
259e91f
refactor(review): reuse the git preflight write scan
Trecek Oct 26, 2026
ae5512e
fix(review): deny git mutations with unresolved entry parents
Trecek Oct 26, 2026
bcab145
fix(review): fail closed on uncertain installation entry stats
Trecek Oct 26, 2026
4e008b6
fix(review): resolve link parents in headless write advisories
Trecek Oct 26, 2026
d6121ef
test(review): assert scan behavior without field-order coupling
Trecek Oct 26, 2026
51abda3
test(review): assert write scope denial reasons
Trecek Oct 26, 2026
f998efa
test(review): rely on real entry boundary coverage
Trecek Oct 26, 2026
c1118d3
test(review): restore known-cwd herestring redirect coverage
Trecek Oct 26, 2026
0f8d423
fix(review): keep write advisory evidence within module budgets
Trecek Oct 26, 2026
88859f3
test(review): track the actual headless scanner consumer
Trecek Oct 26, 2026
8b9702c
fix(review): share write destination identity across hooks and core
Trecek Oct 26, 2026
d0d1e1a
refactor(review): share explicit target directory resolution
Trecek Oct 26, 2026
61aa8e2
fix(review): recognize coreutils informational and backup options
Trecek Oct 26, 2026
3a388da
refactor(review): make parsed destination operands immutable
Trecek Oct 26, 2026
e781cd1
fix(review): identify both target fields in scan invariant errors
Trecek Oct 26, 2026
e553f9f
fix(review): retain install mutation detection for piped shell bodies
Trecek Oct 26, 2026
a6a58d1
fix(review): distinguish unresolved link entries from protected installs
Trecek Oct 26, 2026
99baaf3
fix(review): explain entry path resolution failures in write guard
Trecek Oct 26, 2026
0133e37
style(review): place destination helper with lowercase hook exports
Trecek Oct 26, 2026
344e075
refactor(review): keep write path warnings with headless path helpers
Trecek Oct 26, 2026
3410403
docs(review): focus npm guidance on scanner write boundaries
Trecek Oct 26, 2026
01dbb7e
test(review): scope injected lstat errors to the guard module
Trecek Oct 26, 2026
4ddb702
test(review): cover install directory and single-destination modes
Trecek Oct 26, 2026
381bffb
test(review): remove redundant scan dataclass default assertion
Trecek Oct 26, 2026
5a12b8c
test(review): assert the checked-out refs threatened by explicit dest…
Trecek Oct 26, 2026
0a6ae72
fix(review): complete shared destination helper hook integration
Trecek Oct 27, 2026
492d844
fix(review): keep write advisories cohesive within headless size limits
Trecek Oct 27, 2026
42efe4b
fix(review): preserve constrained headless module boundaries
Trecek Oct 27, 2026
10c469e
fix(review): normalize path-qualified legacy write verbs
Trecek Oct 27, 2026
9531899
fix(review): deny unresolved npm writes without an explicit prefix
Trecek Oct 27, 2026
22f2c73
test(review): verify npm read-only and unresolved script policy
Trecek Oct 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions docs/safety/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,47 @@ 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. 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
`--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.

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
Expand Down
14 changes: 14 additions & 0 deletions src/autoskillit/_destination_paths.py
Original file line number Diff line number Diff line change
@@ -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
21 changes: 2 additions & 19 deletions src/autoskillit/core/io/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
return destination.resolve()
return destination.parent.resolve() / destination.name


def resolve_project_dir() -> Path:
"""Resolve the project root: git toplevel, falling back to cwd.

Expand Down
45 changes: 45 additions & 0 deletions src/autoskillit/execution/headless/_headless_evidence.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand Down
34 changes: 1 addition & 33 deletions src/autoskillit/execution/headless/_headless_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
_is_path_outside_cwd,
)
from autoskillit.execution.process import _marker_is_standalone
from autoskillit.execution.session import (
Expand All @@ -40,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
Expand Down Expand Up @@ -87,37 +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)
if scan.unresolved or not scan.parseable:
warnings.append(
"Bash command contained a write target that could not be statically resolved. "
+ UNRESOLVED_WRITE_TARGET_REMEDIATION
)
for path in scan.targets:
if _is_path_outside_cwd(path, 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,
Expand Down
2 changes: 2 additions & 0 deletions src/autoskillit/hooks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -138,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",
Expand Down
23 changes: 15 additions & 8 deletions src/autoskillit/hooks/_runtime/_command_classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand All @@ -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
Expand Down
15 changes: 15 additions & 0 deletions src/autoskillit/hooks/_runtime/_path_identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,17 @@
from __future__ import annotations

import os
import sys
from pathlib import Path
from typing import TYPE_CHECKING

if TYPE_CHECKING:
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):
Expand All @@ -37,6 +47,11 @@ def hooks_relative_key(script_identity: str | os.PathLike[str], hooks_dir: Path)
) from exc


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:
Expand Down
Loading
Loading