Back to skill

Security audit

Context Window Optimizer

Security checks for vulnerabilities and agentic risk

Overview

This skill has a coherent context-summarization purpose, but it reads local agent session transcripts and can persist conversation-derived content with weak scoping and no clear approval or redaction controls.

Review this skill before installing. Only run it on sessions you are comfortable summarizing, check which transcript it will read, avoid using it where chats may contain secrets or regulated data, and manually approve any extracted facts or preferences before copying them into long-term memory.

Vulnerability Patterns
  • Agent Memory PoisoningWrites attacker-controlled rules into memory that affect later sessions
  • Unauthorized Access and Privilege EscalationObtains permissions beyond the task's legitimate needs
  • Skill Instruction HijackingAlters the agent's session goals or safety constraints when the skill loads
  • Remote Payload Retrieval and ExecutionFetches external code whose behavior can change after review
  • Embedded Malicious CodeShips malicious scripts inside the skill and executes them locally
Findings (2)

T05 · Unauthorized Access and Privilege Escalation

Warning
Location
scripts/extract_decisions.py:14
Finding

Unscoped Access to Sensitive Agent Session Transcripts

Content
View full analysis

Vulnerability Details

File Location: scripts/analyze_context.py:31-44, scripts/extract_decisions.py:14-56, and scripts/summarize_session.py:19-39
Vulnerability Type: Missing session-level access control and ignored session selector
Risk Level: Medium

Complete Code Snippets

scripts/analyze_context.py:31-44:

python
transcript_paths = [
    Path("~/.openclaw/agents/main/sessions/").expanduser(),
]

total_messages = 0
oldest = None
newest = None

for p in transcript_paths:
    if p.exists() and p.is_dir():
        jsonl_files = list(p.glob("*.jsonl"))
        if jsonl_files:
            latest = max(jsonl_files, key=lambda f: f.stat().st_mtime)
            with open(latest) as f:
                for line in f:
                    if line.strip():
                        total_messages += 1

scripts/extract_decisions.py:14-56:

python
def load_messages():
    """Load messages from the latest session transcript."""
    p = Path("~/.openclaw/agents/main/sessions/").expanduser()

    if not p.exists():
        return []

    jsonl_files = [f for f in p.glob("*.jsonl") if ".lock" not in str(f)]
    if not jsonl_files:
        return []

    latest = max(jsonl_files, key=lambda f: f.stat().st_mtime)

    messages = []
    with open(latest) as f:
        for line in f:
            if not line.strip():
                continue
            try:
                entry = json.loads(line)
                if entry.get("type") == "message":
                    msg = entry.get("message", {})
                    role = msg.get("role", "unknown")
                    content = msg.get("content", [])

                    text = ""
                    if isinstance(content, str):
                        text = content
                    elif isinstance(content, list):
                        for block in content:
                            if is
...[truncated 3646 chars]
Remediation
View remediation

Remediation Suggestions

  1. Make --session mandatory and use it to resolve one specific transcript rather than selecting the newest global file.
  2. Validate the session identifier against a strict format and reject path separators or traversal sequences.
  3. Resolve the selected path and verify that it remains inside an approved session directory.
  4. Verify that the caller is authorized to access the requested session.
  5. Do not include tool arguments by default; tool commands can contain tokens, file paths, or other sensitive values.
  6. Apply secret redaction to transcript text before printing or writing it.
  7. Require explicit confirmation before processing a transcript selected through a current alias.
  8. Open files using UTF-8 with controlled error handling and impose limits on transcript size and line length.
  9. Add tests proving that a request for one session cannot read another session, even when the other file has a newer modification time.

T02 · Agent Memory Poisoning

Warning
Location
scripts/extract_decisions.py:68
Finding

Untrusted Conversation Content Can Be Promoted to Persistent Agent Memory

Content
View full analysis

Vulnerability Details

File Location: SKILL.md:43-66 and scripts/extract_decisions.py:68-105
Vulnerability Type: Persistent memory poisoning through unvalidated heuristic extraction
Risk Level: Medium

Complete Code Snippets

SKILL.md:43-66:

markdown
- Decisions that should move to permanent memory

### Step 3: Extract to Memory

**Decisions → `MEMORY.md` or relevant project file:**

Decisions (from 2026-03-25 session)

  • Chose PostgreSQL over MongoDB for project X
  • Agreed on 3-day sprint cadence
  • User prefers detailed explanations, not summaries
text

**Key facts → appropriate domain/project file:**

Project X Facts

  • Tech stack: React + Node + Postgres
  • Main user pain point: slow onboarding
  • Current velocity: 5 story points/sprint
text

**Patterns → `~/self-improving/memory.md`:**

User Preferences

  • Always explain the "why" before the "what"
  • Prefers bullet points over paragraphs
text

scripts/extract_decisions.py:68-105:

python
def extract_decisions_keyword(messages):
    """Extract decisions using keywords and patterns."""
    patterns = {
        "decisions": [
            "decided", "agreed", "choice", "chose", "selected",
            "decision", "going with", "will use", "settled on",
            "concluded", "let's go with", "approved", "confirmed"
        ],
        "actions": [
            "installed", "created", "built", "done", "completed",
            "finished", "implemented", "set up", "configured",
            "wrote", "added", "modified", "updated", "packaged"
        ],
        "preferences": [
            "prefer", "like", "want", "need", "always", "never",
            "i prefer", "user prefers", "style is", "vibe"
        ]
    }

    results = {"decisions": [], "actions": [], "preferences": []}

    for msg in messages:
        content_lower = msg.get("content", "").lower()
      
...[truncated 2931 chars]
Remediation
View remediation

Remediation Suggestions

  1. Treat all extracted items as untrusted drafts and never write them directly to long-term memory.
  2. Require explicit user approval for each item before persistence.
  3. Restrict preference extraction to direct, unambiguous statements from an authenticated user role.
  4. Exclude tool output, quoted text, assistant-generated claims, system text, and third-party content from memory candidates.
  5. Preserve provenance for every candidate, including session identifier, message identifier, role, timestamp, and exact source text.
  6. Detect negation, quotation, hypothetical language, and imperative instructions instead of relying on substring matching.
  7. Replace broad keywords such as always, never, need, and like with stricter structured extraction rules.
  8. Add a quarantine file for proposed memory updates and require a review step before promotion.
  9. Mark stored facts with confidence, expiration, and revocation metadata.
  10. Add adversarial tests covering prompt injection, quoted preferences, assistant speculation, conflicting statements, and malicious tool output.
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Memory PoisoningPersistent Context Injection, Context Window Stuffing, Memory Manipulation
  • Rogue AgentSelf-Modification, Session Persistence
  • Trigger AbuseOverly Broad Trigger, Shadow Command Trigger, Keyword Baiting Trigger
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
Findings (15)

Tp4

High
Category
MCP Tool Poisoning
Confidence
96% confidence
Finding

The skill claims trigger-based context optimization but actually describes writing markdown summaries and archiving material, without managing the live context window. That discrepancy matters because it normalizes filesystem operations and persistence under a workflow users may perceive as ephemeral housekeeping.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
96% confidence
Finding

The skill claims trigger-based context optimization but actually describes writing markdown summaries and archiving material, without managing the live context window. That discrepancy matters because it normalizes filesystem operations and persistence under a workflow users may perceive as ephemeral housekeeping.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
92% confidence
Finding

The skill claims trigger-based context optimization but actually describes writing markdown summaries and archiving material, without managing the live context window. That discrepancy matters because it normalizes filesystem operations and persistence under a workflow users may perceive as ephemeral housekeeping.

Content

No source excerpt is available for this finding.

Memory Manipulation

High
Category
Memory Poisoning
Confidence
80% confidence
Finding

Skill manipulates agent memory, state, or stored context. Memory corruption can alter personality, override safety rules, or cause unpredictable behavior.

Content

Scanner excerpt · SKILL.md (reported line 98)May include surrounding context.

md
### Step 5: Archive, Don't Delete

Never delete context — archive it:
- Move summaries to `memory/YYYY-MM-DD.md`
- Keep pointers in session for recovery
- Use `[[archived:filename.md]]` notation

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
89% confidence
Finding

The skill instructs use of scripts that analyze sessions and write summaries or extracted decisions, but it declares no explicit tool or permission scope. That creates an authorization gap where filesystem read/write behavior is implied but not constrained, increasing the chance of unintended access to transcripts or persistent files.

Content

No source excerpt is available for this finding.

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The trigger conditions are broad and subjective, such as when context 'feels heavy' or before 'complex' tasks. Ambiguous activation increases the chance the skill runs unnecessarily, causing avoidable reads of conversation history and writes of user data to persistent storage.

Content

No source excerpt is available for this finding.

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
91% confidence
Finding

The repeated optimization criteria still lack scope constraints and make it unclear what data range may be processed or when persistence is allowed. In a skill that archives and extracts conversation content, vague triggers materially increase privacy and overreach risk.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

The skill directs extraction of decisions, facts, and user preferences into persistent files, including a self-improving memory file, without warning about retention, sensitivity, or consent. This is dangerous because conversations may contain private, strategic, or regulated information that becomes durably stored beyond the user's expectation.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
87% confidence
Finding

The script silently reads and summarizes conversation transcripts from a user directory, which can expose sensitive prompts, secrets, or personal data without explicit user awareness at execution time. In the context of a context-optimization skill, this is more concerning because users may expect memory compaction, not filesystem-level harvesting of prior session content.

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

Medium
Category
Not specified by scanner
Confidence
82% confidence
Finding

The manifest frames this skill as a context-window optimizer that summarizes history and extracts key facts/decisions to permanent memory. In this file, the implemented behavior includes writing the extracted content to any user-specified filesystem path via --output, which is broader than merely compacting context or updating memory.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The usage text explicitly states that --session selects a target session, but the implementation ignores that argument entirely. This mismatch is dangerous because users may trust they are operating on one transcript while the script actually processes another, which is especially risky for a tool designed to condense potentially sensitive conversation history.

Content

No source excerpt is available for this finding.

Session Persistence

Medium
Category
Rogue Agent
Confidence
78% confidence
Finding

This script implements session persistence by extracting and storing condensed conversation content, which can extend the lifetime and spread of sensitive data beyond the original transcript. In the context-window-optimizer skill, that behavior is core functionality, but it still creates security risk because summaries may preserve confidential decisions, tasks, or identifiers in a new artifact that users may overlook.

Content

Scanner excerpt · scripts/summarize_session.py (reported line 14)May include surrounding context.

python
from pathlib import Path

def summarize_session(session_path=None, output_path=None):
    """Create a summary of the session."""
    
    print("📝 Creating session summary...")

Description-Behavior Mismatch

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

The script claims to summarize a chosen session but ignores the provided session identifier and always reads the most recent JSONL file from a hard-coded sessions directory. In a context-optimization skill, this can cause unintended access to and summarization of a different conversation than the operator intended, creating a privacy and data-mixing issue rather than direct code execution.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
88% confidence
Finding

The script reads full session transcripts from a user directory and can write extracted content to an arbitrary output path without any privacy notice, confirmation, or redaction. Because this skill is specifically built to summarize old conversations and preserve key facts, it increases the chance that sensitive user or system data will be copied into a more portable summary file that may be stored less securely.

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

Low
Category
Not specified by scanner
Confidence
72% confidence
Finding

The manifest describes optimizing context usage around conversation history and task phases, but this implementation unconditionally reads the latest transcript file from a fixed local sessions directory. That behavior is somewhat different from a scoped context-optimization action, because it performs local transcript discovery and analysis independently of the declared triggers or an explicitly supplied context segment.

Content

No source excerpt is available for this finding.

Static analysis

No suspicious patterns detected.