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 |
|---|---|---|---|---|---|---|
"""
Pytest configuration and shared fixtures.
"""
import pytest
import sys
from pathlib import Path
# Add src to path for all tests
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
def pytest_configure(config):
"""Configure pytest with custom markers."""
config.addinivalue_line(
"marker... | slyubarskiy/chatgpt-conversation-extractor | tests/conftest.py | .py | 4d34b42747f8a626 | 8.15 | 19 |
"""
Test suite for CLI argument validation.
Focuses on the new validation logic for JSON output options.
"""
import json
import sys
import argparse
from pathlib import Path
from unittest.mock import patch, MagicMock
import pytest
# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from c... | slyubarskiy/chatgpt-conversation-extractor | tests/test_cli_validation.py | .py | ca146d5c309f0b66 | 7.15 | 19 |
"""
Final tests to push coverage above 80%.
"""
import json
import sys
from pathlib import Path
from unittest.mock import patch, MagicMock, mock_open
import pytest
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from chatgpt_extractor.extractor import ConversationExtractorV2
from chatgpt_extractor.proc... | slyubarskiy/chatgpt-conversation-extractor | tests/test_coverage_final.py | .py | 8ee6237bdb6e9df5 | 8.15 | 19 |
"""
Tests for the main ConversationExtractorV2 class.
"""
import json
import tempfile
from pathlib import Path
import pytest
from unittest.mock import Mock, patch
import sys
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from chatgpt_extractor.extractor import ConversationExtractorV2
from tests.test_... | slyubarskiy/chatgpt-conversation-extractor | tests/test_extractor.py | .py | 1555c125317778ae | 8.15 | 19 |
"""
Helper utilities for testing with logging.
"""
import logging
from contextlib import contextmanager
from io import StringIO
@contextmanager
def capture_logs(logger_name="chatgpt_extractor", level=logging.INFO):
"""Context manager to capture log output for testing.
Args:
logger_name: Name of the ... | slyubarskiy/chatgpt-conversation-extractor | tests/test_helpers.py | .py | 6266a76573783282 | 8.15 | 19 |
"""
Tests for the CLI main module.
"""
import sys
from pathlib import Path
import pytest
from unittest.mock import patch, MagicMock
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from chatgpt_extractor.__main__ import main, run_failure_analysis
from tests.test_helpers import capture_logs, assert_in_lo... | slyubarskiy/chatgpt-conversation-extractor | tests/test_main.py | .py | 8c0fa7ed94fcfa4d | 8.15 | 19 |
"""
Tests for the tracking components.
"""
import time
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from chatgpt_extractor.trackers import SchemaEvolutionTracker, ProgressTracker
class TestSchemaEvolutionTracker:
"""Validates schema pattern det... | slyubarskiy/chatgpt-conversation-extractor | tests/test_trackers.py | .py | 4666daf92f8ddc63 | 8.15 | 19 |
"""Parse ty diagnostics and normalize panic and stderr output."""
import re
from pathlib import Path
from .schema import Diagnostic, DiagnosticLevel
OLD_DIAGNOSTIC_PATTERN = re.compile(
r"^(?P<level>error|warning|fatal)\[(?P<lint_name>.+?)\] "
r"(?P<path>.+?):(?P<line>\d+):(?P<column>\d+): "
r"(?P<messag... | astral-sh/ecosystem-analyzer | src/ecosystem_analyzer/diagnostic.py | .py | 8530b2dbeac41a3c | 7.59 | 14 |
"""Render searchable HTML reports for ecosystem diagnostics."""
import json
import logging
from pathlib import Path
from jinja2 import Environment, FileSystemLoader, PackageLoader
from .schema import Diagnostic, ReportDiagnostic, RunData, RunOutput
logger = logging.getLogger(__name__)
def _is_http_url(value: obje... | astral-sh/ecosystem-analyzer | src/ecosystem_analyzer/ecosystem_report.py | .py | 65da2795aab7d9f0 | 7.59 | 14 |
"""Logic for detecting flaky diagnostics by comparing multiple ty runs."""
from collections import Counter
from .schema import (
Diagnostic,
DiagnosticKey,
FlakyLocation,
FlakyVariant,
SourceLocationKey,
)
def _diagnostic_key(diag: Diagnostic) -> DiagnosticKey:
"""Return a hashable key that ... | astral-sh/ecosystem-analyzer | src/ecosystem_analyzer/flaky.py | .py | 9a9c57b1c73d23c2 | 7.59 | 14 |
"""Clone ecosystem projects and prepare their isolated dependencies."""
import datetime as dt
import hashlib
import logging
import os
import subprocess
import tempfile
from pathlib import Path
from mypy_primer.model import Project
from .config import MINIMUM_PYTHON_VERSION, UV_NO_BUILD_ENV, get_cache_dir
from .git i... | astral-sh/ecosystem-analyzer | src/ecosystem_analyzer/installed_project.py | .py | 418626455be74833 | 7.59 | 14 |
"""Install ecosystem projects and coordinate ty analysis runs."""
import json
import logging
import time
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
from pathlib import Path
from mypy_primer.model import Project
from mypy_primer.projects import get_projects
from .installed_project import ... | astral-sh/ecosystem-analyzer | src/ecosystem_analyzer/manager.py | .py | a5c63d9e03d1156e | 7.59 | 14 |
"""Build and run ty, then aggregate diagnostics and exit evidence."""
import hashlib
import logging
import os
import shlex
import subprocess
import sys
import time
from collections import Counter
from pathlib import Path
from .config import UV_NO_BUILD_ENV
from .diagnostic import DiagnosticsParser, index_panic_messag... | astral-sh/ecosystem-analyzer | src/ecosystem_analyzer/ty.py | .py | 9a7de319a04d20a2 | 7.59 | 14 |
from ecosystem_analyzer.diagnostic import DiagnosticsParser
class TestDiagnosticsParser:
def test_parse_error_diagnostic(self) -> None:
"""Test parsing a basic error diagnostic message."""
parser = DiagnosticsParser()
content = "error[invalid-assignment] try.py:3:1: Object of type `Literal... | astral-sh/ecosystem-analyzer | tests/test_diagnostic.py | .py | 3b0a7551b616cfd5 | 7.09 | 14 |
import datetime as dt
from unittest.mock import MagicMock, patch
import pytest
from mypy_primer.model import Project
from ecosystem_analyzer.installed_project import (
InstalledProject,
validate_exclude_newer,
)
def _make_project(
*,
min_python_version: tuple[int, int] | None = None,
install_cmd... | astral-sh/ecosystem-analyzer | tests/test_exclude_newer.py | .py | 36387de3d2e21e87 | 8.09 | 14 |
from ecosystem_analyzer.flaky import classify_diagnostics
from ecosystem_analyzer.schema import Diagnostic, DiagnosticLevel
def _diag(
path: str,
line: int,
column: int,
message: str,
lint_name: str = "some-lint",
level: DiagnosticLevel = "error",
) -> Diagnostic:
return Diagnostic(
... | astral-sh/ecosystem-analyzer | tests/test_flaky.py | .py | fcd37c05011c0e18 | 7.09 | 14 |
"""Test Git operations against isolated local repositories."""
import json
import os
import subprocess
import traceback
from pathlib import Path
from unittest.mock import call, patch
import pytest
from click.testing import CliRunner
from mypy_primer.model import Project
from ecosystem_analyzer.git import (
_ty_r... | astral-sh/ecosystem-analyzer | tests/test_git.py | .py | 5070af82260f6c17 | 7.09 | 14 |
from pathlib import Path
import pytest
from click.testing import CliRunner, Result
from mypy_primer.model import Project
from ecosystem_analyzer.main import cli, get_all_project_names, shard_projects
from ecosystem_analyzer.process import run
from ecosystem_analyzer.ty import Ty
def _projects(*costs: tuple[str, int... | astral-sh/ecosystem-analyzer | tests/test_sharding.py | .py | 0513e1f189765ec5 | 8.09 | 14 |
#!/usr/bin/env python3
"""mission-migrate.py — single state.json → sessions/<sid>.json 構造への変換
C-3 multi-session 構造への移行ツール。
- デフォルト dry-run。--execute で実際に変換。
- 既存 state.json は state.json.pre-migration として保管。
- session_id は state.json の session_id (B-3 で追加されたフィールド) を採用。
存在しない場合は uuid を生成。
- aggregate.json を作成 (active_... | tackeyy/mission | plugins/mission/skills/mission/bin/mission-migrate.py | .py | d8a59c2f83741818 | 7.45 | 7 |
"""Shared mission state helpers used by state and audit tools."""
from __future__ import annotations
import math
import re
import secrets
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
PREPARATION_ONLY_MARKERS = (
"Oracle Browser Review Prepared",
"Browser Review Prep... | tackeyy/mission | plugins/mission/skills/mission/lib/mission_common.py | .py | 2231b59698a6d057 | 7.45 | 7 |
"""#593 B-2: gate outcome の分類。
pass gate が発火して反復に入ったとき、その反復が何だったのかを機械的に
分類する。本番 451 mission のうち「反復したが composite 不変」15 件は、
現在
- ゲートの誤検知 (弾いたが直すものが無い)
- 修正の失敗 (直したが改善しない)
が混ざっている。対処がまったく異なるのに区別できていない。B-1 で記録した
`artifact_digest` を使って両者を分離する。
このモジュールは **判定のみ** を行い、gate の意味論には一切関与しない。
"""
from __future__ import anno... | tackeyy/mission | plugins/mission/skills/mission/lib/mission_gate_outcome.py | .py | d911f975608b4504 | 7.45 | 7 |
"""Curses rendering helpers for the Keboola Storage Browser demo.
Pure presentation: every function here takes a curses window plus already-fetched
data and draws it. No API calls, no application state, no token handling happen in
this module -- that all lives in ``app.py``. Splitting the drawing out keeps
``app.py`` ... | keboola/cli | examples/storage_tui/_render.py | .py | 73fba9622190e4ce | 7.56 | 12 |
#!/usr/bin/env python3
"""CI guard: verify every CLI command is registered and documented.
The kbagent CLI surface is mirrored across several agent-facing files that have
NO other CI freshness check (see CONTRIBUTING.md "Plugin synchronization map"
and CLAUDE.md convention #17). Forgetting to update one ships an AI ag... | keboola/cli | scripts/check_command_sync.py | .py | 25df374607e9626d | 7.56 | 12 |
"""CI guard: enforce the per-layer file-size budgets from CONTRIBUTING.md.
Budgets are measured in **code lines**, not raw line count: docstrings,
comments and blank lines are excluded. Raw LOC would tax the long
rationale-carrying docstrings this codebase deliberately writes -- they are
what makes it navigable, so a ... | keboola/cli | scripts/check_file_size.py | .py | d964cd6240085d83 | 7.56 | 12 |
#!/usr/bin/env python3
"""Prove the new changelog entry covers every PR the release tag will contain.
``make changelog-check`` answers a different question: does every *released
version* have a changelog entry? It never asks whether that entry covers every
*commit* under the tag. The gap is not hypothetical -- it ship... | keboola/cli | scripts/check_release_scope.py | .py | d73eab8ca59133f2 | 7.56 | 12 |
"""CI helper: assert whether a built wheel bundles the React SPA.
Used by the Windows wheel-build CI job to verify the issue #320 fixes
end-to-end on a real Windows runner (where no developer machine is needed):
- a normal ``uv build`` must bundle ``_ui_dist/index.html`` (Bug 1: the
``npm.cmd`` invocation actually ... | keboola/cli | scripts/check_wheel_ui.py | .py | 25fbadcb4e263607 | 7.56 | 12 |
#!/usr/bin/env python3
"""Generate command-reference.md by introspecting the live Typer app.
Zero-drift by construction: the output is derived from the same Click command
tree that renders ``--help``, so it cannot disagree with the shipped CLI. The
release workflow attaches the result as a GitHub Release asset next to... | keboola/cli | scripts/gen_command_reference.py | .py | 8d94eee4b33d13eb | 7.56 | 12 |
#!/usr/bin/env python3
"""Generate docs/web-server-endpoints.md by introspecting the live FastAPI app.
Zero-drift by construction: the output is derived from ``create_app().openapi()``
-- the same spec ``kbagent serve`` publishes at ``/openapi.json`` -- so the
committed reference cannot disagree with the shipped serve... | keboola/cli | scripts/gen_endpoint_reference.py | .py | e2010bcbd4acbfa6 | 7.56 | 12 |
#!/usr/bin/env python3
"""Generate changelog skeleton from GitHub releases.
Fetches release notes from the GitHub API and prints a Python dict
suitable for pasting into ``src/keboola_agent_cli/changelog.py``.
Usage:
python scripts/generate_changelog.py # print skeleton
python scripts/generate_changel... | keboola/cli | scripts/generate_changelog.py | .py | d581a84c534ae90a | 7.56 | 12 |
"""Hatchling custom build hook that bundles the built React SPA into the wheel.
End-users install this package via:
- ``uv tool install git+https://github.com/keboola/cli`` --
uv clones the repo, runs ``hatchling`` to produce a wheel, installs it,
then deletes the clone. The user does NOT have a checkout on disk.... | keboola/cli | scripts/hatch_build.py | .py | a3ce51dfd4226362 | 7.56 | 12 |
"""Keboola AI Service API client with retry, timeouts, and token masking.
This module communicates with the Keboola AI Service API for component
documentation, search, and suggestion features. Derives the AI Service
URL from the Storage API stack URL by replacing 'connection.' with 'ai.'
in the hostname.
Inherits sha... | keboola/cli | src/keboola_agent_cli/ai_client.py | .py | 20899e7077f6adae | 7.56 | 12 |
"""RFC 8628 device authorization: polling runner for `kbagent auth login --device-code`.
Used both as the forced flow (`--device-code`) and as the automatic fallback
from `auth/pkce.py` when `auth/environment.py` detects a remote/headless
machine, or when the PKCE setup/callback step fails before any code was
exchange... | keboola/cli | src/keboola_agent_cli/auth/device.py | .py | 6a0ea7f0509397bf | 7.56 | 12 |
"""Browser/remote heuristics: decide whether a same-machine loopback login is usable.
`kbagent auth login` prefers the PKCE authorization-code flow (it needs no
copy-paste), but that only works when this process can (a) open a browser
that (b) can actually reach the loopback listener it just bound -- true on a
desktop... | keboola/cli | src/keboola_agent_cli/auth/environment.py | .py | 3baa95b12ad1a154 | 7.56 | 12 |
"""Wire models and persisted state for programmatic auth (browser login).
Two families of model live here:
- Wire models (`AuthUser`, `CliTokenResponse`, `DeviceAuthorization`,
`AuthProject`, `IntrospectResponse`, `DevicePollResult`, `RevokeResult`):
shaped after the Keboola auth-service JSON responses, never per... | keboola/cli | src/keboola_agent_cli/auth/models.py | .py | 39454800263e26c5 | 7.56 | 12 |
"""PKCE authorization-code login: challenge generation + loopback callback.
Implements the browser-based half of `kbagent auth login` (design doc
section 4.5 step 3): generate a fresh verifier/challenge/state triple, hand
the user a browser URL, and receive the authorization-code redirect on a
loopback HTTP listener b... | keboola/cli | src/keboola_agent_cli/auth/pkce.py | .py | 6fe292397557dca6 | 7.56 | 12 |
"""Session-token sentinel helpers.
A session-registered project (`kbagent auth login --register-projects`) does
not have a real Storage API token to put in `ProjectConfig.token` -- its
actual credential lives in `auth.json`, keyed by stack URL, and rotates over
time. Instead, `ProjectConfig.token` holds an opaque sent... | keboola/cli | src/keboola_agent_cli/auth/sentinel.py | .py | 464f508bfcc07dec | 7.56 | 12 |
"""Persistence for programmatic-auth sessions (auth.json)."""
from __future__ import annotations
import contextlib
import json
import logging
import os
import stat
from collections.abc import Iterator
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import TYPE_CHECKING
import filel... | keboola/cli | src/keboola_agent_cli/auth/state_store.py | .py | dc896364c0bc494b | 7.56 | 12 |
"""Composition of the Keboola API client from its endpoint-family mixins.
``KeboolaClient`` is assembled here from the per-family mixins (storage tables,
storage files, configs, queue, tokens, branches, merge requests, stream,
query, workspaces, billing, notifications, misc) over the shared
``_CoreClient`` plumbing ba... | keboola/cli | src/keboola_agent_cli/client/_client.py | .py | 783012da7f275a5d | 7.56 | 12 |
"""Shared HTTP plumbing for the Keboola client mixins.
``_CoreClient`` is the typed base every ``KeboolaClient`` endpoint-family mixin
inherits (issue #520). It holds the construction, request dispatch, sub-client
lifecycle, base-URL derivation and storage-job polling that the mixins call as
``self._request(...)`` / `... | keboola/cli | src/keboola_agent_cli/client/_core.py | .py | 061e7ccd3af89f5b | 7.56 | 12 |
"""Pay-As-You-Go credit balance -- GET /credits on the billing service.
New for issue #594. The billing service also exposes ``POST /credits``, which
triggers a REAL automatic top-up (real money charged to the project). That
endpoint is deliberately NOT wrapped anywhere in this mixin -- kbagent's
billing surface is re... | keboola/cli | src/keboola_agent_cli/client/billing.py | .py | 9c3a8f54892470cc | 7.56 | 12 |
"""Development branches and branch metadata.
Extracted verbatim from the former single-file ``client.py`` (issue #520).
"""
from typing import Any
from ..constants import METADATA_NOT_FOUND
from ._core import _CoreClient
class _BranchesMixin(_CoreClient):
"""Development branches and branch metadata."""
de... | keboola/cli | src/keboola_agent_cli/client/branches.py | .py | fad492844cd25eeb | 7.56 | 12 |
"""Merge-request endpoints, exposed as ``client.merge_requests`` (DMD-1701).
This module holds four pieces:
- ``StorageRequester``: the FUTURE transport interface -- public method names,
defined today. The client-split RFC (draft PR #595; not in this tree yet)
builds the real transport under this seam later; unti... | keboola/cli | src/keboola_agent_cli/client/merge_requests.py | .py | 47c04a7e518937d8 | 7.56 | 12 |
"""Cross-cutting endpoints: global search, OAuth URL, encryption, sync actions.
Extracted verbatim from the former single-file ``client.py`` (issue #520).
"""
from typing import TYPE_CHECKING, Any
from ..constants import (
OAUTH_HOST,
OAUTH_PATH,
)
from ._core import _CoreClient
if TYPE_CHECKING:
from .... | keboola/cli | src/keboola_agent_cli/client/misc.py | .py | 7ada3f34bc437604 | 7.56 | 12 |
"""Notification Service: project-level notification subscriptions (issue #600).
Backs the Flow Builder's *Notifications* tab (the bell icon: Success / Error /
Processing-delay / Warning cards). Those recipients are NOT part of a flow's
``configuration`` JSON -- they live in a separate platform service advertised
as ``... | keboola/cli | src/keboola_agent_cli/client/notifications.py | .py | 9abc4560207b353c | 7.56 | 12 |
"""Query Service: workspace SQL submission, results and history.
Extracted verbatim from the former single-file ``client.py`` (issue #520).
"""
import time
from typing import Any
from ..constants import (
QUERY_JOB_MAX_WAIT,
QUERY_JOB_POLL_INTERVAL,
QUERY_RESULTS_PAGE_SIZE,
)
from ..errors import ErrorCo... | keboola/cli | src/keboola_agent_cli/client/query.py | .py | 811117929b1ae71c | 7.56 | 12 |
"""Queue API: job listing, creation, termination, events and polling.
Extracted verbatim from the former single-file ``client.py`` (issue #520).
"""
import time
from typing import Any
from urllib.parse import quote
from ..constants import (
DEFAULT_GROUPED_JOBS_LIMIT,
DEFAULT_JOB_LIMIT,
DEFAULT_JOB_SORT_... | keboola/cli | src/keboola_agent_cli/client/queue.py | .py | 74c63bc9ae69709d | 7.56 | 12 |
"""Storage Files API: upload, download (incl. sliced), tagging.
Extracted verbatim from the former single-file ``client.py`` (issue #520).
"""
import logging
from pathlib import Path
from typing import TYPE_CHECKING, Any
from urllib.parse import quote
import httpx
from ..constants import (
FILE_DOWNLOAD_CHUNK_S... | keboola/cli | src/keboola_agent_cli/client/storage_files.py | .py | 091c3c92fc8a9ac4 | 7.56 | 12 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
測試運行腳本 - 運行所有測試並生成報告
腳本位置: deploy/test_scripts/run_tests.py
報告輸出: tests/reports/
用法:
python deploy/test_scripts/run_tests.py # 運行所有測試並生成報告
python deploy/test_scripts/run_tests.py --quick # 快速運行,不生成覆蓋率
python deploy/test_scripts/run_tests.... | RonaldJEN/OpenCapyBox | deploy/test_scripts/run_tests.py | .py | 2001b4d194bf52cc | 7.92 | 6 |
"""Codex-compatible local context compaction primitives.
The reference behavior lives in ``docs/codex/codex-rs/core/src/compact.rs``.
This module deliberately keeps compaction policy independent from the Agent
loop so persistence and failover can reuse the exact same replacement rules.
"""
from __future__ import anno... | RonaldJEN/OpenCapyBox | src/agent/context_compaction.py | .py | 78438c2b3615bf09 | 7.42 | 6 |
#!/usr/bin/env python3
"""
Run a single benchmark configuration and output JSON results.
This script wraps the prime-rl training with --bench.output-json to get
metrics directly without parsing console output.
"""
from __future__ import annotations
import json
import subprocess
import sys
import time
from datetime i... | HyperPotatoNeo/prime-values | benchmarks/scripts/run_single_benchmark.py | .py | 6afbbab5da3db6b7 | 7.63 | 17 |
import os
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from pydantic import AfterValidator, Field, model_validator
from prime_rl.utils.config import BaseConfig
# Launcher-managed env vars that a component's `env_vars` must not set. The launcher
# owns GPU partitioning, lifecycle/network ... | HyperPotatoNeo/prime-values | packages/prime-rl-configs/src/prime_rl/configs/shared.py | .py | 4f7aeef01edb9304 | 7.63 | 17 |
from pathlib import Path
from typing import Any
from pydantic_config import BaseConfig as BaseConfig # noqa: F401
from pydantic_config import cli # noqa: F401
def find_package_resource(subdir: str) -> Path | None:
"""Find a directory contributed to the `prime_rl` namespace package by any installed wheel.
... | HyperPotatoNeo/prime-values | packages/prime-rl-configs/src/prime_rl/utils/config.py | .py | f3b341ab1308bc9a | 7.63 | 17 |
from __future__ import annotations
from typing import Any, Optional
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.configs.trainer import TrainerConfig
def propagate_shared_fields(data: Any) -> Any:
"""Propagate ``RLConfig``'s sh... | HyperPotatoNeo/prime-values | packages/prime-rl-configs/src/prime_rl/utils/validation.py | .py | 15d32f3e8c11f808 | 7.63 | 17 |
import json
import os
import subprocess
import sys
from pathlib import Path
from typing import Any
import tomli_w
from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.config import cli
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import format_log_message, get_confi... | HyperPotatoNeo/prime-values | src/prime_rl/entrypoints/inference.py | .py | eb94bac15a88833d | 7.63 | 17 |
import os
import subprocess
import sys
import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
import tomli_w
from prime_rl.configs.sft import SFTConfig
from prime_rl.utils.config import cli
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import... | HyperPotatoNeo/prime-values | src/prime_rl/entrypoints/sft.py | .py | 3440521d85f84ae8 | 7.63 | 17 |
"""Stdlib `logging`-based JSON formatter and dictConfig for vLLM.
Trainer and orchestrator emit JSON via loguru
(`prime_rl.utils.logger.json_sink`). vLLM uses Python's stdlib
`logging` and spawns workers via `multiprocessing.spawn`, so we can't
share the loguru sink directly. We emit the same flat shape from a
stdlib ... | HyperPotatoNeo/prime-values | src/prime_rl/inference/json_logging.py | .py | 61f4177df994afd0 | 7.63 | 17 |
"""Prime-RL extensions to vLLM's `/inference/v1/generate` handler.
vLLM 0.22 ships a generic tokens-in / tokens-out handler at
``vllm.entrypoints.serve.disagg.serving.ServingTokens`` that already covers
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
priority, ``data_parallel_rank`` header r... | HyperPotatoNeo/prime-values | src/prime_rl/inference/vllm/serving_tokens.py | .py | f8ac63db8bddecfa | 7.63 | 17 |
from typing import TYPE_CHECKING
from torch.nn import Module
from vllm.model_executor.model_loader import DefaultModelLoader, get_model_loader
from prime_rl.inference.vllm.worker.weight_transfer import load_weights_checkpoint_layerwise
# This is to get type hints for the Worker class but not actually extend it at ru... | HyperPotatoNeo/prime-values | src/prime_rl/inference/vllm/worker/filesystem.py | .py | 1817e325682ea968 | 7.63 | 17 |
import pickle
from typing import TYPE_CHECKING, Generator, cast
import torch
from torch.nn import Module
from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
from vllm.distributed.utils import StatelessProcessGroup
from vllm.logger import init_logger
from prime_rl.inference.vllm.worker.weight_t... | HyperPotatoNeo/prime-values | src/prime_rl/inference/vllm/worker/nccl.py | .py | 397c72d91ed9daac | 7.63 | 17 |
"""Shared rollout-credit math for orchestrator algorithms."""
from __future__ import annotations
import math
def compute_gae(
*,
reward: float,
values: list[float],
mask: list[bool],
gamma: float,
gae_lambda: float,
value_target_lambda: float,
) -> tuple[list[float], list[float]]:
""... | HyperPotatoNeo/prime-values | src/prime_rl/orchestrator/algo/advantage.py | .py | 67737f2ec97f5cfe | 7.63 | 17 |
"""The per-env algorithm runtime: the :class:`Algorithm` base class.
Each named class in this package *is* one training algorithm, one module per
algorithm: it owns the algorithm's two scoring hooks directly —
``score_rollout`` (per arrival) and ``score_group`` (per group) — and declares
which loss component its actio... | HyperPotatoNeo/prime-values | src/prime_rl/orchestrator/algo/base.py | .py | 0349aa8143406809 | 7.63 | 17 |
from __future__ import annotations
from functools import partial
from typing import TYPE_CHECKING, Callable
from prime_rl.configs.algorithm import EchoAlgoConfig
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
from prime_rl.orchestrator.trajectories import iter_trainable_branches
from prime_rl.utils.utils i... | HyperPotatoNeo/prime-values | src/prime_rl/orchestrator/algo/echo.py | .py | a0c8098614d8b546 | 7.63 | 17 |
from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import OPSDAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm
if TYPE_CHECKING:
from renderers.base import Renderer
from prime_rl.orchestrator.types import Rollout
from prime_... | HyperPotatoNeo/prime-values | src/prime_rl/orchestrator/algo/opsd.py | .py | 10624cdff6aea8aa | 7.63 | 17 |
"""Wire-field stamping for the per-token streams.
The training loss is a sum of three components — ``rl`` (importance-weighted
PG + KL), ``ce`` (masked NLL), and ``ref_kl`` (reverse KL to a reference model
as the PG signal) — each normalized by its own global token count in the
trainer. The algorithm decides which com... | HyperPotatoNeo/prime-values | src/prime_rl/orchestrator/algo/routing.py | .py | 0038eddeb764ca3d | 7.63 | 17 |
#!/usr/bin/env python3
"""Generate TPC-DS data in Parquet format using dsdgen binary."""
import argparse
import os
import subprocess
import sys
from pyspark.sql import SparkSession
from pyspark.sql.types import (
StructType, StructField, StringType, IntegerType, LongType,
DecimalType, DateType,
)
# TPC-DS tab... | onehouseinc/quanton-operator | benchmarks/scripts/datagen.py | .py | 67026637c1037172 | 7.66 | 20 |
#!/usr/bin/env python3
"""Execute TPC-DS SQL queries with timing, output results as JSON."""
import argparse
import json
import os
import time
import traceback
from pyspark.sql import SparkSession
# TPC-DS tables expected in the parquet directory
TPCDS_TABLES = [
"call_center", "catalog_page", "catalog_returns", ... | onehouseinc/quanton-operator | benchmarks/scripts/run_queries.py | .py | 9cd170c4e3275075 | 7.66 | 20 |
#!/usr/bin/env python3
"""Score all three arms on the same cases, by the same rules.
A: culprit alone (deterministic, ~0 tokens, sub-second)
B: agent alone with git (Opus + bash)
C: agent given culprit's output first
Uses benchmarks/run.py's own score_case so no arm gets a friendlier judge.
"""
i... | noordeen123/culprit | benchmarks/agent/score.py | .py | 7f00c56cff49124b | 7.42 | 6 |
#!/usr/bin/env python3
"""Build isolated sandboxes for the agent-baseline arm of the suspect benchmark.
Fairness rules, mirroring exactly what culprit's engine receives:
* culprit gets ONLY the diff. pr_context.from_local sets title=None, body=None,
so it never sees the fix commit message. The agent gets the sa... | noordeen123/culprit | benchmarks/agent/setup.py | .py | 662c2d15ab0a0692 | 7.42 | 6 |
"""Shared helpers for the benchmark scripts: git plumbing and the repo cache."""
import os
import re
import subprocess
CACHE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".cache")
def git(repo, *args):
"""Run git in `repo`, return stdout; raise CalledProcessError on failure.
Some real-worl... | noordeen123/culprit | benchmarks/common.py | .py | 50ae7af973762004 | 7.42 | 6 |
"""Thin, read-only subprocess helpers for git and gh.
Every command here is read-only by construction. Nothing in culprit ever
mutates the target repository or the PR.
"""
from __future__ import annotations
import os
import shutil
import subprocess
from typing import Dict, List, Optional
class ProcError(RuntimeErro... | noordeen123/culprit | culprit/_proc.py | .py | 620225a6cf0dfee4 | 7.42 | 6 |
"""Feature path: what can this change break?
For each changed source file, find who imports it (reverse-import map), which
tests cover those modules, and which touched files live in shared/core areas
(high blast radius). Heuristic but grounded - the reasoning layer ranks risk
and recommends the test surface from this ... | noordeen123/culprit | culprit/blast_radius.py | .py | 31db26af20c0fa61 | 7.42 | 6 |
"""Classify a change as a bugfix or a feature, with evidence.
Deterministic scoring over branch name, PR labels, and commit/title prefixes.
The verdict is advisory: the Claude Code harness (or the API reasoning layer)
makes the final call, but the score + evidence give it grounded signal instead
of guessing.
"""
from ... | noordeen123/culprit | culprit/classify.py | .py | 6136733529a771cf | 7.42 | 6 |
"""Fix completeness: does the fix address the root cause, or just one symptom?
A fix that patches one call site of a broken helper but misses three others is a
partial fix. This module extracts the symbols the fix changed (the enclosing
functions from the hunk headers, plus called names on the changed lines), finds
ot... | noordeen123/culprit | culprit/completeness.py | .py | ee1f23309a31623d | 7.42 | 6 |
"""Optional coverage precision: which *changed lines* are actually uncovered.
The default test-gap is an import heuristic ("this file has no test that imports
it"). Given an lcov or Cobertura report via ``--coverage``, this parses the per-line
coverage, maps it to the lines this change added, and reports exactly which... | noordeen123/culprit | culprit/coverage.py | .py | d2abee54f3f5fe0e | 7.42 | 6 |
"""Line-evolution timeline: how the buggy lines became a bug, commit by commit.
For each line range the fix touched, ``git log -L<start>,<end>:<file>`` over the
base history gives every commit that ever modified those exact lines, oldest
first. We tag the earliest as ``origin``, the prime-suspect commit as
``suspect``... | noordeen123/culprit | culprit/evolution.py | .py | a4a8c2e2dd6d0aab | 7.42 | 6 |
"""Render a self-contained HTML RCA report from a structured result.
One file, no external CDN, no build step: the template ships as package data,
the result JSON and an optional narrative are injected as text nodes. Open the
output in any browser - works offline.
"""
from __future__ import annotations
import json
fr... | noordeen123/culprit | culprit/htmlreport.py | .py | ed9ba1b98d51b77f | 7.42 | 6 |
"""Intent enrichment: what the author was *trying* to do when the bug went in.
The suspect set tells us which commit last touched the buggy lines. This module
adds the missing half - the *intent* behind that commit: its full message body,
the pull request that introduced it (title + description), and any issue it was
... | noordeen123/culprit | culprit/intent.py | .py | 5e439cfb1fa9ca89 | 7.42 | 6 |
"""The bug's lifespan: which releases shipped it, how far it spread, recurrence.
Queries ``git tag --contains`` to find released versions that carried the bug,
counts commits/authors between introduction and fix, and checks whether the file
has a history of repeated bug-fix commits (hotspot detection). All read-only.
... | noordeen123/culprit | culprit/lifecycle.py | .py | 13aa2d06513fe67f | 7.42 | 6 |
"""culprit MCP server: expose the RCA engine as native tool calls.
Install: pip install culprit[mcp]
Run: culprit-mcp (stdio transport, works with any MCP-compatible client)
Add to your client's MCP config (Claude Code, Cursor, Windsurf, VS Code, Codex CLI, etc.):
{
"mcpServers": {
"c... | noordeen123/culprit | culprit/mcp_server.py | .py | 7e9f92a5892f8bf8 | 7.42 | 6 |
"""Suggest reviewers for a change: CODEOWNERS rules + git authorship.
Combines the owners declared in a ``CODEOWNERS`` file for the changed paths with the
people who have historically authored the changed (and suspect) files. Read-only.
"""
from __future__ import annotations
import fnmatch
import os
from collections ... | noordeen123/culprit | culprit/owners.py | .py | 0a9933bd06d12ac8 | 7.42 | 6 |
"""Resolve the analysis target into a normalized context dict.
Two sources, in priority order:
1. A GitHub PR via ``gh`` (title, body, labels, refs, commits, files, diff).
2. Local git only (current/named branch vs a base) when there's no PR or no
gh auth - fully offline, loses PR title/labels/linked-issue si... | noordeen123/culprit | culprit/pr_context.py | .py | f780d0f10a03a210 | 7.42 | 6 |
"""Per-repo project profile: the engine's file-detection config.
``.culprit/profile.json`` has a machine-written ``detected`` block (regenerated
by ``culprit init``) and a human ``overrides`` block (never touched by the tool);
overrides win per-key at read time. Absent / malformed / too-new -> the engine
falls back to... | noordeen123/culprit | culprit/profile.py | .py | 2385e0e0625b9213 | 7.42 | 6 |
"""The one LLM step, isolated behind an adapter.
- ``HarnessAdapter``: returns the structured result + markdown skeleton and
leaves the narrative to the calling agent (the Claude Code harness). No API
key, no network. This is what the SKILL.md uses.
- ``ClaudeAPIAdapter``: calls the Claude API (Anthropic SDK) to w... | noordeen123/culprit | culprit/reasoning.py | .py | bda8566673a49fa3 | 7.42 | 6 |
"""Combine the analysis signals into one QA risk score.
Sums weighted factors over the existing result dict - test gap, fix completeness,
hotspot recurrence, blast radius, churn - into a 0-100 score and a level
(low/medium/high), recording each contributing factor so a reviewer can see why.
``--fail-on <level>`` turns... | noordeen123/culprit | culprit/risk.py | .py | bcdc7aad69d95182 | 7.42 | 6 |
"""Test impact analysis: which existing tests should run for this change.
Walks the reverse-import graph (who imports whom) up to a few hops from the changed
files and collects the test files that reach them - directly (a test imports the
changed module) or transitively. Reuses ``blast_radius``'s reverse-import map an... | noordeen123/culprit | culprit/testimpact.py | .py | 91c1b085ce0c2f74 | 7.92 | 6 |
"""Fix verification: check if a proposed diff fully addresses the root cause.
Takes a not-yet-committed unified diff and checks completeness (other untouched call
sites), test coverage, and risk level, returning a verdict so the caller can iterate
before committing.
"""
from __future__ import annotations
from typing ... | noordeen123/culprit | culprit/verify_fix.py | .py | f79db2d1dd96f74c | 7.42 | 6 |
"""The reasoning-mode note must only appear when the run actually reasons.
`--verify-fix` and `--select-tests` return structured data and never build a
narrative, so telling the user about ANTHROPIC_API_KEY there is noise. An agent
calling verify_fix as a pre-commit gate should see the verdict and nothing else.
"""
im... | noordeen123/culprit | tests/test_cli_notes.py | .py | 57abd5e1f2cdb21b | 7.92 | 6 |
import os
import subprocess
import tempfile
import pytest
from githelper import git as _git
from culprit import completeness
@pytest.fixture()
def multi_call_repo():
"""`scale` is called from a.py and b.py; defined in util.py."""
d = tempfile.mkdtemp(prefix="culprit-comp-")
_git(d, "init", "-b", "main")... | noordeen123/culprit | tests/test_completeness.py | .py | d78b6e434b32a16f | 7.92 | 6 |
import os
import tempfile
import pytest
from githelper import git as _git
from culprit import cli, evolution, pr_context, suspect
@pytest.fixture()
def evo_repo():
"""origin commit creates a line, a middle commit edits it, a later commit
introduces the bug, and a fix branch corrects it."""
d = tempfile.... | noordeen123/culprit | tests/test_evolution.py | .py | fd2fb8f355865a76 | 7.92 | 6 |
import os
import tempfile
import pytest
from githelper import git as _git
from culprit import lifecycle, pr_context, suspect
@pytest.fixture()
def tagged_repo():
"""v1 predates the bug; the bug ships in v2; a fix branch corrects it.
History on main: feat (v1.0.0) -> fix: lint -> perf: tweak [BUG] (v2.0.0).... | noordeen123/culprit | tests/test_lifecycle.py | .py | 5dad00187458497e | 7.92 | 6 |
"""Tests for culprit.mcp_server: tool registration and basic invocation."""
import os
import tempfile
import pytest
from githelper import git as _git
@pytest.fixture()
def simple_repo():
"""A minimal repo with one bug-fix commit on top of a base."""
d = tempfile.mkdtemp(prefix="culprit-mcp-")
_git(d, "in... | noordeen123/culprit | tests/test_mcp_server.py | .py | ce84297311616d19 | 7.92 | 6 |
# core/config.py
"""YAML 配置文件读写,线程安全的便携式存储"""
import logging
import os
import tempfile
import threading
from copy import deepcopy
from datetime import datetime
from typing import Any
import yaml
logger = logging.getLogger(__name__)
# 默认配置模板
DEFAULT_CONFIG = {
"model": {
"last_path": "", # 上次选择的 ... | Narcissu-s1/llm-launcher | core/config.py | .py | b16139cff7406db1 | 7.48 | 8 |
# core/config_preset.py
"""预设导入/导出
将 ConfigStore 中的预设(presets / model_presets)打包为 JSON 文本,
便于用户间分享调参经验。
格式示例:
{
"version": 1,
"presets": {"code": {"temp": 0.2, ...}},
"model_presets": {"qwen2.5-7b": {"temp": 0.3, ...}}
}
"""
import json
import logging
from typing import Any
from core.config import Confi... | Narcissu-s1/llm-launcher | core/config_preset.py | .py | 3428b25dd5efff30 | 7.48 | 8 |
# core/events.py
"""异步事件总线:将事件放入队列,由单一 dispatch 线程消费并同步调用 subscriber"""
import logging
import threading
from queue import Queue, Empty
from typing import Callable
logger = logging.getLogger(__name__)
# 核心事件名称常量,统一引用避免拼写错误
EVENT_STATUS_CHANGED = "status_changed"
EVENT_LOG_LINE = "log_line"
EVENT_ERROR = "error"
EVENT... | Narcissu-s1/llm-launcher | core/events.py | .py | 54f040378289b50f | 7.48 | 8 |
# core/log_watcher.py
"""日志监控器:读取 subprocess 的 stdout/stderr 管道并推送事件"""
import logging
import threading
from core.events import EventBus, EVENT_LOG_LINE
from core.server_readiness import is_server_ready_log
logger = logging.getLogger(__name__)
# 需要高亮的关键词映射
KEYWORD_EVENTS = {
"error": "log_error",
"cuda erro... | Narcissu-s1/llm-launcher | core/log_watcher.py | .py | 0c10c8d904dee5a5 | 7.48 | 8 |
# core/model_library.py
"""扫描目录下的 GGUF 模型文件,解析基本元数据"""
import os
import struct
from dataclasses import dataclass, field
# GGUF 魔数
_GGUF_MAGIC = b"GGUF"
# 量化类型映射(GGUF type id → 名称)
_QUANT_NAMES = {
0: "F32", 1: "F16", 2: "Q4_0", 3: "Q4_1",
6: "Q5_0", 7: "Q5_1", 8: "Q8_0", 9: "Q8_1",
10: "Q2_K", 11: "Q3_K... | Narcissu-s1/llm-launcher | core/model_library.py | .py | dc984c149d4b21d2 | 7.48 | 8 |
# core/model_resolver.py
"""搜索 llama-server.exe 的路径解析器"""
import os
import shutil
class ModelResolver:
"""搜索 llama-server 可执行文件
搜索优先级:
1. config.yaml 中指定的 llama.cpp 目录
2. 当前工作目录
3. 同级 bin/ 子目录
4. PATH 环境变量
config_path 应为 llama.cpp 目录(包含 llama-server.exe 及相关 dll),
而非可执行文件本身。设为目录是为了确保... | Narcissu-s1/llm-launcher | core/model_resolver.py | .py | 397e939a6f9f8ae7 | 7.48 | 8 |
# core/process_manager.py
"""llama-server 进程生命周期管理:启动、停止、存活检测"""
import atexit
import logging
import os
import socket
import subprocess
import threading
import time
from collections import deque
from enum import Enum
from queue import Queue, Empty
import psutil
from core.events import EventBus, EVENT_STATUS_CHANGED,... | Narcissu-s1/llm-launcher | core/process_manager.py | .py | 9d076879a4bab5b5 | 7.48 | 8 |
# core/updater.py
"""在线更新检查
启动时后台调用 GitHub Releases API,比对最新版本与本地版本。
任何网络错误静默忽略——离线环境不应阻塞 UI。
设计原则:
- 不自动下载(避免损坏本地数据/触发杀毒)
- 不阻塞 UI(后台线程)
- 不在 release-info URL 中带 token
"""
import json
import logging
import threading
import urllib.error
import urllib.request
from dataclasses import dataclass
from core._version impo... | Narcissu-s1/llm-launcher | core/updater.py | .py | 90afb98aabd867d9 | 7.48 | 8 |
# core/config.py
"""YAML 配置文件读写,线程安全的便携式存储"""
import logging
import os
import threading
from copy import deepcopy
from typing import Any
import yaml
logger = logging.getLogger(__name__)
# 默认配置模板
DEFAULT_CONFIG = {
"model": {
"last_path": "", # 上次选择的 GGUF 模型路径
"mmproj_path": "", # m... | Narcissu-s1/llm-launcher | llm launcher_TUI原型/core/config.py | .py | 791527e6fcdf4d57 | 7.48 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.