repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
Vibe-Trading | agent/src/memory/persistent.py | .py | """PersistentMemory: file-based cross-session memory, zero external dependencies."""
from __future__ import annotations
import hashlib
import logging
import math
import re
import sys
import time as _time
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime
from pathlib... | 654 | 25,766 |
Vibe-Trading | agent/src/memory/compression.py | .py | """Three-level memory compression pipeline: Raw -> Daily -> Digest (Tier 2).
Uses TF-IDF sentence scoring to extract key information while maintaining
high retention. Original content is archived before compression.
Feature flag: VT_MEMORY_COMPRESSION (default off).
"""
from __future__ import annotations
import log... | 356 | 12,588 |
Vibe-Trading | agent/src/memory/search_index.py | .py | """SQLite FTS5 full-text search index for persistent memory (Tier 2).
Provides O(log n) search via inverted index, replacing the O(n) sequential
token-scan in PersistentMemory.find_relevant(). Falls back gracefully if
FTS5 is unavailable.
Feature flag: VT_MEMORY_FTS_INDEX (default off).
Database: ~/.vibe-trading/memo... | 481 | 17,330 |
Vibe-Trading | agent/src/memory/semantic_links.py | .py | """Semantic linking between memory entries via BM25 similarity (Tier 2).
Automatically discovers and maintains relationships between memories using
term-frequency scoring. Links are stored as .relations.json sidecar files.
Feature flag: VT_MEMORY_LINKS (default off).
"""
from __future__ import annotations
import js... | 372 | 12,098 |
Vibe-Trading | agent/src/providers/__init__.py | .py | """LLM provider abstraction layer."""
from src.providers.llm import build_llm
__all__ = ["build_llm"]
| 6 | 104 |
Vibe-Trading | agent/src/providers/chat.py | .py | """ChatLLM: raw LLM message interface with function calling support.
ChatLLM is designed specifically for the AgentLoop ReAct cycle.
"""
from __future__ import annotations
import html
import logging
import os
import re
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional
f... | 554 | 22,407 |
Vibe-Trading | agent/src/providers/content_filter.py | .py | """Content-filter resilience helpers shared by AgentLoop and swarm worker.
When an LLM provider blocks a response via content moderation
(``finish_reason == "content_filter"``), the caller skips that iteration
and continues instead of breaking on empty/garbage content. These
helpers centralise threshold parsing, the ... | 103 | 3,818 |
Vibe-Trading | agent/src/providers/llm.py | .py | """LLM factory."""
from __future__ import annotations
import logging
import os
from copy import copy
from urllib.parse import urlparse
import re
from collections.abc import AsyncIterator, Iterator, Mapping, Sequence
from importlib import import_module
from importlib.metadata import PackageNotFoundError, version
from ... | 1,377 | 53,954 |
Vibe-Trading | agent/src/providers/copilot_auth.py | .py | """GitHub Copilot SDK adapter.
Authentication and transport are delegated to GitHub's supported SDK. The SDK
resolves ``COPILOT_GITHUB_TOKEN``, stored Copilot CLI credentials, and ``gh``
credentials without Vibe-Trading borrowing an OAuth client or editor identity.
"""
from __future__ import annotations
import async... | 460 | 16,233 |
Vibe-Trading | agent/src/providers/capabilities.py | .py | """Provider capability definitions for OpenAI-compatible chat adapters."""
from __future__ import annotations
import json
import os
from dataclasses import dataclass, field
from functools import lru_cache
from importlib.metadata import PackageNotFoundError, version
from pathlib import Path
from typing import Mapping,... | 408 | 15,098 |
Vibe-Trading | agent/src/providers/openai_codex.py | .py | """OpenAI Codex OAuth provider.
This provider follows the reference OpenAI Codex OAuth path: a ChatGPT account is
authenticated by oauth-cli-kit, then requests are sent to the ChatGPT Codex
Responses endpoint. It is intentionally separate from the standard OpenAI API
key path because ChatGPT OAuth tokens are not OpenA... | 711 | 27,511 |
Vibe-Trading | agent/src/agent/trace.py | .py | """TraceWriter: crash-safe JSONL trace writer.
One JSON record per line; each write is flushed and fsynced so the record
survives an immediate host crash. Large fields are written to sidecar files
(temp-write -> fsync -> ``os.replace`` -> directory fsync) BEFORE the record
that references them is fsynced, so a durable... | 408 | 13,962 |
Vibe-Trading | agent/src/agent/progress.py | .py | """Progress emission channel for long-running tools.
Two mechanisms:
* Tool-level heartbeat: a background timer fires keepalive events every N
seconds while a tool runs, so the UI never looks frozen. Driven by the
agent loop, opaque to the tool.
* Structured progress: tools can opt in via ``emit_progress()... | 185 | 6,053 |
Vibe-Trading | agent/src/agent/__init__.py | .py | """Agent core module: ReAct AgentLoop, tool registry, context, workspace memory, skills."""
from src.agent.loop import AgentLoop
from src.agent.memory import WorkspaceMemory
from src.agent.skills import SkillsLoader
from src.agent.tools import BaseTool, ToolRegistry
__all__ = ["AgentLoop", "WorkspaceMemory", "SkillsL... | 9 | 356 |
Vibe-Trading | agent/src/agent/skills.py | .py | """SkillsLoader: loads scenario guides from the skills/ directory.
Uses progressive disclosure at two levels:
- System prompt only injects one-line summaries (get_descriptions).
- Full docs loaded on demand (get_content, called by the load_skill tool).
- Inside one document, :func:`split_sections` maps the heading str... | 387 | 13,964 |
Vibe-Trading | agent/src/agent/context.py | .py | """ContextBuilder: builds LLM message context for the ReAct AgentLoop."""
from __future__ import annotations
import copy
import json
import logging
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from src.agent.memory import WorkspaceMemory
from src.agent.skills im... | 420 | 24,207 |
Vibe-Trading | agent/src/agent/grounding.py | .py | """Run-scoped identity and numeric evidence gates for the main agent loop.
The language model remains responsible for research and explanation, but three
facts are structural rather than advisory:
* a market-data consumer may only use an identity that was locked before the
current assistant tool-call batch started;... | 2,476 | 106,188 |
Vibe-Trading | agent/src/agent/loop.py | .py | """AgentLoop: ReAct core loop.
Five-layer context management:
Layer 1 (microcompact) — prunes old tool results once under memory pressure
Layer 2 (context_collapse) — folds long text blocks without LLM call (zero cost)
Layer 3 (auto_compact) — LLM structured summary with token-budget tail protection
La... | 2,108 | 83,930 |
Vibe-Trading | agent/src/agent/frontmatter.py | .py | """Shared YAML-like frontmatter parser for skills and memory files."""
from __future__ import annotations
import re
from typing import Any, Dict
# Opening ---, optional meta lines, closing ---. The closing fence may be at
# EOF (no trailing newline) or followed by a body; empty meta (---\n---) is ok.
_FRONTMATTER_RE... | 49 | 1,506 |
Vibe-Trading | agent/src/agent/tools.py | .py | """BaseTool + ToolRegistry: tool infrastructure."""
from __future__ import annotations
import json
import logging
from abc import ABC, abstractmethod
logger = logging.getLogger(__name__)
from typing import Any, Dict, List, Optional
class BaseTool(ABC):
"""Tool base class.
Attributes:
name: Unique ... | 95 | 2,863 |
Vibe-Trading | agent/src/agent/memory.py | .py | """Workspace memory: shared state across tool calls within a single run.
Lightweight runtime state — survives within one AgentLoop.run() invocation only.
Cross-session persistence is handled by src.memory.persistent.PersistentMemory.
"""
from __future__ import annotations
from dataclasses import dataclass, field
fro... | 54 | 1,633 |
Vibe-Trading | agent/src/channels/mochat.py | .py | """Mochat channel implementation using Socket.IO with HTTP polling fallback."""
from __future__ import annotations
import asyncio
import json
from collections import deque
from contextlib import suppress
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any
import ht... | 944 | 37,854 |
Vibe-Trading | agent/src/channels/slack.py | .py | """Slack channel implementation using Socket Mode."""
import asyncio
import re
from pathlib import Path
from typing import Any
import httpx
from pydantic import Field
from slack_sdk.socket_mode.request import SocketModeRequest
from slack_sdk.socket_mode.response import SocketModeResponse
from slack_sdk.socket_mode.we... | 755 | 30,593 |
Vibe-Trading | agent/src/channels/email.py | .py | """Email channel implementation using IMAP polling + SMTP replies."""
import asyncio
import html
import imaplib
import mimetypes
import re
import smtplib
import ssl
from contextlib import suppress
from dataclasses import dataclass
from datetime import date
from email import policy
from email.header import decode_heade... | 915 | 34,906 |
Vibe-Trading | agent/src/channels/utils.py | .py | """Utility helpers for channel adapters."""
from __future__ import annotations
import ipaddress
import re
import socket
from pathlib import Path
from urllib.parse import urlparse
from src.config.paths import get_data_dir
_UNSAFE_CHARS = re.compile(r"[/\\:*?\"<>|]")
def get_media_dir(channel_name: str) -> Path:
... | 180 | 6,349 |
Vibe-Trading | agent/src/channels/napcat.py | .py | """Napcat (OneBot v11) channel for QQ, over WebSocket."""
from __future__ import annotations
import asyncio
import base64
import json
import os
import random
import time
import uuid
from collections import deque
from pathlib import Path
from typing import Annotated, Any, Literal
import aiohttp
import logging; logger... | 581 | 22,299 |
Vibe-Trading | agent/src/channels/runtime.py | .py | """IM channel runtime that connects MessageBus traffic to SessionService."""
from __future__ import annotations
import asyncio
import json
import logging
import time
from contextlib import suppress
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from pathlib import Path
from typing imp... | 375 | 15,543 |
Vibe-Trading | agent/src/channels/signal.py | .py | """Signal channel implementation using signal-cli daemon JSON-RPC interface."""
from __future__ import annotations
import asyncio
import json
import re
import shutil
import unicodedata
from collections import deque
from collections.abc import AsyncIterator, Callable
from contextlib import asynccontextmanager
from dat... | 1,433 | 56,510 |
Vibe-Trading | agent/src/channels/whatsapp.py | .py | """WhatsApp channel implementation using neonize."""
from __future__ import annotations
import asyncio
import mimetypes
import re
import secrets
import time
from collections import OrderedDict
from contextlib import suppress
from pathlib import Path
from typing import Any, Literal, NamedTuple
from pydantic import Fi... | 683 | 23,470 |
Vibe-Trading | agent/src/channels/manager.py | .py | """Channel manager for coordinating chat channels."""
from __future__ import annotations
import asyncio
import hashlib
import logging
from collections.abc import Callable
from contextlib import suppress
from pathlib import Path
from typing import Any
from src.channels.base import BaseChannel
from src.channels.bus.ev... | 479 | 18,676 |
Vibe-Trading | agent/src/channels/__init__.py | .py | """Chat channels module — multi-IM adapter layer.
Provides a plugin-based channel architecture for connecting Vibe-Trading
to chat platforms (Telegram, Discord, Slack, Feishu, WhatsApp, etc.).
Architecture::
IM Message → ChannelAdapter.start()
→ _handle_message()
→ MessageBus.inbound
→ Ag... | 49 | 1,688 |
Vibe-Trading | agent/src/channels/websocket.py | .py | """WebSocket server channel: vibe-trading acts as a WebSocket server and serves connected clients."""
from __future__ import annotations
import asyncio
import hmac
import json
import re
import ssl
import uuid
from collections.abc import Callable
from contextlib import suppress
from pathlib import Path
from typing imp... | 1,204 | 48,194 |
Vibe-Trading | agent/src/channels/msteams.py | .py | """Microsoft Teams channel MVP using a tiny built-in HTTP webhook server.
Scope:
- DM-focused MVP
- text inbound/outbound
- conversation reference persistence
- sender allowlist support
- optional inbound Bot Framework bearer-token validation
- no attachments/cards/polls yet
"""
from __future__ import annotations
im... | 870 | 35,008 |
Vibe-Trading | agent/src/channels/feishu.py | .py | """Feishu/Lark channel implementation using lark-oapi SDK with WebSocket long connection."""
from __future__ import annotations
import asyncio
import importlib.util
import json
import os
import re
import threading
import time
import uuid
from collections import OrderedDict
from contextlib import suppress
from datacla... | 2,360 | 91,964 |
Vibe-Trading | agent/src/channels/registry.py | .py | """Auto-discovery for built-in channel modules and external plugins."""
from __future__ import annotations
import importlib
import importlib.util
import logging
import pkgutil
from collections.abc import Mapping
from dataclasses import dataclass
from types import ModuleType
from typing import Any
from typing import T... | 284 | 10,112 |
Vibe-Trading | agent/src/channels/matrix.py | .py | """Matrix (Element) channel — inbound sync + outbound message/media delivery."""
import asyncio
import json
import mimetypes
import time
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal, TypeAlias
from urllib.parse import quote, urlparse
from p... | 1,033 | 43,861 |
Vibe-Trading | agent/src/channels/weixin.py | .py | """Personal WeChat (微信) channel using HTTP long-poll API.
Uses the ilinkai.weixin.qq.com API for personal WeChat messaging.
No WebSocket, no local WeChat client needed — just HTTP requests with a
bot token obtained via QR code login.
Protocol reverse-engineered from ``@tencent-weixin/openclaw-weixin`` v1.0.3.
"""
fr... | 1,587 | 62,836 |
Vibe-Trading | agent/src/channels/telegram.py | .py | """Telegram channel implementation using python-telegram-bot."""
from __future__ import annotations
import asyncio
import re
import time
import unicodedata
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal
from urllib.parse import urlparse
from... | 1,705 | 69,732 |
Vibe-Trading | agent/src/channels/qq.py | .py | """QQ channel implementation using botpy SDK.
Inbound:
- Parse QQ botpy messages (C2C / Group)
- Download attachments to media dir using chunked streaming write (memory-safe)
- Publish to the Vibe-Trading bus via BaseChannel._handle_message()
- Content includes a clear, actionable "Received files:" list with local pat... | 715 | 26,060 |
Vibe-Trading | agent/src/channels/discord.py | .py | """Discord channel implementation using discord.py."""
from __future__ import annotations
import asyncio
import importlib.util
import time
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
from pydantic import Field
from src.cha... | 819 | 33,155 |
Vibe-Trading | agent/src/channels/dingtalk.py | .py | """DingTalk/DingDing channel implementation using Stream Mode."""
import asyncio
import json
import mimetypes
import os
import time
import zipfile
from io import BytesIO
from pathlib import Path
from typing import Any
from urllib.parse import unquote, urljoin, urlparse
import httpx
from pydantic import Field
from sr... | 774 | 32,185 |
Vibe-Trading | agent/src/channels/config.py | .py | """Channel config loading helpers."""
from __future__ import annotations
from pathlib import Path
from typing import Any
from src.config.loader import load_agent_config
def load_channels_config(config_path: Path | None = None) -> dict[str, Any]:
"""Load the operator IM channel config from the structured agent ... | 22 | 610 |
Vibe-Trading | agent/src/channels/wecom.py | .py | """WeCom (Enterprise WeChat) channel implementation using wecom_aibot_sdk."""
import asyncio
import base64
import hashlib
import importlib.util
import os
import re
from collections import OrderedDict
from pathlib import Path
from typing import Any
from pydantic import Field
from src.channels.bus.events import Outbou... | 555 | 21,449 |
Vibe-Trading | agent/src/channels/base.py | .py | """Base channel interface for chat platforms."""
from __future__ import annotations
import logging
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any
from src.channels.bus.events import InboundMessage, OutboundMessage
from src.channels.bus.queue import MessageBus
from src.channels.pa... | 238 | 8,269 |
Vibe-Trading | agent/src/channels/pairing/store.py | .py | """Pairing store for DM sender approval.
Persistent storage at ``~/.vibe-trading/pairing.json`` keeps approved senders
and pending pairing codes per channel. The store is designed for
private-assistant scale: small JSON file, simple locking, no external DB.
"""
from __future__ import annotations
import json
import ... | 319 | 11,465 |
Vibe-Trading | agent/src/channels/pairing/__init__.py | .py | """Pairing module for DM sender approval."""
from src.channels.pairing.store import (
approve_code,
deny_code,
format_expiry,
format_pairing_reply,
generate_code,
get_approved,
handle_pairing_command,
is_approved,
list_pending,
revoke,
)
# Metadata keys used by channels and com... | 34 | 731 |
Vibe-Trading | agent/src/channels/bus/__init__.py | .py | """Async message bus for decoupled channel-agent communication."""
from src.channels.bus.events import InboundMessage, OutboundMessage
from src.channels.bus.queue import MessageBus
__all__ = ["InboundMessage", "OutboundMessage", "MessageBus"]
| 7 | 245 |
Vibe-Trading | agent/src/channels/bus/queue.py | .py | """Async message queue for decoupled channel-agent communication."""
import asyncio
from src.channels.bus.events import InboundMessage, OutboundMessage
class MessageBus:
"""Async message bus that decouples chat channels from the agent core.
Channels push messages to the inbound queue, and the agent process... | 44 | 1,507 |
Vibe-Trading | agent/src/channels/bus/events.py | .py | """Event types for the message bus."""
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any
# Optional OutboundMessage.metadata key for structured, channel-agnostic UI
# payloads. Value is JSON-serializable with at least ``kind``; rich clients may
# render it and ot... | 55 | 1,971 |
hosts | makeHosts.py | .py | #!/usr/bin/env python
# Script by gfyoung
# https://github.com/gfyoung
#
# This Python script will generate hosts files and update the readme file.
from __future__ import print_function
import argparse
import subprocess
import sys
def print_failure(msg):
"""
Print a failure message.
Parameters
---... | 104 | 2,702 |
hosts | updateHostsFile.py | .py | #!/usr/bin/env python3
# Script by Ben Limmer
# https://github.com/l1m5
#
# This Python script will combine all the host files you provide
# as sources into one, unique host file to keep your internet browsing happy.
import argparse
import fnmatch
import ipaddress
import json
import locale
import os
import platform
f... | 1,991 | 58,997 |
hosts | testUpdateHostsFile.py | .py | #!/usr/bin/env python
# Script by gfyoung
# https://github.com/gfyoung
#
# Python script for testing updateHostFiles.py
import json
import locale
import os
import platform
import re
import shutil
import sys
import tempfile
import unittest
import unittest.mock as mock
from io import BytesIO, StringIO
import requests
... | 2,141 | 72,066 |
hosts | updateReadme.py | .py | #!/usr/bin/env python3
# Script by Steven Black
# https://github.com/StevenBlack
#
# This Python script will update the readme files in this repo.
import json
import os
import time
from string import Template
# Project Settings
BASEDIR_PATH = os.path.dirname(os.path.realpath(__file__))
README_TEMPLATE = os.path.join... | 124 | 4,314 |
nuwa-skill | scripts/quality_check.py | .py | #!/usr/bin/env python3
"""
自动检查生成的SKILL.md是否通过Phase 4质量标准。
对照通过标准表格逐项检查,输出通过/不通过和具体原因。
用法:
python3 quality_check.py <SKILL.md路径>
示例:
python3 quality_check.py .claude/skills/elon-musk-perspective/SKILL.md
"""
import sys
import re
from pathlib import Path
def check_mental_models(content: str) -> tuple[bool, ... | 153 | 5,677 |
nuwa-skill | scripts/srt_to_transcript.py | .py | #!/usr/bin/env python3
"""
将SRT/VTT字幕文件清洗为干净的纯文本transcript。
去除时间戳、序号、重复行、HTML标签,输出可直接阅读的文本。
用法:
python3 srt_to_transcript.py input.srt [output.txt]
python3 srt_to_transcript.py input.vtt [output.txt]
如果不指定输出文件,默认输出到 input_transcript.txt
"""
import sys
import re
from pathlib import Path
def clean_srt(conten... | 109 | 3,115 |
nuwa-skill | scripts/merge_research.py | .py | #!/usr/bin/env python3
"""
合并6个Agent的调研结果,生成Phase 1.5调研Review检查点的摘要表格。
扫描 references/research/ 目录下的01-06 md文件,统计每个维度的来源数量、
一手/二手占比、关键发现。
用法:
python3 merge_research.py <skill目录路径>
示例:
python3 merge_research.py .claude/skills/elon-musk-perspective
输出: 打印markdown格式的摘要表格到stdout
"""
import sys
import re
from pat... | 151 | 5,609 |
nuwa-skill | examples/mrbeast-perspective/scripts/analyze_titles.py | .py | #!/usr/bin/env python3
"""
analyze_titles.py - 分析YouTube频道视频标题模式
分析维度:
- 标题长度分布
- 数字使用频率与类型
- 高频词汇(去除停用词)
- 标题公式分类(挑战型/数字型/悬念型/对比型/情感型)
- 标点符号与大写模式
用法:
python analyze_titles.py titles.txt
python analyze_titles.py titles.txt -o report.md
python analyze_titles.py titles.txt --top 30
输入格式: 纯文本文件,每行一个标题
... | 274 | 11,004 |
nuwa-skill | examples/mrbeast-perspective/scripts/thumbnail_audit.py | .py | #!/usr/bin/env python3
"""
thumbnail_audit.py - 基于MrBeast缩略图理论的检查清单脚本
检查维度(基于MrBeast公开分享的缩略图原则):
1. 标题与缩略图互补性:是否「互补而非重复」?
2. 焦点数量:是否只有1-2个视觉焦点?
3. 文字量:缩略图文字是否少于5个词?
4. 情绪表达:是否有明确的面部表情/情绪?
5. 颜色对比:颜色对比是否足够醒目?
如果提供了图片文件,会用PIL分析颜色分布和亮度对比。
用法:
python thumbnail_audit.py --title "I Spent 50 Hours Buried Alive"... | 354 | 14,560 |
nuwa-skill | examples/mrbeast-perspective/scripts/retention_curve_checker.py | .py | #!/usr/bin/env python3
"""
retention_curve_checker.py - 基于MrBeast方法论的视频脚本retention检查器
检查维度(基于MrBeast公开分享的retention理论):
1. 前30秒hook:是否有明确的hook抓住观众?
2. Re-engagement moments:每3-5分钟是否有升级/转折?
3. 结尾CTA/悬念:结尾是否有行动号召或悬念?
4. Boring parts:是否有长段落无动作的「死区」?
5. 递进结构:内容是否持续升级(MrBeast的核心理念)
用法:
python retention_curve_ch... | 389 | 15,396 |
algo | library/x25519_pubkey.py | .py | #!/usr/bin/python
# x25519_pubkey.py - Ansible module to derive a base64-encoded WireGuard-compatible public key
# from a base64-encoded 32-byte X25519 private key.
#
# Why: community.crypto does not provide raw public key derivation for X25519 keys.
import base64
from ansible.module_utils.basic import AnsibleModule... | 133 | 4,748 |
algo | library/gcp_compute_location_info.py | .py | #!/usr/bin/python
import json
from ansible.module_utils.gcp_utils import GcpModule, GcpSession, navigate_hash
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {"metada... | 92 | 2,682 |
algo | library/scaleway_compute.py | .py | #!/usr/bin/python
#
# Scaleway Compute management module
#
# Copyright (C) 2018 Online SAS.
# https://www.scaleway.com
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {"metadata_version": "1.1", "status": ["preview"], "supported_by": "community"}
DOCU... | 684 | 23,737 |
algo | library/lightsail_region_facts.py | .py | #!/usr/bin/python
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {"metadata_version": "1.1", "status": ["preview"], "supported_by": "community"}
DOCUMENTATION = """
---
module: lightsail_region_facts
short_description: Gath... | 103 | 2,700 |
algo | tests/test_cloud_init_template.py | .py | #!/usr/bin/env python3
"""
Cloud-init template validation test.
This test validates that the cloud-init template for DigitalOcean deployments
renders correctly and produces valid YAML that cloud-init can parse.
This test helps prevent regressions like issue #14800 where YAML formatting
issues caused cloud-init to fai... | 261 | 8,505 |
algo | tests/validate_jinja2_templates.py | .py | #!/usr/bin/env python3
"""
Validate all Jinja2 templates in the Algo codebase.
This script checks for:
1. Syntax errors (including inline comments in expressions)
2. Undefined variables
3. Common anti-patterns
"""
import re
import sys
from pathlib import Path
from jinja2 import Environment, FileSystemLoader, StrictUn... | 257 | 8,766 |
algo | tests/test_package_preinstall.py | .py | #!/usr/bin/env python3
import unittest
from jinja2 import Template
class TestPackagePreinstall(unittest.TestCase):
def setUp(self):
"""Set up test fixtures."""
# Create a simplified test template with just the packages section
self.packages_template = Template("""
packages:
- sudo
{% i... | 79 | 3,008 |
algo | tests/conftest.py | .py | """Shared pytest fixtures for Algo VPN tests."""
import base64
import secrets
import sys
import tempfile
from pathlib import Path
import pytest
import yaml
# Add library directory to path for custom module imports
sys.path.insert(0, str(Path(__file__).parent.parent / "library"))
@pytest.fixture
def test_variables(... | 152 | 4,188 |
algo | tests/integration/ansible-service-wrapper.py | .py | #!/usr/bin/env python3
"""
Wrapper for Ansible's service module that always succeeds for known services
"""
import json
import sys
# Parse module arguments
args = json.loads(sys.stdin.read())
module_args = args.get("ANSIBLE_MODULE_ARGS", {})
service_name = module_args.get("name", "")
state = module_args.get("state",... | 58 | 1,439 |
algo | tests/integration/mock_modules/apt.py | .py | #!/usr/bin/python
# Mock apt module for Docker testing
import subprocess
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec={
"name": {"type": "list", "aliases": ["pkg", "package"]},
"state": {
"type": "str",
... | 97 | 3,680 |
algo | tests/integration/mock_modules/command.py | .py | #!/usr/bin/python
# Mock command module for Docker testing
import subprocess
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec={
"_raw_params": {"type": "str"},
"cmd": {"type": "str"},
"creates": {"type": "path"},
... | 81 | 2,841 |
algo | tests/integration/mock_modules/shell.py | .py | #!/usr/bin/python
# Mock shell module for Docker testing
import subprocess
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec={
"_raw_params": {"type": "str"},
"cmd": {"type": "str"},
"creates": {"type": "path"},
... | 76 | 2,426 |
algo | tests/unit/test_template_rendering.py | .py | #!/usr/bin/env python3
"""
Test that Ansible templates render correctly
This catches undefined variables, syntax errors, and logic bugs
"""
import os
import sys
from pathlib import Path
from jinja2 import Environment, FileSystemLoader, StrictUndefined, TemplateSyntaxError, UndefinedError
# Add parent directory to pa... | 349 | 11,817 |
algo | tests/unit/test_strongswan_templates.py | .py | #!/usr/bin/env python3
"""
Enhanced tests for StrongSwan templates.
Tests all strongswan role templates with various configurations.
"""
import os
import sys
import uuid
from jinja2 import Environment, FileSystemLoader, StrictUndefined
# Add parent directory to path for fixtures
sys.path.insert(0, os.path.dirname(os... | 331 | 11,880 |
algo | tests/unit/test_list_servers.py | .py | """Tests for scripts/list_servers.py."""
import importlib.util
import json
import subprocess
import sys
from pathlib import Path
import pytest
# Load list_servers module from scripts/ (not a Python package)
_script = Path(__file__).resolve().parents[2] / "scripts" / "list_servers.py"
_spec = importlib.util.spec_from... | 96 | 2,804 |
algo | tests/unit/test_scaleway_fix.py | .py | #!/usr/bin/env python3
"""
Test Scaleway role fixes for issue #14846
This test validates that:
1. The Scaleway role uses the modern 'project' parameter instead of deprecated 'organization'
2. The Marketplace API is used for image lookup instead of the broken scaleway_image_info module
3. The prompts include organizati... | 137 | 4,795 |
algo | tests/unit/test_ansible_12_boolean_fix.py | .py | #!/usr/bin/env python3
"""
Test that verifies the fix for Ansible 12.0.0 boolean type checking.
This test reads the actual YAML files to ensure they don't produce string booleans.
"""
import re
from pathlib import Path
class TestAnsible12BooleanFix:
"""Tests to verify Ansible 12.0.0 boolean compatibility."""
... | 121 | 4,830 |
algo | tests/unit/test_user_management.py | .py | #!/usr/bin/env python3
"""
Test user management functionality without deployment
Based on issues #14745, #14746, #14738, #14726
"""
import os
import re
import sys
import tempfile
import yaml
def test_user_list_parsing():
"""Test that user lists in config.cfg are parsed correctly"""
test_config = """
users:
... | 205 | 6,206 |
algo | tests/unit/test_destroy.py | .py | """Tests for the destroy playbook and provider destroy task files."""
import os
import subprocess
import yaml # type: ignore[import-untyped]
PROVIDERS = [
"digitalocean",
"ec2",
"lightsail",
"azure",
"gce",
"hetzner",
"vultr",
"scaleway",
"openstack",
"cloudstack",
"linod... | 203 | 6,786 |
algo | tests/unit/test_yaml_jinja2_expressions.py | .py | #!/usr/bin/env python3
"""
Test that Jinja2 expressions within YAML files are valid.
This catches issues like inline comments in Jinja2 expressions within YAML task files.
"""
import re
from pathlib import Path
import pytest
import yaml
from jinja2 import Environment, StrictUndefined, TemplateSyntaxError
def find_y... | 399 | 15,798 |
algo | tests/unit/test_boolean_variables.py | .py | #!/usr/bin/env python3
"""
Test that Ansible variables produce proper boolean types, not strings.
This prevents issues with Ansible 12.0.0's strict type checking.
"""
import jinja2
def render_template(template_str, variables=None):
"""Render a Jinja2 template with given variables."""
env = jinja2.Environment... | 121 | 5,512 |
algo | tests/unit/test_wireguard_key_generation.py | .py | #!/usr/bin/env python3
"""
Test WireGuard key generation - focused on x25519_pubkey module integration
Addresses test gap identified in tests/README.md line 63-67: WireGuard private/public key generation
"""
import base64
import os
import subprocess
import sys
import tempfile
# Add library directory to path to import... | 350 | 11,266 |
algo | tests/unit/test_iptables_rules.py | .py | #!/usr/bin/env python3
"""
Test iptables rules logic for VPN traffic routing.
These tests verify that the iptables rules templates generate correct
NAT rules for both WireGuard and IPsec VPN traffic.
"""
from pathlib import Path
import pytest
from jinja2 import Environment, FileSystemLoader
def _ansible_bool(value... | 257 | 9,005 |
algo | tests/unit/test_config_validation.py | .py | #!/usr/bin/env python3
"""
Test configuration file validation without deployment
"""
import configparser
import os
import re
import subprocess
import sys
import tempfile
def test_wireguard_config_format():
"""Test that we can validate WireGuard config format"""
# Sample minimal WireGuard config
sample_co... | 153 | 4,677 |
algo | tests/unit/test_double_templating.py | .py | """
Test to detect double Jinja2 templating issues in YAML files.
This test prevents Ansible 12+ errors from embedded templates in Jinja2 expressions.
The pattern `{{ lookup('file', '{{ var }}') }}` is invalid and must be
`{{ lookup('file', var) }}` instead.
Issue: https://github.com/trailofbits/algo/issues/14835
"""... | 142 | 4,909 |
algo | tests/unit/test_lightsail_boto3_fix.py | .py | #!/usr/bin/env python
"""
Test for AWS Lightsail boto3 parameter fix.
Verifies that get_aws_connection_info() works without the deprecated boto3 parameter.
Addresses issue #14822.
"""
import importlib.util
import os
import sys
import unittest
from unittest.mock import MagicMock, patch
# Add the library directory to t... | 169 | 6,792 |
algo | tests/unit/test_generated_configs.py | .py | #!/usr/bin/env python3
"""
Test that generated configuration files have valid syntax
This validates WireGuard, StrongSwan, SSH, and other configs
"""
import re
import subprocess
import sys
def check_command_available(cmd):
"""Check if a command is available on the system"""
try:
subprocess.run([cmd, ... | 389 | 12,402 |
algo | tests/unit/test_docker_localhost_deployment.py | .py | #!/usr/bin/env python3
"""
Simplified Docker-based localhost deployment tests
Verifies services can start and config files exist in expected locations
"""
import os
import subprocess
import sys
def check_docker_available():
"""Check if Docker is available"""
try:
result = subprocess.run(["docker", "-... | 172 | 4,651 |
algo | tests/unit/test_basic_sanity.py | .py | #!/usr/bin/env python3
"""
Basic sanity tests for Algo VPN that don't require deployment
"""
import os
import subprocess
import sys
import yaml
def test_python_version():
"""Ensure we're running on Python 3.11+"""
assert sys.version_info >= (3, 11), f"Python 3.11+ required, got {sys.version}"
print("✓ P... | 126 | 4,215 |
algo | tests/unit/test_cloud_provider_configs.py | .py | #!/usr/bin/env python3
"""
Test cloud provider instance type configurations.
Validates config.cfg against known-deprecated instance types that will fail
at deployment time. Based on issue #14730 (Hetzner cx->cpx migration).
Why not regex format validation? Providers constantly add new instance families
(AWS m7.*, g5.... | 87 | 3,213 |
algo | tests/unit/test_comprehensive_boolean_scan.py | .py | #!/usr/bin/env python3
"""
Test suite to prevent Ansible 12+ boolean type errors in Algo VPN codebase.
Background:
-----------
Ansible 12.0.0 introduced strict boolean type checking that breaks deployments
when string values like "true" or "false" are used in conditionals. This causes
errors like: "Conditional result ... | 313 | 13,679 |
algo | tests/unit/test_openssl_compatibility.py | .py | #!/usr/bin/env python3
"""
Test PKI certificate validation for Ansible-generated certificates
Hybrid approach: validates actual certificates when available, else tests templates/config
Based on issues #14755, #14718 - Apple device compatibility
Issues #75, #153 - Security enhancements (name constraints, EKU restriction... | 577 | 24,226 |
algo | tests/fixtures/__init__.py | .py | """Test fixtures for Algo unit tests"""
from pathlib import Path
import yaml
def load_test_variables():
"""Load test variables from YAML fixture"""
fixture_path = Path(__file__).parent / "test_variables.yml"
with open(fixture_path) as f:
return yaml.safe_load(f)
def get_test_config(overrides=N... | 21 | 487 |
algo | scripts/list_servers.py | .py | #!/usr/bin/env python3
"""List deployed Algo VPN servers as JSON."""
import json
import sys
from pathlib import Path
import yaml
def list_servers(configs_dir: Path) -> list[dict]:
"""Scan configs directory for deployed server metadata."""
servers = []
for config_file in sorted(configs_dir.glob("*/.confi... | 35 | 832 |
algo | scripts/track-test-effectiveness.py | .py | #!/usr/bin/env python3
"""
Track test effectiveness by analyzing CI failures and correlating with issues/PRs
This helps identify which tests actually catch bugs vs just failing randomly
"""
import json
import subprocess
from collections import defaultdict
from datetime import datetime, timedelta
from pathlib import Pa... | 227 | 8,156 |
PythonRobotics | Localization/extended_kalman_filter/extended_kalman_filter.py | .py | """
Extended kalman filter (EKF) localization sample
author: Atsushi Sakai (@Atsushi_twi)
"""
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent.parent))
import math
import matplotlib.pyplot as plt
import numpy as np
from utils.plot import plot_covariance_ellipse
# Covariance for ... | 191 | 4,279 |
PythonRobotics | Localization/extended_kalman_filter/ekf_with_velocity_correction.py | .py | """
Extended kalman filter (EKF) localization with velocity correction sample
author: Atsushi Sakai (@Atsushi_twi)
modified by: Ryohei Sasaki (@rsasaki0109)
"""
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent.parent))
import math
import matplotlib.pyplot as plt
import numpy as np... | 199 | 5,131 |
PythonRobotics | Localization/ensemble_kalman_filter/ensemble_kalman_filter.py | .py | """
Ensemble Kalman Filter(EnKF) localization sample
author: Ryohei Sasaki(rsasaki0109)
Reference:
Ensemble Kalman filtering
(https://rmets.onlinelibrary.wiley.com/doi/10.1256/qj.05.135)
"""
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent.parent))
import math
import matplotlib.py... | 247 | 6,638 |
PythonRobotics | Localization/histogram_filter/histogram_filter.py | .py | """
Histogram Filter 2D localization example
In this simulation, x,y are unknown, yaw is known.
Initial position is not needed.
author: Atsushi Sakai (@Atsushi_twi)
"""
import copy
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from scipy.ndimage import gaussian_filter
f... | 266 | 7,193 |
PythonRobotics | Localization/cubature_kalman_filter/cubature_kalman_filter.py | .py | """
Cubature Kalman filter using Constant Turn Rate and Velocity (CTRV) model
Fuse sensor data from IMU and GPS to obtain accurate position
https://ieeexplore.ieee.org/document/4982682
Author: Raghuram Shankar
state matrix: 2D x-y position, yaw, velocity and yaw rate
measurement matrix: ... | 247 | 8,236 |
PythonRobotics | Localization/particle_filter/particle_filter.py | .py | """
Particle Filter localization sample
author: Atsushi Sakai (@Atsushi_twi)
"""
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent.parent))
import math
import matplotlib.pyplot as plt
import numpy as np
from utils.angle import rot_mat_2d
# Estimation parameter of PF
Q = np.diag([... | 264 | 6,776 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.