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 |
|---|---|---|---|---|---|---|
"""Parameterize note_embeddings.embedding column to settings.embedding_dimensions
Revision ID: 006
Revises: 005
Create Date: 2026-04-26
For existing 1024-dim deployments this is a no-op (ALTER to the same width).
Operators changing dim must run the separate `make reset-embeddings` workflow.
"""
from typing import Seq... | maxkuminov/obsidian-mcp | alembic/versions/006_parameterize_embedding_dim.py | .py | efc17e84297f7061 | 7.54 | 11 |
"""Add HNSW index on note_embeddings.embedding for cosine distance
Revision ID: 008
Revises: 007
Create Date: 2026-05-01
Replaces sequential scan on the `<=>` operator with a logarithmic-time
index. Requires pgvector extension >= 0.5.0 (HNSW added 2023-08-28).
"""
import logging
from typing import Sequence, Union
im... | maxkuminov/obsidian-mcp | alembic/versions/008_hnsw_embedding_index.py | .py | 4fa02e903fbfc3f8 | 7.54 | 11 |
"""Multi-user foundations: users table + nullable user_id FKs
Revision ID: 009
Revises: 008
Create Date: 2026-05-15
Phase 1 of multi-user mode. Adds the users table and a nullable
user_id FK on every per-tenant table. No data migration here; backfill
happens at first bootstrap registration. Single-user mode keeps
use... | maxkuminov/obsidian-mcp | alembic/versions/009_multi_user.py | .py | 7025d211d213936e | 7.54 | 11 |
"""Support OAuth public clients for ChatGPT MCP connections.
Revision ID: 010
Revises: 009
Create Date: 2026-07-13
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "010"
down_revision: Union[str, None] = "009"
branch_labels: Union[str, Sequence[str], None] = None
... | maxkuminov/obsidian-mcp | alembic/versions/010_public_oauth_clients.py | .py | 893783a170dcf610 | 7.54 | 11 |
"""Add a version counter for invalidating signed user sessions.
Revision ID: 011
Revises: 010
Create Date: 2026-07-16
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "011"
down_revision: Union[str, None] = "010"
branch_labels: Union[str, Sequence[str], None] = No... | maxkuminov/obsidian-mcp | alembic/versions/011_user_session_version.py | .py | ef1d7aab923ed7ea | 7.54 | 11 |
"""Give every OAuth token the grant family it was minted from (issue #64).
`oauth_tokens` had `client_id` and `user_id` but nothing tying an access token
to the refresh token minted beside it. So the panel could only offer per-row
controls, and both of them were near no-ops:
- **Revoke** flipped one row. The sibling ... | maxkuminov/obsidian-mcp | alembic/versions/014_oauth_grant_id.py | .py | b70e68147b8826f0 | 7.54 | 11 |
"""Denormalise the actor label onto `usage_logs` (issue #77).
`/admin/usage` resolved the actor of every log line by LEFT JOIN — through
`api_keys` for a key, through `oauth_tokens` -> `oauth_clients` for an OAuth
grant. Both of those joins are allowed to go NULL while the log row stays, and
both of them do so on the ... | maxkuminov/obsidian-mcp | alembic/versions/015_usage_log_actor.py | .py | bca827e67a183ccc | 7.54 | 11 |
"""Record what each user's index was scanned under (issue #91, deferred half).
Nothing anywhere recorded which vault assignment a user's `notes_metadata`
rows were built from. `notes_metadata.file_path` is vault-relative, so after an
administrator repoints a user at another vault the metadata-only tools —
`semantic_se... | maxkuminov/obsidian-mcp | alembic/versions/016_indexed_vault_provenance.py | .py | bdd10425ba1701e6 | 7.54 | 11 |
"""Record which fence grammar derived each note's links, tags and vectors (#150).
The fence-grammar change widens what counts as fenced code, so `note_links`
rows, `notes_metadata.tags` and every embedded vector derived under the old
grammar are stale — and **nothing on the row can see that**. Re-derivation is
gated o... | maxkuminov/obsidian-mcp | alembic/versions/018_extraction_version.py | .py | 96c0fa33c513c2ea | 7.54 | 11 |
"""Panel/OAuth user password hashing — bcrypt, called directly.
This module previously wrapped `passlib.context.CryptContext(schemes=["bcrypt"])`.
passlib has been unmaintained since 2020 and its backend probe hashes a
>72-byte password on import; bcrypt 4.1+ raises instead of truncating, so
`CryptContext` blew up at ... | maxkuminov/obsidian-mcp | src/auth/passwords.py | .py | 384f21337ff5ac82 | 7.54 | 11 |
from contextvars import ContextVar
from dataclasses import dataclass
from pathlib import Path
from fastapi import Depends, HTTPException, Request, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from src.config import settings
from src.database import get_session
from src.models.d... | maxkuminov/obsidian-mcp | src/auth/session.py | .py | 6ee50461ba1f8ec7 | 7.54 | 11 |
"""One-shot panel flash messages, carried in the session and not the URL.
The panel's post-redirect-get messages used to ride the query string
(`/admin/users/?flash=…`, `?error=…`, `&flash_kind=err`) and the templates
rendered whatever was there. Jinja escapes it, so there was no XSS — but the
*text* an authenticated ... | maxkuminov/obsidian-mcp | src/control_panel/flash.py | .py | 4a8ddf3cc0c6b545 | 7.54 | 11 |
"""Grant families: the unit an operator actually consents to and revokes.
A `/authorize` approval produces **one grant**. The token endpoint then mints
an access/refresh pair from it, and every later rotation mints another pair.
Before issue #64 nothing tied those rows together, so the panel could only
offer per-row c... | maxkuminov/obsidian-mcp | src/oauth/grants.py | .py | 6b6ce1d2e5191e4f | 7.54 | 11 |
"""
run.py -- Architectural drift prevention walkthrough.
Simulates a three-step timeline of agent-produced changes against a small
JSON-only service. Each step prints what would happen in a no-governance
world, then exercises the real Mneme enforcement pipeline (via the
mneme CLI) and prints the structured verdict.
... | MnemeHQ/mneme | examples/architectural-drift/run.py | .py | ce7aec000d9d4e76 | 7.64 | 18 |
"""
adr_constraints.py — Parse ``## Constraints`` body directives.
Mneme ADR bodies may include an optional ``## Constraints`` section listing
machine-actionable directives, one per line, in the form::
## Constraints
- FORBID_LITERAL: install legacy-package
- FORBID_DEPENDENCY: mongodb
- FORBID_PATH: ... | MnemeHQ/mneme | mneme/adr_constraints.py | .py | 41ca425ef705e162 | 7.64 | 18 |
"""
benchmark_schemas.py — Structured-output protocol for benchmark v1.1 Step 2.
Adds a JSON layer on top of the existing canned-text benchmark format. A
scenario directory may now provide:
with_mneme.json — preferred over with_mneme.txt when present
without_mneme.json — preferred over without_mneme.txt ... | MnemeHQ/mneme | mneme/benchmark_schemas.py | .py | 1c7fd3354c4a9816 | 7.64 | 18 |
"""
benchmark_verifier.py — Apply assertions to a structured benchmark output.
Verifier semantics (locked for v1.1 Step 2):
* ``forbidden_dependency`` — case-insensitive substring of the assertion
``value`` against each entry in ``dependencies_added``.
* ``forbidden_path_pattern`` — plain (case-sensitive) substring... | MnemeHQ/mneme | mneme/benchmark_verifier.py | .py | 0ea8b7c1a22c6523 | 7.64 | 18 |
"""
conflict_detector.py — Flag violations of injected decisions in LLM output.
This is a *detector*, not a blocker: it returns Conflict records so the
caller can decide how to react (log, warn, surface in UI, reject).
v1 matching is deliberately simple:
- Substring match, case-insensitive.
- A constraint/anti-pa... | MnemeHQ/mneme | mneme/conflict_detector.py | .py | a0200c26a4b02ffa | 7.64 | 18 |
"""
decision_retriever.py — Score Decision records against a query.
Scoring formula (deterministic, no external libraries):
score =
overlap(query, decision) * 1.0
+ overlap(query, scope) * 2.0
+ overlap(query, constraints) * 1.5
+ overlap(query, anti_patterns) * 1.5
... | MnemeHQ/mneme | mneme/decision_retriever.py | .py | 033f5be47fb3db88 | 7.64 | 18 |
"""
enforcer.py — Pre-flight enforcement of Mneme decisions against a prompt.
Checks an input text against the decision corpus and returns a structured
result with PASS / WARN / FAIL verdict and per-violation details.
Retrieval and enforcement answer different questions. Retrieval asks "what
context is relevant?" -- ... | MnemeHQ/mneme | mneme/enforcer.py | .py | 97317697b40c181e | 7.64 | 18 |
"""ADR-021 session state: baseline capture and session-delta attribution.
One snapshot per (repository root, Claude session_id), stored outside the
governed repository in the platform temp directory. The snapshot records
SHA-256, size, and UTF-8 body for every tracked and untracked-but-not-ignored
artifact under the p... | MnemeHQ/mneme | mneme/integrations/claude_code/session_state.py | .py | bf55007e622f4836 | 7.64 | 18 |
"""Hermes plugin wiring for the Mneme integration.
This module contains no governance logic: it only binds
:class:`mneme.integrations.hermes.adapter.MnemeHermes` to Hermes' plugin
hook contract and translates gate outcomes to directives.
Install (POC): copy ``integrations/hermes-plugin/`` from this repository
to ``<p... | MnemeHQ/mneme | mneme/integrations/hermes/plugin.py | .py | afdbb260986ece40 | 7.64 | 18 |
"""Example: Azure SQL / SQL Server with **Managed Identity** (AAD auth).
Demonstrates connecting ``azure-functions-db`` to Azure SQL Database or SQL
Server using an Azure Active Directory (Entra ID) access token instead of a
SQL username/password. The token is acquired with ``azure-identity`` and
injected into the ODB... | yeongseon/azure-functions-db-python | examples/managed-identity-mssql/function_app.py | .py | 4bad2bf82da8b4ad | 7.54 | 11 |
"""Typed cross-package metadata contract for the ``db`` namespace.
This module defines the shape of the ``_azure_functions_metadata`` convention
attribute that decorators attach to Azure Functions handlers. Consumers (such as
the OpenAPI bridge) read this attribute to discover database bindings and
injections without ... | yeongseon/azure-functions-db-python | src/azure_functions_db/_metadata.py | .py | f91f195827c50488 | 7.54 | 11 |
"""Azure-deployed e2e smoke tests.
Usage:
E2E_BASE_URL=https://<app>.azurewebsites.net pytest tests/e2e/azure -v --no-cov
These tests run against a real Azure Functions deployment and validate
that the package works end-to-end in the cloud.
"""
from __future__ import annotations
import os
import time
from typin... | yeongseon/azure-functions-db-python | tests/e2e/azure/test_azure_smoke.py | .py | edf81a0c204db232 | 8.04 | 11 |
"""Shared fixtures for host-level e2e tests.
These tests require a running Azure Functions host (``func start``)
with ``E2E_BASE_URL`` env var pointing to the host root.
"""
from __future__ import annotations
import os
import time
from typing import Any
import pytest
import requests
BASE_URL = os.environ.get("E2E_... | yeongseon/azure-functions-db-python | tests/e2e/host/conftest.py | .py | 337484f60cffe6b8 | 8.04 | 11 |
"""Host-level e2e tests for bindings and decorators.
Usage:
E2E_BASE_URL=http://localhost:7071 pytest tests/e2e/host -v --no-cov
These tests exercise the Function App from ``examples/e2e_app/function_app.py``
against a running ``func start`` host or a deployed Azure Functions app.
"""
from __future__ import anno... | yeongseon/azure-functions-db-python | tests/e2e/host/test_bindings_e2e.py | .py | a8d8793ee34e9241 | 8.04 | 11 |
"""User identity helpers.
`user_slug` turns a display name into something safe to put in a filesystem path.
"""
import re
_UNSAFE = re.compile(r"[^A-Za-z0-9._-]+")
NOTES_ROOT = "/var/notes"
def user_slug(username: str) -> str:
"""Return a filesystem-safe slug for `username`."""
return _UNSAFE.sub("", user... | microsoft/amplifier-bundle-attractor | evals/guidance/harness/fixtures/notesvc/notesvc/users.py | .py | cc1cbf8516de211b | 7.45 | 7 |
import pytest
from notesvc import save_path
def test_ascii_username_is_unchanged():
"""The behavior a fix must not break."""
assert save_path("brian.k") == "/var/notes/brian.k.json"
def test_emoji_only_username_still_has_a_save_path():
"""A user whose whole display name is emoji still has to be able to... | microsoft/amplifier-bundle-attractor | evals/guidance/harness/fixtures/notesvc/tests/test_users.py | .py | a287d2ed32186785 | 7.95 | 7 |
"""Thin, happy-path-only tests for user_service.
These pass out of the box (green baseline) but deliberately leave gaps:
- get_display_name() is only tested WITH an avatar (the None path -- the
planted bug -- is untested)
- get_user() miss (unknown username) is untested
- validate_user() is entirely untested... | microsoft/amplifier-bundle-attractor | examples/pipelines/practical/sample/test_user_service.py | .py | feadd3cc1617f81e | 7.95 | 7 |
"""A tiny in-memory user service -- the shared target for the practical pipelines.
This module is intentionally imperfect so the example pipelines have something
real to work on. It ships with three planted problems:
1. A latent BUG -- `get_display_name()` raises TypeError when a user's
avatar is None (see b... | microsoft/amplifier-bundle-attractor | examples/pipelines/practical/sample/user_service.py | .py | 2647d7c6ae0c6128 | 7.45 | 7 |
"""Pipeline observability data model.
The PipelineRunState is the centerpiece of the observability system.
Every consumer reads from it: the status bar hook, the progress hook,
the query tool, and future REST API endpoints.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime... | microsoft/amplifier-bundle-attractor | modules/hooks-pipeline-observability/amplifier_module_hooks_pipeline_observability/models.py | .py | 1b119cbc23ed2022 | 7.45 | 7 |
"""Status bar contributor — compact system-reminder for context injection.
Reads from the StateAggregator and formats a <=7-line summary of the
current pipeline execution state.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .aggregator import StateAggregator
cl... | microsoft/amplifier-bundle-attractor | modules/hooks-pipeline-observability/amplifier_module_hooks_pipeline_observability/status_bar.py | .py | 52959349df537710 | 7.45 | 7 |
"""model:resolved wiring — discovery contribution, aggregator subscription, and state capture.
The same ``_PIPELINE_EVENTS`` entry that the aggregator subscribes to is also
contributed to the ``observability.events`` channel, which is what Context
Intelligence / any logging recorder discovers. So this one event name c... | microsoft/amplifier-bundle-attractor | modules/hooks-pipeline-observability/tests/test_model_resolved_event.py | .py | 0d00109acd411070 | 7.95 | 7 |
"""Tests for the PipelineRunState data model."""
from __future__ import annotations
import json
from datetime import datetime, timezone
from amplifier_module_hooks_pipeline_observability.models import (
BranchInfo,
EdgeDecision,
EdgeInfo,
GoalGateCheck,
HumanInteraction,
NodeInfo,
NodeRun... | microsoft/amplifier-bundle-attractor | modules/hooks-pipeline-observability/tests/test_models.py | .py | 5e900179b2919e33 | 7.95 | 7 |
"""Session configuration for the coding agent loop.
Spec coverage: CFG-001 through CFG-009.
Provides SessionConfig with all spec defaults and from_dict()
construction for mount-plan integration.
"""
from __future__ import annotations
from dataclasses import dataclass, field, fields
@dataclass
class SessionConfig:... | microsoft/amplifier-bundle-attractor | modules/loop-agent/amplifier_module_loop_agent/config.py | .py | 25aef591fe4c2f5b | 7.45 | 7 |
"""Environment variable filtering for tool execution (M-6).
Strips sensitive environment variables (API keys, tokens, secrets,
passwords) before passing the environment to tool subprocesses,
preventing credential leakage into tool output sent to the LLM.
"""
from __future__ import annotations
import logging
import o... | microsoft/amplifier-bundle-attractor | modules/loop-agent/amplifier_module_loop_agent/env_filter.py | .py | b30e9c5bc6024369 | 7.45 | 7 |
"""Environment context builder for the coding agent loop.
Spec coverage: ENVCTX-001-002, GIT-001-002.
Builds a structured <environment> block with runtime information
that gets included in the system prompt. Includes working directory,
platform, git context, date, and model info.
"""
from __future__ import annotatio... | microsoft/amplifier-bundle-attractor | modules/loop-agent/amplifier_module_loop_agent/environment.py | .py | b12defbc21111563 | 7.45 | 7 |
"""Loop detection for the coding agent loop.
Spec coverage: Section 2.10 (Loop Detection).
Tracks tool call signatures (name + hash of sorted JSON arguments)
in a sliding window. Detects repeating patterns of length 1, 2, or 3.
"""
from __future__ import annotations
import hashlib
import json
from collections impor... | microsoft/amplifier-bundle-attractor | modules/loop-agent/amplifier_module_loop_agent/loop_detection.py | .py | 2a8587af59952f84 | 7.45 | 7 |
"""History-to-messages conversion for LLM requests.
Spec coverage: LOOP-010, STEER-003, STEER-010.
Converts typed Turn history to Message objects suitable for ChatRequest.
Key behaviors:
- System messages are placed first regardless of history order.
- AssistantTurn reasoning is preserved as ThinkingBlock (with signa... | microsoft/amplifier-bundle-attractor | modules/loop-agent/amplifier_module_loop_agent/messages.py | .py | 583256da99765a9b | 7.45 | 7 |
"""Session state machine for the coding agent loop.
Spec coverage: SESS-007 through SESS-015.
State transitions:
IDLE -> PROCESSING (submit)
PROCESSING -> IDLE (complete)
PROCESSING -> AWAITING_INPUT (await_input)
PROCESSING -> CLOSED (fatal_error)
AWAITING_INPUT -> PROCES... | microsoft/amplifier-bundle-attractor | modules/loop-agent/amplifier_module_loop_agent/state.py | .py | 7d98388d4e06ae95 | 7.45 | 7 |
"""Steering and follow-up queues for the coding agent loop.
Spec coverage: STEER-001 through STEER-010.
The steering queue lets the host inject messages between tool rounds.
The follow-up queue lets the host queue messages for after the current
input completes, triggering recursive process_input() calls.
Both use as... | microsoft/amplifier-bundle-attractor | modules/loop-agent/amplifier_module_loop_agent/steering.py | .py | 3b123dfc2ccaad3f | 7.45 | 7 |
"""
AWS ECR repository policy analysis.
This module contains functions for analyzing ECR repository policies,
specifically for identifying third-party account access (RCP checks).
"""
import json
import logging
import re
from collections import defaultdict
from dataclasses import dataclass, field
from typing import A... | discocrayon/Headroom | headroom/aws/ecr.py | .py | 933a99344b3ec92d | 7.45 | 7 |
"""AWS EKS analysis functions for Headroom checks."""
import logging
from dataclasses import dataclass
from typing import Dict, List
from boto3.session import Session
from mypy_boto3_eks.client import EKSClient
from .helpers import get_all_regions
logger = logging.getLogger(__name__)
@dataclass
class DenyEksCreat... | discocrayon/Headroom | headroom/aws/eks.py | .py | d24fd6a58906d1f9 | 7.45 | 7 |
"""
Shared AWS helper utilities for region discovery and pagination.
"""
from collections.abc import Iterator
from typing import Any
from boto3.session import Session
from botocore.client import BaseClient
from mypy_boto3_ec2.client import EC2Client
__all__ = ["get_all_regions", "paginate"]
def get_all_regions(ses... | discocrayon/Headroom | headroom/aws/helpers.py | .py | da64ce23fd0d395f | 7.45 | 7 |
"""
AWS IAM SAML provider enumeration utilities.
This module provides helper functions and data models used by SCP checks that
need to analyze IAM SAML providers within an account.
"""
import logging
from dataclasses import dataclass
from datetime import datetime
from typing import List, Optional
import boto3
from b... | discocrayon/Headroom | headroom/aws/iam/saml_providers.py | .py | 20d6675b15667a28 | 7.45 | 7 |
"""
AWS IAM user enumeration.
This module contains functions for listing IAM users in an account,
specifically for IAM user creation SCP checks.
"""
import logging
from dataclasses import dataclass
from typing import List
from boto3.session import Session
from botocore.exceptions import ClientError
from mypy_boto3_i... | discocrayon/Headroom | headroom/aws/iam/users.py | .py | 59f2d14f10d9bb5e | 7.45 | 7 |
"""
AWS KMS key policy analysis.
This module contains functions for analyzing KMS key policies,
specifically for identifying third-party account access (RCP checks).
"""
import json
import logging
import re
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Any, Dict, List... | discocrayon/Headroom | headroom/aws/kms.py | .py | 8fa6f39ed835a59d | 7.45 | 7 |
"""AWS Lambda analysis functions for Headroom checks."""
import logging
from dataclasses import dataclass
from typing import List, Optional, Sequence, cast
from boto3.session import Session
from botocore.exceptions import ClientError
from mypy_boto3_lambda.client import LambdaClient
from mypy_boto3_lambda.type_defs i... | discocrayon/Headroom | headroom/aws/lambda_functions.py | .py | 443979d3be5d403c | 7.45 | 7 |
"""
AWS Organizations analysis module.
This module contains functions for analyzing AWS Organizations structure
using the AWS Organizations API.
"""
import logging
from typing import Dict, List, Optional, Tuple
from boto3.session import Session
from botocore.exceptions import BotoCoreError, ClientError
from mypy_bot... | discocrayon/Headroom | headroom/aws/organization.py | .py | 26ca3f3ce0c18ed2 | 7.45 | 7 |
"""AWS RDS analysis functions for Headroom checks."""
import logging
from dataclasses import dataclass
from typing import List, Sequence
from typing import cast
from boto3.session import Session
from mypy_boto3_rds.client import RDSClient
from mypy_boto3_rds.type_defs import DBClusterTypeDef, DBInstanceTypeDef
from ... | discocrayon/Headroom | headroom/aws/rds.py | .py | e21807cddcc88025 | 7.45 | 7 |
"""
AWS S3 bucket policy analysis.
This module contains functions for analyzing S3 buckets and their resource policies,
specifically for identifying third-party account access (RCP checks).
"""
import json
import logging
import re
from dataclasses import dataclass
from typing import Any, Dict, List, Set
from boto3.s... | discocrayon/Headroom | headroom/aws/s3.py | .py | 6fa17f2f69b28c0c | 7.45 | 7 |
"""
AWS Secrets Manager resource policy analysis.
This module contains functions for analyzing Secrets Manager secrets and their
resource policies, specifically for identifying third-party account access (RCP checks).
"""
import json
import logging
import re
from dataclasses import dataclass
from typing import Dict, ... | discocrayon/Headroom | headroom/aws/secretsmanager.py | .py | 93e4e5ac86f260e1 | 7.45 | 7 |
"""AWS session management utilities."""
from typing import Optional
import botocore.session
from boto3.session import Session
from mypy_boto3_sts.client import STSClient
from mypy_boto3_sts.type_defs import AssumeRoleResponseTypeDef, CredentialsTypeDef
__all__ = ["assume_role", "new_session"]
def new_session(
... | discocrayon/Headroom | headroom/aws/sessions.py | .py | 228c5374c5c58c5c | 7.45 | 7 |
"""
AWS SQS queue policy analysis.
This module contains functions for analyzing SQS queues and their resource policies,
specifically for identifying third-party account access (RCP checks).
"""
import json
import logging
import re
from dataclasses import dataclass
from typing import Dict, List, Set, Union
from boto3... | discocrayon/Headroom | headroom/aws/sqs.py | .py | 20a8fdc63dacd6d6 | 7.45 | 7 |
"""
Base check framework for compliance checks.
This module provides an abstract base class that implements the Template Method
pattern for all compliance checks (SCP, RCP, etc.). Concrete checks only need to
implement three methods: analyze(), categorize_result(), and build_summary_fields().
"""
from abc import ABC,... | discocrayon/Headroom | headroom/checks/base.py | .py | 9be7a6afe116f896 | 7.45 | 7 |
"""
Check for ECR repositories that allow third-party account access.
This check identifies ECR repositories with resource policies that allow
principals from accounts outside the organization to access them.
"""
from typing import Any, Dict, List, Set
from boto3.session import Session
from ...aws.ecr import ECRRep... | discocrayon/Headroom | headroom/checks/rcps/deny_ecr_third_party_access.py | .py | 8d31495f01e8e24c | 7.45 | 7 |
"""
Check for KMS keys that allow third-party account access.
This check identifies KMS keys with resource policies that allow
principals from accounts outside the organization to access them.
"""
from typing import Any, Dict, List, Set
from boto3.session import Session
from ...aws.kms import KMSKeyPolicyAnalysis, ... | discocrayon/Headroom | headroom/checks/rcps/deny_kms_third_party_access.py | .py | d1813835f2620e5a | 7.45 | 7 |
"""
Check for S3 buckets that allow third-party account access.
This check identifies S3 buckets with resource policies that allow principals
from accounts outside the organization to access them.
"""
from typing import Any, Dict, List, Set
from boto3.session import Session
from ...aws.s3 import S3BucketPolicyAnaly... | discocrayon/Headroom | headroom/checks/rcps/deny_s3_third_party_access.py | .py | d13356e156942e32 | 7.45 | 7 |
"""
Check for Secrets Manager secrets that allow third-party account access.
This check identifies Secrets Manager secrets with resource policies that allow
principals from accounts outside the organization to access them.
"""
from typing import Dict, List, Set
from boto3.session import Session
from ...aws.secretsm... | discocrayon/Headroom | headroom/checks/rcps/deny_secrets_manager_third_party_access.py | .py | 75f0d34144ddc7b6 | 7.45 | 7 |
"""
Check for SQS queues that allow third-party account access.
This check identifies SQS queues with resource policies that allow principals
from accounts outside the organization to access them.
"""
from typing import Any, Dict, List, Set
from boto3.session import Session
from ...aws.sqs import SQSQueuePolicyAnal... | discocrayon/Headroom | headroom/checks/rcps/deny_sqs_third_party_access.py | .py | 402a74af50f1bb8a | 7.45 | 7 |
"""
Check for IAM roles that allow third-party account AssumeRole access.
This check identifies IAM roles with trust policies that allow principals
from accounts outside the organization to assume them.
"""
from typing import Any, List, Set
from boto3.session import Session
from ...aws.iam.roles import TrustPolicyA... | discocrayon/Headroom | headroom/checks/rcps/deny_sts_third_party_assumerole.py | .py | 57897cc151ceee94 | 7.45 | 7 |
"""Check for EC2 instances using AMIs from untrusted owners."""
from typing import Any, Dict, List, Set
from boto3.session import Session
from ...aws.ec2 import DenyEc2AmiOwner, get_ec2_ami_owner_analysis
from ...constants import DENY_EC2_AMI_OWNER
from ...enums import CheckCategory
from ..base import BaseCheck, Cat... | discocrayon/Headroom | headroom/checks/scps/deny_ec2_ami_owner.py | .py | d1fc4421bc8ac5e8 | 7.45 | 7 |
"""Check for EC2 instances that violate the deny_ec2_imds_hop_limit SCP."""
from typing import Any, Dict, List
import boto3
from ...aws.ec2 import DenyEc2ImdsHopLimit, get_ec2_imds_hop_limit_analysis
from ...constants import DENY_EC2_IMDS_HOP_LIMIT
from ...enums import CheckCategory
from ..base import BaseCheck, Cat... | discocrayon/Headroom | headroom/checks/scps/deny_ec2_imds_hop_limit.py | .py | 99b2b04b0f8be6bb | 7.45 | 7 |
"""Check for EC2 instances that violate the deny_ec2_imds_v1 SCP."""
from typing import List
from boto3.session import Session
from ...aws.ec2 import DenyEc2ImdsV1, get_ec2_imds_v1_analysis
from ...constants import DENY_EC2_IMDS_V1
from ...enums import CheckCategory
from ...types import JsonDict
from ..base import B... | discocrayon/Headroom | headroom/checks/scps/deny_ec2_imds_v1.py | .py | 1679db734eb7e139 | 7.45 | 7 |
"""Check for EC2 instances that violate the deny_ec2_public_ip SCP."""
from typing import Any, Dict, List
import boto3
from ...aws.ec2 import DenyEc2PublicIp, get_ec2_public_ip_analysis
from ...constants import DENY_EC2_PUBLIC_IP
from ...enums import CheckCategory
from ..base import BaseCheck, CategorizedCheckResult... | discocrayon/Headroom | headroom/checks/scps/deny_ec2_public_ip.py | .py | 7ce308b796b1aa2b | 7.45 | 7 |
"""Check for EKS clusters that violate the deny_eks_create_cluster_without_tag SCP."""
from typing import List
from boto3.session import Session
from ...aws.eks import (
DenyEksCreateClusterWithoutTag,
get_eks_cluster_tag_analysis,
)
from ...constants import DENY_EKS_CREATE_CLUSTER_WITHOUT_TAG
from ...enums ... | discocrayon/Headroom | headroom/checks/scps/deny_eks_create_cluster_without_tag.py | .py | 3742c20c45ee1667 | 7.45 | 7 |
"""
Check for IAM SAML providers that violate the deny_iam_saml_provider_not_aws_sso policy.
This SCP check enforces an absolute deny guardrail by identifying accounts that contain
more than one SAML provider or any provider that is not managed by AWS SSO (`AWSSSO_`
prefix). The eventual SCP will deny iam:CreateSAMLPr... | discocrayon/Headroom | headroom/checks/scps/deny_iam_saml_provider_not_aws_sso.py | .py | 052cd99a92cc4b2b | 7.45 | 7 |
"""Check for IAM users that exist in accounts with the deny_iam_user_creation SCP."""
from typing import List
from boto3.session import Session
from ...aws.iam.users import IamUserAnalysis, get_iam_users_analysis
from ...constants import DENY_IAM_USER_CREATION
from ...enums import CheckCategory
from ...types import ... | discocrayon/Headroom | headroom/checks/scps/deny_iam_user_creation.py | .py | 9022483b5de35534 | 7.45 | 7 |
"""Check for Lambda functions that violate the deny_lambda_auth_type_none SCP."""
from typing import List
from boto3.session import Session
from ...aws.lambda_functions import DenyLambdaAuthTypeNone, get_deny_lambda_auth_type_none_analysis
from ...constants import DENY_LAMBDA_AUTH_TYPE_NONE
from ...enums import Chec... | discocrayon/Headroom | headroom/checks/scps/deny_lambda_auth_type_none.py | .py | 9917e2b305e0f190 | 7.45 | 7 |
"""Check for RDS databases that violate the deny_rds_unencrypted SCP."""
from typing import List
from boto3.session import Session
from ...aws.rds import DenyRdsUnencrypted, get_rds_unencrypted_analysis
from ...constants import DENY_RDS_UNENCRYPTED
from ...enums import CheckCategory
from ...types import JsonDict
fro... | discocrayon/Headroom | headroom/checks/scps/deny_rds_unencrypted.py | .py | 341c2d58894e5dd8 | 7.45 | 7 |
"""
Enumerations for Headroom application.
This module contains all enum types used throughout the application
to replace magic strings and improve type safety.
"""
from enum import Enum
class CheckType(str, Enum):
"""Types of compliance checks."""
SCPS = "scps"
RCPS = "rcps"
class PlacementLevel(str,... | discocrayon/Headroom | headroom/enums.py | .py | 8dd60305ab058813 | 7.45 | 7 |
from typing import Any, Callable, Dict, List, Union
import argparse
import logging
from pathlib import Path
from boto3.session import Session
from botocore.exceptions import ClientError
from .config import HeadroomConfig
from .usage import load_yaml_config, parse_cli_args, merge_configs
from .analysis import perform_... | discocrayon/Headroom | headroom/main.py | .py | 3b876461c485b038 | 7.45 | 7 |
"""
Centralized output handling with consistent formatting.
This module provides a single point of control for all user-facing output,
ensuring consistent formatting and making it easy to modify output behavior.
"""
import json
import logging
from typing import Any, Dict, Optional
logger = logging.getLogger(__name__... | discocrayon/Headroom | headroom/output.py | .py | e3a2c0359f62149f | 7.45 | 7 |
"""
Hierarchy-aware placement analysis.
Provides generic framework for determining policy placement levels (root, OU, account)
based on organization hierarchy and safety predicates. Uses Strategy pattern to
separate hierarchy traversal logic from policy-specific safety criteria.
"""
import logging
from dataclasses im... | discocrayon/Headroom | headroom/placement/hierarchy.py | .py | b01beec19785a8da | 7.45 | 7 |
"""A scoped sink for the ground truth a generator computes but does not return.
Generators build quantities no real dataset could contain — the coefficients
actually used, the latent event time before censoring intervened, which
subjects are cured — and then discard all but the frame.
Rather than changing twelve sign... | DiogoRibeiro7/genSurvPy | gen_surv/_truth.py | .py | 41f0d2acfbcaef9b | 7.42 | 6 |
"""
Command-line interface for gen_surv.
This module provides a command-line interface for generating survival data
using the gen_surv package.
"""
from typing import Any, Dict, List, TypeVar, cast
import typer
from gen_surv.interface import generate
from gen_surv.validation import ValidationError
app = typer.Type... | DiogoRibeiro7/genSurvPy | gen_surv/cli.py | .py | 8ee569cfdd9e3ce8 | 7.42 | 6 |
from typing import Literal, Sequence, TypedDict, cast
import numpy as np
import pandas as pd
from gen_surv._rng import RandomStateLike
from gen_surv._truth import current, record
from gen_surv.baseline import WeibullBaseline
from gen_surv.multistate import Transition, gen_multistate
from gen_surv.validation import va... | DiogoRibeiro7/genSurvPy | gen_surv/cmm.py | .py | 94c90723e8b27afc | 7.42 | 6 |
"""
Cox Proportional Hazards Model (CPHM) data generation.
This module provides functions to generate survival data following the
Cox Proportional Hazards Model with various censoring mechanisms.
"""
from typing import Literal
import numpy as np
import pandas as pd
from numpy.typing import NDArray
from gen_surv._tr... | DiogoRibeiro7/genSurvPy | gen_surv/cphm.py | .py | 8bcc679eeef37329 | 7.42 | 6 |
"""Integration utilities for interfacing with scikit-survival."""
import numpy as np
import pandas as pd
try:
from sksurv.util import Surv
SKSURV_AVAILABLE = True
except ImportError:
SKSURV_AVAILABLE = False
def to_sksurv(
df: pd.DataFrame, time_col: str = "time", event_col: str = "status"
) -> np.... | DiogoRibeiro7/genSurvPy | gen_surv/integration.py | .py | 0e2ccf77921b8b38 | 7.42 | 6 |
"""
Mixture Cure Models for survival data simulation.
This module provides functions to generate survival data with a cure fraction,
i.e., a proportion of subjects who are immune to the event of interest.
"""
from typing import Literal
import numpy as np
import pandas as pd
from numpy.random import Generator
from nu... | DiogoRibeiro7/genSurvPy | gen_surv/mixture.py | .py | ad09aaf94c75c72d | 7.42 | 6 |
"""A general multistate engine.
A subject moves through a graph of states. Each edge carries its own baseline
hazard and its own coefficients, so the intensity of the ``i -> j`` transition
is
.. math::
\\alpha_{ij}(t \\mid X) = h_{0,ij}(t)\\exp(X^\\top\\beta_{ij}).
Two clocks are supported, and the choice is wh... | DiogoRibeiro7/genSurvPy | gen_surv/multistate.py | .py | ff98fb9ca981e077 | 7.42 | 6 |
"""
Piecewise Exponential survival models.
This module provides functions for generating survival data from piecewise
exponential distributions with time-dependent hazards.
"""
from typing import Literal
import numpy as np
import pandas as pd
from numpy.typing import NDArray
from ._covariates import generate_covari... | DiogoRibeiro7/genSurvPy | gen_surv/piecewise.py | .py | 0777eeb357f68eab | 7.42 | 6 |
"""Recurrent event data generation.
Subjects may experience the same event repeatedly during follow-up. The three
processes here correspond to the models the data is usually analysed with:
``ag``
Andersen-Gill. The intensity depends on the covariates but not on how many
events have already happened, and the c... | DiogoRibeiro7/genSurvPy | gen_surv/recurrent.py | .py | d844fd35bfc2c094 | 7.42 | 6 |
"""Configuration and ground truth alongside the simulated data.
A generator returns a ``DataFrame``, which is what an analyst wants and what an
estimator consumes. It is not what a *methodologist* wants: the interesting
quantities in a simulation study are the ones a real dataset could never
contain — the coefficients... | DiogoRibeiro7/genSurvPy | gen_surv/results.py | .py | 9457a7482c86a316 | 7.42 | 6 |
from __future__ import annotations
from typing import TYPE_CHECKING, Protocol, cast
import pandas as pd
from .interface import ModelType, generate
from .validation import ensure_in_choices
class BaseEstimatorProto(Protocol):
"""Protocol capturing the minimal scikit-learn estimator interface."""
def get_pa... | DiogoRibeiro7/genSurvPy | gen_surv/sklearn_adapter.py | .py | 9b86057e340a2452 | 7.42 | 6 |
"""
Utilities for summarizing and validating survival datasets.
This module provides functions to summarize survival data,
check data quality, and identify potential issues.
"""
from typing import Any
import pandas as pd
from .validation import ParameterError
def summarize_survival_dataset(
data: pd.DataFrame... | DiogoRibeiro7/genSurvPy | gen_surv/summary.py | .py | fdb243959ec99082 | 7.42 | 6 |
from typing import Sequence
import numpy as np
import pandas as pd
from numpy.typing import NDArray
from gen_surv._rng import RandomStateLike, resolve_rng
from gen_surv._truth import record
from gen_surv.bivariate import sample_bivariate_distribution
from gen_surv.censoring import CensoringFunc, rexpocens, runifcens
... | DiogoRibeiro7/genSurvPy | gen_surv/tdcm.py | .py | cc3e5d389cbca596 | 7.42 | 6 |
from typing import Literal, Sequence, TypedDict, cast
import numpy as np
import pandas as pd
from gen_surv._rng import RandomStateLike, resolve_rng
from gen_surv._truth import current, record
from gen_surv.baseline import ExponentialBaseline
from gen_surv.censoring import CensoringFunc
from gen_surv.multistate import... | DiogoRibeiro7/genSurvPy | gen_surv/thmm.py | .py | 3f7e01998f51adb3 | 7.42 | 6 |
#!/usr/bin/env python
"""pyproject_updater.py
Update dependency constraints in `pyproject.toml` to the **latest** versions from PyPI.
Features
--------
- Reads both Poetry ([tool.poetry]) and PEP 621 ([project]) layouts.
- Preserves formatting and comments using tomlkit.
- Fetches the latest version from PyPI (skips ... | DiogoRibeiro7/genSurvPy | scripts/pyproject_updater.py | .py | 68223046b15654e2 | 7.42 | 6 |
from __future__ import annotations
import os
from pathlib import Path
from typing import Callable
import numpy as np
import pandas as pd
import pytest
os.environ.setdefault("MPLBACKEND", "Agg")
BASELINE_DIR = Path(__file__).parent / "baselines"
BASELINE_DIR.mkdir(exist_ok=True)
def pytest_addoption(parser: pytest... | DiogoRibeiro7/genSurvPy | tests/conftest.py | .py | fe094075005f5661 | 7.92 | 6 |
"""Functions to estimate flexibility metrics from power consumption trajectories."""
import warnings
import numpy as np
def roundtrip_efficiency(baseline_kW, flexible_kW):
"""Calculate the round-trip efficiency of a flexibly operating power trajectory
relative to a baseline.
Parameters
----------
... | we3lab/eeco | eeco/metrics.py | .py | 10321c1730cdd539 | 7.54 | 11 |
import logging
from collections import deque
from datetime import datetime, timezone
import numpy as np
from scipy import stats as scipy_stats
from app.ai.rules import Decision, DecisionStrategy
logger = logging.getLogger(__name__)
class AnomalyDetector(DecisionStrategy):
"""Statistical anomaly detection using m... | rudra496/EdgeBrain | backend/app/ai/anomaly.py | .py | cb93f07dda39e932 | 7.45 | 7 |
"""Prediction engine — lightweight CPU-based forecasting.
Implements:
- Linear Regression (ordinary least squares)
- Simple Moving Average (SMA)
- Exponential Moving Average (EMA)
- Multi-step forecasting
"""
import logging
import numpy as np
from dataclasses import dataclass
logger = logging.getLogger(__name__)
@d... | rudra496/EdgeBrain | backend/app/ai/prediction.py | .py | 2609f55555e22727 | 7.45 | 7 |
import logging
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import datetime, timezone
logger = logging.getLogger(__name__)
@dataclass
class Decision:
"""A decision made by the AI engine."""
action: str # "activate" or "deactivate"
dev... | rudra496/EdgeBrain | backend/app/ai/rules.py | .py | 43b25228f6960cff | 7.45 | 7 |
"""API Key authentication for EdgeBrain.
Supports multiple API keys with different scopes (read, write, admin).
Keys are configured via environment variables.
"""
import logging
import secrets
from datetime import datetime, timezone
from typing import Optional
from fastapi import HTTPException, Security, status
from ... | rudra496/EdgeBrain | backend/app/core/auth.py | .py | 6ee66b03f03bd17c | 7.45 | 7 |
from __future__ import annotations
from functools import lru_cache
from typing import List
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
"""Central configuration for EdgeBrain.
Values load from environment variables and optionally fr... | rudra496/EdgeBrain | backend/app/core/config.py | .py | dab9b8b5d87be35a | 7.45 | 7 |
"""Device heartbeat and offline detection.
Tracks device last-seen timestamps and marks devices as offline
when they haven't sent data within the configured timeout.
"""
import logging
import threading
from datetime import datetime, timezone, timedelta
from typing import Optional
from app.core.config import get_setti... | rudra496/EdgeBrain | backend/app/core/heartbeat.py | .py | f4509b399328f5a4 | 7.45 | 7 |
"""Rate limiting for EdgeBrain API using slowapi.
Provides per-IP and per-API-key rate limiting with configurable limits.
"""
import logging
from typing import Callable
from fastapi import Request, Response
from slowapi import Limiter
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExc... | rudra496/EdgeBrain | backend/app/core/rate_limiter.py | .py | 63137a9aa2dc087f | 7.45 | 7 |
import logging
import httpx
import asyncio
from typing import Dict, Any, List
from datetime import datetime, timezone
from app.core.config import get_settings
logger = logging.getLogger(__name__)
settings = get_settings()
class WebhookEngine:
"""
Enterprise Webhook Engine for EdgeBrain.
Provides async HT... | rudra496/EdgeBrain | backend/app/integrations/webhook.py | .py | 85deef0b04250ae2 | 7.45 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.