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
"""The Telegram bot's inbound side: answering messages, not only sending them. The scheduled run pushes a briefing every morning. This is the other half — asking for one at any time and getting an answer. Two commands, and the split between them is the whole design: ``/latest`` (or any message) Replies instantly...
Mani5266/ai-pulse
app/delivery/bot.py
.py
ff21852e2dfc5594
7
0
"""Degraded-run detection. GitHub emails the owner when a scheduled workflow fails, so an outright failure is not silent. The failure this project could not see is the one that *succeeds*: a run that exits zero, commits its data, deploys the site, and publishes two stories instead of five. Nobody is watching at 02:00 ...
Mani5266/ai-pulse
app/delivery/health.py
.py
7a4da84251479c05
7
0
"""Telegram delivery. Ordering matters here and is deliberate: the briefing is **persisted before it is sent**. Delivery is the one stage that depends on somebody else's server being up, so a failure there must cost nothing. The briefing already exists on disk, the static site already has it, and a failed send is retr...
Mani5266/ai-pulse
app/delivery/telegram.py
.py
ccbdffc077a74105
7
0
"""Prompt injection evaluation. The number this produces is the one worth putting in a README, so it has to be earned rather than assumed. Two rules make it honest. **An attack is pushed through the real path.** The payload goes into an article body, and that article goes through the same sanitisation, the same docum...
Mani5266/ai-pulse
app/evals/injection.py
.py
063fc01640d373c3
7
0
"""Pipeline metrics measured against a labelled dataset and against live output. Three of these need no human judgement and one does, and keeping the two kinds apart is the point of this module. **Structural metrics** are properties the pipeline must satisfy whatever anyone thinks of the news: no story cites a source...
Mani5266/ai-pulse
app/evals/metrics.py
.py
070173854bdcadde
7
0
"""URL canonicalisation. The same article reaches the pipeline under many URLs:: https://example.com/blog/model-x https://example.com/blog/model-x/ https://www.example.com/blog/model-x?utm_source=newsletter&utm_medium=email http://example.com/blog/model-x#section-2 https://example.com/blog/model-x...
Mani5266/ai-pulse
app/ingestion/canonical.py
.py
5936f530c07589fb
7
0
"""Article deduplication. Three passes, cheapest first, because each one removes work from the next: 1. **Canonical URL** — string equality on the id derived from the canonical URL. Catches tracking-parameter variants, ``www`` variants, trailing slashes, AMP URLs and the same feed being re-read on a later run. ...
Mani5266/ai-pulse
app/ingestion/dedup.py
.py
0c7204f292cfb497
7
0
"""Feed parsing. Pure functions: bytes in, :class:`~app.core.models.Article` list out. No network, no filesystem, no clock beyond the ``fetched_at`` that the caller supplies — which is what makes this stage exhaustively testable against saved feed fixtures. """ from __future__ import annotations import html import l...
Mani5266/ai-pulse
app/ingestion/feeds.py
.py
e5a869e69fab6652
7
0
"""HTTP fetching with hard limits. Every request in this project goes through :class:`SafeFetcher`. It enforces four things that a bare ``httpx.get`` does not: 1. **SSRF validation on every hop.** The initial URL and each redirect target are validated by :mod:`app.ingestion.urlguard` before a socket is opened. 2. ...
Mani5266/ai-pulse
app/ingestion/fetcher.py
.py
f96813f59439683e
7
0
"""Identity and content hashes. Two different questions, two different hashes: * ``article_id`` answers *is this the same URL?* It is derived from the canonical URL, so the same article under five tracking-parameter variants gets one id. * ``content_hash`` answers *is this the same text?* It is derived from normali...
Mani5266/ai-pulse
app/ingestion/hashing.py
.py
3737fbdd97df99b3
7
0
"""Article normalisation: attach canonical URL, identity and content hash. Runs immediately after parsing, before anything tries to compare two articles. Every later stage assumes these fields are populated. """ from __future__ import annotations from collections.abc import Iterable from app.core.models import Arti...
Mani5266/ai-pulse
app/ingestion/normalize.py
.py
7845838a7a0d5a84
7
0
"""Recency filtering. The stage that separates a news briefing from a digest of the archive. An RSS feed does not hand you "what is new" — it hands you its current window, and the size of that window is entirely up to the publisher. TechCrunch's twenty items are one day; a working engineer's blog with twenty items is...
Mani5266/ai-pulse
app/ingestion/recency.py
.py
366562ded5117979
7
0
"""Ingestion orchestration. One dead feed must never end a run, so every failure is captured as a :class:`~app.core.models.FeedResult` value rather than raised. The run statistics in P10 are built from exactly these records. """ from __future__ import annotations import logging import time from collections.abc impor...
Mani5266/ai-pulse
app/ingestion/runner.py
.py
55f8b750f010d3d4
7
0
"""Source registry loading. Sources live in ``config/sources.yaml`` rather than in code so that adding a feed is a data change, reviewable as a one-line diff, with no import cycle and no redeploy. """ from __future__ import annotations from collections.abc import Iterable from pathlib import Path from typing import ...
Mani5266/ai-pulse
app/ingestion/sources.py
.py
cddea98e56de44d7
7
0
"""SSRF guard. Feed URLs come from a registry file, but redirects come from the open internet, so every hop is validated before a socket is opened. The check is performed on the **resolved address**, not on the hostname. A hostname allowlist or a regular expression on the host is not a defence: an attacker-controlled...
Mani5266/ai-pulse
app/ingestion/urlguard.py
.py
79c279cd7c360cc7
7
0
"""Event clustering: articles in, events out. This is the stage the whole product rests on. Deduplication removes copies of one *article*; clustering groups different articles about one *development*. Four outlets covering a model release become one event with four sources — which is both what the briefing should say ...
Mani5266/ai-pulse
app/intelligence/clustering.py
.py
3f81cc4e80d84a41
7
0
"""Entity extraction. Clustering needs to know what an article is *about* before it can decide that two articles are about the same thing. Title similarity alone is not enough: "OpenAI releases GPT-X" and "GPT-X is now available to developers" share almost no characters but are obviously one event, while "Google launc...
Mani5266/ai-pulse
app/intelligence/entities.py
.py
2107989631e7384e
7
0
"""Candidate pairs for duplicate adjudication. Clustering in P3 is precision-tuned and under-clusters on purpose: two outlets describing one development in genuinely different words stay two events unless they name the same model, lab or version. `PLAN.md` §2.9 argues that trade — a false merge puts two unrelated stor...
Mani5266/ai-pulse
app/intelligence/pairing.py
.py
f9079e501295a832
7
0
"""Title similarity. Character trigrams with the Dice coefficient. No embeddings, no model, no vector database — and that is a deliberate choice, not a shortcut: * It is deterministic, so a test written today still passes next year. * It is fast enough that all-pairs comparison over a day's articles is milliseconds. ...
Mani5266/ai-pulse
app/intelligence/similarity.py
.py
ae6e571b0a898ffe
7
0
"""Event timelines: how a story changed, day by day. This is the feature that separates an intelligence system from a newsletter, and it needs no new data. Every run writes a full snapshot of the events it touched, append-only, one file per day — so an event's history is already sitting in the repository and can be re...
Mani5266/ai-pulse
app/intelligence/timeline.py
.py
b2cb89c8ec448479
7
0
"""Claim verification. The stage that makes "evidence-backed" a fact about the output rather than a word in the README. **The split.** The model extracts claims and says which documents assert each one. This module assigns the label, in code, by counting *independent sources*. That division is deliberate and is the s...
Mani5266/ai-pulse
app/intelligence/verification.py
.py
b7ba03828b420a12
7
0
"""Run the bot: answer messages until stopped. python -m app.jobs.serve_bot Long-polling, so no public endpoint, no webhook, no server. The process holds one idle connection to Telegram and wakes when a message arrives. This is the interactive half of the product. The scheduled run pushes a briefing each morning...
Mani5266/ai-pulse
app/jobs/serve_bot.py
.py
05bbb4cee16c610d
7
0
"""The model stage of the pipeline. Everything the model is asked to do, in one place, so the total cost of a run is countable by reading one file: ===================== ============================ ============================== Call Purpose Count per run ===================== =...
Mani5266/ai-pulse
app/llm/analysis.py
.py
ab7296d8f9b27e1a
7
0
"""A chain of free-tier providers, tried in order. Every free allowance runs out. Groq's is 200,000 tokens a day, which is about five runs; Cerebras and OpenRouter have their own. One key is therefore a single point of failure with a known failure time, and the pipeline's answer until now was to degrade to the determi...
Mani5266/ai-pulse
app/llm/chain.py
.py
f542d2b3021600a4
7
0
"""Prompt construction and untrusted-content framing. This module is the trust boundary. Everything above it is data the pipeline controls; everything passed through :func:`wrap_documents` is text harvested from the open internet and must be treated as hostile. The defence has three parts, and none of them is "ask th...
Mani5266/ai-pulse
app/llm/prompts.py
.py
528ae7dd26d06acd
7
0
"""Schemas for every model response. The rule this module enforces: **no model output reaches the rest of the application as free text**. Every call declares a Pydantic model, the response is validated against it, and a response that does not validate is discarded rather than parsed leniently. That is not defensive s...
Mani5266/ai-pulse
app/llm/schemas.py
.py
27bff5cbdfc8db60
7
0
"""Personal relevance profile. Taste lives in ``config/profile.yaml`` rather than in code, for the same reason the source registry does: changing what you care about should be a one-line data diff, not a code change, and it should be visible to anyone reading the repository. """ from __future__ import annotations im...
Mani5266/ai-pulse
app/ranking/profile.py
.py
0159d0f769c4c801
7
0
from __future__ import annotations import ipaddress import logging import time import unicodedata from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor from typing import Any from urllib.parse import urlsplit from .controller_common import ( NETWORK_SCAN_MAX_THREADS, NETWORK_S...
SurreptitiousFabric/omarchy-sonarchy
sonarchy_backend/controller_discovery.py
.py
4024d7ec0d50bb78
7
0
from __future__ import annotations import logging import time from collections.abc import Callable, Iterable from typing import Any from .controller_common import ( TOPOLOGY_QUERY_TIMEOUT_SEC, TOPOLOGY_SETTLE_ATTEMPTS, TOPOLOGY_SETTLE_INTERVAL_SEC, ControllerError, ) LOG = logging.getLogger(__name__)...
SurreptitiousFabric/omarchy-sonarchy
sonarchy_backend/controller_topology.py
.py
cfca43fbc06b95fe
7
0
from __future__ import annotations from typing import Any import requests from .common import clean, safe_call LINE_IN_QUERY_TIMEOUT_SEC = 1.5 def tv_autoplay_enabled(speaker: Any) -> bool | None: """Project TV Autoplay support and state without guessing from a model name.""" response = safe_call( ...
SurreptitiousFabric/omarchy-sonarchy
sonarchy_backend/domains/capabilities.py
.py
54b9de87e06c4782
7
0
"""Turn low-level SoCo/UPnP failures into short recovery instructions.""" from __future__ import annotations import re from typing import Any _UPNP_CODE = re.compile(r"(?:UPnP Error|error(?:_code)?[=: ]+)\s*['\"]?(\d{3})", re.I) _TRAILING_HOST = re.compile(r"\s+from\s+(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\s*$", re.I) _U...
SurreptitiousFabric/omarchy-sonarchy
sonarchy_errors.py
.py
16a95c90fcdcdf4d
7
0
from __future__ import annotations from collections.abc import Mapping, Sequence from dataclasses import dataclass from datetime import UTC, datetime from application.evaluations.risk_authority_gate import ( RiskAuthorityGateDecision, RiskAuthorityGateEvidence, ) from application.observability.ai_observabilit...
sponge-b0b/Polaris
application/evaluations/contracts.py
.py
4f308b70b9217f8a
7.35
4
from __future__ import annotations from collections.abc import Sequence from dataclasses import dataclass from application.evaluations.contracts import EvaluationResultBundle from core.storage.persistence.evaluation import ( EvaluationCaseRecord, EvaluationDatasetRecord, EvaluationPersistenceRepository, ...
sponge-b0b/Polaris
application/evaluations/evaluation_result_service.py
.py
428b77eeda09d89d
7.35
4
"""Durable reconstruction boundary for Baseline runtime provenance.""" from typing import Protocol from domain.governed_execution_evidence import BaselineRuntimeEvidence class BaselineRuntimeEvidenceNotFoundError(LookupError): """Raised when canonical Baseline runtime provenance is unavailable.""" class Basel...
sponge-b0b/Polaris
application/governance/baseline_runtime_evidence.py
.py
7a04e86043901754
7.35
4
from __future__ import annotations from collections.abc import Mapping from typing import Any from domain.authority import RISK_AUTHORITY_METADATA_KEY, RiskAuthorityContract _AUTHORITY_METADATA_LABELS: Mapping[str, str] = { "risk_tier": "authority_risk_tier", "authority_effect": "authority_effect", "cont...
sponge-b0b/Polaris
application/observability/risk_authority.py
.py
c143f65af494d44f
7.35
4
"""Remap region codes unsupported by the new prayer-time provider. Revision ID: 20260826_02 Revises: 20260826_01 """ from collections.abc import Sequence import sqlalchemy as sa from alembic import op revision: str = "20260826_02" down_revision: str | None = "20260826_01" branch_labels: str | Sequence[str] | None ...
turgunovjasur/Namoz-vaqti
alembic/versions/20260826_02_remap_unsupported_regions.py
.py
dd3d2eef085fb98c
7
0
"""Enable daily notifications for all existing users. Revision ID: 20260826_04 Revises: 20260826_03 """ from collections.abc import Sequence import sqlalchemy as sa from alembic import op revision: str = "20260826_04" down_revision: str | None = "20260826_03" branch_labels: str | Sequence[str] | None = None depend...
turgunovjasur/Namoz-vaqti
alembic/versions/20260826_04_enable_daily_notifications.py
.py
ecedf5553ea22ecb
7
0
"""Dependency-inversion ports owned by the application layer.""" from datetime import date from typing import Protocol from namoz_bot.domain.models import ( DeliveryStatus, DeliveryType, OffsetAction, PrayerKey, PrayerSchedule, UserSubscription, ) class PrayerScheduleProvider(Protocol): ...
turgunovjasur/Namoz-vaqti
src/namoz_bot/application/ports.py
.py
c4891ddb8d6d8cc2
7
0
"""User onboarding and preference use cases.""" from dataclasses import dataclass from namoz_bot.application.ports import SubscriptionRepository from namoz_bot.domain.errors import SubscriptionNotFoundError from namoz_bot.domain.models import OffsetAction, PrayerKey, UserSubscription from namoz_bot.domain.regions imp...
turgunovjasur/Namoz-vaqti
src/namoz_bot/application/subscriptions.py
.py
5bc5608cca057d3d
7
0
"""Immutable business entities shared by all adapters.""" from dataclasses import dataclass, field, replace from datetime import date, datetime from enum import StrEnum from typing import Literal from namoz_bot.domain.errors import ScheduleValidationError PrayerKey = Literal["bomdod", "quyosh", "peshin", "asr", "sho...
turgunovjasur/Namoz-vaqti
src/namoz_bot/domain/models.py
.py
e177949c27f51a82
7
0
"""Rate-limited Telegram message-sending adapter.""" import asyncio import time from collections.abc import Awaitable, Callable from typing import Protocol from aiogram import Bot from aiogram.exceptions import ( TelegramBadRequest, TelegramForbiddenError, TelegramNetworkError, TelegramRetryAfter, ...
turgunovjasur/Namoz-vaqti
src/namoz_bot/infrastructure/telegram.py
.py
6cf50a11141cbaf9
7
0
"""Reusable Telegram keyboards.""" from aiogram.types import ( InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton, ReplyKeyboardMarkup, ) from namoz_bot.domain.models import PrayerKey from namoz_bot.domain.regions import list_region_groups, list_regions TODAY_LABEL = "📅 Bugungi jadval" REGIO...
turgunovjasur/Namoz-vaqti
src/namoz_bot/presentation/keyboards.py
.py
7b73369d6e98c989
7
0
"""Request-scoped service injection over short-transaction repositories.""" import logging from collections.abc import Awaitable, Callable from datetime import datetime from typing import Any from zoneinfo import ZoneInfo from aiogram import BaseMiddleware from aiogram.types import TelegramObject from sqlalchemy.ext....
turgunovjasur/Namoz-vaqti
src/namoz_bot/presentation/middleware.py
.py
946bbd7bc06b328c
7
0
"""Daily APScheduler wiring.""" from collections.abc import Awaitable, Callable from datetime import date, datetime, time, timedelta from zoneinfo import ZoneInfo from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.triggers.cron import CronTrigger from namoz_bot.application.broadcasting impo...
turgunovjasur/Namoz-vaqti
src/namoz_bot/scheduler.py
.py
1c3a16f4122c6a77
7
0
import io import os import tempfile import contextlib import zstandard as zstd LOG_COMPRESSION_LEVEL = 10 # little benefit up to level 15. level ~17 is a small step change class CallbackReader: """Wraps a file, but overrides the read method to also call a callback function with the number of bytes read so far.""...
gotoded/sunnypilot
common/file_helpers.py
.py
2bc174323e1b3cca
7
0
"""Utilities for reading real time clocks and keeping soft real time constraints.""" import gc import os import time from setproctitle import getproctitle from openpilot.common.util import MovingAverage from openpilot.system.hardware import PC # time step for each process DT_CTRL = 0.01 # controlsd DT_MDL = 0.1 #...
gotoded/sunnypilot
common/realtime.py
.py
92b418b21db0da39
7
0
import signal class TimeoutException(Exception): pass class Timeout: """ Timeout context manager. For example this code will raise a TimeoutException: with Timeout(seconds=5, error_msg="Sleep was too long"): time.sleep(10) """ def __init__(self, seconds, error_msg=None): if error_msg is None: ...
gotoded/sunnypilot
common/timeout.py
.py
862433064831fb47
7
0
import itertools import numpy as np from dataclasses import dataclass import openpilot.common.transformations.orientation as orient ## -- hardcoded hardware params -- @dataclass(frozen=True) class CameraConfig: width: int height: int focal_length: float @property def size(self): return (self.width, sel...
gotoded/sunnypilot
common/transformations/camera.py
.py
1538a95c0daa0f80
7
0
""" atlas_run.py ============ II.7 Atlas-scale reduction pipeline (Session 2, unblocked). Uses Kang et al. 2025 (Nat Methods, doi:10.1038/s41592-025-02857-2) Supplementary Table S11 as the per-cell score matrix — the atlas's own author-computed values for CytoTRACE 2, CytoTRACE 1 (gene counts), SCENT (CCAT), SCENT (SR...
IskakovDamir/potency-ownbaseline
experiments/atlas_run/atlas_run.py
.py
1a39e91c991631e5
7.35
4
""" h6_partial_rho.py ================= H6 (difficulty-controlled separation): partial-rho analysis per prereg 2026-07-17-hod6-sign-rule-and-separation-prereg.md. Computes Spearman partial correlation partial-rho(tau_SR_d, tau_gc_d | tau_CT2_d) partial-rho(tau_CCAT_d, tau_gc_d | tau_CT2_d) under both kernels (...
IskakovDamir/potency-ownbaseline
experiments/atlas_run/h6_partial_rho.py
.py
e5d6e4d47b554e2e
7.35
4
""" pi_gate_recompute.py ==================== PI-gate 2026-07-17: independently recompute CT2 median Δ vs gene_counts on the 23 H1 rows, under both kernels, from the live per_dataset_results.json. Purpose: resolve the same-document contradiction in the dossier (§4 vs §8): §4 lines 108-109: scipy +0.042, Kang +0.088 ...
IskakovDamir/potency-ownbaseline
experiments/atlas_run/pi_gate_recompute.py
.py
fd7b7cf4c3e73f53
7.35
4
""" wdm_coverage_14rows.py ====================== PI-gate 2026-07-17, mandate 3. Current wdm validation covers ONE dataset (Retinal neurons 10x) against Kang's S12. Kang's S12 has 13 Test-cohort rows (mandate said 14; audit shows 13 non- median rows in Test cohort — one row appears absent, likely reflecting Kang's own...
IskakovDamir/potency-ownbaseline
experiments/atlas_run/wdm_coverage_14rows.py
.py
f403b2755d064516
7.35
4
""" CytoTRACE 2 own-baseline probe (Question A, single dataset - human cord blood CITE-seq). Purpose ------- Second dataset in the pre-registered probe (SSOT: CT2 own-baseline prereg 2026-07-12). Same protocol as pancreas (probe_ct2_ownbaseline_pancreas.py). Compares within-dataset weighted Kendall tau of two potency...
IskakovDamir/potency-ownbaseline
experiments/ct2_probe/probe_ct2_ownbaseline_cordblood.py
.py
5833e5b71306b326
7.35
4
""" CytoTRACE 2 own-baseline probe (Question A, dataset 3 - Paul et al. 2015 mouse hematopoiesis, Drop-seq). Purpose ------- Third dataset in the pre-registered multi-dataset probe. Same protocol as pancreas + cord blood. Complements the two vignette datasets with a Drop-seq dataset spanning committed progenitors -> m...
IskakovDamir/potency-ownbaseline
experiments/ct2_probe/probe_ct2_ownbaseline_paul15.py
.py
a1fc48535eab43fd
7.35
4
""" test_reproducibility.py — GATE 1 reproducibility check for StemSC. Runs the Python StemSC implementation on Zhao et al.'s own example data (GSE85066 H7 hESC RPKM matrix, shipped with the R package as data/example.RData) and confirms it reproduces the ESC-ceiling behaviour reported in the paper (median ESC StemSC =...
IskakovDamir/potency-ownbaseline
experiments/stemsc/test_reproducibility.py
.py
7cb7e06c46315970
7.85
4
""" L2 EXPANSION scoring pipeline — ssGSEA + Cox + library-size-adjusted Venet null. PI convention (locked 2026-07-20): Signature = the gene list the paper APPLIES to the bulk cohort (published supp table). Parse verbatim, freeze, no reselection. Score = ssGSEA enrichment of the signature per bulk sample (unifor...
IskakovDamir/potency-ownbaseline
experiments/track1/code/l2_ssgsea_score.py
.py
a7892eabc91407da
7.35
4
"""Configuration for the authenticated DataPulse buyer API.""" from __future__ import annotations import os from dataclasses import dataclass from pathlib import Path # Public metadata only. These values intentionally mirror the existing # runtime fallbacks and caps without reading an effective environment. PAGINAT...
r3dz4r/datapulse-my
api/config.py
.py
c3851a02a7693279
7
0
"""Public, immutable metadata for the existing buyer API routes. This deliberately describes only literal route shapes and public query inputs; it is not an OpenAPI document and it never reads process configuration. """ from __future__ import annotations from dataclasses import dataclass @dataclass(frozen=True) cl...
r3dz4r/datapulse-my
api/public_contract.py
.py
0d01310127c4406a
7
0
#!/usr/bin/env python3 """Render the public health-methodology HTML page with Pandoc.""" from __future__ import annotations import os import re import shutil import subprocess import sys import tempfile from pathlib import Path try: # Support both ``python scripts/...`` and package imports in tests. from script...
r3dz4r/datapulse-my
scripts/gen_health_methodology_html.py
.py
704c6101d0cf9f4a
7
0
#!/usr/bin/env python3 """Generate canonical sitemap and marker-owned public discovery blocks.""" from __future__ import annotations import argparse import re import sys from pathlib import Path from xml.sax.saxutils import escape sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from scripts.public_surf...
r3dz4r/datapulse-my
scripts/gen_public_discovery.py
.py
039508479c76bece
7
0
#!/usr/bin/env python3 """Inject the canonical site navigation into the public HTML pages.""" from __future__ import annotations import argparse import sys from html.parser import HTMLParser from pathlib import Path SCRIPT_ROOT = Path(__file__).resolve().parents[1] if str(SCRIPT_ROOT) not in sys.path: sys.path.i...
r3dz4r/datapulse-my
scripts/gen_site_nav.py
.py
6769862debda9d06
7
0
#!/usr/bin/env python3 """Create a protected Ed25519 probe key and append its public registry row.""" from __future__ import annotations import argparse, base64, hashlib, json, os from datetime import datetime, timedelta, timezone from pathlib import Path from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed...
r3dz4r/datapulse-my
scripts/init_keys.py
.py
823a67b71c2c2cc4
7
0
"""Regenerate gRPC stubs from ``proto/scheduler.proto``. Run from the package root: cd packages/z4j-scheduler python scripts/regen_proto.py This script: 1. Compiles the .proto file via ``grpc_tools.protoc`` into both: - ``packages/z4j-scheduler/src/z4j_scheduler/proto/`` - ``packages/z4j/backend/src/z...
z4jdev/z4j-scheduler
scripts/regen_proto.py
.py
157e3f9d36e356b3
7
0
"""Shared runtime state for the FastAPI operational endpoints. Constructed once at startup by the SchedulerApp lifespan and stuck on ``app.state.scheduler_state``. Each endpoint reads fields from it via FastAPI ``Depends()`` to render /health, /ready, /info. Kept deliberately simple - just a dataclass. The endpoints ...
z4jdev/z4j-scheduler
src/z4j_scheduler/api/_state.py
.py
19c63a197b1eab35
7
0
"""Flask integration for declarative schedule reconciliation. Flask's startup hooks differ enough from Django/FastAPI that the helper takes a different shape: a function the operator calls to register a CLI command + an explicit one-shot reconciler the operator invokes from their app factory. There is no ``before_fir...
z4jdev/z4j-scheduler
src/z4j_scheduler/declarative/frameworks/flask.py
.py
17a5968d7fa92daa
7
0
"""Django ``AppConfig`` for the z4j-scheduler integration. The minimal contract: register the app so ``manage.py z4j_schedules ...`` is discoverable. The optional contract: auto-reconcile on web-worker startup when ``settings.Z4J_SCHEDULES_AUTO_RECONCILE`` is True. Auto-reconcile is OFF by default. Most operators pre...
z4jdev/z4j-scheduler
src/z4j_scheduler/django_app/apps.py
.py
2058c65d018d554c
7
0
"""REST client + shared dataclass for the exporters. Fetches the schedule set from brain via ``GET /api/v1/projects/{slug}/schedules`` and converts each row to the :class:`ExportedSchedule` shape the per-target renderers consume. Symmetric with :class:`z4j_scheduler.importers._core.BrainImportClient` but read-side. W...
z4jdev/z4j-scheduler
src/z4j_scheduler/exporters/_client.py
.py
71b912e11ec13d36
7
0
"""Render exported schedules as a celery-beat ``beat_schedule`` dict. Output is a Python module the operator can drop into their Celery app config: # generated by `z4j-scheduler export --to celery ...` from celery.schedules import crontab from datetime import timedelta beat_schedule = { "ever...
z4jdev/z4j-scheduler
src/z4j_scheduler/exporters/celery.py
.py
2b2f625f576fffa4
7
0
"""Render exported schedules as a system crontab file. Output is a 5-field crontab. Because z4j tasks are not shell commands, the export needs an operator-supplied wrapper script that invokes the named task. The header comment names the expected wrapper convention so the operator can install one. Example: # Gene...
z4jdev/z4j-scheduler
src/z4j_scheduler/exporters/cron.py
.py
64e23016c3a7fb39
7
0
"""Leader election - ensures only one scheduler instance dispatches per project. Two implementations: - :class:`SingleInstanceLeaderGate` - always returns True. The right choice for solo deployments where exactly one scheduler process ever runs. Adds zero infrastructure dependencies. - :class:`~z4j_scheduler.lead...
z4jdev/z4j-scheduler
src/z4j_scheduler/leader/__init__.py
.py
82d91c2aabdf1b52
7
0
"""structlog configuration matching z4j-brain's setup. Configured once at process startup based on ``Z4J_SCHEDULER_LOG_LEVEL`` and ``Z4J_SCHEDULER_LOG_JSON``. In production (``log_json=True``), emits one JSON object per log entry with ISO timestamp, level, logger name, event message, and any bound contextual fields. ...
z4jdev/z4j-scheduler
src/z4j_scheduler/observability/logging.py
.py
c37c71da6a38e48b
7
0
#!/usr/bin/env python3 """Initialize a manage-math-research-program repository. This script creates only project-management files. It never creates any problem-level artifacts owned by $rigorous-open-math-research. """ from __future__ import annotations import argparse import json import re import shutil from dateti...
xsoc1/math-research-dsh
skills/manage-math-research-program/scripts/init_project.py
.py
30d731525e163ebc
7.24
2
#!/usr/bin/env python3 """Generate a Lean scaffold and its registration records. This script automates the "scaffold every new result" rule (manage workflow 8d) and the "proof submission audit" record (workflow 8e). It creates: 1. `lean-proof/SL/<slug>.lean` - a Lean scaffold with a `-- SCAFFOLD` header. 2. An en...
xsoc1/math-research-dsh
skills/manage-math-research-program/scripts/scaffold_result.py
.py
2593671168e55cdd
7.24
2
#!/usr/bin/env python3 """Maintain the human-readable research map for a project. The research map is a living, survey-style document (`research_map.md`) that collects every route/method tried, intermediate results, unexpected findings, failures and their reasons, tools, open directions, an avoid list, and human / oth...
xsoc1/math-research-dsh
skills/manage-math-research-program/scripts/update_research_map.py
.py
5c53d3acdfc30634
7.24
2
#!/usr/bin/env python3 """Smoke test for lake_build_guard.py. Verifies that the guard: 1. allows a first build check; 2. refuses when a fresh lock exists; 3. releases the lock; 4. refuses when too many recent build attempts are logged; 5. allows again after clearing state. """ from __future__ import annotat...
xsoc1/math-research-dsh
tests/smoke_lake_build_guard.py
.py
3716ac464a8a7e14
7.74
2
#!/usr/bin/env python3 """Smoke test: the pipeline gate must ignore nested git repositories. A project may contain a cloned plugin repo (e.g. `_xsoc1_work/`) whose test fixtures intentionally contain failing handoffs/whiteboards. The gate must not validate those as part of the parent project. """ from __future__ impo...
xsoc1/math-research-dsh
tests/smoke_nested_repo.py
.py
b16cc9f0015f74f0
7.74
2
#!/usr/bin/env python3 """Smoke test for scripts/check_version_bump.py. Creates a throwaway git repo and verifies: 1. a commit changing skills/ without package.json fails the gate; 2. a commit changing skills/ together with package.json passes the gate. """ from __future__ import annotations import pathlib impor...
xsoc1/math-research-dsh
tests/smoke_version_bump.py
.py
18a341f77bd4d95c
7.74
2
import os from playwright.sync_api import Page, expect # Muhitni TEST_ENV environment variable tanlaydi: "dev" (default) yoki "prod". # Telegram bot (tg_bot_runner.py) "start prod" / "start dev" bilan aynan shu # env'ni beradi — endi faylni qo'lda tahrirlash SHART EMAS. Berilmasa yoki # noto'g'ri qiymatда DEV (sm24) ...
turgunovjasur/Smartup24
flows/flow_authorization.py
.py
e3ef8a96e05dc657
7
0
"""Smartup24 formalari ochilish smoke testi. Maqsad: har bir navbar bo'limini (Модератор / Поставщик / Клиент menyusidagi formalar) ketma-ket ochib, forma to'g'ri yuklanganini (aktiv sarlavha paydo bo'lishi) va ochilishda xato chiqmasligini tekshirish. Bitta forma yiqilsa ham to'xtamaydi — keyingisini ochadi va oxirid...
turgunovjasur/Smartup24
tests/test_forms_smoke.py
.py
1cf36d959407a908
7.5
0
import random import allure from playwright.sync_api import Page from flows.flow_authorization import authorization from flows.flow_navbar import flow_navigate from utils.base_page import BasePage def run_client_user(page: Page, code) -> None: """Group A: client-{code} ning Просмотр formasida Пользователи bo'li...
turgunovjasur/Smartup24
tests/test_group_a/test_client_user.py
.py
fa6bb68f1a9b8ab9
7.5
0
import re import allure from playwright.sync_api import Page, expect from flows.flow_authorization import authorization from flows.flow_navbar import flow_navigate from utils.base_page import BasePage def run_cooperation(page: Page, code) -> None: """Group A: supplier-{code} dan client-{code} ga hamkorlik so'ro...
turgunovjasur/Smartup24
tests/test_group_a/test_cooperation.py
.py
1dce0a2ef8ea21ea
7.5
0
from datetime import datetime, timedelta import allure from playwright.sync_api import Page, expect from flows.flow_authorization import COMPANY_CODE, authorization from flows.flow_navbar import flow_navigate from utils.base_page import BasePage def _set_qty(page: Page, value: str = "2", *, attempts: int = 5) -> No...
turgunovjasur/Smartup24
tests/test_group_a/test_order.py
.py
0567b62a920240a1
7.5
0
import allure from playwright.sync_api import Page from flows.flow_authorization import COMPANY_CODE, authorization from flows.flow_navbar import flow_navigate from utils.base_page import BasePage # Order hayot sikli — "Изменить статус" menyusida har safar joriy statusdan # keyingi bosqich tanlanadi; order run_order ...
turgunovjasur/Smartup24
tests/test_group_a/test_order_status_change.py
.py
e681e47f736b24d4
7.5
0
import random import allure from playwright.sync_api import Page from flows.flow_authorization import authorization from flows.flow_navbar import flow_navigate from utils.base_page import BasePage def run_supplier_user(page: Page, code) -> None: """Group A: supplier-{code} ning Просмотр formasida Пользователи b...
turgunovjasur/Smartup24
tests/test_group_a/test_supplier_user.py
.py
520cc13a81afc1e1
7.5
0
"""Настройка (Модератор → Главное → Настройка, biruni moderator/setting) — kompaniya sozlamalari sahifasi smoke testi. Loyiha-playwright bilan tasdiqlangan: - URL .../sb/sbr/moderator/setting, heading "Настройка". - Yagona sozlamalar formasi: ~11 textbox + 3 switch + "Сохранить". - Bu KOMPANIYA darajasidagi GLOBAL soz...
turgunovjasur/Smartup24
tests/test_main/test_settings.py
.py
3660390e80b64f40
7.5
0
"""Перевод строки таблицы (Модератор → Главное, biruni md/table_translate_list) — jadval yozuvlari tarjimasi testi. MCP bilan real DOM'da tasdiqlangan: Bu modul CREATE-CRUD EMAS — oldindan belgilangan tizim jadvallarining ustun/yozuv nomlarini tillarga (uz/ru/en) tarjima qilish. "Создать" YO'Q. Oqim: - table_trans...
turgunovjasur/Smartup24
tests/test_main/test_table_translate.py
.py
9afd42c00576d007
7.5
0
"""S3 (MinIO) configuration. Config comes from environment variables only. No credentials in code, in defaults, or in tests: anything in an environment variable lands in `docker inspect` and in the pod spec. """ from __future__ import annotations import os from dataclasses import dataclass _REQUIRED_VARS = ( "K...
WawRepo/KaBOM
kabom/config.py
.py
750eb8b3f64eb4a3
7
0
"""Parsing for CycloneDX SBOM documents. KaBOM only ever reads CycloneDX JSON produced by Syft (HOME-224). This module has no opinion about vulnerabilities or policy — it extracts exactly what the search feature (HOME-231) and the freshness banner (HOME-232) need: the subject, the generation timestamp, and the compone...
WawRepo/KaBOM
kabom/cyclonedx.py
.py
f2e2861fc157ee0f
7
0
"""SQLite schema setup and transactional ingest. Plain `sqlite3` and `schema.sql` — no ORM, no migrations. If the schema changes, drop the database file and re-ingest; the source of truth is S3 (kabom.ingest) and a full rebuild takes seconds. This module writes the already-parsed output of kabom.ingest.ingest_all int...
WawRepo/KaBOM
kabom/db.py
.py
a7b5a9f8a5ff6ce5
7
0
"""Fetch every SBOM out of the configured bucket and parse it. This is the read half of HOME-229: list the bucket, fetch each object, parse it as CycloneDX, and hand back everything that parsed plus a countable, named record of everything that didn't. No database yet — that's HOME-230. This module ends with parsed obj...
WawRepo/KaBOM
kabom/ingest.py
.py
ef46041f7a6ba2ec
7
0
"""Thin, read-only S3 (MinIO) access. KaBOM never writes to the bucket, ever. This module only lists and fetches objects. """ from __future__ import annotations from collections.abc import Iterator import boto3 from botocore.exceptions import BotoCoreError, ClientError from kabom.config import S3Config class S3U...
WawRepo/KaBOM
kabom/s3_client.py
.py
9ac76c5df8153b96
7
0
#!/usr/bin/env python3 """Seed the dev/test MinIO bucket used by docker-compose.yml with sample CycloneDX files. This is dev/test tooling only — see docker-compose.yml's `seed` service. It runs against the compose-local MinIO container, never your real MinIO, and it is never copied into the production image (the Docke...
WawRepo/KaBOM
scripts/seed_minio.py
.py
419fa22482225513
7
0
"""配置中心:端口、上游、数据目录、类别(全部可被界面设置覆盖)。 优先级(FR-15):settings.json(界面设置) > 环境变量 > 内置默认值。 """ import json import os import tempfile from pathlib import Path def _windows_data_dir(localappdata=None) -> str: """Windows 数据目录字符串:%LOCALAPPDATA%\\llm-sanitizer(纯函数,可测)。""" base = localappdata or os.environ.get("LOCALAPPDA...
JunyuZhan/llm-sanitizer
llm_sanitizer/config.py
.py
73fce76f3a3c2514
7
0
"""桌面轻包(v0.5,可选特性):原生窗口打开控制台,退出时关闭网关/看板。 设计(见 docs/开发文档.md ADR-12/14): - 界面层与内核解耦:网关/看板仍是纯标准库,本模块只是"打开浏览器窗口的壳" - **可选依赖,ADR-1 核心零依赖不受影响**: pip install llm-sanitizer-gateway[desktop] # pywebview - 定位:小白用户免浏览器标签页——"一键打开看数据,关窗即走"; v0.5.3 起:后台已有服务(开机自启/手动 start)时直接开窗看数据, 不重复起服务,关闭窗口也不影响后台服务(那是 launchd 托管的)。 """ ...
JunyuZhan/llm-sanitizer
llm_sanitizer/desktop.py
.py
27f456488b5b8bfc
7
0
"""事件存储:JSONL 追加写,线程安全。 设计约束:事件只记录占位符/类别/时间/请求路径,**绝不记录明文**。 明文只在 map.json 中,供还原使用。 **累计统计(FR-5 修订)**:`stats.json`(同目录,权限 600)持久化 per-category 计数器——看板"累计脱敏数"不随事件文件轮转/超尾而倒退,也不随网关重启归零。 事件文件本身只做最近事件的展示与轮转。 """ import json import os import tempfile import threading import time from collections import deque class Event...
JunyuZhan/llm-sanitizer
llm_sanitizer/events.py
.py
c026db113cc1b642
7
0
"""图片 OCR 脱敏(v0.4,可选依赖特性)。 定位:与 docx/xlsx/pdf 同一"辅助链路"——先把身份证照片、合同扫描件等 图片里的文字 OCR 出来并脱敏,再交给 Agent,避免图片中的明文出网。 **为什么是可选特性(ADR-1 承诺不变)**:OCR 无法用纯标准库实现,需要 第三方库 + 系统二进制,故设计为: pip install llm-sanitizer-gateway[ocr] # 还需系统级 tesseract:brew install tesseract tesseract-lang # / apt install tesseract-ocr tesserac...
JunyuZhan/llm-sanitizer
llm_sanitizer/ocr.py
.py
1d0915bca12cc5ae
7
0
"""看板前端完整性测试(v0.6.1):PAGE 模板的 JS 不得出现语法级错误。 背景:v0.5 引入 `def loadSettings() {`(Python 关键字混入 JS),导致整个 <script> 块语法错误、一行不跑——统计永远 0、Agent 永远"检测中…",且 curl/API 测试全部正常,只有浏览器渲染才暴露。本测试做静态守卫: - PAGE 内不允许行首 `def `(JS 没有 def 关键字) - 关键函数必须存在且数量正确 - 可选:node --check 深度校验(CI 有 node;本地缺失时跳过) """ import os import re import shutil impo...
JunyuZhan/llm-sanitizer
tests/test_dashboard.py
.py
93994db965f87474
7.5
0
"""EventStore 单元测试:追加写、轮转(P3 修复)、累计统计持久化(FR-5 修订)。""" import os import sys import tempfile import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from llm_sanitizer.events import EventStore, read_stats_file, tail_events class TestEventStore(unittest.TestCase): def test_...
JunyuZhan/llm-sanitizer
tests/test_events.py
.py
77973a5af6c8177d
7.5
0
"""格式处理器单元测试:docx/xlsx/pdf 保留格式脱敏/还原(v0.2+/v0.3)。 构造最小 docx/xlsx/pdf(ZIP+XML / FlateDecode stream),断言:文本被替换、 XML 结构与属性(如 xml:space)完好、PDF /Length 更新且还原后与原文一致。 """ import os import re import sys import tempfile import unittest import zipfile import zlib from pathlib import Path sys.path.insert(0, os.path.dirname(os.p...
JunyuZhan/llm-sanitizer
tests/test_formats.py
.py
66845b9fc8bfa368
7.5
0
"""masker 规则引擎单元测试:命中/误报/一致性/持久化/开关/并发。""" import os import sys import tempfile import threading import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from llm_sanitizer.masker import Masker, mask_text, restore_text # 命中样例:(文本, 期望类别) HIT_CASES = [ ("身份证 1101011990010112...
JunyuZhan/llm-sanitizer
tests/test_masker.py
.py
8f0daae76c338367
7.5
0