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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions executors/docker/enforcer.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
import subprocess
import time

from nomos_runtime.shell_line import control_tokens, shell_line_problem

from .config import ExecutorConfig
from .models import ExecutionContext, ExecutionResult, WritOfExecution
from .nonce_store import NonceStore
Expand Down Expand Up @@ -199,6 +201,12 @@ async def execute_writ(
)

# 6. Blocked pattern check
problem = shell_line_problem(writ.command)
if problem:
return ExecutionResult(
writ_id=writ.writ_id, error=problem, verification_stage="blocked_pattern"
)

blocked = self._check_blocked_patterns(writ.command)
if blocked:
return ExecutionResult(
Expand Down Expand Up @@ -302,12 +310,7 @@ def _is_env_assignment(token: str) -> bool:
@staticmethod
def _shell_tokens(command: str) -> list[str]:
"""Tokenize a shell command while preserving command separators."""
try:
lexer = shlex.shlex(command, posix=True, punctuation_chars="|&;()<>")
lexer.whitespace_split = True
return list(lexer)
except ValueError:
return command.strip().split()
return control_tokens(command, "|&;()<>")

def _extract_tool_names(self, command: str) -> list[str]:
"""
Expand Down
8 changes: 7 additions & 1 deletion nomos/auth/writ_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
WritOfExecution,
)
from nomos.store.base import DurableStore
from nomos_runtime.shell_line import shell_line_problem

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -182,10 +183,15 @@ async def mint_writ(

writ: AuthorizationWrit
if operation is None:
# Command Writs carry shell text regardless of the intent's review type.
command = intent.command or ""
problem = shell_line_problem(command)
if problem:
raise ValueError(problem)
writ = WritOfExecution(
writ_id=_generate_writ_id(),
intent_hash=_compute_intent_hash(intent),
command=intent.command or "",
command=command,
working_directory=working_directory or intent.working_directory or "",
target_agent_id=target_agent_id,
packaged_files=intent.packaged_files,
Expand Down
18 changes: 17 additions & 1 deletion nomos/level_0/types/intent.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
from enum import StrEnum
from typing import Any

from pydantic import BaseModel, Field, PrivateAttr, field_validator, model_validator
from pydantic import BaseModel, Field, PrivateAttr, ValidationInfo, field_validator, model_validator

from nomos_runtime.shell_line import shell_line_problem

from .attestation import AttestationVector
from .packaged_file import PackagedFile
Expand Down Expand Up @@ -287,6 +289,20 @@ def validate_command(cls, v: str) -> str:
raise ValueError(f"Command contains dangerous pattern: {pattern}")
return v

def shell_command_problem(self) -> str:
"""Return a shell syntax error for shell intents only."""
if self.command_type != CommandType.SHELL:
return ""
return shell_line_problem(self.command)

@model_validator(mode="after")
def validate_shell_command(self, info: ValidationInfo) -> "Intent":
if not (info.context or {}).get("restore_durable_workflow"):
problem = self.shell_command_problem()
if problem:
raise ValueError(problem)
return self

@field_validator("target_namespace")
@classmethod
def validate_namespace(cls, v: str) -> str:
Expand Down
19 changes: 5 additions & 14 deletions nomos/level_1/policy/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
"""Shell command policy helpers."""

import re
import shlex

_COMMAND_SEPARATORS = {"|", "||", "&", "&&", ";"}
from nomos_runtime.shell_line import control_tokens

_COMMAND_SEPARATORS = {"|", "||", "&", "&&", ";", "\n"}
_COMMAND_GROUP_TOKENS = {"(", ")"}
_REDIRECT_TOKENS = {">", ">>", "<", "<<", "<<<", ">|", "<>", "&>", "&>>", "2>", "2>>"}
_SHELL_BUILTINS = {"cd"}
Expand All @@ -21,22 +22,12 @@ def _is_env_assignment(word: str) -> bool:

def _shell_tokens(command: str) -> list[str]:
"""Tokenize a shell command while preserving command separators."""
try:
lexer = shlex.shlex(command, posix=True, punctuation_chars="|&;()<>")
lexer.whitespace_split = True
return list(lexer)
except ValueError:
return command.strip().split()
return control_tokens(command, "|&;()<>")


def _shell_tokens_preserving_redirection_words(command: str) -> list[str]:
"""Tokenize shell words while preserving compact redirections like ``2>/dev/null``."""
try:
lexer = shlex.shlex(command, posix=True, punctuation_chars="|&;()")
lexer.whitespace_split = True
return list(lexer)
except ValueError:
return command.strip().split()
return control_tokens(command, "|&;()")


def _is_non_persistent_redirect_target(target: str) -> bool:
Expand Down
72 changes: 37 additions & 35 deletions nomos/level_4/council/council.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,17 @@ def _local_workflow(self, intent_id: str) -> IntentWorkflow | None:
self.expire_workflow(workflow)
return workflow

def _workflow_for_action(self, intent_id: str) -> tuple[IntentWorkflow | None, str]:
"""Read the target command before maintenance can change its recorded state."""
workflow = self._workflows.get(intent_id)
if workflow is not None:
problem = workflow.intent.shell_command_problem()
if problem:
return workflow, problem

self._prune_terminal_workflows()
return self._local_workflow(intent_id), ""

def _expire_elapsed_workflows(self) -> None:
"""Apply every local decision deadline, for listings of current state."""
if self._config.loop_owned_workflows:
Expand Down Expand Up @@ -542,6 +553,10 @@ def preflight_intent(
agent_role: AgentRole | None = None,
) -> PreflightResult:
"""Evaluate policy and reserve capacity without mutating workflow or ledger state."""
problem = intent.shell_command_problem()
if problem:
return PreflightResult(success=False, error=problem)

self._prune_terminal_workflows()
self._reap_expired_preflights()

Expand Down Expand Up @@ -601,6 +616,10 @@ def submit_intent(
Returns immediately with the initial evaluation result.
For intents requiring approval, the workflow enters AWAITING_APPROVAL.
"""
problem = intent.shell_command_problem()
if problem:
return SubmitResult(success=False, error=problem)

# Drop bookkeeping for long-finished workflows so the in-memory map
# stays bounded for a long-lived council; their outcome remains in the
# ledger and persistent store.
Expand Down Expand Up @@ -748,18 +767,6 @@ def approve_intent(
reason: str = "",
) -> SubmitResult:
"""Cast an approval vote for an intent."""
self._prune_terminal_workflows()
workflow = self._local_workflow(intent_id)
if workflow is None:
return SubmitResult(success=False, error="Intent not found")

if workflow.state != WorkflowState.AWAITING_APPROVAL:
return SubmitResult(
success=False,
workflow=workflow,
error=f"Intent is not awaiting approval (state: {workflow.state.value})",
)

return self.cast_member_vote(intent_id, approver_id, VoteType.APPROVE, reason=reason)

def deny_intent(
Expand All @@ -769,18 +776,6 @@ def deny_intent(
reason: str = "",
) -> SubmitResult:
"""Cast a denial vote for an intent."""
self._prune_terminal_workflows()
workflow = self._local_workflow(intent_id)
if workflow is None:
return SubmitResult(success=False, error="Intent not found")

if workflow.state != WorkflowState.AWAITING_APPROVAL:
return SubmitResult(
success=False,
workflow=workflow,
error=f"Intent is not awaiting approval (state: {workflow.state.value})",
)

return self.cast_member_vote(intent_id, denier_id, VoteType.DENY, reason=reason)

def cast_member_vote(
Expand All @@ -793,11 +788,13 @@ def cast_member_vote(
finalize: bool = True,
) -> SubmitResult:
"""Record a council member vote and optionally finalize the review."""
self._prune_terminal_workflows()
workflow = self._local_workflow(intent_id)
workflow, problem = self._workflow_for_action(intent_id)
if workflow is None:
return SubmitResult(success=False, error="Intent not found")

if problem:
return SubmitResult(success=False, workflow=workflow, error=problem)

if workflow.state != WorkflowState.AWAITING_APPROVAL:
return SubmitResult(
success=False,
Expand Down Expand Up @@ -836,11 +833,13 @@ def revise_vote(
who already voted to change their position and records the change
as a ``DEBATE_VOTE`` ledger entry.
"""
self._prune_terminal_workflows()
workflow = self._local_workflow(intent_id)
workflow, problem = self._workflow_for_action(intent_id)
if workflow is None:
return SubmitResult(success=False, error="Intent not found")

if problem:
return SubmitResult(success=False, workflow=workflow, error=problem)

if workflow.state != WorkflowState.AWAITING_APPROVAL:
return SubmitResult(
success=False,
Expand Down Expand Up @@ -875,11 +874,13 @@ def finalize_intent_review(
partial_voters: set[str] | None = None,
) -> SubmitResult:
"""Finalize a batched council review round and sync workflow state."""
self._prune_terminal_workflows()
workflow = self._local_workflow(intent_id)
workflow, problem = self._workflow_for_action(intent_id)
if workflow is None:
return SubmitResult(success=False, error="Intent not found")

if problem:
return SubmitResult(success=False, workflow=workflow, error=problem)

if workflow.state != WorkflowState.AWAITING_APPROVAL:
return SubmitResult(success=True, workflow=workflow)

Expand Down Expand Up @@ -937,9 +938,8 @@ def mint_token(

The token authorizes execution of the action described in the intent.
"""
self._prune_terminal_workflows()
workflow = self._local_workflow(intent_id)
if workflow is None:
workflow, problem = self._workflow_for_action(intent_id)
if workflow is None or problem:
return None

if workflow.state != WorkflowState.APPROVED:
Expand Down Expand Up @@ -978,11 +978,13 @@ def execute_intent(self, intent_id: str) -> ExecuteResult:

This is the complete flow: execute -> verify -> complete/rollback.
"""
self._prune_terminal_workflows()
workflow = self._local_workflow(intent_id)
workflow, problem = self._workflow_for_action(intent_id)
if workflow is None:
return ExecuteResult(success=False, error="Intent not found")

if problem:
return ExecuteResult(success=False, workflow=workflow, error=problem)

if workflow.state == WorkflowState.APPROVED:
token = self.mint_token(intent_id)
if token is None:
Expand Down
4 changes: 3 additions & 1 deletion nomos/level_4/council/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,9 @@ def _dt(key: str) -> datetime | None:

token = data.get("capability_token")
return cls(
intent=Intent.from_dict(data["intent"]),
intent=Intent.model_validate(
data["intent"], context={"restore_durable_workflow": True}
),
state=WorkflowState(data["state"]),
logical_version=int(data.get("logical_version", 0)),
retire_after=_dt("retire_after"),
Expand Down
34 changes: 34 additions & 0 deletions nomos_runtime/shell_line.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Line-oriented command syntax shared by the council and executor."""

import shlex


def shell_line_problem(command: str) -> str:
"""Describe unsupported syntax without including any of the command."""
if "\x00" in command:
return "Shell command contains a null byte"
if "\n" in command or "\r" in command:
return "Shell command must be a single line"
if "`" in command:
return "Shell command contains unsupported backticks"
return ""


def control_tokens(command: str, punctuation: str) -> list[str]:
"""Keep line breaks as separators when inspecting previously stored commands."""
tokens: list[str] = []
lines = command.replace("\r\n", "\n").replace("\r", "\n").split("\n")
for index, line in enumerate(lines):
if index:
tokens.append("\n")
try:
lexer = shlex.shlex(line, posix=True, punctuation_chars=punctuation)
lexer.whitespace_split = True
tokens.extend(list(lexer))
except ValueError:
# A line that does not lex cleanly still has a distinct boundary.
tokens.extend(line.split())
return tokens
31 changes: 31 additions & 0 deletions tests/level_0/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -565,3 +565,34 @@ def test_serialization_roundtrip(self):
assert restored.strategy == RollbackStrategy.SNAPSHOT
assert restored.estimated_duration_seconds == 120
assert restored.artifacts["snapshot_id"] == "snap-123"


@pytest.mark.parametrize("delimiter", ["\n", "\r", "\x00", "`"])
def test_new_shell_intents_reject_unsupported_line_syntax(delimiter):
with pytest.raises(ValueError, match="Shell command"):
Intent.create(
agent_id="agent-1",
description="Print a label",
target_resource="/workspace",
command=f"/bin/echo left{delimiter}right",
)


@pytest.mark.parametrize(
("command_type", "command"),
[
(CommandType.SQL, "SELECT `name`\nFROM users"),
(CommandType.PYTHON, "def value():\n return 1"),
],
)
def test_non_shell_intents_accept_their_language_syntax(command_type, command):
intent = Intent.create(
agent_id="agent-1",
description="Read a value from a program",
target_resource="/workspace",
command=command,
command_type=command_type,
)

assert intent.command == command
assert intent.command_type == command_type
Loading
Loading