Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
513c92d
Classify Git ref outcomes through option tables, not option tokens
Trecek Nov 5, 2026
46ce6af
Attribute Git commands to a proven working directory and repository
Trecek Nov 5, 2026
5bc50b7
Deny cook sessions from moving HEAD of the primary checkout
Trecek Nov 5, 2026
a5dd940
Match headless destructive Git operations by outcome
Trecek Nov 5, 2026
6434f54
Keep revision spellings out of the whole-tree checkout pathspecs
Trecek Nov 5, 2026
05531c9
Resolve command position through per-wrapper grammar
Trecek Nov 5, 2026
b84b501
Fail when Git-classification code tests raw option tokens
Trecek Nov 5, 2026
5d42e31
Make _WrapperSpec a frozen dataclass to satisfy the *Spec naming rule
Trecek Nov 6, 2026
952d794
Keep session-cwd anomalies with a workdir; derive unwrapped blockers …
Trecek Nov 6, 2026
e02983b
Bring Git-spawning guard tests under the hygiene rules; pin whole-tre…
Trecek Nov 6, 2026
4a0f460
fix(review): drop the single-caller _python_c_program wrapper
Trecek Nov 6, 2026
d01b954
fix(review): document the =-joined wrapper option width exception
Trecek Nov 6, 2026
6471164
fix(review): remove dead has_unresolved initialiser in interpreter sp…
Trecek Nov 6, 2026
2f72380
fix(review): derive the walker's logical connector set from the token…
Trecek Nov 6, 2026
e6796ca
fix(review): reuse _PYTHON_NAME_RE in the shell segment walker
Trecek Nov 6, 2026
90afa2e
fix(review): remove unreachable out-of-range branch in _apply_shell_b…
Trecek Nov 6, 2026
a7ed03f
fix(review): drop the unread WalkedSegment.record field
Trecek Nov 6, 2026
a77707b
fix(review): unify the command-start walk on _verb_start_index
Trecek Nov 6, 2026
978418a
fix(review): resolve unreadable rev-parse output as git_query_failed
Trecek Nov 6, 2026
92fe91d
fix(review): match only real Git include config keys as a layout channel
Trecek Nov 6, 2026
a7411ca
fix(review): name the headless blocklist matcher in the Git target do…
Trecek Nov 6, 2026
6c3bb56
fix(review): reuse _ambiguous_outcome for unknown-identity segments
Trecek Nov 6, 2026
d768382
fix(review): report a non-string Bash workdir as an unknown execution…
Trecek Nov 6, 2026
a9252b8
fix(review): scope the Git option-table module docstring to include t…
Trecek Nov 6, 2026
3f71287
fix(review): share one remote-and-refspecs record between push and fe…
Trecek Nov 6, 2026
1ae5a4e
fix(review): treat an interactive git clean as destructive
Trecek Nov 6, 2026
6aa5a38
fix(review): pin the Git builtin subcommand inventory to its referenc…
Trecek Nov 6, 2026
7375617
fix(review): rename misleading _READ_ONLY_SUBCOMMANDS in git_ops_guard
Trecek Nov 6, 2026
46b4247
fix(review): derive git_ops_guard prefilter regex from ref-storage regex
Trecek Nov 6, 2026
6d7cddf
fix(review): drop dead None guards after anchor env binding in prepar…
Trecek Nov 6, 2026
f3e1c71
fix(review): correct git_ops_guard session-scope wording and rewrap i…
Trecek Nov 6, 2026
03ffe2c
fix(review): state real merge_worktree branch contract in make-groups…
Trecek Nov 6, 2026
157398c
fix(review): share the ambient Git variable list through tests/_git_t…
Trecek Nov 6, 2026
67bbae4
fix(review): share one run-record base between the differential Git runs
Trecek Nov 6, 2026
caf63c5
fix(review): drop the self-testing missing_predicates canary
Trecek Nov 6, 2026
d163fdc
fix(review): require HEAD-detaching commands without an outcome conce…
Trecek Nov 6, 2026
9383bb9
fix(review): derive the raw-option-token guard scope from the _git_*.…
Trecek Nov 6, 2026
5c70f99
fix(review): share Git environment isolation and the Git runner throu…
Trecek Nov 6, 2026
f18fdbe
fix(review): drop the shell-walk test's duplicate ambient-environment…
Trecek Nov 6, 2026
cbd2382
fix(review): assert the proven directory on every certain-cwd row
Trecek Nov 6, 2026
c578330
fix(review): move the command_channel_flags rows out of the shell-wal…
Trecek Nov 6, 2026
502d940
fix(review): give the Git global-option subcommand rows readable ids
Trecek Nov 6, 2026
8cb019f
fix(review): read the git_ops_guard deny reason from its public autho…
Trecek Nov 6, 2026
999d5b6
fix(review): keep only the uncovered variable in the destructive-outc…
Trecek Nov 6, 2026
ae3e1a7
fix(review): explain the dashed git-commit row in the destructive-ope…
Trecek Nov 6, 2026
a18c300
fix(review): share the guard invocation and command expansion in the …
Trecek Nov 6, 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
17 changes: 12 additions & 5 deletions docs/safety/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,15 +117,22 @@ caller to use the `prepare_pr → compose_pr` pipeline instead.

### `git_ops_guard.py`
**Guarded tool:** `Bash`, `run_cmd`
Blocks destructive raw git CLI operations in headless skill sessions:
Denies commands that rewrite a branch ref checked out in any worktree of the
repository, and blocks destructive raw git CLI operations in headless skill
sessions. The ref preflight runs while the kitchen is open and in every
autoskillit-launched interactive session (cook, order, managed fleet), whether or not
the kitchen is open. In an interactive cook session it also denies moving `HEAD` of the
anchor repository's primary checkout. Destructive operations blocked in headless skill
sessions:
`commit --amend`, `push --force` / `-f` / `--force-with-lease`, `reset --hard`,
`clean -f` / `-fd`, and `checkout .` / `checkout -- .`. Uses `shlex.split`
tokenisation with global-flag skipping so `git -C /path commit --amend` and
full-path invocations like `/usr/bin/git push --force` are correctly detected.
Also catches interpreter-wrapped (`python3 -c "subprocess.run(['git', 'commit', '--amend'])"`)
and nested-shell forms. Session scope: headless only. Orchestrator sessions
are exempt. Per-subcommand allow-overrides are available via `git_ops_policy`
in `.hook_config.json` for future recipes that legitimately need these operations.
and nested-shell forms. Session scope of the destructive-operation phase: headless
skill sessions; orchestrator sessions are exempt. Per-subcommand allow-overrides are
available via `git_ops_policy` in `.hook_config.json` for future recipes that
legitimately need these operations.

### `resource_exhaustion_guard.py`
**Guarded tool:** `Bash`, `run_cmd`
Expand Down Expand Up @@ -687,7 +694,7 @@ as a defense-in-depth measure against privilege escalation:
| `background_exec_guard.py` | Unrecognized `AUTOSKILLIT_SESSION_TYPE` | Unknown session type should not bypass `run_in_background` prohibition |
| `github_mutation_guard.py` | Ambiguous or unresolved GitHub mutation command, or unexpected classifier error | Unknown mutation scope must not bypass the structured review publisher |
| `exploration_request_identity_guard.py` | A supported exploration event lacks bounded native identity or its one-shot record cannot be written | A Claude exploration call must not execute without request-correlated authority |
| `git_ops_guard.py` | Unexpected runtime error during the checked-out-ref preflight (OSError, subprocess.SubprocessError, TypeError, UnicodeDecodeError, ValueError); or, in the separate headless destructive-op-blocking preflight, an unrecognized global git flag that leaves the real subcommand unresolved | An unhandled exception must not silently allow a checked-out ref mutation — use exit 2 + stderr to hard-block. Separately, `_git_command_classification._contains_blocked_git_op` cannot match `_BLOCKED_GIT_OPS`'s literal subcommand tuples against an unresolved subcommand, so it denies unconditionally the moment `extract_git_subcommand_and_flags` reports `"<unresolved>"`, rather than silently falling through to "not blocked" |
| `git_ops_guard.py` | Any unexpected runtime error (any `Exception`) while classifying a Git command, in the checked-out-ref preflight or the headless destructive-op phase; or an unresolved target (unknown cwd, layout override or unparseable global option) for a ref mutation; or, in the separate headless destructive-op-blocking preflight, an unrecognized global git flag that leaves the real subcommand unresolved | An unhandled exception must not silently allow a checked-out ref mutation — use exit 2 + stderr to hard-block. Separately, `_git_target.contains_blocked_git_op` cannot match `_BLOCKED_GIT_OPS`'s literal subcommand tuples against an unresolved subcommand, so it denies unconditionally the moment `extract_git_subcommand_and_flags` reports `"<unresolved>"`, rather than silently falling through to "not blocked" |
| `pr_create_guard.py` | Hook config unreadable or malformed while the kitchen is open (OSError, JSONDecodeError, AttributeError, TypeError) | An unresolvable `recipe_allows_pr_create` authorization must not be read as permission to bypass the prepare_pr → compose_pr pipeline |
| `unsafe_install_guard.py` | An unrecognized global pip flag leaves `pip`'s `install` token position unresolved | `_find_pip_install` cannot tell whether the command is a pip install at all; treating that the same as "definitely not an install" would silently skip the editable/system-install checks entirely, so it is threaded through as a distinct `"unresolved-pip-flags"` kind and denied unconditionally, matching the pre-existing `"unresolved-subprocess"` kind's treatment |
| `write_guard.py` | A write-verb operand or redirect target cannot be resolved while a write-prefix policy applies | An unresolved target could escape the allowed prefix; the denial explains how to substitute a literal path. |
Expand Down
20 changes: 12 additions & 8 deletions src/autoskillit/cli/session/_session_launch.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,13 @@ class PreparedInteractiveLaunch:
pre_spawn_check: Callable[[], None] | None = None


def _interactive_anchor_env(
extra_env: Mapping[str, str] | None, project_dir: Path
) -> dict[str, str]:
"""Bind hook state to the orchestrating project root for every interactive launch."""
return {**(extra_env or {}), AUTOSKILLIT_STATE_ROOT_ENV_VAR: str(project_dir.resolve())}


def prepare_interactive_launch(
backend: CodingAgentBackend,
*,
Expand All @@ -157,12 +164,13 @@ def prepare_interactive_launch(
mcp_tool_timeout_sec: float | None = None,
) -> PreparedInteractiveLaunch:
"""Probe an exact executable before sealing the capability-complete session env."""
extra_env = _interactive_anchor_env(extra_env, project_dir)

probe_env = dict(os.environ)
if extra_env is not None and "PATH" in extra_env:
if "PATH" in extra_env:
probe_env["PATH"] = extra_env["PATH"]
selector = backend.capabilities.explicit_path_env_var
if selector and extra_env is not None and selector in extra_env:
if selector and selector in extra_env:
probe_env[selector] = extra_env[selector]
explicit_path_env = selector if selector and selector in probe_env else None

Expand All @@ -172,7 +180,7 @@ def prepare_interactive_launch(
cwd=project_dir,
explicit_path_env=explicit_path_env,
)
merged_extras = dict(extra_env or {})
merged_extras = dict(extra_env)
if managed_home is not None:
readiness = backend.probe_launch_readiness(
session_dir=managed_home.generated_home, executable=provisional
Expand Down Expand Up @@ -238,6 +246,7 @@ def _finalize_interactive_launch(
mcp_tool_timeout_sec: float | None = None,
) -> PreparedInteractiveLaunch:
"""Build and validate the finalized invocation with its exact executable binding."""
extra_env = _interactive_anchor_env(extra_env, project_dir)
from autoskillit.execution import assert_interactive_ordering, assert_resume_purity

if exact_binding_probe_required:
Expand Down Expand Up @@ -396,11 +405,6 @@ def _run_interactive_session(
raise ValueError("managed launch inputs are invalid for a raw session")

_project_dir = (project_dir if project_dir is not None else Path.cwd()).resolve()
# Injected so PreToolUse guards can locate `.autoskillit/` state from the
# orchestrating project root even when a command's own cwd points into a
# sibling worktree with its own checked-in `.autoskillit/` — the production
# signal resolve_state_root() (hooks/_hook_payload.py) checks first.
extra_env = {**(extra_env or {}), AUTOSKILLIT_STATE_ROOT_ENV_VAR: str(_project_dir)}
tools_arg: tuple[str, ...] = (
("AskUserQuestion",) if backend.capabilities.skill_injection_capable else ()
)
Expand Down
7 changes: 4 additions & 3 deletions src/autoskillit/core/types/constants/_type_constants_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,10 @@
AUTOSKILLIT_APPLICABLE_GUARDS: str = "AUTOSKILLIT_APPLICABLE_GUARDS"
AUTOSKILLIT_WRITE_GUARD_TOOL_NAMES: str = "AUTOSKILLIT_WRITE_GUARD_TOOL_NAMES"
AUDIT_ADMISSION_AUTHORITY_PATH_ENV_VAR: str = "AUTOSKILLIT_AUDIT_ADMISSION_AUTHORITY_PATH"
# The orchestrating project root, injected by launch preparation so guards can
# locate `.autoskillit/` state in worktree topologies where the hook payload's
# own cwd points into a sibling worktree with its own checked-in `.autoskillit/`.
# The project root for interactive launches and the session cwd for headless ones,
# injected by launch preparation so guards can locate `.autoskillit/` state in
# worktree topologies where the hook payload's own cwd points into a sibling
# worktree with its own checked-in `.autoskillit/`.
# Read as a bare string literal by hooks/_hook_payload.py's resolve_state_root
# (stdlib-only boundary prevents importing this constant there) — keep the two
# string values byte-identical.
Expand Down
11 changes: 11 additions & 0 deletions src/autoskillit/core/types/constants/_type_invariant_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,17 @@ class InvariantDef:
enforcement_layer="hook-deny",
backends=_BOTH,
),
"git-primary-checkout-head": InvariantDef(
id="git-primary-checkout-head",
prohibition=(
"Using checkout, switch, branch or symbolic-ref to move HEAD of the cook anchor "
"repository's primary checkout is prohibited"
),
source_doc="AGENTS.md",
gate_target="guards/git_ops_guard.py",
enforcement_layer="hook-deny",
backends=_BOTH,
),
"recipe-read-headless": InvariantDef(
id="recipe-read-headless",
prohibition="Must not read recipe/skill/agent files directly in headless sessions",
Expand Down
6 changes: 4 additions & 2 deletions src/autoskillit/core/types/foundation/_type_enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,8 +517,10 @@ class SessionType(StrEnum):
run_skill). L0 subagents are the actual leaf nodes — they never
set AUTOSKILLIT_SESSION_TYPE and cannot call run_skill.

Note: interactive L1 sessions (autoskillit cook, bare Claude Code) have no
SessionType value -- they bypass tier checks because AUTOSKILLIT_HEADLESS is unset.
Note: an interactive cook session (autoskillit cook) carries SKILL together with a
launch id and no AUTOSKILLIT_HEADLESS, which is how hooks tell it from a headless
worker. A bare Claude Code session has no SessionType value and bypasses tier
checks because AUTOSKILLIT_HEADLESS is unset.
"""

FLEET = "fleet"
Expand Down
6 changes: 3 additions & 3 deletions src/autoskillit/execution/backends/claude.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,9 +415,9 @@ def build_interactive_cmd(
An interactive session operates at L1 (cook, ``autoskillit cook``) by default.
It becomes an L2 orchestrator (order, ``autoskillit order``) when the user
calls ``open_kitchen``, granting full kitchen access and the ability to dispatch
L1 ``run_skill`` workers. Unlike headless sessions, the orchestration level of
an interactive session is determined at runtime by kitchen state, not by a
``SESSION_TYPE`` env variable.
L1 ``run_skill`` workers. The launcher sets ``SESSION_TYPE`` for cook
(``skill``) and order (``orchestrator``), together with a launch id; the
kitchen state, not that variable, decides which tools are visible.
"""
del generated_home
builder = CmdBuilder(str(executable.path) if executable is not None else "claude")
Expand Down
7 changes: 4 additions & 3 deletions src/autoskillit/hook_registry/_env_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,9 +220,10 @@ def _validate_hook_env_contract(entries: tuple[HookEnvVarDef, ...]) -> None:
HookEnvVarDef(
"AUTOSKILLIT_STATE_ROOT",
"autoskillit",
"autoskillit.cli.session._session_launch:_run_interactive_session",
"autoskillit.cli.session._session_launch:_run_interactive_session",
"Interactive launch binds all hook state to the orchestrating project root.",
"autoskillit.cli.session._session_launch:_interactive_anchor_env",
"autoskillit.cli.session._session_launch:prepare_interactive_launch",
"Every interactive launch (cook, order, fleet) binds hook state to the "
"orchestrating project root.",
),
HookEnvVarDef(
"AUTOSKILLIT_WRITE_GUARD_TOOL_NAMES",
Expand Down
6 changes: 6 additions & 0 deletions src/autoskillit/hooks/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ That inventory test makes any new raw scan under `hooks/` a conscious, reviewed
`StdinLiteral` is the second instance of the `ArgvToken` "tag once at tokenization, consume
tagged provenance downstream" pattern (`_tokenizer.py`, commit `6624dda71`, issue #4680):
future token-level provenance should extend this path rather than add a parallel parser.
Invocation `-c` extraction (`bash -lc`, `python3 -Bc`) and wrapper command-position arity
(`_WRAPPER_SPECS`) live in `_classification/_invocation_flags.py`. Where the command a
wrapper, interpreter or launcher runs cannot be located, the position is *unresolved*; that
signal travels out of band (`WalkedSegment.position_unresolved`) so every shared consumer
keeps its verb. Git option semantics are decided through `_option_grammar` tables;
`tests/arch/test_git_option_literal_scope.py` enforces this.

## Multi-concern files

Expand Down
27 changes: 22 additions & 5 deletions src/autoskillit/hooks/_classification/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,21 @@ block B bootstrap so hook scripts can keep importing via
`EvaluatedSegment`, `StdinLiteral`, `strip_heredoc_bodies`).
- `_flags.py` — flag-parsing tables, shell-substitution regexes, and
protected-read classification.
- `_option_grammar.py` — Git parse-options engine (`parse_options`, `last_option`,
`OptionArity`, `OptionDef`, `ParsedArgv`): bundled, stuck, `=`-joined,
abbreviated and negated options over per-subcommand tables; leaf module.
- `_flag_arity_classification.py` — leaf sibling holding the `_FlagArity` enum
referenced by `_flags.py` and `_interpreters.py`. Lifted out so neither
classification module owns the cross-import that would otherwise create a
bidirectional `_flags` ↔ `_interpreters` coupling.
- `_invocation_flags.py` — leaf holding the shell and Python invocation specs, the
bundle-aware `-c` extractors (`shell_c_payload`, `python_c_program`) and the
per-wrapper command-position tables (`_WRAPPER_SPECS`, `_wrapper_command_start`).
A wrapper option or launcher it does not model is reported *unresolved* out of
band, so shared consumers keep their verb.
- `_python_program_analysis.py` — Python interpreter and subprocess invocation
analysis (`_InterpreterCommandSpec`, `_python_c_program`,
`_python_program_command_specs`, `_python_program_evaluated_specs`).
analysis (`_InterpreterCommandSpec`, `_python_program_command_specs`,
`_python_program_evaluated_specs`).
- `_substitution_scanning.py` — shell-substitution / process-substitution
scanning and the legacy shell-payload segment traversal.
- `_github_mutation_cli_analysis.py` — `gh` / `curl` mutation grammar.
Expand All @@ -40,8 +48,17 @@ block B bootstrap so hook scripts can keep importing via
Sole producer of these symbols; the facade re-exports them.
`scan_write_targets` and `WriteTargetScan` are defined in
`_runtime/_write_target_scan.py` and re-exported by
`_runtime/_command_classification.py`. The scanner tracks mutable cwd and scope
state across evaluated commands.
`_runtime/_command_classification.py`. The scanner consumes
`_runtime/_shell_segment_walk.py`, the single authority for the cwd in effect for
each evaluated segment: it tracks mutable cwd and scope state and, beyond the
shell's logical directory, whether a `cd` certainly ran (`cwd_certain`).

`_CommandSegment` carries the logical operator that joined it to the previous
segment (`connector`: `&&`, `||`, `|`, `&`, `;` or empty) and whether it is the first
statement after a dropped bare keyword line (`after_keyword`). The first operator
after a command wins, so a newline after `&&`, `||`, `|` or `&` keeps that operator.
`_shell_structure` emits the newline boundary before its `;`, so a trailing `#`
comment cannot swallow the boundary.

## Bootstrap Conventions

Expand All @@ -52,7 +69,7 @@ the facade's relative imports and any bare-name bootstrap (hook scripts that
push `hooks/_classification/` onto `sys.path`) resolve the same symbols.

Within-folder imports of leaf siblings (`_tokenizer.py`, `_flag_arity_classification.py`,
`_source_map.py`)
`_source_map.py`, `_option_grammar.py`, `_invocation_flags.py`)
stay at module top-level — they have no back-references into the facade or
into other `_classification/` modules, so the relative-import dance isn't
required.
17 changes: 14 additions & 3 deletions src/autoskillit/hooks/_classification/_flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
ArgvToken,
EvaluatedSegment,
SearchPattern,
_command_start_index,
_verb_start_index,
command_verb,
extract_git_subcommand_and_flags,
)
Expand Down Expand Up @@ -259,6 +259,16 @@ def _consume_str_flag(
"--namespace": _FlagArity.VALUE,
"--config-env": _FlagArity.VALUE,
"--super-prefix": _FlagArity.VALUE,
"--attr-source": _FlagArity.VALUE,
"--list-cmds": _FlagArity.VALUE,
"--no-optional-locks": _FlagArity.BOOLEAN,
"--literal-pathspecs": _FlagArity.BOOLEAN,
"--no-literal-pathspecs": _FlagArity.BOOLEAN,
"--glob-pathspecs": _FlagArity.BOOLEAN,
"--noglob-pathspecs": _FlagArity.BOOLEAN,
"--icase-pathspecs": _FlagArity.BOOLEAN,
"--no-lazy-fetch": _FlagArity.BOOLEAN,
"--no-advice": _FlagArity.BOOLEAN,
# --exec-path[=<path>] is optional-value (usable bare, or with `=`); this
# module's binary arity model can't express "optional". BOOLEAN is the
# correct default for its common bare usage; the rare `=`-form
Expand Down Expand Up @@ -446,7 +456,8 @@ def is_allowed_protected_path_metadata_command(segment: EvaluatedSegment) -> boo
return False
return _is_allowed_git_metadata_invocation(git_parts.subcommand, git_parts.flags)
if verb == "wc" or verb.endswith("/wc"):
start = _command_start_index(tokens)
# Any skipped prefix (keyword, assignment, `env`, wrapper) disqualifies the arm.
start = _verb_start_index(tokens)
if start != 0:
return False
flags = [token for token in tokens[start + 1 :] if token.startswith("-")]
Expand Down Expand Up @@ -504,7 +515,7 @@ def command_has_blocked_protected_path_read(
ArgvToken = _classification.ArgvToken
EvaluatedSegment = _classification.EvaluatedSegment
SearchPattern = _classification.SearchPattern
_command_start_index = _classification._command_start_index
_verb_start_index = _classification._verb_start_index
command_verb = _classification.command_verb
extract_git_subcommand_and_flags = _classification.extract_git_subcommand_and_flags

Expand Down
Loading
Loading