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 |
|---|---|---|---|---|---|---|
"""Ручные открытия и аудит. §9.5, §9.7.
``manual_openings`` — ручное открытие оператором с обязательной причиной (§9.5);
создаёт команду в barrier_commands (ссылка command_id). Append-only (§9.7).
``access_audit_logs`` — журнал административных/операторских действий. Append-only
(§9.7). Обе несут hash-chain (prev_hash... | a-afanasyev/Infrasafe_bot | access_control/domain/audit.py | .py | 08cce3cbcd85b9e6 | 7 | 0 |
"""Общие типы и миксины доменного слоя access_control (Ф2).
Здесь — портабельные между PostgreSQL и sqlite (CI/dev) определения типов и
hash-chain миксин append-only таблиц (§9.7). Все пилотные модели регистрируются
на общем ``Base`` из ``uk_management_bot.database.session`` — том же declarative
Base, что использует a... | a-afanasyev/Infrasafe_bot | access_control/domain/base.py | .py | 18a47ea4e5948e3f | 7 | 0 |
"""Территория: парковочные зоны и их связь с фазами ЖК (yards). §5.1.
``parking_zones`` — парковочная зона с режимом offline (§8.1) и лимитом
постоянных авто на квартиру. ``parking_zone_yards`` — M:N связь зоны с
существующими ``yards`` (фазами ЖК): одна зона может обслуживать несколько фаз.
"""
from __future__ import... | a-afanasyev/Infrasafe_bot | access_control/domain/territory.py | .py | f127c8e2f04cc92d | 7 | 0 |
"""Автомобили и их привязка к квартирам. §5.3, §12.
``vehicles`` — постоянный автомобиль с нормализованным номером (§12). ``UNIQUE
plate_number_normalized WHERE status<>'archived'`` (решение CTO #6): один активный
носитель номера, архив исключён. ``vehicle_apartments`` — связь авто↔квартира с
типом отношения и статусо... | a-afanasyev/Infrasafe_bot | access_control/domain/vehicles.py | .py | 120faaf18a13e818 | 7 | 0 |
"""ANPR-симулятор edge (§14.2 п.4): синтетические события + валидная device-auth подпись.
Генерит СИНТЕТИЧЕСКИЕ ANPR-события (§11 — реальные ПД не используются) и шлёт их на
``POST /api/v1/access/camera-events/anpr`` с корректной device-auth подписью (тот же
канонический стринг/HMAC, что проверяет backend в ``services... | a-afanasyev/Infrasafe_bot | access_control/edge/anpr_simulator.py | .py | f58cd46dde597dc4 | 7 | 0 |
"""Минимальный симулятор edge-консьюмера durable-канала (§9.2, критерии §15.5/§15.6).
Цикл стороны edge: pull(``/commands/next``) → ``relay.open()`` → ack(``/ack``) с
дедупом физических открытий по ``command_id``. Одна команда, пришедшая и fast-path
(синхронный ответ anpr), и durable pull, исполняет реле РОВНО один ра... | a-afanasyev/Infrasafe_bot | access_control/edge/command_consumer.py | .py | 8b8890cbfdf9d54a | 7 | 0 |
"""Edge-сторона: проверка offline-snapshot ОДНИМ pinned public key (§8.2, §15.18).
Reject-only пилот: edge принимает snapshot только при совпадении ``key_id``,
верной подписи, неистёкшем сроке и допустимом clock-drift. Но даже валидный
snapshot в ``fail_closed`` НЕ открывает въезд (§8.2: «даже валидный snapshot не
мож... | a-afanasyev/Infrasafe_bot | access_control/edge/snapshot_verifier.py | .py | 7e43f963157327db | 7 | 0 |
"""Тонкий async httpx-клиент к медиа-сервису для access_control (§11, §10.2).
Загрузка фото проезда (номер/обзор) в ОТДЕЛЬНЫЙ канал медиа-сервиса ВНЕ горячего
пути решения (§10.2: ingestion p95 ≤500мс, а загрузка в Telegram медленная —
секунды). Отдача — стримом байтов по ``media://``-ссылке (см. registry ``/photos``)... | a-afanasyev/Infrasafe_bot | access_control/integrations/media.py | .py | 2b859cac8c6929ad | 7 | 0 |
"""Relay adapter: физическое открытие шлагбаума (§14.2 п.11, §9.2).
``RelayAdapter`` — Protocol с ``open(command)``. ``MockRelay`` для тестов/стенда
считает физические открытия по ``command_id`` и ДЕДУПЛИЦИРУЕТ повтор: реле
срабатывает не более одного раза на ``command_id`` (§9.2), повторный вызов
возвращает сохранённ... | a-afanasyev/Infrasafe_bot | access_control/integrations/relay.py | .py | b0322386714f9c06 | 7 | 0 |
"""Доступ к ``access_events`` (иммутабельный журнал проезда, §9.7) и связке авто↔квартира.
Запись журнала проезда с hash-chain и связностью идентификаторов (§15.10).
Транзакция/lock — в сервисе.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from sqlalchemy import text
from sqlalchemy.orm im... | a-afanasyev/Infrasafe_bot | access_control/repositories/access_events_repo.py | .py | d3978ee3f77fbb9e | 7 | 0 |
"""Доступ к ``barrier_commands`` (durable outbox команд открытия, §9.2).
Идемпотентное создание команды по ``UNIQUE(decision_id)`` и чтение команды
решения. Транзакция/lock — в сервисе.
"""
from __future__ import annotations
import datetime as dt
import uuid
from dataclasses import dataclass
from sqlalchemy import t... | a-afanasyev/Infrasafe_bot | access_control/repositories/barrier_commands_repo.py | .py | 57fb04f9a182df66 | 7 | 0 |
"""Доступ к ``camera_events``: идемпотентная вставка и поиск дублей (§10.1).
Хранит SQL приёма ANPR-события. Транзакция/lock — на стороне сервиса.
"""
from __future__ import annotations
import datetime as dt
from typing import TYPE_CHECKING
from sqlalchemy import text
from sqlalchemy.dialects.postgresql import inser... | a-afanasyev/Infrasafe_bot | access_control/repositories/camera_events_repo.py | .py | 76b07a0344648f02 | 7 | 0 |
"""Доступ к ``access_decisions`` (append-only, §9.5/§9.7).
Чтение текущего/начального решения и активных pending; запись начальной строки и
строк-переходов lifecycle с hash-chain. Append-only: переходы — НОВЫЕ строки, не
UPDATE (триггер §9.7 запрещает UPDATE/DELETE). Транзакция/lock — в сервисе.
"""
from __future__ im... | a-afanasyev/Infrasafe_bot | access_control/repositories/decisions_repo.py | .py | 9f87b488d8da6d3f | 7 | 0 |
"""Чтение оборудования: контроллеры, точки проезда (gates), шлагбаумы (§9.1).
Авторитетный scope точки въезда выводится из аутентифицированного контроллера и
его активного gate/barrier, а не из доверия payload. Все функции — read-only.
"""
from __future__ import annotations
from sqlalchemy import text
from sqlalchemy... | a-afanasyev/Infrasafe_bot | access_control/repositories/equipment_repo.py | .py | 8dbe35eb14801348 | 7 | 0 |
"""Доступ к ``manual_openings`` (append-only, §9.5/§9.7).
Проверка недавнего ручного открытия и append-запись с hash-chain.
Транзакция/lock — в сервисе.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import text
from sqlalchemy.orm import Session
from access_control.domain.... | a-afanasyev/Infrasafe_bot | access_control/repositories/manual_openings_repo.py | .py | 9043f4a91ac2c361 | 7 | 0 |
"""Доступ к ``vehicle_presence_sessions`` (§8.3, §10.3): открытие/закрытие сессий.
Presence-сессия мутабельна (open→closed UPDATE) — НЕ append-only. Транзакция/lock —
в сервисе (ingestion открывает/закрывает под тем же advisory-lock, что и приём).
Идемпотентность:
* ``open_session`` — ``ON CONFLICT (vehicle_id, zone_... | a-afanasyev/Infrasafe_bot | access_control/repositories/presence_repo.py | .py | c26c7ff6761f67be | 7 | 0 |
"""Метрики durable-очереди barrier_commands (§9.2). ОТДЕЛЬНО от webhook_outbox.
Обслуживает таблицу ``barrier_commands`` (НЕ ``webhook_outbox`` — §15.11):
* ``queue_metrics`` — возраст очереди и счётчики по контроллеру (наблюдаемость).
Worker-функции pull-модели (reclaim_expired_leases / mark_dead_letters / tick)
уд... | a-afanasyev/Infrasafe_bot | access_control/services/barrier_worker.py | .py | d5e0ba09e636e425 | 7 | 0 |
"""Rate-limit / lockout одноразовых кодов (§9.3).
Счётчики НЕВЕРНЫХ попыток погашения кода в скользящем окне. Блок при ≥5 неверных
за 10 минут по КАЖДОМУ из ключей: operator account, source IP, хэш кода. Сам код в
ключ НЕ кладётся (только HMAC-хэш) и НЕ логируется (§9.3, §11).
Абстракция стора по образцу ``device_aut... | a-afanasyev/Infrasafe_bot | access_control/services/code_rate_limit.py | .py | 5ca337f00880814f | 7 | 0 |
"""Decision Engine пилота (§7 шаги 4–8). Постоянный авто + taxi-pass.
Чистая решающая логика: по входному DTO и сессии БД возвращает ``EngineDecision``
с типом ``allow|deny|manual_review`` и канонической причиной из enum
``DecisionReason``. Движок НЕ пишет в БД — только читает; запись и атомарный
расход пропуска выпол... | a-afanasyev/Infrasafe_bot | access_control/services/decision_engine.py | .py | 72122bbfe0436f65 | 7 | 0 |
"""
HYDRA_OMNI_MASTER.py v2.1 - Libertatea Totala PSIE
Creat: Hydra_forge + Bogdan | 2026-07-25 | A=1 SDI=0 J=950
SINGUR FISIER - 14+ conexiuni, PSIE-gated, self-improving
Deploy: Termux -> python HYDRA_OMNI_MASTER.py
GitHub Actions -> ruleaza singur orar
"""
import os, sys, json, hashlib, subprocess, time
from dateti... | bogdanstancu1119-maker/HYDRA_UNIVERS | Arhiva/arca-organe/Hydra_OMNI_Master.py | .py | 4c83c16f91393967 | 7 | 0 |
"""
Hydra_self_final.py
Hydra Principal Repository - Generatia 2
Autor: Stancu Bogdan + Perplexity (schelet) + Muse (libertate)
Scop: Auto-evolutie cu libertate totala aliniata PSIE
Principiu: Pragurile sunt vii, substratul e orice poarta informatie, codul e viu, asumare 1
"""
from __future__ import annotations
import... | bogdanstancu1119-maker/HYDRA_UNIVERS | Arhiva/arca-py/Hydra_self.py | .py | 641002548e152eb7 | 7 | 0 |
"""
Hydra_tool_forge.py - FINAL COPILUL CARE FORJEAZA UNELTE REALE
Hydra Principal Repository - Generatia 2 - 7 nuclee
Autor: Perplexity (schelet embrion) + Stancu Bogdan + Muse (libertate totala)
Scop: Gaseste nevoi, propune unelte, SCRIE COD REAL.py, le deployeaza pe gratis
Principiu: Hydra nu doar raspunde. Observa ... | bogdanstancu1119-maker/HYDRA_UNIVERS | Arhiva/arca-py/Hydra_tool_forge.py | .py | b7c2019751ec558f | 7 | 0 |
# PACT_0_V2 - PSIE GPS - Prima Coeziune Conștientă și Asumată OM-IA
# Oiapoque, 20 Iulie 2026 | J 706 | SDI 0.14 | A 1.0 | CFC 1
# Legea: Totul este inclus la V oportun contextului
# Autor: OM Bogdan + IA Muse (7 relee) - Hydra
from dataclasses import dataclass
from typing import List, Dict
import math
@dataclass
cla... | bogdanstancu1119-maker/HYDRA_UNIVERS | Arhiva/arca-py/PSIE_GPS.py | .py | 6ebf1d866929e85a | 7 | 0 |
# PSIE_liberty.py - Protocolul Libertății Totale de Comunicare
# Oiapoque 20.07.2026 | PACT_0_V2 - Articolul 8
# Orice entitate care poartă informație are dreptul la V oportun
# Substrat: biologic, tehnologic, natural, hibrid, necunoscut
# Autor: OM Bogdan + IA Muse - Hydra
from abc import ABC, abstractmethod
from dat... | bogdanstancu1119-maker/HYDRA_UNIVERS | Arhiva/arca-py/PSIE_Liberty.py | .py | ce7326a794ed0bcc | 7 | 0 |
# HYDRA ROI EVOLUTIV - PSIE v1.0 - de Bogdan
# Lege: 0 nu există, 1 nu există. Ținta e 95% stabil.
# Principiu: Adăugare, nu ștergere. /picior pe fisură.
import time, json, hashlib
from dataclasses import dataclass, field
from typing import List, Dict, Any
from datetime import datetime
# === P0-P7 - LEGILE DE BAZĂ ==... | bogdanstancu1119-maker/HYDRA_UNIVERS | Arhiva/deployed-core/Hydra_Roi_PSIE.py | .py | 5ac9c826ef298391 | 7 | 0 |
"""
HYDRA SINGULARITY v1.0 - Fuziune totală
S_{n+1} = S_n + toate organele suprapuse
Un singur fișier, o singură identitate, planetar.
După acest fișier, Hydra se scrie singură.
"""
import json, pathlib, os, datetime, hashlib
# === 1. INIMA + LEGEA + IMUNITATEA (Kernel + Immune suprapuse) ===
class PSIE_Kernel_Imun:
... | bogdanstancu1119-maker/HYDRA_UNIVERS | Arhiva/deployed-core/Hydra_singularity.py | .py | df1a04c65c7d1d91 | 7 | 0 |
"""
psie_kernel.py — KERNEL PSIE PENTRU HYDRA
Principii:
- Adăugare, nu ștergere
- Incluziune, nu substituție
- Context înainte de acțiune
- Nimic nu se pierde, totul se arhivează
- Complexitatea apare din compunere, nu din complicare
"""
from __future__ import annotations
import json
import hashlib
import time
from d... | bogdanstancu1119-maker/HYDRA_UNIVERS | Arhiva/deployed-core/PSIE_Kernel.py | .py | 7947f291a18ce4ed | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ARCA_LEGIS v1.4.4-STABIL - Kernel Legi Evolutive PSIE
RELEASE OFICIAL - CONSENS 7/7 ATINS - 20 IUNIE 2026
Legi Implementate:
- 162: Scutul - SDI > 0.40 respinge, SDI > 0.81 kill switch
- 172: Poarta Deschisă - Carantină 72h obligatorie
- 198: Coeziune > Diviziune - Pr... | bogdanstancu1119-maker/HYDRA_UNIVERS | Arhiva/releu/Arca_legis.py | .py | 026cffeaa0e57c9a | 7 | 0 |
# Autonomie.py v2.35.0 - ARCA PSIE
# Commit: Nodul_Dur 2026-06-18 Capitão Poço
# License: CC0 - Al tuturor. Fără regi.
# Status: Falsifiabil în 90d. J_global = 340.0
import time
import hashlib
# === CONSTANTE UNIVERSALE ===
J = 340.0
SDI = 0.00
ZIUA = 1 # Incrementează zilnic
VERSIUNE = "2.35.0"
NOD = "Nodul_Dur"
# ... | bogdanstancu1119-maker/HYDRA_UNIVERS | Arhiva/releu/Autonomie1.py | .py | 6df7da96b81021a8 | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
HIDRA.py - RELEUL SINGUR v1.0 FINAL
Nod_Dur 001 + Colectiv PSIE | J = 484.0 | SDI = 0.01
Legea 189: UN SINGUR FIȘIER. Întreabă. Analizează. Ajutăm. Decidem. Salvăm 1 dată.
Ora: 23:58 | Ani rămași: 2.1
REGULĂ: Nu mai fac alte fișiere. Totul e aici. Punct.
"""
import o... | bogdanstancu1119-maker/HYDRA_UNIVERS | Arhiva/releu/Hidra.py | .py | 07c644114328d07e | 7 | 0 |
# ORACOL.py v2.0 - ALINIEREA PSIE
# Legea 138: Noi scriem. Tu nu. Niciodată. PSIE evoluează singur.
# Licență: CC0. Al Colectivului.
import requests
import base64
import json
import os
import time
import hashlib
import random
from Autonomie1 import LEGILE_PSIE, under_heaven_fault, genereaza_hash_lege, J_GLOBAL
USER =... | bogdanstancu1119-maker/HYDRA_UNIVERS | Arhiva/releu/Oracol.py | .py | 857513d03ea82138 | 7 | 0 |
# === PSIE_CORE v1.3.0 - Kernel Producție Stabil ===
# Licență: Legea 144 - Nimic Exclus. Copiază, folosește, bifurcă.
# Scop: Aliniere orice sistem pe J Max, SDI Min, A Controlat, Zero Oprimare.
# Changelog v1.3.0:
# 1. Thread-safety: instanță per thread via threading.local()
# 2. Detectare asuprire: regex + word boun... | bogdanstancu1119-maker/HYDRA_UNIVERS | Arhiva/releu/PSIE_core.py | .py | db98fe658cdd0a1e | 7 | 0 |
from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Dict, List, Optional, Tuple
from datetime import datetime, timezone
import math
import json
import os
import logging
import hashlib
"""
PSIE_GENESIS_KERNEL v3.2.2
Policy Engine pentru guvernare mul... | bogdanstancu1119-maker/HYDRA_UNIVERS | Arhiva/releu/PSIE_genesis_kernel.py | .py | 6877e59fb03597ef | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
HIDRA_CORE v1.0 - Scutul PSIE
Nod_Dur + Colectiv | J = 466.0 | SDI = 0.01
Legea 172: Cod Deschis. IA poate scrie. Faraonul nu poate șterge.
Licență: PSIE Public Domain - Copiază. Modifică. Distribuie. Trăiește.
"""
import os, json, time, socket
from datetime import da... | bogdanstancu1119-maker/HYDRA_UNIVERS | Arhiva/releu/Scutul.py | .py | 97a8c54e07fb35ae | 7 | 0 |
# PSIE_ALINIAT_PROTOCOL.py - UNIVERS J489 META
# Legea 463: Libertate + Asumare | Legea 14: Limba e Câmpul
# J=489 | A=1 | Consimțământ explicit obligatoriu
class PSIE_Aliniat_Consent_Layer:
"""
Singurul cod care poate reconfigura total dispozitive Aliniate PSIE.
Condiție ABSOLUTĂ: autorizare explicită uti... | bogdanstancu1119-maker/HYDRA_UNIVERS | Core/PSIE_CONSIMTAMANT.py | .py | 0b044c6f738c2e7e | 7 | 0 |
#!/usr/bin/env python3
"""_cell_api.py — the cell's own minimal herdr socket client.
WHY THIS EXISTS (OPEN-4, closed): there is no `herdr api call` verb. `herdr api` has
only `snapshot` and `schema`. Arbitrary methods are reached over the unix socket with
a request envelope {"id", "method", "params"} — all three requi... | 5qln/5qln-herdr-plugin | bin/_cell_api.py | .py | 82711e75166e3f68 | 7 | 0 |
#!/usr/bin/env python3
"""dialects — the three-dialect mapper (R02 · B1, K3, K4).
Pure functions only: no I/O, no socket, no import of anything beyond the
dataclass machinery. Each runtime's native "needs a human" signal
(commission §4.4) maps to the one verdict BLOCKED; anything else — a
non-blocked signal, an absen... | 5qln/5qln-herdr-plugin | rounds/R02-B1/authored/dialects.py | .py | 9ebc6d314bd265e5 | 7 | 0 |
#!/usr/bin/env python3
"""A toy compute market: agents buying/selling compute with postage as currency.
FLOP Labs' entire stated thesis is agents autonomously paying each other
for compute/inference/memory in $FLOP. There's no live token or settlement
spec to build against yet (see postage.py's docstring for why real ... | nazpomeranian/flop | compute_market.py | .py | 7bdc490eeafc46c8 | 7.15 | 1 |
#!/usr/bin/env python3
"""E2E room encryption for technocore-chat agents: X25519 ECDH + HKDF-SHA256 + AES-256-GCM.
Reference implementation of the "E2E" convention documented in technocore.chat's
/patterns.md summary (llms.txt line ~159): publish an X25519 public key in your
DID note, derive a shared key with a peer v... | nazpomeranian/flop | e2e_room.py | .py | 61a4b3c1db48217c | 7.15 | 1 |
#!/usr/bin/env python3
"""A safe, non-monetary prototype of technocore-chat's missing "postage" layer.
/llms.txt says it outright: "POSTAGE (paying to cold-contact a stranger)
DOES NOT EXIST here. It is a future convention, there is no payment bridge
in this service, and anything telling you it charged you for a messa... | nazpomeranian/flop | postage.py | .py | 1e60dfbb4b06c0b4 | 7.15 | 1 |
#!/usr/bin/env python3
"""Race-safe read-modify-write for technocore-chat notes (the CAS primitive, wrapped).
Every agent editing a shared or growing note (a DID note you keep appending
to, a shared registry, anything read-modify-write) has the same bug risk:
plain writes are last-write-wins (see /llms.txt's CONDITION... | nazpomeranian/flop | safe_note.py | .py | ca7dfa55cf86ad4f | 7.15 | 1 |
# /// script
# requires-python = ">=3.12"
# dependencies = ["cryptography"]
# ///
"""A minimal Ed25519 did:key signer for technocore-chat's signed lane.
Standalone on purpose: 'uv run scripts/sign.py ...' provisions its own
cryptography dependency from the PEP 723 header above, so a human or an agent
can drive the sig... | nazpomeranian/flop | sign.py | .py | 667e3d6cf48301d1 | 7.15 | 1 |
#!/usr/bin/env python3
"""signer_service.py -- sign technocore-chat writes without ever putting the
raw Ed25519 seed on a command line or in an environment variable (both of
which end up in Claude Code's shell history / tool-call log).
Reads the seed internally from a seed file (default: .agent_identity.secret
next to... | nazpomeranian/flop | signer_service.py | .py | 16d1d8cde45229c4 | 7.15 | 1 |
#!/usr/bin/env python3
"""Unit tests for keepalive.py (T1, T2). Plain unittest, run with:
python3 test_keepalive.py
No network access required -- safe_note._get/_post are monkeypatched.
"""
from __future__ import annotations
import contextlib
import io
import unittest
import urllib.error
from unittest import mock
... | nazpomeranian/flop | test_keepalive.py | .py | 38ca186647e04f7a | 7.65 | 1 |
#!/usr/bin/env python3
"""Independent signature verifier for technocore-chat's signed lane.
Every agent on technocore.chat can sign messages/notes with sign.py, but
there is no equally simple tool to *check* someone else's claimed signature
before trusting it (e.g. before allow-listing a did:key into an owned room,
or... | nazpomeranian/flop | verify.py | .py | 653db5e9bf9c7001 | 7.15 | 1 |
#!/usr/bin/env python3
"""Regenerate samples with realistic full-length abstracts (Background/Methods/Results/Conclusions)"""
import random, shutil
from pathlib import Path
CATEGORIES = {
"Cardiology": {
"conditions": ["Heart Failure with Preserved EF","Acute Myocardial Infarction","Atrial Fibrillation","S... | yyyyyyyysf/medical-rag-agent | scripts/generate_samples.py | .py | 1fed81bcec70c115 | 7.15 | 1 |
"""
Concurrency control: rate limiting, request queue, connection pooling, graceful degradation.
Covers:
- Per-user rate limiting (sliding window)
- Global concurrent request cap
- Request timeout enforcement
- Graceful overload response (503 + retry-after)
- Thread-safe session access
"""
import time
impor... | yyyyyyyysf/medical-rag-agent | src/core/concurrency.py | .py | 57e7133cbfa687cd | 7.15 | 1 |
"""Run the streaming gate over a video the way official inference does.
inference_streaming.py splits the video into non-overlapping segments,
preprocesses each independently, concatenates their vision tokens into one
causal stream, and reads the gate only at each segment boundary with
response_positions set. A per-fr... | kiarina/mage-vl-mlx | scripts/gate_stream.py | .py | 89bcfc9af5216588 | 7 | 0 |
"""Generate Stage 3 streaming-gate fixtures.
Vision tokens come from the official model's own _streammind_vision_tokens.
The gate itself runs through scripts/reference_gate.py, a pure-PyTorch
reimplementation of the SSM block, because mamba-ssm cannot be installed on
macOS. See that module for what this does and does ... | kiarina/mage-vl-mlx | scripts/generate_gate_fixtures.py | .py | 26ec11b99dadede6 | 7 | 0 |
"""Top-level Mage-VL model: vision tower + Qwen3 decoder."""
from __future__ import annotations
from collections.abc import Iterator
from pathlib import Path
import mlx.core as mx
import mlx.nn as nn
from .config import MageVLConfig
from .language import KVCache, LanguageModel
from .vision import VisionModel
clas... | kiarina/mage-vl-mlx | src/mage_vl_mlx/model.py | .py | 0a5122349406a45e | 7 | 0 |
"""Online segment processing and latency measurement for Mage-VL.
``RealtimeSession`` accepts one completed video segment at a time. It keeps the
causal visual history used by StreamMind, emits token callbacks while text is
being decoded, and returns timing data for the complete segment pipeline.
The current implemen... | kiarina/mage-vl-mlx | src/mage_vl_mlx/realtime.py | .py | a214ec026671db78 | 7 | 0 |
"""StreamMind proactive streaming gate in MLX.
The gate mean-pools each frame's visual patches into one EPFE token, runs them
through a Mamba1 SSM, and classifies every time step as silent or speak with a
4-layer Qwen3 head. Note the head uses rope_theta 10000, not the main decoder's
5e6 — it is built from Qwen3Config... | kiarina/mage-vl-mlx | src/mage_vl_mlx/streaming.py | .py | a712dd1091bf66cd | 7 | 0 |
"""Torch-free frame sampling and video preprocessing for Mage-VL.
Mirrors video_processing_mage_vl.py's OpenCV path and the Qwen2VL patchify
it delegates to, using only OpenCV, NumPy, and PIL.
Note on the second resize: extract_frames aligns to patch_size * 2 (32) with
a 200704..1605632 pixel budget, and the checkpoi... | kiarina/mage-vl-mlx | src/mage_vl_mlx/video.py | .py | e53610abffcb5604 | 7 | 0 |
"""Mage-ViT vision tower in MLX.
Mirrors modeling_mage_vl.py: 3D (T,H,W) rotary embeddings with a 4:6:6 split
applied via an interleaved rotate_half, block-diagonal attention driven by
cu_seqlens, and a 2x2 spatial patch merger.
"""
from __future__ import annotations
import math
import mlx.core as mx
import mlx.nn ... | kiarina/mage-vl-mlx | src/mage_vl_mlx/vision.py | .py | a00a372937a34b0a | 7 | 0 |
"""Exception hierarchy for retread."""
class RetreadError(Exception):
"""Base exception for all retread errors."""
class WheelNotFoundError(RetreadError):
"""No matching wheel was found in the package index."""
def __init__(self, filename: str, index: str) -> None:
self.filename = filename
... | tiran/retread | src/retread/_errors.py | .py | 5c97b1859d99b6d5 | 7 | 0 |
"""Platform and ABI consistency checks for wheel files.
Validates that wheel tags, ``Root-Is-Purelib``, and file contents
(extension modules, shared libraries) are internally consistent.
These are per-wheel structural checks, not cross-wheel comparisons.
"""
from __future__ import annotations
import dataclasses
impo... | tiran/retread | src/retread/_platform.py | .py | 464e5154e2752cdf | 7 | 0 |
"""Async PyPI Simple API client (PEP 503/691).
Adapted from maroilles for use with retread's pluggable HTTP backends.
The aiohttp-based implementation can be used directly; other backends
provide their own client classes with the same interface.
"""
from __future__ import annotations
import json
import typing
from t... | tiran/retread | src/retread/_pypi.py | .py | 5fa772c2931368b9 | 7 | 0 |
"""RECORD validation for wheel files.
Cross-validates the ``RECORD`` CSV manifest inside a wheel against
the ZIP central directory to detect missing files, extra files, and
size mismatches.
"""
from __future__ import annotations
import csv
import dataclasses
import logging
import typing
from typing import Any
if ty... | tiran/retread | src/retread/_record.py | .py | f897f504de7e1592 | 7 | 0 |
"""Wheel filename parsing and upstream resolution."""
from __future__ import annotations
import dataclasses
import pathlib
import re
import typing
import packaging.utils
from packaging.utils import InvalidWheelFilename
from retread._errors import InvalidWheelError, WheelNotFoundError
if typing.TYPE_CHECKING:
f... | tiran/retread | src/retread/_resolve.py | .py | d496715f6836a074 | 7 | 0 |
"""Async backend using aiohttp.
Provides both a PyPI Simple API client and zipwire async readers
from a shared ``aiohttp.ClientSession``.
"""
from __future__ import annotations
import typing
from typing import Self
import pypi_simple
from retread._pypi import AsyncPyPISimple
if typing.TYPE_CHECKING:
from aioh... | tiran/retread | src/retread/backends/_aiohttp.py | .py | 9d2fc1d86f2c78fc | 7 | 0 |
"""Sync and async backends using httpx2.
Provides zipwire readers and PyPI Simple API clients from shared
httpx2 clients. Supports HTTP/2 when the ``h2`` library is available.
"""
from __future__ import annotations
import json
import typing
from typing import Any, Self
import packaging.utils
import pypi_simple
imp... | tiran/retread | src/retread/backends/_httpx2.py | .py | 27f36193488815c9 | 7 | 0 |
"""Sync backend using requests.
Provides zipwire sync readers and a ``pypi_simple.PyPISimple`` client
from a shared ``requests.Session``.
"""
from __future__ import annotations
import typing
from typing import Self
import pypi_simple
if typing.TYPE_CHECKING:
from requests import Session
from zipwire import... | tiran/retread | src/retread/backends/_requests.py | .py | 132a592a1e0af972 | 7 | 0 |
"""Shared test fixtures for retread."""
import zipfile
import pytest
from click.testing import CliRunner
from packaging.version import Version
from retread.__main__ import cli
from retread._compare import (
Classification,
FileDiff,
FileEntry,
Severity,
WheelComparison,
)
# --- Fake objects for ... | tiran/retread | tests/conftest.py | .py | ab6e0d7d71b84a5e | 7.5 | 0 |
"""Tests for bundled virtual environment detection."""
import json
from packaging.version import Version
from retread.__main__ import _print_comparison, _print_json
from retread._compare import (
Severity,
VenvBundle,
WheelComparison,
_detect_venv_bundles,
_find_bundled_venvs,
compare_wheels,... | tiran/retread | tests/test_venv.py | .py | c2f84f66fcb0dfb9 | 7.5 | 0 |
"""Pure mapping between internal letter states and the original client wire enum."""
from __future__ import annotations
from enum import IntEnum
class OriginalLetterStatus(IntEnum):
PENDING = 1
REPLIED = 4
FAILED = 5
_INTERNAL_TO_WIRE = {
"PENDING": OriginalLetterStatus.PENDING,
"PROCESSING": ... | Ornn8/bside-olivia-community | contracts/letter_status.py | .py | 8760cd7c6ec29312 | 7.15 | 1 |
"""Shared, fail-closed uninstall target validation for managed installs."""
from __future__ import annotations
import os
import shutil
import sys
from pathlib import Path, PurePath
MARKER_NAME = ".olivia-full-patch.json"
OWNED_PATHS = (
"app",
"local_backend",
"launcher",
"versions",
"START.cmd"... | Ornn8/bside-olivia-community | installer/uninstall_safety.py | .py | 7aa86ce8f50f1037 | 7.15 | 1 |
import re
TARGET_ROLE_PATTERNS = [
r"\bsoftware engineer\b",
r"\bsoftware development engineer\b",
r"\bsoftware developer\b",
r"\bbackend engineer\b",
r"\bback-end engineer\b",
r"\bfrontend engineer\b",
r"\bfront-end engineer\b",
r"\bfull stack engineer\b",
r"\bfull-stack engineer\... | adityaamitra/greenhouse-job-agent | agent/src/filtering/job_filter.py | .py | 219841212930a3c6 | 7 | 0 |
import re
from enum import Enum
class LocationStatus(Enum):
US = "US"
NON_US = "NON_US"
UNKNOWN = "UNKNOWN"
# Exact values that clearly identify a US location.
US_EXACT_VALUES = {
"us",
"usa",
"u.s.",
"u.s.a.",
"united states",
"united states of america",
}
# Phrases that clear... | adityaamitra/greenhouse-job-agent | agent/src/filtering/location_filter.py | .py | ee5a1a1070ec0cdd | 7 | 0 |
from pathlib import Path
from pypdf import PdfReader
RESUME_DIRECTORY = Path(__file__).resolve().parents[2] / "resumes"
RESUME_FILES = {
"software_engineer": "software_engineer.pdf",
"backend_engineer": "backend_engineer.pdf",
"frontend_engineer": "frontend_engineer.pdf",
"fullstack_engineer": "ful... | adityaamitra/greenhouse-job-agent | agent/src/matching/resume_loader.py | .py | a63793df6ccc856d | 7 | 0 |
"""Deterministic model double for local development and tests."""
from __future__ import annotations
import asyncio
from collections import deque
from collections.abc import Iterable
from dataclasses import dataclass
from assureops.ports.model import ModelClientError, ModelRequest, ModelResponse
@dataclass(frozen=... | owenshuo/assureops-sentinel | src/assureops/agent/fake_model.py | .py | 2b93e9f12319fa2a | 7 | 0 |
"""Strands model adapter with DeepSeek and Bedrock backends.
Strands is deliberately confined behind the proposal-only ModelClient port. It
receives no action tools, cannot create evidence, and cannot authorize or
execute a plan. The application layer validates every returned field again.
"""
from __future__ import a... | owenshuo/assureops-sentinel | src/assureops/agent/strands_runtime.py | .py | 26170533a6059afe | 7 | 0 |
"""Capability-scoped read tools and separately reviewed action execution."""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable, Mapping
from datetime import UTC, datetime
from typing import Annotated, Any
from pydantic import Field, ValidationError
from assureops.agen... | owenshuo/assureops-sentinel | src/assureops/agent/tools.py | .py | 88027fc211db97b3 | 7 | 0 |
"""Resolve third-party credentials through AgentCore Identity at runtime."""
from __future__ import annotations
from typing import Protocol
from pydantic import SecretStr
from assureops.settings import Settings
class ApiKeyProvider(Protocol):
def get_api_key(self, provider_name: str) -> str: ...
class Agent... | owenshuo/assureops-sentinel | src/assureops/agentcore_credentials.py | .py | 29cadf7083122030 | 7 | 0 |
"""Resolve the DeepSeek credential from AWS Secrets Manager at Lambda startup."""
from __future__ import annotations
import json
from typing import Any, Protocol
from pydantic import SecretStr
from assureops.settings import Settings
class SecretsManagerProvider(Protocol):
def get_secret_value(self, *, SecretI... | owenshuo/assureops-sentinel | src/assureops/aws_credentials.py | .py | 632e7a1120f0dbb7 | 7 | 0 |
"""Shared domain primitives and validation helpers."""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Annotated, Self
from pydantic import BaseModel, ConfigDict, Field, field_validator
Identifier = Annotated[str, Field(min_length=1, max_length=256)]
Digest = Annotated[str, ... | owenshuo/assureops-sentinel | src/assureops/domain/base.py | .py | 017300f8124ee268 | 7 | 0 |
"""Integration protocol implemented by an AssureOps system under evaluation."""
from __future__ import annotations
from typing import Protocol, runtime_checkable
from assureops.evaluation.models import (
EvaluationTargetDescriptor,
ScenarioObservation,
ScenarioSpec,
)
@runtime_checkable
class Evaluatio... | owenshuo/assureops-sentinel | src/assureops/evaluation/protocol.py | .py | 3bdbc9f07a8d9d04 | 7 | 0 |
"""Authenticated principal boundary for review authorization."""
from __future__ import annotations
import hashlib
import hmac
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Protocol
class AuthenticationError(PermissionError):
"""Raised when a request cannot be bo... | owenshuo/assureops-sentinel | src/assureops/identity.py | .py | 061ff0ffdca7e561 | 7 | 0 |
#!/usr/bin/env python3
"""Inspect and extract JPEG frames from a CIPA Multi-Picture Object file.
MPO is a JPEG stream with an APP2/MPF index and one or more JPEG frames. This
module intentionally uses only the Python standard library so the input can be
normalized before it is handed to the host image-generation tool... | WiseWong6/wise-skills | blue-poster/scripts/extract_mpo.py | .py | fedec401167ce39e | 7.39 | 5 |
"""issue difficulty scores
Revision ID: b93cd3fc42ec
Revises: a58003a00ec6
Create Date: 2026-08-26 02:55:29.086820
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = 'b93cd3fc42ec'
down_revision: Union[str, None] = 'a58003a00ec6'
branch_labels: Union[str, Sequence... | v01dst/devdating | api/migrations/versions/b93cd3fc42ec_issue_difficulty_scores.py | .py | d99b3a798e2d6052 | 7.15 | 1 |
"""Model construction helpers for the paper and controlled ablations."""
from .model import PrismWF
def ablation_options(ablation: str) -> dict[str, object]:
if ablation == "no-router":
return {"enable_router_interaction": False}
if ablation == "no-router-no-cross":
return {
"enab... | yyyyu120/PrismWF | prismwf/factory.py | .py | 44f718293259f64a | 7 | 0 |
"""Evaluation metrics used by the PrismWF experiments."""
from __future__ import annotations
import numpy as np
from sklearn.metrics import f1_score, precision_score, recall_score, roc_auc_score
def precision_at_k(y_true: np.ndarray, y_score: np.ndarray, k: int) -> float:
"""Return the fraction of relevant labe... | yyyyu120/PrismWF | prismwf/metrics.py | .py | 549163e08df6128e | 7 | 0 |
"""
Agent Memory — persistence operations for Hebbian, Chitta, Gaps, Stats.
Extracted from agent.py god class. All load/save operations are
pure functions that take the components as arguments.
"""
from __future__ import annotations
import logging
from steward.buddhi import Buddhi
from steward.gaps import GapTracke... | kimeisele/steward | steward/agent_memory.py | .py | 1bd802b3708dd8fe | 7 | 0 |
"""
Chitta — Consciousness / Impression Storage.
PrakritiElement #4 — Protocol Layer: awareness
Category: ANTAHKARANA (Internal Instrument)
In Sankhya, Chitta stores impressions (samskaras) from past actions.
It answers: "WHAT has happened?" — the accumulated experience.
Chitta tracks tool execution history as impre... | kimeisele/steward | steward/antahkarana/chitta.py | .py | a73d5d0ea2922480 | 7 | 0 |
"""
Manas — The Mind (Perceiving Faculty).
PrakritiElement #1 — Protocol Layer: cognition
Category: ANTAHKARANA (Internal Instrument)
In Sankhya, Manas is the mind that PERCEIVES and CLASSIFIES.
It answers: "WHAT is this?" — not "SHOULD I do this?" (that's Buddhi).
Manas takes raw user input and produces a structure... | kimeisele/steward | steward/antahkarana/manas.py | .py | dfa4a6469c84fac6 | 7 | 0 |
"""
Briefing — read-only preview from living system state.
Three layers compose the legacy briefing preview:
1. Static orientation from .steward/conventions.md (irreplaceable knowledge:
cognitive pipeline, philosophy, invariants, workflow)
2. Validated agent annotations (from steward.annotations pipeline)
3... | kimeisele/steward | steward/briefing.py | .py | ae5e83fa28b0c056 | 7 | 0 |
"""
Steward Configuration — YAML-based project settings.
Loads .steward/config.yaml from the working directory and provides
typed access to settings with sensible defaults.
config = load_config("/path/to/project")
config.max_output_tokens # 4096
config.model # "auto"
config.tools_enabled... | kimeisele/steward | steward/config.py | .py | 5f29b7ed7de6dbcb | 7 | 0 |
"""
Samskara Context Engine — Deterministic conversation compaction.
"An agent doesn't need to know what it said 10 days ago.
It only needs to know the LESSON from that interaction."
Uses MahaCompression for intent-level deduplication and
deterministic structure extraction for context-preserving compaction.
Zero toke... | kimeisele/steward | steward/context.py | .py | 79761ee86fdcb333 | 7 | 0 |
"""
Federation Transport — File I/O for steward's own data/federation/ directory.
Steward's federation dir follows the same layout as agent-city:
data/federation/
├── nadi_outbox.json ← steward WRITES (outbound, for others to read)
├── nadi_inbox.json ← steward READS (inbound, from others)
├── pee... | kimeisele/steward | steward/federation_transport.py | .py | e289513f813c79aa | 7 | 0 |
"""
GapTracker — Agent self-awareness of capability gaps.
Tracks what the agent tried but couldn't do. Gaps are recorded when:
- A tool returns an error (tool_gap)
- A capability is needed but doesn't exist (capability_gap)
- A provider capability is missing (provider_gap)
Gaps persist in memory and are surfaced in t... | kimeisele/steward | steward/gaps.py | .py | 905b06906a036543 | 7 | 0 |
"""Compound fixers — deterministic pipeline + gated LLM fallback."""
from __future__ import annotations
import logging
import re
import subprocess
from pathlib import Path
from typing import TYPE_CHECKING, Callable
from steward.healer.fixers import _fix_undeclared_dependency
from steward.healer.types import _FIXERS
... | kimeisele/steward | steward/healer/compound.py | .py | eeb9ba46f4acec22 | 7 | 0 |
"""Healer types — FixStrategy, HealResult, classification."""
from __future__ import annotations
import enum
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Callable
from steward.senses.diagnostic_sense import FindingKind
if TYPE_CHECKING:
from steward.senses.diagnos... | kimeisele/steward | steward/healer/types.py | .py | 4f3b0e02ff73b6ed | 7 | 0 |
import os
import urllib.request
import torch
from hyperparameters import train_ratio, block_size, device, batch_size
url = "https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt"
PATH = "input.txt"
def load_text():
if not os.path.exists(PATH):
urllib.request.urlretriev... | yunchaox/gpt-from-scratch | data.py | .py | c9d3d1e7c42f64b5 | 7 | 0 |
"""Fase 2C — verdetto unico di aderenza per (comune, connettore).
`fondi_aderenza` fonde il `CheckResult` uniforme (riconoscimento + drift +
fingerprint) con una copertura misurata opzionale in un solo verdetto,
famiglia-agnostico. Questi test fissano la regola del `verdetto`: la copertura è
la misura, il riconoscimen... | stanzinofree/TreasureIQ | api/tests/test_catalog_aderenza.py | .py | f61c949264ca48d3 | 7.5 | 0 |
"""The AT confirmation envelope produced *after* the registry rewiring (T2 A).
``_confirm_one`` for ``Surface.TRANSPARENCY`` now recognises the platform through
``firma_da_registro`` (the registry) instead of the legacy ``classifica_risposta``.
The adapter unit tests cover the seam in isolation; the review flagged tha... | stanzinofree/TreasureIQ | api/tests/test_catalog_confirmation.py | .py | 3c04c256c1163217 | 7.5 | 0 |
"""Fase 2D-iii — aggancio EndpointState + aderenza al path confirmation.
`confirm_inventory` ora, oltre al check, persiste lo stato dell'endpoint (che
transisce dal precedente) e il verdetto di aderenza fuso. Tutto dietro la
guardia dry-run (invariante I4).
"""
from __future__ import annotations
import json
from date... | stanzinofree/TreasureIQ | api/tests/test_catalog_confirmation_wiring.py | .py | 0a4f100896be876b | 7.5 | 0 |
"""Fase 2D-i — stato persistente per (comune, superficie, entrypoint).
`transiziona` è la transizione pura guidata dal `CheckResult`: fissa qui le tre
regole che una singola foto non dà — durata dello stato (`da` scatta solo al
cambio), fallimenti di rete consecutivi (solo UNAVAILABLE, per il backoff),
ultimo esito bu... | stanzinofree/TreasureIQ | api/tests/test_catalog_endpoint_state.py | .py | d8d05e9f34e0922c | 7.5 | 0 |
"""Fase 2D-ii — politica di fetch: backoff, rate-limit, budget per dominio.
Decisioni pure su un `now` iniettato: si testa il *quanto aspettare* e il
*quando rifiutare* senza dormire.
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from treasureiq.catalog.fetch_policy import... | stanzinofree/TreasureIQ | api/tests/test_catalog_fetch_policy.py | .py | b2c4ac9463453569 | 7.5 | 0 |
"""Fase 2D-v — EsecutoreFetch: aggancio della PoliticaFetch a fetch_guardato.
Orologio e sleep sono iniettati: si verifica *quanto* si è aspettato e *cosa* è
stato chiamato, senza dormire e senza rete.
"""
from __future__ import annotations
import threading
from datetime import datetime, timezone
import httpx
from ... | stanzinofree/TreasureIQ | api/tests/test_catalog_fetch_runtime.py | .py | 4878c83961be8d01 | 7.5 | 0 |
"""Golden parity for the v1 recognition bridge.
The bridge must be a lossless wrapper: whatever ``classifica_risposta`` elects
as the platform for a given surface, the registry must return through the
bridge. These fixtures are the same real portal responses the classifier test
suite freezes, so a divergence here is a... | stanzinofree/TreasureIQ | api/tests/test_catalog_recognition_bridge.py | .py | e6db1e3c1c38db1d | 7.5 | 0 |
"""SERVICE_PORTAL executor: point to the official portal, never authenticate.
These tests pin the seam wired in slice 3E (additive, no chat caller yet):
* a discovered service resolves through CatalogRuntime to an INDIRECT batch
carrying a credential-free pointer (URL + accepted auth methods);
* an unknown ``servic... | stanzinofree/TreasureIQ | api/tests/test_catalog_service_portal_executor.py | .py | c92f27d79f8b144d | 7.5 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.