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 |
|---|---|---|---|---|---|---|
#!/usr/bin/env python
"""
Generates OSV advisories from Drupal SA advisories stored on disk as JSON.
The advisories should be downloaded using the `scripts/download_sa_advisories.py`
"""
import json
import os
import re
import sys
import tomllib
import typing
from datetime import UTC, datetime
from urllib.parse impor... | DrupalSecurityTeam/drupal-advisory-database | scripts/generate_osv_advisories.py | .py | 5140a3f4d5d6ff97 | 7.42 | 6 |
#!/usr/bin/env python
"""
Precaches the Drupal nodes used by SA advisories,
to help reduce the pressure on the drupal.org api
"""
import json
import os
import time
import typing
from itertools import batched
import requests
from typings import drupal
from user_agent import user_agent
def fetch_drupal_nodes(nids: ... | DrupalSecurityTeam/drupal-advisory-database | scripts/precache_nodes.py | .py | b90ca304a188b58f | 7.42 | 6 |
import typing
EcosystemType = typing.Literal[
'AlmaLinux',
'Alpine',
'Android',
'Bioconductor',
'Bitnami',
'Chainguard',
'ConanCenter',
'CRAN',
'crates.io',
'Debian',
'GHC',
'GitHub Actions',
'Go',
'Hackage',
'Hex',
'Kubernetes',
'Linux',
'Mageia',
'Maven',
'npm',
'NuGet',
'... | DrupalSecurityTeam/drupal-advisory-database | scripts/typings/osv.py | .py | bdba0126cf5370cc | 7.42 | 6 |
"""Configurazione centralizzata.
Una `Config` costruita da variabili d'ambiente (.env). I parametri specifici di
ciascun provider vivono in `ProviderConfig` annidate. Aggiunge: finestra di
contesto e soglie di compaction, streaming, logging di sessione, prezzi
per-modello e chiavi per la ricerca web.
"""
from __futur... | NAST0R/flair | flair/config.py | .py | c11bc7b3edb0144e | 7.64 | 18 |
"""Potatura deterministica degli output di tool SUPERATI (stadio 0 della compaction).
Tra una compaction e l'altra gli output dei tool restano integri in contesto: sono
quasi tutti cache-hit (economici in $) ma occupano la finestra e anticipano la
compaction — che costa una chiamata LLM e, soprattutto, sostituisce il ... | NAST0R/flair | flair/core/prune.py | .py | 92f78e9acc7935dd | 7.64 | 18 |
"""Router per scegliere l'agente (modalità) di un turno.
Strategia:
0. Le continuazioni nude ("procedi", "ok", "vai", "go ahead"…) restano
deterministicamente sull'agente corrente, SENZA chiamata LLM: non contengono
alcun segnale di routing, e farle decidere a un modello può mandarle — a metà
task — sull'agen... | NAST0R/flair | flair/core/router.py | .py | c4e1800d16ae86f0 | 7.64 | 18 |
"""Astrazione dei tool.
Ogni tool tiene insieme, in un solo posto, la sua funzione e il suo schema
JSON. Questo elimina il drift tra "dispatch" e "schemi" che affliggeva il
vecchio progetto (due liste parallele da tenere sincronizzate a mano).
Un `Tool` è creato dal decoratore `@tool(...)`; resta richiamabile come un... | NAST0R/flair | flair/core/tool.py | .py | 0dbdf30704cc400c | 7.64 | 18 |
"""Provider per inference LOCALE OpenAI-compatibile (llama.cpp llama-server,
vLLM, LM Studio, ...).
Differenze rispetto alla base, pensate per llama-server:
- nessuna API key richiesta (default "local": il server non la verifica);
- prezzi a zero: i costi mostrati sono onesti ($0.0000), non stime da listino;
- `temper... | NAST0R/flair | flair/llm/local.py | .py | 7cac9e6d2b605735 | 7.64 | 18 |
"""Caricamento dei prompt di sistema e delle istruzioni di progetto."""
from __future__ import annotations
from pathlib import Path
from ..config import PROJECT_INSTRUCTION_FILES
_DIR = Path(__file__).resolve().parent
_MAX_PROJECT_CHARS = 8000
def load(name: str) -> str:
path = _DIR / f"{name}.md"
if not ... | NAST0R/flair | flair/prompts/__init__.py | .py | 3142b6f8ae62fa2c | 7.64 | 18 |
"""Osservabilità: log di sessione in JSONL e log su file degli eventi interni.
Il `SessionLogger` scrive un record per turno (task, risposta, tool usati, usage)
così da poter analizzare a posteriori dove vanno i token. Vive nella CLI, che
intercetta già i callback dei tool — l'agente resta disaccoppiato dal logging.
"... | NAST0R/flair | flair/session_log.py | .py | 749ac417d79f5779 | 7.64 | 18 |
"""Persistenza delle sessioni: salva e riprende lo stato della conversazione.
Una sessione è un file JSON `<nome>.json` nella cartella sessioni. Contiene la
conversazione condivisa dai due agenti (messaggi + uso cumulativo) e l'ultimo
agente attivo, così da poter chiudere flair e riprendere da dove si era.
Tutto best... | NAST0R/flair | flair/session_store.py | .py | 1d2b54056ab3bbee | 7.64 | 18 |
"""Immagini per gli endpoint con vision (content multipart OpenAI-style).
Il canale dei tool è SOLO TESTO per protocollo (i messaggi role:"tool" non
portano parti immagine in modo portabile): il tool `view_image` quindi valida e
codifica l'immagine, la DEPOSITA nella staging area del ToolContext e risponde
con una con... | NAST0R/flair | flair/tools/images.py | .py | 8399bf20b5879bb7 | 7.64 | 18 |
"""Esecuzione robusta di comandi di shell, multipiattaforma.
Due problemi che questo modulo risolve:
1. Su Windows i comandi multi-riga passati a cmd.exe (shell=True) vengono spezzati
sui ritorni a capo: un `powershell -Command "...multi-riga..."` non arriva intatto
e fallisce silenziosamente.
2. Gli script Pow... | NAST0R/flair | flair/tools/shell.py | .py | 24a0f24e696dde29 | 7.64 | 18 |
"""Tool `explore`: delega una ricerca a un sub-agente in sola lettura con contesto
ISOLATO.
L'esplorazione (molte `read_file`/`grep`/`repo_map`) resta nel contesto del
sub-agente e non gonfia quello del genitore: torna solo la sintesi finale. È la
leva principale di economia di token sui task grandi — più una capacità... | NAST0R/flair | flair/tools/subagent.py | .py | 5da45e9f8927d337 | 7.64 | 18 |
"""Task di valutazione per flair (eval harness).
Ogni task è autosufficiente: prepara una cartella di lavoro, dà un prompt
all'agente e verifica il risultato in modo deterministico. Si eseguono dal vivo
con `run_evals.py` (servono le API key, come per flair); il runner riporta per
ciascuno successo, passi, token e cac... | NAST0R/flair | tests/evals/tasks.py | .py | d34396684c91607c | 8.14 | 18 |
#!/usr/bin/env python3
# Copyright 2026 Carlos Andrés Planchón Prestes
# Licensed under the Apache License, Version 2.0
"""Turn one locally verified signature into one redacted conformance row.
Gaps 1 and 2 of docs/security-invariants.md close with variety, not with code: certificates
issued in different years, cards... | carlosplanchon/firmauy | scripts/conformance_row.py | .py | 017ea28ac50788fc | 7.48 | 8 |
# Copyright 2026 Carlos Andrés Planchón Prestes
# Licensed under the Apache License, Version 2.0
"""Uruguayan cédula de identidad (CI) check-digit validation.
This is a purely **arithmetic consistency check** of a CI number using the standard weighted
check-digit algorithm (weights 2 9 8 7 6 3 4 over the 7-digit body... | carlosplanchon/firmauy | src/firmauy/ci.py | .py | 243becce3c9db549 | 7.48 | 8 |
# Copyright 2026 Carlos Andrés Planchón Prestes
# Licensed under the Apache License, Version 2.0
from dataclasses import dataclass
from enum import Enum
@dataclass(frozen=True)
class StampFields:
"""Which of the five lines the visible stamp prints.
One object rather than five booleans threaded through every... | carlosplanchon/firmauy | src/firmauy/constants.py | .py | 76dcf250f48b2222 | 7.48 | 8 |
# Copyright 2026 Carlos Andrés Planchón Prestes
# Licensed under the Apache License, Version 2.0
import getpass
import os
import sys
from enum import Enum
from typing import Optional
import typer
class PinSource(str, Enum):
prompt = "prompt"
env = "env"
stdin = "stdin"
fd = "fd"
def _read_pin_inte... | carlosplanchon/firmauy | src/firmauy/pin.py | .py | f7c822b26051fbe7 | 7.48 | 8 |
# Copyright 2026 Carlos Andrés Planchón Prestes
# Licensed under the Apache License, Version 2.0
"""Shared result types and helpers for signature verification (XML, PDF and CMS).
Indication model (mirrors the EU DSS semantics):
- VALID: integrity holds and the chain is trusted.
- INDETERMINATE: integrity hold... | carlosplanchon/firmauy | src/firmauy/verify_common.py | .py | 5894590c94e0f010 | 7.48 | 8 |
# Copyright 2026 Carlos Andrés Planchón Prestes
# Licensed under the Apache License, Version 2.0
"""Standards-based XAdES-BES enveloped XML signing (ETSI EN 319 132).
The cédula private key is non-extractable, so the raw RSA-SHA256 operation is
delegated to the token via a `signer` callable (two-phase / delegated sig... | carlosplanchon/firmauy | src/firmauy/xml_sign.py | .py | adca4d91aa50fdcc | 7.48 | 8 |
# Copyright 2026 Carlos Andrés Planchón Prestes
# Licensed under the Apache License, Version 2.0
"""Standards-based XAdES-BES verification (the verify side of `xml_sign`).
Tiered, mirroring the DSS indication model:
- **Level 1** (offline, always): signature integrity (SignedInfo signature + each
Reference digest)... | carlosplanchon/firmauy | src/firmauy/xml_verify.py | .py | 3cc457d47d271493 | 7.48 | 8 |
"""Unit tests for detached CAdES/.p7s signing & verification (cms_sign / cms_verify).
These run without a token: they sign with an in-memory RSA key via pyHanko's
SimpleSigner and verify through the same code path the CLI uses.
"""
import datetime
import pytest
from asn1crypto import cms as asn1cms
from asn1crypto i... | carlosplanchon/firmauy | tests/test_cms.py | .py | 8dcd3e3ce49b5758 | 7.98 | 8 |
# Copyright 2026 Carlos Andrés Planchón Prestes
# Licensed under the Apache License, Version 2.0
"""The conformance row keeps its redaction promise, or it prints nothing.
The row is designed to be pasted into a public GitHub issue by people reporting how firmauy and
firma.gub.uy judged the same document. The one way ... | carlosplanchon/firmauy | tests/test_conformance_row.py | .py | 17f42a5550ede306 | 7.98 | 8 |
"""End-to-end CAdES (sign-any) integration test against a SoftHSM2 token.
Signs an arbitrary file through the real PKCS#11 path (`firmauy sign-any`) and
verifies the detached `.p7s` both with the project's own verifier and, when
available, with `openssl cms -verify`. Skipped when SoftHSM2 / OpenSC are missing.
"""
im... | carlosplanchon/firmauy | tests/test_integration_cms.py | .py | fdc35f160e510703 | 7.98 | 8 |
# Copyright 2026 Carlos Andrés Planchón Prestes
# Licensed under the Apache License, Version 2.0
"""docs/security-invariants.md makes claims about this repository, and this file holds them up.
The page names tests, cites counterexamples, maps matrix rows to clause labels it quotes, and
links files and anchors. Every ... | carlosplanchon/firmauy | tests/test_invariants_doc.py | .py | 6fd641f1dc363202 | 7.98 | 8 |
"""Robustness of verify_xml against malformed / adversarial XAdES structures.
A verifier is routinely handed untrusted input, so a structurally broken signature must produce
a clean INVALID indication, never an uncaught internal exception (e.g. AttributeError)."""
import base64
import pytest
from cryptography.hazmat... | carlosplanchon/firmauy | tests/test_xml_verify.py | .py | 5262e85b9198fbbc | 7.98 | 8 |
import asyncio
from concurrent.futures import ThreadPoolExecutor
import os
import re
from ipwhois import IPWhois
from aiofiles import open as aio_open
def alphanumeric_key(s):
return [int(text) if text.isdigit() else text.lower() for text in re.split('([0-9]+)', s)]
def get_cidr_sync(ip):
"""Perform the IP lo... | Maks-gaming/discord-servers | src/generate_cidr_list.py | .py | a85356d485844afc | 7.45 | 7 |
# Copied from https://github.com/nasaharvest/presto
# Licensed under the MIT License.
from typing import List, Optional
from collections import OrderedDict
from typing import OrderedDict as OrderedDictType
import torch
import numpy as np
import warnings
"""
For easier normalization of the band values (instead of need... | microsoft/rice-irrigation-mapping-s1s2 | ricemapper/models/presto/utils.py | .py | 044322eb04039526 | 7.57 | 13 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import ee
import pandas as pd
class Era5Collections:
def __init__(
self,
aoi,
start_date,
end_date,
cadence=["monthly", "daily"],
vars=["temperature_2m", "total_precipitat... | microsoft/rice-irrigation-mapping-s1s2 | ricemapper/utils/gee/era5.py | .py | 207509f02d8f797e | 7.57 | 13 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import ee
import pandas as pd
from typing import Optional
from ricemapper.utils.utils import convert_tuple2dates, stringify_date
class Sentinel2Collections:
def __init__(
self,
start_date,
end_d... | microsoft/rice-irrigation-mapping-s1s2 | ricemapper/utils/gee/s2.py | .py | 3146a8c13e3c931e | 7.57 | 13 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import ee
import geopandas as gpd
import numpy as np
from datetime import date
from tqdm import tqdm
def flatten_sat_embeddings(
gdf: gpd.GeoDataFrame, emb_column: str = "sat_embs", prefix: str = "emb_", drop=True
) -> ... | microsoft/rice-irrigation-mapping-s1s2 | ricemapper/utils/gee/sat_embs.py | .py | 61ac8653b52da19a | 7.57 | 13 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import geopandas as gpd
import rasterio
from exactextract import exact_extract
from glob import glob
import tqdm
import os
from dotenv import load_dotenv
def filter_polygons_inside_mask_fast(gdf, mask_path):
"""
Fas... | microsoft/rice-irrigation-mapping-s1s2 | scripts/ftw/mask_polygons.py | .py | e25ece1522153006 | 7.57 | 13 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#!/usr/bin/env python3
"""
District Level Predictions and Comparison to Government Records
This script visualizes rice irrigation predictions at the district level and
compares them to government estimates. It generates bar ... | microsoft/rice-irrigation-mapping-s1s2 | scripts/visualization/district_results.py | .py | eb75faab2bcb30c5 | 7.57 | 13 |
#!/usr/bin/env python3
"""Autonomous agent: fetch oldest open issue, generate implementation, create PR.
Uses the recommended free-cloud brain (Cerebras -> Groq -> NVIDIA NIM, by which
key is present) and a slop-gate (slop_gate.py) that refuses destructive /
low-quality output before opening a PR — so an empty or garb... | strikersam/autonomous-ai-agency | .github/scripts/autonomous_agent.py | .py | d6ffeef4d0dae4ab | 7.48 | 8 |
#!/usr/bin/env python3
"""Autonomous CI fix: find open PRs with failing checks, generate a minimal fix,
verify it locally, and push it — or decline and say why.
Replaces an inline, ungated script that used to write an LLM's raw JSON output
straight to disk with no review. That produced two real incidents on PR #1285
w... | strikersam/autonomous-ai-agency | .github/scripts/autonomous_fix.py | .py | bac30f9a53daea2c | 7.48 | 8 |
from __future__ import annotations
"""
Multi-strategy URL content fetcher for process-quick-note workflow.
Exit codes:
0 — success, content written to /tmp/note_content.txt
2 — all strategies exhausted, URL inaccessible
1 — bad args / unexpected error
"""
import re
import sys
import urllib.parse
import urllib... | strikersam/autonomous-ai-agency | .github/scripts/fetch_url.py | .py | dceb7354c63bf8fd | 7.48 | 8 |
#!/usr/bin/env python3
"""Ask every configured provider what it actually serves.
Model ids in this repo were guessed for months, and the guesses rotted: four
separate outages, each one a hand-edited id that a vendor had retired. The
guessing was not laziness — it was unavoidable. The keys live in CI and Render,
a deve... | strikersam/autonomous-ai-agency | .github/scripts/probe_catalogues.py | .py | 26d6688dbbf4263e | 7.48 | 8 |
"""
.github/scripts/provider_policy.py — Read the durable provider policy from the
backend API with a hard failsafe: allow_paid=False when the API is unreachable.
CI scripts (generate_context, apply_review, review_agent, ci-failure-autofix)
import this to decide whether paid LLM providers (Anthropic) may be used.
Usa... | strikersam/autonomous-ai-agency | .github/scripts/provider_policy.py | .py | bbb5e5d57b2f590f | 7.48 | 8 |
from __future__ import annotations
"""
Council-review agent using NVIDIA NIM.
Fetches the git diff of a PR branch vs master and runs the council-review
skill (Security, Correctness, Performance, Maintainability reviewers).
Usage:
python review_agent.py <pr_number>
Writes /tmp/review_result.json with:
{"verdict"... | strikersam/autonomous-ai-agency | .github/scripts/review_agent.py | .py | 94ac1fdfca61d9c5 | 7.48 | 8 |
#!/usr/bin/env python3
"""OpenClaw security fix helper.
Lightweight CLI used by CI to check/fix Dependabot and CodeQL alerts.
Designed to fail-safe: check commands print counts; fix commands attempt work and exit 0.
"""
from __future__ import annotations
import os
import sys
from typing import Any
import requests
... | strikersam/autonomous-ai-agency | .github/scripts/security_fix_agent.py | .py | 58b80e1350991401 | 7.48 | 8 |
#!/usr/bin/env python3
"""Reusable slop-gate for the autonomous PR-generating scripts.
Auto-PR scripts call a model on a vague issue and write whatever comes back.
Without a guard, an empty/garbled model response silently overwrites working
code — e.g. PR #833 replaced an 892-line ``direct_chat.py`` with ``{}`` and
op... | strikersam/autonomous-ai-agency | .github/scripts/slop_gate.py | .py | 60176db0cb9e2c81 | 7.48 | 8 |
"""Extract a usable text transcript from a video URL, without an API key.
Why this exists: quick-note issues carry their whole value in a URL, and some of
those URLs are videos. `fetch_url.py` strips a YouTube watch page down to
navigation chrome and a title — no spoken content — so context generated from a
video link... | strikersam/autonomous-ai-agency | .github/scripts/video_transcript.py | .py | 6577f817bb74dfb4 | 7.48 | 8 |
"""Insert a single new [Unreleased] / ### Added bullet into BOTH changelogs.
Idempotent (no-op if the bullet already present). Writes byte-identical content
to both files so scripts/check_changelog_parity.py stays green.
Reviewer fixes vs prior version:
* Entry text rewritten: dropped developer jargon ("monkeypatch... | strikersam/autonomous-ai-agency | _scripts/_add_colibri_shim_changelog_entry.py | .py | 7a38f8bcf64bc748 | 7.48 | 8 |
"""Pull the python-test failure log via gh run view --log and print the failing-test
summary block.
Writes the log to %TEMP%\\_last_failed_pytest_<dbId>.log so:
- multiple failure runs coexist instead of clobbering each other
- the file lands outside the repo tree (no spurious untracked entries)
Reviewer fixes fo... | strikersam/autonomous-ai-agency | _scripts/_fetch_pytest_failures.py | .py | df7d08e88d04b88e | 7.98 | 8 |
"""★7 Adaptive Loop Halting — velocity-based agent run termination.
Complements StuckDetector (tool-loop pattern detection) with a higher-level
progress monitor that watches the STEP loop, not the tool loop.
Halts a run when the plan is clearly not converging, preventing unnecessary
token burn on plans that have beco... | strikersam/autonomous-ai-agency | agent/adaptive_halting.py | .py | 63b1b00c9cd8d49c | 7.48 | 8 |
"""Autonomy gate — enforce 'agents propose via PR, humans merge'.
The agency can write code, but autonomous (agent-initiated) actions must never:
* commit or push to a protected branch (main/master), or
* merge a pull request.
This is a *security control*: it bounds what the autonomous loop can do to the
r... | strikersam/autonomous-ai-agency | agent/autonomy_gate.py | .py | 8d0cfa23ab527327 | 7.48 | 8 |
"""
Cached LLM Client wrapper.
Drop-in wrapper around any LLM API call that transparently applies
InferenceCache. Designed to wrap the agent's existing LLM calls.
"""
import logging
import time
from typing import Any, Callable, Optional
from agent.inference_cache import InferenceCache, DEFAULT_TTL_SECONDS... | strikersam/autonomous-ai-agency | agent/cached_llm.py | .py | a2dbf8e12940b780 | 7.48 | 8 |
"""Durable agent checkpointing for crash-recovery and resumption.
Provides serialisable snapshots of AgentRunner state so long-running
sessions can survive process restarts and resume from the last checkpoint.
Feature-gated by ``AGENT_CHECKPOINT_ENABLED`` (default: true).
"""
from __future__ import annotatio... | strikersam/autonomous-ai-agency | agent/checkpoint.py | .py | f7154c63bc767265 | 7.48 | 8 |
"""doctor.py — Agent-side doctor diagnostics: environment, provider, and workspace checks."""
from __future__ import annotations
import shutil
import subprocess
import httpx
import logging
import os
from typing import Any, Dict, List, Optional
from pydantic import BaseModel
log = logging.getLogger("qwen-agen... | strikersam/autonomous-ai-agency | agent/doctor.py | .py | cde2c0ca4cc55f5d | 7.48 | 8 |
"""agent/harness_spec.py — the Continual Harness: a persistent, cited spec.
Borrowed from Prime Agent's "Continual Harness" idea: the agent keeps a durable
document about *how to work in this repo* and refines it as evidence arrives, so
run N+1 starts smarter than run N. `agent/lessons.py` already records why steps
fa... | strikersam/autonomous-ai-agency | agent/harness_spec.py | .py | c910484811132c26 | 7.98 | 8 |
"""
FastApiPrometheusLite
This module was inspired by the structure and design philosophy of the 'prometheus-fastapi-instrumentator'
and similar Prometheus client libraries for FastAPI.
Credits:
- Prometheus Python Client (https://github.com/prometheus/client_python)
- FastAPI Prometheus Instrumentator (https://githu... | luzzodev/fastapi-prometheus-lite | fastapi_prometheus_lite/instrumentor.py | .py | 5cbef7e764f60bb6 | 7.48 | 8 |
import logging
import re
import timeit
from contextlib import ExitStack
from typing import Pattern
from fastapi import FastAPI
from prometheus_client import CollectorRegistry
from starlette.datastructures import Headers
from starlette.responses import Response
from starlette.routing import Mount, Route
from starlette.... | luzzodev/fastapi-prometheus-lite | fastapi_prometheus_lite/middleware.py | .py | a3a54513a2e84243 | 7.48 | 8 |
"""
FastApiPrometheusLite
'generate_latest' function comes directly from Prometheus Python Client. Has been changed to add only static_labels.
Credits:
- Prometheus Python Client (https://github.com/prometheus/client_python)
"""
from typing import Dict, List, Optional
from prometheus_client import REGISTRY, Collec... | luzzodev/fastapi-prometheus-lite | fastapi_prometheus_lite/registry/utils.py | .py | a1e7e7c28a51334c | 7.48 | 8 |
from typing import Union
from starlette.routing import Match, Mount, Route, WebSocketRoute
from starlette.staticfiles import StaticFiles
from starlette.types import Scope
try:
# FastAPI >=0.137 resolves include_router(prefix=...) / nested-router prefixes
# through this private context instead of baking them i... | luzzodev/fastapi-prometheus-lite | fastapi_prometheus_lite/starlette_patcher.py | .py | 25c3d3d256f3858b | 7.48 | 8 |
"""
Integration tests for ``matched_path_template`` resolution across the different
ways routes can be registered on a FastAPI app:
- direct routes (with/without path params)
- ``include_router`` with a prefix given on the router
- ``include_router`` with a prefix given at include-time
- nested routers (router include... | luzzodev/fastapi-prometheus-lite | tests/test_include_router_combinations.py | .py | e40c52eda22b1c46 | 7.98 | 8 |
"""
Regression test for a concurrency bug in the live-collector pattern, driven
through a real FastAPI app.
A single live-collector instance is shared across all requests, and per-request
state is stored via ``update_scope`` (read back through ``self._scope``).
``__enter__`` runs synchronously right after ``update_sco... | luzzodev/fastapi-prometheus-lite | tests/test_live_collector_concurrency.py | .py | dd32bb89010378f9 | 7.98 | 8 |
from functools import wraps
from typing import Callable
from fastapi_prometheus_lite.starlette_patcher import RouteType
def unpatch_starlette_routes(*route_classes: type[RouteType]) -> None:
"""
Unpatch Starlette routes.
This unpatch is idempotent and safe to call multiple times.
:param route_class... | luzzodev/fastapi-prometheus-lite | tests/utils.py | .py | 9dc256dfec35a39e | 7.98 | 8 |
"""Verify EVERY flag-table entry against the tool's own --help output.
The source comment and CHANGELOG claim these tables were "verified entry by
entry". This is the check that makes the claim true, run per entry rather than
per table. A boolean entry that actually takes a value is the fail-OPEN
direction -- its valu... | Consiliency/pmcp | .consiliency/notes/verify_tables.py | .py | c43d5f881f46c01e | 7.66 | 20 |
"""Drive a real downstream tool call through a running gateway.
Usage: p1_probe_client.py <gateway streamable-http url> (e.g. .../mcp)
Used by the `min-version-smoke` CI job as the acceptance step for the declared
`mcp` floor. It connects to the gateway over Streamable HTTP, brings the
`p1probe` stdio fixture onlin... | Consiliency/pmcp | .github/probe/p1_probe_client.py | .py | ebcff88df3c5bd7f | 7.66 | 20 |
"""Single-trial probe for the "SSE stream ended without a response" flake.
Investigation note: .consiliency/notes/sse-stream-ended-investigation-20260812.md
Drives concurrent connect/disconnect + concurrent tool-call traffic against N
real, in-process `fake_remote` Streamable HTTP servers (the same harness
`tests/run... | Consiliency/pmcp | scripts/probes/sse_flake_probe.py | .py | 0011123bc5b661ca | 7.66 | 20 |
"""Single-trial probe, variant 2: deliberately race a tool call against a
disconnect of the SAME server, instead of hoping organic load produces the
race.
Rationale (see the investigation note): `fake_remote`'s `MCPServer` is built
with no `event_store`, so `mcp.server.streamable_http`'s per-event `event_id`
(`.venv/.... | Consiliency/pmcp | scripts/probes/sse_flake_probe_interrupt.py | .py | e0a9457f8152e72f | 7.66 | 20 |
"""Detect how `pmcp` was installed on the current host.
Supports two install paths used in practice:
- `uv tool install pmcp` — lives under `~/.local/share/uv/tools/pmcp`
- `pip install --user pmcp` — lives under the Python user-site tree
Both typically shim `~/.local/bin/pmcp`, so having a binary on PATH does
not te... | Consiliency/pmcp | src/pmcp/cli_commands/install.py | .py | d365d32168cbafc4 | 7.66 | 20 |
"""Secrets command handlers for PMCP CLI."""
from __future__ import annotations
import argparse
import re
from pathlib import Path
from pmcp.config.loader import load_configs
from pmcp.env_store import (
read_env_file,
resolve_project_root,
resolve_scope_path,
set_env_value,
validate_env_var_name... | Consiliency/pmcp | src/pmcp/cli_commands/secrets.py | .py | ea0998d88bf37849 | 7.66 | 20 |
"""Guidance configuration for code execution patterns.
This module handles loading and managing configuration for the code execution
guidance system that helps models use PMCP more effectively.
"""
from __future__ import annotations
from pathlib import Path
from typing import Literal
import yaml
from pydantic impor... | Consiliency/pmcp | src/pmcp/config/guidance.py | .py | 9a2c93f647203c30 | 7.66 | 20 |
"""Shared PMCP credential env-file storage helpers."""
from __future__ import annotations
import os
import re
from collections.abc import Mapping
from pathlib import Path
from dotenv import dotenv_values
from pmcp.config.loader import find_project_root
ENV_VAR_NAME_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")... | Consiliency/pmcp | src/pmcp/env_store.py | .py | 2700754b832280ff | 7.66 | 20 |
"""Structured error codes for MCP Gateway.
Error Code Categories:
- E1xx: Configuration errors
- E2xx: Connection/server errors
- E3xx: Tool invocation errors
- E4xx: Policy violations
- E5xx: Installation errors
"""
from __future__ import annotations
from enum import Enum
from typing import Any
from pydantic impor... | Consiliency/pmcp | src/pmcp/errors.py | .py | 098b11ce1dd80dd2 | 7.66 | 20 |
"""Gateway identity detection to prevent recursive spawning.
This module provides functions to detect if a server configuration would
spawn another instance of the gateway, preventing infinite recursion.
"""
from __future__ import annotations
import logging
import os
import sys
from pathlib import Path
f... | Consiliency/pmcp | src/pmcp/identity.py | .py | d51c20333157597f | 7.66 | 20 |
"""Code pattern hint loader and matcher.
This module loads code pattern hints from YAML and matches them to tools
to provide L1 guidance in capability cards.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
import yaml
class CodePatternsLoader:
"""Loads and matches code p... | Consiliency/pmcp | src/pmcp/manifest/code_patterns_loader.py | .py | 73038eca39b8dcd8 | 7.66 | 20 |
"""Environment detection - platform and CLI availability."""
from __future__ import annotations
import asyncio
import logging
import os
import platform
import shutil
from dataclasses import dataclass, field
from typing import Literal
logger = logging.getLogger(__name__)
Platform = Literal["mac", "wsl", "linux", "wi... | Consiliency/pmcp | src/pmcp/manifest/environment.py | .py | 4ad757c6e01f0089 | 7.66 | 20 |
"""Capability matcher - keyword-based matching of requests to manifest entries."""
from __future__ import annotations
import logging
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Literal
from pmcp.manifest.environment import CLIInfo
from pmcp.manifest.loader import CLIAlter... | Consiliency/pmcp | src/pmcp/manifest/matcher.py | .py | 0cd5865bbced8e23 | 7.66 | 20 |
"""Read-only MCP Registry to manifest reconciliation."""
from __future__ import annotations
from dataclasses import dataclass, field
from pmcp.manifest.loader import Manifest
from pmcp.manifest.registry import (
RegistryCache,
RegistryServerEntry,
_server_identity,
)
@dataclass
class RegistrySyncResult... | Consiliency/pmcp | src/pmcp/manifest/sync.py | .py | 659f24d6a72eff25 | 7.66 | 20 |
"""Policy Layer - Handles allow/deny lists, output caps, and secret redaction."""
from __future__ import annotations
import fnmatch
import hashlib
import json
import logging
import re
from pathlib import Path
from typing import Any
import yaml
from pmcp.types import GatewayPolicy
from pmcp.auth import sanitize_auth... | Consiliency/pmcp | src/pmcp/policy/policy.py | .py | a30c6554db078a88 | 7.66 | 20 |
"""Non-secret remote header authentication helpers."""
from __future__ import annotations
import os
import re
from collections.abc import Callable, Mapping
from dataclasses import dataclass, field
from pathlib import Path
REMOTE_HEADER_ENV_PATTERN = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
TENANT_ID_PATTERN = r... | Consiliency/pmcp | src/pmcp/remote_auth.py | .py | b0e60ce2092704fe | 7.66 | 20 |
"""Small import-safety decisions shared by the Beets web import flow."""
from __future__ import annotations
import re
from typing import Callable, Dict, Iterable, List, Optional
def existing_track_matches_target(
*,
fingerprint_status: str = "",
exact_mbid: bool = False,
title_score: float = 0.0,
... | Iranman/beets-web-manager | backend/import_guard.py | .py | b7795bec5878f9ee | 7.52 | 10 |
"""Conservative title normalization helpers for import/search text."""
from __future__ import annotations
import re
_TIME_LIKE_HYPHEN_RE = re.compile(r"(?<!\d)(\d{1,2})[-‐‑‒–—](\d{2})(?!\d)")
def restore_time_colon_title(value: str) -> str:
"""Restore album/title punctuation commonly flattened by filesystems.
... | Iranman/beets-web-manager | backend/title_normalize.py | .py | 94e86d967f05baba | 7.52 | 10 |
"""Wave 26 AI Batch Import acceptance seeding helper (PR #101, section 24).
Runs INSIDE the beets-web-manager container (copied in via `docker cp` by
scripts/verify_two_service_docker_acceptance.py, never baked into the
image). It talks to the exact same `backend.ai_batch_state_store.
AiBatchStateStore` / DB path the ... | Iranman/beets-web-manager | docker/acceptance/ai_batch_seed.py | .py | 593932365d713d94 | 7.52 | 10 |
"""Build-time, version-aware compatibility patch for the Beets engine image.
Upstream issue: beetbox/beets#6033
Upstream fix: beetbox/beets#6039 (released in Beets 2.5.0)
Beets 2.4.0's _get_plugin() iterates a plugin module's __dict__ in insertion order
and selects the first concrete BeetsPlugin subclass. When a pl... | Iranman/beets-web-manager | docker/beets/apply_patches.py | .py | b6ec2644064f3892 | 7.52 | 10 |
#!/usr/bin/env python3
"""Small CI-safe secret scanner for this repository.
The scanner prints path, line, and rule only. It never prints the matched value.
It is intentionally conservative enough for CI while catching high-confidence
private keys, provider tokens, and committed config credentials.
"""
from __future__... | Iranman/beets-web-manager | scripts/security_secret_scan.py | .py | 834285ed41471291 | 7.52 | 10 |
#!/usr/bin/env python3
"""Seed a small, safe demo music library.
Generates a handful of short sine-wave WAV files (self-synthesized audio —
not copied from any real recording, so there is no copyright concern) tagged
with clearly-fake "Demo Artist / Demo Album" metadata. Lets a new user click
through the import/librar... | Iranman/beets-web-manager | scripts/seed_demo_library.py | .py | f3d912b11ec55c45 | 7.52 | 10 |
"""CI gate for the ARCH-003 mutation inventory.
SEC-002 / ARCH-003 final closure review, findings #15-#27: the previous
version of this script only validated the hand-written inventory JSON's
internal consistency (spelling of classifications, existence of named
transaction families) and one hardcoded literal-string ch... | Iranman/beets-web-manager | scripts/verify_arch003_mutation_inventory.py | .py | 4af88a62cabfe144 | 7.52 | 10 |
"""CLI surface: run command — single prompt processing dispatch.
Smart surface: maps parsed args/config to the correct specialized pipeline
orchestrator based on AppConfig.mode, then delegates with zero business logic.
"""
from __future__ import annotations
from modules.shared.src.contract_core_aggregate import (
... | rakaarwaky/qwen-web-arwaky | modules/cli/src/surface_cli_run_command.py | .py | eae927bf2cae78d8 | 7.54 | 11 |
"""CLI surface: Textual-based Session Setup submenu."""
from __future__ import annotations
from collections.abc import Callable
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Vertical
from textual.screen import ModalScreen, Screen
from textual.widgets im... | rakaarwaky/qwen-web-arwaky | modules/cli/src/surface_cli_session_setup.py | .py | 39fbda2899fd7d0e | 7.54 | 11 |
"""CLI surface: update command — self-update & environment synchronization (AES406).
Smart surface: presentation only. Version discovery, pip upgrade, Playwright
Chromium synchronization, and post-flight health checks are owned by the update
manager capability (IUpdateProtocol); this surface formats reports and maps
o... | rakaarwaky/qwen-web-arwaky | modules/cli/src/surface_cli_update_command.py | .py | b2604d09732c1b2a | 7.54 | 11 |
"""Agent: session orchestrator (AES405).
Orchestrates session validation and deletion using browser protocol.
"""
from __future__ import annotations
import shutil
from pathlib import Path
from modules.core.src.utility_core_config_factory import build_app_config
from modules.shared.src.contract_core_aggregate import... | rakaarwaky/qwen-web-arwaky | modules/core/src/agent_session_orchestrator.py | .py | e047ba790b5f77cd | 7.54 | 11 |
"""Capabilities: job persistence and state management (AES403).
Implements IJobStorageProtocol.
"""
from __future__ import annotations
import json
from dataclasses import asdict
from pathlib import Path
from modules.core.src.utility_core_io_writer import atomic_write_text
from modules.core.src.utility_core_logger_f... | rakaarwaky/qwen-web-arwaky | modules/core/src/capabilities_job_manager.py | .py | 7a448aae74f1dac9 | 7.54 | 11 |
"""Capabilities: file saver (AES403).
Implements ISaverProtocol.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
from modules.core.src.utility_core_io_writer import atomic_write_text, ensure_dir, write_json_file
from modules.core.src.utility_core_logger_factory import get_logg... | rakaarwaky/qwen-web-arwaky | modules/core/src/capabilities_output_saver.py | .py | bb945759a48cbc96 | 7.54 | 11 |
"""Capabilities: prompt injection via DOM (AES403).
Implements IInjectionProtocol.
"""
from __future__ import annotations
import contextlib
from typing import Any
from playwright.sync_api import Error, Page
from modules.core.src.utility_core_dom_helper import first_visible_element_handle
from modules.core.src.util... | rakaarwaky/qwen-web-arwaky | modules/core/src/capabilities_prompt_injector.py | .py | c188a500fa743c92 | 7.54 | 11 |
"""Capabilities: send button dispatcher (AES403).
Implements ISendProtocol.
"""
from __future__ import annotations
import contextlib
import time
from playwright.sync_api import Error, Page
from modules.core.src.utility_core_dom_helper import click_send as _dom_click_send
from modules.core.src.utility_core_dom_quer... | rakaarwaky/qwen-web-arwaky | modules/core/src/capabilities_send_dispatcher.py | .py | eb5234044b0ca3ff | 7.54 | 11 |
"""Capabilities: workspace provisioner (AES403).
Implements IWorkspaceProtocol — workspace initialization with XDG directories,
SKILL.md provisioning, .qwen-web symlinks, and .gitignore management.
All file system I/O for workspace setup lives here.
"""
from __future__ import annotations
import os
import shutil
from... | rakaarwaky/qwen-web-arwaky | modules/core/src/capabilities_workspace_provisioner.py | .py | 9c0f61209e3dabc5 | 7.54 | 11 |
"""Root: single DI container for CLI and MCP features.
Wires the 5 specialized agent orchestrators with capability implementations.
"""
from __future__ import annotations
from pathlib import Path
# agent_attachment_prompt_orchestrator
from modules.core.src.agent_attachment_prompt_orchestrator import AttachmentPromp... | rakaarwaky/qwen-web-arwaky | modules/core/src/root_core_container.py | .py | 0949c0238ca54556 | 7.54 | 11 |
"""
Utility layer (utility_core_config_factory): build AppConfig and derive paths.
Stateless functions consumed by Agent orchestrator and StatusFileWriter.
"""
from __future__ import annotations
import os
from pathlib import Path
from modules.shared.src.taxonomy_core_constant import (
DEFAULT_LOG,
DEFAULT_OU... | rakaarwaky/qwen-web-arwaky | modules/core/src/utility_core_config_factory.py | .py | a2fb9144610f4fd7 | 7.54 | 11 |
"""DOM query utilities for Playwright pages.
Utility layer (utility_core_dom_query): stateless functions for DOM reading.
Consumed by SendDispatcher, StreamMonitor, and Agent.
Taxonomy constants + Playwright Page only.
"""
from __future__ import annotations
from playwright.sync_api import Error, Page
from modules.s... | rakaarwaky/qwen-web-arwaky | modules/core/src/utility_core_dom_query.py | .py | a22eba4bf8e2270d | 7.54 | 11 |
"""Filesystem writer utilities.
Utility layer (utility_core_io_writer): atomic file writing, JSONL append,
and directory creation helpers. Stateless functions consumed by Saver
and StatusFileWriter.
"""
from __future__ import annotations
import json
from collections.abc import Mapping
from contextlib import suppress... | rakaarwaky/qwen-web-arwaky | modules/core/src/utility_core_io_writer.py | .py | 3ae8e27990362511 | 7.54 | 11 |
"""Core aggregate contracts — business-logic APIs for all surfaces.
Taxonomy layer (contract(aggregate)): implemented by agent orchestrators and
consumed by CLI and MCP surfaces.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Callable
from pathlib import Path
... | rakaarwaky/qwen-web-arwaky | modules/shared/src/contract_core_aggregate.py | .py | d7bb660afe612232 | 7.54 | 11 |
"""Core capability protocols (contract layer).
Taxonomy layer (contract(protocol)): pure ABCs, signatures use VOs.
Capabilities implement these; agents/surfaces depend on them via DI.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any
from play... | rakaarwaky/qwen-web-arwaky | modules/shared/src/contract_core_protocol.py | .py | 9a78a92e350b99e4 | 7.54 | 11 |
"""Stateful domain entities: circuit breaker, rate limiter, lifecycle emitter.
Taxonomy layer (taxonomy(entity)): identity-bearing stateful entities, no I/O.
"""
from __future__ import annotations
import logging
import time
from collections import deque
from collections.abc import Callable, Sequence
from typing impo... | rakaarwaky/qwen-web-arwaky | modules/shared/src/taxonomy_core_entity.py | .py | 65e880ab8af26fab | 7.54 | 11 |
"""Initial schema: api_keys, usage_logs, notes_metadata, note_embeddings
Revision ID: 001
Revises:
Create Date: 2026-03-17
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import ARRAY, JSONB, TSVECTOR
from pgvector.sqlalchemy import Vector
rev... | maxkuminov/obsidian-mcp | alembic/versions/001_initial.py | .py | d5dacf55783aa45f | 7.54 | 11 |
"""Make usage_logs.key_id nullable for OAuth token usage
Revision ID: 003
Revises: 002
Create Date: 2026-03-17
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "003"
down_revision: Union[str, None] = "002"
branch_labels: Union[str, Sequence[str], None] = None
depe... | maxkuminov/obsidian-mcp | alembic/versions/003_nullable_usage_key_id.py | .py | 545ff27589616e88 | 7.54 | 11 |
"""Add embedded_content_hash to notes_metadata for stale embedding detection
Revision ID: 004
Revises: 003
Create Date: 2026-03-18
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "004"
down_revision: Union[str, None] = "003"
branch_labels: Union[str, Sequence[str... | maxkuminov/obsidian-mcp | alembic/versions/004_embedded_content_hash.py | .py | dfb25884caaeb28e | 7.54 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.