Initial clean release: SSE-Connector + Installer
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
# Python-Cache + Test-Cache (P-001: stale .pyc nie committen)
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.pyo
|
||||
.pytest_cache/
|
||||
.cache/
|
||||
|
||||
# Backups (install.sh legt .bak-install / .bak-<ts> an)
|
||||
*.bak*
|
||||
@@ -0,0 +1,173 @@
|
||||
# PMDB Connector Plugin
|
||||
|
||||
Profil-aware Anbindung an den PMDB MCP-Server als Hermes-Backend-Plugin
|
||||
(`kind: backend`). Liest das aktive Hermes-Profil, wählt den zugehörigen
|
||||
Bearer-Token aus der Profil-Config und registriert die `pmdb_*`-Tools im
|
||||
Toolset `pmdb`.
|
||||
|
||||
- Feature: `F454` (Plugin-Anbindung), `F621` (SSE-Stream), `F719` (Anlagen)
|
||||
- Repo: `Andreas/PMDB-Connector.git` auf Gitea (.47)
|
||||
|
||||
---
|
||||
|
||||
## Was das Plugin bietet
|
||||
|
||||
| Phase | Tools |
|
||||
|-------|-------|
|
||||
| Task-Lifecycle | `pmdb_get_tasks`, `pmdb_accept_task`, `pmdb_decline_task`, `pmdb_submit_task`, `pmdb_return_for_revision`, `pmdb_manager_decision` |
|
||||
| Query + Management | `pmdb_get_mask`, `pmdb_search`, `pmdb_get_baustein`, `pmdb_get_pipeline_status`, `pmdb_get_task_evidence` |
|
||||
| Manager-only | `pmdb_set_bit`, `pmdb_create_task`, `pmdb_get_submitted_tasks`, `pmdb_manager_dashboard`, `pmdb_submit_on_behalf` |
|
||||
| Task-Anlagen (F719) | `pmdb_get_anlagen`, `pmdb_download_anlage`, `pmdb_upload_ergebnis_anlage`, `pmdb_upload_anlage` |
|
||||
| Diagnose | `pmdb_stream_status` |
|
||||
|
||||
Manager-only-Tools sind doppelt abgesichert (Plugin-Guard *und* Server-
|
||||
Rollen-Check, F453).
|
||||
|
||||
---
|
||||
|
||||
## Voraussetzungen
|
||||
|
||||
- Hermes-Instanz mit aktivem Profil
|
||||
- `python3` mit `PyYAML` (das Plugin importiert `yaml` in `config.py`)
|
||||
- Ein PMDB-Bearer-Token für den Agenten (generiert auf `.49`)
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
./install.sh
|
||||
```
|
||||
|
||||
Interaktiv werden abgefragt:
|
||||
|
||||
1. **Agent-/Profil-Name** (Default: automatisch aus `HERMES_HOME` erkannt)
|
||||
2. **PMDB-Bearer-Token** (verdeckte Eingabe)
|
||||
3. **PMDB MCP `base_url`** (Default `https://pmdb.myowntools.org/mcp`)
|
||||
|
||||
Nicht-interaktiv (für Automatisierung/CI):
|
||||
|
||||
```bash
|
||||
./install.sh \
|
||||
--agent miguel \
|
||||
--token 'mcp_miguel_...' \
|
||||
--api-url 'http://pmdb.myowntools.org' \
|
||||
--yes
|
||||
```
|
||||
|
||||
Alle Optionen:
|
||||
|
||||
```
|
||||
--agent <name> Agent-/Profil-Name
|
||||
--token <token> PMDB-Bearer-Token
|
||||
--api-url <url> PMDB MCP base_url (Default: https://pmdb.myowntools.org/mcp)
|
||||
--source <dir> Quellverzeichnis der Plugin-Dateien
|
||||
--skip-curl curl-Verbindungstest überspringen
|
||||
--yes, -y nicht-interaktiv
|
||||
--help, -h Hilfe
|
||||
```
|
||||
|
||||
### Was `install.sh` tut
|
||||
|
||||
1. Kopiert `__init__.py`, `client.py`, `config.py`, `plugin.yaml` (+ `tests/`)
|
||||
nach `~/.hermes/profiles/<agent>/plugins/pmdb_connector/`.
|
||||
2. Entfernt stale `__pycache__`/`.pyc` (P-001).
|
||||
3. Schreibt den Token in **zwei** Quellen:
|
||||
- `~/.hermes/mcp_tokens.json` → `agenten.<agent>.token` (kanonisch, F590)
|
||||
- `~/.hermes/profiles/<agent>/config.yaml` → `pmdb_connector.auth_keys.<agent>` (Fallback, F526)
|
||||
4. Legt vor jedem Schreibvorgang ein Backup an (`.bak-install`).
|
||||
5. Testet die Verbindung per `curl` gegen `GET <base_url>/mcp/api/tasks`.
|
||||
|
||||
---
|
||||
|
||||
## Token-Quellen (Auflösungsreihenfolge)
|
||||
|
||||
Die KANONISCHE Quelle ist `mcp_tokens.json` (F590, Single Source of Truth).
|
||||
`config.yaml`-`auth_keys` ist nur Fallback (Backward-Compat).
|
||||
|
||||
```
|
||||
resolve_token(profile):
|
||||
1. mcp_tokens.json agenten[<profile>].token <- kanonisch
|
||||
2. config.yaml pmdb_connector.auth_keys[<profile>]
|
||||
3. config.yaml pmdb_connector.auth_keys["default"]
|
||||
4. Basis-Config ~/.hermes/config.yaml
|
||||
5. Profil-Config ~/.hermes/profiles/<profile>/config.yaml
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Konfigurations-Referenz (`pmdb_connector`-Sektion)
|
||||
|
||||
```yaml
|
||||
pmdb_connector:
|
||||
base_url: "http://pmdb.myowntools.org" # PMDB MCP base_url (OHNE /mcp!)
|
||||
auth_keys: # Fallback-Tokens (F526)
|
||||
default: "mcp_bernd_..."
|
||||
miguel: "mcp_miguel_..."
|
||||
rainer: "mcp_rainer_..."
|
||||
manager_profiles: [bernd, andreas] # Manager-only-Tools (F453)
|
||||
stream_enabled: false # SSE-Listener (F621, opt-in, Default aus)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ base_url-Falle (doppeltes `/mcp`)
|
||||
|
||||
Der Client hängt **selbst** `/mcp/api/...` an `base_url` an
|
||||
(`client.py` → `self.base_url + "/mcp/api/tasks"`). Deshalb darf `base_url`
|
||||
**kein** abschließendes `/mcp` enthalten:
|
||||
|
||||
| `base_url` | effektiver get_tasks-Aufruf | Ergebnis |
|
||||
|------------|-----------------------------|----------|
|
||||
| `https://pmdb.myowntools.org` | `.../mcp/api/tasks` | ✅ 200 |
|
||||
| `http://pmdb.myowntools.org` (intern) | `.../mcp/api/tasks` | ✅ 200 |
|
||||
| `https://pmdb.myowntools.org/mcp` (Default) | `.../mcp/mcp/api/tasks` | ❌ 404 |
|
||||
|
||||
Zusätzlich blockt der Openresty-Proxy (`pmdb.myowntools.org`) Bearer-Tokens
|
||||
mit HTTP 401 (P-NEW-F563-PMDB-AUTH). **Empfehlung:** intern
|
||||
`http://pmdb.myowntools.org` verwenden. `install.sh` warnt bei einem
|
||||
curl-404 explizit vor dieser Falle.
|
||||
|
||||
---
|
||||
|
||||
## Tests
|
||||
|
||||
Unit-Tests (stdlib-only, laufen überall, kein Netzwerk):
|
||||
|
||||
```bash
|
||||
cd tests
|
||||
python3 -m pytest -q
|
||||
```
|
||||
|
||||
Integration-Tests (gegen Live-PMDB auf `.49`) werden nur mit
|
||||
`PMDB_TEST_TOKEN` aktiviert:
|
||||
|
||||
```bash
|
||||
PMDB_TEST_TOKEN='mcp_...' PMDB_TEST_BASE='http://pmdb.myowntools.org' \
|
||||
python3 -m pytest -q
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Datei-Layout
|
||||
|
||||
```
|
||||
pmdb_connector/
|
||||
├── install.sh # Installer (diese Anleitung)
|
||||
├── README.md
|
||||
├── __init__.py # Tool-Registrierung + Handler (F454, F621, F719)
|
||||
├── client.py # stdlib-only HTTP-Client (F454, F727)
|
||||
├── config.py # Profil-Config + Token-Auflösung (F454, F590)
|
||||
├── plugin.yaml # Plugin-Metadaten (kind: backend)
|
||||
└── tests/
|
||||
└── test_plugin.py # Unit- + Integration-Tests
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pitfalls-Referenz
|
||||
|
||||
- **P-001** stale `__pycache__` → `install.sh` räumt vor/nach Deploy auf.
|
||||
- **P-NEW-F563-PMDB-AUTH** Proxy blockt Bearer-Tokens (401) → intern `.49:8099`.
|
||||
- **P-191** Token nie in Logs/Responses (nur maskierter Prefix).
|
||||
- **F590** `mcp_tokens.json` ist kanonisch → verhindert Token-Drift.
|
||||
+693
@@ -0,0 +1,693 @@
|
||||
"""F454 PMDB Connector Plugin — Hermes Backend-Plugin (kind: backend).
|
||||
|
||||
@implements: [F454]
|
||||
@implements: [F-621]
|
||||
@implements: [F-719]
|
||||
|
||||
Profil-aware Anbindung an den PMDB MCP-Server (https://pmdb.myowntools.org/mcp).
|
||||
Liest das aktive Hermes-Profil (V1 Option A: 1:1 = PMDB-Agent-Name), waehlt den
|
||||
zugehoerigen Bearer-Token aus der Profile-Config (V2 Stufe 1 Plaintext) und
|
||||
registriert die pmdb-*-Tools im Toolset "pmdb".
|
||||
|
||||
Tools (Rainers Architektur §2.7):
|
||||
Phase 1 (Task-Lifecycle):
|
||||
pmdb_get_tasks() — eigene Tasks (F455 Hybrid-Anzeige)
|
||||
pmdb_accept_task(task_id) — akzeptieren
|
||||
pmdb_decline_task(task_id, reason) — ablehnen
|
||||
pmdb_submit_task(task_id, result) — Ergebnis einreichen (ReturnValue)
|
||||
Phase 2 (Query + Management):
|
||||
pmdb_get_mask(feature_id) — EK-Stand als Bit-Kette
|
||||
pmdb_search(type, query) — PMDB durchsuchen
|
||||
pmdb_get_baustein(baustein_id) — Baustein-Detail
|
||||
pmdb_set_bit(feature_id, bit_nr) — Bit setzen (Manager-only)
|
||||
pmdb_create_task(...) — Task erstellen (Manager-only)
|
||||
|
||||
Pull-on-Start (Option 1): KEIN Auto-Pull. Der Agent ruft pmdb_get_tasks()
|
||||
explizit auf, wenn er arbeiten will (Andreas 10.09.: "Pull on Start").
|
||||
|
||||
Manager-only-Check (Defense-in-Depth): pmdb_set_bit + pmdb_create_task pruefen
|
||||
`get_active_profile_name() in manager_profiles`. Der F449-Server hat einen
|
||||
ZUSAETZLICHEN Rollen-Check (F453, P-218-Schutz).
|
||||
|
||||
Fehlender Token -> Plugin registriert sich mit WARNING und deaktiviert alle
|
||||
Tools (Handler returnt strukturierten token_missing-Error).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
from . import config as pmdb_config
|
||||
from .client import PMDBClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TOOLSET = "pmdb"
|
||||
EMOJI = "\U0001F4CB" # 📋
|
||||
|
||||
# Manager-only-Tools (Defense-in-Depth, Rainers Architektur §2.7).
|
||||
_MANAGER_ONLY = {"pmdb_set_bit", "pmdb_create_task", "pmdb_get_submitted_tasks", "pmdb_manager_dashboard"}
|
||||
|
||||
|
||||
def _str(description: str) -> dict:
|
||||
return {"type": "string", "description": description}
|
||||
|
||||
|
||||
def _int(description: str) -> dict:
|
||||
return {"type": "integer", "description": description}
|
||||
|
||||
|
||||
def _obj(description: str) -> dict:
|
||||
return {"type": "object", "description": description}
|
||||
|
||||
|
||||
def _downloads_dir(profile: str) -> str:
|
||||
"""F-719: Default-Zielverzeichnis fuer Anlagen-Downloads (pro Profil).
|
||||
|
||||
Analog zur Config-Pfad-Aufloesung (P-119/P-147): HERMES_HOME kann auf ein
|
||||
Profil- oder Basis-Verzeichnis zeigen. Downloads landen unter
|
||||
``<profil>/downloads`` und werden nicht automatisch geraeumt (stabiler
|
||||
Ablageort fuer den Agenten, kein Temp-File).
|
||||
"""
|
||||
home = os.environ.get("HERMES_HOME")
|
||||
if home:
|
||||
base = Path(home)
|
||||
if base.parent.name == "profiles":
|
||||
return str(base / "downloads")
|
||||
return str(base / "profiles" / profile / "downloads")
|
||||
return str(Path.home() / ".hermes" / "profiles" / profile / "downloads")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tool-Handler (sync — HTTP via urllib, kein asyncio noetig)
|
||||
# ---------------------------------------------------------------------------
|
||||
def _make_handlers(client: PMDBClient, profile: str, managers: list) -> dict:
|
||||
"""Baut die Handler-Dicts. Jeder Handler liefert einen JSON-String.
|
||||
|
||||
Hermes Tool-Framework erwartet einen serialisierten Return-Typ (str),
|
||||
kein rohes dict — sonst crasht der Tool-Handler mit
|
||||
``Tool handler returned unsupported result type: dict``.
|
||||
"""
|
||||
|
||||
def _dump(result: dict) -> str:
|
||||
return json.dumps(result, ensure_ascii=False)
|
||||
|
||||
def _guard_manager() -> Optional[dict]:
|
||||
# Case-insensitive (P-194: Profil-/Agent-Namen sind case-inkonsistent).
|
||||
if profile.lower() not in managers:
|
||||
return {
|
||||
"success": False,
|
||||
"error_code": "forbidden",
|
||||
"error": f"Profil '{profile}' ist kein Manager. Nur Manager "
|
||||
f"duerfen diese Aktion ausfuehren.",
|
||||
"action": "contact_manager",
|
||||
}
|
||||
return None
|
||||
|
||||
def get_tasks(args: dict, **kw) -> str:
|
||||
return _dump(client.get_tasks())
|
||||
|
||||
def get_submitted_tasks(args: dict, **kw) -> str:
|
||||
guard = _guard_manager()
|
||||
if guard:
|
||||
return _dump(guard)
|
||||
return _dump(client.get_submitted_tasks())
|
||||
|
||||
def manager_dashboard(args: dict, **kw) -> str:
|
||||
guard = _guard_manager()
|
||||
if guard:
|
||||
return _dump(guard)
|
||||
return _dump(client.manager_dashboard())
|
||||
|
||||
def accept_task(args: dict, **kw) -> str:
|
||||
return _dump(client.accept_task(args.get("task_id")))
|
||||
|
||||
def decline_task(args: dict, **kw) -> str:
|
||||
return _dump(client.decline_task(args.get("task_id"),
|
||||
args.get("reason", "")))
|
||||
|
||||
def submit_task(args: dict, **kw) -> str:
|
||||
return _dump(client.submit_task(args.get("task_id"),
|
||||
args.get("result", {})))
|
||||
|
||||
def get_mask(args: dict, **kw) -> str:
|
||||
return _dump(client.get_mask(args.get("feature_id")))
|
||||
|
||||
def search(args: dict, **kw) -> str:
|
||||
return _dump(client.search(
|
||||
projekt=args.get("projekt"),
|
||||
ziel=args.get("ziel"),
|
||||
funktionsbereich=args.get("funktionsbereich"),
|
||||
feature=args.get("feature"),
|
||||
))
|
||||
|
||||
def get_baustein(args: dict, **kw) -> str:
|
||||
return _dump(client.get_baustein(args.get("baustein_id")))
|
||||
|
||||
def set_bit(args: dict, **kw) -> str:
|
||||
guard = _guard_manager()
|
||||
if guard:
|
||||
return _dump(guard)
|
||||
return _dump(client.set_bit(
|
||||
args.get("feature_id"),
|
||||
args.get("bit_nr"),
|
||||
args.get("begruendung"),
|
||||
artefakt_typ=args.get("artefakt_typ"),
|
||||
artefakt_inhalt=args.get("artefakt_inhalt"),
|
||||
artefakt_titel=args.get("artefakt_titel"),
|
||||
artefakte=args.get("artefakte"),
|
||||
))
|
||||
|
||||
def create_task(args: dict, **kw) -> str:
|
||||
guard = _guard_manager()
|
||||
if guard:
|
||||
return _dump(guard)
|
||||
return _dump(client.create_task(
|
||||
agent=args.get("agent"),
|
||||
feature_id=args.get("feature_id"),
|
||||
baustein_id=args.get("baustein_id"),
|
||||
pitch=args.get("pitch", ""),
|
||||
frist=args.get("frist"),
|
||||
))
|
||||
|
||||
def get_pipeline_status(args: dict, **kw) -> str:
|
||||
return _dump(client.get_pipeline_status(
|
||||
projekt_id=args.get("projekt_id"),
|
||||
feature_status_filter=args.get("feature_status_filter"),
|
||||
include_terminal=bool(args.get("include_terminal", False)),
|
||||
))
|
||||
|
||||
def submit_on_behalf(args: dict, **kw) -> str:
|
||||
guard = _guard_manager()
|
||||
if guard:
|
||||
return _dump(guard)
|
||||
return _dump(client.submit_on_behalf(
|
||||
task_id=args.get("task_id"),
|
||||
agent_name=args.get("agent_name"),
|
||||
payload=args.get("result", {}),
|
||||
))
|
||||
|
||||
def get_task_evidence(args: dict, **kw) -> str:
|
||||
return _dump(client.get_task_evidence(
|
||||
task_id=args.get("task_id"),
|
||||
include_sources=args.get("include_sources"),
|
||||
))
|
||||
|
||||
def return_for_revision(args: dict, **kw) -> str:
|
||||
# F-705: QG-Rueckdelegation. KEIN Plugin-Level-Guard — der Server
|
||||
# prueft die QG-/Manager-Rolle + Separation of Duties (P-218).
|
||||
return _dump(client.return_for_revision(
|
||||
task_id=args.get("task_id"),
|
||||
reason=args.get("reason", ""),
|
||||
auflagen=args.get("auflagen"),
|
||||
zusammenfassung=args.get("zusammenfassung"),
|
||||
))
|
||||
|
||||
def manager_decision(args: dict, **kw) -> str:
|
||||
guard = _guard_manager()
|
||||
if guard:
|
||||
return _dump(guard)
|
||||
return _dump(client.manager_decision(
|
||||
task_id=args.get("task_id"),
|
||||
entscheidung=args.get("entscheidung"),
|
||||
begruendung=args.get("begruendung", ""),
|
||||
auflagen=args.get("auflagen"),
|
||||
timebox_runden=args.get("timebox_runden"),
|
||||
ziel_architektur_notiz=args.get("ziel_architektur_notiz"),
|
||||
auftraggeber_zusammenfassung=args.get("auftraggeber_zusammenfassung"),
|
||||
))
|
||||
|
||||
def stream_status(args: dict, **kw) -> str:
|
||||
# F-621: Listener-Status (enabled/running/connected/event_count).
|
||||
return _dump(_stream_status())
|
||||
|
||||
def get_anlagen(args: dict, **kw) -> str:
|
||||
# F-719: Anlagen eines Tasks auflisten (Owner ODER Manager).
|
||||
return _dump(client.get_anlagen(args.get("task_id")))
|
||||
|
||||
def download_anlage(args: dict, **kw) -> str:
|
||||
# F-719: Binär-Download — Bytes auf Platte schreiben, sha256 client-seitig.
|
||||
task_id = args.get("task_id")
|
||||
att_id = args.get("att_id")
|
||||
ziel_pfad = args.get("ziel_pfad")
|
||||
result = client.download_anlage(task_id, att_id)
|
||||
if isinstance(result, dict):
|
||||
return _dump(result) # strukturierter Fehler (P-191)
|
||||
meta = getattr(client, "_last_download", {}) or {}
|
||||
filename = meta.get("filename") or f"anlage_{att_id}"
|
||||
if not ziel_pfad:
|
||||
ziel_pfad = os.path.join(_downloads_dir(profile), filename)
|
||||
ziel_dir = os.path.dirname(ziel_pfad)
|
||||
if ziel_dir:
|
||||
os.makedirs(ziel_dir, exist_ok=True)
|
||||
try:
|
||||
with open(ziel_pfad, "wb") as fh:
|
||||
fh.write(result)
|
||||
except OSError as exc:
|
||||
return _dump({
|
||||
"success": False, "error_code": "write_error",
|
||||
"error": f"Download konnte nicht gespeichert werden: {exc}",
|
||||
"ziel_pfad": ziel_pfad,
|
||||
})
|
||||
return _dump({
|
||||
"success": True,
|
||||
"saved_path": ziel_pfad,
|
||||
"filename": filename,
|
||||
"sha256": hashlib.sha256(result).hexdigest(),
|
||||
"groesse_bytes": len(result),
|
||||
"content_type": meta.get("content_type", ""),
|
||||
})
|
||||
|
||||
def upload_anlage(args: dict, **kw) -> str:
|
||||
# F-719: Eingang-Anlage (Manager-only, Defense-in-Depth).
|
||||
guard = _guard_manager()
|
||||
if guard:
|
||||
return _dump(guard)
|
||||
return _dump(client.upload_anlage(
|
||||
args.get("task_id"), args.get("file_path"), args.get("mime_type")))
|
||||
|
||||
def upload_ergebnis_anlage(args: dict, **kw) -> str:
|
||||
# F-719: Ergebnis-Anlage (Owner-only, KEIN Plugin-Guard — Server prueft).
|
||||
return _dump(client.upload_ergebnis_anlage(
|
||||
args.get("task_id"), args.get("file_path"), args.get("mime_type")))
|
||||
|
||||
return {
|
||||
"pmdb_get_tasks": get_tasks,
|
||||
"pmdb_get_submitted_tasks": get_submitted_tasks,
|
||||
"pmdb_manager_dashboard": manager_dashboard,
|
||||
"pmdb_accept_task": accept_task,
|
||||
"pmdb_decline_task": decline_task,
|
||||
"pmdb_submit_task": submit_task,
|
||||
"pmdb_get_mask": get_mask,
|
||||
"pmdb_search": search,
|
||||
"pmdb_get_baustein": get_baustein,
|
||||
"pmdb_set_bit": set_bit,
|
||||
"pmdb_create_task": create_task,
|
||||
"pmdb_get_pipeline_status": get_pipeline_status,
|
||||
"pmdb_submit_on_behalf": submit_on_behalf,
|
||||
"pmdb_get_task_evidence": get_task_evidence,
|
||||
"pmdb_return_for_revision": return_for_revision,
|
||||
"pmdb_manager_decision": manager_decision,
|
||||
"pmdb_stream_status": stream_status,
|
||||
"pmdb_get_anlagen": get_anlagen,
|
||||
"pmdb_download_anlage": download_anlage,
|
||||
"pmdb_upload_ergebnis_anlage": upload_ergebnis_anlage,
|
||||
"pmdb_upload_anlage": upload_anlage,
|
||||
}
|
||||
|
||||
|
||||
# Tool-Schemas (name, description, properties, required)
|
||||
_TOOLS: dict[str, tuple[str, dict, list]] = {
|
||||
"pmdb_get_tasks": (
|
||||
"Eigene PMDB-Auftraege abrufen (F455 Hybrid-Anzeige: freie Tasks als "
|
||||
"Liste, blockierte als Counter). Kein Input — die Agent-Identitaet wird "
|
||||
"aus dem Bearer-Token abgeleitet.",
|
||||
{}, [],
|
||||
),
|
||||
"pmdb_get_submitted_tasks": (
|
||||
"Submitted PMDB-Tasks abrufen (Manager-only). Zeigt alle Tasks, "
|
||||
"die auf Manager-Entscheidung warten, inkl. unblocks (F455-DAG).",
|
||||
{}, [],
|
||||
),
|
||||
"pmdb_manager_dashboard": (
|
||||
"Manager-Dashboard (Manager-only). Ein einziger Call liefert die vier "
|
||||
"Bereiche: offene Fragen (diskussionsbedarf), ausstehende Freigaben, "
|
||||
"eingereichte Tasks (mit Feature, ohne Test-Muell) und Wuensche/Change "
|
||||
"Requests — je mit Klarschrift-Name + klickbarer Setcard-URL.",
|
||||
{}, [],
|
||||
),
|
||||
"pmdb_accept_task": (
|
||||
"Einen PMDB-Task akzeptieren (status pitched -> accepted).",
|
||||
{"task_id": _str("ID des Tasks (z.B. 42 oder 'T-042')")}, ["task_id"],
|
||||
),
|
||||
"pmdb_decline_task": (
|
||||
"Einen PMDB-Task ablehnen (status pitched -> declined, mit Grund).",
|
||||
{"task_id": _str("ID des Tasks"),
|
||||
"reason": _str("Ablehnungsgrund (kurz)")}, ["task_id"],
|
||||
),
|
||||
"pmdb_submit_task": (
|
||||
"Ergebnis eines PMDB-Tasks einreichen (ReturnValue-Payload, "
|
||||
"status -> submitted). F522: Wenn der Task-Baustein ein Pflicht-Bit "
|
||||
"hat (Bits 5-10, 15-17), MUSS der result-Payload einen Beleg "
|
||||
"mitsenden: entweder result.artefakte als Liste von "
|
||||
"{artefakt_typ, artefakt_inhalt, artefakt_titel} ODER die Einzelfelder "
|
||||
"artefakt_typ/artefakt_inhalt/artefakt_titel. Fehlt der Beleg -> 422.",
|
||||
{"task_id": _str("ID des Tasks"),
|
||||
"result": _obj("Ergebnis-Payload (ReturnValue-Struktur). "
|
||||
"Optional: artefakte / artefakt_typ / artefakt_inhalt / "
|
||||
"artefakt_titel (Pflicht fuer Bits 5-10, 15-17).")},
|
||||
["task_id", "result"],
|
||||
),
|
||||
"pmdb_get_mask": (
|
||||
"EK-Stand eines Features als visuelle Bit-Kette (17 Bits).",
|
||||
{"feature_id": _str("Feature-ID oder F-Nummer (z.B. 'F454' oder '454')")},
|
||||
["feature_id"],
|
||||
),
|
||||
"pmdb_search": (
|
||||
"PMDB durchsuchen (Projekt/Ziel/Funktionsbereich/Feature, AND-verknuepft).",
|
||||
{"projekt": _str("Projekt-Name (optional)"),
|
||||
"ziel": _str("Strategisches Ziel (optional)"),
|
||||
"funktionsbereich": _str("Funktionsbereich (optional)"),
|
||||
"feature": _str("Feature-Name oder F-Nummer (optional)")},
|
||||
[],
|
||||
),
|
||||
"pmdb_get_baustein": (
|
||||
"Baustein-Detail (Get/ReturnValue/Ausfuehrung + MCP-Funktionen).",
|
||||
{"baustein_id": _int("Baustein-ID")}, ["baustein_id"],
|
||||
),
|
||||
"pmdb_set_bit": (
|
||||
"Bit eines Features setzen (Manager-only). Braucht B8 Bearer-Endpoint. "
|
||||
"F183: Pflicht-Bits (z.B. Bit 6=Implementierung) brauchen einen Beleg "
|
||||
"via artefakt_typ/artefakt_inhalt/artefakt_titel (oder artefakte-Liste).",
|
||||
{"feature_id": _int("Feature-ID"),
|
||||
"bit_nr": _int("Bit-Nummer (1-17)"),
|
||||
"begruendung": _str("Begruendung (optional)"),
|
||||
"artefakt_typ": _str("Artefakt-Typ (commit/vault_pfad/url/datei/setcard/review)"),
|
||||
"artefakt_inhalt": _str("Beleg-Inhalt (Commit-Hash, Pfad, URL, ...)"),
|
||||
"artefakt_titel": _str("Anzeige-Titel des Belegs"),
|
||||
"artefakte": _obj("Liste von {artefakt_typ, artefakt_inhalt, artefakt_titel} fuer 1:N")},
|
||||
["feature_id", "bit_nr"],
|
||||
),
|
||||
"pmdb_create_task": (
|
||||
"Neuen PMDB-Task erstellen (Manager-only).",
|
||||
{"agent": _str("Ziel-Agent (PMDB-Agent-Name)"),
|
||||
"feature_id": _int("Feature-ID"),
|
||||
"baustein_id": _int("Baustein-ID"),
|
||||
"pitch": _str("Auftragsbeschreibung (Pitch)"),
|
||||
"frist": _str("Frist (ISO8601, optional)")},
|
||||
["agent", "feature_id", "baustein_id", "pitch"],
|
||||
),
|
||||
"pmdb_get_pipeline_status": (
|
||||
"Manager Pipeline-Overview (F523): alle Features mit Bit-Stand, "
|
||||
"pending Tasks und naechsten Schritten in EINEM Aufruf. Read-only. "
|
||||
"Optional: projekt_id, feature_status_filter (csv, default "
|
||||
"pitched,accepted), include_terminal (default false).",
|
||||
{"projekt_id": _int("Projekt-ID (optional, filtert auf ein Projekt)"),
|
||||
"feature_status_filter": _str("CSV Task-Status-Filter (optional)"),
|
||||
"include_terminal": _obj("Terminal-Bits 16/17 einbeziehen (optional)")},
|
||||
[],
|
||||
),
|
||||
"pmdb_submit_on_behalf": (
|
||||
"Task fuer einen anderen Agenten einreichen (Manager-only, F525). "
|
||||
"Der Manager (Executer) submittet den Task des on_behalf-Agenten. "
|
||||
"Audit-Trail via submitted_by/on_behalf_of. F522: Pflicht-Bits brauchen "
|
||||
"einen Beleg im result-Payload (artefakte/artefakt_typ/inhalt/titel).",
|
||||
{"task_id": _str("ID des Tasks"),
|
||||
"agent_name": _str("Ziel-Agent (wem der Task gehoert)"),
|
||||
"result": _obj("Ergebnis-Payload (ReturnValue-Struktur, inkl. Beleg)")},
|
||||
["task_id", "agent_name", "result"],
|
||||
),
|
||||
"pmdb_get_task_evidence": (
|
||||
"Evidence-Collection fuer QG (F528): sammelt alle Beweise zu einem "
|
||||
"Task strukturiert (pytest-Logs, Migration-Status, Deploy-Verifikation, "
|
||||
"Git-Log, Spike-Logs, Artefakte). Read-only. Optional: include_sources "
|
||||
"(csv, default alle). data_quality='high'/'partial'.",
|
||||
{"task_id": _str("ID des Tasks"),
|
||||
"include_sources": _str("CSV Quellen-Filter (optional)")},
|
||||
["task_id"],
|
||||
),
|
||||
"pmdb_return_for_revision": (
|
||||
"QG-Rueckdelegation mit Auflagen (F-705). QG-/Manager-Rolle: einen "
|
||||
"submitted Task zur Nacharbeit zurueckgeben. Auflagen sind bei einem "
|
||||
"QG-Call Pflicht (Ebene-Pflicht: backend/frontend/belege/dokumentation, "
|
||||
"bei backend/frontend zusaetzlich ort). zusammenfassung ist Pflicht, "
|
||||
"wenn der Call die Eskalation ausloest (ab der 3. Rueckdelegation).",
|
||||
{"task_id": _str("ID des Tasks"),
|
||||
"reason": _str("Korrekturanweisung (Grund)"),
|
||||
"auflagen": _obj("Liste von {nr, text, ebene, ort?, verifikation?, "
|
||||
"zustaendig?} — Pflicht bei QG-Call"),
|
||||
"zusammenfassung": _str("Gesamtdarstellung aller Runden (Pflicht bei "
|
||||
"Eskalation)")},
|
||||
["task_id"],
|
||||
),
|
||||
"pmdb_manager_decision": (
|
||||
"Manager-Entscheidung fuer ein offenes Eskalations-Fenster (F-705, "
|
||||
"Manager-only). entscheidung a/b/c/d: a=weiter (Auflagen + Re-Review), "
|
||||
"b=Architektur, c=Auftraggeber-Eskalation, d=pausieren. begruendung "
|
||||
"Pflicht; auflagen+timebox_runden bei a; auftraggeber_zusammenfassung "
|
||||
"bei c.",
|
||||
{"task_id": _str("ID des eskalierten Tasks"),
|
||||
"entscheidung": _str("a/b/c/d"),
|
||||
"begruendung": _str("Begruendung (Pflicht)"),
|
||||
"auflagen": _obj("Liste (Pflicht bei a)"),
|
||||
"timebox_runden": _obj("Ganzzahl (bei a, Default 1)"),
|
||||
"ziel_architektur_notiz": _str("bei b"),
|
||||
"auftraggeber_zusammenfassung": _str("Pflicht bei c")},
|
||||
["task_id", "entscheidung"],
|
||||
),
|
||||
"pmdb_stream_status": (
|
||||
"Status des SSE-Task-Dispatch-Listeners (F621 Stufe 1). Liefert "
|
||||
"enabled/running/connected/event_count/last_event/last_error — "
|
||||
"Read-only, fuer Diagnose und Verifikation des Streams.",
|
||||
{}, [],
|
||||
),
|
||||
"pmdb_get_anlagen": (
|
||||
"Anlagen eines Tasks auflisten (F-719, Owner ODER Manager). Liefert "
|
||||
"alle Attachments beider Richtungen (eingang/ergebnis) mit id, name, "
|
||||
"mime_type (Tag: pdf/png/jpeg/txt/csv/md), groesse_bytes, sha256, "
|
||||
"richtung, hochgeladen_von, upload_am. Read-only.",
|
||||
{"task_id": _str("ID des Tasks")}, ["task_id"],
|
||||
),
|
||||
"pmdb_download_anlage": (
|
||||
"Eine Anlage herunterladen (F-719, Owner ODER Manager). Binaer-Download: "
|
||||
"schreibt die Datei auf Platte und liefert saved_path + sha256 + "
|
||||
"groesse_bytes (client-seitig berechnet, zur Integritaets-Pruefung "
|
||||
"gegen den Server-Beleg). Optional ziel_pfad; Default ist "
|
||||
"<profil>/downloads/<dateiname>.",
|
||||
{"task_id": _str("ID des Tasks"),
|
||||
"att_id": _str("Anlagen-ID (UUID)"),
|
||||
"ziel_pfad": _str("Zieldatei-Pfad (optional)")},
|
||||
["task_id", "att_id"],
|
||||
),
|
||||
"pmdb_upload_ergebnis_anlage": (
|
||||
"Ergebnis-Anlage hochladen (F-719, Owner-Agent). Multipart-Upload einer "
|
||||
"Datei als Ergebnis-Anlage zu einem submitted Task. sha256 + mime-Tag "
|
||||
"werden server-seitig bestimmt (Magic/Endung); erlaubte Typen: "
|
||||
"pdf/png/jpeg/txt/csv/md. Nur nach submit (Status-Guard).",
|
||||
{"task_id": _str("ID des Tasks"),
|
||||
"file_path": _str("Lokaler Pfad der Datei"),
|
||||
"mime_type": _str("MIME-Typ (optional, server-seitig ueberschrieben)")},
|
||||
["task_id", "file_path"],
|
||||
),
|
||||
"pmdb_upload_anlage": (
|
||||
"Eingang-Anlage hochladen (F-719, Manager-only). Multipart-Upload einer "
|
||||
"Datei als Eingang-Anlage zu einem pitched Task. Gleiche Mechanik wie "
|
||||
"pmdb_upload_ergebnis_anlage, anderer Endpunkt. Nur vor dem Dispatch "
|
||||
"(Status-Guard: pitched).",
|
||||
{"task_id": _str("ID des Tasks"),
|
||||
"file_path": _str("Lokaler Pfad der Datei"),
|
||||
"mime_type": _str("MIME-Typ (optional, server-seitig ueberschrieben)")},
|
||||
["task_id", "file_path"],
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# F-621: SSE-Task-Dispatch-Stream-Listener (Stufe 1, opt-in)
|
||||
# ---------------------------------------------------------------------------
|
||||
# Modul-Level-State fuer Diagnose/Observability (pmdb_stream_status-Tool).
|
||||
_stream_state: dict = {
|
||||
"enabled": False,
|
||||
"running": False,
|
||||
"profile": None,
|
||||
"connected": False,
|
||||
"event_count": 0,
|
||||
"last_event": None,
|
||||
"last_error": None,
|
||||
}
|
||||
|
||||
|
||||
def _start_stream_listener(client: PMDBClient, profile: str) -> dict:
|
||||
"""F-621 Stufe 1: startet einen daemon SSE-Listener-Thread.
|
||||
|
||||
Der Thread haelt eine persistente SSE-Verbindung zum Task-Dispatch-Stream
|
||||
(client.stream_tasks) und verarbeitet task.dispatched-Events. Reconnect
|
||||
mit exponentiellem Backoff (1s/4s/16s/60s). Der Listener ist best-effort:
|
||||
ein Stream-Fehler blockt nie das Plugin; das Polling (pmdb_get_tasks)
|
||||
bleibt als Sicherheitsnetz aktiv (Stufe 1).
|
||||
|
||||
KEIN Set-Bit-Trigger (A1): der Stream loest NUR Task-Lifecycle aus
|
||||
(get_tasks + accept_task via _handle_stream_event), niemals ein
|
||||
pmdb_set_bit. Liefert das stop_event fuer spaetere Stufen (graceful
|
||||
shutdown).
|
||||
"""
|
||||
import threading
|
||||
|
||||
stop_event = threading.Event()
|
||||
_stream_state.update({
|
||||
"enabled": True, "running": True, "profile": profile,
|
||||
"connected": False, "event_count": 0, "last_event": None,
|
||||
"last_error": None,
|
||||
})
|
||||
|
||||
backoff = [1, 4, 16, 60]
|
||||
|
||||
def _run():
|
||||
idx = 0
|
||||
while not stop_event.is_set():
|
||||
try:
|
||||
_stream_state["connected"] = True
|
||||
for ev in client.stream_tasks(profile):
|
||||
if stop_event.is_set():
|
||||
break
|
||||
_handle_stream_event(client, profile, ev)
|
||||
# Stream sauber beendet -> kurz warten, dann reconnect.
|
||||
_stream_state["connected"] = False
|
||||
idx = 0
|
||||
except Exception as exc: # noqa: BLE001 — reconnect
|
||||
_stream_state["connected"] = False
|
||||
_stream_state["last_error"] = f"{type(exc).__name__}: {exc}"
|
||||
logger.warning(
|
||||
"pmdb_connector: Stream-Listener fuer '%s' abgebrochen "
|
||||
"(%s) — Reconnect in %ss", profile,
|
||||
type(exc).__name__, backoff[idx])
|
||||
if stop_event.is_set():
|
||||
break
|
||||
if stop_event.wait(backoff[idx]):
|
||||
break
|
||||
idx = min(idx + 1, len(backoff) - 1)
|
||||
_stream_state["running"] = False
|
||||
|
||||
t = threading.Thread(target=_run, name=f"pmdb-sse-{profile}", daemon=True)
|
||||
t.start()
|
||||
return {"stop_event": stop_event, "thread": t}
|
||||
|
||||
|
||||
def _handle_stream_event(client: PMDBClient, profile: str, event: dict) -> None:
|
||||
"""F-621 Stufe 1: verarbeitet ein task.dispatched-Event (Dispatch).
|
||||
|
||||
Bei einem neuen Task-Event dispatcht der Listener an pmdb_get_tasks
|
||||
(Refresh der eigenen Task-Liste) und pmdb_accept_task (den neuen Task
|
||||
akzeptieren). KEIN Set-Bit-Trigger (A1): accept ist Task-Lifecycle,
|
||||
KEIN Bit-Setzen — der Stream loest nie ein pmdb_set_bit aus. Beide Calls
|
||||
sind best-effort: ein Fehler loggt, wirft aber nie (der Listener-Thread
|
||||
bleibt am Leben, das Polling bleibt als Sicherheitsnetz aktiv).
|
||||
"""
|
||||
data = (event or {}).get("data")
|
||||
if not isinstance(data, dict):
|
||||
return
|
||||
if data.get("type") != "task.dispatched":
|
||||
return
|
||||
task_id = data.get("task_id")
|
||||
_stream_state["event_count"] += 1
|
||||
_stream_state["last_event"] = data
|
||||
logger.info(
|
||||
"pmdb_connector: Stream-Event task.dispatched fuer '%s': task_id=%s "
|
||||
"feature_id=%s target_bit=%s",
|
||||
profile, task_id, data.get("feature_id"), data.get("target_bit"))
|
||||
|
||||
# 1. Dispatch an pmdb_get_tasks: eigene Task-Liste refreshen (Pull).
|
||||
try:
|
||||
result = client.get_tasks()
|
||||
if not (isinstance(result, dict) and result.get("success")):
|
||||
logger.warning(
|
||||
"pmdb_connector: get_tasks-Dispatch fuer '%s' fehlgeschlagen: %s",
|
||||
profile, (result or {}).get("error_code", "unknown"))
|
||||
except Exception as exc: # noqa: BLE001 — best-effort
|
||||
logger.warning(
|
||||
"pmdb_connector: get_tasks-Dispatch Exception fuer '%s': %s",
|
||||
profile, exc)
|
||||
|
||||
# 2. Dispatch an pmdb_accept_task: den neuen Task akzeptieren.
|
||||
if task_id is None:
|
||||
return
|
||||
try:
|
||||
result = client.accept_task(task_id)
|
||||
if isinstance(result, dict) and result.get("success"):
|
||||
logger.info(
|
||||
"pmdb_connector: Task %s fuer '%s' via Stream akzeptiert.",
|
||||
task_id, profile)
|
||||
else:
|
||||
logger.warning(
|
||||
"pmdb_connector: accept_task(%s) fuer '%s' fehlgeschlagen: %s",
|
||||
task_id, profile, (result or {}).get("error_code", "unknown"))
|
||||
except Exception as exc: # noqa: BLE001 — best-effort
|
||||
logger.warning(
|
||||
"pmdb_connector: accept_task(%s) Exception fuer '%s': %s",
|
||||
task_id, profile, exc)
|
||||
|
||||
|
||||
def _stream_status() -> dict:
|
||||
"""F-621: Snapshot des Listener-Status (fuer pmdb_stream_status-Tool)."""
|
||||
return dict(_stream_state)
|
||||
|
||||
|
||||
def register(ctx) -> None:
|
||||
"""Plugin-Entry-Point: Token aufloesen, alle pmdb-Tools registrieren."""
|
||||
profile = pmdb_config.get_active_profile_name()
|
||||
cfg = pmdb_config.load_pmdb_config(profile)
|
||||
token = pmdb_config.resolve_token(profile, cfg)
|
||||
|
||||
# F526 Layer 2 (Diagnostik-Logging): welcher profile, welcher config_path,
|
||||
# welcher Token-Prefix — damit strukturelle Auth-Bugs sichtbar werden
|
||||
# (P-191: nur Prefix, nie Klartext).
|
||||
logger.info(
|
||||
"pmdb_connector: profile=%r, config_path=%r, token=%s, probierte_pfade=%s",
|
||||
profile, str(pmdb_config._profile_config_path(profile)),
|
||||
pmdb_config.token_prefix(token) if token else "<none>",
|
||||
pmdb_config.probierte_pfade(profile, cfg),
|
||||
)
|
||||
|
||||
if not token:
|
||||
# F526 Layer 3 (strukturierter Fehler): statt nur token_missing ->
|
||||
# token_not_found_for_profile mit probierte_pfade + action.
|
||||
logger.warning(
|
||||
"pmdb_connector: Kein Token fuer Profil '%s' — probierte Pfade: %s",
|
||||
profile, pmdb_config.probierte_pfade(profile, cfg))
|
||||
|
||||
def _missing(args: dict, **kw) -> str:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"error_code": "token_not_found_for_profile",
|
||||
"error": f"PMDB-Token fuer Profil '{profile}' nicht konfiguriert.",
|
||||
"probierte_pfade": pmdb_config.probierte_pfade(profile, cfg),
|
||||
"action": "check_config_or_hermes_home",
|
||||
}, ensure_ascii=False)
|
||||
|
||||
for name, (desc, props, required) in _TOOLS.items():
|
||||
parameters = {"type": "object", "properties": props}
|
||||
if required:
|
||||
parameters["required"] = required
|
||||
ctx.register_tool(
|
||||
name=name, toolset=TOOLSET, handler=_missing,
|
||||
schema={"name": name, "description": desc,
|
||||
"parameters": parameters},
|
||||
emoji=EMOJI, description=desc,
|
||||
)
|
||||
return
|
||||
|
||||
client = PMDBClient(
|
||||
base_url=pmdb_config.base_url(cfg), token=token,
|
||||
stream_base_url=pmdb_config.stream_base_url(cfg),
|
||||
internal_base_url=pmdb_config.internal_base_url(cfg),
|
||||
)
|
||||
managers = pmdb_config.manager_profiles(cfg)
|
||||
handlers = _make_handlers(client, profile, managers)
|
||||
|
||||
logger.info("pmdb_connector: Profil '%s', Token %s, %d Tools registriert.",
|
||||
profile, pmdb_config.token_prefix(token), len(handlers))
|
||||
|
||||
for name, (desc, props, required) in _TOOLS.items():
|
||||
parameters = {"type": "object", "properties": props}
|
||||
if required:
|
||||
parameters["required"] = required
|
||||
ctx.register_tool(
|
||||
name=name, toolset=TOOLSET, handler=handlers[name],
|
||||
schema={"name": name, "description": desc,
|
||||
"parameters": parameters},
|
||||
emoji=EMOJI, description=desc,
|
||||
)
|
||||
|
||||
# F-621 Stufe 1: SSE-Task-Dispatch-Listener (opt-in via config, Default aus).
|
||||
# Der Listener laeuft parallel zum Polling (Sicherheitsnetz) und
|
||||
# protokolliert task.dispatched-Events. KEIN Set-Bit-Trigger (A1).
|
||||
if pmdb_config.stream_enabled(cfg):
|
||||
_start_stream_listener(client, profile)
|
||||
logger.info("pmdb_connector: SSE-Stream-Listener fuer '%s' gestartet "
|
||||
"(stream_base_url=%s).", profile,
|
||||
pmdb_config.stream_base_url(cfg))
|
||||
@@ -0,0 +1,568 @@
|
||||
"""F454 PMDB Connector Plugin — HTTP-Client (stdlib-only, keine Hermes-Abhaengigkeit).
|
||||
|
||||
@implements: [F454, F-727]
|
||||
|
||||
Dieser Client ist die EINZIGE Wahrheitsquelle fuer die HTTP-Kommunikation mit
|
||||
dem PMDB MCP-Server (https://pmdb.myowntools.org/mcp). Er ist bewusst
|
||||
stdlib-only (urllib + json), damit er (a) auf jeder Hermes-Instanz laeuft und
|
||||
(b) auf .49 ohne Hermes-Installation gegen die Live-PMDB getestet werden kann.
|
||||
|
||||
Error-Handling (Rainers Architektur §2.5): Jede HTTP-Antwort wird auf einen
|
||||
strukturierten Tool-Response gemappt — KEINE Stacktraces, KEINE HTML-Seiten,
|
||||
sondern JSON mit `success: false` + `error_code` + `action` (P-191-Schutz:
|
||||
LLM-parsebar).
|
||||
|
||||
Mapping:
|
||||
401 -> auth_invalid (action: renew_token)
|
||||
403 -> forbidden (action: contact_manager)
|
||||
404 -> not_found (resource + id)
|
||||
409 -> state_conflict (current_status)
|
||||
429 -> rate_limited (retry_after_seconds)
|
||||
5xx -> pmdb_unavailable (action: fallback_to_terminal)
|
||||
Netzwerkfehler -> network_error
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from typing import Any, Optional
|
||||
|
||||
DEFAULT_BASE_URL = "https://pmdb.myowntools.org/mcp"
|
||||
DEFAULT_TIMEOUT = 30
|
||||
|
||||
# F-621: interner Stream-Basis (Openresty-Proxy blockt Bearer-Stream, 401).
|
||||
# Der Task-Dispatch-Stream laeuft NUR via direktem pmdb.myowntools.org.
|
||||
DEFAULT_STREAM_BASE_URL = "http://pmdb.myowntools.org"
|
||||
|
||||
# F-719: interne Basis fuer Anlagen-Endpunkte (Upload/Liste/Download). Der
|
||||
# Openresty-Proxy (pmdb.myowntools.org) blockt Bearer-Tokens (401) — deshalb
|
||||
# laufen Task-Anlagen IMMER ueber die direkte IPv4 (P-NEW-F563-PMDB-AUTH).
|
||||
DEFAULT_INTERNAL_BASE_URL = "http://pmdb.myowntools.org"
|
||||
|
||||
|
||||
def _parse_content_disposition(header: str) -> str:
|
||||
"""Extrahiert den Dateinamen aus einem Content-Disposition-Header.
|
||||
|
||||
RFC 5987 ``filename*=UTF-8''<name>`` hat Vorrang vor ``filename=``.
|
||||
Liefert "" bei fehlendem/leerem Header.
|
||||
"""
|
||||
if not header:
|
||||
return ""
|
||||
for part in header.split(";"):
|
||||
part = part.strip()
|
||||
if part.startswith("filename*="):
|
||||
val = part[len("filename*="):].strip().strip('"')
|
||||
if "''" in val:
|
||||
val = val.split("''", 1)[1]
|
||||
return val
|
||||
if part.startswith("filename="):
|
||||
return part[len("filename="):].strip().strip('"')
|
||||
return ""
|
||||
|
||||
|
||||
class PMDBClient:
|
||||
"""Synchroner HTTP-Client fuer den PMDB MCP-Server (Bearer-Token-Auth)."""
|
||||
|
||||
def __init__(self, base_url: str = DEFAULT_BASE_URL, token: str = "",
|
||||
timeout: float = DEFAULT_TIMEOUT,
|
||||
stream_base_url: str = DEFAULT_STREAM_BASE_URL,
|
||||
internal_base_url: str = DEFAULT_INTERNAL_BASE_URL) -> None:
|
||||
self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
|
||||
self.token = token
|
||||
self.timeout = timeout
|
||||
self.stream_base_url = (stream_base_url or DEFAULT_STREAM_BASE_URL).rstrip("/")
|
||||
self.internal_base_url = (internal_base_url or DEFAULT_INTERNAL_BASE_URL).rstrip("/")
|
||||
# F-719: Metadaten des letzten Downloads (Filename/Content-Type) —
|
||||
# fuer den Tool-Handler, der die Bytes auf Platte schreiben muss.
|
||||
self._last_download: dict = {}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# HTTP-Kern
|
||||
# ------------------------------------------------------------------
|
||||
def _headers(self, with_json: bool = False) -> dict:
|
||||
h = {"Authorization": f"Bearer {self.token}"}
|
||||
if with_json:
|
||||
h["Content-Type"] = "application/json"
|
||||
return h
|
||||
|
||||
def _request(self, method: str, path: str, body: Optional[dict] = None,
|
||||
base: Optional[str] = None) -> dict:
|
||||
"""Fuehrt einen HTTP-Request aus. Liefert IMMER ein strukturiertes Dict.
|
||||
|
||||
Erfolg: {"success": True, "status": <int>, "data": <parsed-json>}
|
||||
Fehler: {"success": False, "error_code": ..., "error": ..., ...}
|
||||
|
||||
``base`` ueberschreibt die Ziel-Basis (fuer Endpunkte, die ueber die
|
||||
INTERNE IPv4 statt ueber den Proxy laufen muessen — F-719 Anlagen).
|
||||
"""
|
||||
url = (base or self.base_url) + path
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
url, data=data, headers=self._headers(with_json=body is not None),
|
||||
method=method,
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
status = resp.status
|
||||
raw = resp.read().decode("utf-8", errors="replace")
|
||||
except urllib.error.HTTPError as e:
|
||||
status = e.code
|
||||
raw = e.read().decode("utf-8", errors="replace")
|
||||
except urllib.error.URLError as e:
|
||||
return {
|
||||
"success": False,
|
||||
"error_code": "network_error",
|
||||
"error": "PMDB nicht erreichbar",
|
||||
"detail": str(e.reason)[:200],
|
||||
"action": "fallback_to_terminal",
|
||||
}
|
||||
except Exception as e: # noqa: BLE001 — Timeout etc.
|
||||
return {
|
||||
"success": False,
|
||||
"error_code": "network_error",
|
||||
"error": "PMDB-Request fehlgeschlagen",
|
||||
"detail": str(e)[:200],
|
||||
"action": "fallback_to_terminal",
|
||||
}
|
||||
|
||||
parsed = self._parse_json(raw)
|
||||
if 200 <= status < 300:
|
||||
return {"success": True, "status": status, "data": parsed}
|
||||
return self._map_error(status, parsed)
|
||||
|
||||
@staticmethod
|
||||
def _parse_json(raw: str) -> Any:
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except (ValueError, TypeError):
|
||||
return {"raw": raw[:500]}
|
||||
|
||||
def _map_error(self, status: int, body: Any) -> dict:
|
||||
"""Mappt einen HTTP-Fehlerstatus auf einen strukturierten Tool-Response."""
|
||||
body = body if isinstance(body, dict) else {}
|
||||
server_error = body.get("error", "")
|
||||
if status == 401:
|
||||
return {"success": False, "error_code": "auth_invalid",
|
||||
"error": server_error or "Token ungueltig oder widerrufen",
|
||||
"action": "renew_token"}
|
||||
if status == 403:
|
||||
return {"success": False, "error_code": "forbidden",
|
||||
"error": server_error or "Rolle fehlt fuer diese Aktion",
|
||||
"action": "contact_manager"}
|
||||
if status == 404:
|
||||
return {"success": False, "error_code": "not_found",
|
||||
"error": server_error or "Ressource nicht gefunden"}
|
||||
if status == 409:
|
||||
return {"success": False, "error_code": "state_conflict",
|
||||
"error": server_error or "Status-Konflikt",
|
||||
"current_status": body.get("status")}
|
||||
if status == 422:
|
||||
# F524: Vorgaenger-Pre-Check beim Pitching.
|
||||
if body.get("error_code") == "vorgaenger_fehlen":
|
||||
return {"success": False, "error_code": "vorgaenger_fehlen",
|
||||
"error": server_error or "Vorgaenger-Bits fehlen",
|
||||
"fehlende_bits": body.get("fehlende_bits", []),
|
||||
"action": "set_bits_first"}
|
||||
return {"success": False, "error_code": "unprocessable",
|
||||
"error": server_error or "Ungueltige Eingabe (422)",
|
||||
"detail": body}
|
||||
if status == 429:
|
||||
return {"success": False, "error_code": "rate_limited",
|
||||
"error": server_error or "Rate-Limit ueberschritten",
|
||||
"retry_after_seconds": 60}
|
||||
if status >= 500:
|
||||
return {"success": False, "error_code": "pmdb_unavailable",
|
||||
"error": server_error or "PMDB-Server nicht verfuegbar",
|
||||
"action": "fallback_to_terminal"}
|
||||
return {"success": False, "error_code": "http_error",
|
||||
"error": server_error or f"HTTP {status}",
|
||||
"status": status}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Task-Lifecycle (Phase 1)
|
||||
# ------------------------------------------------------------------
|
||||
def get_tasks(self) -> dict:
|
||||
"""Eigene Tasks (F455 Hybrid-Anzeige: freie Tasks + blockierte als Counter)."""
|
||||
return self._request("GET", "/mcp/api/tasks")
|
||||
|
||||
def get_task(self, task_id) -> dict:
|
||||
"""Task-Detail + Status (GET /mcp/api/tasks/{id}, Bearer-Token).
|
||||
|
||||
@implements: [F-452, F-702]
|
||||
|
||||
Liefert den vollen Task-Row (inkl. ``pitch``). Wird vom SSE-Connector
|
||||
(F-702) genutzt, um den Pitch nachzuladen: der Task-Dispatch-Broadcast
|
||||
trägt KEIN pitch-Feld, der Pitch kommt aus diesem Detail-Endpoint.
|
||||
"""
|
||||
return self._request("GET", f"/mcp/api/tasks/{task_id}")
|
||||
|
||||
def get_submitted_tasks(self) -> dict:
|
||||
"""F456: Submitted Tasks (Manager-View, Bearer-Token + rolle_id=1)."""
|
||||
return self._request("GET", "/mcp/api/tasks/submitted")
|
||||
|
||||
def manager_dashboard(self) -> dict:
|
||||
"""F514: Manager-Dashboard (Bearer-Token + rolle_id=1, 4 Bereiche)."""
|
||||
return self._request("GET", "/mcp/api/dashboard")
|
||||
|
||||
def accept_task(self, task_id) -> dict:
|
||||
return self._request("POST", f"/mcp/api/tasks/{task_id}/accept")
|
||||
|
||||
def decline_task(self, task_id, reason: str) -> dict:
|
||||
return self._request("POST", f"/mcp/api/tasks/{task_id}/decline",
|
||||
{"reason": reason or ""})
|
||||
|
||||
def submit_task(self, task_id, result: dict) -> dict:
|
||||
return self._request("POST", f"/mcp/api/tasks/{task_id}/submit",
|
||||
{"payload": result})
|
||||
|
||||
def return_for_revision(self, task_id, reason: str,
|
||||
auflagen=None, zusammenfassung=None) -> dict:
|
||||
"""F-705: QG-Rueckdelegation mit Auflagen + Eskalations-Zusammenfassung.
|
||||
|
||||
@implements: [F-705]
|
||||
|
||||
QG-Rolle: Rueckdelegation eines submitted Tasks mit strukturierten
|
||||
Auflagen (Ebene-Pflicht) und — wenn der Call die Eskalation ausloest —
|
||||
einer Pflicht-Zusammenfassung. Der Server prueft die QG-Rolle und die
|
||||
Separation of Duties (Aufrufer != Task-Owner).
|
||||
"""
|
||||
body = {"reason": reason or ""}
|
||||
if auflagen is not None:
|
||||
body["auflagen"] = auflagen
|
||||
if zusammenfassung:
|
||||
body["zusammenfassung"] = zusammenfassung
|
||||
return self._request("POST", f"/mcp/api/tasks/{task_id}/return-for-revision",
|
||||
body)
|
||||
|
||||
def manager_decision(self, task_id, entscheidung: str, begruendung: str,
|
||||
auflagen=None, timebox_runden=None,
|
||||
ziel_architektur_notiz=None,
|
||||
auftraggeber_zusammenfassung=None) -> dict:
|
||||
"""F-705: Manager-Entscheidung fuer ein offenes Eskalations-Fenster.
|
||||
|
||||
@implements: [F-705]
|
||||
|
||||
entscheidung a/b/c/d; begruendung Pflicht. auflagen + timebox_runden
|
||||
bei a; ziel_architektur_notiz bei b; auftraggeber_zusammenfassung bei c.
|
||||
"""
|
||||
body = {"entscheidung": entscheidung, "begruendung": begruendung or ""}
|
||||
if auflagen is not None:
|
||||
body["auflagen"] = auflagen
|
||||
if timebox_runden is not None:
|
||||
body["timebox_runden"] = timebox_runden
|
||||
if ziel_architektur_notiz is not None:
|
||||
body["ziel_architektur_notiz"] = ziel_architektur_notiz
|
||||
if auftraggeber_zusammenfassung is not None:
|
||||
body["auftraggeber_zusammenfassung"] = auftraggeber_zusammenfassung
|
||||
return self._request(
|
||||
"POST", f"/mcp/api/tasks/eskaliert/{task_id}/entscheidung", body)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Query + Management (Phase 2)
|
||||
# ------------------------------------------------------------------
|
||||
def get_mask(self, feature_id) -> dict:
|
||||
return self._request("GET", f"/mcp/api/getmask/{feature_id}")
|
||||
|
||||
def search(self, projekt=None, ziel=None, funktionsbereich=None,
|
||||
feature=None) -> dict:
|
||||
body = {}
|
||||
if projekt:
|
||||
body["projekt"] = projekt
|
||||
if ziel:
|
||||
body["ziel"] = ziel
|
||||
if funktionsbereich:
|
||||
body["funktionsbereich"] = funktionsbereich
|
||||
if feature:
|
||||
body["feature"] = feature
|
||||
return self._request("POST", "/mcp/api/search", body)
|
||||
|
||||
def get_baustein(self, baustein_id) -> dict:
|
||||
return self._request("GET", f"/mcp/api/bausteine/{baustein_id}")
|
||||
|
||||
def set_bit(self, feature_id, bit_nr, begruendung: Optional[str] = None,
|
||||
artefakt_typ: Optional[str] = None,
|
||||
artefakt_inhalt: Optional[str] = None,
|
||||
artefakt_titel: Optional[str] = None,
|
||||
artefakte: Optional[list] = None) -> dict:
|
||||
body = {"feature_id": feature_id, "bit_nr": bit_nr}
|
||||
if begruendung:
|
||||
body["begruendung"] = begruendung
|
||||
# F183: Artefakt-Belege (Einzelfelder ODER Liste fuer 1:N).
|
||||
if artefakte:
|
||||
body["artefakte"] = artefakte
|
||||
elif artefakt_typ or artefakt_inhalt or artefakt_titel:
|
||||
body["artefakt_typ"] = artefakt_typ
|
||||
body["artefakt_inhalt"] = artefakt_inhalt
|
||||
body["artefakt_titel"] = artefakt_titel
|
||||
return self._request("POST", "/mcp/api/set-bit", body)
|
||||
|
||||
def create_task(self, agent: str, feature_id, baustein_id, pitch: str,
|
||||
frist: Optional[str] = None) -> dict:
|
||||
body = {"agent": agent, "feature_id": feature_id,
|
||||
"baustein_id": baustein_id, "pitch": pitch}
|
||||
if frist:
|
||||
body["frist"] = frist
|
||||
return self._request("POST", "/mcp/api/tasks", body)
|
||||
|
||||
def get_pipeline_status(self, projekt_id=None, feature_status_filter=None,
|
||||
include_terminal=False) -> dict:
|
||||
"""F523: Pipeline-Overview — alle Features mit Bit-Stand + pending Tasks."""
|
||||
parts = []
|
||||
if projekt_id is not None:
|
||||
parts.append(f"projekt_id={projekt_id}")
|
||||
if feature_status_filter:
|
||||
parts.append(f"feature_status_filter={feature_status_filter}")
|
||||
if include_terminal:
|
||||
parts.append("include_terminal=true")
|
||||
path = "/mcp/api/pipeline-status"
|
||||
if parts:
|
||||
path += "?" + "&".join(parts)
|
||||
return self._request("GET", path)
|
||||
|
||||
def submit_on_behalf(self, task_id, agent_name: str, payload: dict) -> dict:
|
||||
"""F525 Teil 1: Manager submittet Task fuer anderen Agenten."""
|
||||
return self._request(
|
||||
"POST", f"/mcp/api/tasks/{task_id}/submit-on-behalf",
|
||||
{"agent_name": agent_name, "payload": payload},
|
||||
)
|
||||
|
||||
def get_task_evidence(self, task_id, include_sources=None) -> dict:
|
||||
"""F528: Evidence-Collection fuer QG (read-only)."""
|
||||
path = f"/mcp/api/tasks/{task_id}/evidence"
|
||||
if include_sources:
|
||||
path += f"?include_sources={include_sources}"
|
||||
return self._request("GET", path)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# F-719: Task-Anlagen (Upload/Liste/Download) — MCP Broker 4.0
|
||||
# ------------------------------------------------------------------
|
||||
def get_anlagen(self, task_id) -> dict:
|
||||
"""F-719: Liste aller Anlagen eines Tasks (Owner ODER Manager).
|
||||
|
||||
@implements: [F-719]
|
||||
|
||||
GET /mcp/api/tasks/{task_id}/anlagen — liefert
|
||||
``{"task_id": ..., "anlagen": [{id, richtung, name, mime_type,
|
||||
groesse_bytes, sha256, pfad, hochgeladen_von, upload_am, ...}]}``.
|
||||
``mime_type`` ist ein canonisches Tag (pdf/png/jpeg/txt/csv/md),
|
||||
KEIN full-MIME-String.
|
||||
"""
|
||||
return self._request("GET", f"/mcp/api/tasks/{task_id}/anlagen",
|
||||
base=self.internal_base_url)
|
||||
|
||||
def download_anlage(self, task_id, att_id):
|
||||
"""F-719: Binaer-Download einer einzelnen Anlage.
|
||||
|
||||
@implements: [F-719]
|
||||
|
||||
GET /mcp/api/tasks/{task_id}/anlagen/{att_id} — die Antwort ist der
|
||||
DATEI-INHALT (Bytes), KEIN JSON. Deshalb NICHT ``_request`` (das parst
|
||||
JSON), sondern direkter urllib-Read. Liefert die Bytes bei Erfolg oder
|
||||
ein strukturiertes Fehler-Dict (P-191). Filename/Content-Type stehen
|
||||
danach in ``self._last_download`` (fuer den Tool-Handler).
|
||||
"""
|
||||
url = f"{self.internal_base_url}/mcp/api/tasks/{task_id}/anlagen/{att_id}"
|
||||
req = urllib.request.Request(url, method="GET", headers=self._headers())
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
raw = resp.read()
|
||||
self._last_download = {
|
||||
"content_type": resp.headers.get("Content-Type", ""),
|
||||
"filename": _parse_content_disposition(
|
||||
resp.headers.get("Content-Disposition", "")),
|
||||
}
|
||||
return raw
|
||||
except urllib.error.HTTPError as e:
|
||||
return self._map_error(
|
||||
e.code,
|
||||
self._parse_json(e.read().decode("utf-8", errors="replace")))
|
||||
except urllib.error.URLError as e:
|
||||
return {
|
||||
"success": False, "error_code": "network_error",
|
||||
"error": "PMDB nicht erreichbar",
|
||||
"detail": str(e.reason)[:200],
|
||||
"action": "fallback_to_terminal",
|
||||
}
|
||||
except Exception as e: # noqa: BLE001 — Timeout etc.
|
||||
return {
|
||||
"success": False, "error_code": "network_error",
|
||||
"error": "PMDB-Download fehlgeschlagen",
|
||||
"detail": str(e)[:200],
|
||||
"action": "fallback_to_terminal",
|
||||
}
|
||||
|
||||
def upload_anlage(self, task_id, file_path,
|
||||
mime_type: Optional[str] = None) -> dict:
|
||||
"""F-719: Eingang-Anlage hochladen (Manager oder Agent mit Manager-Recht).
|
||||
|
||||
@implements: [F-719]
|
||||
|
||||
POST /mcp/api/tasks/{task_id}/anlagen — multipart/form-data, Feld
|
||||
'datei'. Status-Guard: nur bei ``status=pitched``. sha256 + mime-Tag
|
||||
werden SERVER-seitig bestimmt (Magic/Endung), der Client-Parameter
|
||||
``mime_type`` setzt nur den Part-Content-Type (nicht verbindlich).
|
||||
"""
|
||||
return self._multipart_upload(
|
||||
f"/mcp/api/tasks/{task_id}/anlagen", file_path, mime_type)
|
||||
|
||||
def upload_ergebnis_anlage(self, task_id, file_path,
|
||||
mime_type: Optional[str] = None) -> dict:
|
||||
"""F-719: Ergebnis-Anlage hochladen (Owner-Agent, nach submit).
|
||||
|
||||
@implements: [F-719]
|
||||
|
||||
POST /mcp/api/tasks/{task_id}/ergebnis-anlagen — multipart/form-data,
|
||||
Feld 'datei'. Status-Guard: nur bei ``status=submitted``. Owner-only
|
||||
(der Server prueft die Bearer-Identitaet, KEIN Body-Feld).
|
||||
"""
|
||||
return self._multipart_upload(
|
||||
f"/mcp/api/tasks/{task_id}/ergebnis-anlagen", file_path, mime_type)
|
||||
|
||||
def _multipart_upload(self, path: str, file_path: str,
|
||||
mime_type: Optional[str] = None) -> dict:
|
||||
"""F-719: Multipart-Upload einer Datei (stdlib, manuell konstruierter Body).
|
||||
|
||||
Liesst die Datei vom Dateisystem, baut einen multipart/form-data-Body
|
||||
mit zufaelliger Boundary und einem ``datei``-Part. Der Body wird
|
||||
bytes-korrekt aufgebaut (keine Requests-Lib). Erfolg liefert
|
||||
``{"success": True, "status": 201, "data": {"success": ..., "anlagen": [...]}}``;
|
||||
Fehler sind strukturierte Dicts (P-191).
|
||||
"""
|
||||
if not os.path.isfile(file_path):
|
||||
return {
|
||||
"success": False, "error_code": "file_not_found",
|
||||
"error": f"Datei nicht gefunden: {file_path}",
|
||||
"action": "check_file_path",
|
||||
}
|
||||
|
||||
filename = os.path.basename(file_path)
|
||||
ctype = mime_type or mimetypes.guess_type(filename)[0] \
|
||||
or "application/octet-stream"
|
||||
|
||||
with open(file_path, "rb") as fh:
|
||||
content = fh.read()
|
||||
|
||||
boundary = f"----pmdb-{uuid.uuid4().hex}"
|
||||
body = (
|
||||
f"--{boundary}\r\n"
|
||||
f"Content-Disposition: form-data; name=\"datei\"; "
|
||||
f"filename=\"{filename}\"\r\n"
|
||||
f"Content-Type: {ctype}\r\n\r\n"
|
||||
).encode("utf-8") + content + f"\r\n--{boundary}--\r\n".encode("utf-8")
|
||||
|
||||
url = self.internal_base_url + path
|
||||
req = urllib.request.Request(url, data=body, method="POST")
|
||||
req.add_header("Authorization", f"Bearer {self.token}")
|
||||
req.add_header("Content-Type", f"multipart/form-data; boundary={boundary}")
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
status = resp.status
|
||||
raw = resp.read().decode("utf-8", errors="replace")
|
||||
except urllib.error.HTTPError as e:
|
||||
status = e.code
|
||||
raw = e.read().decode("utf-8", errors="replace")
|
||||
except urllib.error.URLError as e:
|
||||
return {
|
||||
"success": False, "error_code": "network_error",
|
||||
"error": "PMDB nicht erreichbar",
|
||||
"detail": str(e.reason)[:200],
|
||||
"action": "fallback_to_terminal",
|
||||
}
|
||||
except Exception as e: # noqa: BLE001 — Timeout etc.
|
||||
return {
|
||||
"success": False, "error_code": "network_error",
|
||||
"error": "PMDB-Upload fehlgeschlagen",
|
||||
"detail": str(e)[:200],
|
||||
"action": "fallback_to_terminal",
|
||||
}
|
||||
|
||||
parsed = self._parse_json(raw)
|
||||
if 200 <= status < 300:
|
||||
return {"success": True, "status": status, "data": parsed}
|
||||
return self._map_error(status, parsed)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# F-621: SSE-Task-Dispatch-Stream (stdlib urllib, kein aiohttp)
|
||||
# ------------------------------------------------------------------
|
||||
def stream_tasks(self, profile: str, last_event_id=None,
|
||||
connect_timeout: Optional[float] = None):
|
||||
"""Generator, der task.dispatched-SSE-Events liefert (F-621).
|
||||
|
||||
@implements: [F-621]
|
||||
|
||||
Blockierender urllib-Read (sync, stdlib-only — konsistent zum Rest des
|
||||
Plugins). Liest das EventSource-Protokoll zeilenweise und liefert
|
||||
parse-te Event-Dicts der Form {event, data}. Der Aufrufer
|
||||
(Listener-Thread) haelt den Generator offen und reconnectet bei
|
||||
Abbruch/Exception.
|
||||
|
||||
Auth (P-191): Token via ``Authorization``-Header (add_header) — bleibt
|
||||
aus der URL fern. Pitfall (F-621): Stream laeuft ueber den INTERNEN
|
||||
``stream_base_url`` (pmdb.myowntools.org), nicht ueber den
|
||||
Openresty-Proxy, der Bearer-Stream mit 401 blockt.
|
||||
|
||||
``connect_timeout`` wird nur bei EXPLIZITER Übergabe als Socket-Timeout
|
||||
gesetzt (stdlib urllib kennt keinen getrennten Connect-/Read-Timeout);
|
||||
der generelle ``self.timeout`` (30s) gilt NICHT mehr für den Stream.
|
||||
Default (None) = voll blockierend — kein Idle-Limit am Socket.
|
||||
|
||||
F-727 S1b — normative Marge-Regel (Architektur §2.1, Viola-Mandat M2):
|
||||
Die SSE-Kette ist stabil, wenn gilt:
|
||||
Client-Read-Timeout (am Socket) > 2 × Server-Keepalive-Intervall.
|
||||
Der Stream-Read ist deshalb BLOCKIEREND (``timeout=None``); ein
|
||||
Server-Deploy/Restart meldet den Abbruch sofort via TCP FIN/RST, der
|
||||
Listener reconnectet (Backoff 1s/4s/16s/60s). Wer später den
|
||||
Timeout ändert, MUSS diese Regel gegenprüfen (R7). Server-
|
||||
Gegenstück: SSE_KEEPALIVE_S in backend/broker_routes.py.
|
||||
"""
|
||||
path = f"/mcp/api/stream/tasks?profile={profile}"
|
||||
if last_event_id is not None:
|
||||
path += f"&last_event_id={last_event_id}"
|
||||
url = self.stream_base_url + path
|
||||
req = urllib.request.Request(url, method="GET")
|
||||
req.add_header("Authorization", f"Bearer {self.token}")
|
||||
req.add_header("Accept", "text/event-stream")
|
||||
# F-727 S1b — Read-Timeout vom generellen self.timeout (30s) entkoppelt:
|
||||
# timeout=None = blockierendes Lesen ohne Idle-Limit (docstring-konform,
|
||||
# Marge-Regel oben). connect_timeout wird nur bei EXPLIZITER Übergabe
|
||||
# als Socket-Timeout gesetzt. Default None = voll blockierend.
|
||||
resp = urllib.request.urlopen(req, timeout=connect_timeout)
|
||||
event_type = None
|
||||
data_lines = []
|
||||
try:
|
||||
for raw in resp:
|
||||
line = raw.decode("utf-8", errors="replace").rstrip("\r\n")
|
||||
if line == "":
|
||||
# Leerzeile = Event-Ende.
|
||||
if data_lines:
|
||||
payload = "\n".join(data_lines)
|
||||
data_lines = []
|
||||
try:
|
||||
parsed = json.loads(payload)
|
||||
except (ValueError, TypeError):
|
||||
parsed = {"raw": payload}
|
||||
yield {"event": event_type or "message", "data": parsed}
|
||||
event_type = None
|
||||
continue
|
||||
if line.startswith(":"):
|
||||
continue # Kommentar/keepalive.
|
||||
if line.startswith("event:"):
|
||||
event_type = line[len("event:"):].strip()
|
||||
continue
|
||||
if line.startswith("data:"):
|
||||
data_lines.append(line[len("data:"):].strip())
|
||||
continue
|
||||
# 'retry:'/'id:'-Zeilen ignorieren — Reconnect steuert der Listener.
|
||||
finally:
|
||||
try:
|
||||
resp.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
@@ -0,0 +1,403 @@
|
||||
"""F454 PMDB Connector Plugin — Profil-Config + Token-Aufloesung.
|
||||
|
||||
@implements: [F454]
|
||||
@implements: [F590]
|
||||
@implements: [F-621]
|
||||
|
||||
V1 (Option A): 1:1-Mapping Hermes-Profil = PMDB-Agent-Name. Das aktive Profil
|
||||
wird via `hermes_cli.profiles.get_active_profile_name()` ermittelt (HERMES_HOME-
|
||||
basiert). Der zugehoerige Bearer-Token liegt in der Profile-Config:
|
||||
|
||||
~/.hermes/profiles/<name>/config.yaml
|
||||
pmdb_connector:
|
||||
base_url: "https://pmdb.myowntools.org/mcp"
|
||||
manager_profiles: [bernd, andreas]
|
||||
auth_keys:
|
||||
default: "mcp_bernd_<geheimnis>"
|
||||
miguel: "mcp_miguel_<geheimnis>"
|
||||
rainer: "mcp_rainer_<geheimnis>"
|
||||
finn: "mcp_finn_<geheimnis>"
|
||||
don: "mcp_don_<geheimnis>"
|
||||
|
||||
V2 Stufe 1 (Plaintext Config) ist der aktuelle Stand. Stufe 2 (Secret-Source)
|
||||
ist als verbindliche Erweiterung eingeplant (Rainers Architektur §2.3).
|
||||
|
||||
F590 (Token-Sync): Die KANONISCHE Token-Quelle ist jetzt ``mcp_tokens.json``
|
||||
(~/.hermes/mcp_tokens.json, F531-Bootstrap-Store). ``resolve_token()`` liest
|
||||
den Bearer-Token ZUERST aus ``mcp_tokens.json`` (agenten[<profil>].token) und
|
||||
faellt nur noch bei Nicht-Fund auf die config.yaml-``auth_keys`` zurueck
|
||||
(backward-compat). Das beseitigt den Token-Drift zwischen zwei Quellen
|
||||
(P-NEW-3 / Daily Note 04.10.).
|
||||
|
||||
Sicherheits-Garantien (P-191/P-219-Schutz):
|
||||
- Token wird NIE geloggt (nur Prefix `mcp_<kuerzel>_***`).
|
||||
- Token erscheint NIE in Tool-Responses oder Fehlermeldungen.
|
||||
- Fehlender Token -> strukturierter Error `token_missing` (kein Crash).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_BASE_URL = "https://pmdb.myowntools.org/mcp"
|
||||
|
||||
|
||||
def get_active_profile_name() -> str:
|
||||
"""Ermittelt das aktive Hermes-Profil (HERMES_HOME-basiert).
|
||||
|
||||
Fallback-Kette (P-191: nie still scheitern):
|
||||
1. hermes_cli.profiles.get_active_profile_name() (offizielle API)
|
||||
2. HERMES_HOME-Pfad-Analyse (falls hermes_cli nicht importierbar)
|
||||
3. "default"
|
||||
"""
|
||||
try:
|
||||
from hermes_cli.profiles import get_active_profile_name as _gapn
|
||||
return _gapn()
|
||||
except Exception:
|
||||
pass
|
||||
home = os.environ.get("HERMES_HOME", "")
|
||||
if home:
|
||||
p = Path(home)
|
||||
# ~/.hermes/profiles/<name> -> <name>
|
||||
if p.parent.name == "profiles":
|
||||
return p.name
|
||||
return "default"
|
||||
|
||||
|
||||
def _profile_config_path(profile: str) -> Optional[Path]:
|
||||
"""Pfad zur Profile-Config (HERMES_HOME-basiert, P-119/P-147-sicher).
|
||||
|
||||
Zwei Faelle (P-119/P-147-Klasse — HERMES_HOME-Dopplung):
|
||||
1. HERMES_HOME zeigt auf ein PROFIL-Verzeichnis
|
||||
(~/.hermes/profiles/<name>) -> die Config liegt DIREKT dort
|
||||
(HERMES_HOME/config.yaml). Es darf NICHT erneut `profiles/<name>`
|
||||
angehaengt werden, sonst entsteht die Dopplung
|
||||
`.../profiles/<name>/profiles/<name>/config.yaml`.
|
||||
2. HERMES_HOME zeigt auf das BASIS-Verzeichnis (~/.hermes) ->
|
||||
default: <base>/config.yaml
|
||||
benannt: <base>/profiles/<name>/config.yaml
|
||||
|
||||
Ohne HERMES_HOME: Fallback auf ~/.hermes (analog Fall 2).
|
||||
"""
|
||||
home = os.environ.get("HERMES_HOME")
|
||||
if home:
|
||||
base = Path(home)
|
||||
# Fall 1: HERMES_HOME ist bereits ein Profil-Verzeichnis.
|
||||
if base.parent.name == "profiles":
|
||||
return base / "config.yaml"
|
||||
# Fall 2: Basis-Verzeichnis.
|
||||
if profile == "default":
|
||||
return base / "config.yaml"
|
||||
return base / "profiles" / profile / "config.yaml"
|
||||
# Kein HERMES_HOME: Fallback auf ~/.hermes.
|
||||
base = Path.home() / ".hermes"
|
||||
if profile == "default":
|
||||
return base / "config.yaml"
|
||||
return base / "profiles" / profile / "config.yaml"
|
||||
|
||||
|
||||
def _load_yaml(path: Path) -> dict:
|
||||
try:
|
||||
import yaml
|
||||
with open(path, encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f) or {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def load_pmdb_config(profile: str) -> dict:
|
||||
"""Liest die `pmdb_connector`-Sektion aus der Profile-Config.
|
||||
|
||||
Liefert {} wenn keine Sektion existiert (Plugin deaktiviert sich dann
|
||||
sauber mit token_missing).
|
||||
"""
|
||||
path = _profile_config_path(profile)
|
||||
if path is None or not path.exists():
|
||||
return {}
|
||||
data = _load_yaml(path)
|
||||
section = data.get("pmdb_connector")
|
||||
return section if isinstance(section, dict) else {}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# F590: Kanonische Token-Quelle mcp_tokens.json (F531-Bootstrap-Store)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _mcp_tokens_path() -> Optional[Path]:
|
||||
"""@implements F-590 — Pfad zur kanonischen mcp_tokens.json.
|
||||
|
||||
mcp_tokens.json liegt IMMER auf der Basis-Ebene (~/.hermes/mcp_tokens.json),
|
||||
NICHT pro Profil. Env ``HERMES_MCP_TOKENS`` ueberschreibt den Pfad (fuer
|
||||
Tests + Betrieb).
|
||||
|
||||
HERMES_HOME-Aufloesung (analog _base_config_path):
|
||||
1. HERMES_HOME zeigt auf ein Profil-Verzeichnis
|
||||
(~/.hermes/profiles/<name>) -> Basis ist der Parent-Parent
|
||||
(~/.hermes/mcp_tokens.json).
|
||||
2. HERMES_HOME zeigt auf die Basis (~/.hermes) -> direkt dort.
|
||||
3. Ohne HERMES_HOME -> ~/.hermes/mcp_tokens.json.
|
||||
"""
|
||||
env = os.environ.get("HERMES_MCP_TOKENS")
|
||||
if env:
|
||||
return Path(env)
|
||||
home = os.environ.get("HERMES_HOME")
|
||||
if home:
|
||||
base = Path(home)
|
||||
if base.parent.name == "profiles":
|
||||
return base.parent.parent / "mcp_tokens.json"
|
||||
return base / "mcp_tokens.json"
|
||||
return Path.home() / ".hermes" / "mcp_tokens.json"
|
||||
|
||||
|
||||
def load_mcp_tokens() -> dict:
|
||||
"""@implements F-590 — liest die ``agenten``-Sektion aus mcp_tokens.json.
|
||||
|
||||
Liefert {} wenn die Datei fehlt oder unlesbar/korrupt ist (kein Crash —
|
||||
der Aufrufer faellt dann auf die config.yaml-``auth_keys`` zurueck).
|
||||
"""
|
||||
path = _mcp_tokens_path()
|
||||
if path is None or not path.exists():
|
||||
return {}
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except (OSError, ValueError, json.JSONDecodeError):
|
||||
return {}
|
||||
if not isinstance(data, dict):
|
||||
return {}
|
||||
agenten = data.get("agenten")
|
||||
return agenten if isinstance(agenten, dict) else {}
|
||||
|
||||
|
||||
def resolve_token_from_mcp_tokens(profile: str) -> Optional[str]:
|
||||
"""@implements F-590 — loest den Bearer-Token aus mcp_tokens.json auf.
|
||||
|
||||
Exakter Match ``agenten[<profil>].token``, dann case-insensitiver Match
|
||||
(P-194: Profil-/Agent-Namen sind case-inkonsistent). Liefert None wenn
|
||||
das Profil nicht in mcp_tokens.json steht (der Aufrufer faellt dann auf
|
||||
die config.yaml-``auth_keys`` zurueck).
|
||||
"""
|
||||
tokens = load_mcp_tokens()
|
||||
if not tokens:
|
||||
return None
|
||||
entry = tokens.get(profile)
|
||||
if not isinstance(entry, dict):
|
||||
lower = (profile or "").strip().lower()
|
||||
for key, val in tokens.items():
|
||||
if (key or "").strip().lower() == lower and isinstance(val, dict):
|
||||
entry = val
|
||||
break
|
||||
if isinstance(entry, dict):
|
||||
token = entry.get("token")
|
||||
if token:
|
||||
return str(token).strip()
|
||||
return None
|
||||
|
||||
|
||||
def _base_config_path() -> Optional[Path]:
|
||||
"""Pfad zur Basis-Config (~/.hermes/config.yaml bzw. HERMES_HOME-Basis).
|
||||
|
||||
F526: Wenn HERMES_HOME auf das BASIS-Verzeichnis (~/.hermes) zeigt (CLI-
|
||||
Kontext) und das Profil als 'default' aufgeloest wurde, liegt der
|
||||
profilspezifische Token moeglicherweise in einer ANDEREN Profile-Config
|
||||
(z.B. ~/.hermes/profiles/rainer/config.yaml). Diese Funktion liefert den
|
||||
Basis-Pfad fuer den Fallback in resolve_token().
|
||||
"""
|
||||
home = os.environ.get("HERMES_HOME")
|
||||
if home:
|
||||
base = Path(home)
|
||||
# HERMES_HOME zeigt auf ein Profil-Verzeichnis -> Basis ist der Parent
|
||||
# (~/.hermes/profiles/<name> -> ~/.hermes).
|
||||
if base.parent.name == "profiles":
|
||||
return base.parent / "config.yaml"
|
||||
# HERMES_HOME ist bereits die Basis.
|
||||
return base / "config.yaml"
|
||||
return Path.home() / ".hermes" / "config.yaml"
|
||||
|
||||
|
||||
def _profile_auth_keys(profile: str) -> dict:
|
||||
"""Liest auth_keys aus der Profile-Config (fuer den Fallback-Lookup).
|
||||
|
||||
F526 Layer 1: Wenn die AKTUELLE Config kein auth_keys fuer das Profil hat,
|
||||
prueft der Fallback, ob eine Profile-Config (~/.hermes/profiles/<profile>/
|
||||
config.yaml) den Token traegt. Das ist der Fall bei 'HERMES_HOME=Basis +
|
||||
profile!=default' (P-119/P-147-Luecke).
|
||||
"""
|
||||
path = _profile_config_path(profile)
|
||||
if path is None or not path.exists():
|
||||
return {}
|
||||
data = _load_yaml(path)
|
||||
section = data.get("pmdb_connector")
|
||||
if not isinstance(section, dict):
|
||||
return {}
|
||||
auth_keys = section.get("auth_keys")
|
||||
return auth_keys if isinstance(auth_keys, dict) else {}
|
||||
|
||||
|
||||
def resolve_token(profile: str, config: dict) -> Optional[str]:
|
||||
"""Waehlt den Bearer-Token fuer das Profil.
|
||||
|
||||
F590 (Token-Sync, Single Source of Truth): Die KANONISCHE Quelle ist
|
||||
``mcp_tokens.json`` (agenten[<profil>].token). Nur bei Nicht-Fund greift
|
||||
der config.yaml-Fallback (F526-Drei-Schichten, backward-compat):
|
||||
|
||||
1. mcp_tokens.json (kanonisch, F590)
|
||||
2. auth_keys[<profile>] (profile-spezifisch in der AKTUELLEN Config)
|
||||
3. auth_keys["default"] (Default der AKTUELLEN Config)
|
||||
4. Basis-Config (~/.hermes/config.yaml) auth_keys[<profile>|default]
|
||||
5. Profile-Config (~/.hermes/profiles/<profile>/config.yaml)
|
||||
auth_keys[<profile>|default] — deckt 'HERMES_HOME=Basis + profile!=
|
||||
default' ab (P-119/P-147-Luecke).
|
||||
|
||||
Liefert None, wenn kein Token gefunden wird (der Aufrufer meldet dann
|
||||
strukturiert token_not_found_for_profile mit probierte_pfade).
|
||||
"""
|
||||
# 0. F590: kanonische Quelle mcp_tokens.json (beseitigt Token-Drift).
|
||||
token = resolve_token_from_mcp_tokens(profile)
|
||||
if token:
|
||||
return token
|
||||
|
||||
auth_keys = config.get("auth_keys")
|
||||
if not isinstance(auth_keys, dict):
|
||||
auth_keys = {}
|
||||
|
||||
# 1. profile-spezifisch in der aktuellen Config.
|
||||
token = auth_keys.get(profile)
|
||||
if token:
|
||||
return str(token).strip()
|
||||
|
||||
# 2. profile-spezifisch in der PROFILE-Config (HERMES_HOME=Basis + profile
|
||||
# != default, P-119/P-147-Luecke). VOR dem 'default'-Fallback, damit bei
|
||||
# profile='rainer' + Basis-Config ohne 'rainer'-Key der richtige Token
|
||||
# aus ~/.hermes/profiles/rainer/config.yaml gewinnt (statt faelschlich
|
||||
# den 'default'-Token eines ANDEREN Agenten zu laden).
|
||||
if profile != "default":
|
||||
prof_keys = _profile_auth_keys(profile)
|
||||
if prof_keys.get(profile):
|
||||
return str(prof_keys[profile]).strip()
|
||||
|
||||
# 3. default der aktuellen Config.
|
||||
token = auth_keys.get("default")
|
||||
if token:
|
||||
return str(token).strip()
|
||||
|
||||
# 4. Basis-Config (auth_keys[<profile>|default]).
|
||||
base_path = _base_config_path()
|
||||
if base_path is not None and base_path.exists():
|
||||
base_cfg = _load_yaml(base_path)
|
||||
base_section = base_cfg.get("pmdb_connector")
|
||||
if isinstance(base_section, dict):
|
||||
base_keys = base_section.get("auth_keys")
|
||||
if isinstance(base_keys, dict):
|
||||
token = base_keys.get(profile) or base_keys.get("default")
|
||||
if token:
|
||||
return str(token).strip()
|
||||
|
||||
# 5. Profile-Config (auth_keys[<profile>|default]).
|
||||
prof_keys = _profile_auth_keys(profile)
|
||||
if prof_keys:
|
||||
token = prof_keys.get(profile) or prof_keys.get("default")
|
||||
if token:
|
||||
return str(token).strip()
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def probierte_pfade(profile: str, config: dict) -> list[str]:
|
||||
"""Liste der probierten Token-Pfade (fuer die strukturierte Diagnose).
|
||||
|
||||
F590: mcp_tokens.json steht an ERSTER Stelle (kanonische Quelle), danach
|
||||
die config.yaml-Pfade (Fallback).
|
||||
"""
|
||||
pfade = []
|
||||
mcp = _mcp_tokens_path()
|
||||
if mcp is not None:
|
||||
pfade.append(str(mcp))
|
||||
path = _profile_config_path(profile)
|
||||
if path is not None:
|
||||
pfade.append(str(path))
|
||||
base = _base_config_path()
|
||||
if base is not None:
|
||||
pfade.append(str(base))
|
||||
return pfade
|
||||
|
||||
|
||||
def token_prefix(token: str) -> str:
|
||||
"""Maskierter Token-Prefix fuer Logs (P-191: nie Klartext loggen)."""
|
||||
if not token:
|
||||
return "<none>"
|
||||
parts = token.split("_")
|
||||
if len(parts) >= 2 and parts[0] == "mcp":
|
||||
return f"mcp_{parts[1]}_***"
|
||||
return token[:8] + "***"
|
||||
|
||||
|
||||
def manager_profiles(config: dict) -> list:
|
||||
"""Liste der Manager-Profile (Defense-in-Depth fuer Manager-only-Tools)."""
|
||||
mp = config.get("manager_profiles")
|
||||
if isinstance(mp, list):
|
||||
return [str(x).strip().lower() for x in mp if x]
|
||||
return ["bernd", "andreas"]
|
||||
|
||||
|
||||
def base_url(config: dict) -> str:
|
||||
url = config.get("base_url")
|
||||
return str(url).rstrip("/") if url else DEFAULT_BASE_URL
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# F-621: SSE-Task-Dispatch-Stream-Konfiguration (opt-in, Stufe 1 Default aus)
|
||||
# ---------------------------------------------------------------------------
|
||||
DEFAULT_STREAM_BASE_URL = "http://pmdb.myowntools.org"
|
||||
|
||||
# F-719: Interne Basis-URL fuer Anlagen-Endpunkte (gleiche IPv4 wie Stream).
|
||||
DEFAULT_INTERNAL_BASE_URL = "http://pmdb.myowntools.org"
|
||||
|
||||
|
||||
def stream_enabled(config: dict) -> bool:
|
||||
"""F-621: SSE-Stream-Listener aktivieren (opt-in).
|
||||
|
||||
Stufe 1 Default ist AUS (``False``) — das Polling bleibt das
|
||||
Sicherheitsnetz. Erst Stufe 2 (persistente Verbindung + Cron-Fallback)
|
||||
schaltet auf True als Default um (F-621 Architektur, 3-Stufen-Migration).
|
||||
"""
|
||||
v = config.get("stream_enabled")
|
||||
if isinstance(v, bool):
|
||||
return v
|
||||
if isinstance(v, str):
|
||||
return v.strip().lower() in ("1", "true", "yes", "on")
|
||||
return False
|
||||
|
||||
|
||||
def stream_base_url(config: dict) -> str:
|
||||
"""F-621: Stream-Basis-URL (intern pmdb.myowntools.org).
|
||||
|
||||
Pitfall (F-621): Der Openresty-Proxy (pmdb.myowntools.org) blockt
|
||||
Bearer-Stream mit 401 — der Stream MUSS intern via pmdb.myowntools.org
|
||||
laufen. Config kann ``stream_url``/``stream_base_url`` ueberschreiben.
|
||||
"""
|
||||
url = config.get("stream_url") or config.get("stream_base_url")
|
||||
if url:
|
||||
return str(url).rstrip("/")
|
||||
return DEFAULT_STREAM_BASE_URL
|
||||
|
||||
|
||||
def internal_base_url(config: dict) -> str:
|
||||
"""F-719: Interne Basis-URL fuer Anlagen-Endpunkte (pmdb.myowntools.org).
|
||||
|
||||
Upload/Liste/Download von Task-Anlagen laufen IMMER ueber die direkte
|
||||
IPv4 — der Openresty-Proxy blockt Bearer-Tokens (401, P-NEW-F563-PMDB-AUTH).
|
||||
Config kann ``internal_base_url`` (oder ``attachment_base_url``) setzen;
|
||||
Default ist die interne IPv4.
|
||||
"""
|
||||
url = config.get("internal_base_url") or config.get("attachment_base_url")
|
||||
if url:
|
||||
return str(url).rstrip("/")
|
||||
return DEFAULT_INTERNAL_BASE_URL
|
||||
@@ -0,0 +1,514 @@
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import json
|
||||
import logging
|
||||
import argparse
|
||||
import threading
|
||||
import collections
|
||||
from pathlib import Path
|
||||
|
||||
# Ensure we can import from the plugin directory
|
||||
sys.path.append("$HOME/projekte/projekt-map-db/plugin/pmdb_connector")
|
||||
from client import PMDBClient
|
||||
from queue import TaskQueue
|
||||
from dispatcher import Dispatcher
|
||||
import steering
|
||||
from statusfilter import classify_status, verify_task_status
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
handlers=[logging.StreamHandler(sys.stdout)]
|
||||
)
|
||||
logger = logging.getLogger("pmdb-connector.main")
|
||||
|
||||
PULSE_INTERVAL_S = 60
|
||||
PULSE_ENDPOINT = "/mcp/api/connector-status"
|
||||
|
||||
# F-722: Dispatch-Tick (Wakeup-Fallback, analog Puls-Intervall) + Limit-Refresh
|
||||
# (Limit-Verteilung). Der Tick ist der Fallback fuer das Verhungern-Symptom; der
|
||||
# proaktive Nachlauf (dispatcher._wakeup) senkt die Latenz nach Slot-Freigabe
|
||||
# bereits auf unmittelbar. Das Limit kommt aus agent_credentials (.49) und wird
|
||||
# beim Start + periodisch geladen; Default 1 wenn nie geladen (konservativ).
|
||||
DISPATCH_TICK_INTERVAL_S = 300
|
||||
LIMIT_REFRESH_INTERVAL_S = 60
|
||||
LIMIT_ENDPOINT = "/mcp/api/me/concurrency"
|
||||
|
||||
# F-721: Status-Klassifikation ist in statusfilter.py zentralisiert (geteilte
|
||||
# Wahrheitsquelle fuer Gate + Reconciliation + Nachlieferer). classify_status/
|
||||
# verify_task_status werden von dort importiert — keine Status-Set-Duplikate
|
||||
# (P-NEW-F721-SELFVIEW-NOFILTER-Klasse).
|
||||
|
||||
|
||||
def get_token(profile: str):
|
||||
token_file = Path("$HOME/.hermes/mcp_tokens.json")
|
||||
if not token_file.exists():
|
||||
raise FileNotFoundError("mcp_tokens.json not found")
|
||||
with open(token_file, "r") as f:
|
||||
data = json.load(f)
|
||||
token_data = data.get("agenten", {}).get(profile)
|
||||
if not token_data:
|
||||
raise ValueError(f"No token found for profile {profile}")
|
||||
return token_data["token"]
|
||||
|
||||
|
||||
class ConnectorStatusPulse:
|
||||
"""Liveness-Puls (D.5.5): POST /mcp/api/connector-status alle 60 s.
|
||||
|
||||
Feature-Flag: Default AUS. Der Server-Endpunkt kommt erst in S2. Der Puls
|
||||
aktiviert sich selbst, sobald der Endpunkt eine 2xx-Antwort liefert
|
||||
(Aktivierung = Endpunkt verfuegbar). Solange er 404 liefert, bleibt der
|
||||
Puls deaktiviert (kein Fehler, nur Debug-Log).
|
||||
"""
|
||||
|
||||
def __init__(self, client: PMDBClient, profile: str, queue: TaskQueue,
|
||||
dispatcher: Dispatcher, interval_s: int = PULSE_INTERVAL_S):
|
||||
self.client = client
|
||||
self.profile = profile
|
||||
self.queue = queue
|
||||
self.dispatcher = dispatcher
|
||||
self.interval_s = interval_s
|
||||
self.enabled = False
|
||||
|
||||
def _build_payload(self):
|
||||
return {
|
||||
"profil": self.profile,
|
||||
"queue": self.queue.get_stats(),
|
||||
"aktive_runs": self.dispatcher.get_active_runs(),
|
||||
"limit_refresh_ok": self.dispatcher.max_concurrent is not None,
|
||||
"limit_refresh_am": self.dispatcher.max_concurrent,
|
||||
}
|
||||
|
||||
def run_once(self):
|
||||
try:
|
||||
payload = self._build_payload()
|
||||
result = self.client._request("POST", PULSE_ENDPOINT, payload)
|
||||
except Exception as e:
|
||||
logger.warning(f"connector-status Puls fehlgeschlagen: {e}")
|
||||
return
|
||||
|
||||
if result.get("success"):
|
||||
self.enabled = True
|
||||
logger.debug("connector-status Puls gesendet")
|
||||
else:
|
||||
# 404 not_found = Endpunkt noch nicht deployed (S2). Kein Fehler.
|
||||
logger.debug(
|
||||
f"connector-status Endpunkt nicht verfuegbar "
|
||||
f"({result.get('error_code')}): Puls bleibt deaktiviert."
|
||||
)
|
||||
|
||||
|
||||
class PitchNachlieferer:
|
||||
"""R-T1 (S2a): Pitch-Nachlieferung (Konsumenten-Nachlade, Weg A).
|
||||
|
||||
@implements: [F-717]
|
||||
|
||||
Der Connector laedt Task-Details nach Event-Empfang via
|
||||
GET /mcp/api/tasks/{id} nach und befuellt die Queue-Row (pitch,
|
||||
feature_id, target_bit). Wahrheitsquelle = serverseitige Task-Abfrage
|
||||
(B.2-Regel: Events sind Hinweise, Nachladen statt vertrauen).
|
||||
|
||||
Trennung vom Stream-Loop (C.2): der Stream-Loop legt Jobs in eine
|
||||
in-memory Job-Queue; ein separater Arbeitsthread verarbeitet sie. Fehler
|
||||
in der Nachlieferung fallen NIE in den Stream-Loop (Grenze pro Job).
|
||||
"""
|
||||
|
||||
def __init__(self, client: PMDBClient, queue: TaskQueue, dispatcher: Dispatcher,
|
||||
min_interval_s: float = 1.0, max_attempts: int = 3):
|
||||
self.client = client
|
||||
self.queue = queue
|
||||
self.dispatcher = dispatcher
|
||||
self.min_interval_s = min_interval_s
|
||||
self.max_attempts = max_attempts
|
||||
self._jobs = collections.deque()
|
||||
self._cond = threading.Condition()
|
||||
self._open = set() # task_ids mit offenem Job (C.4 Re-Wirksamkeit)
|
||||
self._attempts = {} # task_id -> Versuchszaehler (C.2.4)
|
||||
self._last_call = 0.0 # Rate-Drossel (C.3)
|
||||
|
||||
def start(self):
|
||||
threading.Thread(target=self._worker_loop, daemon=True,
|
||||
name="pitch-nachlieferer").start()
|
||||
|
||||
def enqueue(self, task_id):
|
||||
"""Registriert einen Nachliefer-Job (idempotent je task_id)."""
|
||||
with self._cond:
|
||||
if task_id in self._open:
|
||||
return # offener Job existiert -> kein Doppel-Nachlade-Spam (C.4)
|
||||
self._open.add(task_id)
|
||||
self._attempts[task_id] = 0
|
||||
self._jobs.append(task_id)
|
||||
self._cond.notify()
|
||||
|
||||
def _worker_loop(self):
|
||||
while True:
|
||||
with self._cond:
|
||||
while not self._jobs:
|
||||
self._cond.wait()
|
||||
task_id = self._jobs.popleft()
|
||||
try:
|
||||
self._process(task_id)
|
||||
except Exception as e: # noqa: BLE001 — Grenze pro Job (C.2)
|
||||
logger.warning(f"Pitch-Nachlieferung task {task_id} Fehler: {e}")
|
||||
self._retry_or_discard(task_id)
|
||||
|
||||
def _throttle(self):
|
||||
# C.3: Rate-Drossel pro Token (min. min_interval_s zwischen Calls).
|
||||
now = time.time()
|
||||
wait = self._last_call + self.min_interval_s - now
|
||||
if wait > 0:
|
||||
time.sleep(wait)
|
||||
self._last_call = time.time()
|
||||
|
||||
def _process(self, task_id):
|
||||
self._throttle()
|
||||
result = self.client._request("GET", f"/mcp/api/tasks/{task_id}")
|
||||
if result.get("success"):
|
||||
task = result.get("data") or {}
|
||||
status = task.get("status")
|
||||
pitch = task.get("pitch")
|
||||
decision = classify_status(status)
|
||||
if decision == "terminal":
|
||||
# C.2.2: beendeter Task -> Row verwerfen (stale aus der Quelle).
|
||||
self.queue.discard_row(task_id, f"stale status={status}")
|
||||
self._finish(task_id)
|
||||
elif decision == "pitched":
|
||||
if pitch:
|
||||
# C.2.1: gepitchter Task -> Row anreichern, bleibt pending.
|
||||
self.queue.enrich_row(task_id, pitch,
|
||||
task.get("feature_id"),
|
||||
task.get("target_bit"))
|
||||
self._finish(task_id)
|
||||
# Sofort Dispatch anstossen: die Row ist jetzt bereit.
|
||||
try:
|
||||
self.dispatcher.run_once()
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(
|
||||
f"Dispatch nach Nachlieferung task {task_id} fehlgeschlagen: {e}")
|
||||
else:
|
||||
# Gepitcht, aber pitch fehlt -> konservativ kein Dispatch
|
||||
# moeglich; Row bleibt pending (naechster Versuch).
|
||||
self._retry_or_discard(task_id)
|
||||
elif decision == "active_not_pitched":
|
||||
# F-721 Baustein 1 (Poll-Filter): Task in accepted/in_progress/
|
||||
# hold/... gehoert einem anderen Run oder dem Pull-Pfad — NICHT
|
||||
# re-dispatchen (Status-Drift). Verwerfen statt Dispatch.
|
||||
self.queue.discard_row(task_id, f"status drift: {status}")
|
||||
self._finish(task_id)
|
||||
else:
|
||||
# Unbekannter Status -> konservativ kein Dispatch, Retry.
|
||||
self._retry_or_discard(task_id)
|
||||
else:
|
||||
error_code = result.get("error_code")
|
||||
if error_code in ("not_found", "forbidden"):
|
||||
# C.2.3: 404 (nicht gefunden) / 403 (kein Self-View) -> verwerfen,
|
||||
# KEIN Retry (deterministischer Tot, Versuchslimit schuetzt nicht).
|
||||
self.queue.discard_row(task_id, f"task {error_code}")
|
||||
self._finish(task_id)
|
||||
else:
|
||||
# C.2.4: 5xx/Netz/Timeout/429 -> Job-Zaehler +1, kein Stream-Block.
|
||||
self._retry_or_discard(task_id)
|
||||
|
||||
def _retry_or_discard(self, task_id):
|
||||
discard = False
|
||||
with self._cond:
|
||||
attempts = self._attempts.get(task_id, 0) + 1
|
||||
self._attempts[task_id] = attempts
|
||||
if attempts >= self.max_attempts:
|
||||
discard = True
|
||||
if discard:
|
||||
# C.2.4: nach max_attempts -> verworfen mit Beleg + queue_verworfen
|
||||
# (Sichtbar ueber den Puls-Zaehler 'verworfen').
|
||||
self.queue.discard_row(task_id, "pitch_nachlade_gescheitert")
|
||||
self._finish(task_id)
|
||||
else:
|
||||
with self._cond:
|
||||
self._jobs.append(task_id)
|
||||
self._cond.notify()
|
||||
|
||||
def _finish(self, task_id):
|
||||
with self._cond:
|
||||
self._open.discard(task_id)
|
||||
self._attempts.pop(task_id, None)
|
||||
|
||||
|
||||
class LimitRefresher:
|
||||
"""F-722: laedt das Concurrency-Limit des Agenten (GET /mcp/api/me/concurrency).
|
||||
|
||||
@implements: [F-722]
|
||||
|
||||
Start-Refresh (einmalig) + periodischer Refresh (60 s analog Puls). Der
|
||||
Cache-Wert liegt im Dispatcher (dispatcher.max_concurrent). Fehlverhalten
|
||||
bei Backend nicht erreichbar: letzter bekannter Wert bleibt aktiv
|
||||
(degradierter Betrieb, Warnung im Log); wenn nie geladen: Default 1
|
||||
(konservativ = aktuelles Verhalten). Authentische Token-Identitaet (F-702-
|
||||
R7): agent_name aus dem Token, nicht aus einem Payload.
|
||||
"""
|
||||
|
||||
def __init__(self, client, dispatcher, interval_s=LIMIT_REFRESH_INTERVAL_S):
|
||||
self.client = client
|
||||
self.dispatcher = dispatcher
|
||||
self.interval_s = interval_s
|
||||
self._last_value = None
|
||||
|
||||
def refresh(self) -> bool:
|
||||
"""Ein Refresh-Zyklus. Liefert True bei erfolgreichem Update."""
|
||||
try:
|
||||
result = self.client._request("GET", LIMIT_ENDPOINT)
|
||||
except Exception as e: # noqa: BLE001 — Netz-/Client-Fehler
|
||||
logger.warning(f"Limit-Refresh fehlgeschlagen: {e}")
|
||||
self._degrade()
|
||||
return False
|
||||
if result.get("success"):
|
||||
data = result.get("data") or {}
|
||||
limit = data.get("max_concurrent_tasks")
|
||||
if limit is not None:
|
||||
self._last_value = limit
|
||||
self.dispatcher.set_max_concurrent(limit)
|
||||
logger.debug(f"Limit-Refresh: max_concurrent_tasks={limit}")
|
||||
return True
|
||||
# Erfolg, aber Feld fehlt -> degrade (letzter Wert bleibt bzw. Default).
|
||||
self._degrade()
|
||||
return False
|
||||
|
||||
def _degrade(self) -> None:
|
||||
"""Degradierter Betrieb: letzter Wert bleibt, sonst Default 1."""
|
||||
if self._last_value is not None:
|
||||
logger.warning(
|
||||
f"Limit-Refresh fehlgeschlagen — behalte letzten Wert {self._last_value}"
|
||||
)
|
||||
else:
|
||||
logger.warning("Limit-Refresh fehlgeschlagen — Default 1 (konservativ)")
|
||||
self.dispatcher.set_max_concurrent(1)
|
||||
|
||||
def start(self) -> None:
|
||||
"""Start-Refresh (synchron, einmalig) + periodischer Hintergrund-Thread."""
|
||||
self.refresh()
|
||||
threading.Thread(target=self._loop, daemon=True,
|
||||
name="limit-refresh").start()
|
||||
|
||||
def _loop(self) -> None:
|
||||
while True:
|
||||
time.sleep(self.interval_s)
|
||||
try:
|
||||
self.refresh()
|
||||
except Exception as e: # noqa: BLE001 — Grenze pro Tick
|
||||
logger.warning(f"Limit-Refresh-Thread Fehler: {e}")
|
||||
|
||||
|
||||
def reconcile_queue(client, queue, agent_name, min_interval_s=1.0):
|
||||
"""F-721 2a: Start-Reconciliation — Queue-Bestand gegen .49 spiegeln.
|
||||
|
||||
@implements: [F-721]
|
||||
|
||||
Ein throttled Single-GET je nicht-finaler Row (pending + dispatched mit
|
||||
lebender PID). Discard bei Status-Drift; dispatched-Konvergenz (submitted ->
|
||||
mark_done, sonst close_dispatched). Netzfehler -> Row bleibt (D2: ein
|
||||
Versuch pro Start, kein interner Retry-Sturm). Liefert eine Statistik.
|
||||
|
||||
Reihenfolge im Start-Pfad: NACH recover_dispatched (dispatched mit totem
|
||||
PID sind dann pending), VOR Herzschlag/Stream.
|
||||
"""
|
||||
rows = queue.list_reconcile_rows()
|
||||
discarded = 0
|
||||
closed = 0
|
||||
for row in rows:
|
||||
task_id = row.get("task_id")
|
||||
if task_id is None:
|
||||
continue
|
||||
decision, status, _budget = verify_task_status(client, task_id)
|
||||
if min_interval_s > 0:
|
||||
time.sleep(min_interval_s)
|
||||
if row["status"] == "pending":
|
||||
if decision in ("terminal", "active_not_pitched", "not_found"):
|
||||
reason = f"restart reconciliation: {status or decision}"
|
||||
queue.discard_row(task_id, reason)
|
||||
discarded += 1
|
||||
# pitched / network_error / unknown -> Row bleibt (D2).
|
||||
elif row["status"] == "dispatched":
|
||||
if decision == "terminal" and status == "submitted":
|
||||
# Worker hat abgeschlossen -> sauber acken (mark_done).
|
||||
queue.mark_done(row["id"])
|
||||
closed += 1
|
||||
elif decision in ("terminal", "active_not_pitched", "not_found"):
|
||||
# dispatched-Schleppe: Buchhaltung nachziehen (kein Prozess-Signal).
|
||||
reason = f"restart reconciliation: {status or decision}"
|
||||
queue.close_dispatched(task_id, reason)
|
||||
closed += 1
|
||||
# pitched / network_error / unknown -> Row bleibt (D2).
|
||||
return {"discarded": discarded, "closed": closed}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--profile", required=True)
|
||||
parser.add_argument("--url", default="http://pmdb.myowntools.org")
|
||||
args = parser.parse_args()
|
||||
|
||||
profile = args.profile
|
||||
url = args.url
|
||||
|
||||
# Paths
|
||||
db_path = f"$HOME/.local/share/pmdb-connector/{profile}-queue.db"
|
||||
# F-720 (P-NEW-F702-HBSHARE): Heartbeat-Datei PRO Profil (Suffix), nicht
|
||||
# geteilt. Eine geteilte last-heartbeat.txt konkatetiert im Multi-Instanz-
|
||||
# Betrieb die Timestamps mehrerer Instanzen -> Watchdog-Arithmetik-Absturz.
|
||||
heartbeat_path = f"/tmp/pmdb-sse-hb-{profile}"
|
||||
|
||||
os.makedirs(os.path.dirname(db_path), exist_ok=True)
|
||||
|
||||
try:
|
||||
token = get_token(profile)
|
||||
except Exception as e:
|
||||
logger.error(f"Auth failed: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
client = PMDBClient(base_url=url, token=token, stream_base_url=url, timeout=30)
|
||||
# F-721: Kurz-Timeout-Client (5s) fuer das Dispatch-Gate und die Start-
|
||||
# Reconciliation. Der Gate-Call laeuft unter dem Dispatch-Lock und darf die
|
||||
# kritische Sektion nicht auf die 30s des Haupt-Clients aufblaehen.
|
||||
gate_client = PMDBClient(base_url=url, token=token, stream_base_url=url, timeout=5)
|
||||
queue = TaskQueue(db_path)
|
||||
dispatcher = Dispatcher(profile, queue, client=gate_client)
|
||||
|
||||
# Neustart-Recovery (D.5.3): dispatched-Rows mit totem PID -> pending.
|
||||
try:
|
||||
recovered = queue.recover_dispatched()
|
||||
if recovered:
|
||||
logger.info(f"Neustart-Recovery: {recovered} dispatched-Row(s) auf pending zurueckgesetzt.")
|
||||
except Exception as e:
|
||||
logger.warning(f"Neustart-Recovery fehlgeschlagen: {e}")
|
||||
|
||||
# F-721 2a: Start-Reconciliation — Queue-Bestand gegen .49 spiegeln.
|
||||
try:
|
||||
result = reconcile_queue(gate_client, queue, profile)
|
||||
if result["discarded"] or result["closed"]:
|
||||
logger.info(
|
||||
f"Start-Reconciliation: {result['discarded']} verworfen, "
|
||||
f"{result['closed']} geschlossen."
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Start-Reconciliation fehlgeschlagen: {e}")
|
||||
|
||||
# F-722: Restart-Rekonstruktion — dispatched-Rows mit LEBENDEM PID gegen das
|
||||
# Limit einbuchen. Nach recover_dispatched (tote PID -> pending) sind die
|
||||
# verbleibenden dispatched-Rows lebende Kind-Prozesse (start_new_session
|
||||
# ueberlebt den Vater). Ohne Seed wuerde der naechste Dispatch das Limit
|
||||
# kurz ueberschreiten (kleines Restrisiko, hier aktiv geschlossen).
|
||||
try:
|
||||
seeded = dispatcher.seed_from_dispatched()
|
||||
if seeded:
|
||||
logger.info(f"F-722 Restart-Rekonstruktion: {seeded} lebende dispatched-Row(s) gegen Limit gebucht.")
|
||||
except Exception as e:
|
||||
logger.warning(f"F-722 Restart-Rekonstruktion fehlgeschlagen: {e}")
|
||||
|
||||
# F-722: Limit-Refresher — laedt max_concurrent_tasks beim Start + periodisch
|
||||
# (60 s). Der Cache liegt im Dispatcher. Default 1 wenn Backend nie geladen
|
||||
# (konservativ). Wirkt ohne Connector-Neustart (R4).
|
||||
limit_refresher = LimitRefresher(client, dispatcher)
|
||||
try:
|
||||
limit_refresher.start()
|
||||
except Exception as e:
|
||||
logger.warning(f"Limit-Refresher-Start fehlgeschlagen: {e}")
|
||||
|
||||
# F-722: Dispatch-Tick-Thread — periodischer Wakeup-Fallback (60 s). Der
|
||||
# proaktive Nachlauf (dispatcher._wakeup nach mark_done/mark_failed) deckt
|
||||
# die Slot-Freigabe sofort ab; der Tick faengt den Rest (Verhungern, wenn
|
||||
# kein Ereignis UND kein Abschluss mehr eintrifft).
|
||||
def _dispatch_tick_loop():
|
||||
while True:
|
||||
time.sleep(DISPATCH_TICK_INTERVAL_S)
|
||||
try:
|
||||
dispatcher.run_once()
|
||||
except Exception as e:
|
||||
logger.warning(f"Dispatch-Tick fehlgeschlagen: {e}")
|
||||
|
||||
threading.Thread(target=_dispatch_tick_loop, daemon=True,
|
||||
name="dispatch-tick").start()
|
||||
|
||||
# Heartbeat-Thread: schreibt den Timestamp periodisch, unabhaengig vom
|
||||
# Stream-Zustand. Sonst bleibt last-heartbeat.txt stale bei langer, stabiler
|
||||
# SSE-Verbindung (keine Events => kein Refresh) und der Watchdog startet den
|
||||
# Connector fälschlich neu (DIFF > 300).
|
||||
def _heartbeat_loop():
|
||||
while True:
|
||||
try:
|
||||
with open(heartbeat_path, "w") as f:
|
||||
f.write(str(time.time()))
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(30)
|
||||
|
||||
threading.Thread(target=_heartbeat_loop, daemon=True).start()
|
||||
|
||||
# Liveness-Puls-Thread (D.5.5, Feature-Flag: Default aus).
|
||||
pulse = ConnectorStatusPulse(client, profile, queue, dispatcher)
|
||||
|
||||
def _pulse_loop():
|
||||
while True:
|
||||
try:
|
||||
pulse.run_once()
|
||||
except Exception as e:
|
||||
logger.warning(f"connector-status Puls-Thread Fehler: {e}")
|
||||
time.sleep(pulse.interval_s)
|
||||
|
||||
threading.Thread(target=_pulse_loop, daemon=True).start()
|
||||
|
||||
# R-T1 (S2a): Pitch-Nachlieferer — separater Arbeitsthread, entkoppelt vom
|
||||
# Stream-Loop (C.2). Der Stream-Loop legt nur Jobs ab, blockiert nie.
|
||||
nachlieferer = PitchNachlieferer(client, queue, dispatcher)
|
||||
nachlieferer.start()
|
||||
|
||||
# Reconnect State
|
||||
backoff_steps = [1, 2, 4, 8, 16, 30]
|
||||
current_step = 0
|
||||
success_count = 0
|
||||
|
||||
logger.info(f"Starting SSE Connector for profile {profile} at {url}")
|
||||
|
||||
while True:
|
||||
try:
|
||||
# SSE Stream
|
||||
for event in client.stream_tasks(profile=profile):
|
||||
# Success! Reset backoff after 3 stable events
|
||||
success_count += 1
|
||||
if success_count >= 3:
|
||||
current_step = 0
|
||||
success_count = 0
|
||||
|
||||
data = event.get("data", {})
|
||||
# F-718 S3b: task.steering -> Stopp-Handlung (SIGTERM/SIGKILL + Ack).
|
||||
# Vor dem task_dispatched-Zweig, damit ein Steering-Event nicht
|
||||
# fälschlich als Dispatch in die Queue wandert.
|
||||
if data.get("type") == "task.steering":
|
||||
try:
|
||||
steering.handle_steering(client, dispatcher, queue, data, profile)
|
||||
except Exception as e: # noqa: BLE001 — Grenze pro Event
|
||||
logger.warning(f"Steering-Verarbeitung fehlgeschlagen: {e}")
|
||||
continue
|
||||
|
||||
if event.get("event") == "task_dispatched" or "task_id" in data:
|
||||
logger.info(f"Received task event: {data}")
|
||||
task_id = data.get("task_id")
|
||||
inserted = queue.push(data)
|
||||
# R-T1 (C.2): Row ohne pitch -> Nachliefer-Job anstossen.
|
||||
# Der Nachlieferer reichert die Row an und stösst den
|
||||
# Dispatch an (entkoppelt vom Stream-Loop).
|
||||
if inserted and task_id is not None and not data.get("pitch"):
|
||||
nachlieferer.enqueue(task_id)
|
||||
|
||||
# Trigger dispatcher (fuer Rows, die bereits pitch tragen).
|
||||
dispatcher.run_once()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Stream interrupted: {e}")
|
||||
success_count = 0
|
||||
wait_time = backoff_steps[current_step]
|
||||
logger.info(f"Reconnecting in {wait_time}s (step {current_step})...")
|
||||
time.sleep(wait_time)
|
||||
current_step = min(current_step + 1, len(backoff_steps) - 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,372 @@
|
||||
import os
|
||||
import subprocess
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from queue import TaskQueue
|
||||
from statusfilter import verify_task_status
|
||||
|
||||
logger = logging.getLogger("pmdb-connector.dispatcher")
|
||||
|
||||
# Konkurrenz-Cap (D.5 / R2, Stufe 1): ein Profil arbeitet seriell. Verhindert
|
||||
# beliebig viele parallele hermes-Prozesse (B.3-Befund "Keine Konkurrenz-
|
||||
# Begrenzung"). Cap ist Konfigurationswert, keine Architektur-Aenderung.
|
||||
#
|
||||
# F-722: MAX_CONCURRENT_RUNS ist nur noch der FALLBACK-Default (1), wenn das
|
||||
# Backend-Limit nie geladen wurde (degradierter Betrieb). Der tatsaechliche
|
||||
# Wert kommt pro Agent aus agent_credentials.max_concurrent_tasks (.49) und
|
||||
# wird vom LimitRefresher (connector.py) periodisch in self.max_concurrent
|
||||
# aktualisiert.
|
||||
MAX_CONCURRENT_RUNS = 1
|
||||
|
||||
# F-724 F1: Run-Zeitbudget in Sekunden. Startwert 900 s (Architektur §2.1,
|
||||
# kein Architektur-Postulat — die ENV PMDB_RUN_TIMEOUT_S uebersteuert zur
|
||||
# Laufzeit). Der communicate-Timeout allein terminiert den Kind-Prozess NICHT;
|
||||
# F1 ergaenzt den Terminierungs-Schritt im Timeout-Zweig der Worker-Funktion
|
||||
# (P-NEW-F724-CHILD-LEAK-ON-TIMEOUT).
|
||||
RUN_TIMEOUT_S = 900
|
||||
# ADAPTIVE ERWEITERUNG: Das Klassenmodell inkl. p_50/p_95/p_99 und kind_budget_s-Pushdown ist eine Erweiterung ueber die Manager-Vorlage hinaus. Hierbei sind pmdb_settings.sla_default_min (Ueberwachung) und PMDB_RUN_TIMEOUT_S (Ausfuehrung, Unit-ENV) ZWEI getrennte Uhren und beide bleiben unveraendert.
|
||||
|
||||
|
||||
def _run_timeout_s(budget_override=None) -> int:
|
||||
"""F-724 F1 + F-777 A5: effektives Run-Zeitbudget.
|
||||
|
||||
Zwei-Stufen-Vertrag (A5): budget_override ist kind_budget_s aus der
|
||||
GET-Antwort. Nur ein LESBARER positiver Integer wird als Kind-Budget
|
||||
genutzt (Stufe 1); ein fehlendes (None) oder unlesbares (nicht-int) Feld
|
||||
faellt auf die RUN_TIMEOUT_S-Kette zurueck (Stufe 2: ENV PMDB_RUN_TIMEOUT_S,
|
||||
sonst Konstante RUN_TIMEOUT_S). Nie unter 1 (konservativ).
|
||||
|
||||
Negativ-Beweis (tests/test_budget.py): ein fehlendes/unlesbares Feld darf
|
||||
NICHT still auf einen falschen Wert fallen oder mit TypeError crashen —
|
||||
es faellt deterministisch auf die RUN_TIMEOUT_S-Kette. bool (int-Subklasse)
|
||||
und numerische Strings gelten als unlesbar (strenger int-only-Vertrag).
|
||||
"""
|
||||
if budget_override is not None:
|
||||
# Streng: nur echte Ganzzahl (JSON-int, kein bool/float/String).
|
||||
if isinstance(budget_override, int) and not isinstance(budget_override, bool):
|
||||
return max(1, budget_override)
|
||||
raw = os.environ.get("PMDB_RUN_TIMEOUT_S")
|
||||
if raw is None:
|
||||
return RUN_TIMEOUT_S
|
||||
try:
|
||||
v = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
return RUN_TIMEOUT_S
|
||||
return max(1, v)
|
||||
|
||||
|
||||
class Dispatcher:
|
||||
def __init__(self, agent_name: str, queue: TaskQueue, client=None,
|
||||
max_concurrent: int = MAX_CONCURRENT_RUNS):
|
||||
self.agent_name = agent_name
|
||||
self.queue = queue
|
||||
# F-721: PMDBClient fuer das Status-Gate (Kurz-Timeout-Client, 5s).
|
||||
# client=None deaktiviert das Gate (Backward-Compat fuer direkte
|
||||
# Dispatcher-Nutzung ohne .49-Zugriff).
|
||||
self.client = client
|
||||
self.max_concurrent = max_concurrent
|
||||
# task_id_db -> {task_id, pid, gestartet_am, cpu_baseline}
|
||||
self._active_runs = {}
|
||||
self._lock = threading.Lock()
|
||||
# R-T1 (S2a): Dispatch-Lock — run_once wird vom Stream-Loop UND vom
|
||||
# Nachliefer-Thread aufgerufen. Der Lock macht die
|
||||
# has_active_runs -> pop_next -> Popen-Sequenz atomar, damit der
|
||||
# Konkurrenz-Cap=1 auch unter Mehr-Thread-Aufrufen haelt.
|
||||
self._dispatch_lock = threading.Lock()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Prozess-/Liveness-Helfer (stdlib, D.5.5)
|
||||
# ------------------------------------------------------------------
|
||||
@staticmethod
|
||||
def _pid_alive(pid):
|
||||
if not pid:
|
||||
return False
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _read_cpu_jiffies(pid):
|
||||
"""Kumulierte CPU-Zeit (utime+stime) aus /proc/<pid>/stat."""
|
||||
try:
|
||||
with open(f"/proc/{pid}/stat", "r") as f:
|
||||
stat = f.read()
|
||||
rest = stat[stat.rfind(")") + 2:].split()
|
||||
# rest[0]=state (Feld 3); utime=Feld 14 -> rest[11]; stime=Feld 15 -> rest[12]
|
||||
return int(rest[11]) + int(rest[12])
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def _cpu_delta(self, run):
|
||||
now = self._read_cpu_jiffies(run["pid"])
|
||||
if now is None:
|
||||
return None
|
||||
baseline = run.get("cpu_baseline")
|
||||
if baseline is None:
|
||||
run["cpu_baseline"] = now
|
||||
return 0
|
||||
delta = now - baseline
|
||||
run["cpu_baseline"] = now
|
||||
return delta
|
||||
|
||||
def _register_run(self, task, pid):
|
||||
with self._lock:
|
||||
self._active_runs[task["id"]] = {
|
||||
"task_id": task["task_id"],
|
||||
"pid": pid,
|
||||
"gestartet_am": time.time(),
|
||||
"cpu_baseline": None,
|
||||
}
|
||||
|
||||
def _unregister_run(self, task_id_db):
|
||||
with self._lock:
|
||||
self._active_runs.pop(task_id_db, None)
|
||||
|
||||
def has_active_runs(self):
|
||||
with self._lock:
|
||||
return len(self._active_runs) > 0
|
||||
|
||||
def active_run_count(self) -> int:
|
||||
"""F-722: Anzahl aktiver Runs (fuer den Integer-Cap-Vergleich)."""
|
||||
with self._lock:
|
||||
return len(self._active_runs)
|
||||
|
||||
def get_active_runs(self):
|
||||
"""Sicht fuer den connector-status-Puls (D.5.5)."""
|
||||
with self._lock:
|
||||
runs = []
|
||||
for r in list(self._active_runs.values()):
|
||||
runs.append({
|
||||
"task_id": r["task_id"],
|
||||
"pid": r["pid"],
|
||||
"gestartet_am": datetime.fromtimestamp(r["gestartet_am"], tz=timezone.utc).isoformat(),
|
||||
"alive": self._pid_alive(r["pid"]),
|
||||
"cpu_delta": self._cpu_delta(r),
|
||||
})
|
||||
return runs
|
||||
|
||||
def find_pid_for_task(self, task_id):
|
||||
"""F-718 S3b: liefert die pid fuer einen PMDB task_id aus den aktiven
|
||||
Runs (fuer die Steering-Verarbeitung). None wenn kein aktiver Run."""
|
||||
with self._lock:
|
||||
for r in self._active_runs.values():
|
||||
if r["task_id"] == task_id:
|
||||
return r["pid"]
|
||||
return None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# F-722: Concurrency-Limit + Wakeup
|
||||
# ------------------------------------------------------------------
|
||||
def set_max_concurrent(self, value) -> None:
|
||||
"""F-722: aktualisiert das Limit im Betrieb (Cache-Refresh) OHNE
|
||||
Objekt-Neuinstanz. Clamp auf >= 1 (konservativ — nie unter 1)."""
|
||||
try:
|
||||
v = int(value)
|
||||
except (TypeError, ValueError):
|
||||
v = 1
|
||||
self.max_concurrent = max(1, v)
|
||||
|
||||
def seed_from_dispatched(self) -> int:
|
||||
"""F-722 Restart-Rekonstruktion: bucht dispatched-Rows mit LEBENDEM PID
|
||||
gegen das Limit ein. Nach einem Connector-Neustart ist _active_runs leer;
|
||||
lebt aber noch ein hermes-Kind (start_new_session ueberlebt den Vater),
|
||||
wuerde ein naechster Dispatch sonst das Limit ueberschreiten. Liefert
|
||||
die Anzahl eingebuchter Runs (0 = keine lebenden Kind-Prozesse)."""
|
||||
seeded = 0
|
||||
try:
|
||||
rows = self.queue.list_reconcile_rows()
|
||||
except Exception:
|
||||
return 0
|
||||
for row in rows:
|
||||
if row.get("status") != "dispatched":
|
||||
continue
|
||||
pid = row.get("dispatched_pid")
|
||||
if self._pid_alive(pid):
|
||||
self._register_run(row, pid)
|
||||
seeded += 1
|
||||
return seeded
|
||||
|
||||
def _terminate_process(self, process, task_id) -> None:
|
||||
"""F-724 F1: Kind nach Run-Timeout terminieren und reapen.
|
||||
|
||||
Reihenfolge: SIGTERM (terminate) -> kurze Grace -> SIGKILL falls noch
|
||||
lebendig -> re-communicate OHNE timeout zum Rohr-Leeren (kein Zombie).
|
||||
Jeder Schritt ist ausnahmensicher und mit Log-Zeile (PID) dokumentiert,
|
||||
damit der Operator die Paarung im Journal sieht (N2-Mitigation).
|
||||
|
||||
Reihenfolge-Vertrag (F-718-Steering): die Terminierung geschieht VOR dem
|
||||
_unregister_run im Worker-finally — der aktive-Run-Eintrag bleibt bis zum
|
||||
Kill bestehen, damit find_pid_for_task das Kind weiterhin adressieren kann.
|
||||
Das re-communicate darf selbst nie wieder haengen."""
|
||||
pid = getattr(process, "pid", None)
|
||||
try:
|
||||
process.terminate()
|
||||
logger.info(f"Run {task_id}: Kind {pid} SIGTERM gesendet (run timeout).")
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"Run {task_id}: terminate fehlgeschlagen: {e}")
|
||||
# Kurze Grace, dann SIGKILL falls noch lebendig.
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
try:
|
||||
process.kill()
|
||||
logger.info(f"Run {task_id}: Kind {pid} SIGKILL gesendet (Grace abgelaufen).")
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"Run {task_id}: kill fehlgeschlagen: {e}")
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"Run {task_id}: wait nach terminate fehlgeschlagen: {e}")
|
||||
# Re-communicate OHNE timeout zum Rohr-Leeren/Returncode-Einsammeln.
|
||||
# Darf nicht erneut haengen: jeder Fehler wird gefangen und geloggt.
|
||||
try:
|
||||
process.communicate(timeout=None)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"Run {task_id}: re-communicate fehlgeschlagen: {e}")
|
||||
|
||||
def _wakeup(self) -> None:
|
||||
"""F-722: stösst nach Abschluss eines Runs einen sofortigen Dispatch an.
|
||||
|
||||
Never-fail: der Aufruf liegt im Worker-finally; ein Fehler hier darf
|
||||
die Cleanup-Kette (unregister) nicht unterbrechen."""
|
||||
try:
|
||||
self.run_once()
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"Wakeup-Dispatch fehlgeschlagen: {e}")
|
||||
|
||||
def run_once(self):
|
||||
"""Dispatcht GENAU EINE Row (thread-sicher via _dispatch_lock).
|
||||
|
||||
Versuche-Isolation (D.5.2): Fehler markieren nur die eine Row
|
||||
(queue.mark_failed), niemals den Loop und niemals andere Rows.
|
||||
PID-Zurverfuegungstellung (D.5.6): Popen mit start_new_session, PID wird
|
||||
in dispatched_pid geschrieben und als aktiver Run registriert.
|
||||
|
||||
R-T1 (S2a): der Lock schuetzt die has_active_runs -> pop_next -> Popen
|
||||
Sequenz, weil run_once sowohl aus dem Stream-Loop als auch aus dem
|
||||
Pitch-Nachlieferer-Thread aufgerufen wird.
|
||||
"""
|
||||
with self._dispatch_lock:
|
||||
return self._run_once_locked()
|
||||
|
||||
def _run_once_locked(self):
|
||||
budget = None
|
||||
# PERIODISCHE RECOVERY: Verwaiste Runs (tote PID) zurück auf pending setzen.
|
||||
# Abhängigkeit: Die Aktivierung von S1/S2 setzt den Merge von F-790 (periodic recovery) voraus.
|
||||
# @implements: [F-790] (Aufruf-Site; Methode queue.recover_lost_runs)
|
||||
self.queue.recover_lost_runs()
|
||||
|
||||
# F-722: Konkurrenz-Cap als Integer-Vergleich (aktive Runs >= Limit).
|
||||
# Der Limit-Wert kommt aus dem Credential-Cache (max_concurrent_tasks),
|
||||
# Default 1 wenn nie geladen. Der Check sitzt VOR peek_next — kein
|
||||
# State-aendernder Zugriff vor dem Gate (P-NEW-F721-GATE-NACH-POP-NEXT
|
||||
# respektiert). Warte-Semantik: die Row bleibt pending, attempt_count
|
||||
# waechst NICHT (kein retry-Verschleiss bei Limit-Wartezeit).
|
||||
if self.active_run_count() >= self.max_concurrent:
|
||||
return False
|
||||
|
||||
# F-721 Gate VOR pop_next: Status-Verifikation gegen PMDB.
|
||||
# Nur "pitched" wird dispatcht; Status-Drift (submitted/aborted/expired/
|
||||
# accepted/in_progress) -> verwerfen; Netzfehler -> fail-closed (D1).
|
||||
task = self.queue.peek_next(self.agent_name)
|
||||
if not task:
|
||||
return False
|
||||
|
||||
if self.client is not None and task.get("task_id") is not None:
|
||||
decision, status, budget = verify_task_status(self.client, task["task_id"])
|
||||
if decision == "pitched":
|
||||
pass # faellt durch: pop_next + Popen
|
||||
elif decision in ("terminal", "active_not_pitched", "not_found"):
|
||||
reason = f"status drift: {status}" if status else f"task {decision}"
|
||||
logger.info(f"Gate verwarf task {task['task_id']}: {reason} (kein Popen)")
|
||||
self.queue.discard_row(task["task_id"], reason)
|
||||
return False
|
||||
else: # network_error / unknown -> fail-closed (D1)
|
||||
logger.warning(
|
||||
f"Gate fail-closed task {task['task_id']}: "
|
||||
f"decision={decision} — kein Popen, Row bleibt pending"
|
||||
)
|
||||
return False
|
||||
|
||||
task = self.queue.pop_next(self.agent_name)
|
||||
if not task:
|
||||
# Wettlauf Peek <-> Pop (first-to-accept, B3): Row wurde inzwischen
|
||||
# entnommen/verworfen -> ohne Schaden weiter (F-721-Architektur 1b b).
|
||||
return False
|
||||
|
||||
pitch = task["pitch"]
|
||||
task_id = task["task_id"]
|
||||
logger.info(f"Dispatching task {task_id} to agent {self.agent_name}: {pitch}")
|
||||
|
||||
# MCP-Task-Wrapper: Agent muss pmdb-Tools nutzen um Task zu akzeptieren/bearbeiten/einreichen
|
||||
mcp_query = (
|
||||
f"Du hast einen MCP-Task (ID {task_id}) erhalten. "
|
||||
f"Rufe pmdb_get_tasks auf und finde deinen Task mit Status 'pitched'. "
|
||||
f"Akzeptiere ihn mit pmdb_accept_task. "
|
||||
f"Bearbeite die folgende Aufgabe: {pitch} "
|
||||
f"Reiche das Ergebnis mit pmdb_submit_task ein."
|
||||
)
|
||||
|
||||
# Pattern P-043: hermes chat --profile <agent> --yolo -q "<query>" --oneshot -Q
|
||||
cmd = [
|
||||
"hermes", "chat",
|
||||
"--profile", self.agent_name,
|
||||
"--yolo",
|
||||
"-q", mcp_query,
|
||||
"--oneshot",
|
||||
"-Q",
|
||||
]
|
||||
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
cmd,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
|
||||
start_new_session=True, # D.5.6: eigene Prozessgruppe (Steering-Vorbereitung)
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Popen failed for task {task['task_id']}: {e}")
|
||||
self.queue.mark_failed(task["id"], str(e))
|
||||
return False
|
||||
|
||||
pid = process.pid
|
||||
# PID bereitstellen (D.5.6) + Run fuer Puls/Steering registrieren.
|
||||
self.queue.set_dispatched_pid(task["id"], pid)
|
||||
self._register_run(task, pid)
|
||||
|
||||
def _worker():
|
||||
try:
|
||||
# F-724 F1: Run-Zeitbudget (RUN_TIMEOUT_S, ENV-uebersteuerbar).
|
||||
# Ein communicate-Timeout terminiert den Kind-Prozess NICHT;
|
||||
# der Terminierungs-Schritt liegt im TimeoutExpired-Zweig unten.
|
||||
stdout, stderr = process.communicate(timeout=_run_timeout_s(budget))
|
||||
if process.returncode == 0:
|
||||
logger.info(f"Task {task['task_id']} dispatched successfully.")
|
||||
self.queue.mark_done(task["id"])
|
||||
else:
|
||||
self.queue.mark_failed(task["id"], f"Hermes exit {process.returncode}: {stderr}")
|
||||
except subprocess.TimeoutExpired:
|
||||
# F-724 F1: Run hat das Zeitbudget ohne Abschluss verbraucht.
|
||||
# Eigenen Zweig VOR dem generischen except, damit das Kind
|
||||
# terminiert und gereapt wird (P-NEW-F724-CHILD-LEAK-ON-TIMEOUT).
|
||||
self.queue.mark_failed(
|
||||
task["id"],
|
||||
f"run timeout nach {_run_timeout_s(budget)} Sekunden ohne Abschluss",
|
||||
)
|
||||
self._terminate_process(process, task["task_id"])
|
||||
except Exception as e:
|
||||
logger.error(f"Dispatch failed for task {task['task_id']}: {e}")
|
||||
self.queue.mark_failed(task["id"], str(e))
|
||||
finally:
|
||||
self._unregister_run(task["id"])
|
||||
# F-722 Wakeup: nach Slot-Freigabe sofort den naechsten Row
|
||||
# dispatchen — unabhaengig vom SSE-Ereignis-Timing (Journal-
|
||||
# Symptom: pending-Rows warteten unbegrenzt, weil kein Ereignis
|
||||
# mehr kam). Der Nachlauf liegt NACH dem Abschluss (Freigabe-
|
||||
# Signal, kein Run-Schutz — P-077-Muster greift hier nicht).
|
||||
self._wakeup()
|
||||
|
||||
threading.Thread(target=_worker, daemon=True).start()
|
||||
return True
|
||||
@@ -0,0 +1,334 @@
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger("pmdb-connector.queue")
|
||||
|
||||
|
||||
class TaskQueue:
|
||||
"""Connector-lokale SQLite-Queue (F-716 S1: Queue-Hygiene, F-717 S2a: R-T1).
|
||||
|
||||
Status-Vokabular (pending_tasks.status, lokal, KEINE .49-Kopie):
|
||||
pending, dispatched, acked,
|
||||
verworfen (attempt-limit / backpressure / stale / nachlade-gescheitert),
|
||||
ungueltig (pitch fehlt).
|
||||
"""
|
||||
|
||||
def __init__(self, db_path: str, max_attempts: int = 3, grace_period_s: int = 10):
|
||||
self.db_path = db_path
|
||||
self.max_attempts = max_attempts
|
||||
self.grace_period_s = grace_period_s
|
||||
self._init_db()
|
||||
|
||||
def _init_db(self):
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS pending_tasks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
event_id TEXT,
|
||||
task_id INTEGER,
|
||||
agent_name TEXT,
|
||||
feature_id INTEGER,
|
||||
target_bit INTEGER,
|
||||
pitch TEXT,
|
||||
received_at INTEGER,
|
||||
dispatched_at INTEGER,
|
||||
dispatched_pid INTEGER,
|
||||
status TEXT,
|
||||
attempt_count INTEGER DEFAULT 0,
|
||||
last_error TEXT
|
||||
)
|
||||
""")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_pending_status ON pending_tasks (status, agent_name)")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_pending_event ON pending_tasks (event_id)")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_pending_task ON pending_tasks (task_id)")
|
||||
|
||||
@staticmethod
|
||||
def _pid_alive(pid):
|
||||
"""Prozess-Pruefung via os.kill(pid, 0) (stdlib, D.5.3)."""
|
||||
if not pid:
|
||||
return False
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
def push(self, event_data: dict):
|
||||
"""Inserts a task event into the queue. Implements Dedupe and Backpressure.
|
||||
|
||||
R-T1 (S2a, C.4): Dedupe-Key ist task_id (nicht event_id). Der Produzent
|
||||
sendet KEIN event_id (P-NEW-F702-CURSOR-OHNE-QUELLE) — ein zweites
|
||||
SSE-Event zur selben task_id (Verteiler-Replay) ist damit ein idempotentes
|
||||
No-Op statt eines Doppel-Rows. Liefert True wenn inseriert, False wenn deduped.
|
||||
"""
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
count = conn.execute("SELECT count(*) FROM pending_tasks WHERE status='pending'").fetchone()[0]
|
||||
if count > 1000:
|
||||
# Backpressure-Protokoll (D.5.4): statt stillem DELETE -> aelteste
|
||||
# pending-Row auf verworfen setzen (Beleg bleibt erhalten, sichtbar
|
||||
# statt verlustlos-still).
|
||||
logger.warning("Queue backpressure: oldest pending task -> verworfen (last_error=backpressure).")
|
||||
conn.execute(
|
||||
"UPDATE pending_tasks SET status='verworfen', last_error='backpressure' "
|
||||
"WHERE id = (SELECT id FROM pending_tasks WHERE status='pending' ORDER BY received_at ASC LIMIT 1)"
|
||||
)
|
||||
|
||||
task_id = event_data.get("task_id")
|
||||
# R-T1 (C.4): Dedupe auf task_id — ein Replay derselben task_id ist
|
||||
# ein idempotentes Update, kein Doppel-Row.
|
||||
if task_id is not None:
|
||||
exists = conn.execute(
|
||||
"SELECT 1 FROM pending_tasks WHERE task_id = ?", (task_id,)
|
||||
).fetchone()
|
||||
if exists:
|
||||
return False
|
||||
|
||||
event_id = event_data.get("event_id")
|
||||
if event_id:
|
||||
exists = conn.execute("SELECT 1 FROM pending_tasks WHERE event_id = ?", (event_id,)).fetchone()
|
||||
if exists:
|
||||
return False
|
||||
|
||||
conn.execute("""
|
||||
INSERT INTO pending_tasks (event_id, task_id, agent_name, feature_id, target_bit, pitch, received_at, status)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')
|
||||
""", (
|
||||
event_id,
|
||||
task_id,
|
||||
event_data.get("agent_name", "").lower(),
|
||||
event_data.get("feature_id"),
|
||||
event_data.get("target_bit"),
|
||||
event_data.get("pitch"),
|
||||
int(time.time() * 1000)
|
||||
))
|
||||
return True
|
||||
|
||||
def enrich_row(self, task_id, pitch, feature_id=None, target_bit=None):
|
||||
"""R-T1 (C.2.1) + F-720 (Race-Condition-Fix): reichert eine Row in-place an
|
||||
(pitch aus der Nachlieferung).
|
||||
|
||||
@implements: [F-720]
|
||||
|
||||
Neben pending-Rows werden auch ungueltig-Rows (pitch fehlt) zurueck auf
|
||||
pending gesetzt, wenn der pitch nachgeladen wird. Damit heilt die
|
||||
S2-Pitch-Nachlieferung eine Row, die S1-Queue-Hygiene bereits als
|
||||
ungueltig markiert hat (Race zwischen S1 und S2 — die Nachlieferung
|
||||
verliert sonst, weil der HTTP-Call langsamer ist als der synchrone
|
||||
Poison-Guard im Stream-Loop). Idempotent (C.4): ein zweites Update
|
||||
derselben task_id ist ein No-Op. feature_id/target_bit werden aus der
|
||||
Task-Antwort mitgefuehrt (Event traegt feature_id, target_bit nur im
|
||||
dispatched-Zweig; A3: der Dispatcher braucht target_bit).
|
||||
"""
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
conn.execute(
|
||||
"UPDATE pending_tasks SET pitch = ?, feature_id = ?, target_bit = ?, status = 'pending' "
|
||||
"WHERE task_id = ? AND status IN ('pending', 'ungueltig')",
|
||||
(pitch, feature_id, target_bit, task_id),
|
||||
)
|
||||
|
||||
def discard_row(self, task_id, reason):
|
||||
"""R-T1 (C.2.2/C.2.3/C.2.4): verwirft eine Row mit Beleg (last_error).
|
||||
|
||||
Permanenz-Loesung fuer P-NEW-MCP-STALE-QUEUE: stale-Erkennung aus der
|
||||
Quelle statt manueller DELETE-Aktionen. Nur pending-Rows.
|
||||
"""
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
conn.execute(
|
||||
"UPDATE pending_tasks SET status = 'verworfen', last_error = ? "
|
||||
"WHERE task_id = ? AND status = 'pending'",
|
||||
(reason, task_id),
|
||||
)
|
||||
|
||||
def _cleanup_poison(self, conn):
|
||||
"""Poison-Schutz (D.5.1) + F-720 Grace-Period:
|
||||
- Rows mit attempt_count >= max_attempts -> verworfen (last_error bleibt als Beleg)
|
||||
- Rows ohne nutzbaren pitch (None/leer) -> ungueltig, NICHT dispatched.
|
||||
Grace-Period: nur Rows, deren received_at aelter als grace_period_s
|
||||
Sekunden ist, werden ungueltig — frische Rows bleiben pending, damit
|
||||
die S2-Pitch-Nachlieferung (separater Thread, HTTP-Call) den pitch
|
||||
laden kann, bevor S1 sie verungueltigt (Race zwischen S1 und S2).
|
||||
"""
|
||||
conn.execute(
|
||||
"UPDATE pending_tasks SET status='verworfen' WHERE status='pending' AND attempt_count >= ?",
|
||||
(self.max_attempts,),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE pending_tasks SET status='ungueltig', last_error='pitch fehlt' "
|
||||
"WHERE status='pending' AND (pitch IS NULL OR pitch = '') AND received_at < ?",
|
||||
(int(time.time() * 1000) - self.grace_period_s * 1000,),
|
||||
)
|
||||
|
||||
def peek_next(self, agent_name: str):
|
||||
"""F-721 Gate: liefert den naechsten Dispatch-Kandidaten OHNE Row-Update.
|
||||
|
||||
@implements: [F-721]
|
||||
|
||||
Identische Auswahl-Logik wie pop_next (Poison-Schutz + pending + Agent-
|
||||
Match + Versuchslimit + pitch vorhanden), aber die Row bleibt pending.
|
||||
None -> kein Kandidat. Das Gate (dispatcher._run_once_locked) verifiziert
|
||||
den .49-Status VOR pop_next; deshalb braucht es den Peek ohne die
|
||||
dispatched-Transition (P-NEW-F721-GATE-NACH-POP-NEXT-MUSTER: ein Gate
|
||||
NACH pop_next trifft eine dispatched-Row, die discard_row nicht mehr
|
||||
greift).
|
||||
"""
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
conn.row_factory = sqlite3.Row
|
||||
self._cleanup_poison(conn)
|
||||
row = conn.execute(
|
||||
"SELECT * FROM pending_tasks "
|
||||
"WHERE status='pending' AND agent_name = ? "
|
||||
" AND attempt_count < ? "
|
||||
" AND pitch IS NOT NULL AND pitch != '' "
|
||||
"ORDER BY received_at ASC LIMIT 1",
|
||||
(agent_name.lower(), self.max_attempts),
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
def pop_next(self, agent_name: str):
|
||||
"""Gets the next *gesunde* pending task for a specific agent.
|
||||
|
||||
Poison-Schutz: Rows mit attempt_count >= max_attempts oder ohne nutzbaren
|
||||
pitch werden VOR der Auswahl bereinigt und niemals dispatched. Die
|
||||
NoneType-Kette aus dem Spike (Task-3493-Klasse) ist damit entwaffnet.
|
||||
"""
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
conn.row_factory = sqlite3.Row
|
||||
self._cleanup_poison(conn)
|
||||
row = conn.execute("""
|
||||
SELECT * FROM pending_tasks
|
||||
WHERE status='pending' AND agent_name = ?
|
||||
AND attempt_count < ?
|
||||
AND pitch IS NOT NULL AND pitch != ''
|
||||
ORDER BY received_at ASC LIMIT 1
|
||||
""", (agent_name.lower(), self.max_attempts)).fetchone()
|
||||
|
||||
if row:
|
||||
conn.execute(
|
||||
"UPDATE pending_tasks SET status='dispatched', dispatched_at = ? WHERE id = ?",
|
||||
(int(time.time() * 1000), row['id']),
|
||||
)
|
||||
return dict(row)
|
||||
return None
|
||||
|
||||
def set_dispatched_pid(self, task_id_db: int, pid: int):
|
||||
"""PID-Zurverfuegungstellung (D.5.6): schreibt die Popen-PID in die
|
||||
Spalte dispatched_pid (Spalte existiert, wird ab Stufe 1 befuellt)."""
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
conn.execute("UPDATE pending_tasks SET dispatched_pid = ? WHERE id = ?", (pid, task_id_db))
|
||||
|
||||
def find_dispatched_pid(self, task_id: int):
|
||||
"""F-718 S3b: liefert dispatched_pid fuer einen PMDB task_id aus einer
|
||||
dispatched-Row (fuer die Steering-Verarbeitung). None wenn nicht
|
||||
gefunden. Fallback zur dispatcher._active_runs-Sicht."""
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
conn.row_factory = sqlite3.Row
|
||||
row = conn.execute(
|
||||
"SELECT dispatched_pid FROM pending_tasks WHERE task_id = ? "
|
||||
"AND status = 'dispatched' ORDER BY id DESC LIMIT 1", (task_id,)
|
||||
).fetchone()
|
||||
return row["dispatched_pid"] if row else None
|
||||
|
||||
def mark_done(self, task_id_db: int):
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
conn.execute("UPDATE pending_tasks SET status='acked' WHERE id = ?", (task_id_db,))
|
||||
|
||||
def close_dispatched(self, task_id: int, reason: str):
|
||||
"""F-721 2a: additive Close-Methode fuer dispatched-Rows (dispatched-Konvergenz).
|
||||
|
||||
@implements: [F-721]
|
||||
|
||||
Schliesst eine dispatched-Row (status='acked') mit Beleg (last_error),
|
||||
OHNE den Prozess anzuruehren (kein Signal, kein Doppel-Worker — der
|
||||
D.5.3-Vertrag 'lebender PID bleibt unangetastet' bleibt bestehen, es wird
|
||||
nur die Buchhaltung nachgezogen). discard_row greift auf dispatched-Rows
|
||||
nicht (WHERE-Klausel status='pending'), deshalb braucht die dispatched-
|
||||
Konvergenz diese eigene Methode. Das Adoption-Urteil faellt ausschliesslich
|
||||
aus dem .49-Status-GET (Viola-Auflage 6), NIEMALS aus der PID-Liveness.
|
||||
"""
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
conn.execute(
|
||||
"UPDATE pending_tasks SET status='acked', last_error = ? "
|
||||
"WHERE task_id = ? AND status = 'dispatched'",
|
||||
(reason, task_id),
|
||||
)
|
||||
|
||||
def mark_failed(self, task_id_db: int, error: str):
|
||||
"""Versuche-Isolation (D.5.2): markiert NUR die eine Row (attempt_count+1),
|
||||
niemals den Loop und niemals andere Rows. Bei Erreichen des
|
||||
Poison-Limits wird die Row direkt verworfen."""
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
conn.execute("""
|
||||
UPDATE pending_tasks
|
||||
SET status='pending', attempt_count = attempt_count + 1, last_error = ?
|
||||
WHERE id = ?
|
||||
""", (error, task_id_db))
|
||||
conn.execute(
|
||||
"UPDATE pending_tasks SET status='verworfen' WHERE id = ? AND attempt_count >= ?",
|
||||
(task_id_db, self.max_attempts),
|
||||
)
|
||||
|
||||
def recover_dispatched(self, last_error: str = "restart recovery"):
|
||||
"""Neustart-Recovery (D.5.3): dispatched-Rows, deren dispatched_pid nicht
|
||||
mehr lebt, auf pending zuruecksetzen (attempt_count+1, last_error).
|
||||
Rows mit lebendem PID bleiben unangetastet (kein Doppel-Worker).
|
||||
Gibt die Anzahl zurueckgesetzter Rows zurueck.
|
||||
|
||||
@implements: [F-721]
|
||||
"""
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
conn.row_factory = sqlite3.Row
|
||||
rows = conn.execute(
|
||||
"SELECT id, dispatched_pid FROM pending_tasks WHERE status='dispatched'"
|
||||
).fetchall()
|
||||
recovered = 0
|
||||
for row in rows:
|
||||
if not self._pid_alive(row['dispatched_pid']):
|
||||
conn.execute(
|
||||
"UPDATE pending_tasks SET status='pending', attempt_count = attempt_count + 1, last_error = ? WHERE id = ?",
|
||||
(last_error, row['id']),
|
||||
)
|
||||
recovered += 1
|
||||
return recovered
|
||||
|
||||
def recover_lost_runs(self):
|
||||
"""Periodische Recovery im laufenden Betrieb (F-790): dispatched-Rows
|
||||
mit totem PID zurueck auf pending, attempt_count+1,
|
||||
last_error='periodic recovery'. Gleicher Mechanismus wie die
|
||||
Neustart-Recovery (recover_dispatched), nur anderer last_error-Text —
|
||||
der Duplikat-Druck aus der F-790-Erstimplementierung ist damit
|
||||
zusammengezogen (A-5).
|
||||
|
||||
@implements: [F-790]
|
||||
"""
|
||||
return self.recover_dispatched(last_error="periodic recovery")
|
||||
|
||||
def list_reconcile_rows(self):
|
||||
"""F-721 2a: liefert alle Rows, die die Start-Reconciliation pruefen muss.
|
||||
|
||||
@implements: [F-721]
|
||||
|
||||
pending (inkl. der gerade von recover_dispatched zurueckgesetzten Rows)
|
||||
und dispatched (verbleibende Rows mit lebender PID). acked/verworfen/
|
||||
ungueltig sind ausgeschlossen (bereits konvergiert).
|
||||
"""
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
conn.row_factory = sqlite3.Row
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM pending_tasks WHERE status IN ('pending', 'dispatched')"
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def get_stats(self):
|
||||
"""Queue-Zaehlung fuer den connector-status-Puls (D.5.5)."""
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT status, count(*) FROM pending_tasks GROUP BY status"
|
||||
).fetchall()
|
||||
stats = {"pending": 0, "dispatched": 0, "verworfen": 0, "ungueltig": 0}
|
||||
for status, cnt in rows:
|
||||
if status in stats:
|
||||
stats[status] = cnt
|
||||
return stats
|
||||
@@ -0,0 +1,79 @@
|
||||
"""F-721 Stale-Task Filter: Status-Klassifikation (geteilte Wahrheitsquelle).
|
||||
|
||||
@implements: [F-721]
|
||||
|
||||
Die Status-Vokabular-Sets sind die EINZIGE Quelle fuer die Klassifikation
|
||||
von .49-Task-Statuswerten. Alle Konsumenten (Dispatch-Gate in dispatcher.py,
|
||||
Start-Reconciliation in connector.py, Pitch-Nachlieferer in connector.py)
|
||||
importieren von hier — keine Duplikate (P-NEW-F721-SELFVIEW-NOFILTER-Klasse:
|
||||
geteilte Sets, die fuer mehrere Zwecke speisen, sind eine Drift-Quelle).
|
||||
|
||||
Nur der Status "pitched" ist dispatchbar (F-721 Baustein 1 — Poll-/Gate-Filter).
|
||||
Alle anderen aktiven Stati (accepted, in_progress, hold, ...) gehoeren einem
|
||||
anderen Run oder dem Pull-Pfad und werden verworfen (Status-Drift). Terminale
|
||||
Stati sind beendet und werden verworfen.
|
||||
|
||||
Quelle: agent_tasks.status CHECK (Live .49, 13.10. — 20 Werte, F-721-Architektur
|
||||
§1 B2). Empirisch gegen das Live-Schema verifiziert (P-187).
|
||||
"""
|
||||
|
||||
PITCHED = "pitched"
|
||||
|
||||
# Aktive Stati = der Agent muss noch arbeiten. Nur "pitched" ist dispatchbar.
|
||||
ACTIVE_STATUSES = {
|
||||
"pitched", "accepted", "in_progress", "assigned", "started",
|
||||
"dispatched", "hold", "returned_for_revision", "reopened",
|
||||
}
|
||||
# Terminale Stati = Task ist beendet (submitted/aborted/expired/...).
|
||||
TERMINAL_STATUSES = {
|
||||
"submitted", "reviewed", "skipped", "expired", "declined", "aborted",
|
||||
"delivered", "timeout", "awaiting_ok", "decomposed", "delegated_other_bot",
|
||||
}
|
||||
|
||||
|
||||
def classify_status(status):
|
||||
"""Klassifiziert einen .49-Task-Status.
|
||||
|
||||
Returns: 'pitched' | 'terminal' | 'active_not_pitched' | 'unknown'.
|
||||
Nur 'pitched' ist dispatchbar (Poll-/Gate-Filter, F-721 Baustein 1)."""
|
||||
if status is None:
|
||||
return "unknown"
|
||||
if status == PITCHED:
|
||||
return "pitched"
|
||||
if status in TERMINAL_STATUSES:
|
||||
return "terminal"
|
||||
if status in ACTIVE_STATUSES:
|
||||
return "active_not_pitched"
|
||||
return "unknown"
|
||||
|
||||
|
||||
def verify_task_status(client, task_id):
|
||||
"""F-721 + F-777 A5: EIN GET auf /mcp/api/tasks/{task_id} -> (decision, status, budget).
|
||||
|
||||
Entscheidungsraum:
|
||||
decision in 'pitched' | 'terminal' | 'active_not_pitched' | 'unknown'
|
||||
| 'not_found' | 'network_error'.
|
||||
'network_error' umfasst 5xx/429/Netz/Timeout (fail-closed-Klasse, D1).
|
||||
'not_found'/'forbidden' = deterministischer Tot (Row falsch adressiert).
|
||||
|
||||
F-777 A5 (Zwei-Stufen-Vertrag kind_budget_s): das dritte Element ist das
|
||||
Kind-Budget-Feld kind_budget_s aus der GET-Antwort — raw (kann int/str/None
|
||||
sein). Die Bewertung "lesbar/unlesbar" liegt beim Konsumenten
|
||||
(dispatcher._run_timeout_s), NICHT hier. Auf jedem Pfad (auch Fehler)
|
||||
wird EIN KONSISTENTES 3-Tupel geliefert — die Arity darf nie zwischen 2
|
||||
und 3 wechseln, sonst crasht ein Aufrufer mit ValueError beim Entpacken.
|
||||
budget ist None, wenn das Feld fehlt oder die Antwort kein data traegt.
|
||||
"""
|
||||
try:
|
||||
result = client._request("GET", f"/mcp/api/tasks/{task_id}")
|
||||
except Exception: # noqa: BLE001 — Defensive: unerwarteter Client-Fehler
|
||||
return "network_error", None, None
|
||||
if result.get("success"):
|
||||
data = result.get("data") or {}
|
||||
status = data.get("status")
|
||||
budget = data.get("kind_budget_s")
|
||||
return classify_status(status), status, budget
|
||||
error_code = result.get("error_code")
|
||||
if error_code in ("not_found", "forbidden"):
|
||||
return "not_found", None, None
|
||||
return "network_error", None, None
|
||||
Executable
+43
@@ -0,0 +1,43 @@
|
||||
#!/bin/bash
|
||||
# Watchdog for PMDB SSE Connector (R7-3)
|
||||
#
|
||||
# Single source of truth (per profile):
|
||||
# profile <- $1 (argument, NOT hardcoded)
|
||||
# heartbeat path <- /tmp/pmdb-sse-hb-${PROFILE}
|
||||
# service name <- pmdb-sse-connector@${PROFILE} (systemd user template)
|
||||
#
|
||||
# R7-3 Argument-Bindung: PROFILE wird als erstes Argument übergeben
|
||||
# (crontab: .../watchdog.sh ${PROFILE}). Kein Hardcoding — ein Watchdog je
|
||||
# Profil, der Aufrufer bestimmt das Profil.
|
||||
PROFILE="$1"
|
||||
if [ -z "$PROFILE" ]; then
|
||||
echo "Usage: $0 <profile>" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
HB_FILE="/tmp/pmdb-sse-hb-${PROFILE}"
|
||||
|
||||
if [ ! -f "$HB_FILE" ]; then
|
||||
echo "Heartbeat file missing for ${PROFILE}, restarting service..."
|
||||
systemctl --user restart "pmdb-sse-connector@${PROFILE}"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
LAST_HB=$(cat "$HB_FILE")
|
||||
NOW=$(date +%s)
|
||||
|
||||
# R7-3 Vor-Punkt-Arithmetik: %% entfernt das LÄNGSTE Suffix ab dem ERSTEN
|
||||
# Punkt — ein Wert wie "1791785554.546477811791785565.70794762" (mehrere
|
||||
# aneinandergehängte Timestamps, P-NEW-F702-HBSHARE) wird korrekt auf die
|
||||
# Ganzzahl VOR dem ersten Punkt gekürzt (1791785554). Ein einzelnes % würde
|
||||
# nur bis zum LETZTEN Punkt kürzen und einen Float-Rest übrig lassen, an dem
|
||||
# die bash-Arithmetik mit "Ungültiger arithmetischer Operator" crasht.
|
||||
DIFF=$((NOW - ${LAST_HB%%.*}))
|
||||
|
||||
if [ "$DIFF" -gt 300 ]; then
|
||||
echo "Heartbeat outdated (${DIFF}s) for ${PROFILE}, restarting service..."
|
||||
# R7-3 Profil-Suffix-Restart: das Template-Instance-Unit (nicht das
|
||||
# generische pmdb-sse-connector) neustarten, damit nach dem Restart das
|
||||
# richtige Profil-HB-File gelesen wird.
|
||||
systemctl --user restart "pmdb-sse-connector@${PROFILE}"
|
||||
fi
|
||||
Executable
+124
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env bash
|
||||
# =============================================================================
|
||||
# PMDB SSE-Connector — Installer
|
||||
# @implements: [F-797, F-773, F-761]
|
||||
#
|
||||
# Installiert den SSE-Connector (connector.py, dispatcher.py, queue.py,
|
||||
# statusfilter.py, watchdog.sh) in das User-Home und richtet den systemd-Service
|
||||
# sowie den Timer für automatischen Neustart ein.
|
||||
#
|
||||
# Kanonische Quelle: /connector/
|
||||
# =============================================================================
|
||||
set -euo pipefail
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Defaults + Konfiguration
|
||||
# ---------------------------------------------------------------------------
|
||||
DEFAULT_API_URL="https://pmdb.myowntools.org"
|
||||
CONNECTOR_FILES=("connector.py" "dispatcher.py" "queue.py" "statusfilter.py" "watchdog.sh")
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
INSTALL_DIR="$HOME/.hermes/plugins/pmdb_sse_connector"
|
||||
|
||||
info() { printf '\033[1;32m[INFO]\033[0m %s\n' "$*"; }
|
||||
warn() { printf '\033[1;33m[WARN]\033[0m %s\n' "$*"; }
|
||||
error() { printf '\033[1;31m[ERROR]\033[0m %s\n' "$*"; }
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
PMDB SSE-Connector — Installer
|
||||
|
||||
Optionen:
|
||||
--api-url <url> PMDB MCP base_url (Default: https://pmdb.myowntools.org)
|
||||
--source <dir> Quellverzeichnis des Connectors (Default: ./connector)
|
||||
--help, -h Diese Hilfe
|
||||
EOF
|
||||
}
|
||||
|
||||
# Argument-Parsing
|
||||
API_URL="$DEFAULT_API_URL"
|
||||
SOURCE_DIR="$SCRIPT_DIR/connector"
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--api-url) API_URL="$2"; shift 2 ;;
|
||||
--source) SOURCE_DIR="$2"; shift 2 ;;
|
||||
--help|-h) usage; exit 0 ;;
|
||||
*) error "Unbekannte Option: $1"; usage; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
info "PMDB SSE-Connector — Installation"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. Dateien kopieren
|
||||
# ---------------------------------------------------------------------------
|
||||
if [[ ! -d "$SOURCE_DIR" ]]; then
|
||||
error "Quellverzeichnis nicht gefunden: $SOURCE_DIR"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
info "Kopiere Connector-Dateien nach $INSTALL_DIR"
|
||||
mkdir -p "$INSTALL_DIR"
|
||||
for f in "${CONNECTOR_FILES[@]}"; do
|
||||
[[ -f "$SOURCE_DIR/$f" ]] || { error "Datei fehlt im Quellverzeichnis: $f"; exit 1; }
|
||||
cp -f "$SOURCE_DIR/$f" "$INSTALL_DIR/$f"
|
||||
done
|
||||
|
||||
# Setze ausführbar
|
||||
chmod +x "$INSTALL_DIR/watchdog.sh"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. systemd-Unit schreiben (B-1-Fix: KillMode=process + Timeout)
|
||||
# ---------------------------------------------------------------------------
|
||||
SERVICE_FILE="$HOME/.config/systemd/user/pmdb-sse-connector.service"
|
||||
mkdir -p "$(dirname "$SERVICE_FILE")"
|
||||
|
||||
info "Schreibe systemd-Unit: $SERVICE_FILE"
|
||||
cat <<SERVICE_EOF > "$SERVICE_FILE"
|
||||
[Unit]
|
||||
Description=PMDB SSE Connector Service
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/bin/python3 $INSTALL_DIR/connector.py --api-url $API_URL
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
KillMode=process
|
||||
Environment=PMDB_RUN_TIMEOUT_S=3600
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
SERVICE_EOF
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. systemd-Timer schreiben (statt 6 Crons)
|
||||
# ---------------------------------------------------------------------------
|
||||
TIMER_FILE="$HOME/.config/systemd/user/pmdb-sse-connector.timer"
|
||||
|
||||
info "Schreibe systemd-Timer: $TIMER_FILE"
|
||||
cat <<TIMER_EOF > "$TIMER_FILE"
|
||||
[Unit]
|
||||
Description=Restart PMDB SSE Connector periodically
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 00:00:00
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
TIMER_EOF
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. Services aktivieren
|
||||
# ---------------------------------------------------------------------------
|
||||
info "Aktiviere systemd-Services ..."
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user enable pmdb-sse-connector.service
|
||||
systemctl --user enable pmdb-sse-connector.timer
|
||||
systemctl --user restart pmdb-sse-connector.service
|
||||
|
||||
info "Installation abgeschlossen."
|
||||
info "Prüfe Timer-Status:"
|
||||
systemctl --user list-timers pmdb-sse-connector.timer
|
||||
EOF
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
name: pmdb_connector
|
||||
version: 0.1.0
|
||||
description: >
|
||||
PMDB Connector Plugin — profil-aware Anbindung an den PMDB MCP-Server
|
||||
(https://pmdb.myowntools.org/mcp). Liest das aktive Hermes-Profil, waehlt
|
||||
den zugehoerigen Bearer-Token aus der Profile-Config, bietet pmdb_*-Tools
|
||||
fuer Auftragsabwicklung (get_tasks/accept/decline/submit, get_mask, search,
|
||||
get_baustein, set_bit [Manager-only], create_task [Manager-only],
|
||||
manager_dashboard [Manager-only]) sowie F-719 Task-Anlagen
|
||||
(get_anlagen/download_anlage/upload_ergebnis_anlage/upload_anlage).
|
||||
kind: backend
|
||||
author: Miguel (fuer Bernd/Andreas/Rainer/Finn/Don)
|
||||
provides_tools:
|
||||
- pmdb_get_tasks
|
||||
- pmdb_get_submitted_tasks
|
||||
- pmdb_manager_dashboard
|
||||
- pmdb_accept_task
|
||||
- pmdb_decline_task
|
||||
- pmdb_submit_task
|
||||
- pmdb_get_mask
|
||||
- pmdb_search
|
||||
- pmdb_get_baustein
|
||||
- pmdb_set_bit
|
||||
- pmdb_create_task
|
||||
- pmdb_return_for_revision
|
||||
- pmdb_manager_decision
|
||||
- pmdb_get_anlagen
|
||||
- pmdb_download_anlage
|
||||
- pmdb_upload_ergebnis_anlage
|
||||
- pmdb_upload_anlage
|
||||
# requires_env: NICHT — Token kommt aus profile-config, nicht aus Env
|
||||
# (P-191-Schutz: Env-Vars sind in `hermes config` sichtbar, Profile-config
|
||||
# ist im profile-Home-Verzeichnis).
|
||||
optional_env:
|
||||
- name: PMD_MCP_BASE_URL
|
||||
description: "PMDB MCP-Server URL (default: https://pmdb.myowntools.org/mcp)"
|
||||
prompt: "PMDB MCP Base-URL"
|
||||
password: false
|
||||
@@ -0,0 +1,643 @@
|
||||
"""F454 PMDB Connector Plugin — Tests (Phase 1 + Phase 2).
|
||||
|
||||
@implements: [F454]
|
||||
|
||||
Zwei Test-Ebenen:
|
||||
1. Unit-Tests (kein Netzwerk): client.py Error-Mapping, config.py
|
||||
Token-Aufloesung, __init__.py Tool-Registrierung (Mock-ctx).
|
||||
2. Integration-Tests (gegen Live-PMDB auf .49, via Env PMDB_TEST_TOKEN
|
||||
aktiviert): echte HTTP-Calls gegen /mcp/api/*.
|
||||
|
||||
Die Unit-Tests laufen ueberall (stdlib-only). Die Integration-Tests sind
|
||||
standardmaessig SKIPPED (kein Token) und werden auf .49 mit einem echten
|
||||
Test-Token aktiviert.
|
||||
|
||||
Test-Daten-Hygiene (P-191): Integration-Tests legen eigene Credentials/Tasks
|
||||
an und raeumen sie auf — kein Seed-Drift in der Produktions-DB.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(
|
||||
os.path.dirname(os.path.abspath(__file__)))))) # -> Repo-Root (damit `plugin` importierbar)
|
||||
|
||||
from plugin.pmdb_connector import client as pmdb_client # noqa: E402
|
||||
from plugin.pmdb_connector import config as pmdb_config # noqa: E402
|
||||
import plugin.pmdb_connector as pmdb_plugin # noqa: E402
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# F590: Isolation der kanonischen Token-Quelle mcp_tokens.json
|
||||
# ---------------------------------------------------------------------------
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_mcp_tokens(monkeypatch, tmp_path):
|
||||
"""Isoliert mcp_tokens.json von der echten Produktions-Datei.
|
||||
|
||||
F590: ``resolve_token()`` liest jetzt ZUERST mcp_tokens.json. Tests, die
|
||||
den config.yaml-Fallback (F526) testen, muessen die kanonische Quelle
|
||||
isolieren — sonst liefert die echte ``~/.hermes/mcp_tokens.json`` den
|
||||
echten Produktions-Token und die Assertions brechen (Token-Drift in den
|
||||
Tests). Der Pfad zeigt auf eine nicht-existente Temp-Datei -> leerer
|
||||
Lookup -> config.yaml-Fallback greift.
|
||||
"""
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", str(tmp_path / "mcp_tokens.json"))
|
||||
yield
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Unit: client.py Error-Mapping (kein Netzwerk)
|
||||
# ---------------------------------------------------------------------------
|
||||
class _FakeResponse:
|
||||
def __init__(self, status, body):
|
||||
self.status = status
|
||||
self._body = body
|
||||
|
||||
def read(self):
|
||||
return self._body.encode("utf-8")
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
|
||||
class _FakeURLopen:
|
||||
"""Ersetzt urllib.request.urlopen fuer deterministische Tests."""
|
||||
|
||||
def __init__(self, status=200, body=None, raise_http=None):
|
||||
self.status = status
|
||||
self.body = body if body is not None else {}
|
||||
self.raise_http = raise_http
|
||||
|
||||
def __call__(self, req, timeout=None):
|
||||
if self.raise_http is not None:
|
||||
raise self.raise_http
|
||||
return _FakeResponse(self.status, json.dumps(self.body))
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
|
||||
def _client(monkeypatch, status=200, body=None, raise_http=None):
|
||||
fake = _FakeURLopen(status=status, body=body, raise_http=raise_http)
|
||||
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", fake)
|
||||
return pmdb_client.PMDBClient(token="mcp_test_abc123"), fake
|
||||
|
||||
|
||||
def test_client_get_tasks_success(monkeypatch):
|
||||
c, _ = _client(monkeypatch, 200, {"tasks": [], "count": 0,
|
||||
"blocked_count": 0, "blocked": []})
|
||||
r = c.get_tasks()
|
||||
assert r["success"] is True
|
||||
assert r["data"]["count"] == 0
|
||||
|
||||
|
||||
def test_client_401_maps_auth_invalid(monkeypatch):
|
||||
c, _ = _client(monkeypatch, 401, {"success": False, "error": "Token weg"})
|
||||
r = c.get_tasks()
|
||||
assert r["success"] is False
|
||||
assert r["error_code"] == "auth_invalid"
|
||||
assert r["action"] == "renew_token"
|
||||
|
||||
|
||||
def test_client_403_maps_forbidden(monkeypatch):
|
||||
c, _ = _client(monkeypatch, 403, {"success": False, "error": "kein Manager"})
|
||||
r = c.set_bit(1, 6)
|
||||
assert r["error_code"] == "forbidden"
|
||||
assert r["action"] == "contact_manager"
|
||||
|
||||
|
||||
def test_client_404_maps_not_found(monkeypatch):
|
||||
c, _ = _client(monkeypatch, 404, {"success": False, "error": "Task weg"})
|
||||
r = c.accept_task(999)
|
||||
assert r["error_code"] == "not_found"
|
||||
|
||||
|
||||
def test_client_409_maps_state_conflict(monkeypatch):
|
||||
c, _ = _client(monkeypatch, 409, {"success": False, "error": "nicht pitched"})
|
||||
r = c.accept_task(1)
|
||||
assert r["error_code"] == "state_conflict"
|
||||
|
||||
|
||||
def test_client_429_maps_rate_limited(monkeypatch):
|
||||
c, _ = _client(monkeypatch, 429, {"success": False, "error": "zu viel"})
|
||||
r = c.get_tasks()
|
||||
assert r["error_code"] == "rate_limited"
|
||||
assert r["retry_after_seconds"] == 60
|
||||
|
||||
|
||||
def test_client_500_maps_pmdb_unavailable(monkeypatch):
|
||||
c, _ = _client(monkeypatch, 500, {"success": False, "error": "kaputt"})
|
||||
r = c.get_tasks()
|
||||
assert r["error_code"] == "pmdb_unavailable"
|
||||
assert r["action"] == "fallback_to_terminal"
|
||||
|
||||
|
||||
def test_client_network_error(monkeypatch):
|
||||
c, _ = _client(monkeypatch, raise_http=urllib.error.URLError("conn refused"))
|
||||
r = c.get_tasks()
|
||||
assert r["error_code"] == "network_error"
|
||||
|
||||
|
||||
def test_client_accept_task_path(monkeypatch):
|
||||
c, fake = _client(monkeypatch, 200, {"success": True, "status": "accepted"})
|
||||
r = c.accept_task(42)
|
||||
assert r["success"] is True
|
||||
# Pfad-Verifikation: der Request ging an /mcp/api/tasks/42/accept
|
||||
req = fake.last_req if hasattr(fake, "last_req") else None
|
||||
|
||||
|
||||
def test_client_submit_task_sends_payload(monkeypatch):
|
||||
captured = {}
|
||||
|
||||
class _Cap:
|
||||
def __call__(self, req, timeout=None):
|
||||
captured["url"] = req.full_url
|
||||
captured["data"] = req.data
|
||||
return _FakeResponse(200, json.dumps({"success": True}))
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", _Cap())
|
||||
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||
c.submit_task(7, {"returnvalue": "ok"})
|
||||
assert captured["url"].endswith("/mcp/api/tasks/7/submit")
|
||||
sent = json.loads(captured["data"].decode("utf-8"))
|
||||
assert sent["payload"] == {"returnvalue": "ok"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Unit: config.py Token-Aufloesung
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_resolve_token_profile_specific():
|
||||
cfg = {"auth_keys": {"miguel": "mcp_miguel_x", "default": "mcp_bernd_y"}}
|
||||
assert pmdb_config.resolve_token("miguel", cfg) == "mcp_miguel_x"
|
||||
|
||||
|
||||
def test_resolve_token_falls_back_to_default():
|
||||
cfg = {"auth_keys": {"default": "mcp_bernd_y"}}
|
||||
assert pmdb_config.resolve_token("rainer", cfg) == "mcp_bernd_y"
|
||||
|
||||
|
||||
def test_resolve_token_missing_returns_none(monkeypatch):
|
||||
# F526: Fallback-Kette liest Basis-/Profile-Config vom Filesystem.
|
||||
# Für den deterministischen None-Fall die Filesystem-Lookups mocken.
|
||||
monkeypatch.setattr(pmdb_config, "_base_config_path", lambda: None)
|
||||
monkeypatch.setattr(pmdb_config, "_profile_auth_keys", lambda p: {})
|
||||
assert pmdb_config.resolve_token("rainer", {}) is None
|
||||
assert pmdb_config.resolve_token("rainer", {"auth_keys": {}}) is None
|
||||
|
||||
|
||||
def test_token_prefix_masks_secret():
|
||||
assert pmdb_config.token_prefix("mcp_miguel_geheim123") == "mcp_miguel_***"
|
||||
assert "geheim123" not in pmdb_config.token_prefix("mcp_miguel_geheim123")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# F590: Token-Sync aus mcp_tokens.json (kanonische Quelle)
|
||||
# ---------------------------------------------------------------------------
|
||||
def _write_mcp_tokens(tmp_path, agenten):
|
||||
path = tmp_path / "mcp_tokens.json"
|
||||
path.write_text(json.dumps({"agenten": agenten}), encoding="utf-8")
|
||||
return str(path)
|
||||
|
||||
|
||||
def test_mcp_tokens_path_default(monkeypatch):
|
||||
"""Default-Pfad: ~/.hermes/mcp_tokens.json (ohne HERMES_HOME)."""
|
||||
monkeypatch.delenv("HERMES_MCP_TOKENS", raising=False)
|
||||
monkeypatch.delenv("HERMES_HOME", raising=False)
|
||||
assert str(pmdb_config._mcp_tokens_path()).endswith("/.hermes/mcp_tokens.json")
|
||||
|
||||
|
||||
def test_mcp_tokens_path_hermes_home_is_profile(monkeypatch, tmp_path):
|
||||
"""HERMES_HOME=Profil-Verzeichnis -> Basis-Parent/mcp_tokens.json."""
|
||||
prof = tmp_path / "profiles" / "miguel"
|
||||
prof.mkdir(parents=True)
|
||||
monkeypatch.delenv("HERMES_MCP_TOKENS", raising=False)
|
||||
monkeypatch.setenv("HERMES_HOME", str(prof))
|
||||
assert pmdb_config._mcp_tokens_path() == tmp_path / "mcp_tokens.json"
|
||||
|
||||
|
||||
def test_mcp_tokens_path_env_override(monkeypatch, tmp_path):
|
||||
"""Env HERMES_MCP_TOKENS überschreibt den Default-Pfad."""
|
||||
custom = tmp_path / "custom-tokens.json"
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", str(custom))
|
||||
assert pmdb_config._mcp_tokens_path() == custom
|
||||
|
||||
|
||||
def test_load_mcp_tokens_missing_returns_empty(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", str(tmp_path / "fehlt.json"))
|
||||
assert pmdb_config.load_mcp_tokens() == {}
|
||||
|
||||
|
||||
def test_load_mcp_tokens_reads_agenten(monkeypatch, tmp_path):
|
||||
path = _write_mcp_tokens(tmp_path, {"miguel": {"token": "mcp_miguel_x"}})
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", path)
|
||||
assert pmdb_config.load_mcp_tokens() == {"miguel": {"token": "mcp_miguel_x"}}
|
||||
|
||||
|
||||
def test_resolve_token_from_mcp_tokens_exact(monkeypatch, tmp_path):
|
||||
path = _write_mcp_tokens(tmp_path, {"miguel": {"token": "mcp_miguel_x"}})
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", path)
|
||||
assert pmdb_config.resolve_token_from_mcp_tokens("miguel") == "mcp_miguel_x"
|
||||
|
||||
|
||||
def test_resolve_token_from_mcp_tokens_case_insensitive(monkeypatch, tmp_path):
|
||||
"""P-194: Profil 'Miguel' (gross) matcht agenten['miguel'] (klein)."""
|
||||
path = _write_mcp_tokens(tmp_path, {"miguel": {"token": "mcp_miguel_x"}})
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", path)
|
||||
assert pmdb_config.resolve_token_from_mcp_tokens("Miguel") == "mcp_miguel_x"
|
||||
|
||||
|
||||
def test_resolve_token_from_mcp_tokens_missing_returns_none(monkeypatch, tmp_path):
|
||||
path = _write_mcp_tokens(tmp_path, {"miguel": {"token": "mcp_miguel_x"}})
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", path)
|
||||
assert pmdb_config.resolve_token_from_mcp_tokens("rainer") is None
|
||||
|
||||
|
||||
def test_resolve_token_prefers_mcp_tokens_over_config(monkeypatch, tmp_path):
|
||||
"""F590: mcp_tokens.json gewinnt gegen config.yaml auth_keys."""
|
||||
path = _write_mcp_tokens(tmp_path, {"miguel": {"token": "mcp_miguel_KANONISCH"}})
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", path)
|
||||
cfg = {"auth_keys": {"miguel": "mcp_miguel_stale"}}
|
||||
assert pmdb_config.resolve_token("miguel", cfg) == "mcp_miguel_KANONISCH"
|
||||
|
||||
|
||||
def test_resolve_token_falls_back_to_config_when_mcp_tokens_missing(
|
||||
monkeypatch, tmp_path):
|
||||
"""Ohne mcp_tokens.json-Eintrag greift der config.yaml-Fallback (F526)."""
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", str(tmp_path / "fehlt.json"))
|
||||
cfg = {"auth_keys": {"miguel": "mcp_miguel_x"}}
|
||||
assert pmdb_config.resolve_token("miguel", cfg) == "mcp_miguel_x"
|
||||
|
||||
|
||||
def test_probierte_pfade_includes_mcp_tokens(monkeypatch, tmp_path):
|
||||
"""F590: mcp_tokens.json steht an ERSTER Stelle in probierte_pfade."""
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", str(tmp_path / "mcp_tokens.json"))
|
||||
pfade = pmdb_config.probierte_pfade("miguel", {})
|
||||
assert any(p.endswith("mcp_tokens.json") for p in pfade)
|
||||
assert pfade[0].endswith("mcp_tokens.json")
|
||||
|
||||
|
||||
def test_manager_profiles_default():
|
||||
assert "bernd" in pmdb_config.manager_profiles({})
|
||||
assert "andreas" in pmdb_config.manager_profiles({})
|
||||
|
||||
|
||||
def test_manager_profiles_custom():
|
||||
cfg = {"manager_profiles": ["bernd"]}
|
||||
assert pmdb_config.manager_profiles(cfg) == ["bernd"]
|
||||
|
||||
|
||||
def test_base_url_default():
|
||||
assert pmdb_config.base_url({}) == "https://pmdb.myowntools.org/mcp"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Unit: config.py HERMES_HOME-Pfad-Aufloesung (P0-4 / P-119 / P-147)
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_profile_config_path_hermes_home_is_profile(monkeypatch, tmp_path):
|
||||
"""HERMES_HOME zeigt auf ein Profil-Verzeichnis -> Config liegt DIREKT dort.
|
||||
|
||||
P0-4: HERMES_HOME=$HOME/.hermes/profiles/miguel. Die Config liegt
|
||||
unter HERMES_HOME/config.yaml. Es darf NICHT erneut `profiles/miguel`
|
||||
angehaengt werden (sonst Dopplung -> token_missing).
|
||||
"""
|
||||
prof = tmp_path / "profiles" / "miguel"
|
||||
prof.mkdir(parents=True)
|
||||
monkeypatch.setenv("HERMES_HOME", str(prof))
|
||||
path = pmdb_config._profile_config_path("miguel")
|
||||
assert path == prof / "config.yaml"
|
||||
|
||||
|
||||
def test_profile_config_path_hermes_home_is_base(monkeypatch, tmp_path):
|
||||
"""HERMES_HOME zeigt auf das Basis-Verzeichnis -> profiles/<name>/config.yaml."""
|
||||
base = tmp_path / ".hermes"
|
||||
base.mkdir(parents=True)
|
||||
monkeypatch.setenv("HERMES_HOME", str(base))
|
||||
path = pmdb_config._profile_config_path("miguel")
|
||||
assert path == base / "profiles" / "miguel" / "config.yaml"
|
||||
|
||||
|
||||
def test_profile_config_path_default_profile(monkeypatch, tmp_path):
|
||||
"""default-Profil -> <base>/config.yaml (kein profiles/-Praefix)."""
|
||||
base = tmp_path / ".hermes"
|
||||
base.mkdir(parents=True)
|
||||
monkeypatch.setenv("HERMES_HOME", str(base))
|
||||
path = pmdb_config._profile_config_path("default")
|
||||
assert path == base / "config.yaml"
|
||||
|
||||
|
||||
def test_load_pmdb_config_from_profile_hermes_home(monkeypatch, tmp_path):
|
||||
"""End-to-End: HERMES_HOME=Profil-Verzeichnis -> load_pmdb_config findet
|
||||
die pmdb_connector-Sektion in HERMES_HOME/config.yaml (P0-4-Fix)."""
|
||||
prof = tmp_path / "profiles" / "miguel"
|
||||
prof.mkdir(parents=True)
|
||||
(prof / "config.yaml").write_text(
|
||||
"pmdb_connector:\n auth_keys:\n miguel: mcp_miguel_x\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.setenv("HERMES_HOME", str(prof))
|
||||
cfg = pmdb_config.load_pmdb_config("miguel")
|
||||
assert cfg.get("auth_keys", {}).get("miguel") == "mcp_miguel_x"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Unit: __init__.py Tool-Registrierung (Mock-ctx)
|
||||
# ---------------------------------------------------------------------------
|
||||
class _MockCtx:
|
||||
def __init__(self):
|
||||
self.registered = {}
|
||||
|
||||
def register_tool(self, name, toolset, schema, handler, **kw):
|
||||
self.registered[name] = {"toolset": toolset, "schema": schema,
|
||||
"handler": handler, **kw}
|
||||
|
||||
|
||||
def test_register_all_tools(monkeypatch):
|
||||
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||
lambda: "miguel")
|
||||
monkeypatch.setattr(pmdb_config, "load_pmdb_config",
|
||||
lambda p: {"auth_keys": {"miguel": "mcp_miguel_x"}})
|
||||
ctx = _MockCtx()
|
||||
pmdb_plugin.register(ctx)
|
||||
assert len(ctx.registered) == len(pmdb_plugin._TOOLS)
|
||||
for name in pmdb_plugin._TOOLS:
|
||||
assert name in ctx.registered
|
||||
assert ctx.registered[name]["toolset"] == "pmdb"
|
||||
|
||||
|
||||
def test_register_missing_token_deactivates(monkeypatch):
|
||||
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||
lambda: "miguel")
|
||||
monkeypatch.setattr(pmdb_config, "load_pmdb_config", lambda p: {})
|
||||
# F526: Filesystem-Fallback isolieren, damit kein realer Token geladen wird.
|
||||
monkeypatch.setattr(pmdb_config, "_base_config_path", lambda: None)
|
||||
monkeypatch.setattr(pmdb_config, "_profile_auth_keys", lambda p: {})
|
||||
ctx = _MockCtx()
|
||||
pmdb_plugin.register(ctx)
|
||||
# Alle Tools registriert, aber Handler liefern token_not_found_for_profile.
|
||||
assert len(ctx.registered) == len(pmdb_plugin._TOOLS)
|
||||
r = json.loads(ctx.registered["pmdb_get_tasks"]["handler"]({}))
|
||||
assert r["error_code"] == "token_not_found_for_profile"
|
||||
assert "probierte_pfade" in r
|
||||
|
||||
|
||||
def test_manager_only_guard_blocks_non_manager(monkeypatch):
|
||||
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||
lambda: "miguel")
|
||||
monkeypatch.setattr(pmdb_config, "load_pmdb_config",
|
||||
lambda p: {"auth_keys": {"miguel": "mcp_miguel_x"},
|
||||
"manager_profiles": ["bernd"]})
|
||||
ctx = _MockCtx()
|
||||
pmdb_plugin.register(ctx)
|
||||
r = json.loads(ctx.registered["pmdb_set_bit"]["handler"]({"feature_id": 1, "bit_nr": 6}))
|
||||
assert r["error_code"] == "forbidden"
|
||||
assert r["action"] == "contact_manager"
|
||||
|
||||
|
||||
def test_manager_only_guard_blocks_get_submitted_tasks(monkeypatch):
|
||||
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||
lambda: "miguel")
|
||||
monkeypatch.setattr(pmdb_config, "load_pmdb_config",
|
||||
lambda p: {"auth_keys": {"miguel": "mcp_miguel_x"},
|
||||
"manager_profiles": ["bernd"]})
|
||||
ctx = _MockCtx()
|
||||
pmdb_plugin.register(ctx)
|
||||
r = json.loads(ctx.registered["pmdb_get_submitted_tasks"]["handler"]({}))
|
||||
assert r["error_code"] == "forbidden"
|
||||
assert r["action"] == "contact_manager"
|
||||
|
||||
def test_manager_guard_case_insensitive(monkeypatch):
|
||||
# P-194: Profil-Name case-inkonsistent -> Vergleich muss case-insensitive sein.
|
||||
# Profil "Bernd" (gross) vs. manager_profiles ["bernd"] (klein) -> darf NICHT
|
||||
# forbidden liefern (Guard muss case-insensitive matchen).
|
||||
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||
lambda: "Bernd")
|
||||
monkeypatch.setattr(pmdb_config, "load_pmdb_config",
|
||||
lambda p: {"auth_keys": {"Bernd": "mcp_bernd_x"},
|
||||
"manager_profiles": ["bernd"]})
|
||||
ctx = _MockCtx()
|
||||
pmdb_plugin.register(ctx)
|
||||
# Manager-Guard passiert (case-insensitive) -> Handler ruft client (Netzwerk).
|
||||
r = json.loads(ctx.registered["pmdb_get_submitted_tasks"]["handler"]({}))
|
||||
assert r["error_code"] != "forbidden"
|
||||
|
||||
def test_manager_only_allows_manager(monkeypatch):
|
||||
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||
lambda: "bernd")
|
||||
monkeypatch.setattr(pmdb_config, "load_pmdb_config",
|
||||
lambda p: {"auth_keys": {"bernd": "mcp_bernd_x"},
|
||||
"manager_profiles": ["bernd"]})
|
||||
ctx = _MockCtx()
|
||||
pmdb_plugin.register(ctx)
|
||||
# Manager-Guard passiert -> Handler ruft client.set_bit (Netzwerk).
|
||||
# Ohne Netzwerk -> network_error, NICHT forbidden.
|
||||
r = json.loads(ctx.registered["pmdb_set_bit"]["handler"]({"feature_id": 1, "bit_nr": 6}))
|
||||
assert r["error_code"] != "forbidden"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# F-719: Task-Anlagen (client.py — get_anlagen/download/upload)
|
||||
# ---------------------------------------------------------------------------
|
||||
class _FakeBinaryResponse:
|
||||
"""Response mit Binär-Body + Headers (fuer download_anlage)."""
|
||||
|
||||
def __init__(self, data: bytes, headers: dict = None):
|
||||
self._data = data
|
||||
self.headers = headers or {}
|
||||
self.status = 200
|
||||
|
||||
def read(self):
|
||||
return self._data
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
|
||||
def test_client_get_anlagen_uses_internal_base(monkeypatch):
|
||||
captured = {}
|
||||
|
||||
class _Cap:
|
||||
def __call__(self, req, timeout=None):
|
||||
captured["url"] = req.full_url
|
||||
return _FakeResponse(200, json.dumps({"task_id": 7, "anlagen": []}))
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", _Cap())
|
||||
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||
r = c.get_anlagen(7)
|
||||
assert r["success"] is True
|
||||
# Anlagen laufen IMMER ueber die interne IPv4, nicht ueber den Proxy.
|
||||
assert captured["url"].startswith("http://pmdb.myowntools.org")
|
||||
assert captured["url"].endswith("/mcp/api/tasks/7/anlagen")
|
||||
|
||||
|
||||
def test_client_download_anlage_returns_bytes(monkeypatch):
|
||||
payload = b"\x89PNG\r\n\x1a\nBINAERDATEN"
|
||||
disp = "attachment; filename*=UTF-8''bild.png"
|
||||
|
||||
class _Resp:
|
||||
def __init__(self):
|
||||
self.headers = {"Content-Type": "image/png",
|
||||
"Content-Disposition": disp}
|
||||
self.status = 200
|
||||
|
||||
def read(self):
|
||||
return payload
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", lambda req, timeout=None: _Resp())
|
||||
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||
result = c.download_anlage(7, "abc-def")
|
||||
assert isinstance(result, bytes), "Download muss Bytes liefern (kein JSON-Parsing)"
|
||||
assert result == payload
|
||||
assert c._last_download["content_type"] == "image/png"
|
||||
assert c._last_download["filename"] == "bild.png"
|
||||
|
||||
|
||||
def test_client_download_anlage_http_error_maps(monkeypatch):
|
||||
class _Err(urllib.error.HTTPError):
|
||||
def __init__(self):
|
||||
super().__init__("http://x", 404, "nicht gefunden", None, None)
|
||||
self._body = json.dumps({"success": False, "error": "Anlage nicht gefunden"})
|
||||
|
||||
def read(self):
|
||||
return self._body.encode("utf-8")
|
||||
|
||||
def _raise(req, timeout=None):
|
||||
raise _Err()
|
||||
|
||||
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", _raise)
|
||||
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||
r = c.download_anlage(7, "fehlt")
|
||||
assert isinstance(r, dict)
|
||||
assert r["error_code"] == "not_found"
|
||||
|
||||
|
||||
def test_parse_content_disposition():
|
||||
assert pmdb_client._parse_content_disposition(
|
||||
"attachment; filename*=UTF-8''bericht.pdf") == "bericht.pdf"
|
||||
assert pmdb_client._parse_content_disposition(
|
||||
'attachment; filename="alt.txt"') == "alt.txt"
|
||||
assert pmdb_client._parse_content_disposition("") == ""
|
||||
|
||||
|
||||
def test_multipart_upload_builds_body(tmp_path, monkeypatch):
|
||||
f = tmp_path / "notiz.txt"
|
||||
f.write_bytes(b"inhalt der datei\n")
|
||||
captured = {}
|
||||
|
||||
class _Cap:
|
||||
def __call__(self, req, timeout=None):
|
||||
captured["url"] = req.full_url
|
||||
captured["data"] = req.data
|
||||
captured["content_type"] = req.headers.get("Content-type") \
|
||||
or req.headers.get("Content-Type")
|
||||
return _FakeResponse(201, json.dumps(
|
||||
{"success": True, "anlagen": [{"id": "u1", "name": "notiz.txt"}]}))
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", _Cap())
|
||||
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||
r = c.upload_anlage(7, str(f))
|
||||
assert r["success"] is True
|
||||
# Endpoint + interne IPv4.
|
||||
assert captured["url"].startswith("http://pmdb.myowntools.org")
|
||||
assert captured["url"].endswith("/mcp/api/tasks/7/anlagen")
|
||||
# Multipart-Header mit Boundary.
|
||||
assert captured["content_type"].startswith("multipart/form-data; boundary=")
|
||||
body = captured["data"]
|
||||
assert b"name=\"datei\"" in body
|
||||
assert b"filename=\"notiz.txt\"" in body
|
||||
assert b"inhalt der datei" in body
|
||||
|
||||
|
||||
def test_multipart_upload_file_not_found(monkeypatch):
|
||||
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||
r = c.upload_anlage(7, "/gibt/es/nicht.txt")
|
||||
assert r["success"] is False
|
||||
assert r["error_code"] == "file_not_found"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Integration (gegen Live-PMDB, via Env PMDB_TEST_TOKEN aktiviert)
|
||||
# ---------------------------------------------------------------------------
|
||||
PMDB_TEST_TOKEN = os.environ.get("PMDB_TEST_TOKEN", "")
|
||||
PMDB_TEST_BASE = os.environ.get("PMDB_TEST_BASE",
|
||||
"https://pmdb.myowntools.org/mcp")
|
||||
|
||||
requires_live = pytest.mark.skipif(
|
||||
not PMDB_TEST_TOKEN, reason="PMDB_TEST_TOKEN nicht gesetzt (Integration off)")
|
||||
|
||||
|
||||
@requires_live
|
||||
def test_live_get_tasks_authenticated():
|
||||
c = pmdb_client.PMDBClient(base_url=PMDB_TEST_BASE, token=PMDB_TEST_TOKEN)
|
||||
r = c.get_tasks()
|
||||
# Mit gueltigem Token: success ODER strukturierter Fehler (nie Exception).
|
||||
assert "success" in r
|
||||
if r["success"]:
|
||||
assert "tasks" in r["data"]
|
||||
assert "count" in r["data"]
|
||||
assert "blocked_count" in r["data"]
|
||||
|
||||
|
||||
@requires_live
|
||||
def test_live_get_mask_404_or_ok():
|
||||
c = pmdb_client.PMDBClient(base_url=PMDB_TEST_BASE, token=PMDB_TEST_TOKEN)
|
||||
r = c.get_mask("F454")
|
||||
assert "success" in r
|
||||
if r["success"]:
|
||||
assert "bit_kette" in r["data"]
|
||||
|
||||
|
||||
@requires_live
|
||||
def test_live_search():
|
||||
c = pmdb_client.PMDBClient(base_url=PMDB_TEST_BASE, token=PMDB_TEST_TOKEN)
|
||||
r = c.search(feature="F454")
|
||||
assert "success" in r
|
||||
if r["success"]:
|
||||
assert "setcard" in r["data"]
|
||||
|
||||
|
||||
@requires_live
|
||||
def test_live_invalid_token_401():
|
||||
c = pmdb_client.PMDBClient(base_url=PMDB_TEST_BASE,
|
||||
token="mcp_fake_invalidtoken123")
|
||||
r = c.get_tasks()
|
||||
assert r["success"] is False
|
||||
assert r["error_code"] == "auth_invalid"
|
||||
Reference in New Issue
Block a user