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 peer address book — gateway runtime state for federation. A node's gateway keeps a small directory mapping a **peer name** to that peer's **edge URL** (its ``httpsfront`` HTTPS front, e.g. ``https://mira:12100``) and an optional **ssh alias** (how to reach it for the ``$AWM_PEER_CRED`` fetch). This is the *only...
phy0x1a79ed/agentic-workspace
awm/gateway/awm/gateway/peers.py
.py
fea0e61154739284
7
0
"""One-shot prep run by ``dev/run.sh`` before uvicorn starts. Idempotent: bootstraps the sandbox DB. Assumes AWM_WORKSPACE points at dev/. Refuses to run otherwise so a stray invocation never touches the real workspace. """ from __future__ import annotations import os import sys from pathlib import Path def _asse...
phy0x1a79ed/agentic-workspace
awm/gateway/dev/_prep.py
.py
110d42d77a5dddc1
7
0
"""Populate the dev-harness sandbox via the running modular gateway. Hits the running gateway over HTTP on loopback (no auth). No ``awm.*`` imports, no service-level shortcuts — everything goes through the gateway's generic ``POST /invoke {name, args}`` RPC surface, calling the scopes service's tools (``project_create...
phy0x1a79ed/agentic-workspace
awm/gateway/dev/seed.py
.py
515cb3143ea74c02
7
0
"""Feature-service tools mirror the live MCP surface onto the CLI. The gateway control plane is generated from the static GATEWAY_OPERATIONS registry (see test_gateway_ops.py). Feature-service tools instead come from a live ``GET /tools`` snapshot and dispatch by name through ``POST /invoke`` — the same surface the MC...
phy0x1a79ed/agentic-workspace
awm/gateway/tests/test_cli_service_commands.py
.py
e98ac613702cb1ee
7.5
0
"""Unit tests for the profile-aware discovery gate (service.toml × AWM_PROFILES). Resolution precedence under test: explicit ``enabled.json`` entry > profile intersection > enabled. A corrupt/invalid marker is marked-but-unmatched (disabled), never fail-open. """ from __future__ import annotations import pytest fro...
phy0x1a79ed/agentic-workspace
awm/gateway/tests/test_discovery_profiles.py
.py
187ad50a4a9e77c6
7.5
0
""" Embedded Hindsight client with automatic daemon lifecycle management. This module provides HindsightEmbedded, a client that uses the same daemon management interface as hindsight-embed CLI, ensuring full compatibility. Example: ```python from hindsight import HindsightEmbedded # Daemon starts automat...
Holetron-lab/fleet-memory
hindsight-all/hindsight/embedded.py
.py
9931b3b0e9d07149
7
0
""" Server module for running Hindsight in a background thread. Provides a simple way to start and stop the Hindsight HTTP API server without blocking the main thread. """ import asyncio import logging import socket import threading import time from typing import Optional import uvicorn from uvicorn import Config fr...
Holetron-lab/fleet-memory
hindsight-all/hindsight/server.py
.py
d75326d93c6f6b5d
7
0
""" Integration tests for HindsightEmbedded client. Tests the embedded client with automatic server lifecycle management: 1. Lazy server startup on first use 2. Server reuse across multiple operations 3. Context manager support 4. Method proxying to underlying HindsightClient 5. Proper cleanup Note: Each test uses ra...
Holetron-lab/fleet-memory
hindsight-all/tests/test_embedded.py
.py
a11ab5144cea0c77
7.5
0
""" Integration test for Hindsight server with context manager. Tests the full workflow: 1. Starting server using context manager 2. Creating a memory bank 3. Storing memories (retain) 4. Recalling memories 5. Reflecting on memories Note: These tests use embedded PostgreSQL (pg0) with a shared server instance across ...
Holetron-lab/fleet-memory
hindsight-all/tests/test_server_integration.py
.py
7c82eb6603e68cf0
7.5
0
""" Hindsight Admin CLI - backup and restore operations. """ import asyncio import io import json import logging import zipfile from datetime import datetime, timezone from pathlib import Path from typing import Any import asyncpg import typer from ..config import DEFAULT_DATABASE_SCHEMA, HindsightConfig from ..exte...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/admin/cli.py
.py
f6d5571891fb2315
7
0
""" Alembic environment configuration for SQLAlchemy with pgvector. Uses synchronous psycopg2 driver for migrations to avoid pgbouncer issues. """ import logging import os from pathlib import Path from alembic import context from dotenv import load_dotenv from sqlalchemy import engine_from_config, pool # Import your...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/env.py
.py
238b0676d528f317
7
0
"""Recreate entities trigram index on LOWER(canonical_name) for case-insensitive matching The previous GIN trigram index on canonical_name was case-sensitive, causing "Alice" and "alice" to have different trigram sets. This recreates it on LOWER(canonical_name) so the % operator matches case-insensitively. Revision I...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/2eee35aa3cfc_case_insensitive_entities_trgm_index.py
.py
822b009e135b30c3
7
0
"""Add file_storage table for BYTEA-based file storage Revision ID: a1b2c3d4e5f6 Revises: y0t1u2v3w4x5 Create Date: 2026-02-16 Creates a dedicated table for storing uploaded files using BYTEA. This provides zero-config file storage that "just works" for development and small deployments. For production/scale, use S3-...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/a1b2c3d4e5f6_add_file_storage_table.py
.py
84eff3389b5ee3ad
7
0
"""Add text_signals column to memory_units for enriched BM25 indexing. text_signals stores a denormalized space-separated string of entity names (and future signals) to improve full-text search recall without polluting the stored fact text. - vchord: text_signals included in tokenize() at insert time - native: search...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/a2b3c4d5e6f7_add_text_signals_column.py
.py
b5326c421c1e13a3
7
0
"""Add GIN index on source_memory_ids for observation lookup performance Without this index, queries using the array overlap operator (&&) or array containment (@>) on source_memory_ids require a full sequential scan over all observation memory_units. At ~77k observations this was measured at 45ms per query, becoming ...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/a2b3c4d5e6f8_add_gin_index_source_memory_ids.py
.py
f5bf038b5ee566e9
7
0
"""Add consolidation_failed_at column to memory_units for tracking persistent LLM failures. When all LLM retries are exhausted on a single-memory batch, the memory is marked with consolidation_failed_at instead of consolidated_at, so it is not silently lost and can be retried later via the API. Revision ID: a3b4c5d6e...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/a3b4c5d6e7f8_add_consolidation_failed_at_to_memory_units.py
.py
6c037b106b97c07f
7
0
"""Fix per-bank vector indexes to match configured extension Revision ID: a4b5c6d7e8f9 Revises: d6e7f8a9b0c1 Create Date: 2026-04-01 Migration d5e6f7a8b9c0 hardcoded HNSW when creating per-bank partial vector indexes, ignoring HINDSIGHT_API_VECTOR_EXTENSION. Banks that existed when that migration ran got HNSW indexes...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/a4b5c6d7e8f9_fix_per_bank_vector_index_type.py
.py
0680a095c28f834c
7
0
"""Add room and hall columns to memory_units for hierarchical filtering (ADR-145) Revision ID: aa1_room_hall Revises: z1u2v3w4x5y6 Create Date: 2026-04-11 Adds room (topic) and hall (knowledge type) columns to memory_units. Room/Hall taxonomy enables pre-semantic filtering: the candidate set is narrowed by topic and ...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/aa1_add_room_hall_to_memory_units.py
.py
c2a52593f6be7667
7
0
"""Make event_date nullable in memory_units to support timestamp-free content Revision ID: aa2b3c4d5e6f Revises: z1u2v3w4x5y6 Create Date: 2026-03-02 When callers retain content without a timestamp (e.g. fictional documents, static text), the event_date column should be allowed to be NULL rather than defaulting to ut...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/aa2b3c4d5e6f_nullable_event_date.py
.py
55a1b7a74722a81c
7
0
"""add content_hash to chunks table for delta retain Revision ID: b3c4d5e6f7a8 Revises: a3b4c5d6e7f8 Create Date: 2026-03-25 """ from collections.abc import Sequence from alembic import context, op revision: str = "b3c4d5e6f7a8" down_revision: str | Sequence[str] | None = "a3b4c5d6e7f8" branch_labels: str | Sequenc...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/b3c4d5e6f7a8_add_content_hash_to_chunks.py
.py
bc8ac4339518da1b
7
0
"""Add partial indexes on memory_units temporal date fields for fast temporal retrieval Revision ID: b3c4d5e6f7g8 Revises: c1a2b3d4e5f6 Create Date: 2026-03-02 The temporal retrieval entry-point query filters memory_units by occurred_start, occurred_end, and mentioned_at using OR conditions. Without dedicated indexes...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/b3c4d5e6f7g8_add_temporal_date_indexes.py
.py
6410f96a7736c37f
7
0
"""Backfill observation_scopes column if missing. This migration ensures observation_scopes exists even on databases that had revision z1u2v3w4x5y6 applied when it referred to the old text_signals migration (before it was renamed to a2b3c4d5e6f7). The ADD COLUMN IF NOT EXISTS makes this a no-op on databases that alrea...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/b4c5d6e7f8a9_backfill_observation_scopes.py
.py
ddbd4ec5782b577f
7
0
"""add_chunks_table Revision ID: b7c4d8e9f1a2 Revises: 5a366d414dce Create Date: 2025-11-28 00:00:00.000000 """ from collections.abc import Sequence import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision: str = "b7c4d8e9f1a2" down...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/b7c4d8e9f1a2_add_chunks_table.py
.py
31a1c553825ccd42
7
0
"""Enable pg_trgm extension and add GIN trigram index on entities.canonical_name Revision ID: c1a2b3d4e5f6 Revises: b4c5d6e7f8a9 Create Date: 2026-03-02 Index is created CONCURRENTLY so the migration does not block writes on entities during production deployments. CONCURRENTLY requires running outside a transaction b...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/c1a2b3d4e5f6_enable_pg_trgm_and_entities_trgm_index.py
.py
1519aadb31cafc7d
7
0
"""Add audit_log table for feature usage tracking. Merge migration that combines the two existing heads (a3b4c5d6e7f8 + c8e5f2a3b4d1). Stores raw request/response as JSONB for expandability without future migrations. The metadata JSONB column allows adding arbitrary fields in the future. Revision ID: c2d3e4f5g6h7 Re...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/c2d3e4f5g6h7_add_audit_log_table.py
.py
7b79e31c1f82e776
7
0
"""Add history column to mental_models Revision ID: c3d4e5f6g7h8 Revises: a2b3c4d5e6f7, a2b3c4d5e6f8 Create Date: 2026-03-06 """ from collections.abc import Sequence from alembic import context, op revision: str = "c3d4e5f6g7h8" down_revision: str | Sequence[str] | None = ("a2b3c4d5e6f7", "a2b3c4d5e6f8") branch_lab...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/c3d4e5f6g7h8_add_history_to_mental_models.py
.py
48a0a16f6af968b1
7
0
"""Add bank_id column to memory_links for direct filtering The stats endpoint JOINs memory_links to memory_units just to filter by bank_id. With millions of links this takes 18+ seconds. Adding bank_id directly to memory_links lets Postgres push the filter down before the JOIN. Revision ID: c5d6e7f8a9b0 Revises: b3...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/c5d6e7f8a9b0_add_bank_id_to_memory_links.py
.py
eb61b7ac616b3b4f
7
0
"""add_retain_params_to_documents Revision ID: c8e5f2a3b4d1 Revises: b7c4d8e9f1a2 Create Date: 2025-12-02 00:00:00.000000 """ from collections.abc import Sequence import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision: str = "c8e5...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/c8e5f2a3b4d1_add_retain_params_to_documents.py
.py
0a1aa41c035ab996
7
0
"""Add covering and composite indexes to speed up link expansion graph retrieval. Two indexes target the two bottlenecks identified by EXPLAIN ANALYZE on a 17M-row memory_links table: 1. idx_memory_links_to_type_weight (to_unit_id, link_type, weight DESC) The semantic incoming direction — finding facts that consi...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/d2e3f4a5b6c7_add_memory_links_expansion_indexes.py
.py
494c70e244ad02bb
7
0
"""Recreate idx_memory_units_source_memory_ids GIN index with fastupdate=off GIN indexes use a "fastupdate" pending list by default: small writes are buffered there and flushed to the main GIN tree in bulk. Flushing requires AccessExclusiveLock on the index. Under high insert concurrency (e.g. 8 parallel pytest-xdist ...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/d4e5f6g7h8i9_gin_source_memory_ids_fastupdate_off.py
.py
07091c7f1a7b4e6c
7
0
"""Add internal_id to banks and per-(bank, fact_type) partial vector indexes Revision ID: d5e6f7a8b9c0 Revises: a3b4c5d6e7f8 Create Date: 2026-03-11 This migration: 1. Adds internal_id UUID column to banks (stable identifier for index naming) 2. Drops the global vector index (competes with per-bank partial indexes) 3...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/d5e6f7a8b9c0_add_bank_internal_id_and_per_bank_hnsw.py
.py
4b6d5330eef8c41c
7
0
"""Rename fact_type 'bank' to 'experience' Revision ID: d9f6a3b4c5e2 Revises: c8e5f2a3b4d1 Create Date: 2024-12-04 15:00:00.000000 """ from alembic import context, op # revision identifiers, used by Alembic. revision = "d9f6a3b4c5e2" down_revision = "c8e5f2a3b4d1" branch_labels = None depends_on = None def _get_s...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/d9f6a3b4c5e2_rename_bank_to_interactions.py
.py
b39fc1d83d0975ac
7
0
"""Add webhooks table and next_retry_at to async_operations. Webhook deliveries are handled as async_operations tasks (operation_type='webhook_delivery') rather than a dedicated webhook_deliveries table. Revision ID: e4f5a6b7c8d9 Revises: d2e3f4a5b6c7 Create Date: 2026-03-04 """ from collections.abc import Sequence ...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/e4f5a6b7c8d9_add_webhooks_tables.py
.py
a9a207e3b689e8f7
7
0
"""add_memory_links_from_type_weight_index Revision ID: f1a2b3c4d5e6 Revises: e0a1b2c3d4e5 Create Date: 2025-01-12 Add composite index on memory_links (from_unit_id, link_type, weight DESC) to optimize graph traversal queries that need top-k edges per type. """ from collections.abc import Sequence from alembic impo...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/f1a2b3c4d5e6_add_memory_links_composite_index.py
.py
99ee099acc3b5e0d
7
0
"""chunk_fk_cascade_delete Revision ID: f6g7h8i9j0k1 Revises: e5f6g7h8i9j0 Create Date: 2026-03-16 00:00:00.000000 """ from collections.abc import Sequence from alembic import op # revision identifiers, used by Alembic. revision: str = "f6g7h8i9j0k1" down_revision: str | Sequence[str] | None = "e5f6g7h8i9j0" branc...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/f6g7h8i9j0k1_chunk_fk_cascade_delete.py
.py
e84cc1081ee0b12e
7
0
"""Add http_config JSONB column to webhooks table. Stores HTTP delivery configuration (method, timeout, headers, params) as a single JSONB column rather than separate columns. Revision ID: f7g8h9i0j1k2 Revises: e4f5a6b7c8d9 Create Date: 2026-03-04 """ from collections.abc import Sequence from alembic import context...
Holetron-lab/fleet-memory
hindsight-api-slim/hindsight_api/alembic/versions/f7g8h9i0j1k2_add_webhook_http_config.py
.py
bcef706ee7e0990e
7
0
from __future__ import annotations import logging import threading import time from collections.abc import Callable from typing import Any # Stay inside the ``webjam`` logger namespace so the redaction filter that # ``core.logging_config`` attaches to the app's handlers covers this module. _LOGGER = logging.getLogger...
rupret007/webjam
api/local_bridge.py
.py
45159226d926e619
7
0
"""What the room itself should say about Art, in one line. A person who picked "Paint together" and pressed Host lands in a room. Until now that room said nothing: the canvas lived behind a menu, and the only mention of it was a message that appeared for nine seconds and told them which menu to open. A user interface ...
rupret007/webjam
core/art_room_presence.py
.py
74500ae8fd12a49f
7
0
"""Small, privacy-safe build provenance helper. Frozen applications read the commit captured by ``webjam.spec`` at build time. Source checkouts fall back to their local Git HEAD. No repository path, command output, environment dump, or other machine-specific value is returned to diagnostics. """ from __future__ imp...
rupret007/webjam
core/build_info.py
.py
0f45749d1d529d8b
7
0
"""Finding a program WebJam did not ship, honestly. Art hands two jobs to real open-source programs: Drawpile paints the shared canvas, and Krita hosts the AI image generator. Neither is bundled, so WebJam makes no publisher claim about either, and the only thing it can honestly assert is that the thing it is about t...
rupret007/webjam
core/external_program.py
.py
a4923faebb0dfd3f
7
0
""" Atomic file-write helpers. Most of WebJam's persistent state lives in user-home dotfiles (``~/.webjam_config.json``, ``~/.webjam_mix.json``, ``~/.webjam_notes.md``, ``~/.webjam_session.json``). A direct ``Path.write_text()`` is **not atomic**: a crash mid-write can leave a half-written file that the next launch f...
rupret007/webjam
core/file_io.py
.py
436a6bfc1e1359ba
7
0
"""Truthful pre-share checks for WebJam's supported private-LAN host flow. This is deliberately *not* a public Internet reachability detector. The current product supports a private RFC1918 LAN invitation, and this evaluator only proves the local facts WebJam can observe before asking a host to share: an authenticate...
rupret007/webjam
core/host_share_readiness.py
.py
eea1ea8f4ad99aa7
7
0
"""Shared environment boundary for every native Jamulus subprocess. WebJam must never let inherited loader, Qt, or QML controls alter which code a verified Jamulus executable loads. This module lives below both the profile and platform layers so launch probes and long-lived child roles use one policy without a core-t...
rupret007/webjam
core/jamulus_child_environment.py
.py
16570483995fceb4
7
0
"""Parsing and validation for user-entered Jamulus server endpoints.""" from __future__ import annotations import ipaddress import re from dataclasses import dataclass DEFAULT_JAMULUS_PORT = 22124 _HOST_LABEL = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$") class JamulusEndpointError(ValueError): ...
rupret007/webjam
core/jamulus_endpoint.py
.py
f62897aed5183d63
7
0
"""Version-scoped musician-name contract for Jamulus boundaries. Jamulus stores the client name in a ``QString`` and its mixer presents the name as two lines of eight user-visible characters. Those are two distinct constraints: * the wire/profile value is limited to 16 UTF-16 code units; * the musician-facing previe...
rupret007/webjam
core/jamulus_name.py
.py
b968985d13e1470a
7
0
"""Exact ordered-roster identity shared by Jamulus client and server RPC. Pinned Jamulus 3.12.2/3.12.3 rewrites server channel IDs into a separate client-local mixer namespace before exposing ``getClientList``. The one cross-RPC invariant retained by Jamulus is row order: both the client list and ``jamulusserver/getC...
rupret007/webjam
core/jamulus_roster_identity.py
.py
7b20d5acc365b137
7
0
"""Stable, path-free identities for one session's logical audio sources. Track, media-segment, and take IDs identify concrete project entities. They must change between takes. A logical source ID instead identifies the same participant/source slot across repeated takes, so Studio can stack lanes without guessing fro...
rupret007/webjam
core/logical_sources.py
.py
3bfc35ba5c8afb1c
7
0
"""WebJam beside a free Webex meeting, told truthfully. ADR 0004 settled the shape: Webex is an independent application in its own window. WebJam stores a meeting link and nothing else — no account, no token, and no embedded runtime here. Whether an Embedded App companion ships is a separate track's decision, and it ...
rupret007/webjam
core/meeting_companion.py
.py
7cf9665a74fc895d
7
0
"""Service-neutral meeting-link policy shared by setup, preflight, and launch. WebJam never embeds, joins, monitors, or controls a meeting on any service. Every conversation handoff is the same truthful action: validate one saved HTTPS link and hand it to the operating system exactly once. Known Webex, Zoom, Microsof...
rupret007/webjam
core/meeting_link.py
.py
5ce8067f477b6db2
7
0
"""Which Song tools an account can actually run, decided at runtime. Music AI workflow slugs belong to the account, not to the platform. The API reference's own example shows a beat-and-BPM workflow whose slug is ``untitled-workflow-e78c2e``, so any hardcoded list of slugs would be a guess dressed as a feature. This m...
rupret007/webjam
core/music_ai_catalog.py
.py
ffd18814c58efced
7
0
"""What a Music session may tell a companion surface, and what it will accept. A companion — a Webex Embedded App panel, or anything else outside the desktop window — needs to show the song and ask for work. This module is the whole contract for that, kept in ``core`` so the desktop side can be built and proven withou...
rupret007/webjam
core/music_companion.py
.py
3761ec3253a341c6
7
0
"""Entry หลักของ agent — loop collect → push → retry/backoff/queue. รันผ่าน: `python -m agent.agent --server <URL> --token <TOKEN> --interval 15` """ from __future__ import annotations import sys import time from pathlib import Path from typing import Any from agent import collect, selfinstall from agent.config imp...
Witawat/monitor-server
agent/agent.py
.py
664dc7a50c2f272d
7
0
"""Config ฝั่ง agent — server_url + token + interval จาก CLI arg / env / ไฟล์. ลำดับความสำคัญ: CLI arg > env (`MONITOR_*`) > ไฟล์ `agent.cfg` (ถ้ามี) > default. """ from __future__ import annotations import argparse import os from dataclasses import dataclass from agent import selfinstall ENV_PREFIX = "MONITOR_" ...
Witawat/monitor-server
agent/config.py
.py
03a6f3218dd88c13
7
0
"""ส่ง batch ไป server (urllib stdlib) + retry/backoff + queue เมื่อ offline.""" from __future__ import annotations import json import urllib.error import urllib.request from pathlib import Path from typing import Any from shared.metric import HEADER_TOKEN, INGEST_PATH _TIMEOUT_SEC = 10 class PushQueue: """Pe...
Witawat/monitor-server
agent/push.py
.py
d0edb421886f567d
7
0
"""Self-install ของ agent — เขียน config + สร้าง/ลบ service เอง (Windows NSSM / Linux systemd). ใช้เมื่อรัน `python -m agent.agent --install` (หรือ exe) — ตั้ง config ในไฟล์ `agent.cfg` ข้างตัว + สร้าง service ให้ agent เอง ไม่ต้องรัน install script แยก (AGENTS.md: ติดตั้งง่าย). """ from __future__ import annotations...
Witawat/monitor-server
agent/selfinstall.py
.py
f6553ae63d06c5d2
7
0
"""Root entry ของ server — รัน + service wrapper (NSSM/systemd). ใช้งาน: - `python run.py --config config.toml` — รัน server (dev) - `python run.py --config config.toml --service install|start|stop|remove` — จัดการ service """ from __future__ import annotations import argparse import subprocess import sys from pathl...
Witawat/monitor-server
run.py
.py
74af2e14f1aa2ffb
7
0
"""สร้างไอคอน 'monitor' (หน้าจอ + เส้น pulse) เป็น .ico หลายขนาด. ใช้ Pillow วาดรูปที่ 256px แล้วย่อลงทุกขนาด → build/monitor.ico + monitor-256.png รัน: python scripts/make_icon.py """ from __future__ import annotations from pathlib import Path from PIL import Image, ImageDraw _ROOT = Path(__file__).resolve().pare...
Witawat/monitor-server
scripts/make_icon.py
.py
6908472cb48d391f
7
0
"""ประเมิน alert rules หลัง ingest — ตรวจจับค่าเกิน threshold ต่อเนื่อง.""" from __future__ import annotations import re import time from collections.abc import Callable from typing import Any from server.alerting.notify import Notifier from server.config import AppConfig from server.storage.db import Database from ...
Witawat/monitor-server
server/alerting/engine.py
.py
9dcead3830788a0d
7
0
"""ตัวส่ง notification — webhook (POST JSON) + Telegram.""" from __future__ import annotations from typing import Any import httpx from server.alerting import settings as notifier_settings from server.config import NotifierConfig from server.storage.db import Database class Notifier: """ส่งแจ้งเตือนไปยัง webh...
Witawat/monitor-server
server/alerting/notify.py
.py
23ba863caef93c1f
7
0
"""Monitor host หมดอายุ (offline) — ส่ง notification เมื่อ host หายไปนานเกิน.""" from __future__ import annotations import asyncio import time from contextlib import suppress from typing import Any from server.alerting.notify import Notifier from server.config import AppConfig from server.storage.db import Database ...
Witawat/monitor-server
server/alerting/offline.py
.py
eeda16a4acaa8e90
7
0
"""ค่า notifier (webhook/telegram) — merge: DB (state_kv) เหนือกว่า config.toml. ผู้ใช้ตั้งค่าผ่าน WebUI → เก็บใน DB (`state_kv["notifiers"]`) ไม่ต้อง restart; config.toml เดิมยังเป็นค่าเริ่มต้น (fallback) ถ้ายังไม่ได้ตั้งผ่าน UI. """ from __future__ import annotations import json from typing import Any from server...
Witawat/monitor-server
server/alerting/settings.py
.py
23c55133169f52a0
7
0
"""Router alerts — CRUD rules + history + ack.""" from __future__ import annotations from typing import Annotated, Any from fastapi import APIRouter, Body, Depends, HTTPException, Request from fastapi.responses import JSONResponse from server.api.deps import require_admin from server.storage.db import Database from...
Witawat/monitor-server
server/api/alerts.py
.py
a80c9bc0f1db1f42
7
0
"""Dependency ที่ใช้ร่วมกันของ routers — require_admin (session cookie).""" from __future__ import annotations from fastapi import HTTPException, Request from server.webui.auth import verify_session SESSION_COOKIE = "session" def client_ip(request: Request) -> str: """คืน IP ของ client โดยรองรับ reverse proxy...
Witawat/monitor-server
server/api/deps.py
.py
8948ffdd8b6e1ffa
7
0
"""อ่าน + validate config.toml ฝั่ง server (pydantic + stdlib tomllib).""" from __future__ import annotations import tomllib from pathlib import Path from typing import Any, Literal from pydantic import BaseModel, Field, field_validator, model_validator # ── model config ── _OPS = Literal[">", ">=", "<", "<=", "==...
Witawat/monitor-server
server/config.py
.py
2d570539d1670477
7
0
"""ตรรกะรับ push จาก agent — validate batch + rate limit + upsert host. หัวใจของฝั่งรับ: เช็ค token → rate limit → validate schema → เขียนลง DB. """ from __future__ import annotations import time from typing import Any from server.alerting.engine import AlertEngine from server.config import AppConfig from server.st...
Witawat/monitor-server
server/ingest.py
.py
c52afc7225877292
7
0
"""SSE event hub — push event ไป client ที่ subscribe (กัน poll ถี่).""" from __future__ import annotations import asyncio from collections.abc import AsyncIterator # ชนิด event ที่ broadcast ได้ (ตรงกับที่ client ฟัง) EVENT_HOSTS = "hosts" # fleet/host data เปลี่ยน (มี snapshot ใหม่ / host เปลี่ยน) EVENT_ALER...
Witawat/monitor-server
server/streaming.py
.py
5a23e314a7db4ea0
7
0
"""Helper auth ฝั่ง WebUI — bcrypt hash + เซ็น/ตรวจ cookie session.""" from __future__ import annotations import base64 import hashlib import hmac import json import time import bcrypt _COOKIE_MAX_AGE = 7 * 86400 # หมดอายุ 7 วัน def hash_password(password: str) -> str: """สร้าง bcrypt hash ของรหัสผ่าน (ใช้ g...
Witawat/monitor-server
server/webui/auth.py
.py
4ff493387e29fc42
7
0
"""Schema metric + ingest contract ที่ server กับ agent ใช้ร่วมกัน. บางพอให้ agent (stdlib เท่านั้น) import ได้ — ใช้ dataclasses ล้วน ไม่พึ่ง pydantic. Server ใช้ validate ฝั่งรับ push; agent ใช้สร้าง snapshot ตอน collect. """ from __future__ import annotations from dataclasses import dataclass, field from typing i...
Witawat/monitor-server
shared/metric.py
.py
941d0919e7098cfd
7
0
"""ทดสอบ server/main.py — skeleton API /api/health + /api/status.""" from __future__ import annotations import tempfile from contextlib import contextmanager from pathlib import Path from fastapi.testclient import TestClient from server import __version__ from server.config import AppConfig from server.main import ...
Witawat/monitor-server
tests/test_api_status.py
.py
e9605e89fcb8fc22
7.5
0
"""ทดสอบ agent/collect.py — pure parsers + snapshot ผ่าน provider.""" from __future__ import annotations import platform from agent.collect import ( check_ports, host_id, parse_meminfo, parse_net_dev, parse_uptime, snapshot, ) from agent.config import _parse_ports from shared.metric import ( ...
Witawat/monitor-server
tests/test_collect.py
.py
89510b4763894cf6
7.5
0
"""ทดสอบ server/config.py — อ่าน + validate config.toml.""" from __future__ import annotations import tomllib import pytest from pydantic import ValidationError from server.config import AppConfig, load_config VALID_TOML = """ [server] host = "127.0.0.1" port = 18080 [ingest] rate_limit_per_min = 100 max_batch_si...
Witawat/monitor-server
tests/test_config.py
.py
144eae8105e471bd
7.5
0
"""ทดสอบงานเสริม — tags, services, export CSV, host-down notify, login rate-limit, security headers.""" from __future__ import annotations import time import pytest from fastapi.testclient import TestClient from server.alerting.offline import HostDownMonitor from server.config import AppConfig from server.main impo...
Witawat/monitor-server
tests/test_extras.py
.py
783b29d493049a09
7.5
0
"""ทดสอบ server/ingest.py — validate batch + rate limit + auto-register.""" from __future__ import annotations import pytest from server.config import AppConfig from server.ingest import ( IngestService, InvalidBatch, RateLimited, UnauthorizedToken, ) from server.storage.db import Database @pytest....
Witawat/monitor-server
tests/test_ingest.py
.py
bc0db95537448357
7.5
0
"""ทดสอบ agent/push.py — PushQueue + push_batch ผ่าน fake HTTP server.""" from __future__ import annotations import json import threading from http.server import BaseHTTPRequestHandler, HTTPServer import pytest from agent.push import Backoff, PushQueue, push_batch class _Handler(BaseHTTPRequestHandler): """Fa...
Witawat/monitor-server
tests/test_push.py
.py
1d9bd0d8b3b07914
7.5
0
"""Bryant / Carrier variable-speed continuous fan speed programming via thermostat. Method (furnace control board): 1. HVAC mode OFF, fan ON — continuous fan runs 2. Within ~3s: Auto → On ×3 (three toggles) to step to the next pre-programmed speed 3. Typically ~6 discrete continuous-fan speeds (speed_1 lowest … ...
redawg/hass-sensorlinx
custom_components/sensorlinx/blower_fan_speed.py
.py
37bd978aa264811c
7
0
"""Climate platform for HBX THM thermostats.""" from __future__ import annotations import logging from typing import Any from homeassistant.components.climate import ( ClimateEntity, ClimateEntityFeature, HVACMode, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATT...
redawg/hass-sensorlinx
custom_components/sensorlinx/climate.py
.py
a5ae1df85140b25c
7
0
"""Config flow for HBX SensorLinx.""" from __future__ import annotations import logging from typing import Any import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant, callback from homeassistant.excep...
redawg/hass-sensorlinx
custom_components/sensorlinx/config_flow.py
.py
e64fe0083d3e0c3f
7
0
"""Data update coordinator for HBX SensorLinx.""" from __future__ import annotations import asyncio import logging from dataclasses import dataclass from datetime import timedelta from typing import Any from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassista...
redawg/hass-sensorlinx
custom_components/sensorlinx/coordinator.py
.py
e8316415cb18384f
7
0
"""Sync external HA switches with SensorLinx floor / hot-water state.""" from __future__ import annotations import logging from dataclasses import dataclass, field from typing import Any, Callable from homeassistant.config_entries import ConfigEntry from homeassistant.const import STATE_OFF, STATE_ON from homeassist...
redawg/hass-sensorlinx
custom_components/sensorlinx/external_control.py
.py
2a3ef368c43caa6f
7
0
"""Heating zone registry — SensorLinx THM zones plus external climate entities.""" from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING from homeassistant.core import HomeAssistant from .const import ( DEFAULT_PRIMARY_BATH_CLIMATE, DEFAULT_PRIMARY_BATH_ROOM_S...
redawg/hass-sensorlinx
custom_components/sensorlinx/heating_zones.py
.py
49a13d6f0eb190f9
7
0
"""Shared helpers for SensorLinx entities.""" from __future__ import annotations from typing import Any from .const import DOMAIN from .coordinator import SensorlinxCoordinator, SensorlinxDeviceData def thm_device_info( coordinator: SensorlinxCoordinator, device_data: SensorlinxDeviceData, ) -> dict[str, A...
redawg/hass-sensorlinx
custom_components/sensorlinx/helpers.py
.py
9c13cf705e1d86fe
7
0
"""Number platform for HBX ZON-0600 writable setpoints.""" from __future__ import annotations from typing import Any from homeassistant.components.number import NumberEntity, NumberMode from homeassistant.config_entries import ConfigEntry from homeassistant.const import UnitOfTemperature from homeassistant.core impo...
redawg/hass-sensorlinx
custom_components/sensorlinx/number.py
.py
e974c5091267d01d
7
0
"""Validate door/window openings and refresh stale contact sensors. Ecobee contact sensors can stick open while a paired August door sensor reports closed (or vice versa). For paired openings this guard: 1. Periodically calls ``homeassistant.update_entity`` on watched contacts 2. Cross-checks authority sensors when a...
redawg/hass-sensorlinx
custom_components/sensorlinx/openings_guard.py
.py
445f45c973752dfa
7
0
"""Switch platform for HBX SensorLinx devices.""" from __future__ import annotations from typing import Any from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddE...
redawg/hass-sensorlinx
custom_components/sensorlinx/switch.py
.py
2966be6ba2b9c355
7
0
#!/usr/bin/env python3 """Apply recommended zone adjustments.""" import requests BASE = "http://172.16.255.250:8123" TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJlNDM2OWE2YTVmYjk0ODIzOTFmNDA3OTdiM2NiZmFiYyIsImlhdCI6MTc3ODU0NzMyNCwiZXhwIjoyMDkzOTA3MzI0fQ.Kh_2jOBqDJnevRqvrEGnZ1E849jrRK0_-SOdr6lr2Fs" headers ...
redawg/hass-sensorlinx
scripts/apply_adjustments.py
.py
e65291f866419a9b
7
0
#!/usr/bin/env python3 """Check outdoor reset and zone status.""" import requests BASE = "http://172.16.255.250:8123" TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJlNDM2OWE2YTVmYjk0ODIzOTFmNDA3OTdiM2NiZmFiYyIsImlhdCI6MTc3ODU0NzMyNCwiZXhwIjoyMDkzOTA3MzI0fQ.Kh_2jOBqDJnevRqvrEGnZ1E849jrRK0_-SOdr6lr2Fs" headers...
redawg/hass-sensorlinx
scripts/check_reset.py
.py
58c3fbe57b8aab54
7
0
import os from flask import Blueprint, current_app, session api_bp = Blueprint("api", __name__) def _actor(): """조치 주체(로그인 사용자). 감사 로그·워치리스트 기록용.""" return session.get("user") or "system" def audit_record(action, target="", detail=""): """전역 감사 로그에 분석가 조치 1건 기록 (app.audit 없으면 무시).""" audit = getat...
MintKangaroo/AI-SOC-DashBoard
api/_common.py
.py
140e32646605ac4e
7
0
"""LSTM Autoencoder 시계열 이상탐지 (실험적 — 비활성). `modules/ml_analyst.py` 에서 이관. ## 격리 사유 1. **학습 데이터에 시간 구조가 없다.** 학습 시퀀스 400개는 각 타임스텝을 독립적으로 뽑은 uniform 난수다(`synthetic_data.generate_normal_sequences`). LSTM 오토인코더는 시간 의존성을 재구성하는 구조인데, 재구성할 시간 의존성이 데이터에 존재하지 않는다. 이 모델이 수렴해서 배우는 것은 피처별 평균이며, 그것은 `np.mean` 한 줄과 같다....
MintKangaroo/AI-SOC-DashBoard
experimental/lstm_autoencoder.py
.py
2b9adc991095c24e
7
0
"""Random Forest 6클래스 위협 분류기 (실험적 — 비활성). `modules/ml_analyst.py` 에서 이관. ## 격리 사유 1. **라벨이 없다.** 지도학습 분류기인데 전 시스템의 사람 판정 라벨이 1건이다 (`alerts.db` verdict_actor='mintkangaroo' 1건; 아카이브 110,748건은 전부 UNREVIEWED). 학습도 검증도 불가능하다. 2. **학습 분포 밖에서 자신 있게 틀린다.** 합성 6클래스는 서로 겹치지 않는 uniform 상자다. 실제 트래픽은 어느 상자에도 속하지 않지만, 랜...
MintKangaroo/AI-SOC-DashBoard
experimental/rf_classifier.py
.py
6099d8f8ac246153
7
0
"""합성 학습 데이터 생성기 (실험용). `modules/ml_analyst.py` 에서 이관. 클래스별로 **서로 겹치지 않는 uniform 구간**에서 난수를 뽑는 방식이라, 이 데이터로 학습한 분류기의 홀드아웃 성능은 모델 품질이 아니라 생성기의 분리도를 측정한다. 실제로 손으로 쓴 if문 6줄이 macro-F1 0.997 을 받는다 (`scripts/eval_ml.py` 참조). 성능 주장의 근거로 쓰지 말 것. 회귀 테스트와 형태 검증 용도로만 유지한다. """ import numpy as np FEATURE_NAMES = [ "pps", ...
MintKangaroo/AI-SOC-DashBoard
experimental/synthetic_data.py
.py
9d87493426624f72
7
0
"""Q-Learning 임계값 튜너 (실험적 — 비활성). `modules/ml_analyst.py` 에서 이관. ## 격리 사유 1. **보상에 외부 정답 신호가 없다.** 원본 `_compute_reward(result, action)` 는 `result["summary"]["threats"]` — 즉 **자신이 튜닝하는 모델들의 출력** 만 본다. 분석가 FP 피드백(`mark_alert`)이 채우는 창은 `_state_index` 의 **상태** 계산에만 쓰이고 보상에는 닿지 않는다. 결과적으로 "자기가 조정하는 대상과 얼마나 일치...
MintKangaroo/AI-SOC-DashBoard
experimental/threshold_qlearner.py
.py
27b24953dadc5c0a
7
0
"""전역 감사 로그 — 분석가 조치(알림 상태변경·차단·인시던트 갱신)를 append-only 로 기록. SOC 책임추적성·근무 인수인계의 기본. 인시던트별 타임라인과 별개로 "누가 언제 무엇을 했는가"를 한 테이블에 모아 조회한다. """ import os import sqlite3 import threading from datetime import datetime # 액션 코드 → 한글 (UI 표시·필터) ACTIONS = { "ALERT_ACK": "알림 확인(ACK)", "ALERT_CLOSE": "알림 종료(CLOSED)", ...
MintKangaroo/AI-SOC-DashBoard
modules/audit_log.py
.py
664a6a2a1f3c7773
7
0
"""구조화 로깅 설정 (docs/AUDIT.md B-9). 이전에는 전 모듈이 `print()` 119회로 상태를 알렸다. 그래서 - **시각이 없었다.** "[Syslog] 바인딩 불가"가 언제 난 건지 알 수 없다. - **레벨이 없었다.** 정상 시작 메시지와 저장 실패가 같은 무게로 섞여, 무엇을 봐야 하는지 화면만 보고는 구분되지 않았다. - **파일에 남지 않았다.** nohup 으로 띄우면 stdout 이 흘러가고, 문제가 생긴 뒤에는 원인을 되짚을 기록이 없다. - **끌 수 없었다.** 모듈별로 시끄러움을 조절할 방법이 없다. 메시지의 ...
MintKangaroo/AI-SOC-DashBoard
modules/logging_setup.py
.py
d8b4c139462c6d66
7
0
"""SOAR 플레이북 실행 이력을 보존하는 SQLite 저장소.""" import json import os import sqlite3 import threading # 정리 대상에서 **항상 제외**하는 상태. # 제외 목록으로 정의하는 이유: 새 상태값이 생겨도 기본이 '보존'이 되게 하기 위함이다. # 특히 waiting_approval 은 사람의 결정을 기다리는 항목이라 지우면 그 결정 기회가 # 사라진다(실 DB 기준 1,685건). processing_approval/running/pending 도 진행 중이다. NON_TERMINAL_STATUSES ...
MintKangaroo/AI-SOC-DashBoard
modules/soar_execution_store.py
.py
438817de11590cbe
7
0
"""Validate and read out the frozen BTF-2 deadline-router census. This is preregistration scaffolding, not an experiment result. The census was made from question text, resolution criteria, and background only. It excludes the standard Opus contamination-probe flags and the known ECB memory-claim question. PRE-REGI...
edisonymy/forecast-scaffold
bench/analysis/deadline_census.py
.py
82502c754f63087e
7
0
"""Free post-processing test: does logit-extremization p' = sigma(d * logit(p)) close the refinement gap? Honest split: fit d on the 47 tranche-1 qids, evaluate the chosen d on the 105 fresh qids only. Run for base and skeptic arms; teacher for reference.""" import json import math import statistics as st import sys i...
edisonymy/forecast-scaffold
bench/analysis/extremize_test.py
.py
db2f1c77fe42962e
7.5
0
"""Memory-claim prefilter for one or more benchmark result files. Mechanically shortlist rows whose reasoning may assert the question's outcome as remembered fact (weights leakage surfacing mid-forecast). Apply the screen uniformly to every arm, then read and judge the candidates. This is a pastcast-only artifact: a l...
edisonymy/forecast-scaffold
bench/analysis/memory_screen.py
.py
f80903e46f390f51
7
0
"""Direct OpenRouter chat transport for the bench's tool-less, single-completion calls. Some bench calls are one-shot completions with NO tools: contamination_probe.py's recall probes, and run_bench.py's "zero" tier under --leakfree none. Shelling those out to the `claude` CLI has two measured problems: 1. The CLI pr...
edisonymy/forecast-scaffold
bench/direct_agent.py
.py
6dde0d5562f55b95
7
0
"""Build a frozen "pastcasting" question set from FutureSearch's public BTF-2 dataset (Bench-to-the-Future 2, HuggingFace ``BTF-2/BTF-2``), for offline reasoning-layer eval. Unlike ``fetch_set.py``'s still-open markets, BTF-2 questions are already RESOLVED — that is the point: pastcasting freezes the agent's effective...
edisonymy/forecast-scaffold
bench/fetch_btf2.py
.py
614a0dc835770565
7
0
"""Build a frozen benchmark question set from ForecastBench's public datasets. ForecastBench (Forecasting Research Institute, CC-BY-SA 4.0) publishes ~500-question sets biweekly; the market-sourced questions (Metaculus, Manifold, Polymarket, RAND/INFER) carry ``freeze_datetime_value`` — the crowd probability at freeze...
edisonymy/forecast-scaffold
bench/fetch_set.py
.py
841cc60aae4b7c69
7
0