text stringlengths 185 73.3k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 7
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
"""Schwab market metrics provider.
Schwab's API provides some fundamental data but not a dedicated
IV rank endpoint. This provider fetches what Schwab offers natively
and computes IV rank approximations from available data.
"""
from __future__ import annotations
import logging
from income_desk.broker.base import Ma... | nitinblue/income-desk | income_desk/broker/schwab/metrics.py | .py | 783f2663ea610961 | 7.63 | 17 |
"""TastyTrade broker integration — optional sub-package.
Requires ``tastytrade`` SDK: ``pip install tastytrade-sdk``
Usage::
from income_desk.broker.tastytrade import connect_tastytrade
market_data, metrics, account = connect_tastytrade()
ma = MarketAnalyzer(data_service=DataService(),
... | nitinblue/income-desk | income_desk/broker/tastytrade/__init__.py | .py | bc979a28d0cca8cd | 7.63 | 17 |
"""TastyTrade account balance and positions — real data from broker."""
from __future__ import annotations
import asyncio
import logging
import re
from datetime import date
from typing import TYPE_CHECKING
from income_desk.broker.base import AccountProvider
from income_desk.models.quotes import AccountBalance, Broke... | nitinblue/income-desk | income_desk/broker/tastytrade/account.py | .py | 1d15767cbcef0973 | 7.63 | 17 |
"""DXLink streaming utilities — extracted from market_data.py.
Low-level DXLink fetch functions that open a single streamer connection,
subscribe to events, collect results, and return clean dicts. Each function
handles its own timeout and error classification.
Timeouts match eTrading's proven tastytrade_adapter.py:
... | nitinblue/income-desk | income_desk/broker/tastytrade/dxlink.py | .py | f15fb69d35182bad | 7.63 | 17 |
"""TastyTrade market data — DXLink streaming for quotes and Greeks.
Adapted from eTrading tastytrade_adapter.py.
Uses DXLinkStreamer exactly as implemented in cotrader.
DXLink streaming patterns, timeouts, and symbol formats are copied
from the proven eTrading adapter to ensure consistency.
All DXLink logic lives in... | nitinblue/income-desk | income_desk/broker/tastytrade/market_data.py | .py | 2e7c80a8949433d8 | 7.63 | 17 |
"""TastyTrade market metrics — IV rank, IV percentile, beta, liquidity.
Adapted from eTrading tastytrade_adapter.py get_market_metrics().
"""
from __future__ import annotations
import asyncio
import logging
import math
from decimal import Decimal
from typing import TYPE_CHECKING
from income_desk.broker.base import ... | nitinblue/income-desk | income_desk/broker/tastytrade/metrics.py | .py | b0714a2efd651fc0 | 7.63 | 17 |
"""TastyTrade session — auth from env vars (preferred) or YAML.
Env var convention (same as eTrading .env):
TASTYTRADE_CLIENT_SECRET_LIVE / TASTYTRADE_REFRESH_TOKEN_LIVE
TASTYTRADE_CLIENT_SECRET_PAPER / TASTYTRADE_REFRESH_TOKEN_PAPER
TASTYTRADE_CLIENT_SECRET_DATA / TASTYTRADE_REFRESH_TOKEN_DATA (DXLink)
"... | nitinblue/income-desk | income_desk/broker/tastytrade/session.py | .py | 00a7b465c65efc0e | 7.63 | 17 |
"""Streamer symbol utilities — conversion between formats.
DXLink streamer symbol format: ``.{TICKER}{YYMMDD}{C|P}{STRIKE}``
e.g. ``.SPY260320P580``
OCC format: ``{TICKER:6}{YYMMDD}{C|P}{STRIKE*1000:08d}``
e.g. ``SPY 260320P00580000``
Same conventions as eTrading ``tastytrade_adapter.py``.
"""
from __future__... | nitinblue/income-desk | income_desk/broker/tastytrade/symbols.py | .py | a541605af3850802 | 7.63 | 17 |
"""TastyTrade watchlist provider — pull tickers from broker watchlists.
Uses the tastytrade SDK's PrivateWatchlist and PublicWatchlist classes
to fetch user-curated ticker lists for screening.
Also supports creating/updating watchlists via API and fetching
the full equity universe for filtering.
"""
from __future__ ... | nitinblue/income-desk | income_desk/broker/tastytrade/watchlist.py | .py | 315f14ad4ea09047 | 7.63 | 17 |
"""Zerodha (Kite Connect) broker integration for India NSE/BSE markets.
Provides live option quotes, chain data, account balance, and instrument
lookup for all NSE F&O instruments via Kite Connect REST API.
Credentials: API key + daily access token (OAuth2 flow).
- Standalone: load from zerodha_credentials.yaml
- Saa... | nitinblue/income-desk | income_desk/broker/zerodha/__init__.py | .py | 1eb38b0e3d386c9f | 7.63 | 17 |
"""Zerodha (Kite Connect) market data provider.
Provides live option quotes, chains, Greeks (computed), and intraday data
for NSE/BSE markets via Kite Connect REST API.
Credentials: API key + daily access token.
- Standalone: load from zerodha_credentials.yaml
- SaaS: eTrading passes pre-authenticated KiteConnect ses... | nitinblue/income-desk | income_desk/broker/zerodha/market_data.py | .py | 5f349cac4f40c375 | 7.63 | 17 |
"""Zerodha watchlist provider — uses holdings + positions as proxy.
Kite Connect doesn't have a native watchlist API.
We use portfolio holdings and F&O positions as "watchlist" sources.
For curated universes, use MarketRegistry.get_universe() instead.
"""
from __future__ import annotations
import logging
from incom... | nitinblue/income-desk | income_desk/broker/zerodha/watchlist.py | .py | f38da8a4c9e87dd3 | 7.63 | 17 |
#!/usr/bin/env python3
"""kimi-usage: status line auto-setup, run by the plugin's SessionStart hook.
The kimi-code plugin manifest cannot declare a [status_line] command, so
this hook merges one into <KIMI_CODE_HOME>/tui.toml:
- idempotent: our managed block (delimited by marker comments) is created
once and refres... | YD-233/kimi-usage | scripts/setup_statusline.py | .py | b3f37e0836ef71df | 7.62 | 16 |
"""phase2: worker_jobs table, explanation cache, ingestion_jobs error_message
Revision ID: 0002_phase2
Revises: 0001_initial
Create Date: 2026-03-12 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from alembic import op
revision: str = "0002_p... | LAA-Software-Engineering/raglogs | migrations/versions/0002_phase.py | .py | 1ec02f4d006286f1 | 7.42 | 6 |
"""source provenance: source_adapter/source_ref on ingestion_jobs + log_entries
Revision ID: 0003_source_provenance
Revises: 0002_phase2
Create Date: 2026-08-16 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "0003_source_provenance"
down_revision... | LAA-Software-Engineering/raglogs | migrations/versions/0003_source_provenance.py | .py | ebb6a2489f058e4a | 7.42 | 6 |
"""api_keys table for hashed HTTP API credentials
Revision ID: 0004_api_keys
Revises: 0003_source_provenance
Create Date: 2026-08-17 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from alembic import op
revision: str = "0004_api_keys"
down_r... | LAA-Software-Engineering/raglogs | migrations/versions/0004_api_keys.py | .py | 1dfaf233d99fcbb7 | 7.42 | 6 |
"""per-key webhook signing secret on api_keys
Revision ID: 0006_api_key_webhook_secret
Revises: 0005_ingest_modes
Create Date: 2026-08-17 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "0006_api_key_webhook_secret"
down_revision: Union[str, Non... | LAA-Software-Engineering/raglogs | migrations/versions/0006_api_key_webhook_secret.py | .py | 219c11547c933386 | 7.42 | 6 |
"""cluster embeddings table and ANN indexes on vector columns
Revision ID: 0009_cluster_embeddings
Revises: 0008_scope_isolation
Create Date: 2026-08-17 00:00:00.000000
Adds ``cluster_embeddings`` keyed by ``(scope, fingerprint)`` so similar-incident
search can look up historical cluster templates. Creates an ANN ind... | LAA-Software-Engineering/raglogs | migrations/versions/0009_cluster_embeddings.py | .py | 51ba37c7884db8e2 | 7.42 | 6 |
"""retention: CASCADE FKs, scope_retention, scope on cluster_runs/explanations
Revision ID: 0010_retention
Revises: 0009_cluster_embeddings
Create Date: 2026-08-17 00:00:00.000000
Raw purge deletes ``log_entries``; ``log_embeddings`` and ``cluster_members``
follow via ON DELETE CASCADE. Cluster summaries/embeddings s... | LAA-Software-Engineering/raglogs | migrations/versions/0010_retention.py | .py | e33824b712846403 | 7.42 | 6 |
"""api_keys.config_json for per-key query override defaults (G14)
Revision ID: 0011_api_key_config
Revises: 0010_retention
Create Date: 2026-08-17 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from alembic import op
revision: str = "0011_a... | LAA-Software-Engineering/raglogs | migrations/versions/0011_api_key_config.py | .py | 82b3f5af87de96f1 | 7.42 | 6 |
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Iterable, Iterator, Optional, Protocol, runtime_checkable
@dataclass
class SourceSpec:
"""What integrators send instead of file paths — identifies an adapter and its params."""
adapter: str
params: dict[str, An... | LAA-Software-Engineering/raglogs | src/adapters/base.py | .py | 90bc749fd0125c29 | 7.42 | 6 |
import os
from pathlib import Path
from typing import Generator, Iterable, Iterator, Optional
from src.adapters.base import LogStreamRef, RawLogLine, SourceSpec, TimeWindow
def discover_files(paths: list[str], recursive: bool = False) -> list[Path]:
"""
Discover all files from a list of paths (files or direc... | LAA-Software-Engineering/raglogs | src/adapters/file/adapter.py | .py | 1a8c17805cdc3774 | 7.42 | 6 |
"""Warn (or refuse) when the API binds off-loopback with authentication disabled."""
from __future__ import annotations
from typing import Any
LOOPBACK_HOSTS: frozenset[str] = frozenset({"127.0.0.1", "::1", "localhost"})
class InsecureBindError(RuntimeError):
"""Raised when AUTH_REFUSE_INSECURE_BIND is set and... | LAA-Software-Engineering/raglogs | src/api/auth/bind_guard.py | .py | 3e1c80f4e63fd266 | 7.42 | 6 |
"""Argon2-hashed API keys. Plaintext is never stored or logged."""
from __future__ import annotations
import secrets
import uuid
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Sequence
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerifyMis... | LAA-Software-Engineering/raglogs | src/api/auth/keys.py | .py | 6ab573b400345ded | 7.42 | 6 |
"""Route → allowed role mapping.
`admin` is included in every non-exempt set. Scope isolation (G8) is enforced
in ``src.api.auth.scope`` and query filters, not in this role map.
A leading `/v1` or `/v2` (any `/v<digits>`) is stripped before matching, so
`POST /v1/ingestions` uses the same roles as `POST /ingestions`.... | LAA-Software-Engineering/raglogs | src/api/auth/roles.py | .py | a01409e383cdd63b | 7.42 | 6 |
"""Resolve the isolation scope for an HTTP request (G8).
Service requests always end with a non-empty scope, or ``400 SCOPE_REQUIRED``.
Pinned API keys (and OIDC principals) cannot switch to another scope.
"""
from __future__ import annotations
from typing import Optional
from fastapi import Request
from starlette.... | LAA-Software-Engineering/raglogs | src/api/auth/scope.py | .py | 9f4f06a439442a9a | 7.42 | 6 |
"""Mark unversioned ingest/query/config aliases as deprecated.
Canonical routes live under ``/v1/``. Unversioned ``/ingestions``, ``/query``,
and ``/config`` stay mounted for one release and send ``Deprecation: true``
plus a ``Link`` successor-version header. Health, the web UI, and ``/static``
are not deprecated.
"""... | LAA-Software-Engineering/raglogs | src/api/deprecation.py | .py | 6b033bf2a568a2f8 | 7.42 | 6 |
"""Per-API-key token-bucket rate limiting for ingest and query routes (G9).
Buckets are in-memory and per process — they are not shared across
uvicorn workers or hosts. Identity is ``request.state.auth_principal.key_id``
when present; otherwise ``\"anonymous\"`` (including AUTH_ENABLED=false).
``RATELIMIT_INGEST_RPS`... | LAA-Software-Engineering/raglogs | src/api/ratelimit.py | .py | 9b362943beb7805d | 7.42 | 6 |
#!/usr/bin/env python3
import os
import re
import sys
class DocValidator:
"""Statically validates markdown files, checking links, hierarchy, and absolute leaks."""
def __init__(self, workspace_path: str):
self.workspace_path = workspace_path
self.errors = []
self.total_checked = 0
... | jggomez/expert-ai-developer-skills | plugins/docs-and-quality/skills/documentation-expert/scripts/validate_docs.py | .py | 58a9d7f01b1688dc | 7.52 | 10 |
#!/usr/bin/env python3
import os
import re
import sys
class GherkinValidator:
"""Statically analyzes Gherkin .feature files for structural correctness."""
def __init__(self, workspace_path: str):
self.workspace_path = workspace_path
self.errors = []
self.total_checked = 0
def ... | jggomez/expert-ai-developer-skills | plugins/docs-and-quality/skills/testing-expert/scripts/validate_gherkin.py | .py | 8d471104df6302a0 | 8.02 | 10 |
#!/usr/bin/env python3
import json
import logging
import os
import subprocess
import sys
from datetime import datetime
# Setup logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[logging.StreamHandler(sys.stdout)]
)
class PullRequestAuditor:
"""... | jggomez/expert-ai-developer-skills | plugins/multi-agent-ops/skills/loop-engineering/scripts/pr_cron_reviewer.py | .py | 071bb8daf959705b | 7.52 | 10 |
#!/usr/bin/env python3
import os
import sys
import json
import re
from datetime import date
def walk_tree(root_dir, max_depth=3):
"""Generates a tree map of the repository up to max_depth."""
ignore_dirs = {
'.git', 'node_modules', '__pycache__', '.venv', 'venv', 'env',
'.gemini', '.pytest_cach... | jggomez/expert-ai-developer-skills | plugins/multi-agent-ops/skills/repo-research/scripts/repo_analyzer.py | .py | 550daf25cbcf5566 | 7.52 | 10 |
#!/usr/bin/env python3
import os
import sys
from datetime import date
def generate_sdd(title, status="Draft"):
# Clean up title for filename
clean_title = "".join(c if c.isalnum() or c in (" ", "-", "_") else "" for c in title)
kebab_title = clean_title.lower().replace(" ", "-").replace("_", "-")
... | jggomez/expert-ai-developer-skills | plugins/python-backend/skills/design-spec-expert/scripts/create_sdd.py | .py | 6b406972344d602a | 7.02 | 10 |
#!/usr/bin/env python3
import os
import sys
import re
import time
import tracemalloc
import importlib.util
# Regex patterns for finding potential performance issues in code
PERF_PATTERNS = {
"N+1 Query Risk (Database query inside loop)": r"(?s)(for|while)\b.*?:\s*.*?\b(db|session|cursor|conn|query|execute|select|u... | jggomez/expert-ai-developer-skills | plugins/python-backend/skills/performance-scalability/scripts/measure_performance.py | .py | 14b998e602bdcb97 | 7.52 | 10 |
#!/usr/bin/env python3
import os
import sys
import subprocess
def detect_and_run_tests(root_dir="."):
"""Detects the test suite runner and runs the project's tests."""
print(f"Detecting test suite in {os.path.abspath(root_dir)}...")
# 1. Node.js (package.json)
pkg_json = os.path.join(root_dir, "pa... | jggomez/expert-ai-developer-skills | plugins/python-backend/skills/refactoring-code-expert/scripts/run_tests.py | .py | 6ec1548adee940a9 | 8.02 | 10 |
#!/usr/bin/env python3
import os
import sys
import subprocess
def run_tests_with_coverage(root_dir="."):
print(f"Checking test coverage in {os.path.abspath(root_dir)}...")
# 1. Node.js project (Jest, Vitest)
pkg_json = os.path.join(root_dir, "package.json")
if os.path.exists(pkg_json):
pri... | jggomez/expert-ai-developer-skills | plugins/python-backend/skills/test-driven-development/scripts/verify_tests.py | .py | 561fa4fafd5833f9 | 7.02 | 10 |
#!/usr/bin/env python3
import os
import sys
import time
import subprocess
import logging
# Setup logging
log_file = "workspace_daemon.log"
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler(log_file),
logging.StreamHandl... | jggomez/expert-ai-developer-skills | sidecars/workspace-daemon/daemon_monitor.py | .py | 918c771008df4866 | 7.52 | 10 |
import os
import re
import pytest
def test_skills_trigger_coverage(skills_dirs):
"""Verifies that all skills contain descriptive triggers in their descriptions for AI selection."""
assert len(skills_dirs) > 0, "No skills found to evaluate!"
missing_triggers = []
for skill_dir in skills_dirs:
... | jggomez/expert-ai-developer-skills | tests/behavioral/test_skills_behavioral.py | .py | b21db0d603b71f9f | 8.02 | 10 |
import os
import pytest
import yaml
WORKSPACE_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
@pytest.fixture
def workspace_root():
return WORKSPACE_ROOT
@pytest.fixture
def skills_dirs():
"""Returns a list of all absolute paths to skill directories in both /skills and /plugins."""
... | jggomez/expert-ai-developer-skills | tests/conftest.py | .py | e9238080f23b2a5d | 8.02 | 10 |
import os
import re
import pytest
import yaml
def parse_frontmatter(file_path):
"""Parses YAML frontmatter from a SKILL.md file."""
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
pattern = r"^---\s*\n(.*?)\n---\s*\n"
match = re.search(pattern, content, re.DOTALL)
... | jggomez/expert-ai-developer-skills | tests/structure/test_skills_structure.py | .py | 26142a505affb70a | 8.02 | 10 |
"""Un-pruned raw DNSBL corpus generator for the ADR-06 Phase-1 spike.
ADR-06 moves parse -> normalise -> classify -> build into the Python plugin and
*drops* the build-time list optimisations (dedup, subdomain collapse, user/TOP1M
whitelist removal). The realistic init load is therefore the **un-pruned** raw
feed text... | pfBlockerNG/pfBlockerNG | legacy/benchmarks/_corpus_raw.py | .py | 77cd23d6a030c43b | 7.64 | 18 |
"""Memory comparison: pre-ADR flat dicts vs post-ADR domain trie.
Run with: python -m pytest benchmarks/test_memory.py -s
(`-s` so the report table is printed.)
Two metrics, two tools:
* Retained footprint (primary) — ``pympler.asizeof``. Deep object-graph size:
follows every reference (dict tables, key/label str... | pfBlockerNG/pfBlockerNG | legacy/benchmarks/test_memory.py | .py | 7b5ff59f722c319b | 8.14 | 18 |
"""Real paths out of git's C-quoted output.
git wraps a path in double quotes and C-escapes it whenever the path holds a
double quote, a backslash or a control byte. That quoting is unconditional:
``core.quotePath`` only governs whether HIGH-BIT bytes are escaped too. Every
changed-file gate in this repo classifies a ... | pfBlockerNG/pfBlockerNG | scripts/_git_paths.py | .py | 0156dd19cd2efe22 | 7.64 | 18 |
#!/usr/bin/env python3
"""Forbid delegation-process narration in newly added code comments.
ADR phase numbers ("wired in Phase 4"), `RESULTS/` handoff refs, and review
archaeology ("review-fanout C9", "Copilot, PR #947") narrate how a change was
produced, not what the code must uphold — that evidence belongs in the AD... | pfBlockerNG/pfBlockerNG | scripts/check_comment_narration.py | .py | 5fa22ad8f6914da0 | 7.64 | 18 |
#!/usr/bin/env python3
"""Fail CI when a suite's JUnit report skips a test that is not allowlisted (issue #2359).
PROBLEM
-------
A test that no environment executes still counts toward the suite total and still
reports "OK" — #2356 found nine PHPUnit cases that had silently skipped in CI for
a year, and the only sign... | pfBlockerNG/pfBlockerNG | scripts/check_skip_allowlist.py | .py | 642c25623eb68571 | 7.64 | 18 |
#!/usr/bin/env python3
"""Keep the on/off toggle contract in the configuration registry, not in the page.
issue #2123 moved seventeen `PFB_FILTER_ON_OFF` toggle keys off the 3.2 arrangement --
default declared at the top of the page, stored vocabulary decided at the save site,
comparison written inline at the render -... | pfBlockerNG/pfBlockerNG | scripts/check_toggle_registry.py | .py | c89927d22be00918 | 7.64 | 18 |
#!/usr/bin/env python3
"""Verify the committed CodeMirror 6 vendor tree matches its pinned source.
PROBLEM
-------
pfBlockerNG is a NO_BUILD FreeBSD port: ``make package`` / build-pkg-portable.py
/ ``deploy.sh`` copy ``src/`` verbatim, so the CodeMirror 6 regex-list editor
bundle under ``src/usr/local/www/pfblockerng/... | pfBlockerNG/pfBlockerNG | scripts/check_webassets_vendor.py | .py | 8f263b54b0fbb456 | 7.64 | 18 |
#!/usr/bin/env python3
"""Fetch the ADR-49 survey corpus: the first bytes of every catalogue feed.
Walks ``src/usr/local/www/pfblockerng/pfblockerng_feeds.json`` (every ``url``
entry, primaries and alternates), fetches the first SAMPLE_BYTES of each
reachable feed ONCE, and commits the result as an offline, mockable c... | pfBlockerNG/pfBlockerNG | scripts/fetch_feed_corpus.py | .py | ae67c77c813e94f3 | 7.64 | 18 |
"""live_gate_matrix.py — pure matrix-building logic for the tagged ingestion
prepare-live-gate job (issue #2389): cross-reference what the pkg-owned stage
operation actually touched against the ci-metadata CI matrix's testable legs, so
validate-live-pages-install fans out exactly one live-VM install test per
(destinati... | pfBlockerNG/pfBlockerNG | scripts/live_gate_matrix.py | .py | a8903d6530c9fcec | 7.64 | 18 |
#!/usr/bin/env python3
"""check_top1m_providers.py -- health-check the Top1M provider URLs we ship.
Issue #884: nothing caught the Alexa Top1M source rotting silently (its
hardcoded URL died years ago; cleaned up in #877). This script gives the
weekly top1m-healthcheck.yml workflow something to fail on the day the nex... | pfBlockerNG/pfBlockerNG | scripts/misc/check_top1m_providers.py | .py | a8ec8ca035314bef | 7.64 | 18 |
#!/usr/bin/env python3
"""reconcile-plan.py — decide the daily image-reconcile actions for one channel
(issue #1823). Pure text-in/JSON-out: the box facts (gathered by
scripts/box-facts.sh from booted smoke images) and the supported-version matrix
go in; a list of actions comes out. The workflow executes them:
repub... | pfBlockerNG/pfBlockerNG | scripts/reconcile-plan.py | .py | 1d2f2aaa9f505006 | 7.64 | 18 |
"""Parse pfBlockerNG release tags and derive their canonical release metadata."""
from __future__ import annotations
import hashlib
import re
import subprocess
import sys
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Literal, Mapping, Sequence
PACKAGE = "... | pfBlockerNG/pfBlockerNG | scripts/release_version.py | .py | bef92294f36c6553 | 7.64 | 18 |
"""
在 Agent 中使用额外输入文件的示例
演示如何在自定义 Agent 中集成和使用额外输入文件。
"""
from typing import Any
from pure_auto_codeql.core.context import AnalysisContext
from pure_auto_codeql.core.pipeline import AnalysisStep
class EnhancedCVEAnalysisStep(AnalysisStep):
"""增强的 CVE 分析步骤,使用额外输入文件"""
def __init__(self):
super()... | Fruit-Guardians/PureAutoCodeql | examples/agent_with_extra_files.py | .py | 0396eeaa3de558e8 | 7.5 | 9 |
#!/usr/bin/env python3
"""
LLM 配置系统演示脚本
展示新配置系统的各种功能和用法。
"""
from pure_auto_codeql.configuration import (
get_llm_config,
LLMRole,
ProviderRegistry,
ProviderConfig,
display_providers_status,
display_provider_detail,
validate_provider,
)
def demo_basic_usage():
"""演示基本用法"""
print(... | Fruit-Guardians/PureAutoCodeql | examples/config_demo.py | .py | 1456a646a22cf736 | 7.5 | 9 |
"""
演示:如何使用 keys.toml 中定义的自定义提供商
这个脚本展示了:
1. 如何从 keys.toml 读取自定义提供商
2. 如何在代码中使用自定义提供商
3. 如何验证自定义提供商的配置
"""
import sys
from pathlib import Path
# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from pure_auto_codeql.configuration import (
ProviderRegistry,
get_llm... | Fruit-Guardians/PureAutoCodeql | examples/custom_provider_demo.py | .py | 08a05f48f3697e5f | 7.5 | 9 |
"""
额外输入文件功能 - 简单演示
展示如何使用 inputs 目录中的额外文件。
"""
from pathlib import Path
from pure_auto_codeql.utils.case import resolve_case, discover_cve_assets
def demo_basic():
"""基础演示"""
print("\n" + "=" * 80)
print("额外输入文件功能演示")
print("=" * 80 + "\n")
# 使用一个现有的案例
case_id = "CVE-2024-7099"
... | Fruit-Guardians/PureAutoCodeql | examples/simple_extra_files_demo.py | .py | fd40b824648f068a | 7.5 | 9 |
"""
额外输入文件功能使用示例
演示如何使用 inputs 目录中的额外文件来增强漏洞分析。
"""
from pathlib import Path
from pure_auto_codeql.utils.case import resolve_case, discover_cve_assets
def example_basic_usage():
"""基础使用示例"""
print("\n=== 示例 1: 基础使用 ===\n")
case_id = "CVE-2024-7099"
# 解析案例
case_paths = resolve_case(case... | Fruit-Guardians/PureAutoCodeql | examples/use_extra_input_files.py | .py | 512c226add86382f | 7.5 | 9 |
"""验证类 Agent 的共享基类。
Sink 验证与 Source 验证 Agent 的逻辑几乎完全一致,仅在“Sink/Source”标签、
模板 key、task_id 前缀以及个别提示文案上有差异。该基类把公共流程集中到一处,
子类只需声明各自的 kind / label 等类属性。集中实现也从结构上避免了两个 Agent
返回值元数(arity)不一致这类 bug 再次出现。
"""
import hashlib
import re
from datetime import datetime
from typing import TYPE_CHECKING, Callable, Optional, Tuple
fr... | Fruit-Guardians/PureAutoCodeql | pure_auto_codeql/agents/base_verification_agent.py | .py | 4b4374325efc0fde | 7.5 | 9 |
"""CodeQL 生成类 Agent 的共享基类。
历史上 codeql_gen_agents 下的每个 Agent 都各自复制了一份 `_load_prompt`、
`_fill_placeholders` 以及 agent_start / agent_complete / error 事件发射样板。
该基类把这些公共逻辑集中到一处,子类只需实现各自的 build_prompt / 业务方法。
"""
from __future__ import annotations
import logging
from datetime import datetime
from pathlib import Path
from ty... | Fruit-Guardians/PureAutoCodeql | pure_auto_codeql/agents/codeql_gen_agents/base.py | .py | 98200c5c143296ba | 7.5 | 9 |
from pathlib import Path
from typing import TYPE_CHECKING, Optional
from pure_auto_codeql.services.llm_service import AgentResult
if TYPE_CHECKING:
class MultiAgentAnalyzer:
pass
from pure_auto_codeql.utils.io import read_json_text
class CVEAnalysisAgent:
"""用于分析CVE JSON文件的Agent。"""
def __init... | Fruit-Guardians/PureAutoCodeql | pure_auto_codeql/agents/cve_analysis_agent.py | .py | 8ebc8cd3919bc953 | 7.5 | 9 |
import json
import logging
from typing import TYPE_CHECKING, Any, Dict, List
from pure_auto_codeql.services.llm_service import AgentResult
if TYPE_CHECKING:
class MultiAgentAnalyzer:
pass
from pure_auto_codeql.prompts.path_analysis_prompts import build_path_analysis_prompt
from pure_auto_codeql.services.... | Fruit-Guardians/PureAutoCodeql | pure_auto_codeql/agents/path_analysis_agent.py | .py | 56975c3a3d95e62c | 7.5 | 9 |
import json
import logging
import os
import re
from pathlib import Path
from typing import TYPE_CHECKING, List
from pydantic import ValidationError
from pure_auto_codeql.analysis_schemas import (
SourceAnalysisOutput,
normalize_source_candidate,
)
from pure_auto_codeql.services.llm_service import AgentResult
... | Fruit-Guardians/PureAutoCodeql | pure_auto_codeql/agents/unified_source_analysis_agent.py | .py | 700cdb99aa9beb64 | 7.5 | 9 |
"""API服务器配置模块"""
from __future__ import annotations
from pathlib import Path
from typing import List
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
from pure_auto_codeql.paths import get_repo_root
try:
import tomli as tomllib # Python < 3.11
except ImportError:
t... | Fruit-Guardians/PureAutoCodeql | pure_auto_codeql/api/config.py | .py | 19086493b482d3bf | 7.5 | 9 |
"""API数据模型定义"""
from __future__ import annotations
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field
class ProjectInfo(BaseModel):
"""项目基本信息"""
case_id: str = Field(..., description="项目案例ID")
path: str = Field(..., de... | Fruit-Guardians/PureAutoCodeql | pure_auto_codeql/api/models.py | .py | 61b94e2886b83b4c | 7.5 | 9 |
"""项目案例管理API路由"""
from __future__ import annotations
import json
import logging
from pathlib import Path
from typing import List, Optional
from fastapi import APIRouter, HTTPException, Query
from pure_auto_codeql.application import (
ProjectImportPolicyError,
ProjectImportPolicySettings,
import_project_... | Fruit-Guardians/PureAutoCodeql | pure_auto_codeql/api/projects_routes.py | .py | 74125dc855e892f1 | 7.5 | 9 |
"""Shared analysis workflow validation."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from pure_auto_codeql.utils.case import CasePaths, resolve_case
@dataclass(frozen=True)
class AnalysisValidationError(ValueError):
"""Validation failure for an analysis workf... | Fruit-Guardians/PureAutoCodeql | pure_auto_codeql/application/analysis.py | .py | 1871b32596c2da7b | 7.5 | 9 |
"""Shared project import workflow services."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
from pure_auto_codeql.application.project_import_policy import (
ProjectImportPolicy,
ProjectImportPolicyError,
validate_project_import_... | Fruit-Guardians/PureAutoCodeql | pure_auto_codeql/application/project_import.py | .py | 1867bdcc8f13682e | 7.5 | 9 |
"""Project import policy checks for shared workflow callers."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
class ProjectImportPolicyError(ValueError):
"""Raised when a project import request violates caller policy."""
def __init... | Fruit-Guardians/PureAutoCodeql | pure_auto_codeql/application/project_import_policy.py | .py | 44a4a4432aca733d | 7.5 | 9 |
"""
Живая консоль: что панель делает прямо сейчас.
Обычный журнал сервера лежит в systemd, и чтобы его посмотреть, нужен
доступ по ssh. Между тем девяносто процентов вопросов к панели звучат
как «она вообще работает?» и «почему эта точка до сих пор не проверена».
Ответ на них есть в журнале, и его достаточно показать.... | maximdr86/tikpilot | app/activity.py | .py | 2c8eeb05aa3b0467 | 7.45 | 7 |
"""
Команды RouterOS ровно в том виде, в каком их пишут в терминале.
Зачем понадобилось
------------------
Массовое действие «Произвольная команда» умело только синтаксис API:
путь через слэши и параметры отдельными строками. Это не то, что человек
держит в голове и не то, что лежит у него в шпаргалке. Из Winbox, с ф... | maximdr86/tikpilot | app/cli.py | .py | 05bf85b5412ba9a8 | 7.45 | 7 |
"""
Работа с текстовыми экспортами конфигураций: сравнение и поиск.
Две задачи, ради которых бэкапы вообще стоит хранить дольше одного дня:
* **что изменилось.** Сравнение двух копий одной точки отвечает на вопрос
«конфиг трогали?» и показывает, что именно. После аварии это первое,
что хочется увидеть;
* **где ещ... | maximdr86/tikpilot | app/configdiff.py | .py | f628cadcb618fb71 | 7.45 | 7 |
"""
Место на диске самой панели.
Зачем
-----
Панель следит за полусотней роутеров и однажды не уследила за собой:
диск сервера кончился, SQLite перестала писать, приём журнала встал,
а сводка в Телеграм ушла шестьдесят раз подряд, потому что отметку
об отправке тоже некуда было записать. Место при этом кончалось не
в... | maximdr86/tikpilot | app/disk.py | .py | 7ba3d7538627680d | 7.45 | 7 |
"""
Пинг с сервера панели: второе мнение о недоступной точке.
Зачем
-----
Доступность у панели означает «отвечает API»: она стучится на 8728,
и это правильный вопрос, потому что через API она и работает. Но у
этого ответа есть неприятная двусмысленность. «Оффлайн» одинаково
выглядит и когда площадку обесточили, и ког... | maximdr86/tikpilot | app/icmp.py | .py | ae34439a2e2401c5 | 7.45 | 7 |
"""
Приглашения: ссылка, по которой человек заводит себе учётную запись сам.
Зачем это вообще. Раньше администратор придумывал новому человеку логин
и пароль и пересылал их в переписке. Пароль, отправленный в мессенджер,
остаётся там навсегда, а половина таких паролей потом не меняется никогда.
По ссылке человек задаё... | maximdr86/tikpilot | app/invites.py | .py | d97fb7e7a87455fd | 7.45 | 7 |
"""
Защита входа от подбора пароля.
После нескольких промахов подряд адрес получает паузу. Смысл не в том,
чтобы остановить настойчивого злоумышленника — от него защищают длинный
пароль и `ADMIN_NETWORKS`, — а в том, чтобы перебор перестал быть дешёвым.
Без паузы тысяча попыток в секунду ограничена только каналом.
Сч... | maximdr86/tikpilot | app/loginguard.py | .py | 3bb83274caaaafd9 | 7.45 | 7 |
"""
Точка входа приложения Tikpilot.
Запуск:
uvicorn app.main:app --host 0.0.0.0 --port 8080
или просто:
python -m app.main
"""
from __future__ import annotations
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, PlainT... | maximdr86/tikpilot | app/main.py | .py | 142d901cf4f9ca40 | 7.45 | 7 |
"""
Ограничение доступа к панели по сетям.
Задача одна: публичный лист состояния должен открываться откуда угодно,
а сама панель — только из доверенных сетей. Иначе, пробросив порт наружу
ради ссылки для подрядчиков, вы заодно выставляете туда форму входа
в систему управления парком.
Настраивается переменной `ADMIN_N... | maximdr86/tikpilot | app/netguard.py | .py | 0953e3829dba244e | 7.45 | 7 |
"""
Ходовые настройки: те, что правятся из панели, а не из `.env`.
Зачем
-----
Поменять интервал опроса или срок хранения логов проще всего тогда, когда
ты уже смотришь на панель и видишь, что тебе не нравится. Вместо этого
приходилось идти на сервер, править `.env` и перезапускать службу, а
в Docker ещё и вспоминать... | maximdr86/tikpilot | app/prefs.py | .py | 4873afe90c619bbe | 7.45 | 7 |
"""
Публичный лист состояния группы.
Ссылка вида `/status/<токен>` открывается без входа: её дают подрядчикам,
дежурной смене, кому угодно. Поэтому страница отдаёт ровно один вид сведений
и ничего сверх него: имя точки, в сети она или нет, и с какого момента.
Чего здесь нет намеренно:
* **адресов.** Список внутренни... | maximdr86/tikpilot | app/routes/public.py | .py | 534cadfa6e4d2af8 | 7.45 | 7 |
"""Раздел «Скрипты»: библиотека команд и то, что раскатано по парку."""
from __future__ import annotations
from fastapi import APIRouter, Body, Depends, Request
from fastapi.responses import JSONResponse
from .. import permissions, snippets
from ..auth import Forbidden, client_ip, current_user
from ..database import... | maximdr86/tikpilot | app/routes/snippets.py | .py | 94c7274316529af4 | 7.45 | 7 |
"""Терминал до устройства: страница и вебсокет."""
from __future__ import annotations
import asyncio
import json
import logging
import threading
from typing import Any
from fastapi import APIRouter, Body, Depends, Request, WebSocket, WebSocketDisconnect
from .. import permissions, terminal
from ..auth import client... | maximdr86/tikpilot | app/routes/terminal.py | .py | 8bb1b28d5e08f901 | 7.45 | 7 |
"""Заходы по публичным ссылкам: кто смотрит сейчас и кто смотрел раньше."""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, Depends, Request
from .. import publicviews
from ..auth import require
from ..database import query, query_one
from .deps import PAGE_SIZE, pager, rend... | maximdr86/tikpilot | app/routes/visits.py | .py | 25a32602a1e437a5 | 7.45 | 7 |
"""
Расписание бэкапов: правила «что, когда и сколько хранить».
Правило описывает три вещи:
* **что снимать.** Группу устройств, весь парк или архив самой панели;
* **когда.** Время суток и дни недели. Пустой список дней означает
ежедневно;
* **сколько хранить.** Число последних копий на устройство. Лишние
удаляю... | maximdr86/tikpilot | app/schedules.py | .py | 1c7b19a0e8a8d038 | 7.45 | 7 |
"""
Библиотека команд: то, что написали один раз и хотят повторять.
Зачем
-----
Длинный скрипт живёт в переписке, в блокноте и в буфере обмена. Через
месяц его ищут по чату, находят три версии и не помнят, какая раскатана.
Панель, которая умеет выполнять команды на всём парке, обязана уметь их
и хранить.
Как узнаётс... | maximdr86/tikpilot | app/snippets.py | .py | b25b80be19ddc1a1 | 7.45 | 7 |
#!/usr/bin/env python3
"""
wiki-knowledge-agent — onboarding wizard
Creates ~/.config/wiki-knowledge-agent/config.yaml interactively.
Questions:
1. Wiki root path
2. Input channels (any / specific list; default = current chat)
3. Target language
4. Alert channel (webhook/email optional; default = current chat)... | atukunare/wiki-knowledge-agent | scripts/onboarding.py | .py | 7074e7579426d372 | 7.54 | 11 |
"""Probe → channel-message adaptation.
A LongMemEval question has shape::
{
"question_id": "qa_30__simple_user_info",
"question": "What's my favorite color?",
"question_date": "2023/06/01 (Thu) 14:23",
"haystack_sessions": [...],
"haystack_dates": [...],
"haystack_session_ids":... | jasoncarreira/mimir | benchmarks/longmemeval_via_mimir/route.py | .py | b322a8672f2092d0 | 7.42 | 6 |
"""Scoring — thin wrapper around saga's existing LongMemEval judge.
saga ships an evaluator harness that pipes hypothesis JSONL files to
LongMemEval's upstream ``evaluate_qa.py`` (gpt-4o judge). The integration
runner produces hypotheses in the same shape::
{"question_id": "qa_30__simple_user_info", "hypothesis":... | jasoncarreira/mimir | benchmarks/longmemeval_via_mimir/score.py | .py | 4e32878b3ceb2ccf | 7.42 | 6 |
import numpy as np
def dcg(relevances, k):
"""Discounted Cumulative Gain at k."""
relevances = np.asfarray(relevances)[:k]
if relevances.size:
return relevances[0] + np.sum(relevances[1:] / np.log2(np.arange(2, relevances.size + 1)))
return 0.
def ndcg(rankings, correct_docs, corpus_ids, k=1... | jasoncarreira/mimir | benchmarks/saga/external/longmemeval/src/retrieval/eval_utils.py | .py | c98b8d1096877a15 | 7.42 | 6 |
"""GEPA adapter for SAGA cluster→observation prompt optimization.
The adapter evolves only the rich consolidation prompt text. It renders a
candidate prompt against exported source clusters, calls an injected synthesis
function, and scores each raw response with :mod:`evals.cluster_observation.metrics`.
Default model... | jasoncarreira/mimir | evals/cluster_observation/adapter.py | .py | fa6f9106de000206 | 7.42 | 6 |
"""GEPA adapter for the commitments-extraction pilot (chainlink #404, Path A).
Runs a candidate **system prompt** through the same model path as
``mimir.commitments.extractor`` (saga's ``call_llm`` + ``_parse_extraction_json``),
scores the extracted commitment texts with the reference-free
:mod:`evals.commitments_extr... | jasoncarreira/mimir | evals/commitments_extraction/adapter.py | .py | 21c219f5a653daae | 7.42 | 6 |
"""Reference-free quality metrics + ASI for the commitments-extraction GEPA pilot.
Chainlink #404, Path A. These score an extractor candidate's output **without
gold labels** — every signal is computed from (source_text, extracted_texts)
alone, so no hand-annotated corpus is needed. The objective they encode is the
on... | jasoncarreira/mimir | evals/commitments_extraction/metrics.py | .py | 70438929053de79b | 7.42 | 6 |
"""Parse the source skills into a structured form the variant generator can reshape.
A skill on disk is ``SKILL.md`` (with YAML frontmatter) plus optional companion
markdown (``examples.md``, ``reference.md``) and an optional ``references/``
folder of one-concern rule files. We parse just enough structure -- frontmatt... | aerospike/agent-skills | scripts/skills_compile/skillsrc.py | .py | d65e9415818a1868 | 7.57 | 13 |
"""Guards for CI mistakes that got past review.
The common shape is a fact restated in two places, then drifting.
"""
import pathlib
import re
import yaml
REPO_ROOT = pathlib.Path(__file__).resolve().parents[2]
WORKFLOWS = REPO_ROOT / ".github" / "workflows"
TESTS = REPO_ROOT / "tests"
def test_skill_validator_wo... | aerospike/agent-skills | tests/unit/test_ci_workflows.py | .py | 6d85508bc01c8083 | 8.07 | 13 |
"""No document may point at the retired SKILLS.md, and the install table must
cover every platform we claim to support."""
import json
import pathlib
REPO_ROOT = pathlib.Path(__file__).resolve().parents[2]
TRACKED_SUFFIXES = {".md", ".json", ".yml", ".sh", ".py"}
SKIP_DIRS = {".git", "eval", "results", ".venv", ".sup... | aerospike/agent-skills | tests/unit/test_docs_references.py | .py | 761bc4a6840fe36c | 8.07 | 13 |
"""Both registries must receive exactly one submission: the compiled skill."""
import json
import os
import pathlib
import shutil
import subprocess
import pytest
REPO_ROOT = pathlib.Path(__file__).resolve().parents[2]
REPO_URL = "https://github.com/aerospike/agent-skills"
def _run(script, *args):
result = subp... | aerospike/agent-skills | tests/unit/test_publish_scripts.py | .py | 07008579312f8901 | 8.07 | 13 |
"""Release tags are stable semantic versions that move forward.
The gate is only worth having if it fails on the tags it is meant to catch, so these
exercise the script itself rather than asserting on its source.
"""
import pathlib
import shutil
import subprocess
import pytest
REPO_ROOT = pathlib.Path(__file__).res... | aerospike/agent-skills | tests/unit/test_release_version.py | .py | 63a25ede990952e8 | 8.07 | 13 |
"""Every skill declares the server range its guidance targets, so "matches
current server behavior" has something concrete to be checked against."""
import pathlib
import pytest
from scripts.skills_compile.skillsrc import split_frontmatter
REPO_ROOT = pathlib.Path(__file__).resolve().parents[2]
SKILL_FILES = sorted... | aerospike/agent-skills | tests/unit/test_skill_metadata.py | .py | 8a29650027aae587 | 8.07 | 13 |
"""Deviation classification: world_changed | stale_model | infeasible.
On an action failure the bridge re-observes the target area and compares
it with its last observation of the same area (architecture note,
"Deviation reports"):
- fresh prior observation that contradicts the world now -> world_changed
(someone a... | bdambrosio/Cognitive_workbench | factorio/bridge/deviation.py | .py | 9b5d9e211d06c668 | 7.52 | 10 |
"""RCON transport to the fle-bridge mod's remote interface."""
import json
import logging
import re
import threading
import factorio_rcon
from slpp import slpp
from .policy import ALLOWED_ACTIONS
log = logging.getLogger(__name__)
class ActionError(Exception):
"""A remote action errored inside the mod (Lua erro... | bdambrosio/Cognitive_workbench | factorio/bridge/rcon_link.py | .py | 370a3eebd948f422 | 7.52 | 10 |
#!/usr/bin/env python3
"""Join a turn to the harness revision that was live when it ran.
This is what makes harness-change regression measurable at all. The v2
suite only ever varied the backend model, so a harness edit could not be
seen. Every metric here is tagged (model x harness revision); this supplies
the second... | bdambrosio/Cognitive_workbench | measure/harness_rev.py | .py | f025a8845774a212 | 7.52 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.