Änderungen — CHANGE-0001
← zurück
diff --git a/docs-store/CURRENT.md b/docs-store/CURRENT.md
new file mode 100644
index 0000000..a83098d
--- /dev/null
+++ b/docs-store/CURRENT.md
@@ -0,0 +1,83 @@
+# TARS — Current State
+
+> **Chats are a workspace, not the canonical project store.
+> The current TARS state must be documented locally and queryable through TKC.**
+
+_Last updated: 2026-09-03_
+_Documentation store: /opt/tars/docs/ (local Git repository)_
+
+---
+
+## Architecture Baseline
+
+**Active baseline:** [architecture/architecture-v0.1.md](architecture/architecture-v0.1.md)
+Version: v0.1 · Date: 2026-09-03 · Status: Active · Supersedes: — (first baseline)
+
+---
+
+## Active Services (TON-01 · 10.10.10.5)
+
+| Service | Version | Port | Status |
+|---|---|---|---|
+| TKC (tkc-service) | 0.2.2 | 8110 | LIVE — systemd managed |
+| Engineering Gateway (tars-admin) | UNVERIFIED | UNVERIFIED | LIVE — systemd managed |
+| tars-status aggregator | UNVERIFIED | UNVERIFIED | LIVE — systemd managed |
+| TARS MCP Server (tars-mcp-server) | UNVERIFIED | via VPS nginx /mcp | LIVE |
+| tars-web-runtime | UNVERIFIED | 8767 (TON-01 internal) | LIVE — systemd managed |
+
+Network topology: TON-01 LAN `192.168.2.21` · WireGuard/TARS `10.10.10.5` · VPS public gateway `dev.teich-tb.de`
+
+---
+
+## Active Repositories
+
+| Repository | Branch (LIVE) | Last merged |
+|---|---|---|
+| tars-platform | main | 2026-08-30 (deploy pipeline v0.1) |
+| tars-tkc | main | 2026-08-17 (ST1 Phase 1+2 lifecycle) |
+| tars-interaction-runtime | main | UNVERIFIED |
+
+DEV workspaces: `/opt/tars/dev/bob/<repo>` on branch `bob/dev`
+
+---
+
+## Active Agents
+
+| Agent | Role | Status |
+|---|---|---|
+| Hermes | Primary TARS orchestrator | ACTIVE |
+| Bob (AI-001) | Engineering agent / worker | ACTIVE — governed DEV workflow |
+
+Bob has no production write access. Engineering changes flow through DEV → PR → human approval → LIVE.
+
+---
+
+## Active Constraints
+
+- Milvus stack (etcd, minio, standalone) does not auto-start after TON-01 reboot — restart required manually. _(No fix confirmed yet.)_
+- `TKCClient.ingest_raw()` in tars-interaction-runtime silently drops provenance metadata (sends unknown top-level field). Source context data lost on session write.
+- `tars-tkc` is not in the Engineering Gateway repository allowlist — Bob cannot read TKC source directly.
+- WIKI objects default to `candidate` and require explicit activation (`POST /knowledge/{id}/activate`) before retrieval.
+
+---
+
+## Major Open Items
+
+See [design-journal/2026-09.md](design-journal/2026-09.md) for full context.
+
+- Design governed `tkc_raw_ingest` write capability for agents
+- Fix tars-interaction-runtime RAW source metadata loss
+- Define `knowledge_relations` schema and API
+- Design incremental ChatGPT TARS-TKC migration / import
+- TKC indexing of this documentation store (future)
+
+---
+
+## Documentation Store
+
+| Document | Description |
+|---|---|
+| [architecture/architecture-v0.1.md](architecture/architecture-v0.1.md) | First project-wide architecture baseline |
+| [design-journal/2026-09.md](design-journal/2026-09.md) | September 2026 design decisions |
+| [releases/README.md](releases/README.md) | Release versioning conventions |
+| [components/README.md](components/README.md) | Component documentation conventions |
diff --git a/docs-store/architecture/architecture-v0.1.md b/docs-store/architecture/architecture-v0.1.md
new file mode 100644
index 0000000..878020d
--- /dev/null
+++ b/docs-store/architecture/architecture-v0.1.md
@@ -0,0 +1,247 @@
+---
+architecture_version: v0.1
+date: 2026-09-03
+status: active
+supersedes: "— (first project-wide baseline)"
+superseded_by: ~
+---
+
+# TARS Architecture Baseline v0.1
+
+## 1. Scope
+
+This document captures the first explicit project-wide TARS architecture baseline.
+
+**In scope:** system topology, active components, agent model, knowledge architecture,
+interaction layer, engineering governance model, documentation architecture.
+
+**Out of scope:** detailed internal implementation of individual services;
+future interface classes (robot, wearable, mobile) beyond their current conceptual status;
+character/personality layer (PLANNED, not yet implemented).
+
+**Accuracy policy:** Each assertion is marked CONFIRMED, PLANNED, CONCEPTUAL, or UNVERIFIED.
+Do not remove or downgrade markers without evidence. Do not invent state.
+
+---
+
+## 2. Core Architectural Principles
+
+_Source: TKC WIKI (knowledge objects 2088b3de, 7f9dfc36) — CONFIRMED_
+
+- Knowledge belongs to the user. AI agents consume TKC but do not own knowledge.
+- AI models are replaceable. No interface or agent is coupled to a specific model.
+- Human remains in control. Write operations and production changes require human approval.
+- Every fact has a source. Knowledge provenance is mandatory.
+- Learning is traceable. Knowledge lifecycle (RAW → WIKI candidate → active) is explicit.
+- Security and transparency are mandatory.
+
+---
+
+## 3. System / Component Overview
+
+### 3.1 Infrastructure
+
+| Component | Status | Notes |
+|---|---|---|
+| TON-01 | **CONFIRMED LIVE** | Primary management node. LAN: 192.168.2.21. WireGuard/TARS: 10.10.10.5. |
+| VPS / TARS Relay | **CONFIRMED LIVE** | External gateway at 217.154.124.64 / dev.teich-tb.de. TLS termination, nginx reverse proxy. Connects to TON-01 via WireGuard. |
+| WireGuard VPN | **CONFIRMED LIVE** | Connects TON-01, VPS, and cross-site clients (laptop at pond, future nodes). |
+
+### 3.2 Knowledge Layer
+
+| Component | Version | Status | Port |
+|---|---|---|---|
+| TKC — TARS Knowledge Core | 0.2.2 | **CONFIRMED LIVE** | 8110 (TON-01) |
+| PostgreSQL | UNVERIFIED | **CONFIRMED LIVE** (backing TKC) | internal |
+| Milvus (etcd + minio + standalone) | UNVERIFIED | **CONFIRMED LIVE** (manual restart after reboot required) | internal |
+| Neo4j | UNVERIFIED | **CONFIRMED LIVE** (backing TKC) | internal |
+
+TKC schema: `knowledge_objects` (layer raw|wiki, domain, status candidate|active|superseded),
+`knowledge_provenance` (N:M, DERIVED_FROM|CONFIRMED_BY|CONTRADICTS),
+`superseded_by` inline FK on knowledge_objects.
+Embedding model: `sentence-transformers/all-MiniLM-L6-v2` (384-dim).
+
+### 3.3 Platform Services (TON-01)
+
+| Service | Status | Port | Notes |
+|---|---|---|---|
+| tars-admin (Engineering Gateway) | **CONFIRMED LIVE** | UNVERIFIED | Allowlisted repo operations, service control, host management. systemd managed. |
+| tars-status aggregator | **CONFIRMED LIVE** | UNVERIFIED | Aggregates service health. systemd managed. |
+| vps-control-agent | **CONFIRMED LIVE** | UNVERIFIED | VPS-side service controls. |
+
+### 3.4 Agent / MCP Layer
+
+| Component | Status | Notes |
+|---|---|---|
+| TARS MCP Server (tars-mcp-server) | **CONFIRMED LIVE** | Streamable HTTP. Endpoint: `https://dev.teich-tb.de/mcp`. Exposes TKC read tools (brain_query, semantic_search, knowledge_query). Write tools (POST /knowledge) intentionally not exposed. |
+| Bob (AI-001) | **CONFIRMED ACTIVE** | Engineering agent and worker. Runs in IBM watsonx Orchestrate (or equivalent). Governed DEV workflow via Engineering Gateway. No production write access. |
+| Hermes | **CONFIRMED ACTIVE as role** | Primary TARS orchestrator. Implementation details UNVERIFIED. Consumes MCP Server for TKC reads. |
+
+### 3.5 Interaction Layer
+
+The tars-interaction-runtime repository provides multiple operational modes.
+Deployment state is assessed per mode.
+
+| Mode / Component | Status | Details |
+|---|---|---|
+| **web-server mode** (`tars-web-runtime.service`) | **CONFIRMED LIVE** on TON-01 | FastAPI/Uvicorn ASGI backend. Binds `0.0.0.0:8767` on TON-01. VPS nginx proxies `/tars/auth/*`, `/tars/health`, `/tars/ws` → `10.10.10.5:8767`. Cookie-based auth (bcrypt, HttpOnly Secure cookie). WebSocket session per browser connection. ElevenLabs and Gemini Native voice support. |
+| **web frontend (React build)** | **CONFIRMED** in deployment design | VPS nginx serves static React build from `/srv/tars-web/dist/`. Accessible at `dev.teich-tb.de/tars/*`. Exact deployed version UNVERIFIED. |
+| **node-server mode** (NodeServer, port 8766) | **DEV — not deployed LIVE** | WebSocket server for hardware interaction nodes (TARS-Desk, future). Last confirmed state 2026-08-17: implemented in DEV, VPS nginx proxy config not yet applied. |
+| **local mode** (PTT, sounddevice) | **CONFIRMED as capability** | Runs on a local device with microphone and speakers. Not a server-side deployment. |
+
+The repository `tars-interaction-runtime` is **CONFIRMED LIVE** in its web-server capacity.
+The node-server mode is DEV-only at last confirmed state (2026-08-17).
+
+Core capabilities (all server modes): TKC brain_query at session start,
+TKC POST /knowledge (RAW) at session close, MCP tool dispatch with Human Gate UX,
+Gemini Live API for reasoning.
+
+### 3.6 Web / UI Layer
+
+| Component | Status | Notes |
+|---|---|---|
+| TARS Control v0.3 (tars-control/index.html) | **CONFIRMED** in tars-platform | Fixed-topology status frontend. Active development in DEV workspace. |
+| TARS Brain (frontend/brain/) | **DEV** | Cytoscape.js free-graph frontend. In DEV workspace, not yet committed to main. |
+| tars-admin frontend | **CONFIRMED LIVE** | Admin UI for service and host management. Part of tars-platform. |
+
+### 3.7 Edge / Hardware
+
+| Component | Status | Notes |
+|---|---|---|
+| TARS Robot | **CONCEPTUAL** | Phase 6 planning. No hardware platform defined. |
+| TARS Wearable / HUD | **CONCEPTUAL** | Phase 7. |
+| Interaction Nodes (tars-node-windows) | **DEV** | Reference node: Windows laptop at pond. 16 tests passing. Not deployed. |
+
+---
+
+## 4. Major Interfaces
+
+| Interface | Protocol | Endpoint | Auth | Status |
+|---|---|---|---|---|
+| TKC REST API | HTTP | `http://10.10.10.5:8110` | None (LAN) / Bearer (external) | CONFIRMED LIVE |
+| TARS MCP Server | Streamable HTTP (MCP) | `https://dev.teich-tb.de/mcp` | Bearer token | CONFIRMED LIVE |
+| Engineering Gateway | HTTPS | internal (WireGuard) | Bearer token | CONFIRMED LIVE |
+| tars-web-runtime WebSocket | WSS | `https://dev.teich-tb.de/tars/ws` | Cookie (production) / Bearer (dev) | CONFIRMED LIVE |
+| tars-web-runtime Auth | HTTPS | `https://dev.teich-tb.de/tars/auth/*` | Cookie | CONFIRMED LIVE |
+| NodeServer WebSocket | WSS | `wss://dev.teich-tb.de/node` (planned) | Bearer token | DEV — VPS proxy not yet deployed |
+
+---
+
+## 5. Deployment / Runtime Topology
+
+```
+Internet / WireGuard clients
+ │
+ ▼
+ VPS (217.154.124.64 / dev.teich-tb.de)
+ ├── nginx: TLS termination
+ ├── /mcp → TON-01 Engineering Gateway / MCP [port UNVERIFIED]
+ ├── /tars/ws → TON-01:8767 (tars-web-runtime WebSocket)
+ ├── /tars/auth/* → TON-01:8767 (tars-web-runtime Auth)
+ ├── /tars/health → TON-01:8767 (tars-web-runtime Health)
+ ├── /tars/... → /srv/tars-web/dist/ (React static build)
+ └── /node → TON-01:8766 (NodeServer — PLANNED, proxy not yet applied)
+ │ WireGuard
+ ▼
+ TON-01 (10.10.10.5)
+ ├── tkc-service.service → :8110 (TKC)
+ ├── tars-admin.service → :UNVERIFIED (Engineering Gateway)
+ ├── tars-status.service → :UNVERIFIED (Status aggregator)
+ ├── tars-web-runtime.service → :8767 (Interaction Runtime web mode)
+ ├── /opt/tars/repos/ → LIVE Git repositories
+ ├── /opt/tars/dev/bob/ → DEV workspaces (bob/dev branch)
+ ├── /opt/tars/docs/ → Documentation Store (this repository)
+ └── /opt/tars/stacks/infrastructure/ → Milvus Docker Compose stack
+```
+
+ADR-0001: `/opt/tars` is not itself a Git repository. Repos live under `/opt/tars/repos/`.
+ADR-0003: Engineering Gateway is not exposed directly to the internet.
+All external access is via the VPS Relay over WireGuard.
+
+---
+
+## 6. Agent Architecture
+
+**Hermes** is the primary TARS orchestrator. It manages sessions, context, and tool dispatch.
+Implementation details (runtime platform, version) are UNVERIFIED in this baseline.
+
+**Bob (AI-001)** is the engineering agent and worker. Bob:
+- Operates under a version-controlled Agent Contract (ADR-0002,
+ `tars-platform/agents/AI-001-Bob/contract.yaml`)
+- Works exclusively in the DEV workspace (`/opt/tars/dev/bob/`, branch `bob/dev`)
+- Reaches production only via human-approved PRs
+- Has no direct production write access
+
+Agent authority is defined by the Agent Contract, not by character profile or orchestrator.
+AI models are infrastructure; they do not carry agent identity (ADR-0002).
+
+---
+
+## 7. Knowledge Architecture
+
+**Canonical store:** TKC (PostgreSQL + Milvus + Neo4j). No agent or interface owns knowledge.
+
+**Layer model:**
+- `layer=raw`: Source evidence. Preserved verbatim. Active immediately (no approval gate).
+- `layer=wiki`: TARS condensed understanding. Created as `candidate`. Requires explicit activation.
+
+**Lifecycle:**
+```
+RAW ingest → (synthesis) → WIKI candidate → human approval
+ → WIKI active → (superseding) → WIKI superseded
+```
+
+**Provenance:** `knowledge_provenance` table (N:M).
+Vocabulary: `DERIVED_FROM | CONFIRMED_BY | CONTRADICTS`.
+`SUPERSEDES` stored as inline FK columns (`superseded_by`, `superseded_at`,
+`supersede_reason`) on `knowledge_objects` — not as a relation row.
+
+**Domain isolation:** Fail-closed. Default domain `unclassified`.
+Domain `all` required for cross-domain retrieval.
+
+**Known gap:** `TKCClient.ingest_raw()` drops provenance metadata silently (sends an unknown
+top-level field that Pydantic discards). Source context should be placed in `metadata` field
+until fixed. No `knowledge_relations` table yet exists for general semantic object relations.
+
+---
+
+## 8. Documentation Architecture
+
+**Canonical project documentation:** `/opt/tars/docs/` — standalone local Git repository on
+TON-01. Not a subdirectory of any application repo. Not dependent on GitHub.
+
+**Repository documentation** (ADRs, deploy docs, engineering standards) remains in
+`tars-platform/docs/` and component repositories. That material is reference/source, not
+duplicated here.
+
+**Principle:** Markdown is the canonical authoring layer. TKC will later index
+`/opt/tars/docs/` for semantic search and retrieval. TKC is not the authoring store.
+
+**Future agent writes** (e.g. Hermes writing Design Journal entries) must go through a
+controlled, allowlisted, audited write boundary with human-governed rules.
+The specific mechanism is not yet decided.
+
+---
+
+## 9. Key Active Constraints
+
+| Constraint | Impact | Source |
+|---|---|---|
+| Milvus stack does not auto-restart after TON-01 reboot | Knowledge retrieval unavailable until manual restart | Phase-1 session e15a6361 |
+| `tars-tkc` repo not in Engineering Gateway allowlist | Bob cannot read TKC source directly | Previous review session |
+| `ingest_raw()` drops provenance metadata | RAW objects from Interaction Runtime have no session provenance link | Previous review session |
+| NodeServer VPS nginx proxy not deployed | Node Protocol (port 8766) not externally reachable | ADR a9151b94 (2026-08-17) |
+| WIKI objects default to candidate | New WIKI knowledge is not retrieved until explicitly activated | ADR e1436da2 |
+
+---
+
+## 10. References
+
+- `tars-platform/docs/architecture/ADR-0001` — Repository separation
+- `tars-platform/docs/architecture/ADR-0002` — Agent contract model
+- `tars-platform/docs/architecture/ADR-0003` — Remote engineering connectivity
+- `tars-platform/docs/architecture/TARS-HUMAN-INTERFACE-ARCHITECTURE.md v0.1` — Interface architecture design (input to this baseline)
+- `tars-platform/docs/architecture/Trustworthy-Knowledge.md` — Knowledge governance
+- TKC WIKI: e1436da2 (layer model), a27ea229 (provenance model), 251aeae0 (domain isolation)
+- TKC RAW: e15a6361 (Phase-1 implementation session)
+- `/opt/tars/docs/design-journal/2026-09.md` — Design journal context
diff --git a/docs-store/components/README.md b/docs-store/components/README.md
new file mode 100644
index 0000000..00d11ba
--- /dev/null
+++ b/docs-store/components/README.md
@@ -0,0 +1,59 @@
+# TARS Component Documentation
+
+This directory contains current documentation and state for individual TARS components.
+
+## What belongs here
+
+Per-component files covering:
+- Current version and deployment state
+- Configuration surface (non-secret)
+- Key interfaces and endpoints
+- Known constraints or open items
+- Relationship to the active architecture baseline
+
+## What does NOT belong here
+
+- Detailed implementation code (stays in component repositories)
+- Secrets or credentials
+- Architecture baseline decisions (stays in `../architecture/`)
+- Chronological design reasoning (stays in `../design-journal/`)
+
+## Naming convention
+
+```
+components/tkc.md
+components/tars-interaction-runtime.md
+components/tars-admin.md
+components/tars-mcp-server.md
+```
+
+## Component versioning
+
+Component versions are independent of project release versions and architecture
+baseline versions.
+
+Mark any unverified information explicitly as `UNVERIFIED`.
+Do not invent versions or deployment states.
+
+## Document header template
+
+Each component file should open with a metadata block:
+
+```
+# <Component Name>
+
+| Field | Value |
+|---|---|
+| Version | <version or UNVERIFIED> |
+| Status | CONFIRMED LIVE / DEV / PLANNED / CONCEPTUAL |
+| Last verified | YYYY-MM-DD |
+| Architecture baseline | architecture-vX.Y |
+| Repository | <repo name> |
+| Port / Endpoint | <if applicable, or UNVERIFIED> |
+```
+
+## Current component files
+
+_No component files yet._
+_Initial component documentation to follow based on real usage and query patterns._
+_Reference: `../CURRENT.md` contains the current verified component summary._
diff --git a/docs-store/design-journal/2026-09.md b/docs-store/design-journal/2026-09.md
new file mode 100644
index 0000000..1859537
--- /dev/null
+++ b/docs-store/design-journal/2026-09.md
@@ -0,0 +1,81 @@
+# TARS Design Journal — September 2026
+
+## 2026-09-02 — TKC RAW Ingest & Knowledge Relations
+
+### Context
+Im Rahmen der Hermes→TKC-Integration wurde geprüft, wie Diskussionen,
+Sessions, Design-Änderungen und später ChatGPT-Projektwissen dauerhaft
+in TKC übernommen werden können.
+
+### Findings
+- TKC RAW objects are active without an approval gate.
+- WIKI objects default to candidate and require lifecycle approval.
+- `TKCClient.ingest_raw()` in the Interaction Runtime sends provenance
+ in an unsupported top-level field; Pydantic silently discards it.
+- Source/context information should therefore currently be stored via
+ `source_type` and structured `metadata`.
+- TARS MCP currently exposes TKC read operations only.
+ `POST /knowledge` is intentionally not exposed.
+- Existing `knowledge_provenance` is strictly limited to:
+ `DERIVED_FROM`, `CONFIRMED_BY`, `CONTRADICTS`.
+- General semantic Object→Object relations do not currently exist.
+
+### Design Direction
+RAW knowledge should be modeled as:
+
+ Source + Context + optional true Provenance + Semantic Relations
+
+Provenance and semantic relations must remain separate.
+
+Proposed future canonical model:
+
+ knowledge_objects
+ knowledge_provenance
+ knowledge_relations
+
+`knowledge_relations` should be canonical in PostgreSQL and projected
+to Neo4j. Relation types must be allowlisted/enumerated; agents must
+not invent arbitrary relation types.
+
+Context such as project, system, component, repository, session and
+source system remains in metadata initially. Promotion to first-class
+entities should only happen after real query patterns justify it.
+
+### Initial Relation Candidates
+- RELATES_TO
+- PART_OF
+- DEPENDS_ON
+- IMPLEMENTS
+
+Additional relation types should only be introduced based on demonstrated
+usage.
+
+### Migration Direction
+ChatGPT Project TARS-TKC is currently an important project knowledge source.
+A future incremental import should ingest new project conversations as RAW,
+preserving source/context information.
+
+Long-term target:
+
+ ChatGPT migration bridge
+ ↓
+ Hermes / TARS
+ ↓
+ TARS MCP
+ ↓
+ TKC
+ RAW → Synthesis
+ ↓
+ WIKI Candidate
+ ↓
+ Approval
+
+ChatGPT should eventually cease being the primary project memory.
+TKC becomes the model-independent canonical knowledge core.
+
+### Open
+- Design governed `tkc_raw_ingest` MCP capability.
+- Fix Interaction Runtime RAW source metadata loss.
+- Define `knowledge_relations` schema/API.
+- Define minimal relation vocabulary from real usage.
+- Design incremental ChatGPT TARS-TKC migration/import.
diff --git a/docs-store/releases/README.md b/docs-store/releases/README.md
new file mode 100644
index 0000000..e703214
--- /dev/null
+++ b/docs-store/releases/README.md
@@ -0,0 +1,37 @@
+# TARS Releases
+
+This directory contains TARS release documentation.
+
+## Version model
+
+TARS uses three distinct version dimensions. They are independent and must not be conflated:
+
+| Dimension | What it tracks | Where documented |
+|---|---|---|
+| **Architecture Version** | Structural baseline of the TARS system as a whole | `../architecture/architecture-vX.Y.md` |
+| **Project / Release Version** | Feature milestones and cross-component releases | `releases/release-vX.Y.md` (this directory) |
+| **Component Version** | Individual service or library versions | `../components/<name>.md` |
+
+A new project release does not automatically produce a new architecture baseline.
+An architecture baseline change does not automatically produce a new project release.
+
+## Naming convention
+
+```
+releases/release-v0.1.md
+releases/release-v0.2.md
+```
+
+## Minimum content per release file
+
+- Release version
+- Date
+- Scope summary
+- Component versions included (reference to `../components/` where applicable)
+- Breaking changes
+- Migration notes (if any)
+
+## Current releases
+
+_No formal release document yet._
+_See `../CURRENT.md` for the current verified component and service state._
diff --git a/docs/design-journal/2026-09.md b/docs/design-journal/2026-09.md
new file mode 100644
index 0000000..1859537
--- /dev/null
+++ b/docs/design-journal/2026-09.md
@@ -0,0 +1,81 @@
+# TARS Design Journal — September 2026
+
+## 2026-09-02 — TKC RAW Ingest & Knowledge Relations
+
+### Context
+Im Rahmen der Hermes→TKC-Integration wurde geprüft, wie Diskussionen,
+Sessions, Design-Änderungen und später ChatGPT-Projektwissen dauerhaft
+in TKC übernommen werden können.
+
+### Findings
+- TKC RAW objects are active without an approval gate.
+- WIKI objects default to candidate and require lifecycle approval.
+- `TKCClient.ingest_raw()` in the Interaction Runtime sends provenance
+ in an unsupported top-level field; Pydantic silently discards it.
+- Source/context information should therefore currently be stored via
+ `source_type` and structured `metadata`.
+- TARS MCP currently exposes TKC read operations only.
+ `POST /knowledge` is intentionally not exposed.
+- Existing `knowledge_provenance` is strictly limited to:
+ `DERIVED_FROM`, `CONFIRMED_BY`, `CONTRADICTS`.
+- General semantic Object→Object relations do not currently exist.
+
+### Design Direction
+RAW knowledge should be modeled as:
+
+ Source + Context + optional true Provenance + Semantic Relations
+
+Provenance and semantic relations must remain separate.
+
+Proposed future canonical model:
+
+ knowledge_objects
+ knowledge_provenance
+ knowledge_relations
+
+`knowledge_relations` should be canonical in PostgreSQL and projected
+to Neo4j. Relation types must be allowlisted/enumerated; agents must
+not invent arbitrary relation types.
+
+Context such as project, system, component, repository, session and
+source system remains in metadata initially. Promotion to first-class
+entities should only happen after real query patterns justify it.
+
+### Initial Relation Candidates
+- RELATES_TO
+- PART_OF
+- DEPENDS_ON
+- IMPLEMENTS
+
+Additional relation types should only be introduced based on demonstrated
+usage.
+
+### Migration Direction
+ChatGPT Project TARS-TKC is currently an important project knowledge source.
+A future incremental import should ingest new project conversations as RAW,
+preserving source/context information.
+
+Long-term target:
+
+ ChatGPT migration bridge
+ ↓
+ Hermes / TARS
+ ↓
+ TARS MCP
+ ↓
+ TKC
+ RAW → Synthesis
+ ↓
+ WIKI Candidate
+ ↓
+ Approval
+
+ChatGPT should eventually cease being the primary project memory.
+TKC becomes the model-independent canonical knowledge core.
+
+### Open
+- Design governed `tkc_raw_ingest` MCP capability.
+- Fix Interaction Runtime RAW source metadata loss.
+- Define `knowledge_relations` schema/API.
+- Define minimal relation vocabulary from real usage.
+- Design incremental ChatGPT TARS-TKC migration/import.
diff --git a/docs/engineering/queue-mvp/README.md b/docs/engineering/queue-mvp/README.md
new file mode 100644
index 0000000..f9070ce
--- /dev/null
+++ b/docs/engineering/queue-mvp/README.md
@@ -0,0 +1,59 @@
+# TARS Engineering Queue MVP — workspace-only prototype
+
+Status: prepared for review. The SQL has not been applied; no service is installed; no record is written to any persistent queue or MAIN environment.
+
+## Model and first record
+
+Change records carry `change_id`, title, description, one `repository`, status, priority, owner, dependency IDs, `commit_sha`, `base_sha`, changed-file manifest, test-evidence references, Human Gate 1/2 status and reference, version, claim, submission and audit timestamps.
+
+Proposed first seed: `RECOVERY-DEV-001`; title “Secure snapshot and Git inventory of existing DEV repositories”; `repository=tars-platform`; status `proposed`; priority `P1`; owner `Mirko Kümpfel`; dependencies `[]`; commit SHA `null`; no test evidence yet; both approval statuses `not_requested`. It documents work over all three existing DEV repos in `description`/acceptance, but the Change Record intentionally names a single coordinating repository. Seed is a proposal only; persistence and uniqueness are unverified.
+
+## Runtime configuration and identity contract
+
+The values below are names and contracts only. Supply all credentials through an approved protected runtime secret source; never place credential values in this README, Git, command arguments, logs, or test evidence.
+
+`src/api.py:create_app()` requires the following for a PostgreSQL-backed service:
+
+| Variable / setting | Purpose and identity |
+|---|---|
+| `TARS_QUEUE_AGENT_DSN` | PostgreSQL connection for Agent actions; use the dedicated least-privilege `tars_queue_agent_login`, not a setup/superuser or Operator login. |
+| `TARS_QUEUE_OPERATOR_DSN` | PostgreSQL connection for Operator actions; use the distinct `tars_queue_operator_login`. |
+| `agent_api_keys` argument to `create_app()` | Required mapping of inbound Agent bearer token(s) to server-configured Agent subject(s). There is no `TARS_QUEUE_DEV_API_KEY` lookup in `create_app()`; the hosting adapter must provide this mapping without accepting the subject from a request. |
+| `TARS_QUEUE_DEV_OPERATOR_KEY` | Separate inbound Operator bearer credential. It must not equal any Agent credential. |
+| `TARS_QUEUE_DEV_OPERATOR_ID` | Server-configured Operator subject used for audit; callers cannot choose it. |
+| `TARS_QUEUE_SEED_DSN` | Optional, separate Seed-import connection, restricted in code to `127.0.0.1:55432`, database `tars_queue_itest`, user `tars_queue_seed_login`. It is not needed for ordinary API startup. |
+
+The operator may read queue and grant metadata. Agents create and edit changes, claim work, attach evidence, and submit for review. Only the Operator identity can issue/revoke execution grants and transition a change to `ready`. A claim requires a valid, unexpired, unrevoked grant bound to that exact change. The API does not issue Human Gate decisions or promote to MAIN; `submit-for-review` only marks the external Human Gate as pending. Agent and Operator DB DSNs and inbound API credentials must be distinct.
+
+## API contract
+
+All routes except `GET /health` require `Authorization: Bearer <role-specific credential>`.
+
+- `POST /v1/changes` — Agent creates a `proposed` record; approval fields and unknown fields are rejected.
+- `GET /v1/changes?status=&repository=&limit=100&cursor=` — Agent or Operator reads a bounded, optionally filtered list.
+- `GET /v1/changes/{change_id}` and `GET /v1/changes/{change_id}/execution-grants` — read change and non-secret grant metadata.
+- `POST /v1/execution-grants` and `POST /v1/execution-grants/{grant_id}/revoke` — Operator-only grant issue/revocation; issuer is derived from the authenticated Operator DB identity.
+- `PATCH /v1/changes/{change_id}/status` — Agent updates allowed lifecycle states with optimistic `expected_version` and reason; only Operator can authorize `ready` with a grant.
+- `POST /v1/changes/{change_id}/claim` — Agent claim with the grant reference; store validates target, scope, expiry/revocation, dependencies, and claim lease.
+- `POST /v1/changes/{change_id}/evidence` and `GET /v1/changes/{change_id}/evidence` — Agent appends evidence; Agent/Operator can read it.
+- `POST /v1/changes/{change_id}/submit-for-review` — Agent submits a validated, commit-pinned change with passing evidence; response explicitly leaves external Human Gate approval pending.
+
+There is no autonomous worker runner or retry daemon in this MVP tree. The claim/status API is not by itself proof of task execution.
+
+## Database migration guards and isolation
+
+The SQL is **not** a generic migration to run against any database named `*_dev`. Before any DDL, an already-authorized operator must confirm the exact target by a protected read-only PostgreSQL connection and compare its database, login, server/client addresses, PostgreSQL major version, database owner, `pg_control_system().system_identifier`, existing queue object owners/counts, data inventory, and role/membership state with the literal guards in the specific migration. The guarded test bootstrap/migration scripts pin an exact disposable test target; do not relax or repoint those guards to make another database fit.
+
+`001_engineering_queue.sql` creates the base queue schema. `002_phase2_dev_queue.sql` adds execution-grant state and contains an `UPDATE` that can reset `ready`/`claimed` rows without a qualifying grant; do not rerun it against existing data without a fresh, exact-target review. `003a_queue_test_role_bootstrap.sql` creates cluster-wide `NOLOGIN` capability/owner roles and requires the exact pinned test cluster; `003a1_queue_test_login_bootstrap.sql` creates cluster-wide Agent/Operator/Seed LOGIN roles and memberships; `003_queue_db_roles.sql` transfers queue object ownership and sets function/table ACLs. These steps have distinct cluster/database effects and must be inspected and verified one at a time. The README does not authorize any migration or role/credential change.
+
+No service launcher or systemd unit is included in this workspace. `src/api.py` exposes `create_app()` but no module-level `app`; a deployment adapter must construct it with the required Agent identity mapping and protected settings. Do not invent a startup command or start a service until a reviewed DEV launcher/configuration exists and the exact DB is confirmed isolated.
+
+## Verification performed
+
+The API contract tests use in-memory/fake stores. They verify route/auth behavior only; they do not prove PostgreSQL persistence, migration correctness, database ACLs, a running service, worker execution, or deployment. See the actual current test suite under `tests/`; run unit/API tests separately from database-dependent integration cases and report DB skips as not run, not passed.
+
+The queue-MVP directory is a Hermes workspace snapshot without Git metadata. It is not itself a TARS DEV Git worktree; do not initialize a repository here or infer a commit/branch. Stage this README into the designated TARS DEV repository through its authorized file workflow before making a DEV commit.
+
+## Search result scope
+
+`tars-tkc` also contains a separate synthesis-coverage queue; it is not this Engineering Change Queue. This README describes only the queue-MVP source in this workspace, not a running or canonical persistent queue. Verify persistent records through an authenticated read from the confirmed DEV queue service before treating any seed as a ticket.
diff --git a/frontend/tars-control/index.html b/frontend/tars-control/index.html
index 59a4243..0753ee8 100644
--- a/frontend/tars-control/index.html
+++ b/frontend/tars-control/index.html
@@ -5,337 +5,1511 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TARS Control</title>
<style>
-/* ─── Reset & base ──────────────────────────────────────────────────────── */
+/* ─── Reset ───────────────────────────────────────────────────────────────── */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
- --bg: #0d1117;
- --surface: #161b22;
- --border: #30363d;
- --text: #e6edf3;
- --muted: #8b949e;
- --ok: #3fb950;
- --warn: #d29922;
- --err: #f85149;
- --unknown: #6e7681;
- --active-tag: #238636;
- --super-tag: #6e40c9;
- --accent: #58a6ff;
- --font-mono: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
- --radius: 6px;
-}
-
-html { background: var(--bg); color: var(--text); font-family: -apple-system, "Segoe UI", system-ui, sans-serif; font-size: 14px; line-height: 1.5; }
-body { min-height: 100vh; }
-
-/* ─── Layout ────────────────────────────────────────────────────────────── */
-.page { max-width: 1000px; margin: 0 auto; padding: 24px 20px 64px; }
-
-.header { display: flex; align-items: baseline; justify-content: space-between; border-bottom: 1px solid var(--border); padding-bottom: 14px; margin-bottom: 24px; }
-.header h1 { font-size: 18px; font-weight: 700; letter-spacing: 0.06em; color: var(--text); }
-.header-meta { font-size: 12px; color: var(--muted); }
-
-.grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 16px; }
-.grid-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 16px; margin-bottom: 16px; }
-
-/* ─── Cards ─────────────────────────────────────────────────────────────── */
-.card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 16px; }
-.card-title { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.08em; color: var(--muted); margin-bottom: 12px; }
-
-/* ─── Service rows ───────────────────────────────────────────────────────── */
-.svc-row { display: flex; align-items: center; justify-content: space-between; padding: 5px 0; border-bottom: 1px solid var(--border); }
-.svc-row:last-child { border-bottom: none; }
-.svc-name { font-size: 13px; color: var(--text); }
-.svc-right { display: flex; align-items: center; gap: 8px; }
-.svc-detail { font-size: 11px; color: var(--muted); font-family: var(--font-mono); }
-
-/* ─── Status dot ─────────────────────────────────────────────────────────── */
-.dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
-.dot-ok { background: var(--ok); box-shadow: 0 0 6px var(--ok); }
-.dot-warn { background: var(--warn); box-shadow: 0 0 6px var(--warn); }
-.dot-error { background: var(--err); box-shadow: 0 0 6px var(--err); }
+ --bg: #0d1117;
+ --surface: #161b22;
+ --surface2: #1c2128;
+ --border: #21262d;
+ --border-hi: #30363d;
+ --text: #e6edf3;
+ --muted: #8b949e;
+ --dim: #484f58;
+ --ok: #3fb950;
+ --warn: #d29922;
+ --err: #f85149;
+ --unknown: #484f58;
+ --super: #a371f7;
+ --mono: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
+
+ /* primary node accent colours */
+ --c-tars: #58a6ff;
+ --c-tkc: #3fb950;
+ --c-bob: #d29922;
+ --c-mcp: #a371f7;
+ --c-ton: #4fb3d8;
+
+ /* secondary node colour (all secondaries share one muted ring style) */
+ --c-sec: #30363d;
+}
+
+html {
+ background: var(--bg);
+ color: var(--text);
+ font-family: -apple-system, "Segoe UI", system-ui, sans-serif;
+ font-size: 14px;
+ line-height: 1.5;
+ height: 100%;
+ overflow: hidden; /* canvas fills viewport */
+}
+body {
+ height: 100vh;
+ width: 100vw;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+}
+
+/* ─── Header bar ──────────────────────────────────────────────────────────── */
+#topbar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 9px 18px;
+ border-bottom: 1px solid var(--border);
+ flex-shrink: 0;
+ z-index: 10;
+}
+#topbar-title {
+ font-size: 11px;
+ font-weight: 700;
+ letter-spacing: 0.16em;
+ text-transform: uppercase;
+ color: var(--muted);
+}
+#topbar-meta {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ font-size: 11px;
+ color: var(--dim);
+}
+#topbar-meta button {
+ background: none;
+ border: 1px solid var(--border-hi);
+ color: var(--dim);
+ border-radius: 4px;
+ padding: 2px 8px;
+ cursor: pointer;
+ font-size: 11px;
+ transition: border-color 0.15s, color 0.15s;
+}
+#topbar-meta button:hover { border-color: var(--c-tars); color: var(--c-tars); }
+
+/* ─── Error banner ────────────────────────────────────────────────────────── */
+#error-banner {
+ display: none;
+ font-size: 12px;
+ color: var(--err);
+ padding: 6px 18px;
+ background: rgba(248,81,73,0.06);
+ border-bottom: 1px solid rgba(248,81,73,0.2);
+ flex-shrink: 0;
+}
+
+/* ─── Canvas ──────────────────────────────────────────────────────────────── */
+#canvas {
+ flex: 1;
+ position: relative;
+ overflow: hidden;
+}
+
+/* Full-size SVG for edges — sits behind nodes */
+#topo-svg {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ z-index: 1;
+}
+
+/* ─── Primary nodes ───────────────────────────────────────────────────────── */
+.node {
+ position: absolute;
+ transform: translate(-50%, -50%);
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ cursor: pointer;
+ user-select: none;
+ z-index: 3;
+ transition: left 0.38s cubic-bezier(0.4,0,0.2,1),
+ top 0.38s cubic-bezier(0.4,0,0.2,1),
+ opacity 0.25s ease;
+}
+.node-ring {
+ border-radius: 50%;
+ border: 1.5px solid var(--border-hi);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ position: relative;
+ transition: border-color 0.2s, box-shadow 0.2s, width 0.25s, height 0.25s;
+}
+/* status dot inside ring */
+.node-dot {
+ width: 7px; height: 7px;
+ border-radius: 50%;
+ position: absolute;
+ bottom: 4px; right: 4px;
+}
+.dot-ok { background: var(--ok); }
+.dot-warn { background: var(--warn); }
+.dot-error { background: var(--err); }
.dot-unknown { background: var(--unknown); }
-/* ─── Stat tiles ─────────────────────────────────────────────────────────── */
-.stat-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
-.stat-tile { text-align: center; padding: 12px 8px; background: var(--bg); border-radius: 4px; border: 1px solid var(--border); }
-.stat-value { font-size: 28px; font-weight: 700; line-height: 1; color: var(--text); }
-.stat-label { font-size: 11px; color: var(--muted); margin-top: 4px; text-transform: uppercase; letter-spacing: 0.06em; }
-.stat-value.active { color: var(--ok); }
-.stat-value.superseded { color: var(--super-tag); }
-
-/* ─── Repository rows ────────────────────────────────────────────────────── */
-.repo-row { padding: 8px 0; border-bottom: 1px solid var(--border); }
-.repo-row:last-child { border-bottom: none; }
-.repo-name { font-size: 13px; font-weight: 600; margin-bottom: 5px; color: var(--text); }
-.repo-slots { display: flex; gap: 8px; flex-wrap: wrap; }
-.repo-slot { display: flex; align-items: center; gap: 5px; font-size: 11px; font-family: var(--font-mono); color: var(--muted); }
-.repo-slot .slot-label { color: var(--muted); font-size: 10px; text-transform: uppercase; }
-.repo-slot .slot-commit { color: var(--accent); }
-.repo-slot .slot-warn { color: var(--warn); }
-.repo-slot .slot-err { color: var(--err); }
-
-/* ─── Knowledge table ────────────────────────────────────────────────────── */
-.knowledge-list { width: 100%; }
-.kl-row { display: grid; grid-template-columns: 140px 90px 1fr 80px; gap: 10px; align-items: start; padding: 8px 0; border-bottom: 1px solid var(--border); }
-.kl-row:last-child { border-bottom: none; }
-.kl-header { font-size: 10px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); padding-bottom: 6px; border-bottom: 1px solid var(--border); margin-bottom: 2px; }
-
-.kl-ts { font-size: 11px; font-family: var(--font-mono); color: var(--muted); }
-.kl-type { font-size: 11px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
-.kl-title { font-size: 13px; color: var(--text); }
-.kl-super { font-size: 11px; color: var(--muted); margin-top: 2px; }
-.kl-super .arrow { color: var(--super-tag); }
-.kl-super .replaced-by { color: var(--text); }
-
-.badge { display: inline-block; font-size: 10px; font-weight: 600; padding: 1px 6px; border-radius: 10px; text-transform: uppercase; letter-spacing: 0.04em; }
-.badge-active { background: rgba(63,185,80,0.15); color: var(--ok); border: 1px solid rgba(63,185,80,0.35); }
-.badge-superseded { background: rgba(110,64,201,0.15); color: #a371f7; border: 1px solid rgba(110,64,201,0.35); }
-
-/* ─── Error / loading states ─────────────────────────────────────────────── */
-.loading { color: var(--muted); font-size: 13px; padding: 20px; text-align: center; }
-.error-banner { background: rgba(248,81,73,0.12); border: 1px solid rgba(248,81,73,0.4); border-radius: var(--radius); padding: 10px 14px; margin-bottom: 16px; font-size: 13px; color: var(--err); display: none; }
-
-/* ─── Refresh bar ────────────────────────────────────────────────────────── */
-.refresh-bar { display: flex; align-items: center; gap: 10px; font-size: 12px; color: var(--muted); }
-.refresh-bar button {
- background: none; border: 1px solid var(--border); color: var(--muted); border-radius: 4px;
- padding: 2px 10px; cursor: pointer; font-size: 11px;
-}
-.refresh-bar button:hover { border-color: var(--accent); color: var(--accent); }
-
-/* ─── Full-width section ─────────────────────────────────────────────────── */
-.full { margin-bottom: 16px; }
+/* pulse animation for non-ok nodes */
+.node.pulse .node-ring::after {
+ content: "";
+ position: absolute;
+ inset: -6px;
+ border-radius: 50%;
+ border: 1px solid currentColor;
+ opacity: 0;
+ animation: pulse-ring 2.2s ease-out infinite;
+}
+@keyframes pulse-ring {
+ 0% { opacity: 0.5; transform: scale(1); }
+ 100% { opacity: 0; transform: scale(1.4); }
+}
+
+.node-label {
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--muted);
+ margin-top: 5px;
+ letter-spacing: 0.05em;
+ text-align: center;
+ transition: color 0.2s;
+ white-space: nowrap;
+}
+.node-sublabel {
+ font-size: 10px;
+ color: var(--dim);
+ font-family: var(--mono);
+ margin-top: 1px;
+ text-align: center;
+ white-space: nowrap;
+}
+
+/* Per-node sizes and accent colours */
+.n-tars .node-ring { border-color: rgba(88,166,255,0.35); color: var(--c-tars); background: rgba(88,166,255,0.05); width: 72px; height: 72px; font-size: 11px; }
+.n-tkc .node-ring { border-color: rgba(63,185,80,0.35); color: var(--c-tkc); background: rgba(63,185,80,0.05); width: 60px; height: 60px; }
+.n-bob .node-ring { border-color: rgba(210,153,34,0.35); color: var(--c-bob); background: rgba(210,153,34,0.05); width: 56px; height: 56px; }
+.n-mcp .node-ring { border-color: rgba(163,113,247,0.35); color: var(--c-mcp); background: rgba(163,113,247,0.05); width: 56px; height: 56px; }
+.n-ton .node-ring { border-color: rgba(79,179,216,0.35); color: var(--c-ton); background: rgba(79,179,216,0.05); width: 56px; height: 56px; }
+
+/* Selected state */
+.node.selected .node-ring {
+ border-width: 2px;
+ box-shadow: 0 0 18px -4px currentColor;
+}
+.node.selected .node-label { color: var(--text); }
+.node.selected.n-tars .node-ring { border-color: var(--c-tars); width: 80px; height: 80px; }
+.node.selected.n-tkc .node-ring { border-color: var(--c-tkc); width: 68px; height: 68px; }
+.node.selected.n-bob .node-ring { border-color: var(--c-bob); width: 64px; height: 64px; }
+.node.selected.n-mcp .node-ring { border-color: var(--c-mcp); width: 64px; height: 64px; }
+.node.selected.n-ton .node-ring { border-color: var(--c-ton); width: 64px; height: 64px; }
+
+/* Dimmed (unrelated) primary nodes */
+.node.dimmed { opacity: 0.18; pointer-events: none; }
+
+/* ─── Secondary nodes ─────────────────────────────────────────────────────── */
+.sec-node {
+ position: absolute;
+ transform: translate(-50%, -50%);
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ z-index: 2;
+ cursor: default;
+ transition: left 0.38s cubic-bezier(0.4,0,0.2,1),
+ top 0.38s cubic-bezier(0.4,0,0.2,1),
+ opacity 0.25s ease;
+ opacity: 0;
+ pointer-events: none;
+}
+.sec-node.visible {
+ opacity: 1;
+}
+.sec-node.clickable {
+ cursor: pointer;
+ pointer-events: auto;
+}
+.sec-node.clickable:hover .sec-ring {
+ border-color: var(--c-tkc);
+ color: var(--c-tkc);
+}
+.sec-ring {
+ width: 40px; height: 40px;
+ border-radius: 50%;
+ border: 1px dashed var(--border-hi);
+ color: var(--muted);
+ background: rgba(255,255,255,0.03);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 9px;
+ transition: border-color 0.2s, color 0.2s;
+}
+/* Static/capability secondary nodes (MCP tools etc) — square-dashed */
+.sec-ring.static {
+ border-style: dotted;
+ border-color: var(--dim);
+ color: var(--dim);
+ background: rgba(255,255,255,0.015);
+}
+/* Selected secondary */
+.sec-node.sec-selected .sec-ring {
+ border-color: var(--c-tkc);
+ border-style: solid;
+ color: var(--c-tkc);
+ box-shadow: 0 0 12px -4px var(--c-tkc);
+}
+.sec-label {
+ font-size: 10px;
+ color: var(--dim);
+ margin-top: 4px;
+ text-align: center;
+ max-width: 64px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ letter-spacing: 0.02em;
+}
+.sec-node.clickable .sec-label { color: var(--muted); }
+.sec-sublabel {
+ font-size: 9px;
+ color: var(--dim);
+ font-family: var(--mono);
+ text-align: center;
+ max-width: 70px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+/* ─── Tertiary knowledge micro-nodes ──────────────────────────────────────── */
+.kn-node {
+ position: absolute;
+ transform: translate(-50%, -50%);
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ z-index: 2;
+ cursor: default;
+ pointer-events: none;
+ transition: left 0.38s cubic-bezier(0.4,0,0.2,1),
+ top 0.38s cubic-bezier(0.4,0,0.2,1),
+ opacity 0.25s ease;
+ opacity: 0;
+}
+.kn-node.visible { opacity: 1; }
+.kn-dot {
+ width: 10px; height: 10px;
+ border-radius: 50%;
+ background: rgba(63,185,80,0.25);
+ border: 1px solid rgba(63,185,80,0.5);
+ flex-shrink: 0;
+}
+.kn-dot.sup {
+ background: rgba(163,113,247,0.18);
+ border: 1px solid rgba(163,113,247,0.35);
+ background-clip: padding-box;
+ /* hollow look */
+ background-image: radial-gradient(circle, transparent 3px, rgba(163,113,247,0.18) 3px);
+}
+.kn-label {
+ font-size: 9px;
+ color: var(--muted);
+ margin-top: 3px;
+ max-width: 80px;
+ text-align: center;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font-family: var(--mono);
+ line-height: 1.3;
+}
+.kn-label.sup {
+ color: var(--dim);
+ text-decoration: line-through;
+ text-decoration-color: var(--super);
+}
+.kn-more {
+ font-size: 9px;
+ color: var(--dim);
+ font-style: italic;
+ text-align: center;
+ font-family: var(--mono);
+}
+
+/* ─── SVG edge classes ────────────────────────────────────────────────────── */
+.conn {
+ stroke-width: 1;
+ stroke: var(--border-hi);
+ opacity: 0.4;
+ transition: opacity 0.2s, stroke-width 0.2s;
+}
+.conn.lit {
+ opacity: 0.85;
+ stroke-width: 1.5;
+}
+.conn.dimmed-line { opacity: 0.04; }
+/* Secondary edges */
+.conn-sec {
+ stroke: var(--border-hi);
+ stroke-width: 0.8;
+ stroke-dasharray: 3 3;
+ opacity: 0;
+ transition: opacity 0.3s;
+}
+.conn-sec.visible { opacity: 0.5; }
+/* Static/capability secondary edges */
+.conn-sec.static-edge {
+ stroke: var(--dim);
+ opacity: 0;
+}
+.conn-sec.static-edge.visible { opacity: 0.3; }
+/* Superseding arcs */
+.conn-super {
+ stroke: var(--super);
+ stroke-width: 1;
+ stroke-dasharray: 4 3;
+ opacity: 0;
+ transition: opacity 0.3s;
+ marker-end: url(#arrow-super);
+}
+.conn-super.visible { opacity: 0.55; }
+/* Knowledge micro-node edges */
+.conn-kn {
+ stroke: rgba(63,185,80,0.3);
+ stroke-width: 0.7;
+ opacity: 0;
+ transition: opacity 0.3s;
+}
+.conn-kn.visible { opacity: 1; }
+.conn-kn.sup-kn {
+ stroke: rgba(163,113,247,0.3);
+}
+
+/* ─── Info overlay ────────────────────────────────────────────────────────── */
+#overlay {
+ position: absolute;
+ z-index: 20;
+ width: 280px;
+ background: var(--surface2);
+ border: 1px solid var(--border-hi);
+ border-radius: 6px;
+ padding: 12px 14px 10px;
+ font-size: 12px;
+ pointer-events: none;
+ opacity: 0;
+ transform: translateY(4px);
+ transition: opacity 0.18s ease, transform 0.18s ease;
+}
+#overlay.open {
+ opacity: 1;
+ transform: translateY(0);
+ pointer-events: auto;
+}
+.ov-head {
+ font-size: 11px;
+ font-weight: 700;
+ color: var(--text);
+ letter-spacing: 0.06em;
+ margin-bottom: 8px;
+ padding-bottom: 6px;
+ border-bottom: 1px solid var(--border);
+}
+.ov-row {
+ display: flex;
+ justify-content: space-between;
+ align-items: baseline;
+ gap: 6px;
+ padding: 2px 0;
+}
+.ov-key {
+ color: var(--muted);
+ font-size: 11px;
+ flex-shrink: 0;
+ min-width: 90px;
+}
+.ov-val {
+ color: var(--text);
+ font-size: 11px;
+ text-align: right;
+ font-family: var(--mono);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 160px;
+}
+.ov-val.ok { color: var(--ok); }
+.ov-val.warn { color: var(--warn); }
+.ov-val.err { color: var(--err); }
+.ov-val.un { color: var(--dim); font-style: italic; }
+.ov-val.sup { color: var(--super); }
+.ov-note {
+ font-size: 10px;
+ color: var(--dim);
+ margin-top: 6px;
+ padding-top: 5px;
+ border-top: 1px solid var(--border);
+ line-height: 1.4;
+}
+/* Spill pills inside overlay */
+.spill {
+ display: inline-flex; align-items: center; gap: 4px;
+ font-size: 10px; font-weight: 600; border-radius: 10px;
+ padding: 1px 6px; border: 1px solid transparent; line-height: 1.4;
+}
+.spill-ok { color: var(--ok); border-color: rgba(63,185,80,0.35); background: rgba(63,185,80,0.08); }
+.spill-warn { color: var(--warn); border-color: rgba(210,153,34,0.35); background: rgba(210,153,34,0.08); }
+.spill-err { color: var(--err); border-color: rgba(248,81,73,0.35); background: rgba(248,81,73,0.08); }
+.spill-partial { color: var(--warn); border-color: rgba(210,153,34,0.35); background: rgba(210,153,34,0.08); }
+.spill-unknown { color: var(--dim); border-color: rgba(72,79,88,0.5); background: rgba(72,79,88,0.08); }
+.spill-dot { width: 5px; height: 5px; border-radius: 50%; background: currentColor; }
+
+/* ─── Bottom-sheet fallback (narrow viewports) ────────────────────────────── */
+@media (max-width: 699px) {
+ #overlay {
+ position: fixed !important;
+ left: 0 !important; right: 0 !important; top: auto !important;
+ bottom: 0 !important;
+ width: 100% !important;
+ border-radius: 10px 10px 0 0;
+ border-bottom: none;
+ transform: translateY(8px);
+ max-height: 48vh;
+ overflow-y: auto;
+ }
+ #overlay.open { transform: translateY(0); }
+}
+
+/* ─── Idle strip ──────────────────────────────────────────────────────────── */
+#idle-strip {
+ position: absolute;
+ bottom: 18px;
+ left: 50%;
+ transform: translateX(-50%);
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 11px;
+ color: var(--dim);
+ pointer-events: none;
+ z-index: 5;
+ transition: opacity 0.2s;
+ white-space: nowrap;
+}
+#idle-strip.hidden { opacity: 0; }
+
+/* ─── Keyboard hint ───────────────────────────────────────────────────────── */
+#kbd-hint {
+ position: absolute;
+ bottom: 18px;
+ right: 18px;
+ font-size: 10px;
+ color: var(--dim);
+ pointer-events: none;
+ z-index: 5;
+}
+
+/* ─── Node labels hidden on very small screens ────────────────────────────── */
+@media (max-width: 399px) {
+ .node-label, .node-sublabel, .sec-label, .sec-sublabel { display: none; }
+}
+
+/* ─── Navigation arrows (transparent, viewport-edge) ─────────────────────── */
+.nav-arrow {
+ position: absolute;
+ top: 50%;
+ transform: translateY(-50%);
+ z-index: 30;
+ width: 44px;
+ height: 80px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ border-radius: 6px;
+ background: rgba(255,255,255,0.03);
+ border: 1px solid rgba(255,255,255,0.06);
+ color: rgba(255,255,255,0.22);
+ font-size: 20px;
+ transition: background 0.18s, color 0.18s, opacity 0.18s;
+ user-select: none;
+ -webkit-tap-highlight-color: transparent;
+}
+.nav-arrow:hover {
+ background: rgba(88,166,255,0.08);
+ color: rgba(88,166,255,0.7);
+ border-color: rgba(88,166,255,0.18);
+}
+.nav-arrow.hidden { opacity: 0; pointer-events: none; }
+#nav-left { left: 10px; }
+#nav-right { right: 10px; }
+
+/* ─── Side views (Home / Pond) ────────────────────────────────────────────── */
+.side-view {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 0.32s cubic-bezier(0.4,0,0.2,1);
+ z-index: 4;
+ overflow-y: auto;
+}
+.side-view.visible {
+ opacity: 1;
+ pointer-events: auto;
+}
+/* Center-view wrapper */
+#center-view {
+ position: absolute;
+ inset: 0;
+ transition: opacity 0.32s cubic-bezier(0.4,0,0.2,1);
+ z-index: 3;
+}
+#center-view.hidden { opacity: 0; pointer-events: none; }
+
+/* Side view card grid */
+.sv-grid {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 14px;
+ justify-content: center;
+ padding: 20px 60px 20px;
+ max-width: 760px;
+ width: 100%;
+}
+.sv-card {
+ background: var(--surface);
+ border: 1px solid var(--border-hi);
+ border-radius: 6px;
+ padding: 14px 18px;
+ min-width: 200px;
+ flex: 1 1 200px;
+ max-width: 320px;
+}
+.sv-card-title {
+ font-size: 10px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.1em;
+ color: var(--muted);
+ margin-bottom: 12px;
+}
+.sv-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 4px 0;
+ border-bottom: 1px solid var(--border);
+ gap: 8px;
+}
+.sv-row:last-child { border-bottom: none; }
+.sv-name { font-size: 12px; color: var(--text); }
+.sv-val { font-size: 12px; font-family: var(--mono); color: var(--muted); }
+.sv-label {
+ font-size: 30px;
+ font-weight: 700;
+ letter-spacing: 0.14em;
+ color: var(--dim);
+ text-transform: uppercase;
+ margin-bottom: 6px;
+ text-align: center;
+}
+.sv-sub {
+ font-size: 11px;
+ color: var(--dim);
+ letter-spacing: 0.06em;
+ text-align: center;
+ margin-bottom: 22px;
+}
+/* View indicator dots */
+#view-dots {
+ position: absolute;
+ bottom: 14px;
+ left: 50%;
+ transform: translateX(-50%);
+ display: flex;
+ gap: 7px;
+ z-index: 30;
+ pointer-events: none;
+}
+.view-dot {
+ width: 5px; height: 5px;
+ border-radius: 50%;
+ background: var(--dim);
+ transition: background 0.2s;
+}
+.view-dot.active { background: var(--muted); }
+
</style>
</head>
<body>
-<div class="page">
-
- <!-- Header -->
- <div class="header">
- <h1>TARS CONTROL</h1>
- <div class="refresh-bar">
- <span id="last-updated">—</span>
- <button onclick="refresh()">↻ Refresh</button>
+
+<div id="topbar">
+ <div id="topbar-title">TARS Control</div>
+ <div id="topbar-meta">
+ <span id="last-updated">—</span>
+ <button onclick="doRefresh()">↻</button>
+ </div>
+</div>
+<div id="error-banner"></div>
+
+<div id="canvas">
+
+ <!-- Navigation arrows (NavigationBus entry points) -->
+ <div id="nav-left" class="nav-arrow" role="button" aria-label="Previous view" tabindex="0">←</div>
+ <div id="nav-right" class="nav-arrow" role="button" aria-label="Next view" tabindex="0">→</div>
+
+ <!-- View indicator dots -->
+ <div id="view-dots">
+ <div class="view-dot" id="vdot-0"></div>
+ <div class="view-dot" id="vdot-1"></div>
+ <div class="view-dot" id="vdot-2"></div>
+ </div>
+
+ <!-- HOME / Zuhause side view -->
+ <div class="side-view" id="view-home">
+ <div class="sv-label">Zuhause</div>
+ <div class="sv-sub">Home</div>
+ <div class="sv-grid" id="home-grid">
+ <div class="sv-card">
+ <div class="sv-card-title">Status</div>
+ <div class="sv-row"><span class="sv-name" style="color:var(--dim);font-size:11px">Loading…</span></div>
+ </div>
+ </div>
+ </div>
+
+ <!-- POND / Teich side view -->
+ <div class="side-view" id="view-pond">
+ <div class="sv-label">Teich</div>
+ <div class="sv-sub">Pond</div>
+ <div class="sv-grid" id="pond-grid">
+ <div class="sv-card">
+ <div class="sv-card-title">Status</div>
+ <div class="sv-row"><span class="sv-name" style="color:var(--dim);font-size:11px">Loading…</span></div>
+ </div>
</div>
</div>
- <div id="error-banner" class="error-banner"></div>
+ <!-- CENTER-VIEW wrapper (existing topology graph content lives here) -->
+ <div id="center-view">
- <!-- ── Row 1: System + Knowledge ──────────────────────────────────────── -->
- <div class="grid-2">
+ <!-- SVG edge layer -->
+ <svg id="topo-svg" aria-hidden="true">
+ <defs>
+ <marker id="arrow-super" markerWidth="6" markerHeight="6"
+ refX="5" refY="3" orient="auto">
+ <path d="M0,0 L0,6 L6,3 z" fill="#a371f7" opacity="0.7"/>
+ </marker>
+ </defs>
+ </svg>
- <!-- System -->
- <div class="card" id="card-system">
- <div class="card-title">System</div>
- <div id="system-body" class="loading">Loading…</div>
+ <!-- Primary nodes -->
+ <div class="node n-tars" id="node-tars" onclick="selectNode('tars')" role="button" aria-label="TARS system node" tabindex="0">
+ <div class="node-ring" id="ring-tars">
+ <span class="node-dot dot-unknown" id="dot-tars"></span>
</div>
+ <div class="node-label">System</div>
+ </div>
- <!-- Knowledge stats -->
- <div class="card" id="card-knowledge">
- <div class="card-title">Knowledge</div>
- <div id="knowledge-body" class="loading">Loading…</div>
+ <div class="node n-tkc" id="node-tkc" onclick="selectNode('tkc')" role="button" aria-label="TKC knowledge core node" tabindex="0">
+ <div class="node-ring" id="ring-tkc">
+ <span class="node-dot dot-unknown" id="dot-tkc"></span>
</div>
+ <div class="node-label">Knowledge</div>
+ <div class="node-sublabel" id="sub-tkc">—</div>
+ </div>
+ <div class="node n-bob" id="node-bob" onclick="selectNode('bob')" role="button" aria-label="Bob AI-001 agent node" tabindex="0">
+ <div class="node-ring" id="ring-bob">
+ <span class="node-dot dot-unknown" id="dot-bob"></span>
+ </div>
+ <div class="node-label">AI-001</div>
</div>
- <!-- ── Row 2: Repositories ────────────────────────────────────────────── -->
- <div class="full">
- <div class="card" id="card-repos">
- <div class="card-title">Repositories</div>
- <div id="repos-body" class="loading">Loading…</div>
+ <div class="node n-mcp" id="node-mcp" onclick="selectNode('mcp')" role="button" aria-label="MCP interface node" tabindex="0">
+ <div class="node-ring" id="ring-mcp">
+ <span class="node-dot dot-unknown" id="dot-mcp"></span>
</div>
+ <div class="node-label">Interface</div>
</div>
- <!-- ── Row 3: Recent Knowledge ───────────────────────────────────────── -->
- <div class="full">
- <div class="card" id="card-recent">
- <div class="card-title">Recent Knowledge</div>
- <div id="recent-body" class="loading">Loading…</div>
+ <div class="node n-ton" id="node-ton" onclick="selectNode('ton')" role="button" aria-label="TON-01 infrastructure node" tabindex="0">
+ <div class="node-ring" id="ring-ton">
+ <span class="node-dot dot-unknown" id="dot-ton"></span>
</div>
+ <div class="node-label">TON-01</div>
+ </div>
+
+ <!-- Secondary + tertiary nodes injected by JS -->
+
+ <!-- Info overlay -->
+ <div id="overlay"></div>
+
+ <!-- Idle strip -->
+ <div id="idle-strip">
+ <span id="idle-summary" style="color:var(--dim)">Loading…</span>
</div>
+ <div id="kbd-hint">esc to clear</div>
-</div><!-- .page -->
+ </div><!-- /#center-view -->
+</div>
<script>
// ─────────────────────────────────────────────────────────────────────────────
-// Configuration
-//
-// TARS Control v0.1 is VPN/internal-only.
-// The aggregator is accessed through the same trusted nginx origin — no Bearer
-// token is embedded in this file. Authentication is enforced at the network
-// layer (VPN membership + nginx subnet restriction). External authentication
-// can be designed separately when a public-facing surface is required.
+// TARS Control v0.3 — "TARS Brain" focus-graph interaction model
//
-// STATUS_URL: nginx proxies /tars-status → tars-status service on 127.0.0.1:8900
+// Data source: GET /tars-status (tars-status aggregator, VPN-internal)
+// No credentials in this file. Auth enforced at nginx/VPN layer.
// ─────────────────────────────────────────────────────────────────────────────
const STATUS_URL = "/tars-status";
const REFRESH_MS = 30_000;
+const KN_CAP = 6; // max knowledge micro-nodes before +N indicator
+
+// ─── State ───────────────────────────────────────────────────────────────────
+
+let currentData = null; // last successful /tars-status payload
+let selectedNode = null; // primary node id or null
+let selectedSecNode = null; // secondary node id or null ('knowledge' only for now)
+let refreshTimer = null;
+
+// ─── Canvas geometry ─────────────────────────────────────────────────────────
+// Positions are computed in px at layout time and stored here.
+// All nodes (primary + secondary + tertiary) are absolutely positioned.
+
+const primaryIds = ["tars","tkc","bob","mcp","ton"];
+
+// Idle layout: radial arrangement around canvas centre
+// Returns {id: {x, y}} in px given canvas w, h
+function idlePositions(w, h) {
+ const cx = w * 0.50;
+ const cy = h * 0.50;
+ const rx = Math.min(w * 0.34, 210);
+ const ry = Math.min(h * 0.36, 170);
+ return {
+ tars: { x: cx, y: cy - ry }, // top-centre
+ tkc: { x: cx - rx * 0.55, y: cy + ry * 0.15 }, // mid-left
+ mcp: { x: cx + rx * 0.55, y: cy + ry * 0.15 }, // mid-right
+ bob: { x: cx - rx, y: cy - ry * 0.15 }, // left
+ ton: { x: cx, y: cy + ry }, // bottom-centre
+ };
+}
+
+// Focus layout: selected node at focus point; related nodes orbit around it
+function focusPositions(w, h, sel) {
+ const focusX = w * 0.50;
+ const focusY = h * 0.48;
+ const orbitR = Math.min(w * 0.30, 185);
+ const orbitRY = Math.min(h * 0.28, 140);
+
+ const related = (ADJ[sel] || []);
+ const unrelated = primaryIds.filter(id => id !== sel && !related.includes(id));
+
+ const pos = {};
+ pos[sel] = { x: focusX, y: focusY };
+
+ // Distribute related nodes in an arc above/around focus point
+ const n = related.length;
+ related.forEach((id, i) => {
+ const span = Math.PI * 1.1;
+ const start = -Math.PI / 2 - span / 2;
+ const angle = n === 1 ? -Math.PI / 2 : start + (span / (n - 1)) * i;
+ pos[id] = {
+ x: focusX + Math.cos(angle) * orbitR,
+ y: focusY + Math.sin(angle) * orbitRY,
+ };
+ });
+
+ // Push unrelated nodes to canvas edges
+ const corners = [
+ { x: w * 0.08, y: h * 0.10 },
+ { x: w * 0.92, y: h * 0.10 },
+ { x: w * 0.08, y: h * 0.90 },
+ { x: w * 0.92, y: h * 0.90 },
+ ];
+ unrelated.forEach((id, i) => {
+ pos[id] = corners[i % corners.length];
+ });
+
+ return pos;
+}
+
+// Current resolved positions for primary nodes (updated on layout)
+let resolvedPos = {};
+
+// ─── Primary edge definitions ─────────────────────────────────────────────────
+const EDGES = [
+ ["tars", "tkc", "--c-tars"],
+ ["tars", "bob", "--c-bob"],
+ ["tars", "mcp", "--c-mcp"],
+ ["bob", "tkc", "--border-hi"],
+ ["bob", "mcp", "--c-mcp"],
+ ["tkc", "mcp", "--border-hi"],
+ ["tkc", "ton", "--c-ton"],
+ ["bob", "ton", "--c-ton"],
+ ["mcp", "ton", "--c-ton"],
+];
+
+// Adjacency map (which primary nodes are directly connected)
+const ADJ = {
+ tars: ["tkc","bob","mcp"],
+ tkc: ["tars","bob","mcp","ton"],
+ bob: ["tars","tkc","mcp","ton"],
+ mcp: ["tars","tkc","bob","ton"],
+ ton: ["tkc","bob","mcp"],
+};
-let refreshTimer = null;
+// ─── Secondary node definitions per focused primary ───────────────────────────
+// type: 'live' = derived from telemetry, 'static' = known from architecture
+function secondaryDefs(focusId, data) {
+ const ss = (data && data.subsystems) || {};
+ const repos = (data && data.repositories) || [];
+ const services = (data && data.services) || [];
-// ─── Fetch ───────────────────────────────────────────────────────────────────
+ const svcStatus = (name) => {
+ const s = services.find(x => x.name === name);
+ return s ? s.status : "unknown";
+ };
+ const sub = (id, label, sublabel, type, clickable, statusHint) =>
+ ({ id, label, sublabel: sublabel || "", type: type || "live", clickable: !!clickable, statusHint: statusHint || null });
+
+ switch (focusId) {
+ case "tkc":
+ return [
+ sub("sec-pg", "PostgreSQL", "lifecycle", "live", false, _normalise(ss.postgresql)),
+ sub("sec-mv", "Milvus", "vectors", "live", false, _normalise(ss.milvus)),
+ sub("sec-neo", "Neo4j", "graph", "live", false, _normalise(ss.neo4j)),
+ sub("sec-know", "Knowledge", "objects", "live", true, null),
+ ];
+ case "bob":
+ return [
+ sub("sec-mcp-conn", "MCP", "interface", "live", false, svcStatus("MCP Server")),
+ sub("sec-tkc-conn", "TKC", "via MCP", "live", false, svcStatus("TKC")),
+ ...repos.map((r, i) => sub(
+ `sec-repo-${i}`,
+ r.name.replace("tars-",""),
+ r.dev_commit ? r.dev_commit.slice(0,7) : "?",
+ "live", false,
+ r.dev_clean === false ? "warn" : "ok"
+ )),
+ ];
+ case "mcp":
+ return [
+ sub("sec-tool-health", "tkc_health", "read-only", "static", false),
+ sub("sec-tool-search", "tkc_search", "read-only", "static", false),
+ sub("sec-tool-query", "tkc_query", "read-only", "static", false),
+ ];
+ case "ton":
+ return [
+ sub("sec-tkc-svc", "tkc-service", ":8110", "live", false, svcStatus("TKC")),
+ sub("sec-mcp-svc", "mcp-server", ":8765", "live", false, svcStatus("MCP Server")),
+ sub("sec-gw-svc", "gateway", ":8080", "live", false, svcStatus("Engineering Gateway")),
+ sub("sec-status-svc", "tars-status", ":8120", "live", false, "ok"),
+ ];
+ case "tars":
+ default:
+ return [];
+ }
+}
+
+// ─── Secondary node layout (orbit positions) ──────────────────────────────────
+function secondaryPositions(focusId, secNodes, w, h) {
+ const focus = resolvedPos[focusId];
+ if (!focus || secNodes.length === 0) return {};
+
+ const n = secNodes.length;
+ // Orbit secondary nodes below / around the focused node
+ const r = Math.min(w * 0.22, 130);
+ const ry = Math.min(h * 0.22, 115);
+ const spanAngle = Math.PI * 1.0;
+ const startAngle = Math.PI * 0.15; // arc from ~lower-left to ~lower-right
+
+ const pos = {};
+ secNodes.forEach((s, i) => {
+ const angle = n === 1
+ ? Math.PI / 2
+ : startAngle + (spanAngle / (n - 1)) * i;
+ pos[s.id] = {
+ x: clamp(focus.x + Math.cos(angle) * r, 50, w - 50),
+ y: clamp(focus.y + Math.sin(angle) * ry, 40, h - 40),
+ };
+ });
+ return pos;
+}
+
+// ─── Knowledge tertiary node layout ──────────────────────────────────────────
+function knowledgePositions(knNodes, w, h) {
+ // Arc below the sec-know secondary node position
+ const secPos = currentSecPos["sec-know"];
+ if (!secPos || knNodes.length === 0) return {};
+
+ const n = knNodes.length;
+ const r = Math.min(w * 0.18, 110);
+ const spanAngle = Math.PI * 0.9;
+ const startAngle = Math.PI * 0.2;
+
+ const pos = {};
+ knNodes.forEach((kn, i) => {
+ const angle = n === 1
+ ? Math.PI / 2
+ : startAngle + (spanAngle / (n - 1)) * i;
+ pos[kn.id] = {
+ x: clamp(secPos.x + Math.cos(angle) * r, 40, w - 40),
+ y: clamp(secPos.y + Math.sin(angle) * r * 0.8, 40, h - 40),
+ };
+ });
+ return pos;
+}
+
+let currentSecPos = {}; // id → {x,y} for active secondary nodes
+let currentKnPos = {}; // id → {x,y} for knowledge tertiary nodes
+
+// ─── Fetch ────────────────────────────────────────────────────────────────────
async function fetchStatus() {
- const res = await fetch(STATUS_URL);
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- return res.json();
+ const r = await fetch(STATUS_URL);
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ return r.json();
}
-// ─── Render helpers ───────────────────────────────────────────────────────────
+// ─── Helpers ─────────────────────────────────────────────────────────────────
-function dotClass(status) {
- if (status === "ok") return "dot dot-ok";
- if (status === "degraded") return "dot dot-warn";
- if (status === "error") return "dot dot-error";
- return "dot dot-unknown";
+function svc(data, name) {
+ return (data.services || []).find(s => s.name === name) || { name, status: "unknown", detail: null };
}
-function fmtTs(iso) {
- if (!iso) return "—";
- const d = new Date(iso);
- return d.toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
+function _normalise(raw) {
+ if (!raw || raw === "unknown") return "unknown";
+ if (["online","ok","healthy","active"].includes(raw)) return "ok";
+ if (["offline","error","down"].includes(raw)) return "error";
+ if (raw === "degraded") return "degraded";
+ return "unknown";
}
-function esc(str) {
- return String(str ?? "")
- .replace(/&/g, "&")
- .replace(/</g, "<")
- .replace(/>/g, ">")
- .replace(/"/g, """);
+function clamp(v, lo, hi) { return Math.max(lo, Math.min(hi, v)); }
+
+// ─── Derived statuses ─────────────────────────────────────────────────────────
+function derivedStatuses(data) {
+ if (!data) return { tars:"unknown", tkc:"unknown", bob:"unknown", mcp:"unknown", ton:"unknown" };
+ const tkc = svc(data, "TKC").status;
+ const mcp = svc(data, "MCP Server").status;
+ const gw = svc(data, "Engineering Gateway").status;
+ const bob = mcp === "ok" ? "connected" : "unknown";
+ const tonStatuses = [tkc, gw];
+ const ton = tonStatuses.every(s => s === "ok") ? "ok"
+ : tonStatuses.some(s => s === "error") ? "error"
+ : tonStatuses.some(s => s === "ok") ? "degraded"
+ : "unknown";
+ const ss = data.subsystems || {};
+ const pgKnown = ss.postgresql && ss.postgresql !== "unknown";
+ const njKnown = ss.neo4j && ss.neo4j !== "unknown";
+ const coreOk = tkc === "ok" && mcp === "ok" && gw === "ok";
+ const tars = coreOk && pgKnown && njKnown ? "ok"
+ : coreOk && !pgKnown && !njKnown ? "partial"
+ : (tkc === "error" || mcp === "error") ? "error"
+ : "degraded";
+ return { tars, tkc, mcp, bob, ton };
}
-// ─── System panel ─────────────────────────────────────────────────────────────
+function dotCls(st) {
+ if (st === "ok" || st === "connected") return "dot-ok";
+ if (st === "error") return "dot-error";
+ if (st === "degraded" || st === "partial") return "dot-warn";
+ return "dot-unknown";
+}
-function renderSystem(services) {
- if (!services || !services.length) {
- document.getElementById("system-body").innerHTML = '<span class="loading">No data</span>';
- return;
+function spillCls(st) {
+ if (st === "ok" || st === "connected") return "spill-ok";
+ if (st === "error") return "spill-err";
+ if (st === "degraded")return "spill-warn";
+ if (st === "partial") return "spill-partial";
+ return "spill-unknown";
+}
+
+function spillHTML(st) {
+ return `<span class="spill ${spillCls(st)}"><span class="spill-dot"></span>${esc(st)}</span>`;
+}
+
+function secStatusDot(statusHint) {
+ if (!statusHint) return "";
+ const cls = statusHint === "ok" ? "dot-ok"
+ : statusHint === "warn" ? "dot-warn"
+ : statusHint === "error" ? "dot-error"
+ : statusHint === "unknown" ? "dot-unknown"
+ : dotCls(statusHint);
+ return `<span class="node-dot ${cls}" style="position:static;width:5px;height:5px;display:inline-block;margin-left:2px;flex-shrink:0"></span>`;
+}
+
+// ─── Layout & drawing ─────────────────────────────────────────────────────────
+
+function layout() {
+ const canvas = document.getElementById("canvas");
+ const w = canvas.offsetWidth;
+ const h = canvas.offsetHeight;
+
+ // 1. Compute primary node target positions
+ resolvedPos = selectedNode
+ ? focusPositions(w, h, selectedNode)
+ : idlePositions(w, h);
+
+ // 2. Move primary nodes
+ for (const id of primaryIds) {
+ const el = document.getElementById(`node-${id}`);
+ if (!el) continue;
+ const p = resolvedPos[id];
+ if (p) { el.style.left = p.x + "px"; el.style.top = p.y + "px"; }
}
- const rows = services.map(s => `
- <div class="svc-row">
- <span class="svc-name">${esc(s.name)}</span>
- <span class="svc-right">
- ${s.detail ? `<span class="svc-detail">${esc(s.detail)}</span>` : ""}
- <span class="${dotClass(s.status)}" title="${esc(s.status)}"></span>
- </span>
- </div>`).join("");
- document.getElementById("system-body").innerHTML = rows;
-}
-
-// ─── Knowledge stats panel ────────────────────────────────────────────────────
-
-function renderKnowledge(stats) {
- if (!stats) {
- document.getElementById("knowledge-body").innerHTML = '<span class="loading">Unavailable — new endpoint not yet deployed</span>';
- return;
+
+ // 3. Secondary nodes
+ if (selectedNode && currentData) {
+ const defs = secondaryDefs(selectedNode, currentData);
+ currentSecPos = secondaryPositions(selectedNode, defs, w, h);
+ defs.forEach(s => {
+ const el = document.getElementById(`secnode-${s.id}`);
+ if (el) {
+ const p = currentSecPos[s.id];
+ if (p) { el.style.left = p.x + "px"; el.style.top = p.y + "px"; }
+ }
+ });
}
- document.getElementById("knowledge-body").innerHTML = `
- <div class="stat-grid">
- <div class="stat-tile">
- <div class="stat-value">${stats.total}</div>
- <div class="stat-label">Total</div>
- </div>
- <div class="stat-tile">
- <div class="stat-value active">${stats.active}</div>
- <div class="stat-label">Active</div>
- </div>
- <div class="stat-tile">
- <div class="stat-value superseded">${stats.superseded}</div>
- <div class="stat-label">Superseded</div>
- </div>
- </div>`;
+
+ // 4. Knowledge tertiary nodes
+ if (selectedSecNode === "knowledge" && currentData) {
+ const knDefs = buildKnowledgeDefs(currentData);
+ currentKnPos = knowledgePositions(knDefs, w, h);
+ knDefs.forEach(kn => {
+ const el = document.getElementById(`knnode-${kn.id}`);
+ if (el) {
+ const p = currentKnPos[kn.id];
+ if (p) { el.style.left = p.x + "px"; el.style.top = p.y + "px"; }
+ }
+ });
+ }
+
+ // 5. Redraw edges
+ drawEdges(w, h);
+}
+
+function drawEdges(w, h) {
+ const svg = document.getElementById("topo-svg");
+ // Keep defs, remove everything else
+ const defs = svg.querySelector("defs");
+ svg.innerHTML = "";
+ if (defs) svg.appendChild(defs);
+
+ const cs = getComputedStyle(document.documentElement);
+ const col = varName => cs.getPropertyValue(varName).trim();
+
+ // Primary edges
+ for (const [a, b, colorVar] of EDGES) {
+ const pa = resolvedPos[a], pb = resolvedPos[b];
+ if (!pa || !pb) continue;
+ const line = makeLine(pa.x, pa.y, pb.x, pb.y, col(colorVar) || "#30363d", ["conn"]);
+ line.dataset.edge = `${a}-${b}`;
+ if (selectedNode) {
+ const lit = a === selectedNode || b === selectedNode;
+ line.classList.add(lit ? "lit" : "dimmed-line");
+ }
+ svg.appendChild(line);
+ }
+
+ // Secondary edges
+ if (selectedNode && currentData) {
+ const defs2 = secondaryDefs(selectedNode, currentData);
+ defs2.forEach(s => {
+ const pa = resolvedPos[selectedNode];
+ const pb = currentSecPos[s.id];
+ if (!pa || !pb) return;
+ const cls = ["conn-sec"];
+ if (s.type === "static") cls.push("static-edge");
+ const line = makeLine(pa.x, pa.y, pb.x, pb.y, null, cls);
+ line.classList.add("visible");
+ svg.appendChild(line);
+ });
+ }
+
+ // Knowledge tertiary edges + superseding arcs
+ if (selectedSecNode === "knowledge" && currentData) {
+ const secKnowPos = currentSecPos["sec-know"];
+ if (secKnowPos) {
+ const knDefs = buildKnowledgeDefs(currentData);
+
+ // build id → pos lookup
+ const knPosMap = currentKnPos;
+
+ knDefs.forEach(kn => {
+ if (kn.isMore) return;
+ const pb = knPosMap[kn.id];
+ if (!pb) return;
+ const cls = ["conn-kn"];
+ if (kn.superseded) cls.push("sup-kn");
+ const line = makeLine(secKnowPos.x, secKnowPos.y, pb.x, pb.y, null, cls);
+ line.classList.add("visible");
+ svg.appendChild(line);
+ });
+
+ // Superseding arcs: superseded → replacement node (matched by object_id)
+ const recent = (currentData.knowledge_recent || []);
+ // Build object_id → knDef id map for visible nodes
+ const idMap = {};
+ knDefs.forEach(kn => { if (kn.objId) idMap[kn.objId] = kn.id; });
+
+ knDefs.forEach(kn => {
+ if (!kn.superseded || !kn.supersededBy) return;
+ const fromId = kn.id;
+ const toKnId = idMap[kn.supersededBy];
+ if (!toKnId) return; // replacement not in visible set — skip
+ const pa = knPosMap[fromId];
+ const pb = knPosMap[toKnId];
+ if (!pa || !pb) return;
+ const arc = makeLine(pa.x, pa.y, pb.x, pb.y, null, ["conn-super"]);
+ arc.classList.add("visible");
+ svg.appendChild(arc);
+ });
+ }
+ }
+}
+
+function makeLine(x1, y1, x2, y2, stroke, classes) {
+ const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
+ line.setAttribute("x1", x1); line.setAttribute("y1", y1);
+ line.setAttribute("x2", x2); line.setAttribute("y2", y2);
+ if (stroke) line.setAttribute("stroke", stroke);
+ classes.forEach(c => line.classList.add(c));
+ return line;
+}
+
+// ─── Knowledge tertiary node definitions ──────────────────────────────────────
+
+function buildKnowledgeDefs(data) {
+ const recent = (data.knowledge_recent || []).slice(0, KN_CAP + 1);
+ const total = data.knowledge_stats ? data.knowledge_stats.total : 0;
+ const capped = recent.slice(0, KN_CAP);
+ const overflow = total > KN_CAP ? total - KN_CAP : 0;
+
+ const defs = capped.map((o, i) => ({
+ id: `kn-${i}`,
+ objId: o.object_id || null,
+ label: (o.title || o.object_id || "?").slice(0, 28),
+ superseded: o.status === "superseded",
+ // Primary key: superseded_by object ID
+ supersededBy: o.superseded_by || null,
+ // Display fallback only
+ replacementTitle: o.replacement_title || null,
+ isMore: false,
+ }));
+
+ if (overflow > 0) {
+ defs.push({ id: "kn-more", isMore: true, label: `+${overflow} more`, superseded: false, supersededBy: null, objId: null, replacementTitle: null });
+ }
+ return defs;
}
-// ─── Repository panel ─────────────────────────────────────────────────────────
+// ─── DOM management for secondary / tertiary nodes ────────────────────────────
+
+function clearSecondaryNodes() {
+ document.querySelectorAll(".sec-node, .kn-node").forEach(el => el.remove());
+ currentSecPos = {};
+ currentKnPos = {};
+ selectedSecNode = null;
+}
+
+function renderSecondaryNodes(focusId, data) {
+ const canvas = document.getElementById("canvas");
+ const defs = secondaryDefs(focusId, data);
+
+ defs.forEach(s => {
+ const el = document.createElement("div");
+ el.className = "sec-node" + (s.clickable ? " clickable" : "");
+ el.id = `secnode-${s.id}`;
+ el.style.left = "-200px"; el.style.top = "-200px"; // off-screen until positioned
+
+ const ringClass = "sec-ring" + (s.type === "static" ? " static" : "");
+ const statusDot = s.type === "live" && s.statusHint
+ ? `<span class="node-dot ${dotCls(_normalise(s.statusHint))}" style="position:absolute;bottom:2px;right:2px;width:5px;height:5px"></span>`
+ : "";
+ el.innerHTML = `
+ <div class="${ringClass}" style="position:relative">${statusDot}</div>
+ <div class="sec-label">${esc(s.label)}</div>
+ ${s.sublabel ? `<div class="sec-sublabel">${esc(s.sublabel)}</div>` : ""}
+ `;
+
+ if (s.clickable) {
+ el.addEventListener("click", (e) => {
+ e.stopPropagation();
+ toggleKnowledgeNodes(data);
+ });
+ }
-function repoSlot(label, commit, clean, ahead, behind, diverged) {
- let cls = "slot-commit";
- let flags = "";
- if (ahead > 0) flags += ` <span class="slot-warn">+${ahead}</span>`;
- if (behind > 0) flags += ` <span class="slot-warn">-${behind}</span>`;
- if (diverged) flags += ` <span class="slot-warn">⚠ diverged</span>`;
- if (clean === false) flags += ` <span class="slot-warn">dirty</span>`;
- return `<span class="repo-slot">
- <span class="dot ${commit ? "dot-ok" : "dot-unknown"}"></span>
- <span class="slot-label">${esc(label)}</span>
- ${commit ? `<span class="${cls}">${esc(commit.substring(0, 7))}</span>` : ""}
- ${flags}
- </span>`;
+ canvas.appendChild(el);
+ // Trigger transition
+ requestAnimationFrame(() => el.classList.add("visible"));
+ });
}
-function renderRepos(repos) {
- if (!repos || !repos.length) {
- document.getElementById("repos-body").innerHTML = '<span class="loading">No data</span>';
+function toggleKnowledgeNodes(data) {
+ if (selectedSecNode === "knowledge") {
+ // Collapse
+ selectedSecNode = null;
+ document.querySelectorAll(".kn-node").forEach(el => el.remove());
+ document.getElementById("secnode-sec-know")?.classList.remove("sec-selected");
+ layout();
return;
}
- const rows = repos.map(r => {
- const errNote = r.error ? `<span style="color:var(--err);font-size:11px"> — ${esc(r.error)}</span>` : "";
- return `
- <div class="repo-row">
- <div class="repo-name">${esc(r.name)}${errNote}</div>
- <div class="repo-slots">
- ${repoSlot("DEV", r.dev_commit, r.dev_clean, r.dev_ahead || 0, r.dev_behind || 0, false)}
- ${repoSlot("LIVE", r.live_commit, r.live_clean, 0, 0, r.live_diverged)}
- </div>
- </div>`;
- }).join("");
- document.getElementById("repos-body").innerHTML = rows;
-}
-
-// ─── Recent knowledge panel ───────────────────────────────────────────────────
-
-function renderRecent(objects) {
- if (!objects || !objects.length) {
- document.getElementById("recent-body").innerHTML = '<span class="loading">Unavailable — new endpoint not yet deployed</span>';
+ selectedSecNode = "knowledge";
+ document.getElementById("secnode-sec-know")?.classList.add("sec-selected");
+ renderKnowledgeNodes(data);
+ layout();
+}
+
+function renderKnowledgeNodes(data) {
+ document.querySelectorAll(".kn-node").forEach(el => el.remove());
+ currentKnPos = {};
+
+ const canvas = document.getElementById("canvas");
+ const defs = buildKnowledgeDefs(data);
+
+ defs.forEach(kn => {
+ const el = document.createElement("div");
+ el.className = "kn-node";
+ el.id = `knnode-${kn.id}`;
+ el.style.left = "-200px"; el.style.top = "-200px";
+
+ if (kn.isMore) {
+ el.innerHTML = `<div class="kn-more">${esc(kn.label)}</div>`;
+ } else {
+ const dotCls2 = kn.superseded ? "kn-dot sup" : "kn-dot";
+ const lblCls = kn.superseded ? "kn-label sup" : "kn-label";
+ let extra = "";
+ if (kn.superseded && kn.replacementTitle) {
+ extra = `<div class="kn-more" style="color:var(--super);text-decoration:none">↱ ${esc(kn.replacementTitle.slice(0,20))}</div>`;
+ }
+ el.innerHTML = `<div class="${dotCls2}"></div><div class="${lblCls}">${esc(kn.label)}</div>${extra}`;
+ }
+
+ canvas.appendChild(el);
+ requestAnimationFrame(() => el.classList.add("visible"));
+ });
+}
+
+// ─── Node selection ───────────────────────────────────────────────────────────
+
+function selectNode(id) {
+ if (selectedNode === id) {
+ // Deselect
+ selectedNode = null;
+ clearSecondaryNodes();
+ applySelectionClasses();
+ closeOverlay();
+ layout();
return;
}
- const header = `
- <div class="kl-row kl-header">
- <span>Timestamp</span><span>Type</span><span>Title</span><span>Status</span>
- </div>`;
-
- const rows = objects.map(o => {
- const badgeCls = o.status === "active" ? "badge-active" : "badge-superseded";
- const supersededLine = (o.status === "superseded" && o.replacement_title)
- ? `<div class="kl-super"><span class="arrow">↳ replaced by</span> <span class="replaced-by">${esc(o.replacement_title)}</span></div>`
- : "";
- const reasonLine = (o.status === "superseded" && o.supersede_reason)
- ? `<div class="kl-super" title="${esc(o.supersede_reason)}" style="font-size:10px;color:var(--muted);max-width:400px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(o.supersede_reason)}</div>`
- : "";
- return `
- <div class="kl-row">
- <span class="kl-ts">${fmtTs(o.created_at)}</span>
- <span class="kl-type">${esc(o.object_type)}</span>
- <span class="kl-title">
- ${esc(o.title || o.object_id)}
- ${supersededLine}
- ${reasonLine}
- </span>
- <span><span class="badge ${badgeCls}">${esc(o.status)}</span></span>
- </div>`;
- }).join("");
+ clearSecondaryNodes();
+ selectedNode = id;
+ applySelectionClasses();
+ layout();
+ if (currentData) {
+ renderSecondaryNodes(id, currentData);
+ layout(); // re-layout after secondary nodes placed
+ showOverlay(id, currentData);
+ }
+}
+
+function applySelectionClasses() {
+ primaryIds.forEach(id => {
+ const el = document.getElementById(`node-${id}`);
+ if (!el) return;
+ el.classList.remove("selected","dimmed","pulse");
+ if (selectedNode) {
+ if (id === selectedNode) el.classList.add("selected");
+ else if (!(ADJ[selectedNode]||[]).includes(id)) el.classList.add("dimmed");
+ }
+ });
+
+ // Idle strip
+ document.getElementById("idle-strip").classList.toggle("hidden", !!selectedNode);
+ document.getElementById("kbd-hint").style.opacity = selectedNode ? "1" : "0.4";
+
+ // Restore pulses when deselected
+ if (!selectedNode && currentData) updatePulse(currentData);
+}
+
+// ─── Info overlay ──────────────────────────────────────────────────────────────
+
+function showOverlay(id, data) {
+ const ov = document.getElementById("overlay");
+ ov.innerHTML = buildOverlayHTML(id, data);
+ positionOverlay(id);
+ ov.classList.add("open");
+}
+
+function closeOverlay() {
+ document.getElementById("overlay").classList.remove("open");
+}
+
+function positionOverlay(id) {
+ if (window.innerWidth <= 699) return; // bottom-sheet handled by CSS
+ const ov = document.getElementById("overlay");
+ const canvas = document.getElementById("canvas");
+ const p = resolvedPos[id];
+ if (!p) return;
+ const ovW = 280, ovH = 200; // estimated height
+ const margin = 14;
+ const nodeH = 50;
+
+ let x = p.x - ovW / 2;
+ let y = p.y + nodeH + margin;
+
+ // Clamp to canvas bounds
+ x = clamp(x, margin, canvas.offsetWidth - ovW - margin);
+ y = clamp(y, margin, canvas.offsetHeight - ovH - margin);
- document.getElementById("recent-body").innerHTML = header + rows;
+ ov.style.left = x + "px";
+ ov.style.top = y + "px";
}
-// ─── Main refresh cycle ───────────────────────────────────────────────────────
+function buildOverlayHTML(id, data) {
+ const st = derivedStatuses(data);
+ const ss = data.subsystems || {};
+ const ks = data.knowledge_stats;
+ const repos = data.repositories || [];
-async function refresh() {
+ const row = (key, valHTML) =>
+ `<div class="ov-row"><span class="ov-key">${esc(key)}</span><span>${valHTML}</span></div>`;
+
+ switch (id) {
+ case "tars": {
+ const note = st.tars === "partial"
+ ? `<div class="ov-note">PostgreSQL + Neo4j telemetry not yet reported by TKC /health</div>`
+ : "";
+ return `<div class="ov-head">TARS — System</div>
+ ${row("system", spillHTML(st.tars))}
+ ${row("TKC", spillHTML(svc(data,"TKC").status))}
+ ${row("MCP", spillHTML(svc(data,"MCP Server").status))}
+ ${row("Gateway",spillHTML(svc(data,"Engineering Gateway").status))}
+ ${ks ? row("knowledge", `<span class="ov-val ok">${ks.active} active</span> <span class="ov-val" style="color:var(--super)">${ks.superseded} superseded</span>`) : ""}
+ ${note}`;
+ }
+ case "tkc": {
+ const lc = ss.knowledge_lifecycle;
+ return `<div class="ov-head">TKC — Knowledge Core</div>
+ ${row("service", spillHTML(svc(data,"TKC").status))}
+ ${row("lifecycle", spillHTML(lc && lc !== "unknown" ? "ok" : "unknown") + `<span style="font-size:10px;color:var(--dim);margin-left:4px">${esc(lc || "not reported")}</span>`)}
+ ${row("milvus", spillHTML(_normalise(ss.milvus)))}
+ ${row("postgresql",spillHTML(_normalise(ss.postgresql)) + `<span style="font-size:10px;color:var(--dim);margin-left:4px">not reported</span>`)}
+ ${row("neo4j", spillHTML(_normalise(ss.neo4j)) + `<span style="font-size:10px;color:var(--dim);margin-left:4px">not reported</span>`)}
+ ${ks ? row("objects", `<span class="ov-val">${ks.total} total · <span style="color:var(--ok)">${ks.active} active</span> · <span style="color:var(--super)">${ks.superseded} superseded</span></span>`) : ""}
+ <div class="ov-note">Click Knowledge secondary node to expand entries</div>`;
+ }
+ case "bob": {
+ const bobSt = svc(data,"MCP Server").status === "ok" ? "connected" : "unknown";
+ const repoRows = repos.map(r =>
+ `${esc(r.name.replace("tars-",""))} <span style="color:var(--c-tars)">${esc((r.dev_commit||"?").slice(0,7))}</span>${r.dev_clean===false?`<span style="color:var(--warn)"> dirty</span>`:""}`)
+ .join(" · ");
+ return `<div class="ov-head">Bob / AI-001 — Agent</div>
+ ${row("status", spillHTML(bobSt) + `<span style="font-size:10px;color:var(--dim);margin-left:4px">derived from MCP</span>`)}
+ ${row("MCP", spillHTML(svc(data,"MCP Server").status))}
+ ${row("endpoint", `<span class="ov-val un">dev.teich-tb.de/mcp</span>`)}
+ ${repos.length ? `<div class="ov-row" style="flex-wrap:wrap"><span class="ov-key">DEV</span><span style="font-size:10px;font-family:var(--mono);color:var(--muted)">${repoRows}</span></div>` : ""}`;
+ }
+ case "mcp": {
+ const m = svc(data,"MCP Server");
+ return `<div class="ov-head">MCP — Agent Interface</div>
+ ${row("service", spillHTML(m.status) + (m.detail ? `<span style="font-size:10px;color:var(--muted);margin-left:4px">${esc(m.detail)}</span>` : ""))}
+ ${row("transport", `<span class="ov-val un">Streamable HTTP · stateful</span>`)}
+ ${row("tools", `<span class="ov-val" style="color:var(--dim)">3 (read-only)</span>`)}
+ <div class="ov-note">Tool nodes shown are static capabilities, not live telemetry</div>`;
+ }
+ case "ton": {
+ const gw = svc(data,"Engineering Gateway");
+ const repos2 = repos.map(r =>
+ `<div class="ov-row">
+ <span class="ov-key" style="font-size:10px;min-width:80px">${esc(r.name.replace("tars-",""))}</span>
+ <span style="font-size:10px;font-family:var(--mono);color:var(--muted)">
+ DEV <span style="color:var(--c-tars)">${esc((r.dev_commit||"?").slice(0,7))}</span>
+ →
+ LIVE <span style="color:var(--c-tars)">${esc((r.live_commit||"?").slice(0,7))}</span>
+ ${r.live_diverged ? `<span style="color:var(--warn)">⚠</span>` : ""}
+ </span>
+ </div>`).join("");
+ return `<div class="ov-head">TON-01 — Infrastructure Host</div>
+ ${row("gateway", spillHTML(gw.status) + `<span style="font-size:10px;color:var(--muted);margin-left:4px">:8080</span>`)}
+ ${row("TKC", spillHTML(svc(data,"TKC").status) + `<span style="font-size:10px;color:var(--muted);margin-left:4px">:8110</span>`)}
+ ${row("MCP", spillHTML(svc(data,"MCP Server").status) + `<span style="font-size:10px;color:var(--muted);margin-left:4px">:8765</span>`)}
+ ${repos2}`;
+ }
+ default: return "";
+ }
+}
+
+// ─── Top-level status updates ─────────────────────────────────────────────────
+
+function updateDots(data) {
+ const st = derivedStatuses(data);
+ const map = {
+ tars: st.tars,
+ tkc: svc(data,"TKC").status,
+ bob: st.bob,
+ mcp: svc(data,"MCP Server").status,
+ ton: st.ton,
+ };
+ for (const [id, status] of Object.entries(map)) {
+ const dot = document.getElementById(`dot-${id}`);
+ if (dot) dot.className = `node-dot ${dotCls(status)}`;
+ }
+ const ks = data.knowledge_stats;
+ const sub = document.getElementById("sub-tkc");
+ if (sub && ks) sub.textContent = `${ks.active}a · ${ks.superseded}s`;
+ updatePulse(data);
+}
+
+function updatePulse(data) {
+ if (selectedNode) return;
+ const st = derivedStatuses(data);
+ const map = { tars:st.tars, tkc:svc(data,"TKC").status, bob:st.bob, mcp:svc(data,"MCP Server").status, ton:st.ton };
+ primaryIds.forEach(id => {
+ const el = document.getElementById(`node-${id}`);
+ if (!el) return;
+ const s = map[id];
+ el.classList.toggle("pulse", s !== "ok" && s !== "connected");
+ });
+}
+
+function updateIdleStrip(data) {
+ const st = derivedStatuses(data);
+ const ks = data.knowledge_stats;
+ const strip = document.getElementById("idle-summary");
+ const kPart = ks
+ ? `<span style="color:var(--dim)"> · ${ks.total} objects · <span style="color:var(--ok)">${ks.active} active</span> · <span style="color:var(--super)">${ks.superseded} superseded</span></span>`
+ : "";
+ strip.innerHTML = `${spillHTML(st.tars)} ${kPart}`;
+}
+
+// ─── Main refresh ─────────────────────────────────────────────────────────────
+
+async function doRefresh() {
const banner = document.getElementById("error-banner");
banner.style.display = "none";
-
try {
const data = await fetchStatus();
-
- renderSystem(data.services);
- renderKnowledge(data.knowledge_stats);
- renderRepos(data.repositories);
- renderRecent(data.knowledge_recent);
-
- const ts = data.checked_at ? new Date(data.checked_at).toLocaleTimeString() : new Date().toLocaleTimeString();
+ currentData = data;
+ updateDots(data);
+ updateIdleStrip(data);
+ const ts = data.checked_at
+ ? new Date(data.checked_at).toLocaleTimeString()
+ : new Date().toLocaleTimeString();
document.getElementById("last-updated").textContent = `Updated ${ts}`;
+ if (selectedNode) {
+ showOverlay(selectedNode, data);
+ // Refresh secondary status dots
+ document.querySelectorAll(".sec-node").forEach(el => el.remove());
+ renderSecondaryNodes(selectedNode, data);
+ layout();
+ }
} catch (err) {
banner.textContent = `Failed to load status: ${err.message}`;
banner.style.display = "block";
@@ -343,10 +1517,260 @@ async function refresh() {
}
}
-// ─── Startup ──────────────────────────────────────────────────────────────────
+// ─── Utility ──────────────────────────────────────────────────────────────────
+
+function esc(str) {
+ return String(str ?? "").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");
+}
+
+function fmtTs(iso) {
+ if (!iso) return "—";
+ const d = new Date(iso);
+ return d.toLocaleString(undefined, { month:"short", day:"numeric", hour:"2-digit", minute:"2-digit" });
+}
+
+// ─── Keyboard & background interaction ────────────────────────────────────────
+
+document.addEventListener("keydown", e => {
+ if (e.key === "Escape" && selectedNode) {
+ selectedNode = null;
+ clearSecondaryNodes();
+ applySelectionClasses();
+ closeOverlay();
+ layout();
+ }
+});
+
+document.getElementById("canvas").addEventListener("click", e => {
+ const isCanvas = e.target === document.getElementById("canvas")
+ || e.target === document.getElementById("topo-svg");
+ if (isCanvas && selectedNode) {
+ selectedNode = null;
+ clearSecondaryNodes();
+ applySelectionClasses();
+ closeOverlay();
+ layout();
+ }
+});
+
+// ─── Init & resize ────────────────────────────────────────────────────────────
+
+const ro = new ResizeObserver(() => {
+ layout();
+ if (selectedNode) positionOverlay(selectedNode);
+});
+ro.observe(document.getElementById("canvas"));
+
+layout();
+doRefresh();
+refreshTimer = setInterval(doRefresh, REFRESH_MS);
+
+
+// ─────────────────────────────────────────────────────────────────────────────
+// NavigationBus — decoupled input abstraction
+//
+// Input sources (click, keyboard, XR head-tracking, gesture) call
+// NavigationBus.navigate() without knowing about view layout.
+// The view layer registers exactly one handler via NavigationBus.register().
+// ─────────────────────────────────────────────────────────────────────────────
+
+const NavigationBus = (() => {
+ let _handler = null;
+ return {
+ register(fn) { _handler = fn; },
+ navigate(direction) { if (_handler) _handler(direction); },
+ };
+})();
+
+// ─── View system ──────────────────────────────────────────────────────────────
+
+const VIEWS = ['home', 'system', 'pond']; // index 0=left, 1=centre, 2=right
+let viewIndex = 1; // default: centre
+
+function activateView(idx) {
+ if (idx < 0 || idx >= VIEWS.length) return;
+ viewIndex = idx;
+ const isCenter = (idx === 1);
+
+ // Show/hide center-view
+ document.getElementById('center-view').classList.toggle('hidden', !isCenter);
+
+ // Show/hide side views
+ document.getElementById('view-home').classList.toggle('visible', idx === 0);
+ document.getElementById('view-pond').classList.toggle('visible', idx === 2);
+
+ // Nav arrow visibility
+ document.getElementById('nav-left').classList.toggle('hidden', idx === 0);
+ document.getElementById('nav-right').classList.toggle('hidden', idx === VIEWS.length - 1);
+
+ // Indicator dots
+ VIEWS.forEach((_, i) => {
+ document.getElementById('vdot-' + i).classList.toggle('active', i === idx);
+ });
+
+ // Re-layout topology when returning to centre
+ if (isCenter) { layout(); if (selectedNode) positionOverlay(selectedNode); }
+
+ // Populate side views with current data (lazy — data may arrive later)
+ if (idx === 0 && currentData) renderHomeView(currentData);
+ if (idx === 2 && currentData) renderPondView(currentData);
+}
+
+// Register view handler with bus
+NavigationBus.register(function(direction) {
+ if (direction === 'left') activateView(viewIndex - 1);
+ if (direction === 'right') activateView(viewIndex + 1);
+ if (direction === 'center') activateView(1);
+});
+
+// Arrow button handlers (delegate through bus)
+document.getElementById('nav-left').addEventListener('click', function() { NavigationBus.navigate('left'); });
+document.getElementById('nav-right').addEventListener('click', function() { NavigationBus.navigate('right'); });
+
+// Keyboard arrow keys — only when no text input is focused
+document.addEventListener('keydown', function(e) {
+ if (document.activeElement && ['INPUT','TEXTAREA','SELECT'].includes(document.activeElement.tagName)) return;
+ if (e.key === 'ArrowLeft' && !e.ctrlKey && !e.altKey) { e.preventDefault(); NavigationBus.navigate('left'); return; }
+ if (e.key === 'ArrowRight' && !e.ctrlKey && !e.altKey) { e.preventDefault(); NavigationBus.navigate('right'); return; }
+}, true); // capture phase so it doesn't conflict with Escape handler
+
+// ─── Home / Zuhause view ──────────────────────────────────────────────────────
+
+function renderHomeView(data) {
+ const grid = document.getElementById('home-grid');
+ if (!grid) return;
+
+ const services = (data.services || []);
+ const repos = (data.repositories || []);
+
+ // Home-relevant: interaction nodes, web runtime, audio, presence
+ const homeServices = services.filter(function(s) {
+ return /node|windows|laptop|audio|presence|home|web.runtime|tars-web/i.test(s.name);
+ });
+
+ // ── Card: Interaction Nodes ──
+ var nodeRows = homeServices.length
+ ? homeServices.map(function(s) {
+ return '<div class="sv-row">' +
+ '<span class="sv-name">' + esc(s.name) + '</span>' +
+ '<span style="display:flex;align-items:center;gap:6px">' +
+ (s.detail ? '<span class="sv-val">' + esc(s.detail) + '</span>' : '') +
+ '<span class="node-dot ' + dotCls(s.status) + '" style="width:7px;height:7px;border-radius:50%;flex-shrink:0"></span>' +
+ '</span>' +
+ '</div>';
+ }).join('')
+ : '<div class="sv-row"><span class="sv-name" style="color:var(--dim);font-size:11px">No home nodes in telemetry</span></div>';
+
+ // ── Card: All Services ──
+ var allRows = services.map(function(s) {
+ return '<div class="sv-row">' +
+ '<span class="sv-name">' + esc(s.name) + '</span>' +
+ '<span style="display:flex;align-items:center;gap:6px">' +
+ (s.detail ? '<span class="sv-val">' + esc(s.detail) + '</span>' : '') +
+ '<span class="node-dot ' + dotCls(s.status) + '" style="width:7px;height:7px;border-radius:50%;flex-shrink:0"></span>' +
+ '</span>' +
+ '</div>';
+ }).join('');
+
+ // ── Card: DEV workspace ──
+ var repoRows = repos.length
+ ? repos.map(function(r) {
+ return '<div class="sv-row">' +
+ '<span class="sv-name" style="font-size:11px">' + esc(r.name.replace('tars-','')) + '</span>' +
+ '<span class="sv-val">' +
+ esc((r.dev_commit||'?').slice(0,7)) +
+ (r.dev_clean === false ? '<span style="color:var(--warn)"> dirty</span>' : '') +
+ '</span>' +
+ '</div>';
+ }).join('')
+ : '<div class="sv-row"><span class="sv-name" style="color:var(--dim);font-size:11px">No repo data</span></div>';
+
+ grid.innerHTML =
+ '<div class="sv-card"><div class="sv-card-title">Interaction Nodes</div>' + nodeRows + '</div>' +
+ '<div class="sv-card"><div class="sv-card-title">Platform Services</div>' +
+ (allRows || '<div class="sv-row"><span class="sv-name" style="color:var(--dim);font-size:11px">No data</span></div>') +
+ '</div>' +
+ '<div class="sv-card"><div class="sv-card-title">DEV Workspace</div>' + repoRows + '</div>';
+}
+
+// ─── Pond / Teich view ────────────────────────────────────────────────────────
+
+function renderPondView(data) {
+ const grid = document.getElementById('pond-grid');
+ if (!grid) return;
+
+ const services = (data.services || []);
+ const ss = (data.subsystems || {});
+ const ks = data.knowledge_stats;
+ const repos = (data.repositories || []);
+
+ // Infrastructure services (TON-01 services visible at the pond desk)
+ var infraRows = services.filter(function(s) {
+ return /tkc|mcp|gateway|status|admin/i.test(s.name);
+ }).map(function(s) {
+ return '<div class="sv-row">' +
+ '<span class="sv-name">' + esc(s.name) + '</span>' +
+ '<span style="display:flex;align-items:center;gap:6px">' +
+ (s.detail ? '<span class="sv-val">' + esc(s.detail) + '</span>' : '') +
+ '<span class="node-dot ' + dotCls(s.status) + '" style="width:7px;height:7px;border-radius:50%;flex-shrink:0"></span>' +
+ '</span>' +
+ '</div>';
+ }).join('') || '<div class="sv-row"><span class="sv-name" style="color:var(--dim);font-size:11px">No telemetry</span></div>';
+
+ // Knowledge stats
+ var knRows = ks
+ ? '<div class="sv-row"><span class="sv-name">Total</span><span class="sv-val">' + ks.total + '</span></div>' +
+ '<div class="sv-row"><span class="sv-name">Active</span><span class="sv-val" style="color:var(--ok)">' + ks.active + '</span></div>' +
+ '<div class="sv-row"><span class="sv-name">Superseded</span><span class="sv-val" style="color:var(--super)">' + ks.superseded + '</span></div>'
+ : '<div class="sv-row"><span class="sv-name" style="color:var(--dim);font-size:11px">Not available</span></div>';
+
+ // Subsystem health
+ var subRows = [['PostgreSQL', _normalise(ss.postgresql)], ['Milvus', _normalise(ss.milvus)], ['Neo4j', _normalise(ss.neo4j)]].map(function(pair) {
+ var name = pair[0], st = pair[1];
+ return '<div class="sv-row">' +
+ '<span class="sv-name">' + esc(name) + '</span>' +
+ '<span style="display:flex;align-items:center;gap:5px">' +
+ '<span class="node-dot ' + dotCls(st) + '" style="width:7px;height:7px;border-radius:50%;flex-shrink:0"></span>' +
+ '<span class="sv-val">' + esc(st) + '</span>' +
+ '</span>' +
+ '</div>';
+ }).join('');
+
+ // LIVE repo commits
+ var repoRows = repos.map(function(r) {
+ return '<div class="sv-row">' +
+ '<span class="sv-name" style="font-size:11px">' + esc(r.name.replace('tars-','')) + '</span>' +
+ '<span class="sv-val">LIVE <span style="color:var(--c-tars)">' + esc((r.live_commit||'?').slice(0,7)) + '</span>' +
+ (r.live_diverged ? '<span style="color:var(--warn)"> ⚠</span>' : '') +
+ '</span>' +
+ '</div>';
+ }).join('');
+
+ grid.innerHTML =
+ '<div class="sv-card"><div class="sv-card-title">Infrastructure — TON-01</div>' + infraRows + '</div>' +
+ '<div class="sv-card"><div class="sv-card-title">Knowledge Core</div>' +
+ knRows +
+ '<div style="border-top:1px solid var(--border);margin-top:10px;padding-top:10px">' + subRows + '</div>' +
+ '</div>' +
+ (repos.length ? '<div class="sv-card"><div class="sv-card-title">LIVE Repositories</div>' + repoRows + '</div>' : '');
+}
+
+// ─── Patch refresh cycle to update side views ─────────────────────────────────
+// After each doRefresh() completes, re-render the active side view if needed.
+const _origDoRefresh = doRefresh;
+const _patchedRefresh = async function() {
+ await _origDoRefresh();
+ if (currentData) {
+ if (viewIndex === 0) renderHomeView(currentData);
+ if (viewIndex === 2) renderPondView(currentData);
+ }
+};
+clearInterval(refreshTimer);
+refreshTimer = setInterval(_patchedRefresh, REFRESH_MS);
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+activateView(1); // centre view is default
-refresh();
-refreshTimer = setInterval(refresh, REFRESH_MS);
</script>
</body>
</html>
diff --git a/services/tars-engineering-queue-dev/B3-A-INTEGRATION.md b/services/tars-engineering-queue-dev/B3-A-INTEGRATION.md
new file mode 100644
index 0000000..00a560b
--- /dev/null
+++ b/services/tars-engineering-queue-dev/B3-A-INTEGRATION.md
@@ -0,0 +1,25 @@
+# EQ-001/EQ-002 B3-A DEV integration
+
+This addition reuses the existing Engineering Queue API (`/v1/changes`, execution-grant read, claim, status, evidence). It creates no second queue or database path.
+
+## Hermes worker
+
+`api_worker.py` is a bounded API Agent worker. The default allowlist contains only `queue.self_test.v1`; job descriptions must be a strict JSON `{ "action": ..., "payload": ... }` envelope. Arbitrary prose, shell, URLs, modules, files, Git, SQL, and tool calls are never executed. Unsupported actions remain unclaimed.
+
+The worker lists ready tasks for `tars-platform`, reads existing grant metadata, rejects missing/expired/revoked grants, and supplies the existing grant ID to the Queue API claim endpoint. The API/database remains authoritative and revalidates grants. It then transitions to `in_progress`, runs the fixed executor, appends pass/fail evidence, and records `validated` (pending external review) or `blocked`. It never creates a grant, sets `ready`, approves a Human Gate, or promotes MAIN. Configure `TARS_QUEUE_AGENT_API_KEY` from a protected DEV secret provider. Run once by default; polling requires explicit `TARS_QUEUE_WORKER_ONCE=0` and optional 1–60 second `TARS_QUEUE_WORKER_INTERVAL`.
+
+The current executor is intentionally a harmless contract smoke action, not arbitrary engineering-code execution. New action types require reviewed code and tests.
+
+## GPT MCP facade
+
+`gpt_queue_mcp.py` exposes three tools: `queue_create`, `queue_status`, and `queue_result`. All requests use the same existing Queue API with a dedicated Agent API credential supplied as protected `TARS_QUEUE_GPT_AGENT_API_KEY`. Create is forced to `proposed`; grant/readiness and Human Gate actions are not exposed. Status/result read the persisted change and evidence. The MCP server needs to be wired into the existing authenticated MCP host/registry by its operator; this package does not activate a listener or create credentials.
+
+## Offline verification
+
+Run from repository root:
+
+```sh
+PYTHONPATH=. python -m unittest services.tars_engineering_queue_dev.test_api_worker services.tars_engineering_queue_dev.test_gpt_queue_mcp
+```
+
+These tests use fakes and validate route-contract behavior only; they do not prove DB persistence, credentials, service availability, or a real MCP registration. Existing PostgreSQL identity and independent Operator grant remain mandatory for a runtime roundtrip.
diff --git a/services/tars-engineering-queue-dev/B3-B-BOOTSTRAP.md b/services/tars-engineering-queue-dev/B3-B-BOOTSTRAP.md
new file mode 100644
index 0000000..b4c1cc9
--- /dev/null
+++ b/services/tars-engineering-queue-dev/B3-B-BOOTSTRAP.md
@@ -0,0 +1,34 @@
+# B3-B Queue Operator Bootstrap Contract (DEV)
+
+## Components
+
+- `operator_runner.b3b_runtime.B3BQueueActions` connects the existing fail-closed Runner action contract to an injected `QueueOperatorConnector`; it has no shell, SQL, Docker, credential, or service-management escape hatch.
+- `gpt_mcp_host.create_app` builds a separate OAuth resource-server MCP application. It does not alter or extend `services/tkc-health-mcp`, whose public surface stays exactly `tkc_health`.
+- Queue API remains the persistence store. Agent API credentials are used only by the Queue client/worker; Operator identity and independent grants stay separate.
+
+## Connector contract
+
+The authorized operator integration must implement only the typed methods in `b3b_runtime.py`, using already authorized providers:
+
+1. Read-only PostgreSQL clone identity bound to the independent manifest (cluster/system ID, DB, session/current user, server/client IP, port, version, owner).
+2. Schema/migration evidence and bootstrap only through one-use action-bound Runner approval with exact migration IDs and hashes.
+3. Agent API credentials stored in a protected secret backend; return opaque reference and distinct Agent/Operator subjects only, never secret bytes.
+4. Start `tars-engineering-queue-dev` only on `172.25.0.3:8904` with private runtime configuration. Do not expose Docker socket or elevated host authority to Hermes.
+5. Execute only the fixed Hermes worker against a synthetic task that an independent Operator has made ready under a Queue execution grant.
+6. Read status/evidence back through the existing authenticated Queue API.
+
+Write actions must go through the existing Runner and its verified caller, independent action-bound approval, durable audit and idempotency checks. Do not call the concrete methods as a substitute for Runner dispatch.
+
+## GPT MCP registration
+
+Build a standalone app with `gpt_mcp_host.create_app`, passing the GPT facade with a protected dedicated Agent API credential, the existing trusted OAuth/JWKS TokenVerifier, issuer, Queue-MCP audience and explicit host allowlist. Required scope is `tars:queue`. Register as its own private MCP host/route. Do not add tools to `tkc-health-mcp`; do not expose the broad shared-token TARS MCP server. The app exposes only `queue_create`, `queue_status`, `queue_result`; create produces proposed tasks only.
+
+## One remaining external operator action
+
+An authorized operator must provide the concrete `QueueOperatorConnector` implementation and narrowly scoped providers for DB identity, approved bootstrap, secrets, API service operation, plus the existing OAuth verifier/route. The DEV contract and Fake tests do not create credentials, perform migrations, start services, issue grants, or prove persistence. After provider injection, run one isolated synthetic roundtrip and read the same record/evidence after reconnect.
+
+## Offline tests
+
+`PYTHONPATH=. python -m unittest services.tars_engineering_queue_dev.operator_runner.test_b3b_runtime services.tars_engineering_queue_dev.test_gpt_mcp_host`
+
+Tests use fakes and MCP SDK shims; they verify contract validation and registration only, not live infrastructure.
\ No newline at end of file
diff --git a/services/tars-engineering-queue-dev/README.md b/services/tars-engineering-queue-dev/README.md
new file mode 100644
index 0000000..a24f0cc
--- /dev/null
+++ b/services/tars-engineering-queue-dev/README.md
@@ -0,0 +1,40 @@
+# TARS Engineering Queue DEV Service (MVP)
+
+This package is an adapter for the existing Queue MVP source, not a second queue. It does not include database migrations, a service unit, or a credential vault.
+
+## Launcher and protected configuration
+
+ASGI factory: `services.tars_engineering_queue_dev.launcher:build_app`.
+
+It requires `TARS_QUEUE_RUNTIME_ENV_FILE` naming a regular mode-0600-or-stricter runtime configuration file; a service supervisor must load that protected file before starting the process. Do not put secrets in Git, shell arguments, logs, or production environment files.
+
+Required settings:
+
+- `TARS_QUEUE_AGENT_DSN`: exact endpoint `127.0.0.1:55432`, database `tars_queue_itest`, login `tars_queue_agent_login`.
+- `TARS_QUEUE_OPERATOR_DSN`: same exact isolated endpoint/database, but distinct login `tars_queue_operator_login` and distinct DSN.
+- `TARS_QUEUE_DEV_OPERATOR_KEY` and `TARS_QUEUE_DEV_OPERATOR_ID`.
+- `TARS_QUEUE_AGENT_COUNT` (1–32); for each index `n`, set `TARS_QUEUE_AGENT_<n>_KEY` and `TARS_QUEUE_AGENT_<n>_ID`; all Agent/Operator keys and subjects must be distinct.
+- Optional `TARS_QUEUE_BIND_HOST`, if set, must equal `127.0.0.1`.
+
+The launcher also hard-pins both DSN host/port/database/user fields and rejects service/hostaddr overrides. It constructs the existing `create_app()` factory; it does not open DB connections until API calls.
+
+## Start / health / stop
+
+No systemd unit is supplied or installed. From the reviewed package root, after source dependencies are present and the protected DEV config and DB are verified:
+
+```sh
+python -m uvicorn services.tars_engineering_queue_dev.launcher:build_app --factory --host 127.0.0.1 --port 8904
+```
+
+Health check: `curl --fail --silent --show-error http://127.0.0.1:8904/health`.
+Stop only the foreground process started for this test (Ctrl-C) or its exact approved unit once one exists. No global process kill.
+
+## Fixed one-shot worker
+
+`services.tars_engineering_queue_dev.worker` supports exactly `EQ-DEV-SMOKE-1`, whose claimed record must match title “Queue worker harmless self-test” and repository `tars-platform`. It invokes one fixed action `queue.self_test.v1`; ticket text is never evaluated and cannot select code, shell, file, Git, URL, or module behavior. Flow: claim with an existing execution-grant reference → `in_progress` → fixed local action → append pass/fail test evidence → `validated` or `blocked`. This is not a polling/retry service.
+
+The Agent DSN must be supplied from the protected environment and is independently hard-pinned to the Agent login. Human Gate decisions and MAIN promotion remain external.
+
+## Migration gates
+
+Do not migrate during launcher startup. Operator must verify database owner, preexisting object names/owners/counts/content, cluster isolation, server/client addresses, PostgreSQL major version, system identifier and role/membership state against the literal guards for each migration. 003a and 003a1 create cluster-global roles/logins; 003 changes ownership/ACLs; 002 includes an UPDATE that can reset ready/claimed rows on rerun. Never weaken or repoint those guards. No DDL is authorized by this package.
diff --git a/services/tars-engineering-queue-dev/__init__.py b/services/tars-engineering-queue-dev/__init__.py
new file mode 100644
index 0000000..dac5788
--- /dev/null
+++ b/services/tars-engineering-queue-dev/__init__.py
@@ -0,0 +1 @@
+"""DEV-only launcher and fixed-action worker for the Engineering Queue MVP."""
diff --git a/services/tars-engineering-queue-dev/api_worker.py b/services/tars-engineering-queue-dev/api_worker.py
new file mode 100644
index 0000000..0af5fd5
--- /dev/null
+++ b/services/tars-engineering-queue-dev/api_worker.py
@@ -0,0 +1,218 @@
+"""Bounded Hermes worker client for the existing Engineering Queue API.
+
+Only queue.self_test.v1 is executable. Ticket prose is never evaluated, and the
+worker cannot issue grants, set work ready, approve a Human Gate, or promote.
+"""
+from __future__ import annotations
+
+import json
+import os
+import time
+from datetime import datetime, timezone
+from typing import Any, Callable
+from urllib.error import HTTPError, URLError
+from urllib.parse import quote, urlencode, urlsplit
+from urllib.request import Request, urlopen
+
+API_BASE = "http://172.25.0.3:8904"
+API_HOST = "172.25.0.3"
+API_PORT = 8904
+API_REPOSITORY = "tars-platform"
+ACTION = "queue.self_test.v1"
+MAX_RESPONSE_BYTES = 1_000_000
+
+
+class QueueAPIError(RuntimeError):
+ def __init__(self, status: int, message: str = "Queue API request failed"):
+ super().__init__(message)
+ self.status = status
+
+
+class QueueAPIClient:
+ """Minimal authenticated client; bearer token is never logged or returned."""
+
+ def __init__(self, token: str, base_url: str = API_BASE, timeout: float = 5.0):
+ parsed = urlsplit(base_url)
+ if (parsed.scheme, parsed.hostname, parsed.port, parsed.path, parsed.query, parsed.fragment) != (
+ "http", API_HOST, API_PORT, "", "", ""
+ ):
+ raise ValueError("Queue API URL must match the pinned internal DEV endpoint")
+ if not isinstance(token, str) or not token.strip():
+ raise ValueError("Queue Agent API credential is required")
+ self._token = token
+ self.base_url = base_url
+ self.timeout = timeout
+
+ def _request(self, method: str, path: str, payload: dict[str, Any] | None = None):
+ body = None if payload is None else json.dumps(payload, separators=(",", ":")).encode("utf-8")
+ headers = {"Authorization": "Bearer " + self._token, "Accept": "application/json"}
+ if body is not None:
+ headers["Content-Type"] = "application/json"
+ request = Request(self.base_url + path, data=body, headers=headers, method=method)
+ try:
+ with urlopen(request, timeout=self.timeout) as response:
+ raw = response.read(MAX_RESPONSE_BYTES + 1)
+ if len(raw) > MAX_RESPONSE_BYTES:
+ raise QueueAPIError(502, "Queue API response exceeds size limit")
+ except HTTPError as exc:
+ # Do not surface response bodies: they may contain untrusted or sensitive data.
+ raise QueueAPIError(exc.code) from None
+ except (URLError, TimeoutError, OSError) as exc:
+ raise QueueAPIError(503, "Queue API unavailable") from exc
+ try:
+ return json.loads(raw.decode("utf-8")) if raw else None
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
+ raise QueueAPIError(502, "Queue API returned invalid JSON") from exc
+
+ def list_ready(self) -> list[dict[str, Any]]:
+ query = urlencode({"status": "ready", "repository": API_REPOSITORY, "limit": 100})
+ result = self._request("GET", "/v1/changes?" + query)
+ items = result.get("items") if isinstance(result, dict) else None
+ if not isinstance(items, list):
+ raise QueueAPIError(502, "Queue API ready-list response is invalid")
+ return items
+
+ def get(self, change_id: str):
+ return self._request("GET", "/v1/changes/" + quote(change_id, safe=""))
+
+ def list_grants(self, change_id: str):
+ return self._request("GET", "/v1/changes/" + quote(change_id, safe="") + "/execution-grants")
+
+ def claim(self, change_id: str, grant_id: str):
+ return self._request("POST", "/v1/changes/" + quote(change_id, safe="") + "/claim",
+ {"execution_approval_ref": grant_id})
+
+ def update_status(self, change_id: str, status: str, version: int, reason: str):
+ return self._request("PATCH", "/v1/changes/" + quote(change_id, safe="") + "/status",
+ {"status": status, "expected_version": version, "reason": reason})
+
+ def attach_evidence(self, change_id: str, evidence: dict[str, Any]):
+ return self._request("POST", "/v1/changes/" + quote(change_id, safe="") + "/evidence", evidence)
+
+
+def _self_test(payload: dict[str, Any]) -> dict[str, Any]:
+ if set(payload) - {"label"}:
+ raise ValueError("unsupported self-test payload fields")
+ label = payload.get("label", "queue-smoke")
+ if not isinstance(label, str) or not 1 <= len(label) <= 80:
+ raise ValueError("self-test label must be 1..80 characters")
+ return {"action": ACTION, "label": label, "result": "pass"}
+
+
+EXECUTORS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {ACTION: _self_test}
+
+
+def _task_action(record: dict[str, Any]) -> tuple[str, dict[str, Any]]:
+ """Accept only a strict JSON action envelope in description; never eval prose."""
+ raw = record.get("description", "")
+ if not isinstance(raw, str) or len(raw) > 2048:
+ raise ValueError("task action envelope is invalid")
+ try:
+ envelope = json.loads(raw)
+ except (json.JSONDecodeError, TypeError) as exc:
+ raise ValueError("task description must contain the allowlisted JSON action envelope") from exc
+ if not isinstance(envelope, dict) or set(envelope) != {"action", "payload"}:
+ raise ValueError("task action envelope has unsupported fields")
+ action, payload = envelope["action"], envelope["payload"]
+ if action not in EXECUTORS or not isinstance(payload, dict):
+ raise ValueError("task action is not allowlisted")
+ return action, payload
+
+
+def _active_grant(grants: Any, now: datetime) -> str:
+ if not isinstance(grants, list):
+ raise ValueError("Queue grant response is invalid")
+ candidates = []
+ for grant in grants:
+ if not isinstance(grant, dict) or grant.get("scope") != "execute" or grant.get("revoked_at") is not None:
+ continue
+ try:
+ expiry = datetime.fromisoformat(str(grant["expires_at"]).replace("Z", "+00:00"))
+ if expiry.tzinfo is None:
+ expiry = expiry.replace(tzinfo=timezone.utc)
+ except (KeyError, TypeError, ValueError):
+ continue
+ grant_id = grant.get("grant_id")
+ if expiry > now and isinstance(grant_id, str) and grant_id:
+ candidates.append((expiry, grant_id))
+ if not candidates:
+ raise PermissionError("no active independent execution grant")
+ # Prefer the soonest-expiring valid grant to minimize authority lifetime.
+ return min(candidates)[1]
+
+
+class HermesQueueWorker:
+ """One-shot worker using the existing Queue API Agent routes."""
+
+ def __init__(self, queue: Any, executor_registry=None, clock=None):
+ self.queue = queue
+ self.executors = EXECUTORS if executor_registry is None else executor_registry
+ self.clock = clock or (lambda: datetime.now(timezone.utc))
+
+ def run_once(self, change_id: str | None = None) -> dict[str, Any] | None:
+ candidates = [self.queue.get(change_id)] if change_id else self.queue.list_ready()
+ for record in candidates:
+ if not isinstance(record, dict) or record.get("repository") != API_REPOSITORY or record.get("status") != "ready":
+ continue
+ cid = record.get("change_id")
+ if not isinstance(cid, str) or not cid:
+ continue
+ try:
+ action, payload = _task_action(record)
+ except ValueError:
+ # Unsupported jobs are left untouched for an appropriately scoped worker.
+ continue
+ executor = self.executors.get(action)
+ if executor is None:
+ continue
+ grant_id = _active_grant(self.queue.list_grants(cid), self.clock())
+ claimed = self.queue.claim(cid, grant_id)
+ if not isinstance(claimed, dict) or claimed.get("status") != "claimed" or claimed.get("change_id") != cid:
+ raise RuntimeError("Queue claim response does not match requested task")
+ active = self.queue.update_status(cid, "in_progress", claimed["version"], "Hermes allowlisted execution started")
+ try:
+ result = executor(payload)
+ summary = json.dumps(result, sort_keys=True, separators=(",", ":"))[:1000]
+ evidence = self.queue.attach_evidence(cid, {
+ "evidence_type": "test",
+ "uri": "queue-worker://" + quote(cid, safe=""),
+ "summary": "Hermes executed " + action + ": " + summary,
+ "result": "pass",
+ })
+ final = self.queue.update_status(cid, "validated", active["version"], "Hermes allowlisted execution completed; awaiting external review")
+ return {"change": final, "evidence": evidence, "result": result}
+ except Exception as exc:
+ evidence = self.queue.attach_evidence(cid, {
+ "evidence_type": "test",
+ "uri": "queue-worker://" + quote(cid, safe="") + "/failure",
+ "summary": "Hermes allowlisted execution failed: " + type(exc).__name__,
+ "result": "fail",
+ })
+ blocked = self.queue.update_status(cid, "blocked", active["version"], "Hermes allowlisted execution failed")
+ return {"change": blocked, "evidence": evidence, "error": type(exc).__name__}
+ return None
+
+
+def build_worker_from_env() -> HermesQueueWorker:
+ token = os.environ.get("TARS_QUEUE_AGENT_API_KEY", "")
+ return HermesQueueWorker(QueueAPIClient(token))
+
+
+def main() -> int:
+ worker = build_worker_from_env()
+ once = os.environ.get("TARS_QUEUE_WORKER_ONCE", "1") != "0"
+ if once:
+ result = worker.run_once()
+ if result is None:
+ print("queue worker: no eligible granted task")
+ return 0
+ print("queue worker: status=" + str(result["change"].get("status")) + " evidence-recorded")
+ return 0 if result["change"].get("status") == "validated" else 1
+ interval = min(60, max(1, int(os.environ.get("TARS_QUEUE_WORKER_INTERVAL", "5"))))
+ while True:
+ worker.run_once()
+ time.sleep(interval)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/services/tars-engineering-queue-dev/config.py b/services/tars-engineering-queue-dev/config.py
new file mode 100644
index 0000000..7b4aaff
--- /dev/null
+++ b/services/tars-engineering-queue-dev/config.py
@@ -0,0 +1,64 @@
+"""Fail-closed Queue DEV target and protected-file validation."""
+from __future__ import annotations
+import os
+import stat
+from pathlib import Path
+from psycopg.conninfo import conninfo_to_dict
+
+CLONE_HOST = "172.25.0.2"
+CLONE_PORT = "5432"
+CLONE_DATABASE = "tars_queue_itest"
+RUNNER_BIND_HOST = "172.25.0.3"
+AGENT_LOGIN = "tars_queue_agent_login"
+OPERATOR_LOGIN = "tars_queue_operator_login"
+_ALLOWED_DSN_OPTIONS = {
+ "host", "port", "dbname", "user", "password", "passfile",
+ "connect_timeout", "sslmode", "application_name",
+}
+
+
+def _private_regular_file(path: str, label: str) -> os.stat_result:
+ try:
+ info = os.lstat(path)
+ except (OSError, TypeError, ValueError) as exc:
+ raise RuntimeError(f"{label} is unavailable") from exc
+ if (not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077
+ or info.st_uid != os.geteuid()):
+ raise RuntimeError(f"{label} must be a private regular file owned by this runtime identity")
+ return info
+
+
+def validate_runtime_env_file(path: str) -> None:
+ _private_regular_file(path, "Queue runtime config file")
+
+
+def validate_clone_dsn(dsn: str, expected_user: str) -> None:
+ if expected_user not in {AGENT_LOGIN, OPERATOR_LOGIN}:
+ raise RuntimeError("Queue login is not an approved DEV identity")
+ try:
+ parts = conninfo_to_dict(dsn)
+ except Exception as exc:
+ raise RuntimeError("Queue DSN is invalid") from exc
+ if set(parts) - _ALLOWED_DSN_OPTIONS:
+ raise RuntimeError("Queue DSN contains unsupported connection options")
+ expected = {"host": CLONE_HOST, "port": CLONE_PORT,
+ "dbname": CLONE_DATABASE, "user": expected_user}
+ if any(parts.get(key) != value for key, value in expected.items()):
+ raise RuntimeError("Queue DSN does not match the approved isolated DEV clone")
+ if parts.get("password"):
+ raise RuntimeError("Queue DSN must not embed a password")
+ passfile = parts.get("passfile") or os.environ.get("PGPASSFILE")
+ if passfile:
+ _private_regular_file(passfile, "Queue PostgreSQL passfile")
+
+
+def validate_runner_bind(host: str) -> None:
+ if host != RUNNER_BIND_HOST:
+ raise RuntimeError("Queue API bind must use the approved internal DEV runner IP")
+
+
+def validate_agent_operator_dsns(agent_dsn: str, operator_dsn: str) -> None:
+ validate_clone_dsn(agent_dsn, AGENT_LOGIN)
+ validate_clone_dsn(operator_dsn, OPERATOR_LOGIN)
+ if agent_dsn == operator_dsn:
+ raise RuntimeError("Agent and Operator DSNs must differ")
diff --git a/services/tars-engineering-queue-dev/core/CORE-SOURCE.json b/services/tars-engineering-queue-dev/core/CORE-SOURCE.json
new file mode 100644
index 0000000..1dc334d
--- /dev/null
+++ b/services/tars-engineering-queue-dev/core/CORE-SOURCE.json
@@ -0,0 +1,5 @@
+{
+ "source_id": "tars-platform:bob/dev@221ab63477194a66447a10111fefa946f035e85b",
+ "source_path": "services/tars-engineering-queue-dev/core/",
+ "note": "Core source is versioned in this DEV commit. It is package-local and imported via relative package paths; it does not import /opt/hermes workspace files."
+}
diff --git a/services/tars-engineering-queue-dev/core/__init__.py b/services/tars-engineering-queue-dev/core/__init__.py
new file mode 100644
index 0000000..39308e3
--- /dev/null
+++ b/services/tars-engineering-queue-dev/core/__init__.py
@@ -0,0 +1,2 @@
+"""Reviewed package-local copy of the TARS Engineering Queue MVP core."""
+SOURCE_ID="queue-mvp-source-snapshot-2026-11-17"
diff --git a/services/tars-engineering-queue-dev/core/api.py b/services/tars-engineering-queue-dev/core/api.py
new file mode 100644
index 0000000..0b67a2f
--- /dev/null
+++ b/services/tars-engineering-queue-dev/core/api.py
@@ -0,0 +1,98 @@
+"""FastAPI contract for the isolated DEV engineering queue MVP."""
+from __future__ import annotations
+import os
+from typing import Any, Literal
+from fastapi import FastAPI, HTTPException, Query, Request
+from fastapi.responses import JSONResponse
+from pydantic import BaseModel, Field
+from .auth import AgentIdentity, authorize
+from .queue_store import EngineeringQueue, QueueError
+SERVICE_NAME="tars-engineering-queue-dev"
+class StrictModel(BaseModel): model_config={"extra":"forbid"}
+class ChangeCreate(StrictModel):
+ change_id:str; title:str; description:str=""; repository:str; priority:str="P2"; owner:str
+ dependencies:list[str]=Field(default_factory=list); commit_sha:str|None=None; base_sha:str|None=None
+ files:list[str]=Field(default_factory=list); test_evidence:list[dict[str,Any]]=Field(default_factory=list)
+ status:Literal["proposed"]="proposed"; hg1_status:Literal["not_requested"]="not_requested"; hg2_status:Literal["not_requested"]="not_requested"
+class ClaimRequest(StrictModel): execution_approval_ref:str
+class GrantCreate(StrictModel): change_id:str; scope:str; ttl_seconds:int=Field(ge=1,le=86400); reason:str
+class GrantRevoke(StrictModel): reason:str
+class StatusUpdate(StrictModel): status:str; expected_version:int=Field(ge=1); reason:str; execution_approval_ref:str|None=None
+class EvidenceCreate(StrictModel): evidence_type:str; uri:str; sha256:str|None=None; summary:str; result:str|None=None
+class SubmitRequest(StrictModel): expected_version:int=Field(ge=1)
+def create_app(queue:EngineeringQueue|None=None,*,agent_queue:EngineeringQueue|None=None,operator_queue:EngineeringQueue|None=None,agent_api_keys:dict[str,str]|None=None,operator_api_key:str|None=None,operator_id:str|None=None)->FastAPI:
+ agent_dsn=os.environ.get("TARS_QUEUE_AGENT_DSN",""); operator_dsn=os.environ.get("TARS_QUEUE_OPERATOR_DSN","")
+ agents=agent_api_keys or {}; op_key=operator_api_key if operator_api_key is not None else os.environ.get("TARS_QUEUE_DEV_OPERATOR_KEY",""); op_id=operator_id if operator_id is not None else os.environ.get("TARS_QUEUE_DEV_OPERATOR_ID","")
+ if queue is None and agent_queue is None and (not agent_dsn or not operator_dsn): raise RuntimeError("separate Agent and Operator DSNs required")
+ if not agents: raise RuntimeError("agent API credentials must be configured")
+ if not op_key or not op_id.strip(): raise RuntimeError("separate operator credential and server-side identity required")
+ if op_key in agents: raise ValueError("operator and agent credentials must be distinct")
+ if queue is None:
+ agent_store=agent_queue or EngineeringQueue(agent_dsn); operator_store=operator_queue or EngineeringQueue(operator_dsn)
+ else: agent_store=agent_queue or queue; operator_store=operator_queue or queue
+ app=FastAPI(title=SERVICE_NAME,version="0.3.0",docs_url=None,redoc_url=None)
+ app.state.agent_queue=agent_store; app.state.operator_queue=operator_store; app.state.queue=agent_store
+ app.state.agent_keys=dict(agents); app.state.operator_key=op_key; app.state.operator_id=op_id.strip()
+ def db_queue(principal): return app.state.operator_queue if principal[0]=="operator" else app.state.agent_queue
+ @app.middleware("http")
+ async def authenticate(request,call_next):
+ if request.method=="GET" and request.url.path=="/health": return await call_next(request)
+ h=request.headers.get("Authorization",""); token=h[7:] if h.startswith("Bearer ") else ""
+ if token and token==app.state.operator_key: request.state.principal=("operator",app.state.operator_id)
+ elif token in app.state.agent_keys: request.state.principal=("agent",app.state.agent_keys[token])
+ else: return JSONResponse({"error":"unauthorized"},status_code=401,headers={"WWW-Authenticate":"Bearer"})
+ return await call_next(request)
+ def invoke(action,fn,*args,principal,**kwargs):
+ try:
+ role,subject=principal; perms={"read","issue_grant","revoke_grant"} if role=="operator" else {"read","claim","edit","evidence","submit_review"}
+ authorize(AgentIdentity(subject,frozenset(perms)),action); return fn(*args,**kwargs)
+ except QueueError as exc: raise HTTPException(status_code=exc.status_code,detail=str(exc)) from exc
+ except ValueError as exc: raise HTTPException(status_code=422,detail=str(exc)) from exc
+ except Exception as exc: raise HTTPException(status_code=500,detail="queue operation failed") from exc
+ def agent(req):
+ p=req.state.principal
+ if p[0]!="agent": raise HTTPException(status_code=403,detail="agent identity required")
+ return p
+ def operator(req):
+ p=req.state.principal
+ if p[0]!="operator": raise HTTPException(status_code=403,detail="operator authentication required")
+ return p
+ @app.get("/health")
+ def health(): return {"status":"ok","service":SERVICE_NAME,"approval_authority":False}
+ @app.post("/v1/changes",status_code=201)
+ def create_change(body:ChangeCreate,req:Request):
+ p=agent(req);return invoke("edit",app.state.agent_queue.create,body.model_dump(),principal=p)
+ @app.get("/v1/changes")
+ def list_changes(req:Request,status:str|None=None,repository:str|None=None,limit:int=Query(default=100,ge=1,le=200),cursor:str|None=None):
+ p=req.state.principal;return invoke("read",db_queue(p).list,status=status,repository=repository,limit=limit,cursor=cursor,principal=p)
+ @app.get("/v1/changes/{change_id}")
+ def get_change(change_id:str,req:Request):
+ p=req.state.principal;return invoke("read",db_queue(p).get,change_id,principal=p)
+ @app.get("/v1/changes/{change_id}/execution-grants")
+ def list_grants(change_id:str,req:Request):
+ p=req.state.principal;return invoke("read",db_queue(p).list_grants,change_id,principal=p)
+ @app.post("/v1/execution-grants",status_code=201)
+ def issue_grant(body:GrantCreate,req:Request):
+ p=operator(req);return invoke("issue_grant",app.state.operator_queue.create_grant,p[1],body.change_id,body.scope,body.ttl_seconds,body.reason,principal=p)
+ @app.post("/v1/execution-grants/{grant_id}/revoke")
+ def revoke_grant(grant_id:str,body:GrantRevoke,req:Request):
+ p=operator(req);return invoke("revoke_grant",app.state.operator_queue.revoke_grant,p[1],grant_id,body.reason,principal=p)
+ @app.post("/v1/changes/{change_id}/claim")
+ def claim(change_id:str,body:ClaimRequest,req:Request):
+ p=agent(req);return invoke("claim",app.state.agent_queue.claim,change_id,p[1],body.execution_approval_ref,principal=p)
+ @app.patch("/v1/changes/{change_id}/status")
+ def update_status(change_id:str,body:StatusUpdate,req:Request):
+ if body.status=="ready":
+ p=operator(req);return invoke("issue_grant",app.state.operator_queue.update_status,change_id,p[1],body.status,body.expected_version,body.reason,grant_id=body.execution_approval_ref,operator_actor=p[1],principal=p)
+ p=agent(req);return invoke("edit",app.state.agent_queue.update_status,change_id,p[1],body.status,body.expected_version,body.reason,principal=p)
+ @app.post("/v1/changes/{change_id}/evidence",status_code=201)
+ def attach_evidence(change_id:str,body:EvidenceCreate,req:Request):
+ p=agent(req);return invoke("evidence",app.state.agent_queue.attach_evidence,change_id,p[1],body.model_dump(),principal=p)
+ @app.post("/v1/changes/{change_id}/submit-for-review")
+ def submit_review(change_id:str,body:SubmitRequest,req:Request):
+ p=agent(req);result=invoke("submit_review",app.state.agent_queue.submit_for_review,change_id,p[1],body.expected_version,principal=p)
+ return {"change":result,"approval_authority":"external-human-gate","approval_status":"pending"}
+ @app.get("/v1/changes/{change_id}/evidence")
+ def evidence(change_id:str,req:Request):
+ p=req.state.principal;return invoke("read",db_queue(p).evidence,change_id,principal=p)
+ return app
diff --git a/services/tars-engineering-queue-dev/core/auth.py b/services/tars-engineering-queue-dev/core/auth.py
new file mode 100644
index 0000000..9a795e1
--- /dev/null
+++ b/services/tars-engineering-queue-dev/core/auth.py
@@ -0,0 +1,14 @@
+from __future__ import annotations
+from dataclasses import dataclass
+class AuthorizationError(PermissionError): pass
+@dataclass(frozen=True)
+class AgentIdentity:
+ subject:str
+ permissions:frozenset[str]
+_ACTIONS={"read":"read","claim":"claim","edit":"edit","evidence":"evidence","submit_review":"submit_review","issue_grant":"issue_grant","revoke_grant":"revoke_grant","authorize_execution":"authorize_execution","review":"review","approve_human_gate":"approve_human_gate","promote_main":"promote_main"}
+def authorize(identity:AgentIdentity,action:str)->bool:
+ if not isinstance(identity,AgentIdentity) or not identity.subject.strip(): raise AuthorizationError("authenticated identity required")
+ permission=_ACTIONS.get(action)
+ if permission is None or permission not in identity.permissions: raise AuthorizationError(f"identity not authorized: {action}")
+ if action in {"authorize_execution","approve_human_gate","promote_main"}: raise AuthorizationError("protected operation requires external human authority")
+ return True
diff --git a/services/tars-engineering-queue-dev/core/config.py b/services/tars-engineering-queue-dev/core/config.py
new file mode 100644
index 0000000..f78f715
--- /dev/null
+++ b/services/tars-engineering-queue-dev/core/config.py
@@ -0,0 +1,65 @@
+"""Fail-closed runtime target validation for the isolated Queue DEV clone."""
+from __future__ import annotations
+
+import os
+import stat
+from pathlib import Path
+from psycopg.conninfo import conninfo_to_dict
+
+CLONE_HOST = "172.25.0.2"
+CLONE_PORT = "5432"
+CLONE_DATABASE = "tars_queue_itest"
+RUNNER_BIND_HOST = "172.25.0.3"
+AGENT_LOGIN = "tars_queue_agent_login"
+OPERATOR_LOGIN = "tars_queue_operator_login"
+_ALLOWED_DSN_OPTIONS = {
+ "host", "port", "dbname", "user", "password", "passfile",
+ "connect_timeout", "sslmode", "application_name",
+}
+
+
+def validate_runtime_env_file(path: str) -> None:
+ """Require a private, regular, non-symlink runtime config file."""
+ try:
+ info = Path(path).lstat()
+ except (OSError, TypeError, ValueError) as exc:
+ raise RuntimeError("Queue runtime config file is unavailable") from exc
+ if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077:
+ raise RuntimeError("Queue runtime config must be a private regular file")
+
+
+def validate_clone_dsn(dsn: str, expected_user: str) -> None:
+ """Pin a libpq DSN to the approved isolated clone and role."""
+ if expected_user not in {AGENT_LOGIN, OPERATOR_LOGIN}:
+ raise RuntimeError("Queue login is not an approved DEV identity")
+ try:
+ parts = conninfo_to_dict(dsn)
+ except Exception as exc:
+ raise RuntimeError("Queue DSN is invalid") from exc
+ # Explicitly reject libpq indirections/overrides, and reject unknown
+ # connection settings rather than silently accepting another target.
+ if set(parts) - _ALLOWED_DSN_OPTIONS:
+ raise RuntimeError("Queue DSN contains unsupported connection options")
+ expected = {
+ "host": CLONE_HOST,
+ "port": CLONE_PORT,
+ "dbname": CLONE_DATABASE,
+ "user": expected_user,
+ }
+ if any(parts.get(key) != value for key, value in expected.items()):
+ raise RuntimeError("Queue DSN does not match the approved isolated DEV clone")
+ if parts.get("password") and parts.get("passfile"):
+ raise RuntimeError("Queue DSN must use only one protected credential source")
+
+
+def validate_runner_bind(host: str) -> None:
+ """Permit binding only to the internal DEV runner interface."""
+ if host != RUNNER_BIND_HOST:
+ raise RuntimeError("Queue API bind must use the approved internal DEV runner IP")
+
+
+def validate_agent_operator_dsns(agent_dsn: str, operator_dsn: str) -> None:
+ validate_clone_dsn(agent_dsn, AGENT_LOGIN)
+ validate_clone_dsn(operator_dsn, OPERATOR_LOGIN)
+ if agent_dsn == operator_dsn:
+ raise RuntimeError("Agent and Operator DSNs must differ")
diff --git a/services/tars-engineering-queue-dev/core/queue_store.py b/services/tars-engineering-queue-dev/core/queue_store.py
new file mode 100644
index 0000000..2d8cfcb
--- /dev/null
+++ b/services/tars-engineering-queue-dev/core/queue_store.py
@@ -0,0 +1,129 @@
+from __future__ import annotations
+import json,re
+from datetime import datetime,timedelta,timezone
+from typing import Any
+REPOSITORIES={"tars-platform","tars-interaction-runtime","tars-tkc"};PRIORITIES={"P0","P1","P2","P3"};STATUSES={"proposed","ready","claimed","in_progress","blocked","validated","completed","submitted_for_review","rejected","superseded"};EVIDENCE_TYPES={"test","review","snapshot","security","operations","rollback","other"}
+_SHA=re.compile(r"^[0-9a-f]{40,64}$");_SHA256=re.compile(r"^[0-9a-f]{64}$");_CHANGE_ID=re.compile(r"^[A-Z][A-Z0-9-]{2,63}$")
+def _text(v:Any,f:str,n:int,*,empty_ok=False)->str:
+ if not isinstance(v,str):raise ValueError(f"{f} must be a string")
+ v=v.strip()
+ if not v and not empty_ok:raise ValueError(f"{f} must not be empty")
+ if len(v)>n:raise ValueError(f"{f} exceeds {n} characters")
+ return v
+def _sha(v:Any,f:str,*,optional=False):
+ if v is None and optional:return None
+ if not isinstance(v,str) or not _SHA.fullmatch(v):raise ValueError(f"{f} must be full lowercase Git SHA")
+ return v
+def validate_change(p:dict[str,Any])->dict[str,Any]:
+ if not isinstance(p,dict):raise ValueError("change must be an object")
+ cid=_text(p.get('change_id'),'change_id',64)
+ if not _CHANGE_ID.fullmatch(cid):raise ValueError('invalid change_id')
+ repo=_text(p.get('repository'),'repository',64)
+ if repo not in REPOSITORIES:raise ValueError('repository is not approved DEV repository')
+ priority=p.get('priority','P2')
+ if priority not in PRIORITIES:raise ValueError('invalid priority')
+ if 'execution_approval_ref' in p or 'execution_approval_actor' in p:raise ValueError('client cannot supply approval fields')
+ files=p.get('files',[]);deps=p.get('dependencies',[]);evidence=p.get('test_evidence',[])
+ if not isinstance(files,list) or any(not isinstance(x,str) for x in files):raise ValueError('files must be string array')
+ if any(x.startswith('/') or '..' in x.split('/') for x in files) or len(set(files))!=len(files):raise ValueError('invalid file paths')
+ if not isinstance(deps,list) or any(not isinstance(x,str) for x in deps) or cid in deps or len(set(deps))!=len(deps):raise ValueError('invalid dependencies')
+ if not isinstance(evidence,list) or any(not isinstance(x,dict) for x in evidence):raise ValueError('invalid evidence')
+ for e in evidence:
+ if set(e)-{'kind','result','uri','sha256','summary'}:raise ValueError('unsupported evidence field')
+ if e.get('sha256') is not None and (not isinstance(e['sha256'],str) or not _SHA256.fullmatch(e['sha256'])):raise ValueError('invalid evidence sha256')
+ if e.get('result') not in {'pass','fail','info'}:raise ValueError('invalid evidence result')
+ if p.get('status','proposed')!='proposed' or 'hg1_status' in p or 'hg2_status' in p:raise ValueError('cannot set lifecycle/approval state')
+ return {'change_id':cid,'title':_text(p.get('title'),'title',240),'description':_text(p.get('description',''),'description',10000,empty_ok=True),'repository':repo,'status':'proposed','priority':priority,'owner':_text(p.get('owner'),'owner',120),'dependencies':deps,'commit_sha':_sha(p.get('commit_sha'),'commit_sha',optional=True),'base_sha':_sha(p.get('base_sha'),'base_sha',optional=True),'files':files,'test_evidence':evidence,'hg1_status':'not_requested','hg2_status':'not_requested'}
+class QueueError(RuntimeError):status_code=400
+class NotFound(QueueError):status_code=404
+class Conflict(QueueError):status_code=409
+class Forbidden(QueueError):status_code=403
+class EngineeringQueue:
+ def __init__(self,dsn:str,*,claim_ttl_seconds=900):
+ if not dsn:raise ValueError('DEV-only PostgreSQL DSN required')
+ if not 30<=claim_ttl_seconds<=86400:raise ValueError('claim ttl out of range')
+ self._dsn=dsn;self._claim_ttl=claim_ttl_seconds
+ def _connect(self):
+ import psycopg
+ from psycopg.rows import dict_row
+ return psycopg.connect(self._dsn,row_factory=dict_row)
+ @staticmethod
+ def _record(row):
+ r=dict(row)
+ for f in ('files','test_evidence'):
+ if f in r and not isinstance(r[f],list):r[f]=json.loads(r[f])
+ r.pop('claim_expires_at',None);return r
+ def create(self,data):
+ x=validate_change(data)
+ with self._connect() as c,c.cursor() as q:
+ q.execute('SELECT * FROM public.engineering_queue_create_change(%s,%s,%s,%s,%s,%s,%s,%s,%s::jsonb,%s::jsonb,%s)',(x['change_id'],x['title'],x['description'],x['repository'],x['priority'],x['owner'],x['commit_sha'],x['base_sha'],json.dumps(x['files']),json.dumps(x['test_evidence']),x['dependencies']));r=q.fetchone()
+ if not r:raise Forbidden('agent DB identity required')
+ out=self._record(r);out['dependencies']=x['dependencies'];return out
+ def create_grant(self,issuer,cid,scope,ttl,reason):
+ if scope!='execute' or not isinstance(ttl,int) or not 1<=ttl<=86400:raise ValueError('invalid grant')
+ expiry=datetime.now(timezone.utc)+timedelta(seconds=ttl)
+ from uuid import uuid4
+ with self._connect() as c,c.cursor() as q:
+ if q.execute('SELECT session_user').fetchone()['session_user']!='tars_queue_operator_login':raise Forbidden('operator DB identity required')
+ q.execute('SELECT * FROM public.engineering_queue_issue_execution_grant(%s,%s,%s,%s,%s)',('EG-'+uuid4().hex,cid,scope,expiry,_text(reason,'reason',1000)));r=q.fetchone()
+ if not r:raise Forbidden('operator DB login required')
+ return dict(r)
+ def revoke_grant(self,actor,gid,reason):
+ with self._connect() as c,c.cursor() as q:
+ if q.execute('SELECT session_user').fetchone()['session_user']!='tars_queue_operator_login':raise Forbidden('operator DB identity required')
+ q.execute('SELECT * FROM public.engineering_queue_revoke_execution_grant(%s,%s)',(gid,_text(reason,'reason',1000)));r=q.fetchone()
+ if not r:raise Forbidden('operator DB login required')
+ return dict(r)
+ def claim(self,cid,actor,grant):
+ with self._connect() as c,c.cursor() as q:
+ if q.execute('SELECT session_user').fetchone()['session_user']!='tars_queue_agent_login':raise Forbidden('agent DB identity required')
+ q.execute('SELECT * FROM public.engineering_queue_claim(%s,%s,%s)',(cid,_text(grant,'grant',120),self._claim_ttl));r=q.fetchone()
+ if not r:raise Forbidden('agent DB login required')
+ return self._record(r)
+ def update_status(self,cid,actor,status,version,reason,*,grant_id=None,operator_actor=None):
+ with self._connect() as c,c.cursor() as q:
+ who=q.execute('SELECT session_user').fetchone()['session_user']
+ if status=='ready':
+ if who!='tars_queue_operator_login' or not grant_id:raise Forbidden('operator grant required')
+ q.execute('SELECT * FROM public.engineering_queue_authorize_ready(%s,%s,%s,%s)',(cid,version,_text(reason,'reason',1000),grant_id))
+ else:
+ if who!='tars_queue_agent_login':raise Forbidden('agent DB identity required')
+ q.execute('SELECT * FROM public.engineering_queue_agent_status(%s,%s,%s,%s)',(cid,status,version,_text(reason,'reason',1000)))
+ r=q.fetchone()
+ if not r:raise Forbidden('runtime login required')
+ return self._record(r)
+ def get(self,cid):
+ with self._connect() as c,c.cursor() as q:
+ q.execute('SELECT * FROM public.engineering_changes WHERE change_id=%s',(cid,));r=q.fetchone()
+ if not r:raise NotFound('change not found')
+ q.execute('SELECT depends_on_change_id FROM public.engineering_change_dependencies WHERE change_id=%s ORDER BY 1',(cid,));r['dependencies']=[x['depends_on_change_id'] for x in q.fetchall()]
+ return self._record(r)
+ def list(self,*,status=None,repository=None,limit=100,cursor=None):
+ if not 1<=limit<=200:raise ValueError('invalid limit')
+ clauses=[];params=[]
+ if status:clauses.append('status=%s');params.append(status)
+ if repository:clauses.append('repository=%s');params.append(repository)
+ if cursor:clauses.append('change_id>%s');params.append(cursor)
+ where=' WHERE '+' AND '.join(clauses) if clauses else ''
+ with self._connect() as c,c.cursor() as q:
+ q.execute(f'SELECT * FROM public.engineering_changes{where} ORDER BY change_id LIMIT %s',(*params,limit+1));rows=q.fetchall();more=len(rows)>limit;rows=rows[:limit]
+ for r in rows:q.execute('SELECT depends_on_change_id FROM public.engineering_change_dependencies WHERE change_id=%s ORDER BY 1',(r['change_id'],));r['dependencies']=[x['depends_on_change_id'] for x in q.fetchall()]
+ return {'items':[self._record(x) for x in rows],'next_cursor':rows[-1]['change_id'] if more and rows else None}
+ def list_grants(self,cid):
+ with self._connect() as c,c.cursor() as q:
+ q.execute('SELECT grant_id,change_id,scope,issuer,issued_at,expires_at,revoked_at,revoked_by,revoke_reason,reason FROM public.engineering_execution_grants WHERE change_id=%s ORDER BY issued_at,grant_id',(cid,));return [dict(x) for x in q.fetchall()]
+ def attach_evidence(self,cid,actor,e):
+ with self._connect() as c,c.cursor() as q:
+ if q.execute('SELECT session_user').fetchone()['session_user']!='tars_queue_agent_login':raise Forbidden('agent DB identity required')
+ q.execute('SELECT * FROM public.engineering_queue_attach_evidence(%s,%s,%s,%s,%s,%s)',(cid,e['evidence_type'],e['uri'],e.get('sha256'),e['summary'],e.get('result')));r=q.fetchone()
+ if not r:raise Forbidden('agent login required')
+ return dict(r)
+ def submit_for_review(self,cid,actor,version):
+ with self._connect() as c,c.cursor() as q:
+ if q.execute('SELECT session_user').fetchone()['session_user']!='tars_queue_agent_login':raise Forbidden('agent DB identity required')
+ q.execute('SELECT * FROM public.engineering_queue_submit_for_review(%s,%s)',(cid,version));r=q.fetchone()
+ if not r:raise Forbidden('agent login required')
+ return self._record(r)
+ def evidence(self,cid):
+ with self._connect() as c,c.cursor() as q:q.execute('SELECT * FROM public.engineering_change_evidence WHERE change_id=%s ORDER BY evidence_id',(cid,));return [dict(x) for x in q.fetchall()]
+ def set_approval_from_authority(self,*a,**k):raise Forbidden('Human Gate decisions are external')
diff --git a/services/tars-engineering-queue-dev/gpt_mcp_host.py b/services/tars-engineering-queue-dev/gpt_mcp_host.py
new file mode 100644
index 0000000..71e578b
--- /dev/null
+++ b/services/tars-engineering-queue-dev/gpt_mcp_host.py
@@ -0,0 +1,27 @@
+"""GPT Queue MCP host factory, isolated from the TKC health-only facade."""
+from __future__ import annotations
+import json
+from typing import Any
+from .gpt_queue_mcp import GPTQueueFacade
+SERVER_NAME="tars-engineering-queue-gpt"
+MCP_PATH="/mcp"
+REQUIRED_SCOPE="tars:queue"
+def create_app(*,facade:GPTQueueFacade,token_verifier:Any,issuer:str,audience:str,allowed_hosts:tuple[str,...]):
+ if not issuer or not audience or not allowed_hosts: raise ValueError("issuer, audience, and explicit allowed hosts are required")
+ try:
+ from mcp.server.auth.settings import AuthSettings
+ from mcp.server.mcpserver import MCPServer
+ from mcp.server.transport_security import TransportSecuritySettings
+ from mcp.types import ToolAnnotations
+ except ImportError as exc: raise RuntimeError("MCP Python SDK v2 is required") from exc
+ server=MCPServer(name=SERVER_NAME,version="0.1.0",instructions="Queue create makes proposed tasks only; independent Operator grants and Human Gate decisions remain external.",token_verifier=token_verifier,auth=AuthSettings(issuer_url=issuer,resource_server_url=audience,required_scopes=[REQUIRED_SCOPE],validate_token_resource=True))
+ @server.tool(name="queue_create",title="Create Queue task",description="Create proposed task through the existing Queue API.",annotations=ToolAnnotations(read_only_hint=False,destructive_hint=False,idempotent_hint=False,open_world_hint=False))
+ async def queue_create(change_id:str,title:str,description:str,repository:str="tars-platform",priority:str="P2",owner:str="gpt"):
+ return json.dumps(facade.create({"change_id":change_id,"title":title,"description":description,"repository":repository,"priority":priority,"owner":owner}),ensure_ascii=False,sort_keys=True)
+ @server.tool(name="queue_status",title="Queue status",description="Read task from existing Queue API.",annotations=ToolAnnotations(read_only_hint=True,destructive_hint=False,idempotent_hint=True,open_world_hint=False))
+ async def queue_status(change_id:str): return json.dumps(facade.status(change_id),ensure_ascii=False,sort_keys=True)
+ @server.tool(name="queue_result",title="Queue result and evidence",description="Read task result and evidence from existing Queue API.",annotations=ToolAnnotations(read_only_hint=True,destructive_hint=False,idempotent_hint=True,open_world_hint=False))
+ async def queue_result(change_id:str): return json.dumps(facade.result(change_id),ensure_ascii=False,sort_keys=True)
+ app=server.streamable_http_app(streamable_http_path=MCP_PATH,transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=True,allowed_hosts=list(allowed_hosts),allowed_origins=["https://"+h.split(":",1)[0] for h in allowed_hosts if not h.startswith("127.")]))
+ app.state.mcp_server=server; app.state.facade_name=SERVER_NAME
+ return app
diff --git a/services/tars-engineering-queue-dev/gpt_queue_mcp.py b/services/tars-engineering-queue-dev/gpt_queue_mcp.py
new file mode 100644
index 0000000..f9ef74b
--- /dev/null
+++ b/services/tars-engineering-queue-dev/gpt_queue_mcp.py
@@ -0,0 +1,91 @@
+"""MCP facade exposing bounded GPT access to the existing Queue API only.
+
+Creates tasks as proposed; execution grants and lifecycle authorization remain
+external Operator actions. No direct database or alternate queue is introduced.
+"""
+from __future__ import annotations
+
+import json
+import os
+from typing import Any
+from urllib.parse import quote
+
+from .api_worker import API_BASE, QueueAPIClient
+
+MAX_TASK_BYTES = 16_384
+_ALLOWED_CREATE_FIELDS = {
+ "change_id", "title", "description", "repository", "priority", "owner",
+ "dependencies", "commit_sha", "base_sha", "files", "test_evidence",
+}
+
+
+class GPTQueueFacade:
+ def __init__(self, agent_api_key: str, base_url: str = API_BASE, timeout: float = 8.0):
+ self.client = QueueAPIClient(agent_api_key, base_url=base_url, timeout=timeout)
+
+ def create(self, task: dict[str, Any]):
+ if not isinstance(task, dict) or set(task) - _ALLOWED_CREATE_FIELDS:
+ raise ValueError("task contains unsupported fields")
+ body = json.dumps(task, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
+ if len(body) > MAX_TASK_BYTES:
+ raise ValueError("task exceeds size limit")
+ return self.client._request("POST", "/v1/changes", task)
+
+ def status(self, change_id: str):
+ return self.client.get(change_id)
+
+ def result(self, change_id: str):
+ return {"change": self.client.get(change_id), "evidence": self.client._request(
+ "GET", "/v1/changes/" + quote(change_id, safe="") + "/evidence"
+ )}
+
+
+def _build_mcp_server(facade: GPTQueueFacade):
+ try:
+ from mcp.server.mcpserver import MCPServer
+ from mcp.types import ToolAnnotations
+ except ImportError as exc:
+ raise RuntimeError("MCP Python SDK v2 is required for GPT Queue tools") from exc
+
+ server = MCPServer(
+ name="tars-engineering-queue-gpt",
+ version="0.1.0",
+ instructions=("Queue client for DEV. Create makes proposed tasks only. "
+ "Execution grants/readiness require an independent Operator."),
+ )
+
+ @server.tool(
+ name="queue_create", title="Create Queue task",
+ description="Create a proposed task in the existing Engineering Queue DEV API; no grant or readiness is issued.",
+ annotations=ToolAnnotations(read_only_hint=False, destructive_hint=False, idempotent_hint=False, open_world_hint=False),
+ )
+ async def queue_create(change_id: str, title: str, description: str, repository: str = "tars-platform",
+ priority: str = "P2", owner: str = "gpt") -> str:
+ result = facade.create({"change_id": change_id, "title": title, "description": description,
+ "repository": repository, "priority": priority, "owner": owner})
+ return json.dumps(result, ensure_ascii=False, sort_keys=True)
+
+ @server.tool(
+ name="queue_status", title="Read Queue task status",
+ description="Read the current task record from the existing Engineering Queue DEV API.",
+ annotations=ToolAnnotations(read_only_hint=True, destructive_hint=False, idempotent_hint=True, open_world_hint=False),
+ )
+ async def queue_status(change_id: str) -> str:
+ return json.dumps(facade.status(change_id), ensure_ascii=False, sort_keys=True)
+
+ @server.tool(
+ name="queue_result", title="Read Queue result and evidence",
+ description="Read task status and persisted evidence from the existing Engineering Queue DEV API.",
+ annotations=ToolAnnotations(read_only_hint=True, destructive_hint=False, idempotent_hint=True, open_world_hint=False),
+ )
+ async def queue_result(change_id: str) -> str:
+ return json.dumps(facade.result(change_id), ensure_ascii=False, sort_keys=True)
+
+ return server
+
+
+def build_server_from_env():
+ token = os.environ.get("TARS_QUEUE_GPT_AGENT_API_KEY", "")
+ if not token.strip():
+ raise RuntimeError("TARS_QUEUE_GPT_AGENT_API_KEY must be supplied by a protected DEV secret provider")
+ return _build_mcp_server(GPTQueueFacade(token, base_url=os.environ.get("TARS_QUEUE_API_BASE", API_BASE)))
diff --git a/services/tars-engineering-queue-dev/launcher.py b/services/tars-engineering-queue-dev/launcher.py
new file mode 100644
index 0000000..280d2c3
--- /dev/null
+++ b/services/tars-engineering-queue-dev/launcher.py
@@ -0,0 +1,77 @@
+from __future__ import annotations
+import os
+import stat
+from pathlib import Path
+
+from services.tars_engineering_queue_dev.config import (
+ AGENT_LOGIN, OPERATOR_LOGIN, RUNNER_BIND_HOST,
+ validate_agent_operator_dsns, validate_runner_bind, validate_runtime_env_file,
+)
+from services.tars_engineering_queue_dev.core.api import create_app
+from services.tars_engineering_queue_dev.core.queue_store import EngineeringQueue
+from services.tars_engineering_queue_dev.runtime_readiness import verify_runtime_databases
+
+
+def _private_env() -> None:
+ path = os.environ.get("TARS_QUEUE_RUNTIME_ENV_FILE", "")
+ if not path:
+ raise RuntimeError("TARS_QUEUE_RUNTIME_ENV_FILE required")
+ validate_runtime_env_file(path)
+ info = Path(path).lstat()
+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o077:
+ raise RuntimeError("Queue runtime configuration must be a private regular file owned by the service identity")
+
+
+def _store(dsn: str) -> EngineeringQueue:
+ return EngineeringQueue(dsn)
+
+
+def build_app():
+ """Construct the existing API only after both clone logins pass read-only readiness."""
+ _private_env()
+ validate_runner_bind(os.environ.get("TARS_QUEUE_BIND_HOST", RUNNER_BIND_HOST))
+ agent_dsn = os.environ.get("TARS_QUEUE_AGENT_DSN", "")
+ operator_dsn = os.environ.get("TARS_QUEUE_OPERATOR_DSN", "")
+ validate_agent_operator_dsns(agent_dsn, operator_dsn)
+ expected_system_id = os.environ.get("TARS_QUEUE_EXPECTED_SYSTEM_ID", "")
+ if not expected_system_id.isdigit():
+ raise RuntimeError("TARS_QUEUE_EXPECTED_SYSTEM_ID must be pinned in protected DEV configuration")
+ # Performs SELECT-only identity, role, schema and direct-DML checks for both logins.
+ # It never migrates, writes Queue rows, issues grants, or alters privileges.
+ verify_runtime_databases(agent_dsn, operator_dsn, expected_system_id)
+
+ n = int(os.environ.get("TARS_QUEUE_AGENT_COUNT", "0"))
+ opk = os.environ.get("TARS_QUEUE_DEV_OPERATOR_KEY", "")
+ opi = os.environ.get("TARS_QUEUE_DEV_OPERATOR_ID", "")
+ if not 1 <= n <= 32:
+ raise RuntimeError("Agent count invalid")
+ if not opk or not opi.strip():
+ raise RuntimeError("Operator credential and identity are required")
+ agents = {}
+ for i in range(1, n + 1):
+ key = os.environ.get(f"TARS_QUEUE_AGENT_{i}_KEY", "")
+ subject = os.environ.get(f"TARS_QUEUE_AGENT_{i}_ID", "")
+ if (not key or not subject or key == opk or key in agents or
+ subject == opi or subject in agents.values()):
+ raise RuntimeError("Agent/Operator IDs or credentials overlap")
+ agents[key] = subject
+ return create_app(
+ agent_queue=_store(agent_dsn),
+ operator_queue=_store(operator_dsn),
+ agent_api_keys=agents,
+ operator_api_key=opk,
+ operator_id=opi,
+ )
+
+
+def main() -> None:
+ """Run the API on its fixed private DEV interface; secrets come from service env."""
+ import uvicorn
+ _private_env()
+ host = os.environ.get("TARS_QUEUE_BIND_HOST", RUNNER_BIND_HOST)
+ validate_runner_bind(host)
+ uvicorn.run(build_app(), host=host, port=8904, access_log=False)
+
+
+if __name__ == "__main__": # pragma: no cover - process entry point
+ main()
diff --git a/services/tars-engineering-queue-dev/migrations/004_queue_store_contract.sql b/services/tars-engineering-queue-dev/migrations/004_queue_store_contract.sql
new file mode 100644
index 0000000..f0d3169
--- /dev/null
+++ b/services/tars-engineering-queue-dev/migrations/004_queue_store_contract.sql
@@ -0,0 +1,276 @@
+-- Version 004: install the routines required by current DEV queue_store.py.
+-- Operator must set transaction-local expected identity GUCs from the immediately preceding read-only probe.
+-- This changes only Queue routines/ACLs and object ownership, not table definitions or row data.
+BEGIN;
+SET LOCAL search_path = pg_catalog, public;
+DO $$
+DECLARE expected_system_id numeric; expected_server inet; expected_client inet; actual_system_id numeric; db_owner name; schema_owner name;
+BEGIN
+ BEGIN
+ expected_system_id:=current_setting('tars.queue.expected_system_identifier',true)::numeric;
+ expected_server:=current_setting('tars.queue.expected_server_addr',true)::inet;
+ expected_client:=current_setting('tars.queue.expected_client_addr',true)::inet;
+ EXCEPTION WHEN OTHERS THEN RAISE EXCEPTION 'required operator-pinned clone identity settings missing or invalid'; END;
+ IF expected_system_id IS DISTINCT FROM 7709241176253177900::numeric THEN RAISE EXCEPTION 'operator expected system identifier must match approved isolated clone'; END IF;
+ IF expected_system_id IS NULL OR expected_server IS NULL OR expected_client IS NULL THEN RAISE EXCEPTION 'required operator-pinned clone identity settings missing'; END IF;
+ IF current_database()<>'tars_queue_itest' OR current_user<>session_user OR session_user IN ('tars_queue_agent_login','tars_queue_operator_login','tars_queue_seed_login') THEN RAISE EXCEPTION 'wrong database, switched role, or runtime login cannot migrate'; END IF;
+ IF NOT (SELECT rolsuper FROM pg_roles WHERE rolname=session_user) THEN RAISE EXCEPTION 'authorized isolated setup superuser required'; END IF;
+ SELECT pg_get_userbyid(datdba) INTO db_owner FROM pg_database WHERE datname=current_database();
+ SELECT pg_get_userbyid(nspowner) INTO schema_owner FROM pg_namespace WHERE nspname='public';
+ IF db_owner<>'tars_queue_itest' THEN RAISE EXCEPTION 'database owner mismatch'; END IF;
+ IF schema_owner<>'pg_database_owner' THEN RAISE EXCEPTION 'public schema owner mismatch'; END IF;
+ IF inet_server_addr() IS DISTINCT FROM expected_server OR inet_client_addr() IS DISTINCT FROM expected_client THEN RAISE EXCEPTION 'server/client endpoint differs from operator preflight'; END IF;
+ SELECT system_identifier INTO actual_system_id FROM pg_control_system();
+ IF actual_system_id IS DISTINCT FROM expected_system_id THEN RAISE EXCEPTION 'cluster system identifier differs from operator preflight'; END IF;
+ IF current_setting('server_version_num')::integer NOT BETWEEN 160000 AND 169999 THEN RAISE EXCEPTION 'unreviewed PostgreSQL major version'; END IF;
+END $$;
+DO $$
+DECLARE
+ t text[] := ARRAY['engineering_changes','engineering_change_dependencies','engineering_change_evidence','engineering_change_events','engineering_execution_grants','engineering_execution_grant_events'];
+ s text[] := ARRAY['engineering_change_evidence_evidence_id_seq','engineering_change_events_event_id_seq','engineering_execution_grant_events_event_id_seq']; n integer;
+BEGIN
+ IF current_database()<>'tars_queue_itest' OR current_user<>session_user OR session_user IN ('tars_queue_agent_login','tars_queue_operator_login','tars_queue_seed_login') THEN RAISE EXCEPTION 'wrong database, switched role, or runtime login cannot migrate'; END IF;
+ IF NOT (SELECT rolsuper FROM pg_roles WHERE rolname=session_user) THEN RAISE EXCEPTION 'authorized isolated setup superuser required'; END IF;
+ IF NOT EXISTS(SELECT 1 FROM pg_roles WHERE rolname='tars_queue_owner' AND NOT rolcanlogin AND NOT rolsuper AND NOT rolcreatedb AND NOT rolcreaterole AND NOT rolreplication AND NOT rolbypassrls) THEN RAISE EXCEPTION 'safe NOLOGIN owner role required'; END IF;
+ IF NOT EXISTS(SELECT 1 FROM pg_roles WHERE rolname='tars_queue_agent' AND NOT rolcanlogin AND NOT rolsuper AND NOT rolcreatedb AND NOT rolcreaterole AND NOT rolreplication AND NOT rolbypassrls) OR NOT EXISTS(SELECT 1 FROM pg_roles WHERE rolname='tars_queue_operator' AND NOT rolcanlogin AND NOT rolsuper AND NOT rolcreatedb AND NOT rolcreaterole AND NOT rolreplication AND NOT rolbypassrls) OR NOT EXISTS(SELECT 1 FROM pg_roles WHERE rolname='tars_queue_seed' AND NOT rolcanlogin AND NOT rolsuper AND NOT rolcreatedb AND NOT rolcreaterole AND NOT rolreplication AND NOT rolbypassrls) THEN RAISE EXCEPTION 'capability roles missing or unsafe'; END IF;
+ IF NOT EXISTS(SELECT 1 FROM pg_roles WHERE rolname='tars_queue_agent_login' AND rolcanlogin AND NOT rolsuper AND NOT rolcreatedb AND NOT rolcreaterole AND NOT rolreplication AND NOT rolbypassrls) OR NOT EXISTS(SELECT 1 FROM pg_roles WHERE rolname='tars_queue_operator_login' AND rolcanlogin AND NOT rolsuper AND NOT rolcreatedb AND NOT rolcreaterole AND NOT rolreplication AND NOT rolbypassrls) OR NOT EXISTS(SELECT 1 FROM pg_roles WHERE rolname='tars_queue_seed_login' AND rolcanlogin AND NOT rolsuper AND NOT rolcreatedb AND NOT rolcreaterole AND NOT rolreplication AND NOT rolbypassrls) THEN RAISE EXCEPTION 'restricted login roles missing or unsafe'; END IF;
+ IF EXISTS(SELECT 1 FROM pg_auth_members m JOIN pg_roles u ON u.oid=m.member JOIN pg_roles r ON r.oid=m.roleid WHERE u.rolname IN ('tars_queue_agent_login','tars_queue_operator_login','tars_queue_seed_login') AND ((u.rolname='tars_queue_agent_login' AND r.rolname<>'tars_queue_agent') OR (u.rolname='tars_queue_operator_login' AND r.rolname<>'tars_queue_operator') OR (u.rolname='tars_queue_seed_login' AND r.rolname<>'tars_queue_seed') OR m.admin_option OR NOT m.inherit_option OR m.set_option)) OR (SELECT count(*) FROM pg_auth_members m JOIN pg_roles u ON u.oid=m.member WHERE u.rolname IN ('tars_queue_agent_login','tars_queue_operator_login','tars_queue_seed_login'))<>3 OR EXISTS(SELECT 1 FROM pg_auth_members m JOIN pg_roles r ON r.oid=m.roleid WHERE r.rolname='tars_queue_owner') THEN RAISE EXCEPTION 'runtime membership contract mismatch'; END IF;
+ IF EXISTS (SELECT 1 FROM pg_catalog.pg_namespace n CROSS JOIN LATERAL aclexplode(COALESCE(n.nspacl,acldefault('n',n.nspowner))) a WHERE n.nspname='public' AND a.grantee=0 AND a.privilege_type='CREATE') THEN RAISE EXCEPTION 'public schema CREATE granted to PUBLIC; refusing broad ACL change'; END IF;
+ SELECT count(*) INTO n FROM pg_class c JOIN pg_namespace x ON x.oid=c.relnamespace WHERE x.nspname='public' AND c.relname=ANY(t) AND c.relkind IN ('r','p'); IF n<>6 THEN RAISE EXCEPTION 'all six queue tables must exist with table relkinds'; END IF;
+ IF EXISTS(SELECT 1 FROM pg_class c JOIN pg_namespace x ON x.oid=c.relnamespace WHERE x.nspname='public' AND c.relname=ANY(t) AND c.relowner<>'tars_queue_itest'::regrole) THEN RAISE EXCEPTION 'queue table pre-migration owner mismatch'; END IF;
+ SELECT count(*) INTO n FROM pg_class c JOIN pg_namespace x ON x.oid=c.relnamespace WHERE x.nspname='public' AND c.relname=ANY(s) AND c.relkind='S'; IF n<>3 THEN RAISE EXCEPTION 'all three queue sequences must exist'; END IF;
+ IF EXISTS(SELECT 1 FROM pg_class c JOIN pg_namespace x ON x.oid=c.relnamespace WHERE x.nspname='public' AND c.relname=ANY(s) AND c.relowner<>'tars_queue_itest'::regrole) THEN RAISE EXCEPTION 'queue sequence pre-migration owner mismatch'; END IF;
+ IF EXISTS(SELECT 1 FROM (VALUES
+ ('engineering_changes','change_id'),('engineering_changes','title'),('engineering_changes','description'),('engineering_changes','repository'),('engineering_changes','status'),('engineering_changes','priority'),('engineering_changes','owner'),('engineering_changes','commit_sha'),('engineering_changes','base_sha'),('engineering_changes','files'),('engineering_changes','test_evidence'),('engineering_changes','hg1_status'),('engineering_changes','hg1_approval_ref'),('engineering_changes','hg2_status'),('engineering_changes','hg2_approval_ref'),('engineering_changes','claimed_by'),('engineering_changes','claim_expires_at'),('engineering_changes','execution_approval_ref'),('engineering_changes','execution_approval_actor'),('engineering_changes','version'),('engineering_changes','updated_at'),('engineering_changes','submitted_at'),
+ ('engineering_change_dependencies','change_id'),('engineering_change_dependencies','depends_on_change_id'),
+ ('engineering_change_evidence','evidence_id'),('engineering_change_evidence','change_id'),('engineering_change_evidence','evidence_type'),('engineering_change_evidence','uri'),('engineering_change_evidence','sha256'),('engineering_change_evidence','summary'),('engineering_change_evidence','result'),('engineering_change_evidence','recorded_by'),
+ ('engineering_change_events','change_id'),('engineering_change_events','event_type'),('engineering_change_events','actor'),('engineering_change_events','old_status'),('engineering_change_events','new_status'),('engineering_change_events','details'),
+ ('engineering_execution_grants','grant_id'),('engineering_execution_grants','change_id'),('engineering_execution_grants','scope'),('engineering_execution_grants','issuer'),('engineering_execution_grants','issued_at'),('engineering_execution_grants','expires_at'),('engineering_execution_grants','revoked_at'),('engineering_execution_grants','revoked_by'),('engineering_execution_grants','revoke_reason'),('engineering_execution_grants','reason'),
+ ('engineering_execution_grant_events','event_id'),('engineering_execution_grant_events','grant_id'),('engineering_execution_grant_events','change_id'),('engineering_execution_grant_events','event_type'),('engineering_execution_grant_events','actor'),('engineering_execution_grant_events','details')
+ ) AS required(table_name,column_name) WHERE NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace x ON x.oid=c.relnamespace JOIN pg_attribute a ON a.attrelid=c.oid WHERE x.nspname='public' AND c.relname=required.table_name AND a.attname=required.column_name AND a.attnum>0 AND NOT a.attisdropped)) THEN RAISE EXCEPTION 'queue schema column contract mismatch'; END IF;
+ IF EXISTS(SELECT 1 FROM unnest(t) AS obj(table_name) CROSS JOIN (VALUES ('tars_queue_agent'),('tars_queue_operator'),('tars_queue_seed'),('tars_queue_agent_login'),('tars_queue_operator_login'),('tars_queue_seed_login')) AS roles(role_name) WHERE has_table_privilege(roles.role_name,'public.'||table_name,'INSERT') OR has_table_privilege(roles.role_name,'public.'||table_name,'UPDATE') OR has_table_privilege(roles.role_name,'public.'||table_name,'DELETE') OR has_table_privilege(roles.role_name,'public.'||table_name,'TRUNCATE') OR has_table_privilege(roles.role_name,'public.'||table_name,'REFERENCES') OR has_table_privilege(roles.role_name,'public.'||table_name,'TRIGGER') OR (roles.role_name IN ('tars_queue_seed','tars_queue_seed_login') AND has_table_privilege(roles.role_name,'public.'||table_name,'SELECT'))) THEN RAISE EXCEPTION 'runtime or seed direct table privileges violate least privilege'; END IF;
+ IF EXISTS(SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace CROSS JOIN LATERAL aclexplode(COALESCE(c.relacl,acldefault('S',c.relowner))) a WHERE n.nspname='public' AND c.relname=ANY(s) AND a.grantee=0 AND a.privilege_type IN ('USAGE','SELECT','UPDATE')) THEN RAISE EXCEPTION 'PUBLIC has queue sequence privileges'; END IF;
+ IF EXISTS(SELECT 1 FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace CROSS JOIN (VALUES ('tars_queue_agent'),('tars_queue_operator'),('tars_queue_seed'),('tars_queue_agent_login'),('tars_queue_operator_login'),('tars_queue_seed_login')) AS roles(role_name) WHERE n.nspname='public' AND c.relname=ANY(t) AND a.attnum>0 AND NOT a.attisdropped AND (has_column_privilege(roles.role_name,c.oid,a.attnum,'INSERT') OR has_column_privilege(roles.role_name,c.oid,a.attnum,'UPDATE') OR has_column_privilege(roles.role_name,c.oid,a.attnum,'REFERENCES'))) THEN RAISE EXCEPTION 'column-level runtime/seed table privileges violate least privilege'; END IF;
+ IF EXISTS(SELECT 1 FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid=p.pronamespace CROSS JOIN LATERAL aclexplode(COALESCE(p.proacl,acldefault('f',p.proowner))) a WHERE n.nspname='public' AND p.proname LIKE 'engineering_queue_%' AND a.grantee=0 AND a.privilege_type='EXECUTE') THEN RAISE EXCEPTION 'PUBLIC can execute a queue routine'; END IF;
+ IF EXISTS(SELECT 1 FROM pg_proc p JOIN pg_namespace x ON x.oid=p.pronamespace WHERE x.nspname='public' AND p.proname=ANY(ARRAY['engineering_queue_create_change','engineering_queue_issue_execution_grant','engineering_queue_revoke_execution_grant','engineering_queue_authorize_ready','engineering_queue_claim','engineering_queue_attach_evidence','engineering_queue_agent_status','engineering_queue_submit_for_review','engineering_queue_seed_import','engineering_queue_protect_approval_columns'])) THEN RAISE EXCEPTION 'routine collision or partial migration'; END IF;
+ IF EXISTS(SELECT 1 FROM pg_trigger WHERE tgname='engineering_queue_protect_approval_columns_trigger' AND NOT tgisinternal) THEN RAISE EXCEPTION 'approval protection trigger already exists'; END IF;
+END $$;
+DO $$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_catalog.pg_namespace n CROSS JOIN LATERAL aclexplode(COALESCE(n.nspacl,acldefault('n',n.nspowner))) a WHERE n.nspname='public' AND a.grantee=0 AND a.privilege_type='CREATE') THEN RAISE EXCEPTION 'public schema CREATE granted to PUBLIC; refusing broad ACL change'; END IF;
+ IF has_schema_privilege('tars_queue_agent','public','CREATE') OR has_schema_privilege('tars_queue_operator','public','CREATE') OR has_schema_privilege('tars_queue_seed','public','CREATE') OR has_schema_privilege('tars_queue_agent_login','public','CREATE') OR has_schema_privilege('tars_queue_operator_login','public','CREATE') OR has_schema_privilege('tars_queue_seed_login','public','CREATE') THEN RAISE EXCEPTION 'runtime role has public schema CREATE'; END IF;
+END $$;
+GRANT USAGE,CREATE ON SCHEMA public TO tars_queue_owner;
+REVOKE CREATE ON SCHEMA public FROM tars_queue_agent,tars_queue_operator,tars_queue_seed;
+GRANT USAGE ON SCHEMA public TO tars_queue_agent,tars_queue_operator,tars_queue_seed;
+DO $$ DECLARE obj text; BEGIN
+ FOREACH obj IN ARRAY ARRAY['engineering_changes','engineering_change_dependencies','engineering_change_evidence','engineering_change_events','engineering_execution_grants','engineering_execution_grant_events'] LOOP
+ EXECUTE format('ALTER TABLE public.%I OWNER TO %I',obj,'tars_queue_owner');
+ END LOOP;
+ FOREACH obj IN ARRAY ARRAY['engineering_change_evidence_evidence_id_seq','engineering_change_events_event_id_seq','engineering_execution_grant_events_event_id_seq'] LOOP
+ EXECUTE format('ALTER SEQUENCE public.%I OWNER TO %I',obj,'tars_queue_owner');
+ END LOOP;
+END $$;
+DO $$ DECLARE n integer; BEGIN
+ SELECT count(*) INTO n FROM pg_class c JOIN pg_namespace x ON x.oid=c.relnamespace WHERE x.nspname='public' AND c.relname=ANY(ARRAY['engineering_changes','engineering_change_dependencies','engineering_change_evidence','engineering_change_events','engineering_execution_grants','engineering_execution_grant_events']) AND c.relkind IN ('r','p') AND c.relowner='tars_queue_owner'::regrole;
+ IF n<>6 THEN RAISE EXCEPTION 'queue table owner handoff mismatch'; END IF;
+ SELECT count(*) INTO n FROM pg_class c JOIN pg_namespace x ON x.oid=c.relnamespace WHERE x.nspname='public' AND c.relname=ANY(ARRAY['engineering_change_evidence_evidence_id_seq','engineering_change_events_event_id_seq','engineering_execution_grant_events_event_id_seq']) AND c.relkind='S' AND c.relowner='tars_queue_owner'::regrole;
+ IF n<>3 THEN RAISE EXCEPTION 'queue sequence owner handoff mismatch'; END IF;
+END $$;
+SET LOCAL ROLE tars_queue_owner;
+CREATE OR REPLACE FUNCTION public.engineering_queue_create_change(p_change_id TEXT,p_title TEXT,p_description TEXT,p_repository TEXT,p_priority TEXT,p_owner TEXT,p_commit_sha TEXT,p_base_sha TEXT,p_files JSONB,p_test_evidence JSONB,p_dependencies TEXT[])
+RETURNS SETOF public.engineering_changes LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$
+DECLARE actor TEXT:=session_user; r public.engineering_changes; dep TEXT;
+BEGIN
+ IF actor<>'tars_queue_agent_login' THEN RAISE EXCEPTION 'agent login required' USING ERRCODE='42501'; END IF;
+ IF p_files IS NULL OR jsonb_typeof(p_files)<>'array' OR p_test_evidence IS NULL OR jsonb_typeof(p_test_evidence)<>'array' THEN RAISE EXCEPTION 'files and evidence must be arrays' USING ERRCODE='22023'; END IF;
+ IF p_repository NOT IN ('tars-platform','tars-interaction-runtime','tars-tkc') OR p_priority NOT IN ('P0','P1','P2','P3') OR p_change_id !~ '^[A-Z][A-Z0-9-]{2,63}$' OR length(trim(p_title)) NOT BETWEEN 1 AND 240 OR length(trim(p_owner)) NOT BETWEEN 1 AND 120 THEN RAISE EXCEPTION 'invalid change fields' USING ERRCODE='22023'; END IF;
+ IF p_commit_sha IS NOT NULL AND p_commit_sha !~ '^[0-9a-f]{40,64}$' OR p_base_sha IS NOT NULL AND p_base_sha !~ '^[0-9a-f]{40,64}$' THEN RAISE EXCEPTION 'invalid Git SHA' USING ERRCODE='22023'; END IF;
+ IF EXISTS(SELECT 1 FROM unnest(COALESCE(p_dependencies,ARRAY[]::TEXT[])) d GROUP BY d HAVING count(*)>1) OR p_change_id=ANY(COALESCE(p_dependencies,ARRAY[]::TEXT[])) THEN RAISE EXCEPTION 'invalid dependencies' USING ERRCODE='22023'; END IF;
+ INSERT INTO public.engineering_changes(change_id,title,description,repository,status,priority,owner,commit_sha,base_sha,files,test_evidence,hg1_status,hg2_status) VALUES(p_change_id,p_title,COALESCE(p_description,''),p_repository,'proposed',p_priority,actor,p_commit_sha,p_base_sha,p_files,p_test_evidence,'not_requested','not_requested') RETURNING * INTO r;
+ FOREACH dep IN ARRAY COALESCE(p_dependencies,ARRAY[]::TEXT[]) LOOP INSERT INTO public.engineering_change_dependencies(change_id,depends_on_change_id) VALUES(p_change_id,dep); END LOOP;
+ INSERT INTO public.engineering_change_events(change_id,event_type,actor,new_status,details) VALUES(p_change_id,'created',actor,'proposed',jsonb_build_object('repository',p_repository)); RETURN NEXT r;
+END; $$;
+CREATE OR REPLACE FUNCTION public.engineering_queue_issue_execution_grant(p_grant_id TEXT,p_change_id TEXT,p_scope TEXT,p_expires_at TIMESTAMPTZ,p_reason TEXT)
+RETURNS SETOF public.engineering_execution_grants LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$
+DECLARE actor TEXT:=session_user; r public.engineering_execution_grants;
+BEGIN
+ IF actor<>'tars_queue_operator_login' THEN RAISE EXCEPTION 'operator login required' USING ERRCODE='42501'; END IF;
+ IF p_scope<>'execute' OR p_expires_at<=now() OR p_expires_at>now()+interval '24 hours' THEN RAISE EXCEPTION 'invalid scope or expiry' USING ERRCODE='22023'; END IF;
+ IF NOT EXISTS(SELECT 1 FROM public.engineering_changes WHERE change_id=p_change_id AND status IN ('proposed','blocked')) THEN RAISE EXCEPTION 'change is not grantable' USING ERRCODE='22023'; END IF;
+ IF EXISTS(SELECT 1 FROM public.engineering_changes WHERE change_id=p_change_id AND owner=actor) THEN RAISE EXCEPTION 'self approval forbidden' USING ERRCODE='42501'; END IF;
+ INSERT INTO public.engineering_execution_grants(grant_id,change_id,scope,issuer,expires_at,reason) VALUES(p_grant_id,p_change_id,p_scope,actor,p_expires_at,p_reason) RETURNING * INTO r;
+ INSERT INTO public.engineering_execution_grant_events(grant_id,change_id,event_type,actor,details) VALUES(p_grant_id,p_change_id,'issued',actor,jsonb_build_object('scope',p_scope,'expires_at',p_expires_at,'reason',p_reason)); RETURN NEXT r;
+END; $$;
+CREATE OR REPLACE FUNCTION public.engineering_queue_revoke_execution_grant(p_grant_id TEXT,p_reason TEXT)
+RETURNS SETOF public.engineering_execution_grants LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$
+DECLARE g public.engineering_execution_grants; actor TEXT:=session_user;
+BEGIN
+ IF actor<>'tars_queue_operator_login' THEN RAISE EXCEPTION 'operator login required' USING ERRCODE='42501'; END IF;
+ SELECT * INTO g FROM public.engineering_execution_grants WHERE grant_id=p_grant_id FOR UPDATE; IF NOT FOUND OR g.revoked_at IS NOT NULL THEN RAISE EXCEPTION 'grant missing or already revoked' USING ERRCODE='22023'; END IF;
+ RETURN QUERY UPDATE public.engineering_execution_grants SET revoked_at=now(),revoked_by=actor,revoke_reason=p_reason WHERE grant_id=p_grant_id RETURNING *;
+ INSERT INTO public.engineering_execution_grant_events(grant_id,change_id,event_type,actor,details) VALUES(p_grant_id,g.change_id,'revoked',actor,jsonb_build_object('reason',p_reason));
+END; $$;
+CREATE OR REPLACE FUNCTION public.engineering_queue_authorize_ready(p_change_id TEXT,p_expected_version BIGINT,p_reason TEXT,p_grant_id TEXT)
+RETURNS SETOF public.engineering_changes LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$
+DECLARE oldrow public.engineering_changes; g public.engineering_execution_grants; actor TEXT:=session_user; old_status TEXT;
+BEGIN
+ IF actor<>'tars_queue_operator_login' THEN RAISE EXCEPTION 'operator login required' USING ERRCODE='42501'; END IF;
+ SELECT * INTO oldrow FROM public.engineering_changes WHERE change_id=p_change_id FOR UPDATE; IF NOT FOUND OR oldrow.version<>p_expected_version THEN RAISE EXCEPTION 'change missing or stale version' USING ERRCODE='40001'; END IF;
+ old_status:=oldrow.status; IF old_status NOT IN ('proposed','blocked') THEN RAISE EXCEPTION 'change is not readyable' USING ERRCODE='22023'; END IF;
+ SELECT * INTO g FROM public.engineering_execution_grants WHERE grant_id=p_grant_id AND change_id=p_change_id FOR UPDATE;
+ IF NOT FOUND OR g.scope<>'execute' OR g.issuer<>actor OR g.revoked_at IS NOT NULL OR g.expires_at<=now() THEN RAISE EXCEPTION 'invalid execution grant' USING ERRCODE='42501'; END IF;
+ UPDATE public.engineering_changes SET status='ready',execution_approval_ref=p_grant_id,execution_approval_actor=actor,claimed_by=NULL,claim_expires_at=NULL,version=version+1,updated_at=now() WHERE change_id=p_change_id RETURNING * INTO oldrow;
+ INSERT INTO public.engineering_change_events(change_id,event_type,actor,old_status,new_status,details) VALUES(p_change_id,'status_changed',actor,old_status,'ready',jsonb_build_object('reason',p_reason));
+ INSERT INTO public.engineering_execution_grant_events(grant_id,change_id,event_type,actor,details) VALUES(p_grant_id,p_change_id,'verified',actor,jsonb_build_object('transition','ready')); RETURN NEXT oldrow;
+END; $$;
+CREATE OR REPLACE FUNCTION public.engineering_queue_claim(p_change_id TEXT,p_grant_id TEXT,p_claim_ttl INTEGER)
+RETURNS SETOF public.engineering_changes LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$
+DECLARE oldrow public.engineering_changes; g public.engineering_execution_grants; actor TEXT:=session_user; old_status TEXT;
+BEGIN
+ IF actor<>'tars_queue_agent_login' THEN RAISE EXCEPTION 'agent login required' USING ERRCODE='42501'; END IF;
+ IF p_claim_ttl NOT BETWEEN 30 AND 86400 THEN RAISE EXCEPTION 'invalid claim ttl' USING ERRCODE='22023'; END IF;
+ SELECT * INTO oldrow FROM public.engineering_changes WHERE change_id=p_change_id FOR UPDATE; IF NOT FOUND OR oldrow.status NOT IN ('ready','claimed') THEN RAISE EXCEPTION 'only ready or expired claims may be claimed' USING ERRCODE='40001'; END IF;
+ IF oldrow.status='claimed' AND oldrow.claim_expires_at>now() THEN RAISE EXCEPTION 'change has an active claim' USING ERRCODE='40001'; END IF;
+ SELECT * INTO g FROM public.engineering_execution_grants WHERE grant_id=p_grant_id AND change_id=p_change_id FOR UPDATE;
+ IF NOT FOUND OR g.scope<>'execute' OR g.revoked_at IS NOT NULL OR g.expires_at<=now() OR oldrow.execution_approval_ref<>p_grant_id OR oldrow.execution_approval_actor<>g.issuer THEN RAISE EXCEPTION 'missing or invalid active grant' USING ERRCODE='42501'; END IF;
+ IF g.issuer=actor THEN RAISE EXCEPTION 'grant issuer cannot claim own work' USING ERRCODE='42501'; END IF;
+ IF EXISTS(SELECT 1 FROM public.engineering_change_dependencies d JOIN public.engineering_changes p ON p.change_id=d.depends_on_change_id WHERE d.change_id=p_change_id AND p.status NOT IN ('validated','completed','submitted_for_review')) THEN RAISE EXCEPTION 'unresolved dependencies block claim' USING ERRCODE='40001'; END IF;
+ IF oldrow.status='claimed' THEN INSERT INTO public.engineering_change_events(change_id,event_type,actor,old_status,new_status,details) VALUES(p_change_id,'claim_expired',actor,'claimed','ready',jsonb_build_object('previous_claimant',oldrow.claimed_by)); old_status:='ready'; ELSE old_status:=oldrow.status; END IF;
+ UPDATE public.engineering_changes SET status='claimed',claimed_by=actor,claim_expires_at=now()+make_interval(secs=>p_claim_ttl),version=version+1,updated_at=now() WHERE change_id=p_change_id RETURNING * INTO oldrow;
+ INSERT INTO public.engineering_change_events(change_id,event_type,actor,old_status,new_status,details) VALUES(p_change_id,'claimed',actor,old_status,'claimed',jsonb_build_object('grant_id',p_grant_id));
+ INSERT INTO public.engineering_execution_grant_events(grant_id,change_id,event_type,actor,details) VALUES(p_grant_id,p_change_id,'verified',actor,jsonb_build_object('transition','claim')); RETURN NEXT oldrow;
+END; $$;
+CREATE OR REPLACE FUNCTION public.engineering_queue_attach_evidence(p_change_id TEXT,p_evidence_type TEXT,p_uri TEXT,p_sha256 TEXT,p_summary TEXT,p_result TEXT)
+RETURNS SETOF public.engineering_change_evidence LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$
+DECLARE actor TEXT:=session_user; ev public.engineering_change_evidence;
+BEGIN
+ IF actor<>'tars_queue_agent_login' THEN RAISE EXCEPTION 'agent login required' USING ERRCODE='42501'; END IF;
+ PERFORM 1 FROM public.engineering_changes WHERE change_id=p_change_id FOR UPDATE; IF NOT FOUND THEN RAISE EXCEPTION 'change not found' USING ERRCODE='P0002'; END IF;
+ INSERT INTO public.engineering_change_evidence(change_id,evidence_type,uri,sha256,summary,result,recorded_by) VALUES(p_change_id,p_evidence_type,p_uri,p_sha256,p_summary,p_result,actor) RETURNING * INTO ev;
+ UPDATE public.engineering_changes SET test_evidence=CASE WHEN p_evidence_type='test' THEN test_evidence||jsonb_build_array(jsonb_build_object('kind',p_evidence_type,'result',p_result,'uri',p_uri,'sha256',p_sha256,'summary',p_summary)) ELSE test_evidence END,version=version+1,updated_at=now() WHERE change_id=p_change_id;
+ INSERT INTO public.engineering_change_events(change_id,event_type,actor,details) VALUES(p_change_id,'evidence_attached',actor,jsonb_build_object('evidence_type',p_evidence_type,'evidence_id',ev.evidence_id)); RETURN NEXT ev;
+END; $$;
+CREATE OR REPLACE FUNCTION public.engineering_queue_agent_status(p_change_id TEXT,p_status TEXT,p_expected_version BIGINT,p_reason TEXT)
+RETURNS SETOF public.engineering_changes LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$
+DECLARE oldrow public.engineering_changes; actor TEXT:=session_user; old_status TEXT;
+BEGIN
+ IF actor<>'tars_queue_agent_login' THEN RAISE EXCEPTION 'agent login required' USING ERRCODE='42501'; END IF;
+ IF p_status NOT IN ('in_progress','validated','completed') THEN RAISE EXCEPTION 'status requires an authorized workflow' USING ERRCODE='42501'; END IF;
+ SELECT * INTO oldrow FROM public.engineering_changes WHERE change_id=p_change_id FOR UPDATE; IF NOT FOUND OR oldrow.version<>p_expected_version THEN RAISE EXCEPTION 'change missing or stale version' USING ERRCODE='40001'; END IF;
+ old_status:=oldrow.status; IF (old_status='claimed' AND p_status<>'in_progress') OR (old_status='in_progress' AND p_status<>'validated') OR (old_status='validated' AND p_status<>'completed') THEN RAISE EXCEPTION 'invalid status transition' USING ERRCODE='22023'; END IF;
+ IF old_status='claimed' AND oldrow.claimed_by<>actor THEN RAISE EXCEPTION 'only claimant may update claimed change' USING ERRCODE='42501'; END IF;
+ IF p_status IN ('validated','completed') AND (oldrow.commit_sha IS NULL OR NOT EXISTS(SELECT 1 FROM public.engineering_change_evidence WHERE change_id=p_change_id AND evidence_type='test' AND result='pass')) THEN RAISE EXCEPTION 'pinned commit and passing test evidence required' USING ERRCODE='22023'; END IF;
+ IF p_status='validated' AND NOT EXISTS(SELECT 1 FROM public.engineering_execution_grants g WHERE g.grant_id=oldrow.execution_approval_ref AND g.change_id=p_change_id AND g.scope='execute' AND g.issuer=oldrow.execution_approval_actor AND g.revoked_at IS NULL AND g.expires_at>now()) THEN RAISE EXCEPTION 'active execution grant required' USING ERRCODE='42501'; END IF;
+ IF p_status='completed' AND oldrow.hg1_status IN ('pending','accepted') THEN RAISE EXCEPTION 'completed cannot represent a Human Gate decision' USING ERRCODE='42501'; END IF;
+ UPDATE public.engineering_changes SET status=p_status,claimed_by=NULL,claim_expires_at=NULL,version=version+1,updated_at=now() WHERE change_id=p_change_id RETURNING * INTO oldrow;
+ INSERT INTO public.engineering_change_events(change_id,event_type,actor,old_status,new_status,details) VALUES(p_change_id,'status_changed',actor,old_status,p_status,jsonb_build_object('reason',p_reason)); RETURN NEXT oldrow;
+END; $$;
+CREATE OR REPLACE FUNCTION public.engineering_queue_submit_for_review(p_change_id TEXT,p_expected_version BIGINT)
+RETURNS SETOF public.engineering_changes LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$
+DECLARE oldrow public.engineering_changes; actor TEXT:=session_user;
+BEGIN
+ IF actor<>'tars_queue_agent_login' THEN RAISE EXCEPTION 'agent login required' USING ERRCODE='42501'; END IF;
+ SELECT * INTO oldrow FROM public.engineering_changes WHERE change_id=p_change_id FOR UPDATE; IF NOT FOUND OR oldrow.version<>p_expected_version THEN RAISE EXCEPTION 'change missing or stale version' USING ERRCODE='40001'; END IF;
+ IF oldrow.status<>'validated' OR oldrow.commit_sha IS NULL OR oldrow.hg1_status<>'not_requested' OR NOT EXISTS(SELECT 1 FROM public.engineering_change_evidence WHERE change_id=p_change_id AND evidence_type='review') THEN RAISE EXCEPTION 'review prerequisites not met' USING ERRCODE='22023'; END IF;
+ UPDATE public.engineering_changes SET status='submitted_for_review',hg1_status='pending',submitted_at=now(),version=version+1,updated_at=now() WHERE change_id=p_change_id RETURNING * INTO oldrow;
+ INSERT INTO public.engineering_change_events(change_id,event_type,actor,old_status,new_status,details) VALUES(p_change_id,'submitted_for_review',actor,'validated','submitted_for_review','{}'::jsonb); RETURN NEXT oldrow;
+END; $$;
+CREATE OR REPLACE FUNCTION public.engineering_queue_seed_import(p_batch JSONB)
+RETURNS TABLE(inserted TEXT[],unchanged TEXT[],count INTEGER) LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$
+DECLARE item JSONB; dep TEXT; cid TEXT; n INTEGER:=0; existing public.engineering_changes;
+BEGIN
+ IF session_user<>'tars_queue_seed_login' THEN RAISE EXCEPTION 'seed login required' USING ERRCODE='42501'; END IF;
+ IF jsonb_typeof(p_batch)<>'array' THEN RAISE EXCEPTION 'batch must be an array' USING ERRCODE='22023'; END IF;
+ IF EXISTS(SELECT 1 FROM jsonb_array_elements(p_batch) x WHERE (x->>'status'='completed' AND (x->>'commit_sha' IS NULL OR NOT EXISTS(SELECT 1 FROM jsonb_array_elements(COALESCE(x->'test_evidence','[]'::JSONB)) e WHERE e->>'kind'='test' AND e->>'result'='pass')))) THEN RAISE EXCEPTION 'completed seed requires commit and passing test evidence' USING ERRCODE='22023'; END IF;
+ inserted:=ARRAY[]::TEXT[];unchanged:=ARRAY[]::TEXT[];
+ FOR item IN SELECT value FROM jsonb_array_elements(p_batch) LOOP
+ cid:=item->>'change_id';
+ IF cid IS NULL OR item->>'status' NOT IN ('proposed','completed') THEN RAISE EXCEPTION 'invalid seed projection' USING ERRCODE='22023'; END IF;
+ SELECT * INTO existing FROM public.engineering_changes WHERE change_id=cid FOR UPDATE;
+ IF FOUND THEN
+ IF existing.title IS DISTINCT FROM item->>'title'
+ OR existing.description IS DISTINCT FROM COALESCE(item->>'description','')
+ OR existing.repository IS DISTINCT FROM item->>'repository'
+ OR existing.status IS DISTINCT FROM item->>'status'
+ OR existing.priority IS DISTINCT FROM item->>'priority'
+ OR existing.owner IS DISTINCT FROM item->>'owner'
+ OR existing.commit_sha IS DISTINCT FROM item->>'commit_sha'
+ OR existing.base_sha IS DISTINCT FROM item->>'base_sha'
+ OR existing.files IS DISTINCT FROM COALESCE(item->'files','[]'::JSONB)
+ OR existing.test_evidence IS DISTINCT FROM COALESCE(item->'test_evidence','[]'::JSONB)
+ OR existing.hg1_status<>'not_requested' OR existing.hg1_approval_ref IS NOT NULL
+ OR existing.hg2_status<>'not_requested' OR existing.hg2_approval_ref IS NOT NULL
+ OR existing.execution_approval_ref IS NOT NULL OR existing.execution_approval_actor IS NOT NULL
+ OR EXISTS(SELECT 1 FROM public.engineering_change_dependencies d WHERE d.change_id=cid AND NOT d.depends_on_change_id=ANY(ARRAY(SELECT jsonb_array_elements_text(COALESCE(item->'dependencies','[]'::JSONB)))))
+ OR (SELECT count(*) FROM public.engineering_change_dependencies d WHERE d.change_id=cid)<>(SELECT count(*) FROM jsonb_array_elements(COALESCE(item->'dependencies','[]'::JSONB)))
+ THEN RAISE EXCEPTION 'seed conflict: %',cid USING ERRCODE='23505'; END IF;
+ unchanged:=array_append(unchanged,cid); CONTINUE;
+ END IF;
+ INSERT INTO public.engineering_changes(change_id,title,description,repository,status,priority,owner,commit_sha,base_sha,files,test_evidence,hg1_status,hg2_status)
+ VALUES(cid,item->>'title',COALESCE(item->>'description',''),item->>'repository',item->>'status',item->>'priority',item->>'owner',item->>'commit_sha',item->>'base_sha',COALESCE(item->'files','[]'::JSONB),COALESCE(item->'test_evidence','[]'::JSONB),'not_requested','not_requested');
+ FOR dep IN SELECT jsonb_array_elements_text(COALESCE(item->'dependencies','[]'::JSONB)) LOOP
+ IF NOT EXISTS(SELECT 1 FROM public.engineering_changes WHERE change_id=dep) THEN RAISE EXCEPTION 'missing dependency % for %',dep,cid USING ERRCODE='23503'; END IF;
+ INSERT INTO public.engineering_change_dependencies(change_id,depends_on_change_id) VALUES(cid,dep);
+ END LOOP;
+ INSERT INTO public.engineering_change_events(change_id,event_type,actor,new_status,details) VALUES(cid,'created',session_user,item->>'status',jsonb_build_object('source','authorized-seed-import'));
+ inserted:=array_append(inserted,cid); n:=n+1;
+ END LOOP;
+ count:=n; RETURN NEXT;
+END $$;
+CREATE OR REPLACE FUNCTION public.engineering_queue_protect_approval_columns()
+RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog,public AS $$
+BEGIN
+ IF TG_OP='INSERT' THEN
+ IF session_user IN ('tars_queue_agent_login','tars_queue_operator_login') THEN
+ IF NEW.status<>'proposed' OR NEW.hg1_status<>'not_requested' OR NEW.hg1_approval_ref IS NOT NULL OR NEW.hg2_status<>'not_requested' OR NEW.hg2_approval_ref IS NOT NULL OR NEW.execution_approval_ref IS NOT NULL OR NEW.execution_approval_actor IS NOT NULL OR NEW.claimed_by IS NOT NULL OR NEW.claim_expires_at IS NOT NULL THEN RAISE EXCEPTION 'runtime inserts must be proposed and unapproved' USING ERRCODE='42501'; END IF;
+ ELSIF session_user='tars_queue_seed_login' THEN
+ IF NEW.status NOT IN ('proposed','completed') OR NEW.hg1_status<>'not_requested' OR NEW.hg1_approval_ref IS NOT NULL OR NEW.hg2_status<>'not_requested' OR NEW.hg2_approval_ref IS NOT NULL OR NEW.execution_approval_ref IS NOT NULL OR NEW.execution_approval_actor IS NOT NULL OR NEW.claimed_by IS NOT NULL OR NEW.claim_expires_at IS NOT NULL THEN RAISE EXCEPTION 'seed imports must be proposed/completed and unapproved' USING ERRCODE='42501'; END IF;
+ ELSE RAISE EXCEPTION 'only dedicated runtime or seed login may insert queue items' USING ERRCODE='42501'; END IF;
+ ELSIF (NEW.status IS DISTINCT FROM OLD.status OR NEW.claimed_by IS DISTINCT FROM OLD.claimed_by OR NEW.claim_expires_at IS DISTINCT FROM OLD.claim_expires_at OR NEW.hg1_status IS DISTINCT FROM OLD.hg1_status OR NEW.hg1_approval_ref IS DISTINCT FROM OLD.hg1_approval_ref OR NEW.hg2_status IS DISTINCT FROM OLD.hg2_status OR NEW.hg2_approval_ref IS DISTINCT FROM OLD.hg2_approval_ref OR NEW.execution_approval_ref IS DISTINCT FROM OLD.execution_approval_ref OR NEW.execution_approval_actor IS DISTINCT FROM OLD.execution_approval_actor) AND current_user<>(SELECT tableowner FROM pg_catalog.pg_tables WHERE schemaname='public' AND tablename='engineering_changes') THEN RAISE EXCEPTION 'status, claim and approval fields require queue authority functions' USING ERRCODE='42501';
+ END IF;
+ RETURN NEW;
+END; $$;
+CREATE TRIGGER engineering_queue_protect_approval_columns_trigger BEFORE INSERT OR UPDATE ON public.engineering_changes FOR EACH ROW EXECUTE FUNCTION public.engineering_queue_protect_approval_columns();
+REVOKE EXECUTE ON FUNCTION public.engineering_queue_create_change(TEXT,TEXT,TEXT,TEXT,TEXT,TEXT,TEXT,TEXT,JSONB,JSONB,TEXT[]) FROM PUBLIC,tars_queue_agent,tars_queue_operator,tars_queue_seed,tars_queue_agent_login,tars_queue_operator_login,tars_queue_seed_login;
+REVOKE EXECUTE ON FUNCTION public.engineering_queue_issue_execution_grant(TEXT,TEXT,TEXT,TIMESTAMPTZ,TEXT),public.engineering_queue_revoke_execution_grant(TEXT,TEXT),public.engineering_queue_authorize_ready(TEXT,BIGINT,TEXT,TEXT) FROM PUBLIC,tars_queue_agent,tars_queue_operator,tars_queue_seed,tars_queue_agent_login,tars_queue_operator_login,tars_queue_seed_login;
+REVOKE EXECUTE ON FUNCTION public.engineering_queue_claim(TEXT,TEXT,INTEGER),public.engineering_queue_attach_evidence(TEXT,TEXT,TEXT,TEXT,TEXT,TEXT),public.engineering_queue_agent_status(TEXT,TEXT,BIGINT,TEXT),public.engineering_queue_submit_for_review(TEXT,BIGINT) FROM PUBLIC,tars_queue_agent,tars_queue_operator,tars_queue_seed,tars_queue_agent_login,tars_queue_operator_login,tars_queue_seed_login;
+REVOKE EXECUTE ON FUNCTION public.engineering_queue_seed_import(JSONB),public.engineering_queue_protect_approval_columns() FROM PUBLIC,tars_queue_agent,tars_queue_operator,tars_queue_seed,tars_queue_agent_login,tars_queue_operator_login,tars_queue_seed_login;
+GRANT EXECUTE ON FUNCTION public.engineering_queue_create_change(TEXT,TEXT,TEXT,TEXT,TEXT,TEXT,TEXT,TEXT,JSONB,JSONB,TEXT[]),public.engineering_queue_claim(TEXT,TEXT,INTEGER),public.engineering_queue_attach_evidence(TEXT,TEXT,TEXT,TEXT,TEXT,TEXT),public.engineering_queue_agent_status(TEXT,TEXT,BIGINT,TEXT),public.engineering_queue_submit_for_review(TEXT,BIGINT) TO tars_queue_agent;
+GRANT EXECUTE ON FUNCTION public.engineering_queue_issue_execution_grant(TEXT,TEXT,TEXT,TIMESTAMPTZ,TEXT),public.engineering_queue_revoke_execution_grant(TEXT,TEXT),public.engineering_queue_authorize_ready(TEXT,BIGINT,TEXT,TEXT) TO tars_queue_operator;
+GRANT EXECUTE ON FUNCTION public.engineering_queue_seed_import(JSONB) TO tars_queue_seed;
+GRANT SELECT ON public.engineering_changes,public.engineering_change_dependencies,public.engineering_change_evidence,public.engineering_change_events,public.engineering_execution_grants,public.engineering_execution_grant_events TO tars_queue_agent,tars_queue_operator;
+DO $$ BEGIN
+ IF NOT has_table_privilege('tars_queue_agent_login','public.engineering_changes','SELECT') OR NOT has_table_privilege('tars_queue_operator_login','public.engineering_changes','SELECT') THEN RAISE EXCEPTION 'runtime login SELECT grant verification failed'; END IF;
+END $$;
+DO $$ DECLARE obj text; col_name text; BEGIN
+ FOREACH obj IN ARRAY ARRAY['engineering_change_evidence_evidence_id_seq','engineering_change_events_event_id_seq','engineering_execution_grant_events_event_id_seq'] LOOP
+ EXECUTE format('REVOKE ALL PRIVILEGES ON SEQUENCE public.%I FROM PUBLIC',obj);
+ END LOOP;
+ FOREACH obj IN ARRAY ARRAY['engineering_changes','engineering_change_dependencies','engineering_change_evidence','engineering_change_events','engineering_execution_grants','engineering_execution_grant_events'] LOOP
+ EXECUTE format('REVOKE SELECT ON TABLE public.%I FROM PUBLIC',obj);
+ FOR col_name IN SELECT a.attname FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relname=obj AND a.attnum>0 AND NOT a.attisdropped LOOP
+ EXECUTE format('REVOKE SELECT (%I) ON TABLE public.%I FROM PUBLIC',col_name,obj);
+ END LOOP;
+ END LOOP;
+END $$;
+DO $$ DECLARE n integer; BEGIN
+ IF EXISTS(SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace nsp ON nsp.oid=c.relnamespace CROSS JOIN LATERAL aclexplode(COALESCE(c.relacl,acldefault('S',c.relowner))) a WHERE nsp.nspname='public' AND c.relname=ANY(ARRAY['engineering_change_evidence_evidence_id_seq','engineering_change_events_event_id_seq','engineering_execution_grant_events_event_id_seq']) AND a.grantee=0 AND a.privilege_type IN ('USAGE','SELECT','UPDATE')) THEN RAISE EXCEPTION 'PUBLIC has queue sequence privileges'; END IF;
+ IF EXISTS(SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace nsp ON nsp.oid=c.relnamespace CROSS JOIN LATERAL aclexplode(COALESCE(c.relacl,acldefault('r',c.relowner))) a WHERE nsp.nspname='public' AND c.relname=ANY(ARRAY['engineering_changes','engineering_change_dependencies','engineering_change_evidence','engineering_change_events','engineering_execution_grants','engineering_execution_grant_events']) AND a.grantee=0 AND a.privilege_type='SELECT') OR EXISTS(SELECT 1 FROM pg_catalog.pg_attribute att JOIN pg_catalog.pg_class c ON c.oid=att.attrelid JOIN pg_catalog.pg_namespace nsp ON nsp.oid=c.relnamespace CROSS JOIN LATERAL aclexplode(att.attacl) a WHERE nsp.nspname='public' AND c.relname=ANY(ARRAY['engineering_changes','engineering_change_dependencies','engineering_change_evidence','engineering_change_events','engineering_execution_grants','engineering_execution_grant_events']) AND a.grantee=0 AND a.privilege_type='SELECT') THEN RAISE EXCEPTION 'PUBLIC SELECT remains on queue table'; END IF;
+END $$;
+DO $$ DECLARE role_name text; obj text; col_name text; BEGIN
+ FOREACH role_name IN ARRAY ARRAY['tars_queue_agent','tars_queue_operator','tars_queue_seed','tars_queue_agent_login','tars_queue_operator_login','tars_queue_seed_login'] LOOP
+ FOREACH obj IN ARRAY ARRAY['engineering_changes','engineering_change_dependencies','engineering_change_evidence','engineering_change_events','engineering_execution_grants','engineering_execution_grant_events'] LOOP
+ EXECUTE format('REVOKE INSERT,UPDATE,DELETE,TRUNCATE,REFERENCES,TRIGGER,SELECT ON TABLE public.%I FROM PUBLIC',obj);
+ EXECUTE format('REVOKE INSERT,UPDATE,DELETE,TRUNCATE,REFERENCES,TRIGGER ON TABLE public.%I FROM %I',obj,role_name);
+ FOR col_name IN SELECT a.attname FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relname=obj AND a.attnum>0 AND NOT a.attisdropped LOOP
+ EXECUTE format('REVOKE INSERT (%1$I),UPDATE (%1$I),REFERENCES (%1$I) ON TABLE public.%2$I FROM PUBLIC',col_name,obj);
+ EXECUTE format('REVOKE SELECT (%1$I) ON TABLE public.%2$I FROM PUBLIC',col_name,obj);
+ EXECUTE format('REVOKE INSERT (%1$I),UPDATE (%1$I),REFERENCES (%1$I) ON TABLE public.%2$I FROM %3$I',col_name,obj,role_name);
+ END LOOP;
+ END LOOP;
+ END LOOP;
+END $$;
+DO $$ DECLARE n integer; BEGIN
+ IF EXISTS(SELECT 1 FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace x ON x.oid=c.relnamespace CROSS JOIN (VALUES ('tars_queue_agent'),('tars_queue_operator'),('tars_queue_seed'),('tars_queue_agent_login'),('tars_queue_operator_login'),('tars_queue_seed_login')) AS roles(role_name) WHERE x.nspname='public' AND c.relname=ANY(ARRAY['engineering_changes','engineering_change_dependencies','engineering_change_evidence','engineering_change_events','engineering_execution_grants','engineering_execution_grant_events']) AND a.attnum>0 AND NOT a.attisdropped AND (has_column_privilege(roles.role_name,c.oid,a.attnum,'INSERT') OR has_column_privilege(roles.role_name,c.oid,a.attnum,'UPDATE') OR has_column_privilege(roles.role_name,c.oid,a.attnum,'REFERENCES'))) THEN RAISE EXCEPTION 'column-level runtime DML privileges remain'; END IF;
+END $$;
+COMMIT;
diff --git a/services/tars-engineering-queue-dev/operator_runner/b3b_runtime.py b/services/tars-engineering-queue-dev/operator_runner/b3b_runtime.py
new file mode 100644
index 0000000..51c7184
--- /dev/null
+++ b/services/tars-engineering-queue-dev/operator_runner/b3b_runtime.py
@@ -0,0 +1,69 @@
+"""Typed B3-B bindings for explicitly injected authorized DEV operators.
+
+No shell/SQL/Docker APIs, service control, or secret bytes are implemented here.
+A concrete connector must be provided by an independently authorized operator.
+"""
+from __future__ import annotations
+from dataclasses import dataclass
+from typing import Any, Protocol
+from .actions import Actions, MIGRATION_ORDER
+from .contracts import CloneIdentity, Hold, Result
+
+@dataclass(frozen=True)
+class CredentialReceipt:
+ credential_ref: str
+ agent_subject: str
+ operator_subject: str
+
+class QueueOperatorConnector(Protocol):
+ def clone_identity(self) -> CloneIdentity: ...
+ def schema_summary(self) -> dict[str, Any]: ...
+ def apply_queue_bootstrap(self, migration_ids: tuple[str, ...], sha256s: tuple[str, ...]) -> dict[str, Any]: ...
+ def provision_queue_agent_credentials(self) -> CredentialReceipt: ...
+ def start_internal_queue_api(self, *, bind_host: str, port: int) -> dict[str, Any]: ...
+ def run_granted_smoke(self, *, change_id: str, grant_ref: str) -> dict[str, Any]: ...
+ def read_queue_evidence(self, *, change_id: str) -> dict[str, Any]: ...
+
+@dataclass
+class B3BIdentityProvider:
+ connector: QueueOperatorConnector
+ def read_identity(self) -> CloneIdentity:
+ value=self.connector.clone_identity()
+ if not isinstance(value,CloneIdentity): raise Hold("invalid clone identity response")
+ return value
+ def read_schema_summary(self): return self.connector.schema_summary()
+
+@dataclass
+class B3BQueueActions(Actions):
+ connector: QueueOperatorConnector | None = None
+ expected_artifact_hashes: tuple[str,str,str] | None = None
+ def __post_init__(self):
+ if self.connector is None: raise Hold("authorized Queue operator connector required")
+ self.identity_provider=B3BIdentityProvider(self.connector)
+ def _connector(self):
+ if self.connector is None: raise Hold("authorized Queue operator connector unavailable")
+ return self.connector
+ def bootstrap_apply(self,artifact_hashes):
+ self.identity_verify()
+ if self.expected_artifact_hashes is None or tuple(artifact_hashes)!=self.expected_artifact_hashes: raise Hold("bootstrap hashes are not independently pinned")
+ receipt=self._connector().apply_queue_bootstrap(MIGRATION_ORDER,self.expected_artifact_hashes)
+ if not isinstance(receipt,dict) or set(receipt)-{"migration_ids","status","evidence_ref"} or tuple(receipt.get("migration_ids",()))!=MIGRATION_ORDER or receipt.get("status")!="applied": raise Hold("bootstrap receipt failed verification")
+ return Result("operator","queue.bootstrap.apply","applied",receipt.get("evidence_ref"),{"migration_ids":MIGRATION_ORDER})
+ def credentials_provision(self):
+ self.identity_verify(); receipt=self._connector().provision_queue_agent_credentials()
+ if not isinstance(receipt,CredentialReceipt) or not all((receipt.credential_ref,receipt.agent_subject,receipt.operator_subject)) or receipt.agent_subject==receipt.operator_subject: raise Hold("credential backend must return opaque reference and distinct subjects only")
+ return Result("operator","queue.credentials.provision","provisioned",receipt.credential_ref,{"agent_subject":receipt.agent_subject,"operator_subject":receipt.operator_subject})
+ def api_start(self):
+ self.identity_verify(); receipt=self._connector().start_internal_queue_api(bind_host="172.25.0.3",port=8904)
+ if not isinstance(receipt,dict) or set(receipt)-{"service","bind_host","port","status"} or receipt!={"service":"tars-engineering-queue-dev","bind_host":"172.25.0.3","port":8904,"status":"running"}: raise Hold("service did not confirm exact private DEV target")
+ return Result("operator","queue.api.start","running",details={"service":receipt["service"],"bind_host":receipt["bind_host"],"port":receipt["port"]})
+ def smoke_execute(self,change_id,grant_ref):
+ self.identity_verify()
+ if not change_id or not grant_ref: raise Hold("synthetic task and independent grant reference required")
+ receipt=self._connector().run_granted_smoke(change_id=change_id,grant_ref=grant_ref)
+ if not isinstance(receipt,dict) or set(receipt)-{"change_id","status","evidence_ref"} or receipt.get("change_id")!=change_id or receipt.get("status") not in {"validated","blocked"} or not receipt.get("evidence_ref"): raise Hold("worker receipt failed change/status/evidence binding")
+ return Result("operator","queue.smoke.execute",receipt["status"],receipt["evidence_ref"],{"change_id":change_id})
+ def evidence_read(self,change_id):
+ self.identity_verify(); receipt=self._connector().read_queue_evidence(change_id=change_id)
+ if not isinstance(receipt,dict) or set(receipt)-{"change","evidence","grant_metadata"} or not isinstance(receipt.get("change"),dict) or receipt["change"].get("change_id")!=change_id or not isinstance(receipt.get("evidence"),list): raise Hold("evidence result failed validation")
+ return Result("read-only","queue.evidence.read","verified",details=receipt)
diff --git a/services/tars-engineering-queue-dev/operator_runner/test_b3b_runtime.py b/services/tars-engineering-queue-dev/operator_runner/test_b3b_runtime.py
new file mode 100644
index 0000000..3e4a161
--- /dev/null
+++ b/services/tars-engineering-queue-dev/operator_runner/test_b3b_runtime.py
@@ -0,0 +1,55 @@
+from __future__ import annotations
+import unittest
+from services.tars_engineering_queue_dev.operator_runner.b3b_runtime import B3BQueueActions, CredentialReceipt
+from services.tars_engineering_queue_dev.operator_runner.actions import MIGRATION_ORDER
+from services.tars_engineering_queue_dev.operator_runner.contracts import CloneIdentity, Hold
+from services.tars_engineering_queue_dev.operator_runner.identity import IdentityManifest
+SID = "7709241176253177900"
+def manifest(): return IdentityManifest(SID,"tars_queue_itest","tars_queue_operator_login","tars_queue_operator_login","172.25.0.2",5432,"172.25.0.3",16,"tars_queue_itest")
+def identity(): return CloneIdentity(SID,"tars_queue_itest","tars_queue_operator_login","tars_queue_operator_login","172.25.0.2",5432,"172.25.0.3",16,"tars_queue_itest")
+class FakeConnector:
+ def __init__(self): self.calls=[]
+ def clone_identity(self): self.calls.append("identity"); return identity()
+ def schema_summary(self): self.calls.append("schema"); return {"migration_ids":list(MIGRATION_ORDER),"tables":6,"checks":["fixture"]}
+ def apply_queue_bootstrap(self,migration_ids,sha256s): self.calls.append(("bootstrap",migration_ids,sha256s)); return {"migration_ids":list(migration_ids),"status":"applied","evidence_ref":"audit://fake"}
+ def provision_queue_agent_credentials(self): self.calls.append("credentials"); return CredentialReceipt("secretref://fake-agent","queue-agent","queue-operator")
+ def start_internal_queue_api(self,*,bind_host,port): self.calls.append(("start",bind_host,port)); return {"service":"tars-engineering-queue-dev","bind_host":bind_host,"port":port,"status":"running"}
+ def run_granted_smoke(self,*,change_id,grant_ref): self.calls.append(("smoke",change_id,grant_ref)); return {"change_id":change_id,"status":"validated","evidence_ref":"evidence://fake"}
+ def read_queue_evidence(self,*,change_id): self.calls.append(("read",change_id)); return {"change":{"change_id":change_id,"status":"validated"},"evidence":[{"result":"pass"}]}
+class RuntimeActionTests(unittest.TestCase):
+ def setUp(self):
+ self.connector=FakeConnector(); self.hashes=("a"*64,"b"*64,"c"*64)
+ self.actions=B3BQueueActions(manifest=manifest(),connector=self.connector,expected_artifact_hashes=self.hashes)
+ def test_clone_and_schema_delegate_to_pinned_identity_provider(self):
+ self.assertEqual(self.actions.identity_verify().status,"verified")
+ self.assertEqual(self.actions.schema_verify().details["tables"],6)
+ def test_bootstrap_fixed_order_and_hashes(self):
+ result=self.actions.bootstrap_apply(self.hashes)
+ self.assertEqual(result.status,"applied"); self.assertEqual(self.connector.calls[-1],("bootstrap",MIGRATION_ORDER,self.hashes))
+ def test_bootstrap_hash_mismatch_fails_before_provider(self):
+ with self.assertRaises(Hold): self.actions.bootstrap_apply(("d"*64,"b"*64,"c"*64))
+ self.assertFalse(any(isinstance(c,tuple) and c[0]=="bootstrap" for c in self.connector.calls))
+ def test_credentials_are_receipt_only_and_subjects_separate(self):
+ result=self.actions.credentials_provision()
+ self.assertNotIn("password",str(result.details).lower()); self.assertEqual(result.evidence_ref,"secretref://fake-agent")
+ def test_overlapping_subjects_hold(self):
+ class Bad(FakeConnector):
+ def provision_queue_agent_credentials(self): return CredentialReceipt("opaque","same","same")
+ with self.assertRaises(Hold): B3BQueueActions(manifest=manifest(),connector=Bad()).credentials_provision()
+ def test_start_pinned_internal_only(self):
+ result=self.actions.api_start(); self.assertEqual((result.details["bind_host"],result.details["port"]),("172.25.0.3",8904))
+ def test_wrong_service_target_holds(self):
+ class Bad(FakeConnector):
+ def start_internal_queue_api(self,**kw): return {"service":"live","bind_host":"0.0.0.0","port":80,"status":"running"}
+ with self.assertRaises(Hold): B3BQueueActions(manifest=manifest(),connector=Bad()).api_start()
+ def test_smoke_requires_grant_reference_and_returns_evidence(self):
+ result=self.actions.smoke_execute("EQ-SYNTH-01","EG-operator")
+ self.assertEqual(result.status,"validated"); self.assertEqual(self.connector.calls[-1],("smoke","EQ-SYNTH-01","EG-operator"))
+ def test_evidence_is_change_bound(self):
+ self.assertEqual(self.actions.evidence_read("EQ-SYNTH-01").details["change"]["change_id"],"EQ-SYNTH-01")
+ class Bad(FakeConnector):
+ def read_queue_evidence(self,*,change_id): return {"change":{"change_id":"OTHER"},"evidence":[]}
+ with self.assertRaises(Hold): B3BQueueActions(manifest=manifest(),connector=Bad()).evidence_read("EQ-SYNTH-01")
+ def test_missing_connector_holds(self):
+ with self.assertRaises(Hold): B3BQueueActions(manifest=manifest())
+if __name__=="__main__": unittest.main()
diff --git a/services/tars-engineering-queue-dev/runtime_readiness.py b/services/tars-engineering-queue-dev/runtime_readiness.py
new file mode 100644
index 0000000..1f9ab12
--- /dev/null
+++ b/services/tars-engineering-queue-dev/runtime_readiness.py
@@ -0,0 +1,134 @@
+"""Read-only readiness gate for the pre-existing isolated Queue database."""
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any, Callable
+
+from .config import AGENT_LOGIN, CLONE_DATABASE, CLONE_HOST, CLONE_PORT, OPERATOR_LOGIN, validate_clone_dsn
+
+ORIGINAL_SYSTEM_ID = "7708052904864636966"
+EXPECTED_CLIENT_ADDR = "172.25.0.3"
+REQUIRED_TABLES = frozenset({
+ "engineering_changes",
+ "engineering_change_dependencies",
+ "engineering_execution_grants",
+ "engineering_change_evidence",
+})
+REQUIRED_FUNCTIONS = frozenset({
+ "engineering_queue_create_change",
+ "engineering_queue_issue_execution_grant",
+ "engineering_queue_revoke_execution_grant",
+ "engineering_queue_claim",
+ "engineering_queue_authorize_ready",
+ "engineering_queue_agent_status",
+ "engineering_queue_attach_evidence",
+ "engineering_queue_submit_for_review",
+})
+
+
+class QueueReadinessError(RuntimeError):
+ """Fail-closed refusal when the configured runtime is not the pinned clone."""
+
+
+@dataclass(frozen=True)
+class DatabaseIdentity:
+ database: str
+ session_user: str
+ current_user: str
+ server_addr: str
+ server_port: int
+ client_addr: str
+ postgres_major: int
+ system_identifier: str
+ database_owner: str
+ is_superuser: bool
+ can_create_role: bool
+ can_create_database: bool
+ bypasses_rls: bool
+
+
+def _default_connect(dsn: str):
+ import psycopg
+ return psycopg.connect(dsn)
+
+
+def verify_database(dsn: str, expected_user: str, expected_system_id: str,
+ *, connect: Callable[[str], Any] | None = None) -> DatabaseIdentity:
+ """Use only read-only SELECTs; never migrates or changes existing Queue rows."""
+ if expected_user not in {AGENT_LOGIN, OPERATOR_LOGIN}:
+ raise QueueReadinessError("runtime identity is not an approved Queue role")
+ if not expected_system_id.isdigit() or expected_system_id == ORIGINAL_SYSTEM_ID:
+ raise QueueReadinessError("an independent non-original PostgreSQL system id is required")
+ try:
+ validate_clone_dsn(dsn, expected_user)
+ from psycopg.conninfo import conninfo_to_dict
+ conninfo = conninfo_to_dict(dsn)
+ if conninfo.get("password") or not conninfo.get("passfile"):
+ raise QueueReadinessError("Queue credentials must use a protected role-specific passfile")
+ if conninfo.get("passfile").startswith("/dev/"):
+ raise QueueReadinessError("credential passfile path is invalid")
+ import os, stat
+ credential = os.stat(conninfo["passfile"], follow_symlinks=False)
+ if (not stat.S_ISREG(credential.st_mode) or credential.st_mode & 0o077
+ or credential.st_uid != os.geteuid()):
+ raise QueueReadinessError("Queue credential passfile is not private to the runtime identity")
+ except QueueReadinessError:
+ raise
+ except Exception as exc:
+ raise QueueReadinessError("Queue DSN or protected credential source is invalid") from exc
+
+ open_connection = connect or _default_connect
+ identity_sql = """SELECT current_database(), session_user::text, current_user::text,
+ inet_server_addr()::text, inet_server_port(), inet_client_addr()::text,
+ current_setting('server_version_num')::integer / 10000,
+ (SELECT system_identifier::text FROM pg_control_system()),
+ (SELECT pg_get_userbyid(datdba) FROM pg_database WHERE datname=current_database()),
+ r.rolsuper, r.rolcreaterole, r.rolcreatedb, r.rolbypassrls
+ FROM pg_roles AS r WHERE r.rolname=session_user"""
+ try:
+ with open_connection(dsn) as conn:
+ with conn.cursor() as cur:
+ cur.execute(identity_sql)
+ row = cur.fetchone()
+ if row is None or len(row) != 13:
+ raise QueueReadinessError("PostgreSQL identity probe returned no complete identity")
+ identity = DatabaseIdentity(*row)
+ if (identity.database != CLONE_DATABASE
+ or identity.session_user != expected_user
+ or identity.current_user != expected_user
+ or identity.server_addr != CLONE_HOST
+ or identity.server_port != int(CLONE_PORT)
+ or identity.client_addr != EXPECTED_CLIENT_ADDR
+ or identity.system_identifier != expected_system_id
+ or identity.database_owner != CLONE_DATABASE
+ or identity.is_superuser or identity.can_create_role
+ or identity.can_create_database or identity.bypasses_rls):
+ raise QueueReadinessError("PostgreSQL identity differs from the pinned isolated Queue clone")
+ cur.execute("""SELECT c.relname
+ FROM pg_class AS c JOIN pg_namespace AS n ON n.oid=c.relnamespace
+ WHERE n.nspname='public' AND c.relkind IN ('r','p')
+ AND c.relname = ANY(%s)""", (sorted(REQUIRED_TABLES),))
+ tables = {r[0] for r in cur.fetchall()}
+ cur.execute("""SELECT p.proname
+ FROM pg_proc AS p JOIN pg_namespace AS n ON n.oid=p.pronamespace
+ WHERE n.nspname='public' AND p.proname = ANY(%s)""", (sorted(REQUIRED_FUNCTIONS),))
+ functions = {r[0] for r in cur.fetchall()}
+ if tables != REQUIRED_TABLES or functions != REQUIRED_FUNCTIONS:
+ raise QueueReadinessError("required Engineering Queue schema objects are missing")
+ return identity
+ except QueueReadinessError:
+ raise
+ except Exception as exc:
+ # Do not return connection strings, SQL details, or database error bodies.
+ raise QueueReadinessError("read-only Queue database readiness probe failed") from exc
+
+
+def verify_runtime_databases(agent_dsn: str, operator_dsn: str, expected_system_id: str,
+ *, connect: Callable[[str], Any] | None = None) -> dict[str, str]:
+ if not agent_dsn or not operator_dsn or agent_dsn == operator_dsn:
+ raise QueueReadinessError("separate Agent and Operator DSNs are required")
+ agent = verify_database(agent_dsn, AGENT_LOGIN, expected_system_id, connect=connect)
+ operator = verify_database(operator_dsn, OPERATOR_LOGIN, expected_system_id, connect=connect)
+ return {"database": CLONE_DATABASE, "system_identifier": expected_system_id,
+ "agent_login": agent.session_user, "operator_login": operator.session_user,
+ "schema": "ready"}
diff --git a/services/tars-engineering-queue-dev/test_api_worker.py b/services/tars-engineering-queue-dev/test_api_worker.py
new file mode 100644
index 0000000..0e3259c
--- /dev/null
+++ b/services/tars-engineering-queue-dev/test_api_worker.py
@@ -0,0 +1,113 @@
+from __future__ import annotations
+import unittest
+from datetime import datetime, timedelta, timezone
+from services.tars_engineering_queue_dev.api_worker import (
+ API_BASE, ACTION, HermesQueueWorker, QueueAPIClient, QueueAPIError, _task_action,
+)
+
+
+class FakeQueue:
+ def __init__(self, record=None, grants=None):
+ self.record = record or {
+ "change_id": "EQ-B3A-FAKE-01", "repository": "tars-platform", "status": "ready",
+ "description": '{"action":"queue.self_test.v1","payload":{"label":"offline-roundtrip"}}',
+ }
+ expiry = (datetime.now(timezone.utc) + timedelta(minutes=5)).isoformat()
+ self.grants = grants if grants is not None else [{
+ "grant_id": "EG-OPERATOR-TEST", "scope": "execute", "expires_at": expiry,
+ "revoked_at": None, "issuer": "independent-operator",
+ }]
+ self.calls = []
+ self.version = 1
+
+ def list_ready(self):
+ self.calls.append(("list_ready",))
+ return [self.record]
+ def get(self, cid):
+ self.calls.append(("get", cid))
+ return self.record
+ def list_grants(self, cid):
+ self.calls.append(("list_grants", cid))
+ return self.grants
+ def claim(self, cid, grant):
+ self.calls.append(("claim", cid, grant))
+ self.version = 2
+ return {"change_id": cid, "status": "claimed", "version": self.version}
+ def update_status(self, cid, status, version, reason):
+ self.calls.append(("status", cid, status, version, reason))
+ self.version += 1
+ return {"change_id": cid, "status": status, "version": self.version}
+ def attach_evidence(self, cid, evidence):
+ self.calls.append(("evidence", cid, evidence))
+ return {"evidence_id": 42}
+
+
+class APIWorkerTests(unittest.TestCase):
+ def test_full_fake_roundtrip_claim_execute_status_evidence_readable(self):
+ queue = FakeQueue()
+ executor_calls = []
+ def executor(payload):
+ executor_calls.append(payload)
+ return {"result": "pass", "label": payload["label"]}
+ worker = HermesQueueWorker(queue, {ACTION: executor})
+ result = worker.run_once()
+ self.assertEqual(result["change"]["status"], "validated")
+ self.assertEqual(result["evidence"]["evidence_id"], 42)
+ self.assertEqual(executor_calls, [{"label": "offline-roundtrip"}])
+ self.assertEqual([call[0] for call in queue.calls], [
+ "list_ready", "list_grants", "claim", "status", "evidence", "status"
+ ])
+ self.assertEqual(queue.calls[2], ("claim", "EQ-B3A-FAKE-01", "EG-OPERATOR-TEST"))
+ self.assertEqual(queue.calls[3][2], "in_progress")
+ self.assertEqual(queue.calls[-1][2], "validated")
+ self.assertEqual(queue.calls[4][2]["result"], "pass")
+ self.assertIn("external review", queue.calls[-1][-1])
+
+ def test_does_not_claim_without_independent_active_grant(self):
+ queue = FakeQueue(grants=[])
+ with self.assertRaises(PermissionError):
+ HermesQueueWorker(queue).run_once()
+ self.assertNotIn("claim", [call[0] for call in queue.calls])
+
+ def test_revoked_and_expired_grants_are_not_used(self):
+ queue = FakeQueue(grants=[
+ {"grant_id": "revoked", "scope": "execute", "expires_at": (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(), "revoked_at": "now"},
+ {"grant_id": "expired", "scope": "execute", "expires_at": (datetime.now(timezone.utc) - timedelta(seconds=1)).isoformat(), "revoked_at": None},
+ ])
+ with self.assertRaises(PermissionError):
+ HermesQueueWorker(queue).run_once()
+
+ def test_unsupported_task_is_left_unclaimed(self):
+ queue = FakeQueue()
+ queue.record["description"] = '{"action":"shell.exec","payload":{"cmd":"echo unsafe"}}'
+ self.assertIsNone(HermesQueueWorker(queue).run_once())
+ self.assertNotIn("claim", [call[0] for call in queue.calls])
+
+ def test_executor_failure_is_evidenced_and_blocked(self):
+ queue = FakeQueue()
+ def fail(_):
+ raise RuntimeError("private failure detail")
+ result = HermesQueueWorker(queue, {ACTION: fail}).run_once()
+ self.assertEqual(result["change"]["status"], "blocked")
+ self.assertEqual(result["error"], "RuntimeError")
+ evidence = [call for call in queue.calls if call[0] == "evidence"][0][2]
+ self.assertEqual(evidence["result"], "fail")
+ self.assertNotIn("private failure detail", evidence["summary"])
+
+ def test_client_pins_internal_api_destination(self):
+ with self.assertRaises(ValueError):
+ QueueAPIClient("test-token", "http://127.0.0.1:8904")
+ with self.assertRaises(ValueError):
+ QueueAPIClient("test-token", "http://172.25.0.3:8904/other")
+ self.assertEqual(QueueAPIClient("test-token").base_url, API_BASE)
+
+ def test_action_envelope_rejects_extra_fields_and_non_json(self):
+ record = {"description": '{"action":"queue.self_test.v1","payload":{},"exec":"x"}'}
+ with self.assertRaises(ValueError):
+ _task_action(record)
+ with self.assertRaises(ValueError):
+ _task_action({"description": "please run whatever is needed"})
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/services/tars-engineering-queue-dev/test_db_wiring.py b/services/tars-engineering-queue-dev/test_db_wiring.py
new file mode 100644
index 0000000..752fcfb
--- /dev/null
+++ b/services/tars-engineering-queue-dev/test_db_wiring.py
@@ -0,0 +1,81 @@
+from __future__ import annotations
+import os
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+from fastapi.testclient import TestClient
+from services.tars_engineering_queue_dev import launcher
+from services.tars_engineering_queue_dev.core import api as core_api
+from services.tars_engineering_queue_dev.runtime_readiness import DatabaseIdentity, QueueReadinessError, verify_runtime_databases
+SYSTEM_ID="7709241176253177900"
+def _private_file():
+ f=tempfile.NamedTemporaryFile(delete=False);f.close();os.chmod(f.name,0o600);return Path(f.name)
+def config():
+ runtime,agent_pass,operator_pass=_private_file(),_private_file(),_private_file()
+ env={"TARS_QUEUE_RUNTIME_ENV_FILE":str(runtime),"TARS_QUEUE_AGENT_DSN":f"host=172.25.0.2 port=5432 dbname=tars_queue_itest user=tars_queue_agent_login passfile={agent_pass}","TARS_QUEUE_OPERATOR_DSN":f"host=172.25.0.2 port=5432 dbname=tars_queue_itest user=tars_queue_operator_login passfile={operator_pass}","TARS_QUEUE_EXPECTED_SYSTEM_ID":SYSTEM_ID,"TARS_QUEUE_BIND_HOST":"172.25.0.3","TARS_QUEUE_DEV_OPERATOR_KEY":"operator-test-only","TARS_QUEUE_DEV_OPERATOR_ID":"operator-test-id","TARS_QUEUE_AGENT_COUNT":"1","TARS_QUEUE_AGENT_1_KEY":"agent-test-only","TARS_QUEUE_AGENT_1_ID":"agent-worker-test"}
+ return [runtime,agent_pass,operator_pass],env
+class SpyStore:
+ def __init__(self,dsn):self.dsn=dsn;self.calls=[]
+ def create(self,*a):self.calls.append("create");return {"change_id":"EQ-X"}
+ def create_grant(self,*a):self.calls.append("create_grant");return {"grant_id":"EG-X"}
+ def update_status(self,*a,**k):self.calls.append(("status",a[2]));return {"status":a[2],"version":2}
+ def claim(self,*a):self.calls.append("claim");return {"status":"claimed"}
+class ReadinessTests(unittest.TestCase):
+ def test_runtime_identity_gate_accepts_both_expected_logins(self):
+ seen=[]
+ def connect(dsn):
+ from psycopg.conninfo import conninfo_to_dict
+ user=conninfo_to_dict(dsn)["user"];seen.append(user)
+ from services.tars_engineering_queue_dev.runtime_readiness import REQUIRED_TABLES,REQUIRED_FUNCTIONS
+ class Cursor:
+ def __enter__(self):return self
+ def __exit__(self,*a):return None
+ def __init__(self):self.n=0
+ def execute(self,*a):self.n+=1
+ def fetchone(self):return ("tars_queue_itest",user,user,"172.25.0.2",5432,"172.25.0.3",16,SYSTEM_ID,"tars_queue_itest",False,False,False,False)
+ def fetchall(self):return [(x,) for x in sorted(REQUIRED_TABLES if self.n==2 else REQUIRED_FUNCTIONS)]
+ class Conn:
+ def __enter__(self):return self
+ def __exit__(self,*a):return None
+ def cursor(self):return Cursor()
+ return Conn()
+ paths,env=config()
+ try:
+ result=verify_runtime_databases(env["TARS_QUEUE_AGENT_DSN"],env["TARS_QUEUE_OPERATOR_DSN"],SYSTEM_ID,connect=connect)
+ self.assertEqual(seen,["tars_queue_agent_login","tars_queue_operator_login"]);self.assertEqual(result["schema"],"ready")
+ finally:
+ for p in paths:p.unlink(missing_ok=True)
+ def test_runtime_identity_rejects_original(self):
+ paths,env=config()
+ try:
+ with self.assertRaises(QueueReadinessError):verify_runtime_databases(env["TARS_QUEUE_AGENT_DSN"],env["TARS_QUEUE_OPERATOR_DSN"],"7708052904864636966",connect=lambda _:None)
+ finally:
+ for p in paths:p.unlink(missing_ok=True)
+class WiringTests(unittest.TestCase):
+ def test_launcher_readiness_precedes_stores(self):
+ paths,env=config();stores=[]
+ def factory(dsn):x=SpyStore(dsn);stores.append(x);return x
+ try:
+ with patch.dict(os.environ,env,clear=True),patch.object(launcher,"verify_runtime_databases",return_value={"schema":"ready"}) as ready,patch.object(launcher,"_store",side_effect=factory):app=launcher.build_app()
+ ready.assert_called_once_with(env["TARS_QUEUE_AGENT_DSN"],env["TARS_QUEUE_OPERATOR_DSN"],SYSTEM_ID);self.assertIs(app.state.agent_queue,stores[0]);self.assertIs(app.state.operator_queue,stores[1])
+ finally:
+ for p in paths:p.unlink(missing_ok=True)
+ def test_launcher_fails_closed_on_identity_error(self):
+ paths,env=config()
+ try:
+ with patch.dict(os.environ,env,clear=True),patch.object(launcher,"verify_runtime_databases",side_effect=QueueReadinessError("blocked")),patch.object(launcher,"_store") as store:
+ with self.assertRaises(QueueReadinessError):launcher.build_app()
+ store.assert_not_called()
+ finally:
+ for p in paths:p.unlink(missing_ok=True)
+ def test_api_agent_operator_paths_remain_separate(self):
+ a=SpyStore("agent");o=SpyStore("operator");app=core_api.create_app(agent_queue=a,operator_queue=o,agent_api_keys={"a":"agent"},operator_api_key="o",operator_id="operator")
+ with TestClient(app) as c:
+ ah={"Authorization":"Bearer a"};oh={"Authorization":"Bearer o"}
+ self.assertEqual(c.post("/v1/changes",headers=ah,json={"change_id":"EQ-X","title":"x","repository":"tars-platform","owner":"a"}).status_code,201)
+ self.assertEqual(c.post("/v1/execution-grants",headers=oh,json={"change_id":"EQ-X","scope":"execute","ttl_seconds":60,"reason":"test"}).status_code,201)
+ self.assertEqual(c.patch("/v1/changes/EQ-X/status",headers=oh,json={"status":"ready","expected_version":1,"reason":"r","execution_approval_ref":"EG-X"}).status_code,200)
+ self.assertEqual(c.post("/v1/changes/EQ-X/claim",headers=ah,json={"execution_approval_ref":"EG-X"}).status_code,200)
+ self.assertIn("claim",a.calls);self.assertIn("create_grant",o.calls)
+if __name__=="__main__":unittest.main()
diff --git a/services/tars-engineering-queue-dev/test_gpt_mcp_host.py b/services/tars-engineering-queue-dev/test_gpt_mcp_host.py
new file mode 100644
index 0000000..12d7b29
--- /dev/null
+++ b/services/tars-engineering-queue-dev/test_gpt_mcp_host.py
@@ -0,0 +1,35 @@
+"""Offline tests for separate OAuth-protected GPT Queue MCP host assembly."""
+from __future__ import annotations
+import unittest
+from unittest.mock import patch
+from services.tars_engineering_queue_dev.gpt_mcp_host import create_app, REQUIRED_SCOPE, SERVER_NAME
+class FakeFacade:
+ def create(self, task): return {"change_id":task["change_id"],"status":"proposed"}
+ def status(self, cid): return {"change_id":cid,"status":"validated"}
+ def result(self, cid): return {"change":{"change_id":cid,"status":"validated"},"evidence":[]}
+class FakeAnnotations:
+ def __init__(self,**kwargs): self.kwargs=kwargs
+class FakeServer:
+ def __init__(self,*args,**kwargs): self.args=args; self.kwargs=kwargs; self.registered=[]
+ def tool(self,**metadata):
+ def decorate(fn): self.registered.append((metadata,fn)); return fn
+ return decorate
+ def streamable_http_app(self,**kwargs):
+ app=type("FakeASGI",(),{})(); app.state=type("State",(),{})(); app.mount_args=kwargs; return app
+class HostTests(unittest.TestCase):
+ def test_host_is_separate_oauth_resource_server_with_three_tools(self):
+ server_holder=[]
+ def build(*args,**kwargs):
+ s=FakeServer(*args,**kwargs); server_holder.append(s); return s
+ with patch.dict("sys.modules",{"mcp":type("M",(),{})(),"mcp.server":type("S",(),{})(),"mcp.server.auth":type("A",(),{})(),"mcp.server.auth.settings":type("AS",(),{"AuthSettings":FakeAnnotations})(),"mcp.server.mcpserver":type("MS",(),{"MCPServer":build})(),"mcp.server.transport_security":type("TS",(),{"TransportSecuritySettings":FakeAnnotations})(),"mcp.types":type("T",(),{"ToolAnnotations":FakeAnnotations})()}):
+ app=create_app(facade=FakeFacade(),token_verifier=object(),issuer="https://issuer.test",audience="https://queue.test/mcp",allowed_hosts=("queue.test",))
+ server=server_holder[0]
+ self.assertEqual(server.kwargs["name"],SERVER_NAME)
+ self.assertEqual(server.kwargs["auth"].kwargs["required_scopes"],[REQUIRED_SCOPE])
+ self.assertTrue(server.kwargs["auth"].kwargs["validate_token_resource"])
+ self.assertEqual([x[0]["name"] for x in server.registered],["queue_create","queue_status","queue_result"])
+ self.assertEqual(app.mount_args["streamable_http_path"],"/mcp")
+ def test_requires_explicit_oauth_and_hosts(self):
+ with self.assertRaises(ValueError): create_app(facade=FakeFacade(),token_verifier=object(),issuer="",audience="x",allowed_hosts=("x",))
+ with self.assertRaises(ValueError): create_app(facade=FakeFacade(),token_verifier=object(),issuer="i",audience="a",allowed_hosts=())
+if __name__=="__main__": unittest.main()
diff --git a/services/tars-engineering-queue-dev/test_gpt_queue_mcp.py b/services/tars-engineering-queue-dev/test_gpt_queue_mcp.py
new file mode 100644
index 0000000..e84eead
--- /dev/null
+++ b/services/tars-engineering-queue-dev/test_gpt_queue_mcp.py
@@ -0,0 +1,36 @@
+from __future__ import annotations
+import unittest
+from unittest.mock import patch
+from services.tars_engineering_queue_dev.gpt_queue_mcp import GPTQueueFacade, MAX_TASK_BYTES
+
+class FakeClient:
+ def __init__(self, *_a, **_k): self.calls=[]
+ def _request(self, method, path, payload=None):
+ self.calls.append((method,path,payload))
+ if method == "POST": return {"change_id":payload["change_id"],"status":"proposed"}
+ if path.endswith("/evidence"): return [{"evidence_id":7,"result":"pass"}]
+ return {"change_id":path.rsplit("/",1)[-1],"status":"validated"}
+ def get(self,cid):
+ self.calls.append(("GET","/v1/changes/"+cid,None))
+ return {"change_id":cid,"status":"validated"}
+
+class GPTFacadeTests(unittest.TestCase):
+ def setUp(self):
+ p=patch("services.tars_engineering_queue_dev.gpt_queue_mcp.QueueAPIClient",FakeClient)
+ p.start(); self.addCleanup(p.stop); self.facade=GPTQueueFacade("synthetic-test-only")
+ def task(self):
+ return {"change_id":"EQ-GPT-TEST-1","title":"synthetic","description":"{}","repository":"tars-platform","priority":"P2","owner":"gpt"}
+ def test_create_uses_existing_api(self):
+ self.assertEqual(self.facade.create(self.task())["status"],"proposed")
+ self.assertEqual(self.facade.client.calls[0][:2],("POST","/v1/changes"))
+ def test_create_rejects_approval_or_lifecycle_fields(self):
+ for key,value in (("execution_approval_ref","self-grant"),("hg1_status","approved"),("status","ready")):
+ bad=self.task(); bad[key]=value
+ with self.subTest(key=key), self.assertRaises(ValueError): self.facade.create(bad)
+ def test_status_and_result_read_existing_api(self):
+ self.assertEqual(self.facade.status("EQ-GPT-TEST-1")["status"],"validated")
+ self.assertEqual(self.facade.result("EQ-GPT-TEST-1")["evidence"][0]["result"],"pass")
+ def test_create_size_is_bounded(self):
+ with self.assertRaises(ValueError): self.facade.create({"description":"x"*MAX_TASK_BYTES})
+
+if __name__=="__main__": unittest.main()
diff --git a/services/tars-engineering-queue-dev/test_launcher_worker.py b/services/tars-engineering-queue-dev/test_launcher_worker.py
new file mode 100644
index 0000000..31838b3
--- /dev/null
+++ b/services/tars-engineering-queue-dev/test_launcher_worker.py
@@ -0,0 +1,85 @@
+from __future__ import annotations
+import os
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+from services.tars_engineering_queue_dev.config import RUNNER_BIND_HOST, validate_clone_dsn
+from services.tars_engineering_queue_dev.launcher import build_app
+from services.tars_engineering_queue_dev.worker import ACTION, TEST_CHANGE_ID, TEST_TITLE, QueueWorker, build_worker_from_env, execute_allowlisted
+
+SYSTEM_ID = "7709241176253177900"
+
+def _private():
+ h=tempfile.NamedTemporaryFile(delete=False); h.close(); os.chmod(h.name,0o600); return Path(h.name)
+def make_env():
+ runtime, agent_pass, operator_pass = _private(), _private(), _private()
+ env={"TARS_QUEUE_RUNTIME_ENV_FILE":str(runtime),"TARS_QUEUE_AGENT_DSN":f"host=172.25.0.2 port=5432 dbname=tars_queue_itest user=tars_queue_agent_login passfile={agent_pass}","TARS_QUEUE_OPERATOR_DSN":f"host=172.25.0.2 port=5432 dbname=tars_queue_itest user=tars_queue_operator_login passfile={operator_pass}","TARS_QUEUE_EXPECTED_SYSTEM_ID":SYSTEM_ID,"TARS_QUEUE_BIND_HOST":RUNNER_BIND_HOST,"TARS_QUEUE_DEV_OPERATOR_KEY":"operator-test-only","TARS_QUEUE_DEV_OPERATOR_ID":"operator-test-id","TARS_QUEUE_AGENT_COUNT":"1","TARS_QUEUE_AGENT_1_KEY":"agent-test-only","TARS_QUEUE_AGENT_1_ID":"agent-worker-test"}
+ return [runtime,agent_pass,operator_pass],env
+class QueueLauncherWorkerTests(unittest.TestCase):
+ def run_launcher(self,overrides=None):
+ paths,env=make_env();env.update(overrides or {})
+ try:
+ with patch.dict(os.environ,env,clear=True): return build_app()
+ finally:
+ for p in paths:p.unlink(missing_ok=True)
+ def test_launcher_accepts_separate_identities_and_pinned_clone(self):
+ with patch("services.tars_engineering_queue_dev.launcher.verify_runtime_databases",return_value={"schema":"ready"}):
+ app=self.run_launcher()
+ self.assertTrue(callable(app));self.assertEqual(app.state.agent_keys,{"agent-test-only":"agent-worker-test"});self.assertEqual(app.state.operator_id,"operator-test-id")
+ def test_launcher_fails_closed_without_expected_clone_system_id(self):
+ with self.assertRaises(RuntimeError):self.run_launcher({"TARS_QUEUE_EXPECTED_SYSTEM_ID":""})
+ def test_launcher_rejects_wrong_bind_ip(self):
+ with patch("services.tars_engineering_queue_dev.launcher.verify_runtime_databases"):
+ with self.assertRaises(RuntimeError):self.run_launcher({"TARS_QUEUE_BIND_HOST":"127.0.0.1"})
+ def test_launcher_rejects_wrong_database_endpoint_and_identity(self):
+ for name,value in (("TARS_QUEUE_AGENT_DSN","host=172.23.0.2 port=5432 dbname=tars_queue_itest user=tars_queue_agent_login"),("TARS_QUEUE_AGENT_DSN","host=172.25.0.2 port=55432 dbname=tars_queue_itest user=tars_queue_agent_login"),("TARS_QUEUE_AGENT_DSN","host=172.25.0.2 port=5432 dbname=postgres user=tars_queue_agent_login"),("TARS_QUEUE_AGENT_DSN","host=172.25.0.2 port=5432 dbname=tars_queue_itest user=tars_queue_itest"),("TARS_QUEUE_OPERATOR_DSN","host=172.25.0.2 port=5432 dbname=tars_queue_itest user=tars_queue_agent_login")):
+ with self.subTest(dsn_name=name),patch("services.tars_engineering_queue_dev.launcher.verify_runtime_databases"):
+ with self.assertRaises(RuntimeError):self.run_launcher({name:value})
+ def test_dsn_rejects_service_and_hostaddr_overrides(self):
+ for d in ("host=172.25.0.2 port=5432 dbname=tars_queue_itest user=tars_queue_agent_login passfile=/tmp/a service=wrong","host=172.25.0.2 port=5432 dbname=tars_queue_itest user=tars_queue_agent_login passfile=/tmp/a hostaddr=127.0.0.1"):
+ with self.assertRaises(RuntimeError):validate_clone_dsn(d,"tars_queue_agent_login")
+ def test_runtime_config_rejects_permissive_file(self):
+ paths,env=make_env()
+ try:
+ os.chmod(paths[0],0o644)
+ with patch.dict(os.environ,env,clear=True),patch("services.tars_engineering_queue_dev.launcher.verify_runtime_databases"):
+ with self.assertRaises(RuntimeError):build_app()
+ finally:
+ for p in paths:p.unlink(missing_ok=True)
+ def test_launcher_rejects_overlapping_agent_operator_credentials(self):
+ with patch("services.tars_engineering_queue_dev.launcher.verify_runtime_databases"):
+ with self.assertRaises(RuntimeError):self.run_launcher({"TARS_QUEUE_AGENT_1_KEY":"operator-test-only"})
+ def test_worker_accepts_protected_agent_configuration_without_connecting(self):
+ paths,env=make_env()
+ try:
+ with patch.dict(os.environ,env,clear=True),patch("services.tars_engineering_queue_dev.worker.EngineeringQueue") as store:
+ w=build_worker_from_env()
+ self.assertIsNotNone(w);store.assert_called_once()
+ finally:
+ for p in paths:p.unlink(missing_ok=True)
+ def test_worker_rejects_wrong_target_before_store(self):
+ paths,env=make_env();env["TARS_QUEUE_AGENT_DSN"]=env["TARS_QUEUE_AGENT_DSN"].replace("172.25.0.2","172.23.0.2")
+ try:
+ with patch.dict(os.environ,env,clear=True),patch("services.tars_engineering_queue_dev.worker.EngineeringQueue") as store:
+ with self.assertRaises(RuntimeError):build_worker_from_env()
+ store.assert_not_called()
+ finally:
+ for p in paths:p.unlink(missing_ok=True)
+ def test_worker_allowlist_rejects_arbitrary_actions(self):
+ self.assertEqual(execute_allowlisted(ACTION,{"label":"safe"})["result"],"pass")
+ with self.assertRaises(ValueError):execute_allowlisted("shell.exec",{"cmd":"x"})
+ with self.assertRaises(ValueError):execute_allowlisted(ACTION,{"label":"safe","cmd":"x"})
+ def test_existing_smoke_worker_claims_updates_status_and_evidence(self):
+ class Store:
+ def __init__(self):self.calls=[]
+ def get(self,c):self.calls.append(("get",c));return {"status":"ready","change_id":TEST_CHANGE_ID,"title":TEST_TITLE,"repository":"tars-platform"}
+ def claim(self,*a):self.calls.append(("claim",a));return {"status":"claimed","change_id":TEST_CHANGE_ID,"title":TEST_TITLE,"repository":"tars-platform","version":2}
+ def update_status(self,*a):self.calls.append(("status",a));return {"status":a[2],"version":3 if a[2]=="in_progress" else 4}
+ def attach_evidence(self,*a):self.calls.append(("evidence",a));return {"evidence_id":7}
+ s=Store();result=QueueWorker(s).run_once(TEST_CHANGE_ID,"operator-grant-ref")
+ self.assertEqual(result["change"]["status"],"validated");self.assertEqual([c[0] for c in s.calls],["get","claim","status","evidence","status"])
+ self.assertEqual(s.calls[1][1][2],"operator-grant-ref");self.assertEqual(s.calls[3][1][2]["result"],"pass")
+ def test_worker_refuses_unapproved_ticket_id(self):
+ with self.assertRaises(ValueError):QueueWorker(object()).run_once("OTHER-TICKET","grant-ref")
+if __name__=="__main__":unittest.main()
diff --git a/services/tars-engineering-queue-dev/tests/test_queue_store_contract_migration.py b/services/tars-engineering-queue-dev/tests/test_queue_store_contract_migration.py
new file mode 100644
index 0000000..4201ad6
--- /dev/null
+++ b/services/tars-engineering-queue-dev/tests/test_queue_store_contract_migration.py
@@ -0,0 +1,172 @@
+"""Static tests for the proposed queue-store contract migration."""
+from pathlib import Path
+import re
+import unittest
+
+ROOT = Path(__file__).resolve().parents[1]
+STORE = ROOT / "core" / "queue_store.py"
+MIGRATION = ROOT / "migrations" / "004_queue_store_contract.sql"
+TABLES = {"engineering_changes", "engineering_change_dependencies", "engineering_change_evidence", "engineering_change_events", "engineering_execution_grants", "engineering_execution_grant_events"}
+FUNCTIONS = {"engineering_queue_create_change", "engineering_queue_issue_execution_grant", "engineering_queue_revoke_execution_grant", "engineering_queue_authorize_ready", "engineering_queue_claim", "engineering_queue_attach_evidence", "engineering_queue_agent_status", "engineering_queue_submit_for_review"}
+
+class QueueStoreContractTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.store = STORE.read_text()
+ cls.sql = MIGRATION.read_text()
+
+ def test_store_reads_are_narrowly_allowlisted(self):
+ referenced = set(re.findall(r"(?:FROM|JOIN)\s+public\.(engineering_[a-z_]+)", self.store, re.I))
+ tables = {n for n in referenced if not n.startswith("engineering_queue_")}
+ self.assertLessEqual(tables, TABLES)
+ self.assertTrue(TABLES.issubset(set(re.findall(r"engineering_[a-z_]+", self.sql))))
+
+ def test_store_calls_exactly_eight_migrated_functions(self):
+ called = set(re.findall(r"public\.(engineering_queue_[a-z_]+)\s*\(", self.store))
+ defined = set(re.findall(r"CREATE\s+OR\s+REPLACE\s+FUNCTION\s+public\.(engineering_queue_[a-z_]+)\s*\(", self.sql, re.I))
+ self.assertEqual(called, FUNCTIONS)
+ self.assertEqual(defined, FUNCTIONS | {"engineering_queue_seed_import", "engineering_queue_protect_approval_columns"})
+
+ def test_function_permissions_preserve_agent_operator_seed_split(self):
+ agent_match = re.search(r"GRANT EXECUTE ON FUNCTION ([^;]+) TO tars_queue_agent;", self.sql)
+ operator_match = re.search(r"GRANT EXECUTE ON FUNCTION ([^;]+) TO tars_queue_operator;", self.sql)
+ self.assertIsNotNone(agent_match)
+ self.assertIsNotNone(operator_match)
+ assert agent_match is not None and operator_match is not None
+ agent = agent_match.group(1)
+ operator = operator_match.group(1)
+ self.assertEqual(len(re.findall(r"engineering_queue_", agent)), 5)
+ self.assertNotIn("engineering_queue_issue_execution_grant", agent)
+ self.assertNotIn("engineering_queue_authorize_ready", agent)
+ self.assertEqual(set(re.findall(r"engineering_queue_[a-z_]+", agent)), {"engineering_queue_create_change", "engineering_queue_claim", "engineering_queue_attach_evidence", "engineering_queue_agent_status", "engineering_queue_submit_for_review"})
+ self.assertEqual(set(re.findall(r"engineering_queue_[a-z_]+", operator)), {"engineering_queue_issue_execution_grant", "engineering_queue_revoke_execution_grant", "engineering_queue_authorize_ready"})
+ self.assertIn("self approval forbidden", self.sql)
+ self.assertIn("grant issuer cannot claim own work", self.sql)
+ self.assertIn("tars_queue_agent_login", self.sql)
+ self.assertIn("tars_queue_operator_login", self.sql)
+ self.assertIn("tars_queue_seed_login", self.sql)
+ self.assertIn("REVOKE EXECUTE ON FUNCTION public.engineering_queue_seed_import(JSONB),public.engineering_queue_protect_approval_columns()", self.sql)
+ self.assertIn("GRANT EXECUTE ON FUNCTION public.engineering_queue_seed_import(JSONB) TO tars_queue_seed", self.sql)
+ self.assertNotRegex(self.sql, r"GRANT\s+EXECUTE\s+ON\s+FUNCTION[^;]+TO\s+PUBLIC")
+
+ def test_runtime_select_grants_all_six_tables_but_never_direct_dml(self):
+ grant_match = re.search(r"GRANT SELECT ON ([^;]+) TO tars_queue_agent,tars_queue_operator;", self.sql)
+ self.assertIsNotNone(grant_match)
+ assert grant_match is not None
+ grant = grant_match.group(1)
+ granted_tables = set(re.findall(r"engineering_[a-z_]+", grant))
+ self.assertEqual(granted_tables, TABLES)
+ self.assertNotRegex(self.sql, r"GRANT\s+(?:INSERT|UPDATE|DELETE|TRUNCATE)[^;]+TO\s+(?:tars_queue_agent|tars_queue_operator|tars_queue_seed)")
+ self.assertIn("queue schema column contract mismatch", self.sql)
+ self.assertNotIn("runtime table read contract missing", self.sql)
+ self.assertIn("GRANT SELECT ON public.engineering_changes", self.sql)
+ self.assertLess(self.sql.index("SET LOCAL ROLE tars_queue_owner"), self.sql.index("CREATE OR REPLACE FUNCTION public.engineering_queue_create_change"))
+ self.assertLess(self.sql.index("GRANT USAGE,CREATE ON SCHEMA public TO tars_queue_owner"), self.sql.index("CREATE OR REPLACE FUNCTION public.engineering_queue_create_change"))
+ self.assertIn("IF NOT has_table_privilege('tars_queue_agent_login','public.engineering_changes','SELECT') OR NOT has_table_privilege('tars_queue_operator_login'", self.sql)
+ self.assertIn("IF EXISTS(SELECT 1 FROM unnest(t) AS obj(table_name) CROSS JOIN", self.sql)
+ self.assertIn("has_table_privilege(roles.role_name,'public.'||table_name", self.sql)
+ self.assertIn("queue table pre-migration owner mismatch", self.sql)
+ self.assertIn("queue sequence pre-migration owner mismatch", self.sql)
+ self.assertIn("GRANT USAGE ON SCHEMA public TO tars_queue_agent,tars_queue_operator,tars_queue_seed", self.sql)
+ self.assertIn("GRANT USAGE,CREATE ON SCHEMA public TO tars_queue_owner", self.sql)
+ self.assertIn("REVOKE CREATE ON SCHEMA public FROM tars_queue_agent,tars_queue_operator,tars_queue_seed", self.sql)
+ self.assertLess(self.sql.index("GRANT USAGE,CREATE ON SCHEMA public TO tars_queue_owner"), self.sql.index("CREATE OR REPLACE FUNCTION public.engineering_queue_create_change"))
+ self.assertNotRegex(self.sql, r"GRANT\s+SELECT[^;]+tars_queue_seed")
+
+ def test_public_object_dml_acl_is_explicitly_revoked(self):
+ self.assertIn("REVOKE INSERT,UPDATE,DELETE,TRUNCATE,REFERENCES,TRIGGER,SELECT ON TABLE public.%I FROM PUBLIC',obj", self.sql)
+ self.assertIn("ON TABLE public.%2$I FROM PUBLIC',col_name,obj", self.sql)
+
+ def test_public_cannot_read_queue_or_use_queue_sequences(self):
+ self.assertIn("REVOKE ALL PRIVILEGES ON SEQUENCE public.%I FROM PUBLIC", self.sql)
+ self.assertIn("REVOKE SELECT ON TABLE public.%I FROM PUBLIC", self.sql)
+ self.assertIn("PUBLIC has queue sequence privileges", self.sql)
+ self.assertIn("PUBLIC SELECT remains on queue table", self.sql)
+
+ def test_setup_identity_cannot_enter_with_an_existing_role_switch(self):
+ self.assertIn("current_user<>session_user", self.sql)
+ self.assertIn("database owner mismatch", self.sql)
+ self.assertIn("public schema owner mismatch", self.sql)
+
+ def test_column_privilege_revoke_covers_public_and_runtime_roles(self):
+ self.assertIn("has_column_privilege", self.sql)
+ self.assertIn("REVOKE INSERT (%1$I),UPDATE (%1$I),REFERENCES (%1$I) ON TABLE public.%2$I FROM %3$I", self.sql)
+ self.assertIn("column-level runtime/seed table privileges violate least privilege", self.sql)
+ self.assertIn("column-level runtime DML privileges remain", self.sql)
+
+ def test_existing_missing_select_privilege_is_not_required_before_migration_grants_it(self):
+ preflight = self.sql.split("CREATE OR REPLACE FUNCTION public.engineering_queue_create_change", 1)[0]
+ self.assertNotIn("runtime table read contract missing", preflight)
+ self.assertIn("GRANT SELECT ON public.engineering_changes", self.sql)
+ self.assertLess(self.sql.index("GRANT SELECT ON public.engineering_changes"), self.sql.index("COMMIT;"))
+
+ def test_schema_create_is_granted_before_functions_without_pregrant_requirement(self):
+ self.assertNotIn("has_schema_privilege('tars_queue_owner','public','CREATE')", self.sql)
+ grant_at = self.sql.index("GRANT USAGE,CREATE ON SCHEMA public TO tars_queue_owner")
+ function_at = self.sql.index("CREATE OR REPLACE FUNCTION public.engineering_queue_create_change")
+ self.assertLess(grant_at, function_at)
+
+ def test_migration_transfers_queue_objects_to_nologin_definer_owner(self):
+ preflight_end = self.sql.index("GRANT USAGE,CREATE ON SCHEMA public TO tars_queue_owner")
+ self.assertIn("c.relowner<>'tars_queue_itest'::regrole", self.sql[:preflight_end])
+ self.assertIn("ALTER TABLE public.%I OWNER TO %I", self.sql)
+ self.assertIn("ALTER SEQUENCE public.%I OWNER TO %I", self.sql)
+ transfer_at = self.sql.index("FOREACH obj IN ARRAY ARRAY['engineering_changes'")
+ role_at = self.sql.index("SET LOCAL ROLE tars_queue_owner")
+ self.assertLess(transfer_at, role_at)
+ self.assertIn("queue table owner handoff mismatch", self.sql)
+ self.assertIn("queue sequence owner handoff mismatch", self.sql)
+
+ def test_migration_requires_operator_pinned_cluster_identity(self):
+ for setting in ("tars.queue.expected_system_identifier", "tars.queue.expected_server_addr", "tars.queue.expected_client_addr"):
+ self.assertIn(setting, self.sql)
+ self.assertIn("expected_system_id IS DISTINCT FROM 7709241176253177900::numeric", self.sql)
+ self.assertIn("authorized isolated setup superuser required", self.sql)
+ self.assertIn("safe NOLOGIN owner role required", self.sql)
+ self.assertIn("GRANT USAGE,CREATE ON SCHEMA public TO tars_queue_owner", self.sql)
+
+ def test_public_schema_create_is_checked_not_revoked_globally(self):
+ self.assertIn("public schema CREATE granted to PUBLIC; refusing broad ACL change", self.sql)
+ self.assertIn("a.grantee=0", self.sql)
+ self.assertIn("REVOKE CREATE ON SCHEMA public FROM tars_queue_agent,tars_queue_operator,tars_queue_seed", self.sql)
+ self.assertIn("has_schema_privilege('tars_queue_agent','public','CREATE')", self.sql)
+
+ def test_direct_login_execute_defaults_are_revoked(self):
+ for login in ("tars_queue_agent_login", "tars_queue_operator_login", "tars_queue_seed_login"):
+ self.assertIn(login, self.sql)
+ self.assertIn("FROM PUBLIC,tars_queue_agent,tars_queue_operator,tars_queue_seed,tars_queue_agent_login,tars_queue_operator_login,tars_queue_seed_login", self.sql)
+
+ def test_seed_import_and_human_gate_protection_are_not_reimplemented_or_weakened(self):
+ self.assertIn("engineering_queue_seed_import", self.sql)
+ self.assertIn("engineering_queue_protect_approval_columns", self.sql)
+ self.assertIn("engineering_queue_protect_approval_columns_trigger", self.sql)
+ self.assertIn("set_approval_from_authority", self.store)
+ self.assertNotIn("hg1_approval_ref=", self.sql)
+ self.assertNotIn("hg2_approval_ref=", self.sql)
+
+ def test_grants_claim_evidence_and_human_gate_rules_are_present(self):
+ for marker in ("self approval forbidden", "grant issuer cannot claim own work", "active claim", "unresolved dependencies block claim", "active execution grant required", "passing test evidence required", "completed cannot represent a Human Gate decision", "submitted_for_review"):
+ self.assertIn(marker, self.sql)
+
+ def test_migration_fails_closed_and_does_not_reset_or_mutate_existing_rows(self):
+ self.assertIn("current_database()<>'tars_queue_itest'", self.sql)
+ self.assertIn("SET LOCAL ROLE tars_queue_owner", self.sql)
+ self.assertIn("authorized isolated setup superuser required", self.sql)
+ self.assertIn("session_user IN ('tars_queue_agent_login','tars_queue_operator_login','tars_queue_seed_login')", self.sql)
+ self.assertIn("ALTER TABLE public.%I OWNER TO %I", self.sql)
+ self.assertIn("ALTER SEQUENCE public.%I OWNER TO %I", self.sql)
+ ownership = self.sql.split("GRANT USAGE,CREATE ON SCHEMA public TO tars_queue_owner", 1)[1].split("SET LOCAL ROLE tars_queue_owner", 1)[0]
+ self.assertIn("ALTER TABLE public.%I OWNER TO %I", ownership)
+ self.assertIn("ALTER SEQUENCE public.%I OWNER TO %I", ownership)
+ self.assertNotIn("session_user", ownership)
+ self.assertIn("queue table owner handoff mismatch", self.sql)
+ self.assertIn("queue sequence owner handoff mismatch", self.sql)
+ self.assertIn("routine collision or partial migration", self.sql)
+ upper = self.sql.upper()
+ for forbidden in ("DROP TABLE", "TRUNCATE TABLE", "DELETE FROM PUBLIC.ENGINEERING_CHANGES"):
+ self.assertNotIn(forbidden, upper)
+ self.assertNotRegex(self.sql, r"UPDATE\s+PUBLIC\.ENGINEERING_CHANGES")
+ self.assertTrue(self.sql.rstrip().endswith("COMMIT;"))
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/services/tars-engineering-queue-dev/worker.py b/services/tars-engineering-queue-dev/worker.py
new file mode 100644
index 0000000..fcc3337
--- /dev/null
+++ b/services/tars-engineering-queue-dev/worker.py
@@ -0,0 +1,102 @@
+from __future__ import annotations
+
+"""One-shot worker over the packaged, pinned Queue MVP core."""
+import argparse
+import os
+from typing import Any
+from .config import AGENT_LOGIN, validate_clone_dsn, validate_runtime_env_file
+from .core.queue_store import EngineeringQueue
+
+ACTION = "queue.self_test.v1"
+TEST_CHANGE_ID = "EQ-DEV-SMOKE-3D-A-20261118-01"
+TEST_TITLE = "Queue worker harmless self-test for Gate 3D-A"
+EVIDENCE_PREFIX = "queue-dev-worker://smoke-3d-a-20261118-01/"
+
+
+def execute_allowlisted(action: str, payload: dict[str, Any]) -> dict[str, Any]:
+ if action != ACTION:
+ raise ValueError("worker action is not allowlisted")
+ if not isinstance(payload, dict) or set(payload) - {"label"}:
+ raise ValueError("unsupported self-test payload fields")
+ label = payload.get("label", "queue-smoke")
+ if not isinstance(label, str) or not 1 <= len(label) <= 80:
+ raise ValueError("self-test label must be 1..80 characters")
+ return {"action": ACTION, "label": label, "result": "pass"}
+
+
+class QueueWorker:
+ def __init__(self, queue: EngineeringQueue, *, agent_subject=AGENT_LOGIN):
+ if agent_subject != AGENT_LOGIN:
+ raise ValueError("worker subject must be dedicated DEV Agent identity")
+ self.queue = queue
+ self.agent_subject = agent_subject
+
+ def run_once(self, change_id: str, execution_approval_ref: str) -> dict[str, Any]:
+ if change_id != TEST_CHANGE_ID:
+ raise ValueError("worker accepts only unique named DEV smoke ticket")
+ # Read-only identity/status check before acquiring the execution claim.
+ record = self.queue.get(change_id)
+ if (record.get("change_id") != TEST_CHANGE_ID or
+ record.get("title") != TEST_TITLE or
+ record.get("repository") != "tars-platform" or
+ record.get("status") != "ready"):
+ raise RuntimeError("pre-claim record is not the exact ready smoke ticket")
+ claimed = self.queue.claim(change_id, self.agent_subject, execution_approval_ref)
+ if (claimed.get("status") != "claimed" or
+ claimed.get("change_id") != TEST_CHANGE_ID or
+ claimed.get("title") != TEST_TITLE or
+ claimed.get("repository") != "tars-platform"):
+ raise RuntimeError("claimed record identity mismatch")
+ active = self.queue.update_status(
+ change_id, self.agent_subject, "in_progress", claimed["version"],
+ "fixed DEV self-test started",
+ )
+ try:
+ result = execute_allowlisted(ACTION, {"label": TEST_CHANGE_ID})
+ except Exception as exc:
+ evidence = self.queue.attach_evidence(change_id, self.agent_subject, {
+ "evidence_type": "test",
+ "uri": f"{EVIDENCE_PREFIX}{change_id}",
+ "summary": "Fixed DEV test failed",
+ "result": "fail",
+ })
+ blocked = self.queue.update_status(
+ change_id, self.agent_subject, "blocked", active["version"],
+ "fixed DEV test failed",
+ )
+ return {"change": blocked, "evidence": evidence, "error": type(exc).__name__}
+ evidence = self.queue.attach_evidence(change_id, self.agent_subject, {
+ "evidence_type": "test",
+ "uri": f"{EVIDENCE_PREFIX}{change_id}",
+ "summary": f"{ACTION} completed",
+ "result": "pass",
+ })
+ validated = self.queue.update_status(
+ change_id, self.agent_subject, "validated", active["version"],
+ "fixed DEV self-test passed",
+ )
+ return {"change": validated, "evidence": evidence, "result": result}
+
+
+def build_worker_from_env() -> QueueWorker:
+ source = os.environ.get("TARS_QUEUE_RUNTIME_ENV_FILE", "")
+ if not source:
+ raise RuntimeError("TARS_QUEUE_RUNTIME_ENV_FILE required")
+ validate_runtime_env_file(source)
+ dsn = os.environ.get("TARS_QUEUE_AGENT_DSN", "")
+ validate_clone_dsn(dsn, AGENT_LOGIN)
+ return QueueWorker(EngineeringQueue(dsn))
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Run one fixed Queue DEV smoke action")
+ parser.add_argument("change_id", choices=[TEST_CHANGE_ID])
+ parser.add_argument("execution_approval_ref")
+ args = parser.parse_args()
+ result = build_worker_from_env().run_once(args.change_id, args.execution_approval_ref)
+ print(f"worker status={result['change'].get('status')} evidence={result['evidence'].get('evidence_id', 'recorded')}")
+ return 0 if result["change"].get("status") == "validated" else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/services/tars-status/HEALTH-2.0-CONTRACT.md b/services/tars-status/HEALTH-2.0-CONTRACT.md
new file mode 100644
index 0000000..1ec995a
--- /dev/null
+++ b/services/tars-status/HEALTH-2.0-CONTRACT.md
@@ -0,0 +1,188 @@
+# HEALTH-2.0-CONTRACT
+
+Verbindlicher Feld- und Semantik-Contract für `GET /services` und `GET /services/{id}`
+im `tars-status`-Service. **Abgeleitet ausschließlich aus dem Code des Slice-1c-Kandidaten**
+(`app/services_registry.py`, `app/main.py`) und den zugehörigen Tests. Keine gewünschten
+Eigenschaften, keine Live-Messungen.
+
+Status: Entwurf zur Freigabe · Stand 2026-11-06 · gilt für den Integrationskandidaten
+`slice-1c.diff` (5 Dateien, +1352/−20).
+
+---
+
+## 0. Drei unabhängige Dimensionen
+
+| Dimension | Feld | Vocabulary | Bedeutung |
+|---|---|---|---|
+| Legacy-/Laufzeitstatus | `status` | `ok`, `degraded`, `error`, `unknown` | eigener Zustand des Service, Legacy-Vokabular, unverändert |
+| Aggregierte Gesundheit | `health` | `healthy`, `degraded`, `unhealthy`, `unknown` | strikte Evidenzbewertung inkl. Abhängigkeiten |
+| Betriebsmodus | `operationalMode` | `normal`, `maintenance` | dritte, unabhängige Dimension |
+
+Quelle: `services_registry.py:61` (`SERVICE_STATUS_VALUES`), `:70` (`HEALTH_VALUES`),
+`:76` (`OPERATIONAL_MODES`). `status` bleibt „same vocabulary, same combination rules"
+(Modul-Docstring, `:53-55`).
+
+---
+
+## 1. `status`
+
+**Typ:** `str`, nie `null`.
+**Werte:** `ok` | `degraded` | `error` | `unknown`.
+**Semantik:** eigener Zustand des Service aus seiner primären Quelle; kombiniert
+Inventar-/Installationszustand, Runtime-Zustand und gemessene Evidenz. Bleibt das
+Legacy-Feld für bestehende Consumer.
+
+**Auflösungsreihenfolge** (`_resolve_status`, `:922-957`):
+1. `state == "planned"` → `unknown`, Detail „planned — not deployed"
+2. `install_state == "not_installed"` → `unknown`, „not installed"
+3. `source == SRC_TKC_STATUS` → `_tkc_status(...)`
+4. `SRC_PROBE`/`SRC_HERMES_API` → Probe vorhanden? sonst `unknown`, „probe unavailable"
+5. `SRC_FILESYSTEM` → `mounted is False` → `error`; `mounted is True` → `ok`; ungemessen → `ok`
+6. `SRC_SYSTEMD` → ohne lesbare Properties `unknown`
+7. sonst → `unknown`, „no read-only source for this service"
+
+**Container-Zweig** (`_container_status`, `:818-858`): `running` + Healthcheck unhealthy →
+`error`; `running` + Healthcheck starting → `unknown`; `running` ohne Healthcheck → `ok`
+(nur Laufzeitbeweis); `exited`/`dead` → `error`; `restarting` → `error` („crash loop");
+`paused`/`created`/`unrecognised`/`not_listed` → `unknown`.
+`_apply_runtime` (`:731-743`) kann ein Ergebnis nur verschlechtern, nie verbessern.
+
+**Backup-Job-Zweig:** `_backup_job_status` überschreibt `status` mit
+`running`→`degraded`, `failed`→`error`, `success`→`ok`, nie ausgeführt→`unknown`.
+Die Endwerte werden in das Entry zurückgeschrieben (`:1123-1127`).
+
+---
+
+## 2. `health`
+
+**Typ:** `str`, nie `null`.
+**Werte:** `healthy` | `degraded` | `unhealthy` | `unknown`.
+**Basistabelle** `_STATUS_TO_HEALTH` (`:116-117`): `ok→healthy`, `degraded→degraded`,
+`error→unhealthy`, `unknown→unknown`. Diese Tabelle ist der Ausgangspunkt, nicht das
+Endergebnis: `_apply_dependency_health` kann `health` danach auf `degraded` senken,
+während `status` unverändert bleibt.
+
+**Entscheidungsreihenfolge** (`_evidence_health`, `:329-375`), erste Übereinstimmung gewinnt:
+1. `planned` → `unknown` / `not_deployed`
+2. `not_installed` → `unknown` / `not_deployed`
+3. `source == SRC_NONE` → `unknown` / `no_probe_source`
+4. `health_evidence == "constant"` → `unknown` / `constant_value`
+5. Evidenz älter als `max_age_seconds` (Default `90`, `:121`) → `unknown` / `stale_evidence`
+6. `runtime_only` → `unknown` / `runtime_only`
+7. `error_kind` gesetzt → `unhealthy` wenn `status == "error"`, sonst `unknown`; Code =
+ `error_kind` oder `check_failed`
+8. `status == "ok"` → `healthy` / `healthy_evidence`
+9. `status == "degraded"` → `degraded` / `degraded_evidence`
+10. `status == "error"` → `unhealthy` / `check_failed`
+11. sonst → `unknown` / `no_evidence`
+
+**Abhängigkeitsregel** (`_apply_dependency_health`, `:1254-1272`): Nur Einträge mit
+`health == "healthy"` werden betrachtet. Ist ein deklariertes Ziel (`dependencies[].target`)
+`unhealthy`, wird `health` auf `degraded` gesetzt, `healthReasonCode` auf
+`dependency_unhealthy`, `healthReason` auf „dependency <target> is unhealthy", und
+`lastSuccess` auf `null`. Nur Absenkung, nie Anhebung. `unknown` und `unhealthy` bleiben
+unberührt. `status` wird dabei **nicht** verändert.
+
+---
+
+## 3. `operationalMode`
+
+**Typ:** `str`, nie `null`.
+**Werte:** `normal` | `maintenance`.
+**Regel** (`:1135`): `"maintenance"` genau dann, wenn `maintenance_for(...)` ein Objekt mit
+`active == True` liefert; sonst `"normal"`.
+**Invariante:** Maintenance überschreibt niemals `health`. Ein Service in Maintenance behält
+seinen gemessenen `health`-Wert (Docstring `:45-48`; Tests
+`test_slice1b.py::test_6_explicitly_declared_maintenance_is_active_and_keeps_health`,
+`test_health2.py::test_maintenance_active_keeps_an_unhealthy_health`).
+
+---
+
+## 4. `healthSource`
+
+**Typ:** Objekt `{"kind": str, "reference": str}`, nie `null` (immer gesetzt).
+**`kind`-Werte** (`_status_source`, `:692-723`): `tkc_status`, `tars_status`,
+`hermes_api`, `in_process`, `filesystem`, `systemd`, `unknown`.
+**Bedeutung:** Herkunft der Evidenz. Ein deklarierter `systemd`-Spec ohne gelesene
+Properties degradiert zu `kind="unknown"` mit Referenz „declared systemd unit … was not read
+in this cycle" (`:717-721`). `healthSource` ist Attribution, kein Beweis.
+
+---
+
+## 5. `healthReasonCode` und `healthReason`
+
+**`healthReasonCode`:** `str`, nie `null`; einer von 25 Codes (`:84-113`):
+`healthy_evidence`, `degraded_evidence`, `check_failed`, `probe_timeout`, `probe_unreachable`,
+`probe_http_error`, `stale_evidence`, `no_evidence`, `no_probe_source`, `constant_value`,
+`not_deployed`, `dependency_unhealthy`, `runtime_only`, `container_unhealthy`,
+`container_exited`, `container_restarting`, `container_paused`, `container_created`,
+`container_dead`, `backup_success`, `backup_failed`, `backup_running`, `backup_stale`,
+`backup_never_ran`, `storage_not_mounted`.
+**`healthReason`:** `str | null`; menschenlesbarer Text, keine Maschinensteuerung.
+
+**Garantie:** Timeout (`probe_timeout`), nicht erreichbar (`probe_unreachable`), HTTP-Fehler
+(`probe_http_error`) und nie ausgeführte Prüfung (`no_probe_source`, `constant_value`) bleiben
+unterscheidbar (Modul-Docstring `:41-44`).
+
+---
+
+## 6. `lastChecked` und `lastSuccess`
+
+**`lastChecked`:** ISO-8601-String oder `null`; Zeitpunkt der letzten Beobachtung
+(`:1055-1064`):
+- `SRC_TKC_STATUS` → `tkc_observed_at` oder der Antwort-Zeitstempel
+- `SRC_PROBE`/`SRC_HERMES_API` und `status != unknown` → aktueller Zeitstempel
+- `SRC_FILESYSTEM` und `status != unknown` → aktueller Zeitstempel
+- sonst → `null`
+- Backup-Job-Zweig überschreibt mit `startedAt` oder `lastSuccess` des Jobs (`:1117-1122`)
+
+**`lastSuccess`:** ISO-8601-String oder `null` (`:1130-1133`):
+`job_last_success` aus dem Backup-Job, sonst `lastChecked` wenn `health == "healthy"`,
+sonst der zwischengespeicherte letzte Erfolg. Bei `dependency_unhealthy` explizit `null`.
+
+**Aktualitätsregel:** Evidenz älter als `max_age_seconds` (Default 90 s, per
+`HEALTH_MAX_AGE_SECONDS` überschreibbar) wird als `stale_evidence` auf `unknown` gesetzt,
+nicht als Erfolg (`:355-362`).
+
+---
+
+## 7. `maintenance`
+
+**Typ:** Objekt oder `null`. `null` wenn kein Fenster zutrifft (`maintenance_for`, `:266-330`).
+
+**Deklarierte Periode (`kind="declared"`)** — Vorrang vor Kalenderfenstern:
+Felder `active` (bool), `windowId`, `kind`, `reason`, `startsAt`, `endsAt` (oder `null`),
+`groups`, `role` (`source`/`impacted`), `sourceService`.
+- `start <= now` → `active: true`
+- `start > now` → `active: false` (bevorstehend, sichtbar)
+- `now >= end` → Periode wird verworfen; Rückkehr zu `normal` erfolgt allein durch die Uhr,
+ ohne Persistenz und ohne Schreib-API.
+
+**Kalenderfenster (`kind="scheduled"`)** — innerhalb der Grenzen:
+`active: false`, `kind: "scheduled"`, `evidence: "calendar_plan"`, plus `startsAt`/`endsAt`.
+Ein Kalenderplan ist **kein** Nachweis laufender Wartung; `operationalMode` bleibt `normal`
+(`:308-310`).
+
+---
+
+## 8. `statusSource` und `statusDetail`
+
+**`statusSource`:** Objekt `{"kind": str, "reference": str}`; bestehendes Feld, unverändert.
+**`statusDetail`:** `str | null`; Freitext zum Status. Nach dem Backup-Zweig wird der Wert
+explizit zurückgeschrieben, damit `status`, `statusDetail` und `health` nicht auseinanderlaufen
+(`:1123-1127`).
+
+---
+
+## 9. Null- und Fehlersemantik (verbindlich)
+
+- Fehlende Evidenz → `status="unknown"`, `health="unknown"`, Code `no_evidence` /
+ `no_probe_source` / `stale_evidence`. **Niemals** `healthy`.
+- `planned` / `not_installed` → `unknown` / `not_deployed`.
+- Konstanter Literalwert → `unknown` / `constant_value`, unabhängig vom Wert.
+- Nicht messbarer Mount → `status="ok"` mit Detail „mount identity not measured";
+ als `mounted: false` gemeldeter Mount → `error` / `storage_not_mounted`.
+- Backup-Unit ohne `InvocationID` → `unknown` / `backup_never_ran`, auch bei `Result=success`.
+- Unbekannter Container-Statusstring → `unknown`, nie ein erfundenener Zustand.
+- Alle Felder außer `status`, `health`, `healthReasonCode`, `healthSource`,
+ `operationalMode`, `statusSource` dürfen `null` sein.
diff --git a/services/tars-status/app/main.py b/services/tars-status/app/main.py
index 6b68cd5..8e674fd 100644
--- a/services/tars-status/app/main.py
+++ b/services/tars-status/app/main.py
@@ -37,6 +37,7 @@ from __future__ import annotations
import asyncio
import os
+import shutil
import subprocess
import time
from datetime import datetime, timezone
@@ -45,7 +46,9 @@ from typing import Any, Optional
import httpx
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.middleware.cors import CORSMiddleware
-from pydantic import BaseModel
+from pydantic import BaseModel, ConfigDict, Field
+
+from app.services_registry import SERVICE_ID_RE, build_service_entries, subsystem_status
# ─────────────────────────────────────────────────────────────────────────────
# Configuration
@@ -54,15 +57,29 @@ from pydantic import BaseModel
TKC_BASE_URL = os.environ.get("TKC_BASE_URL", "http://10.10.10.5:8110")
MCP_HEALTH_URL = os.environ.get("MCP_HEALTH_URL", "http://localhost:8765/health")
GATEWAY_HEALTH_URL = os.environ.get("GATEWAY_HEALTH_URL", "http://10.10.10.5:8080/health")
+HERMES_HEALTH_URL = os.environ.get("HERMES_HEALTH_URL", "http://127.0.0.1:8642/v1/health")
REPO_DEV_BASE = os.environ.get("REPO_DEV_BASE", "/opt/tars/dev/bob")
REPO_LIVE_BASE = os.environ.get("REPO_LIVE_BASE", "/opt/tars/repos")
STATUS_CACHE_TTL = int(os.environ.get("STATUS_CACHE_TTL", "30"))
+#: Age beyond which an observation stops being health evidence. Three cache
+#: windows by default: long enough to survive a slow upstream, short enough
+#: that a silently dead probe cannot look healthy for minutes.
+HEALTH_MAX_AGE_SECONDS = int(os.environ.get("HEALTH_MAX_AGE_SECONDS", "90"))
+#: The backup job probe is opt-in: it shells out to read-only `systemctl show`.
+#: Default off so an isolated test run never touches the host's systemd.
+BACKUP_PROBE_ENABLED = os.environ.get("BACKUP_PROBE_ENABLED", "0") == "1"
+BACKUP_SERVICE_UNIT = os.environ.get("BACKUP_SERVICE_UNIT", "tars-borg-daily.service")
+BACKUP_TIMER_UNIT = os.environ.get("BACKUP_TIMER_UNIT", "tars-borg-daily.timer")
STATUS_API_KEY = os.environ.get("STATUS_API_KEY", "")
PORT = int(os.environ.get("PORT", "8900"))
# Hardcoded repo names — never sourced from user input
REPOS = ["tars-platform", "tars-tkc", "tars-mcp-server"]
+# Backup mountpoint for the storage-usage readout — hardcoded like REPOS, never
+# sourced from user input. Read with statvfs only (no subprocess, no privilege).
+BACKUP_MOUNT = "/backup"
+
HTTP_TIMEOUT = 5.0 # seconds per upstream call
# ─────────────────────────────────────────────────────────────────────────────
@@ -116,6 +133,10 @@ class ServiceStatus(BaseModel):
name: str
status: str # "ok" | "degraded" | "error" | "unknown"
detail: Optional[str] = None
+ #: Machine-readable reason of the last failure ("probe_timeout",
+ #: "probe_unreachable", "probe_http_error", "check_failed").
+ #: Excluded from serialisation so the /status contract stays byte-identical.
+ errorKind: Optional[str] = Field(default=None, exclude=True)
class SubsystemStatus(BaseModel):
postgresql: str
@@ -163,17 +184,186 @@ class StatusResponse(BaseModel):
repositories: list[RepoStatus]
+# ── /services response models ───────────────────────────────────────────────
+# Typed so the endpoint has a real OpenAPI contract and field typos cannot reach
+# the client. Values stay explicit nulls (no exclude_none) — an honest "not
+# reported" must remain visible instead of silently disappearing.
+
+class ServiceSource(BaseModel):
+ kind: str
+ reference: Optional[str] = None
+
+class ServiceArchitecture(BaseModel):
+ state: str
+ source: ServiceSource
+
+class ServicePlace(BaseModel):
+ node: str
+
+class ServiceIdentities(BaseModel):
+ container: Optional[str] = None
+ unit: Optional[str] = None
+ units: list[str] = Field(default_factory=list)
+ endpoint: Optional[str] = None
+
+class ServiceDependency(BaseModel):
+ target: str
+ kind: str
+ evidence: Optional[str] = None
+ confidence: Optional[str] = None
+
+class MaintenanceWindow(BaseModel):
+ id: str
+ onCalendar: str
+ service: Optional[str] = None # source window (the job itself)
+ sourceService: Optional[str] = None # impacted projection of that window
+ timer: Optional[str] = None
+ timezone: Optional[str] = None
+ maxDurationSeconds: Optional[int] = None
+ state: Optional[str] = None
+ active: Optional[bool] = None # None until Slice 1b computes it
+ expectedImpact: Optional[list[str]] = None
+ source: Optional[ServiceSource] = None
+ note: Optional[str] = None
+
+class ServiceEntry(BaseModel):
+ """One entry of GET /services. A missing value is always an explicit null."""
+
+ # `extra="allow"`: a field added to the registry must never be dropped by the
+ # response model. Drift between registry and model is caught by the test that
+ # compares the endpoint response with the raw builder output.
+ model_config = ConfigDict(extra="allow")
+
+ id: str
+ label: str
+ kind: str
+ status: str
+ statusDetail: Optional[str] = None
+ statusSource: ServiceSource
+ state: str
+ installState: str
+ evidenceClass: str
+ architecture: ServiceArchitecture
+ checkedAt: str
+ place: ServicePlace
+ identities: ServiceIdentities
+ dependencies: list[ServiceDependency] = Field(default_factory=list)
+ maintenanceRole: Optional[str] = None
+ maintenanceWindow: Optional[MaintenanceWindow] = None
+ maintenanceWindows: Optional[list[MaintenanceWindow]] = None
+ # registry-supplied detail blocks (structure defined by the Service Data Contract)
+ components: Optional[list[dict]] = None
+ notes: Optional[list[str]] = None
+ databases: Optional[list[dict]] = None
+ repository: Optional[dict] = None
+ schedule: Optional[list[dict]] = None
+ encryption: Optional[dict] = None
+ retention: Optional[dict] = None
+ lastSuccessfulRun: Optional[dict] = None
+ nextScheduledRun: Optional[dict] = None
+ restoreVerification: Optional[dict] = None
+ offHostCopy: Optional[dict] = None
+ storage: Optional[dict] = None
+ # Health 2.0 — additive, optional, and never a replacement for `status`.
+ # `status` keeps its legacy vocabulary and combination rules.
+ health: Optional[str] = None
+ healthSource: Optional[ServiceSource] = None
+ healthReasonCode: Optional[str] = None
+ healthReason: Optional[str] = None
+ lastChecked: Optional[str] = None
+ lastSuccess: Optional[str] = None
+ operationalMode: Optional[str] = None
+ maintenance: Optional[dict] = None
+
+class ServiceListResponse(BaseModel):
+ checked_at: str
+ cache_ttl_seconds: int
+ services: list[ServiceEntry]
+
+
# ─────────────────────────────────────────────────────────────────────────────
# Response cache
# ─────────────────────────────────────────────────────────────────────────────
_cache: dict[str, Any] = {"data": None, "expires_at": 0.0}
+# Service inventory (GET /services) — same TTL as /status, separate payload.
+_services_cache: dict[str, Any] = {"data": None, "expires_at": 0.0}
+
+# TKC GET /status is the heaviest upstream call (it runs real queries). Cache the
+# raw payload separately so /status and /services share one call per TTL window.
+_tkc_status_cache: dict[str, Any] = {"data": None, "error": None,
+ "error_kind": None, "expires_at": 0.0}
+
+
+def _cache_fresh(cache: dict[str, Any]) -> Optional[dict]:
+ """Return a cached payload only while its TTL is still valid."""
+ if cache["data"] and time.monotonic() < cache["expires_at"]:
+ return cache["data"]
+ return None
+
+
+# In-flight shared tasks, keyed by cache. Concurrent callers of the same key
+# share ONE upstream round instead of each starting its own (a cold cache used to
+# fan out to N identical TKC /status calls, and TKC /status runs real queries).
+_inflight: dict[str, asyncio.Task] = {}
+
+
+def _consume_task_exception(task: asyncio.Task) -> None:
+ """Retrieve the outcome of a shared task so asyncio never warns about it."""
+ if not task.cancelled():
+ task.exception()
+
+
+async def _single_flight(key: str, factory) -> Any:
+ """Run ``factory`` once per in-flight window and share its result.
+
+ Task-based instead of lock-based: it cannot deadlock and it is safe to nest
+ (the /services and /status builders both await the shared TKC task). The
+ shared task owns its own HTTP client, so a caller that goes away cannot leave
+ the task working with a closed client.
+ """
+ task = _inflight.get(key)
+ if task is None or task.done():
+ task = asyncio.create_task(factory())
+ _inflight[key] = task
+ task.add_done_callback(_consume_task_exception)
+ # shield: one client disconnecting must not cancel the shared work for the others
+ return await asyncio.shield(task)
+
# ─────────────────────────────────────────────────────────────────────────────
# Upstream probes — each returns a partial result; never raises
# ─────────────────────────────────────────────────────────────────────────────
+def _kind_from_detail(detail: Optional[str]) -> Optional[str]:
+ """Map a probe failure detail onto a machine-readable health reason code.
+
+ Used for failures that reach us as a string (the TKC /status probe keeps its
+ two-value contract); the string carries the exception type as a prefix.
+ """
+ if not detail:
+ return None
+ text = detail.lower()
+ if "timeout" in text or "timed out" in text:
+ return "probe_timeout"
+ if "httpstatuserror" in text or "server error" in text or "client error" in text:
+ return "probe_http_error"
+ if "connecterror" in text or "connect" in text or "refused" in text or "no route" in text:
+ return "probe_unreachable"
+ return "check_failed"
+
+
+def _classify_probe_error(exc: BaseException) -> str:
+ """Reason code for an exception raised by an upstream probe."""
+ if isinstance(exc, httpx.TimeoutException):
+ return "probe_timeout"
+ if isinstance(exc, httpx.HTTPStatusError):
+ return "probe_http_error"
+ if isinstance(exc, (httpx.ConnectError, httpx.NetworkError)):
+ return "probe_unreachable"
+ return _kind_from_detail(f"{type(exc).__name__}: {exc}") or "check_failed"
+
async def probe_tkc(client: httpx.AsyncClient) -> tuple[ServiceStatus, Optional[SubsystemStatus], Optional[KnowledgeStats], list]:
"""Probe TKC /health, /knowledge/stats, and /knowledge/recent."""
svc = ServiceStatus(name="TKC", status="unknown")
@@ -195,7 +385,8 @@ async def probe_tkc(client: httpx.AsyncClient) -> tuple[ServiceStatus, Optional[
)
except Exception as exc:
svc.status = "error"
- svc.detail = str(exc)
+ svc.detail = f"{type(exc).__name__}: {exc}"
+ svc.errorKind = _classify_probe_error(exc)
return svc, subsystems, stats, recent
# Knowledge stats — new endpoint (may not exist on old deploy)
@@ -233,7 +424,9 @@ async def probe_mcp(client: httpx.AsyncClient) -> ServiceStatus:
detail = f"v{h.get('version','?')}"
return ServiceStatus(name="MCP Server", status=svc_status, detail=detail)
except Exception as exc:
- return ServiceStatus(name="MCP Server", status="error", detail=str(exc))
+ return ServiceStatus(name="MCP Server", status="error",
+ detail=f"{type(exc).__name__}: {exc}",
+ errorKind=_classify_probe_error(exc))
async def probe_gateway(client: httpx.AsyncClient) -> ServiceStatus:
@@ -245,7 +438,138 @@ async def probe_gateway(client: httpx.AsyncClient) -> ServiceStatus:
svc_status = "ok" if h.get("status") in ("ok", "healthy") else "degraded"
return ServiceStatus(name="Engineering Gateway", status=svc_status, detail=h.get("status"))
except Exception as exc:
- return ServiceStatus(name="Engineering Gateway", status="error", detail=str(exc))
+ return ServiceStatus(name="Engineering Gateway", status="error",
+ detail=f"{type(exc).__name__}: {exc}",
+ errorKind=_classify_probe_error(exc))
+
+
+async def probe_tkc_status(client: httpx.AsyncClient) -> tuple[Optional[dict], Optional[str]]:
+ """Probe TKC GET /status — authoritative for PostgreSQL/Milvus/Neo4j and the
+ container inventory. Returns (payload, error); never raises."""
+ try:
+ r = await client.get(f"{TKC_BASE_URL}/status")
+ r.raise_for_status()
+ body = r.json()
+ if not isinstance(body, dict):
+ return None, "TKC /status returned a non-object payload"
+ return body, None
+ except Exception as exc:
+ # The exception type stays visible in the detail so the aggregator can
+ # classify the failure without changing this function's 2-value contract.
+ return None, f"{type(exc).__name__}: {exc}"
+
+
+async def _fetch_tkc_status() -> tuple[Optional[dict], Optional[str]]:
+ """Fetch and cache TKC GET /status.
+
+ Owns its own client on purpose: this coroutine runs as a shared single-flight
+ task, so it must not borrow a client from whichever caller happened to start it.
+ """
+ now = time.monotonic()
+ if _tkc_status_cache["expires_at"] > now:
+ return _tkc_status_cache["data"], _tkc_status_cache["error"]
+
+ async with httpx.AsyncClient(timeout=HTTP_TIMEOUT) as client:
+ data, error = await probe_tkc_status(client)
+
+ _tkc_status_cache["data"] = data
+ _tkc_status_cache["error"] = error
+ _tkc_status_cache["error_kind"] = _kind_from_detail(error)
+ _tkc_status_cache["expires_at"] = now + STATUS_CACHE_TTL
+ return data, error
+
+
+async def cached_tkc_status() -> tuple[Optional[dict], Optional[str]]:
+ """TTL-cached, single-flight TKC GET /status.
+
+ One upstream call per cache window, however many /status and /services
+ requests arrive at the same time.
+ """
+ if _tkc_status_cache["expires_at"] > time.monotonic():
+ return _tkc_status_cache["data"], _tkc_status_cache["error"]
+ return await _single_flight("tkc_status", _fetch_tkc_status)
+
+
+async def probe_hermes(client: httpx.AsyncClient) -> ServiceStatus:
+ """Probe Hermes Agent GET /v1/health (unauthenticated by design — status + version).
+
+ The authenticated Hermes API is deliberately NOT used: the service key is not
+ read, stored or forwarded by this aggregator.
+ """
+ try:
+ r = await client.get(HERMES_HEALTH_URL)
+ r.raise_for_status()
+ h = r.json()
+ detail = h.get("version") or h.get("status")
+ svc_status = "ok" if str(h.get("status")).lower() in ("ok", "healthy") else "degraded"
+ return ServiceStatus(name="Hermes Agent", status=svc_status, detail=detail)
+ except Exception as exc:
+ return ServiceStatus(name="Hermes Agent", status="unknown",
+ detail=f"{type(exc).__name__}: {exc}",
+ errorKind=_classify_probe_error(exc))
+
+
+BACKUP_SERVICE_PROPS = ("ActiveState", "SubState", "Result", "ExecMainStatus",
+ "ExecMainStartTimestamp", "ExecMainExitTimestamp",
+ "InvocationID")
+BACKUP_TIMER_PROPS = ("ActiveState", "SubState", "LastTriggerUSec",
+ "NextElapseUSecRealtime", "TimersCalendar")
+
+
+def _systemctl_show(unit: str, props: tuple[str, ...]) -> dict[str, str]:
+ """Read unit properties without privileges. Never raises."""
+ args = ["systemctl", "show", unit] + [f"-p{p}" for p in props]
+ try:
+ result = subprocess.run(args, capture_output=True, text=True, timeout=5)
+ except Exception:
+ return {}
+ if result.returncode != 0:
+ return {}
+ values: dict[str, str] = {}
+ for line in result.stdout.splitlines():
+ key, sep, value = line.partition("=")
+ if sep:
+ values[key.strip()] = value.strip()
+ return values
+
+
+def probe_backup_job() -> Optional[dict]:
+ """Read-only evidence of the last backup unit invocation.
+
+ Returns None when the unit properties are unreadable — the caller then
+ reports "unknown" instead of inventing a backup result.
+ """
+ service = _systemctl_show(BACKUP_SERVICE_UNIT, BACKUP_SERVICE_PROPS)
+ if not service:
+ return None
+ timer = _systemctl_show(BACKUP_TIMER_UNIT, BACKUP_TIMER_PROPS)
+ return {"service": service, "timer": timer}
+
+
+def backup_filesystem_usage() -> Optional[dict]:
+ """Read-only statvfs of the backup mountpoint. No subprocess, no privilege.
+
+ Returns None when the mountpoint is not readable/statable — the caller then
+ reports no storage numbers instead of invented ones.
+ """
+ try:
+ usage = shutil.disk_usage(BACKUP_MOUNT)
+ except Exception:
+ return None
+ # ``ismount`` is a read-only stat call: it separates "the path is readable"
+ # from "the expected device is actually mounted there". A plain directory on
+ # the root filesystem would otherwise masquerade as backup storage.
+ try:
+ mounted = os.path.ismount(BACKUP_MOUNT)
+ except OSError:
+ mounted = None
+ return {
+ "mount": BACKUP_MOUNT,
+ "mounted": mounted,
+ "totalBytes": usage.total,
+ "usedBytes": usage.used,
+ "freeBytes": usage.free,
+ }
# ─────────────────────────────────────────────────────────────────────────────
@@ -367,28 +691,57 @@ def probe_all_repos() -> list[RepoStatus]:
# ─────────────────────────────────────────────────────────────────────────────
async def collect_status() -> dict:
- now = time.monotonic()
- if _cache["data"] and now < _cache["expires_at"]:
- return _cache["data"]
+ """Return the aggregated status (TTL cached, single-flight)."""
+ payload = _cache_fresh(_cache)
+ if payload is not None:
+ return payload
+ return await _single_flight("status", _build_status_payload)
+
+async def _build_status_payload() -> dict:
+ payload = _cache_fresh(_cache) # a concurrent caller may have refreshed us
+ if payload is not None:
+ return payload
+
+ now = time.monotonic()
async with httpx.AsyncClient(timeout=HTTP_TIMEOUT) as client:
- tkc_task = asyncio.create_task(probe_tkc(client))
- mcp_task = asyncio.create_task(probe_mcp(client))
- gateway_task = asyncio.create_task(probe_gateway(client))
+ tkc_task = asyncio.create_task(probe_tkc(client))
+ tkc_status_task = asyncio.create_task(cached_tkc_status())
+ mcp_task = asyncio.create_task(probe_mcp(client))
+ gateway_task = asyncio.create_task(probe_gateway(client))
- tkc_result, mcp_result, gateway_result = await asyncio.gather(
- tkc_task, mcp_task, gateway_task
+ tkc_result, tkc_status_result, mcp_result, gateway_result = await asyncio.gather(
+ tkc_task, tkc_status_task, mcp_task, gateway_task
)
tkc_svc, subsystems, stats, recent = tkc_result
-
- # Synthesise per-subsystem service entries from TKC health response
+ tkc_status, _tkc_status_error = tkc_status_result
+
+ # TKC GET /status runs REAL queries against PostgreSQL, Milvus and Neo4j and is
+ # therefore authoritative for the subsystem block. The previous /health-only
+ # derivation could never report PostgreSQL or Neo4j as "ok": /health carries no
+ # such keys, so both always fell through to "unknown" even while TKC was
+ # healthy. /health remains the fallback when /status is unavailable. The block
+ # keeps TKC's own value vocabulary (raw states), so no consumer sees a changed
+ # string — only a corrected source.
+ subsystems = _subsystems_from_tkc_status(tkc_status) or subsystems
+
+ # Synthesise per-subsystem service entries from the subsystem block.
+ # The status combines TKC state AND health: a subsystem TKC flags yellow is
+ # "degraded", never "ok". The `subsystems` block itself keeps TKC's raw
+ # vocabulary (unchanged contract); only this normalised list is health-aware.
services: list[ServiceStatus] = [tkc_svc]
if subsystems:
services.extend([
- ServiceStatus(name="PostgreSQL", status=_normalise(subsystems.postgresql)),
- ServiceStatus(name="Milvus", status=_normalise(subsystems.milvus)),
- ServiceStatus(name="Neo4j", status=_normalise(subsystems.neo4j)),
+ ServiceStatus(name="PostgreSQL",
+ status=subsystem_status(tkc_status, "postgresql")
+ or _normalise(subsystems.postgresql)),
+ ServiceStatus(name="Milvus",
+ status=subsystem_status(tkc_status, "milvus")
+ or _normalise(subsystems.milvus)),
+ ServiceStatus(name="Neo4j",
+ status=subsystem_status(tkc_status, "neo4j")
+ or _normalise(subsystems.neo4j)),
])
else:
services.extend([
@@ -416,6 +769,46 @@ async def collect_status() -> dict:
return payload
+def _subsystems_from_tkc_status(tkc_status: Optional[dict]) -> Optional[SubsystemStatus]:
+ """Derive the subsystem block from TKC GET /status (authoritative).
+
+ /status reports the outcome of real PostgreSQL/Milvus/Neo4j queries, so it is
+ the only source that can legitimately report those subsystems as "ok". Missing
+ keys degrade to "unknown" — never to a guess. Returns None when the payload is
+ unusable, so the caller can fall back to the /health derivation.
+ """
+ if not isinstance(tkc_status, dict):
+ return None
+ knowledge = tkc_status.get("knowledge")
+ services = tkc_status.get("services")
+ if not isinstance(knowledge, dict):
+ return None
+
+ def _state(section: Any, key: str) -> str:
+ if not isinstance(section, dict):
+ return "unknown"
+ item = section.get(key)
+ if isinstance(item, dict) and item.get("state") is not None:
+ # RAW upstream value, deliberately not normalised: this block has always
+ # carried TKC's own vocabulary ("online"/"active"), and the /status
+ # contract must keep it. Only the *source* changes here.
+ return str(item["state"])
+ return "unknown"
+
+ lifecycle = None
+ if isinstance(services, dict):
+ item = services.get("knowledge_lifecycle")
+ if isinstance(item, dict) and item.get("state") is not None:
+ lifecycle = str(item["state"])
+
+ return SubsystemStatus(
+ postgresql=_state(knowledge, "postgresql"),
+ milvus=_state(knowledge, "milvus"),
+ neo4j=_state(knowledge, "neo4j"),
+ knowledge_lifecycle=lifecycle,
+ )
+
+
def _normalise(raw: str) -> str:
"""Map TKC health string values to canonical status tokens."""
if raw in ("online", "ok", "healthy", "active"):
@@ -427,6 +820,91 @@ def _normalise(raw: str) -> str:
return "unknown"
+def _probe_dict(value: Any) -> Optional[dict]:
+ """Accept a ServiceStatus model or a plain dict from a probe."""
+ if isinstance(value, dict):
+ return value
+ dump = getattr(value, "model_dump", None)
+ return dump() if callable(dump) else None
+
+
+async def collect_services() -> dict:
+ """Build the read-only service inventory (Cosmos NODES service level).
+
+ TTL cached and single-flight; never raises on upstream failure — every
+ unavailable source degrades to status "unknown" with its attribution kept.
+ """
+ payload = _cache_fresh(_services_cache)
+ if payload is not None:
+ return payload
+ return await _single_flight("services", _build_services_payload)
+
+
+async def _build_services_payload() -> dict:
+ payload = _cache_fresh(_services_cache) # may have been refreshed meanwhile
+ if payload is not None:
+ return payload
+
+ now = time.monotonic()
+ async with httpx.AsyncClient(timeout=HTTP_TIMEOUT) as client:
+ tkc_status_task = asyncio.create_task(cached_tkc_status())
+ mcp_task = asyncio.create_task(probe_mcp(client))
+ gateway_task = asyncio.create_task(probe_gateway(client))
+ hermes_task = asyncio.create_task(probe_hermes(client))
+
+ (tkc_status, tkc_error), mcp, gateway, hermes = await asyncio.gather(
+ tkc_status_task, mcp_task, gateway_task, hermes_task
+ )
+
+ # Health 2.0 evidence the registry cannot observe on its own: the failure
+ # kind of each probe round, the previous healthy timestamp per service, and
+ # the freshness bound. Without this, "timeout" and "never checked" both
+ # collapse into "unknown" and a stale value can linger as healthy.
+ probe_error_kinds: dict[str, str] = {}
+ for key, probe in (("mcp", mcp), ("gateway", gateway), ("hermes", hermes)):
+ kind = getattr(probe, "errorKind", None)
+ if kind:
+ probe_error_kinds[key] = kind
+ tkc_kind = _tkc_status_cache.get("error_kind")
+ if tkc_kind:
+ probe_error_kinds["tkc_status"] = tkc_kind
+
+ backup_job = None
+ if BACKUP_PROBE_ENABLED:
+ backup_job = await asyncio.get_event_loop().run_in_executor(
+ None, probe_backup_job
+ )
+
+ previous = _services_cache.get("data") or {}
+ prior_success: dict[str, str] = {}
+ for old in previous.get("services", []) or []:
+ if isinstance(old, dict) and old.get("health") == "healthy" and old.get("lastSuccess"):
+ prior_success[old.get("id")] = old["lastSuccess"]
+
+ services = build_service_entries(
+ tkc_status=tkc_status,
+ tkc_error=tkc_error,
+ mcp=_probe_dict(mcp),
+ gateway=_probe_dict(gateway),
+ hermes=_probe_dict(hermes),
+ backup_filesystem=backup_filesystem_usage(),
+ backup_job=backup_job,
+ health_max_age_seconds=HEALTH_MAX_AGE_SECONDS,
+ probe_error_kinds=probe_error_kinds,
+ last_success=prior_success,
+ )
+
+ payload = {
+ "checked_at": datetime.now(tz=timezone.utc).isoformat(),
+ "cache_ttl_seconds": STATUS_CACHE_TTL,
+ "services": services,
+ }
+
+ _services_cache["data"] = payload
+ _services_cache["expires_at"] = now + STATUS_CACHE_TTL
+ return payload
+
+
# ─────────────────────────────────────────────────────────────────────────────
# Routes
# ─────────────────────────────────────────────────────────────────────────────
@@ -449,6 +927,33 @@ async def status_endpoint():
return await collect_status()
+@app.get("/services", summary="Read-only service inventory (Cosmos NODES service level)",
+ response_model=ServiceListResponse)
+async def services_endpoint():
+ """List every declared service with live state, attribution and inventory data.
+
+ Additive, read-only. The registry lives server-side, so the Cosmos NODES
+ service level needs no per-service entry in the frontend.
+ """
+ return await collect_services()
+
+
+@app.get("/services/{service_id}", summary="Read-only detail for a single service id",
+ response_model=ServiceEntry)
+async def service_detail_endpoint(service_id: str):
+ """Return one service entry. 400 on a malformed id, 404 on an unknown id."""
+ if not SERVICE_ID_RE.match(service_id):
+ raise HTTPException(
+ status_code=400,
+ detail="service_id must match <host>__<service> (e.g. ton-01__postgresql)",
+ )
+ payload = await collect_services()
+ for entry in payload["services"]:
+ if entry.get("id") == service_id:
+ return entry
+ raise HTTPException(status_code=404, detail=f"Unknown service id '{service_id}'")
+
+
# ─────────────────────────────────────────────────────────────────────────────
# Entry point (uvicorn)
# ─────────────────────────────────────────────────────────────────────────────
diff --git a/services/tars-status/app/services_registry.py b/services/tars-status/app/services_registry.py
new file mode 100644
index 0000000..f057c32
--- /dev/null
+++ b/services/tars-status/app/services_registry.py
@@ -0,0 +1,1272 @@
+"""services_registry — read-only service inventory for the Cosmos NODES service level.
+
+One canonical, **server-side** registry so the Cosmos service level renders
+data-driven and no per-service entry is hardcoded in the frontend.
+
+Rules (see the Service Data Contract):
+* Canonical IDs are ``<host_slug>__<service_slug>``. Physical facts (container,
+ unit, port, repository path) are *attributes* and are the join keys to live
+ sources. Sources are matched through this table only — never by string
+ similarity.
+* Four separate dimensions: ``status`` (operational health), ``state``
+ (inventory), ``installState`` (deployment), ``architecture.state``
+ (documentation trust). A failed probe never moves the architecture ring; a
+ planned or not-installed service can never be ``ok``.
+* ``status`` is combined from TKC ``state`` *and* ``health``: health may only
+ make an entry look worse (yellow ⇒ degraded, red ⇒ error), never better, and an
+ unrecognised value is *no opinion* rather than a silent negative.
+* The docker runtime state is part of container evaluation: a runtime reporting
+ error/degraded downgrades its containers and is never invented for a container
+ the runtime does not report at all.
+* No fabricated data. No source ⇒ ``status "unknown"`` + ``statusSource.kind
+ "unknown"``. Metrics that were never specified stay ``None``. A manual
+ observation is never presented as a monitored production value.
+* No I/O here: ``build_service_entries`` is pure (payloads are passed in), so
+ every mapping rule is unit-testable without network access.
+
+Slice-1 live sources (all read-only, no new privilege): TKC ``GET /status``
+(container inventory, PostgreSQL/Milvus/Neo4j, systemd state), the aggregator's
+own MCP/Gateway probes, Hermes ``/v1/health`` (unauthenticated by design), and
+``statvfs`` on the backup mountpoint.
+
+Health 2.0 adds a second, strictly evidence-based dimension next to the unchanged
+legacy ``status`` field:
+
+* ``health`` (healthy/degraded/unhealthy/unknown) is only ``healthy`` when a real
+ check produced a FRESH success. A fixed literal is never a measurement
+ (``constant_value``), a missing source is never a green (``no_probe_source``),
+ and an observation past the freshness bound degrades to ``unknown``
+ (``stale_evidence``) instead of lingering as healthy.
+* Every value carries its provenance (``healthSource``), the observation and last
+ success timestamps (``lastChecked``/``lastSuccess``) and a machine-readable
+ ``healthReasonCode``, so a timeout (``probe_timeout``), an unreachable endpoint
+ (``probe_unreachable``), a bad status code (``probe_http_error``) and a check
+ that never ran (``no_probe_source``/``constant_value``) stay distinguishable.
+* ``operationalMode`` (normal/maintenance) is a THIRD, independent dimension.
+ Maintenance never rewrites health: a service in maintenance keeps its measured
+ value. Declared ``MAINTENANCE_PERIODS`` and the scheduled ``MAINTENANCE_WINDOWS``
+ are evaluated against the clock, so an expired window returns to ``normal`` by
+ itself — no persistence and no write API are involved.
+
+``status`` stays exactly as it was: same vocabulary, same combination rules, so
+every existing client keeps working. Health 2.0 is purely additive.
+"""
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from datetime import datetime, timedelta, timezone
+from typing import Any, Optional
+
+SERVICE_STATUS_VALUES = ("ok", "degraded", "error", "unknown")
+SERVICE_KINDS = ("container", "unit", "process", "runtime", "api", "storage")
+SERVICE_STATES = ("existing", "planned")
+INSTALL_STATES = ("installed", "not_installed", "unknown")
+ARCHITECTURE_STATES = ("canonical", "manual_verified", "inferred", "unknown")
+EVIDENCE_CLASSES = ("machine_observed", "operator_provided")
+
+# ── Health 2.0 vocabulary ────────────────────────────────────────────────────
+#: The mandated health vocabulary. Deliberately NOT identical to the legacy
+#: `status` vocabulary: `status` is the combined operational dimension that
+#: existing clients already consume and must keep, `health` is the strict
+#: evidence dimension layered on top of it.
+HEALTH_VALUES = ("healthy", "degraded", "unhealthy", "unknown")
+
+#: Operational mode — an independent dimension, never a health value.
+OPERATIONAL_MODES = ("normal", "maintenance")
+
+#: How the value of an entry is produced. "constant" marks a literal that used to
+#: look like a measurement; it can never be reported as healthy.
+HEALTH_EVIDENCE_KINDS = ("probe", "constant", "none")
+
+#: Machine-readable reason codes. Text keeps the human detail; the code is what
+#: makes "timeout", "probe failed", "stale" and "never checked" distinguishable.
+HEALTH_REASON_CODES = (
+ "healthy_evidence",
+ "degraded_evidence",
+ "check_failed",
+ "probe_timeout",
+ "probe_unreachable",
+ "probe_http_error",
+ "stale_evidence",
+ "no_evidence",
+ "no_probe_source",
+ "constant_value",
+ "not_deployed",
+ "dependency_unhealthy",
+ # container evidence (Docker status strings from TKC /status)
+ "runtime_only",
+ "container_unhealthy",
+ "container_exited",
+ "container_restarting",
+ "container_paused",
+ "container_created",
+ "container_dead",
+ # backup job evidence (systemd properties of the backup unit)
+ "backup_success",
+ "backup_failed",
+ "backup_running",
+ "backup_stale",
+ "backup_never_ran",
+ "storage_not_mounted",
+)
+
+#: 1:1 table from the legacy status vocabulary onto the health vocabulary — a
+#: table (not inline literals) so the two vocabularies cannot drift apart.
+_STATUS_TO_HEALTH = {"ok": "healthy", "degraded": "degraded",
+ "error": "unhealthy", "unknown": "unknown"}
+
+#: Age beyond which an observation is no longer evidence. The caller passes the
+#: effective bound; this default keeps the pure builder usable on its own.
+DEFAULT_HEALTH_MAX_AGE_SECONDS = 90
+
+#: Canonical ID format, validated on the detail route.
+SERVICE_ID_RE = re.compile(r"^[a-z0-9-]+__[a-z][a-z0-9-]*$")
+
+SRC_TKC_STATUS = "tkc_status"
+SRC_PROBE = "tars_status_probe"
+SRC_HERMES_API = "hermes_api"
+SRC_FILESYSTEM = "filesystem"
+SRC_NONE = "unknown"
+SRC_IN_PROCESS = "in_process"
+SRC_SYSTEMD = "systemd"
+
+_OK = ("online", "ok", "healthy", "active")
+_ERROR = ("offline", "error", "down")
+_DEGRADED = ("degraded", "yellow")
+
+
+def normalise_status(raw: Any) -> str:
+ """Map an upstream status string onto the canonical wire vocabulary."""
+ if not isinstance(raw, str):
+ return "unknown"
+ value = raw.strip().lower()
+ if value in _OK:
+ return "ok"
+ if value in _ERROR:
+ return "error"
+ if value in _DEGRADED:
+ return "degraded"
+ return "unknown"
+
+
+#: TKC reports two dimensions per item: `state` (online/active/…) and `health`
+#: (green/yellow/red). Only `state` used to be read, so a subsystem that TKC
+#: flagged yellow was rendered as "ok" — a false green. Both are evaluated now.
+_HEALTH_IDENTITY = {"green": "ok", "yellow": "degraded", "red": "error"}
+
+#: Severity used to combine evidence. `unknown` is deliberately absent: absence
+#: of evidence is never escalated into a specific claim.
+_DEFECT = {"degraded": 1, "error": 2}
+
+
+def health_status(raw: Any) -> str:
+ """Map a TKC `health` value onto the canonical vocabulary.
+
+ Unrecognised values fall back to the state vocabulary and, if they stay
+ unrecognised, to "unknown" = *no opinion* (never a silent negative).
+ """
+ if not isinstance(raw, str):
+ return "unknown"
+ value = raw.strip().lower()
+ if value in _HEALTH_IDENTITY:
+ return _HEALTH_IDENTITY[value]
+ return normalise_status(value)
+
+
+def combine_state_and_health(item: Any) -> str:
+ """Combine TKC `state` and `health` conservatively.
+
+ Rules:
+ * `state` is the base. An unrecognised/missing state stays "unknown" and is
+ never upgraded by a green health.
+ * `health` may only make things worse: yellow -> degraded, red -> error.
+ * A missing or unrecognised health is *no opinion* — it neither degrades nor
+ upgrades. It stays visible in ``statusDetail`` instead of being hidden.
+ """
+ if not isinstance(item, dict):
+ return "unknown"
+
+ state_status = normalise_status(item.get("state"))
+ if state_status == "unknown":
+ return "unknown"
+
+ health = health_status(item.get("health"))
+ if health in _DEFECT and _DEFECT[health] > _DEFECT.get(state_status, 0):
+ return health
+ return state_status
+
+
+def health_from_status(status: str) -> str:
+ """Map the legacy status vocabulary onto the health vocabulary."""
+ return _STATUS_TO_HEALTH.get(status, "unknown")
+
+
+def _parse_iso(value: Any) -> Optional[datetime]:
+ """Parse an ISO-8601 timestamp; None when it is absent or unparsable."""
+ if not isinstance(value, str) or not value.strip():
+ return None
+ try:
+ parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Operational mode — declared periods and the existing scheduled windows
+# ─────────────────────────────────────────────────────────────────────────────
+
+def _groups_for(spec_id: str) -> list[str]:
+ """Named groups a service belongs to (scope vocabulary of a window)."""
+ return sorted(name for name, members in SERVICE_GROUPS.items() if spec_id in members)
+
+
+def _period_scope(period: dict) -> tuple[set, list]:
+ """(explicit ids + group members, group names) addressed by one period."""
+ ids = set(period.get("services") or ())
+ groups = list(period.get("groups") or ())
+ for name in groups:
+ ids.update(SERVICE_GROUPS.get(name, ()))
+ if period.get("service"):
+ ids.add(str(period["service"]))
+ return ids, groups
+
+
+#: "<dow> *-*-* HH:MM:SS <TZ>" — the only onCalendar form the registry declares.
+#: Anything else is treated as "no opinion" rather than as an ongoing outage.
+_ONCALENDAR_RE = re.compile(
+ r"^(?P<dow>[a-z]{3})\s+\*-\*-\*\s+(?P<h>\d{2}):(?P<m>\d{2}):(?P<s>\d{2})\s+(?P<tz>[a-z]{3,4})$"
+)
+_DOW = {"mon": 0, "tue": 1, "wed": 2, "thu": 3, "fri": 4, "sat": 5, "sun": 6}
+
+
+def _scheduled_occurrence(window: dict, now: datetime) -> Optional[tuple[datetime, datetime]]:
+ """(start, end) of the most recent occurrence at/before *now*, or None.
+
+ None means "not evaluated" — an unsupported schedule or a missing duration is
+ never rendered as an active maintenance window.
+ """
+ match = _ONCALENDAR_RE.match(str(window.get("onCalendar", "")).strip().lower())
+ if not match or match.group("tz") != "utc":
+ return None
+ duration = window.get("maxDurationSeconds")
+ if not isinstance(duration, int) or duration <= 0:
+ return None
+
+ now_utc = now.astimezone(timezone.utc)
+ start = now_utc.replace(hour=int(match.group("h")), minute=int(match.group("m")),
+ second=int(match.group("s")), microsecond=0)
+ start -= timedelta(days=(start.weekday() - _DOW[match.group("dow")]) % 7)
+ if start > now_utc:
+ start -= timedelta(days=7)
+ return start, start + timedelta(seconds=duration)
+
+
+def maintenance_for(spec_id: str, *, now: datetime, windows: Any = None,
+ periods: Any = None) -> Optional[dict]:
+ """Effective operational-mode information for one service at *now*.
+
+ Declared periods win over scheduled windows. A period that has not started yet
+ is reported with ``active: False`` (upcoming maintenance), one that has ended is
+ dropped — that is the automatic return to ``normal``, derived from the clock and
+ therefore needing neither persistence nor a write API. Returns None when no
+ window applies, so the caller can emit an explicit null.
+ """
+ periods = MAINTENANCE_PERIODS if periods is None else periods
+ windows = MAINTENANCE_WINDOWS if windows is None else windows
+
+ for period in periods:
+ ids, groups = _period_scope(period)
+ if spec_id not in ids:
+ continue
+ start = _parse_iso(period.get("startsAt"))
+ end = _parse_iso(period.get("endsAt"))
+ if start is None or (end is not None and now >= end):
+ continue
+ return {
+ "active": start <= now,
+ "windowId": str(period.get("id", "")),
+ "kind": "declared",
+ "reason": str(period.get("reason") or "declared maintenance window"),
+ "startsAt": start.isoformat(),
+ "endsAt": end.isoformat() if end else None,
+ "groups": groups,
+ "role": "source" if period.get("service") == spec_id else "impacted",
+ "sourceService": period.get("service"),
+ }
+
+ for window in windows:
+ if window.get("service") != spec_id and spec_id not in (window.get("expectedImpact") or ()):
+ continue
+ bounds = _scheduled_occurrence(window, now)
+ if bounds is None:
+ continue
+ start, end = bounds
+ if not (start <= now < end):
+ continue
+ # A calendar plan is NOT evidence that maintenance is running. The window
+ # stays visible as planned metadata, but the operational mode stays
+ # "normal" until an explicit declaration says otherwise.
+ return {
+ "active": False,
+ "windowId": str(window.get("id", "")),
+ "kind": "scheduled",
+ "evidence": "calendar_plan",
+ "reason": (f"planned maintenance window: "
+ f"{window.get('timer') or window.get('id')} (not confirmed active)"),
+ "startsAt": start.isoformat(),
+ "endsAt": end.isoformat(),
+ "groups": _groups_for(spec_id),
+ "role": "source" if window.get("service") == spec_id else "impacted",
+ "sourceService": window.get("service"),
+ }
+
+ return None
+
+
+def _evidence_health(spec: "ServiceSpec", *, status: str, detail: Optional[str],
+ now: datetime, max_age_seconds: Optional[int],
+ error_kind: Optional[str],
+ last_checked: Optional[str],
+ runtime_only: bool = False) -> tuple[str, str, Optional[str]]:
+ """(health, reasonCode, reason) — the strict evidence evaluation.
+
+ Order matters: "not deployed" and "no source" outrank everything, a constant
+ outranks any value, freshness outranks a success, a recorded failure outranks
+ the (unknown) value, and only then does the measured value decide.
+ """
+ if spec.state == "planned":
+ return "unknown", "not_deployed", detail or "planned — not deployed"
+ if spec.install_state == "not_installed":
+ return "unknown", "not_deployed", detail or "not installed"
+ if spec.source == SRC_NONE:
+ return "unknown", "no_probe_source", detail or "no read-only source for this service"
+
+ if spec.health_evidence == "constant":
+ return ("unknown", "constant_value",
+ "no independent check: this entry's value is a fixed constant, not a measurement")
+
+ if last_checked:
+ observed = _parse_iso(last_checked)
+ if observed is not None and max_age_seconds is not None:
+ age = (now - observed).total_seconds()
+ if age > max_age_seconds:
+ return ("unknown", "stale_evidence",
+ f"evidence is {int(age)}s old (limit {max_age_seconds}s)")
+
+ if runtime_only:
+ # The container runs, but Docker has no healthcheck for it: that is a
+ # positive runtime proof, NOT a functional test. Never "healthy".
+ return ("unknown", "runtime_only",
+ "container running; no Docker healthcheck — runtime evidence only")
+
+ if error_kind:
+ code = error_kind if error_kind in HEALTH_REASON_CODES else "check_failed"
+ if status == "error":
+ return "unhealthy", code, detail or "check failed"
+ return "unknown", code, detail or "no evidence: the upstream check failed"
+
+ if status == "ok":
+ return "healthy", "healthy_evidence", detail
+ if status == "degraded":
+ return "degraded", "degraded_evidence", detail
+ if status == "error":
+ return "unhealthy", "check_failed", detail or "check failed"
+ return "unknown", "no_evidence", detail or "no usable evidence"
+
+
+def _evidence_key(spec: "ServiceSpec") -> Optional[str]:
+ """Key under which main.py records the failure kind of the last probe."""
+ if spec.source == SRC_TKC_STATUS:
+ return "tkc_status"
+ if spec.source in (SRC_PROBE, SRC_HERMES_API):
+ return spec.probe_key
+ return None
+
+
+#: TKC /status paths of the knowledge subsystems (used by /status and /services
+#: so both endpoints can never disagree about the same subsystem).
+SUBSYSTEM_ITEMS: dict[str, tuple[str, ...]] = {
+ "postgresql": ("knowledge", "postgresql"),
+ "milvus": ("knowledge", "milvus"),
+ "neo4j": ("knowledge", "neo4j"),
+}
+
+
+def subsystem_status(tkc_status: Any, name: str) -> Optional[str]:
+ """Combined status of one knowledge subsystem.
+
+ Returns None when the /status payload is unusable, so the caller can keep its
+ previous (/health-derived) value instead of guessing.
+ """
+ if not isinstance(tkc_status, dict) or not isinstance(tkc_status.get("knowledge"), dict):
+ return None
+ path = SUBSYSTEM_ITEMS.get(name)
+ if not path:
+ return None
+ item = _dig(tkc_status, path)
+ return combine_state_and_health(item) if item is not None else "unknown"
+
+
+@dataclass(frozen=True)
+class ServiceSpec:
+ """One logical service; physical identities are attributes, not the identity."""
+
+ id: str # "<host_slug>__<service_slug>"
+ label: str
+ kind: str
+ source: str = SRC_NONE
+ probe_key: str | None = None # mcp | gateway | hermes | self
+ container: str | None = None # docker container name (join key)
+ unit: str | None = None # primary systemd unit (join key)
+ extra_units: tuple[str, ...] = ()
+ endpoint: str | None = None # informational; never contacted here
+ state: str = "existing"
+ install_state: str = "unknown"
+ architecture_state: str = "unknown"
+ architecture_source_kind: str = "unknown"
+ architecture_reference: str = ""
+ evidence_class: str = "machine_observed"
+ tkc_item: tuple[str, ...] = () # path into the TKC /status payload
+ depends_on: tuple[tuple[str, str, str], ...] = () # (target, evidence, confidence)
+ maintenance_role: str | None = None # "source" | "impacted"
+ #: Health 2.0 evidence class: "probe" (a real check produced the value),
+ #: "constant" (the value is a fixed literal) or "none" (no read-only source).
+ #: Declared on the spec so a placeholder can never be rendered as a measurement.
+ health_evidence: str = "probe"
+
+
+SERVICES: tuple[ServiceSpec, ...] = (
+ # ── knowledge core (containers on TON-01) ───────────────────────────────
+ ServiceSpec("ton-01__tkc-service", "TKC Service", "unit", SRC_TKC_STATUS,
+ unit="tkc-service.service", endpoint="http://10.10.10.5:8110",
+ architecture_state="canonical", architecture_source_kind="tars_docs",
+ architecture_reference="docs/brain/Knowledge-Core.md",
+ tkc_item=("services", "tkc_service"), maintenance_role="impacted"),
+ ServiceSpec("ton-01__postgresql", "PostgreSQL", "container", SRC_TKC_STATUS,
+ container="tkc-postgres", architecture_state="canonical",
+ architecture_source_kind="tars_docs",
+ architecture_reference="docs/brain/Knowledge-Core.md",
+ tkc_item=("knowledge", "postgresql")),
+ ServiceSpec("ton-01__milvus", "Milvus", "container", SRC_TKC_STATUS,
+ container="milvus-standalone", architecture_state="canonical",
+ architecture_source_kind="tars_docs",
+ architecture_reference="docs/brain/Knowledge-Core.md",
+ tkc_item=("knowledge", "milvus"), maintenance_role="impacted",
+ depends_on=(
+ ("ton-01__milvus-etcd",
+ "co-located containers in TKC /status → services.docker.containers",
+ "inferred"),
+ ("ton-01__milvus-minio",
+ "co-located containers in TKC /status → services.docker.containers",
+ "inferred"),
+ )),
+ ServiceSpec("ton-01__milvus-etcd", "Milvus etcd", "container", SRC_TKC_STATUS,
+ container="milvus-etcd", architecture_state="canonical",
+ architecture_source_kind="tars_docs",
+ architecture_reference="docs/brain/Knowledge-Core.md (Milvus derived store)",
+ maintenance_role="impacted"),
+ ServiceSpec("ton-01__milvus-minio", "Milvus MinIO", "container", SRC_TKC_STATUS,
+ container="milvus-minio", architecture_state="canonical",
+ architecture_source_kind="tars_docs",
+ architecture_reference="docs/brain/Knowledge-Core.md (Milvus derived store)",
+ maintenance_role="impacted"),
+ ServiceSpec("ton-01__neo4j", "Neo4j", "container", SRC_TKC_STATUS,
+ container="tkc-neo4j", architecture_state="canonical",
+ architecture_source_kind="tars_docs",
+ architecture_reference="docs/brain/Knowledge-Core.md",
+ tkc_item=("knowledge", "neo4j"), maintenance_role="impacted"),
+ # ── platform runtime ────────────────────────────────────────────────────
+ ServiceSpec("ton-01__docker", "Docker", "runtime", SRC_TKC_STATUS,
+ architecture_state="canonical", architecture_source_kind="node_registry",
+ architecture_reference="nodes/ton-01/node.yaml (services)",
+ tkc_item=("services", "docker")),
+ ServiceSpec("ton-01__portainer", "Portainer", "container", SRC_TKC_STATUS,
+ container="portainer", endpoint="https://10.10.10.5:9443",
+ architecture_state="canonical", architecture_source_kind="node_registry",
+ architecture_reference="nodes/ton-01/node.yaml (services) + "
+ "stacks/infrastructure/compose.yml",
+ maintenance_role="impacted"),
+ ServiceSpec("ton-01__tars-interaction-runtime", "Interaction Runtime", "unit", SRC_NONE,
+ unit="tars-web-runtime.service", endpoint="http://10.10.10.5:8767",
+ architecture_state="canonical", architecture_source_kind="tars_docs",
+ architecture_reference="deploy/DEPLOY.md (tars-web-runtime.service / :8767)"),
+ ServiceSpec("ton-01__tars-status", "tars-status", "unit", SRC_PROBE, probe_key="self",
+ # The self entry is produced from a literal ("serving this request").
+ # That proves this process answered — it is NOT a check of this
+ # service's dependencies, so health must stay "unknown".
+ health_evidence="constant",
+ unit="tars-status.service", endpoint="http://10.10.10.5:8120",
+ architecture_state="canonical", architecture_source_kind="tars_docs",
+ architecture_reference="TARS-HUMAN-INTERFACE-ARCHITECTURE.md (EXISTS :8120)"),
+ ServiceSpec("ton-01__tars-admin", "tars-admin", "unit", SRC_NONE,
+ unit="tars-admin.service", endpoint="http://10.10.10.5:8901",
+ architecture_state="canonical", architecture_source_kind="tars_docs",
+ architecture_reference="TARS-ADMIN-ARCHITECTURE.md"),
+ ServiceSpec("ton-01__engineering-gateway", "Engineering Gateway", "api", SRC_PROBE,
+ probe_key="gateway", endpoint="http://10.10.10.5:8080",
+ architecture_state="canonical", architecture_source_kind="node_registry",
+ architecture_reference="nodes/ton-01/node.yaml (gateway.service = tars-gateway)"),
+ ServiceSpec("ton-01__mcp-server", "MCP Server", "api", SRC_PROBE, probe_key="mcp",
+ endpoint="http://127.0.0.1:8765", architecture_state="manual_verified",
+ architecture_source_kind="manual",
+ architecture_reference="probed by tars-status (MCP_HEALTH_URL); "
+ "not in docs/brain/Nodes.md"),
+ ServiceSpec("ton-01__hermes", "Hermes Agent", "unit", SRC_HERMES_API, probe_key="hermes",
+ unit="hermes-gateway.service", endpoint="http://127.0.0.1:8642",
+ architecture_state="manual_verified", architecture_source_kind="manual",
+ architecture_reference="session/architecture notes; no explicit "
+ "TON-01<->Hermes doc line found"),
+ # ── backup ──────────────────────────────────────────────────────────────
+ ServiceSpec("ton-01__borgbackup", "BorgBackup", "unit",
+ # Deliberately NO live source: repository and job scripts are
+ # root-only and the job logs to the system journal, which the
+ # service user cannot read. Until a deliberately readable status
+ # file exists (Slice S5c) every runtime metric stays None and the
+ # status stays "unknown" — a successful *manual* run must not be
+ # dressed up as a monitored production result.
+ SRC_SYSTEMD, unit="tars-borg-daily.service",
+ extra_units=("tars-borg-daily.timer", "tars-borg-weekly.service",
+ "tars-borg-weekly.timer"),
+ state="existing", install_state="installed",
+ architecture_state="manual_verified", architecture_source_kind="manual",
+ architecture_reference="user mandate 2026-11-06 "
+ "(Cosmos Service Drill-down Addendum)",
+ evidence_class="operator_provided", maintenance_role="source"),
+ ServiceSpec("ton-01__backup-storage", "Backup Storage", "storage", SRC_FILESYSTEM,
+ architecture_state="manual_verified", architecture_source_kind="manual",
+ architecture_reference="verified device facts: lsblk/mount/df on TON-01"),
+ # ── remote nodes (declared in NODES, no local source) ───────────────────
+ ServiceSpec("vps__endpoints", "Public Endpoints", "api", SRC_NONE,
+ architecture_state="inferred", architecture_source_kind="tars_docs",
+ architecture_reference="deploy/DEPLOY.md (deploy target, not in Nodes.md)"),
+ ServiceSpec("laptop__ollama", "Ollama", "api", SRC_NONE,
+ endpoint="http://192.168.2.191:11434", architecture_state="unknown",
+ architecture_source_kind="unknown",
+ architecture_reference="not reachable from TON-01; home network only"),
+)
+
+#: Static per-service detail that is not a live metric.
+SERVICE_DETAIL: dict[str, dict[str, Any]] = {
+ "ton-01__postgresql": {
+ "components": [
+ {"name": "container", "value": "tkc-postgres"},
+ {"name": "roles", "value": "role 'tkc' (DSN target); no CREATE ROLE/GRANT is "
+ "versioned in any readable repo"},
+ ],
+ "databases": [
+ {"name": "tkc", "purpose": "production", "state": "existing",
+ "architectureState": "canonical",
+ "evidence": "TKC_POSTGRES_DSN target in migrations 001-004; 101 objects reported live"},
+ {"name": "tkc_dev", "purpose": "development", "state": "planned",
+ "architectureState": "unknown",
+ "evidence": "zero hits in tars-tkc / tars-platform / tars-docs"},
+ {"name": "tkc_backup", "purpose": "restore testing", "state": "existing",
+ "architectureState": "manual_verified", "evidenceClass": "operator_provided",
+ "evidence": "operator-reported successful restore test; not machine-verifiable"},
+ ],
+ "notes": ["version 'PostgreSQL 17' is operator-provided; no readable source reports the "
+ "version (the Docker API is not accessible to the status service)"],
+ },
+ "ton-01__borgbackup": {
+ "components": [
+ {"name": "package", "value": "borgbackup 1.2.8-1 (noble/universe), installed"},
+ {"name": "repository", "value": "/backup/tars-tkc/borg"},
+ {"name": "staging", "value": "/var/tmp (cold copy of stopped container data)"},
+ ],
+ "repository": {
+ "path": "/backup/tars-tkc/borg",
+ "state": "existing",
+ "inspectable": False,
+ "inspectableReason": "/backup/tars-tkc is drwx------ root:root; no read-only "
+ "inspection path exists for the status service",
+ },
+ # Static facts read from the deployed unit files (world-readable).
+ "schedule": [
+ {"unit": "tars-borg-daily.timer", "kind": "online",
+ "onCalendar": "*-*-* 02:00:00", "timezone": "host (UTC)", "enabled": True,
+ "nextScheduledRun": None, "lastTriggeredRun": None},
+ {"unit": "tars-borg-weekly.timer", "kind": "cold",
+ "onCalendar": "Sun *-*-* 03:00:00 UTC", "timezone": "UTC", "enabled": True,
+ "nextScheduledRun": None, "lastTriggeredRun": None},
+ ],
+ "encryption": {
+ "enabled": False, "reason": "explicit user request", "verified": False,
+ "note": "no encryption/passphrase artefact exists in any readable script copy; the "
+ "initialised repository is not inspectable, so 'none' is intended, not proven",
+ },
+ "retention": None,
+ "lastSuccessfulRun": None,
+ "nextScheduledRun": None,
+ "restoreVerification": None,
+ "offHostCopy": {"present": False, "planned": ["second USB drive"]},
+ "notes": [
+ "timers are enabled and armed but have NEVER triggered (LastTriggerUSec empty on "
+ "both); next runs were 2026-11-07 02:00 UTC and 2026-11-08 03:00 UTC at check time",
+ "one MANUAL first run succeeded on 2026-11-06 14:43-14:50 (archive "
+ "daily-2026-11-06T144320Z; 296769 files; 24.86 GB original -> 7.12 GB deduplicated) "
+ "and ended with metadata verification SUCCESS — an observation from a development "
+ "log, not a monitored metric, hence lastSuccessfulRun stays None",
+ "metadata verification (borg check --verify-data) is NOT a restore test",
+ "a restore-test area exists at /var/tmp/tars-borg-restore-test but is root-only, so "
+ "its outcome is unverifiable and restoreVerification stays None",
+ "retention was never specified (no --keep-* / prune logic exists in any readable "
+ "copy); no numbers are invented here",
+ "the weekly job stops tkc-service, tkc-historian.timer and five containers for up to "
+ "TimeoutStartSec=6h — see maintenanceWindow",
+ ],
+ },
+ "ton-01__backup-storage": {
+ "components": [
+ {"name": "device", "value": "/dev/sda1"},
+ {"name": "deviceModel", "value": "Samsung SSD 850"},
+ {"name": "filesystem", "value": "ext4"},
+ {"name": "mount", "value": "/backup"},
+ ],
+ "notes": ["backup storage is a filesystem, NOT a third PostgreSQL database",
+ "/backup/tars-tkc contents are root-only and are never read by this service"],
+ },
+}
+
+#: Maintenance windows are METADATA; they never change `status`.
+MAINTENANCE_WINDOWS: tuple[dict[str, Any], ...] = (
+ {
+ "id": "mw-borg-weekly",
+ "service": "ton-01__borgbackup",
+ "timer": "tars-borg-weekly.timer",
+ "onCalendar": "Sun *-*-* 03:00:00 UTC",
+ "timezone": "UTC",
+ "maxDurationSeconds": 21600, # TimeoutStartSec=6h
+ "state": "enabled",
+ "active": None, # Slice 1b (excluded) would compute this live
+ "expectedImpact": (
+ "ton-01__tkc-service", "ton-01__milvus", "ton-01__milvus-etcd",
+ "ton-01__milvus-minio", "ton-01__neo4j", "ton-01__portainer",
+ ),
+ "source": {
+ "kind": "manifest",
+ "reference": "/etc/systemd/system/tars-borg-weekly.service "
+ "(+ .d/execute.conf), tars-borg-weekly.timer",
+ },
+ "note": "planned outage; MUST NOT be rendered or derived as a health state",
+ },
+)
+
+#: Named service groups — the scope vocabulary for maintenance periods, so a
+#: period addresses a defined set instead of an ad-hoc id list.
+SERVICE_GROUPS: dict[str, tuple[str, ...]] = {
+ "knowledge-core": ("ton-01__tkc-service", "ton-01__postgresql", "ton-01__milvus",
+ "ton-01__milvus-etcd", "ton-01__milvus-minio", "ton-01__neo4j"),
+ "platform-runtime": ("ton-01__docker", "ton-01__portainer",
+ "ton-01__tars-interaction-runtime", "ton-01__tars-status",
+ "ton-01__tars-admin", "ton-01__engineering-gateway",
+ "ton-01__mcp-server", "ton-01__hermes"),
+ "backup": ("ton-01__borgbackup", "ton-01__backup-storage"),
+ "remote-nodes": ("vps__endpoints", "laptop__ollama"),
+}
+
+#: Declared maintenance periods — the writable-by-hand half of the operational
+#: mode. Deliberately EMPTY: nothing is in maintenance unless a human declares it
+#: here (a code change, i.e. via the normal Engineering Change Lifecycle). A
+#: period is
+#: {"id", "reason", "startsAt", "endsAt"?, "services"? , "groups"?, "service"?}
+#: with ISO-8601 UTC timestamps; an omitted "endsAt" runs until it is edited, an
+#: expired one returns to "normal" by itself. No new persistence, no write API.
+MAINTENANCE_PERIODS: tuple[dict[str, Any], ...] = ()
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Pure shaping
+# ─────────────────────────────────────────────────────────────────────────────
+
+def _dig(payload: Any, path: tuple[str, ...]) -> Any:
+ current = payload
+ for key in path:
+ if not isinstance(current, dict):
+ return None
+ current = current.get(key)
+ return current
+
+
+def _status_source(spec: ServiceSpec, *,
+ has_evidence: bool = True) -> dict[str, str]:
+ """Where this entry's value comes from — the honest attribution.
+
+ ``has_evidence`` lets a declared source degrade to ``unknown`` when this
+ cycle read nothing from it: a spec that *names* systemd is not the same as
+ a measurement taken from systemd.
+ """
+ if spec.source == SRC_TKC_STATUS:
+ if spec.container and not spec.tkc_item:
+ return {"kind": "tkc_status",
+ "reference": f"TKC GET /status → services.docker.containers[{spec.container}]"}
+ if spec.tkc_item:
+ return {"kind": "tkc_status",
+ "reference": "TKC GET /status → " + ".".join(spec.tkc_item)}
+ return {"kind": "tkc_status", "reference": "TKC GET /status"}
+ if spec.source == SRC_PROBE:
+ if spec.probe_key == "self":
+ return {"kind": SRC_IN_PROCESS,
+ "reference": "the request itself (this process answered it)"}
+ return {"kind": "tars_status", "reference": f"tars-status probe of {spec.label}"}
+ if spec.source == SRC_HERMES_API:
+ return {"kind": "hermes_api", "reference": "Hermes GET /v1/health (unauthenticated)"}
+ if spec.source == SRC_FILESYSTEM:
+ return {"kind": "filesystem", "reference": "statvfs on the backup mountpoint"}
+ if spec.source == SRC_SYSTEMD:
+ if not has_evidence:
+ return {"kind": "unknown",
+ "reference": "declared systemd unit " + (spec.unit or "")
+ + " was not read in this cycle"}
+ return {"kind": "systemd",
+ "reference": "systemctl show " + (spec.unit or "") + " (+ timer)"}
+ return {"kind": "unknown", "reference": "no read-only source for this service"}
+
+
+def _apply_runtime(runtime_status: str, status: str,
+ detail: Optional[str]) -> tuple[str, Optional[str]]:
+ """Let the docker runtime make an entry look WORSE, never better.
+
+ A runtime that reports degraded/error downgrades container evidence taken
+ from the container list, so a broken runtime can no longer coexist with
+ containers rendered "ok". It never *escalates* an unreported container into a
+ concrete failure: absence of evidence stays "unknown" instead of becoming an
+ invented container state.
+ """
+ if status == "unknown" or runtime_status not in _DEFECT:
+ return status, detail
+ if _DEFECT[runtime_status] > _DEFECT.get(status, 0):
+ note = f"docker runtime: {runtime_status}"
+ return runtime_status, f"{detail} ({note})" if detail else note
+ return status, detail
+
+
+def _container_evidence(docker: Any, container: str) -> dict[str, Any]:
+ """Parse one container status string from TKC /status — without guessing.
+
+ TKC reports Docker's human status line, not a structured object:
+ "Up 3 hours (healthy)" running + healthcheck healthy
+ "Up 3 hours (unhealthy)" running + healthcheck failed
+ "Up 3 hours (health: starting)" running, healthcheck not decided
+ "Up 3 hours" running, NO healthcheck configured
+ "Exited (1) 2 hours ago" exited, exit code 1
+ "Restarting (1) 5 seconds ago" crash loop
+ "Paused" / "Created" / "Dead"
+
+ ``state`` is the Docker lifecycle state, ``healthcheck`` the parenthetical
+ marker (None when absent), ``exitCode`` parsed from "Exited (N)".
+ ``runtime_only`` is True for a running container WITHOUT a healthcheck:
+ that is a positive runtime proof, not a functional test.
+ """
+ result: dict[str, Any] = {
+ "present": False, "state": "absent", "healthcheck": None,
+ "exitCode": None, "raw": None, "runtime_only": False,
+ }
+ if not isinstance(docker, dict):
+ result["state"] = "no_runtime_section"
+ return result
+ containers = docker.get("containers")
+ if not isinstance(containers, dict):
+ result["state"] = "no_inventory"
+ return result
+
+ if container in containers:
+ raw = str(containers[container])
+ result.update(present=True, raw=raw)
+ lowered = raw.lower()
+ if lowered.startswith("up"):
+ result["state"] = "running"
+ elif lowered.startswith("exited"):
+ result["state"] = "exited"
+ elif lowered.startswith("restarting"):
+ result["state"] = "restarting"
+ elif lowered.startswith("paused"):
+ result["state"] = "paused"
+ elif lowered.startswith("created"):
+ result["state"] = "created"
+ elif lowered.startswith("dead"):
+ result["state"] = "dead"
+ else:
+ result["state"] = "unrecognised"
+
+ # healthcheck marker — only Docker writes this parenthetical
+ if "(unhealthy)" in lowered:
+ result["healthcheck"] = "unhealthy"
+ elif "(healthy)" in lowered:
+ result["healthcheck"] = "healthy"
+ elif "health: starting" in lowered or "(starting)" in lowered:
+ result["healthcheck"] = "starting"
+
+ # exit code from "Exited (1)" / "Exited (137)"
+ match = re.search(r"exited\s*\((\d+)\)", lowered)
+ if match:
+ result["exitCode"] = int(match.group(1))
+
+ result["runtime_only"] = (result["state"] == "running"
+ and result["healthcheck"] is None)
+ return result
+
+ missing = docker.get("missing_expected")
+ if isinstance(missing, list) and container in missing:
+ result.update(present=False, state="missing", raw=None)
+ return result
+ result["state"] = "not_listed"
+ return result
+
+
+def _container_status(docker: Any, container: str) -> tuple[str, Optional[str]]:
+ """Resolve one container against TKC's docker section. Never guesses."""
+ if not isinstance(docker, dict):
+ return "unknown", "TKC /status reports no docker runtime section"
+
+ containers = docker.get("containers")
+ if not isinstance(containers, dict):
+ return "unknown", "TKC /status reports no docker container inventory"
+
+ # Absent/unrecognised runtime state = no opinion, so it cannot flip a
+ # container that the runtime itself reports as running.
+ runtime = combine_state_and_health(docker)
+ evidence = _container_evidence(docker, container)
+ state = evidence["state"]
+
+ if state == "running":
+ # A running container without a healthcheck is runtime evidence only.
+ if evidence["healthcheck"] == "unhealthy":
+ return _apply_runtime(runtime, "error",
+ f"running, Docker healthcheck unhealthy ({evidence['raw']})")
+ if evidence["healthcheck"] == "starting":
+ return _apply_runtime(runtime, "unknown",
+ f"running, Docker healthcheck starting ({evidence['raw']})")
+ return _apply_runtime(runtime, "ok", str(evidence["raw"]))
+
+ if state in ("exited", "dead"):
+ return _apply_runtime(runtime, "error", str(evidence["raw"]))
+ if state == "restarting":
+ return _apply_runtime(runtime, "error", f"crash loop ({evidence['raw']})")
+ if state in ("paused", "created", "unrecognised", "not_listed"):
+ # A container the runtime does not list has no raw status line; never
+ # render the string "None" as if it were Docker's own wording.
+ if evidence["raw"] is None:
+ text = {
+ "not_listed": "container not reported by the TKC docker runtime",
+ "paused": "container is paused",
+ "created": "container created but never started",
+ "unrecognised": "container status line not understood",
+ }[state]
+ return _apply_runtime(runtime, "unknown", text)
+ return _apply_runtime(runtime, "unknown", str(evidence["raw"]))
+ if state == "missing":
+ return _apply_runtime(runtime, "error",
+ "expected container is not running (TKC missing_expected)")
+ return _apply_runtime(runtime, "unknown",
+ "container not reported by the TKC docker runtime")
+
+
+def _item_detail(item: dict) -> Optional[str]:
+ """Human-readable evidence of one TKC item.
+
+ `state` and `health` come first: the raw values must stay visible so a
+ downgraded or unrecognised health is traceable in the UI instead of being
+ silently swallowed by the status mapping.
+ """
+ parts = []
+ for key in ("state", "health"):
+ if item.get(key) is not None:
+ parts.append(f"{key}={item[key]}")
+ for key in ("knowledge_objects", "project_memories", "nodes", "relationships"):
+ if item.get(key) is not None:
+ parts.append(f"{key}={item[key]}")
+ if isinstance(item.get("collections"), list):
+ parts.append(f"collections={len(item['collections'])}")
+ if isinstance(item.get("containers"), dict):
+ parts.append(f"containers={len(item['containers'])}")
+ if isinstance(item.get("missing_expected"), list) and item["missing_expected"]:
+ parts.append("missing_expected=" + ",".join(str(x) for x in item["missing_expected"]))
+ if item.get("message"):
+ parts.append(str(item["message"]))
+ return ", ".join(parts) or None
+
+
+def _tkc_status(spec: ServiceSpec, tkc_status: Any,
+ tkc_error: Optional[str]) -> tuple[str, Optional[str]]:
+ if not isinstance(tkc_status, dict):
+ # The source exists; the data did not arrive. Keep the attribution and
+ # say why — never pretend healthy, never invent offline.
+ return "unknown", tkc_error or "TKC /status unavailable"
+
+ docker = _dig(tkc_status, ("services", "docker"))
+
+ runtime = combine_state_and_health(docker)
+
+ if spec.tkc_item:
+ item = _dig(tkc_status, spec.tkc_item)
+ if isinstance(item, dict) and item.get("state") is not None:
+ status = combine_state_and_health(item)
+ detail = _item_detail(item)
+ if spec.container:
+ # A real query result is surfaced, but it can no longer override a
+ # broken docker runtime (M4) — container evidence is downgraded.
+ status, detail = _apply_runtime(runtime, status, detail)
+ return status, detail
+ if spec.container:
+ return _container_status(docker, spec.container)
+ return "unknown", "field not reported by TKC /status"
+
+ if spec.container:
+ return _container_status(docker, spec.container)
+
+ return "unknown", "no mapping defined for this service"
+
+
+def _resolve_status(spec: ServiceSpec, *, tkc_status: Any, tkc_error: Optional[str],
+ probes: dict[str, Any],
+ backup_filesystem: Any = None) -> tuple[str, Optional[str]]:
+ # Inventory/installation beats every live source.
+ if spec.state == "planned":
+ return "unknown", "planned — not deployed"
+ if spec.install_state == "not_installed":
+ return "unknown", "not installed"
+
+ if spec.source == SRC_TKC_STATUS:
+ return _tkc_status(spec, tkc_status, tkc_error)
+
+ if spec.source in (SRC_PROBE, SRC_HERMES_API):
+ probe = probes.get(spec.probe_key)
+ if not isinstance(probe, dict):
+ return "unknown", "probe unavailable"
+ return normalise_status(probe.get("status")), probe.get("detail")
+
+ if spec.source == SRC_FILESYSTEM:
+ # A readable statvfs is real evidence — but only for "the mountpoint can
+ # be measured", never for "the backup succeeded". The detail says which.
+ if isinstance(backup_filesystem, dict):
+ mount = backup_filesystem.get("mount") or "mountpoint"
+ if backup_filesystem.get("mounted") is False:
+ return "error", f"expected device not mounted at {mount}"
+ if backup_filesystem.get("mounted") is True:
+ return "ok", f"{mount} mounted and readable (statvfs)"
+ return "ok", f"{mount} readable (statvfs); mount identity not measured"
+ return "unknown", "filesystem evidence unavailable for this read"
+
+ if spec.source == SRC_SYSTEMD:
+ # Filled in from the unit properties by build_service_entries; without
+ # readable properties the honest answer is "no evidence".
+ return "unknown", "systemd evidence unavailable for this read"
+
+ return "unknown", "no read-only source for this service"
+
+
+def build_service_entries(
+ *,
+ tkc_status: Any = None,
+ tkc_error: Optional[str] = None,
+ mcp: Any = None,
+ gateway: Any = None,
+ hermes: Any = None,
+ backup_filesystem: Any = None,
+ backup_job: Any = None,
+ checked_at: Optional[str] = None,
+ health_max_age_seconds: Optional[int] = None,
+ probe_error_kinds: Optional[dict] = None,
+ last_success: Optional[dict] = None,
+ maintenance_now: Optional[datetime] = None,
+) -> list[dict[str, Any]]:
+ """Shape registry + upstream payloads into /services entries.
+
+ Pure: no I/O, no network, one clock read (``checked_at`` is injectable for
+ deterministic tests). Every spec yields exactly one entry, in registry order.
+
+ Health 2.0 arguments (all optional — the previous call signature keeps working):
+ health_max_age_seconds freshness bound for an observation; None disables it
+ probe_error_kinds {evidence key: reason code} of the last probe round
+ last_success {service id: ISO timestamp} of the last healthy check
+ maintenance_now evaluation instant of the operational mode
+ """
+ timestamp = checked_at or datetime.now(tz=timezone.utc).isoformat()
+ now_dt = _parse_iso(timestamp) or datetime.now(tz=timezone.utc)
+ maintenance_at = maintenance_now or now_dt
+ if health_max_age_seconds is None:
+ health_max_age_seconds = DEFAULT_HEALTH_MAX_AGE_SECONDS
+ probe_error_kinds = probe_error_kinds or {}
+ last_success = last_success or {}
+
+ #: The instant TKC /status observed its own subsystems — real provenance for
+ #: every TKC-derived entry, instead of "when we happened to shape the payload".
+ tkc_observed_at = None
+ if isinstance(tkc_status, dict):
+ tkc_observed_at = tkc_status.get("generated_at")
+ probes = {"mcp": mcp, "gateway": gateway, "hermes": hermes,
+ "self": {"status": "ok", "detail": "serving this request"}}
+
+ entries: list[dict[str, Any]] = []
+
+ for spec in SERVICES:
+ status, detail = _resolve_status(
+ spec, tkc_status=tkc_status, tkc_error=tkc_error, probes=probes,
+ backup_filesystem=backup_filesystem,
+ )
+
+ # Hard invariant: nothing without a live source may look healthy.
+ if spec.source == SRC_NONE and status == "ok":
+ status, detail = "unknown", detail or "no read-only source for this service"
+
+ # Did this cycle actually READ the declared systemd unit? Only then may
+ # the payload attribute a value to "systemd".
+ systemd_evidence = False
+ if spec.source == SRC_SYSTEMD and isinstance(backup_job, dict):
+ systemd_evidence = _backup_job_status(backup_job, now=now_dt) is not None
+
+ entry: dict[str, Any] = {
+ "id": spec.id,
+ "label": spec.label,
+ "kind": spec.kind,
+ "status": status,
+ "statusDetail": detail,
+ "statusSource": _status_source(spec, has_evidence=systemd_evidence),
+ "state": spec.state,
+ "installState": spec.install_state,
+ "evidenceClass": spec.evidence_class,
+ "architecture": {
+ "state": spec.architecture_state,
+ "source": {"kind": spec.architecture_source_kind,
+ "reference": spec.architecture_reference},
+ },
+ "checkedAt": timestamp,
+ "place": {"node": spec.id.split("__", 1)[0]},
+ "identities": {
+ "container": spec.container,
+ "unit": spec.unit,
+ "units": list(spec.extra_units),
+ "endpoint": spec.endpoint,
+ },
+ "dependencies": [
+ {"target": target, "kind": "dependency", "evidence": evidence,
+ "confidence": confidence}
+ for target, evidence, confidence in spec.depends_on
+ ],
+ }
+
+ if spec.source == SRC_TKC_STATUS:
+ last_checked = tkc_observed_at or timestamp
+ elif spec.source in (SRC_PROBE, SRC_HERMES_API) and status != "unknown":
+ last_checked = timestamp
+ elif spec.source == SRC_FILESYSTEM and status != "unknown":
+ last_checked = timestamp
+ else:
+ last_checked = None
+
+ # Container-only entries (no TKC knowledge item) are judged on the Docker
+ # status string: lifecycle state + healthcheck marker + exit code.
+ error_kind = probe_error_kinds.get(_evidence_key(spec))
+ if (spec.source == SRC_FILESYSTEM and isinstance(backup_filesystem, dict)
+ and backup_filesystem.get("mounted") is False):
+ error_kind = "storage_not_mounted"
+ runtime_only = False
+ if spec.container and not spec.tkc_item:
+ ev = _container_evidence(_dig(tkc_status, ("services", "docker")), spec.container)
+ if ev["state"] == "running" and ev["healthcheck"] == "unhealthy":
+ error_kind = "container_unhealthy"
+ elif ev["state"] == "running" and ev["healthcheck"] is None:
+ runtime_only = bool(ev["runtime_only"])
+ elif ev["state"] == "exited":
+ error_kind = "container_exited"
+ elif ev["state"] == "restarting":
+ error_kind = "container_restarting"
+ elif ev["state"] == "paused":
+ error_kind = "container_paused"
+ elif ev["state"] == "created":
+ error_kind = "container_created"
+ elif ev["state"] == "dead":
+ error_kind = "container_dead"
+
+ health, health_code, health_reason = _evidence_health(
+ spec,
+ status=status,
+ detail=detail,
+ now=now_dt,
+ max_age_seconds=health_max_age_seconds,
+ error_kind=error_kind,
+ last_checked=last_checked,
+ runtime_only=runtime_only,
+ )
+
+ # The backup JOB dimension: only real unit properties count. A unit that
+ # never ran must not be reported as a successful backup.
+ job_last_success: Optional[str] = None
+ if spec.source == SRC_SYSTEMD and isinstance(backup_job, dict):
+ job = _backup_job_status(backup_job, now=now_dt)
+ if job:
+ status = job["status"]
+ detail = job["detail"]
+ health = job["health"]
+ health_code = job["code"]
+ health_reason = job["detail"]
+ job_last_success = job.get("lastSuccess")
+ if job.get("startedAt"):
+ last_checked = job["startedAt"]
+ elif job_last_success:
+ last_checked = job_last_success
+
+ # The backup-job branch above may have replaced status/detail; write the
+ # final values back into the already-built entry so the payload cannot
+ # disagree with itself (health said "healthy" while status said "unknown").
+ entry["status"] = status
+ entry["statusDetail"] = detail
+
+ maintenance = maintenance_for(spec.id, now=maintenance_at)
+
+ entry.update({
+ "health": health,
+ "healthSource": _status_source(spec, has_evidence=systemd_evidence),
+ "healthReasonCode": health_code,
+ "healthReason": health_reason,
+ "lastChecked": last_checked,
+ "lastSuccess": (job_last_success
+ or (last_checked if health == "healthy"
+ else last_success.get(spec.id))),
+ "operationalMode": "maintenance" if maintenance and maintenance["active"] else "normal",
+ "maintenance": maintenance,
+ })
+
+ entry.update(SERVICE_DETAIL.get(spec.id, {}))
+
+ if spec.id == "ton-01__backup-storage" and isinstance(backup_filesystem, dict):
+ entry["storage"] = {**backup_filesystem, "evidenceClass": "machine_observed"}
+
+ windows = [w for w in MAINTENANCE_WINDOWS
+ if w["service"] == spec.id or spec.id in w["expectedImpact"]]
+ if windows:
+ entry["maintenanceRole"] = spec.maintenance_role
+ if spec.maintenance_role == "source":
+ entry["maintenanceWindow"] = windows[0]
+ else:
+ entry["maintenanceWindows"] = [
+ {"id": w["id"], "onCalendar": w["onCalendar"],
+ "maxDurationSeconds": w["maxDurationSeconds"],
+ "active": w["active"], "sourceService": w["service"]}
+ for w in windows
+ ]
+
+ entries.append(entry)
+
+ _apply_dependency_health(entries)
+
+ return entries
+
+
+def _calendar_interval_seconds(calendar: str) -> Optional[int]:
+ """Expected interval from the timer's own OnCalendar — nothing invented.
+
+ Only the two forms TARS actually declares are understood; anything else
+ returns None, which disables the staleness judgement instead of guessing.
+ """
+ text = (calendar or "").lower()
+ if "sun *-*-*" in text or "mon *-*-*" in text or "tue *-*-*" in text \
+ or "wed *-*-*" in text or "thu *-*-*" in text \
+ or "fri *-*-*" in text or "sat *-*-*" in text:
+ return 7 * 86400
+ if "*-*-*" in text:
+ return 86400
+ return None
+
+
+def _backup_job_status(units: Any, *, now: datetime,
+ grace_seconds: int = 21600) -> Optional[dict[str, Any]]:
+ """Evaluate the backup unit's systemd properties into a job status.
+
+ Returns None when no usable unit evidence was read. States:
+ running — start timestamp present, exit timestamp empty, unit activating/active
+ success — Result=success AND a real InvocationID AND an exit timestamp
+ failed — non-zero exit / failed Result AND a real InvocationID
+ unknown — anything else (never ran, unreadable, contradictory)
+
+ ``stale`` is reported separately from ``success``: an old success stays a
+ success, but its health is degraded once the timer interval plus grace is
+ exceeded. A failed run is never masked by an older success.
+ """
+ if not isinstance(units, dict):
+ return None
+ service = units.get("service")
+ timer = units.get("timer") or {}
+ if not isinstance(service, dict):
+ return None
+
+ active = str(service.get("ActiveState") or "")
+ sub_state = str(service.get("SubState") or "")
+ result = str(service.get("Result") or "")
+ exit_status = str(service.get("ExecMainStatus") or "")
+ started = service.get("ExecMainStartTimestamp") or None
+ exited = service.get("ExecMainExitTimestamp") or None
+ invocation = service.get("InvocationID") or None
+
+ base = {
+ "activeState": active, "subState": sub_state, "result": result,
+ "exitCode": int(exit_status) if exit_status.lstrip("-").isdigit() else None,
+ "startedAt": started, "exitedAt": exited, "invocationId": invocation,
+ "nextElapse": timer.get("NextElapseUSecRealtime") or None,
+ "lastTrigger": timer.get("LastTriggerUSec") or None,
+ }
+
+ running = bool(started) and not exited and active in ("active", "activating", "reloading")
+ if running:
+ base.update(state="running", status="degraded", health="degraded",
+ code="backup_running",
+ detail=f"backup job running since {started}")
+ return base
+
+ # No invocation id means the unit never actually ran; Result=success is then
+ # systemd's default, not a measurement.
+ if not invocation:
+ base.update(state="unknown", status="unknown", health="unknown",
+ code="backup_never_ran",
+ detail="no backup invocation recorded; Result/success is a default")
+ return base
+
+ failed = result not in ("success", "") or (base["exitCode"] not in (None, 0))
+ if failed:
+ base.update(state="failed", status="error", health="unhealthy",
+ code="backup_failed",
+ detail=f"last backup failed (Result={result or '?'}, exit={exit_status or '?'})")
+ return base
+
+ interval = _calendar_interval_seconds(str(timer.get("TimersCalendar") or ""))
+ stale_after = interval + grace_seconds if interval else None
+ age = None
+ if exited:
+ try:
+ age = (now - _parse_iso(exited)).total_seconds()
+ except Exception:
+ age = None
+
+ base.update(state="success", lastSuccess=exited, expectedIntervalSeconds=interval,
+ staleAfterSeconds=stale_after)
+ if stale_after is not None and age is not None and age > stale_after:
+ base.update(status="degraded", health="degraded", code="backup_stale",
+ detail=f"last successful backup is {int(age)}s old "
+ f"(expected interval {interval}s + grace {grace_seconds}s)")
+ return base
+ base.update(status="ok", health="healthy", code="backup_success",
+ detail=f"last backup succeeded at {exited}")
+ return base
+
+
+def _apply_dependency_health(entries: list[dict[str, Any]]) -> None:
+ """Downgrade a healthy entry whose declared dependency is unhealthy.
+
+ A service whose dependency failed is partially functional at best, so a
+ "healthy" claim is lowered to "degraded" with the target named in the reason.
+ Only ever downgrades, only from "healthy": "unknown" (no evidence) and
+ "unhealthy" (already a failure) are left untouched, and no claim is invented.
+ """
+ by_id = {entry["id"]: entry for entry in entries}
+ for entry in entries:
+ if entry.get("health") != "healthy":
+ continue
+ broken = [dep["target"] for dep in entry.get("dependencies", ())
+ if by_id.get(dep["target"], {}).get("health") == "unhealthy"]
+ if broken:
+ entry["health"] = "degraded"
+ entry["healthReasonCode"] = "dependency_unhealthy"
+ entry["healthReason"] = f"dependency {broken[0]} is unhealthy"
+ entry["lastSuccess"] = None
diff --git a/services/tars-status/tests/test_health2.py b/services/tars-status/tests/test_health2.py
new file mode 100644
index 0000000..c6d367e
--- /dev/null
+++ b/services/tars-status/tests/test_health2.py
@@ -0,0 +1,305 @@
+"""TARS Health 2.0 — evidence discipline, freshness, operational mode.
+
+These tests pin the rules that make `health` different from `status`:
+
+* a literal is never a measurement (``constant_value``)
+* no source is never green (``no_probe_source``)
+* an observation past the freshness bound becomes ``unknown`` (``stale_evidence``)
+* a timeout stays distinguishable from a probe that never ran
+* ``maintenance`` is a third dimension: it never rewrites ``health``
+* ``/status`` keeps its legacy shape (no health fields leak into it)
+
+No network access: every upstream is replaced by a deterministic stand-in.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+from datetime import datetime, timedelta, timezone
+
+import httpx
+import pytest
+
+from app import main as M
+from app import services_registry as R
+
+
+# ── helpers ──────────────────────────────────────────────────────────────────
+
+def _iso(dt: datetime) -> str:
+ return dt.astimezone(timezone.utc).isoformat()
+
+
+NOW = datetime.now(tz=timezone.utc)
+NOW_ISO = _iso(NOW)
+
+
+def _tkc_status(generated_at=None):
+ return {
+ "generated_at": generated_at or NOW_ISO,
+ "services": {
+ "docker": {
+ "state": "online", "health": "green",
+ "containers": {
+ "tkc-postgres": "Up 2 days",
+ "milvus-standalone": "Up 2 days",
+ "milvus-etcd": "Up 2 days",
+ "milvus-minio": "Up 2 days",
+ "tkc-neo4j": "Up 2 days",
+ "portainer": "Up 2 days",
+ },
+ "missing_expected": [],
+ },
+ },
+ "knowledge": {
+ "postgresql": {"state": "online", "health": "green", "knowledge_objects": 101},
+ "milvus": {"state": "online", "health": "green"},
+ "neo4j": {"state": "online", "health": "green", "nodes": 104},
+ },
+ }
+
+
+def _entries(**kwargs):
+ defaults = dict(
+ tkc_status=_tkc_status(),
+ tkc_error=None,
+ mcp={"status": "ok", "detail": "v0.4.0"},
+ gateway={"status": "ok", "detail": "ok"},
+ hermes={"status": "ok", "detail": "0.2.0"},
+ backup_filesystem=None,
+ checked_at=NOW_ISO,
+ health_max_age_seconds=90,
+ )
+ defaults.update(kwargs)
+ return {e["id"]: e for e in R.build_service_entries(**defaults)}
+
+
+class _NullClient:
+ """Async context manager stand-in; the probes themselves are patched."""
+
+ def __init__(self, *a, **k):
+ pass
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *exc):
+ return False
+
+ async def get(self, *a, **k):
+ raise AssertionError("no real network access in tests")
+
+
+@pytest.fixture(autouse=True)
+def _cold(monkeypatch):
+ for name in ("_cache", "_services_cache", "_tkc_status_cache"):
+ monkeypatch.setattr(M, name, {"data": None, "error": None, "expires_at": 0.0})
+ monkeypatch.setattr(M, "_inflight", {})
+
+
+# ── 1. healthy evidence ──────────────────────────────────────────────────────
+
+def test_healthy_entry_carries_provenance_and_timestamps():
+ e = _entries()["ton-01__postgresql"]
+ assert e["status"] == "ok"
+ assert e["health"] == "healthy"
+ assert e["healthReasonCode"] == "healthy_evidence"
+ assert e["healthSource"]["kind"] == "tkc_status"
+ assert "TKC GET /status" in e["healthSource"]["reference"]
+ assert e["lastChecked"] == NOW_ISO
+ assert e["lastSuccess"] == NOW_ISO
+ assert e["operationalMode"] == "normal"
+ assert e["maintenance"] is None
+
+
+# ── 2. reachable, but a declared dependency is unhealthy ─────────────────────
+
+def test_healthy_service_with_unhealthy_dependency_becomes_degraded():
+ payload = _tkc_status()
+ # A container that is merely LISTED still counts as present ("Up" is not parsed),
+ # so the honest way to report a dead dependency is TKC's own missing_expected.
+ del payload["services"]["docker"]["containers"]["milvus-etcd"]
+ payload["services"]["docker"]["missing_expected"] = ["milvus-etcd"]
+ e = _entries(tkc_status=payload)["ton-01__milvus"]
+ assert e["status"] == "ok" # its own evidence is still fine
+ assert e["health"] == "degraded" # but a dependency is not
+ assert e["healthReasonCode"] == "dependency_unhealthy"
+ assert "milvus-etcd" in e["healthReason"]
+
+
+# ── 3. not reachable ─────────────────────────────────────────────────────────
+
+def test_unreachable_upstream_is_unknown_not_healthy():
+ e = _entries(tkc_status=None, tkc_error="ConnectError: All connection attempts failed",
+ probe_error_kinds={"tkc_status": "probe_unreachable"})["ton-01__postgresql"]
+ assert e["status"] == "unknown"
+ assert e["health"] == "unknown"
+ assert e["healthReasonCode"] == "probe_unreachable"
+ assert e["lastSuccess"] is None
+
+
+# ── 4. probe timeout is distinguishable ──────────────────────────────────────
+
+def test_timeout_is_its_own_reason_code():
+ e = _entries(mcp={"status": "error", "detail": "TimeoutException: timed out"},
+ probe_error_kinds={"mcp": "probe_timeout"})["ton-01__mcp-server"]
+ assert e["health"] == "unhealthy"
+ assert e["healthReasonCode"] == "probe_timeout"
+
+
+# ── 5. no probe at all ───────────────────────────────────────────────────────
+
+def test_missing_source_is_unknown_never_green():
+ e = _entries()["ton-01__tars-interaction-runtime"]
+ assert e["status"] == "unknown"
+ assert e["health"] == "unknown"
+ assert e["healthReasonCode"] == "no_probe_source"
+ assert e["lastChecked"] is None and e["lastSuccess"] is None
+
+
+# ── 6. stale evidence ────────────────────────────────────────────────────────
+
+def test_stale_observation_degrades_to_unknown():
+ old = _iso(NOW - timedelta(seconds=600))
+ e = _entries(tkc_status=_tkc_status(generated_at=old),
+ health_max_age_seconds=90)["ton-01__postgresql"]
+ assert e["health"] == "unknown"
+ assert e["healthReasonCode"] == "stale_evidence"
+ assert "600s" in e["healthReason"]
+
+
+def test_fresh_observation_stays_healthy():
+ recent = _iso(NOW - timedelta(seconds=20))
+ e = _entries(tkc_status=_tkc_status(generated_at=recent),
+ health_max_age_seconds=90)["ton-01__postgresql"]
+ assert e["health"] == "healthy"
+
+
+# ── 7–9. maintenance is an independent dimension ─────────────────────────────
+
+def _period(start_delta_min: int, end_delta_min: int | None, **extra):
+ period = {
+ "id": "mp-test",
+ "reason": "planned database upgrade",
+ "startsAt": _iso(NOW + timedelta(minutes=start_delta_min)),
+ "services": ["ton-01__postgresql"],
+ }
+ if end_delta_min is not None:
+ period["endsAt"] = _iso(NOW + timedelta(minutes=end_delta_min))
+ period.update(extra)
+ return (period,)
+
+
+def _with_periods(monkeypatch, periods):
+ monkeypatch.setattr(R, "MAINTENANCE_PERIODS", periods)
+
+
+def test_maintenance_active_keeps_a_healthy_health(monkeypatch):
+ _with_periods(monkeypatch, _period(-10, 30))
+ e = _entries(maintenance_now=NOW)["ton-01__postgresql"]
+ assert e["operationalMode"] == "maintenance"
+ assert e["maintenance"]["active"] is True
+ assert e["maintenance"]["reason"] == "planned database upgrade"
+ assert e["health"] == "healthy" # maintenance never masks the truth
+
+
+def test_maintenance_active_keeps_an_unhealthy_health(monkeypatch):
+ _with_periods(monkeypatch, _period(-10, 30))
+ payload = _tkc_status()
+ payload["knowledge"]["postgresql"] = {"state": "offline", "health": "red"}
+ e = _entries(tkc_status=payload, maintenance_now=NOW)["ton-01__postgresql"]
+ assert e["operationalMode"] == "maintenance"
+ assert e["health"] == "unhealthy"
+ assert e["status"] == "error"
+
+
+def test_expired_maintenance_returns_to_normal_by_itself(monkeypatch):
+ _with_periods(monkeypatch, _period(-120, -60))
+ e = _entries(maintenance_now=NOW)["ton-01__postgresql"]
+ assert e["operationalMode"] == "normal"
+ assert e["maintenance"] is None
+
+
+def test_upcoming_maintenance_is_visible_but_not_active(monkeypatch):
+ _with_periods(monkeypatch, _period(60, 120))
+ e = _entries(maintenance_now=NOW)["ton-01__postgresql"]
+ assert e["maintenance"]["active"] is False
+ assert e["operationalMode"] == "normal"
+
+
+# ── 10. maintenance scope does not swallow unrelated errors ──────────────────
+
+def test_error_outside_the_maintenance_scope_stays_visible(monkeypatch):
+ _with_periods(monkeypatch, _period(-10, 30))
+ payload = _tkc_status()
+ payload["knowledge"]["neo4j"] = {"state": "offline", "health": "red"}
+ entries = _entries(tkc_status=payload, maintenance_now=NOW)
+ assert entries["ton-01__postgresql"]["operationalMode"] == "maintenance"
+ assert entries["ton-01__neo4j"]["operationalMode"] == "normal"
+ assert entries["ton-01__neo4j"]["health"] == "unhealthy"
+ assert entries["ton-01__neo4j"]["status"] == "error"
+
+
+# ── 11. legacy contract ──────────────────────────────────────────────────────
+
+def test_health_fields_are_additive_and_do_not_touch_status():
+ entries = _entries()
+ for e in entries.values():
+ assert e["status"] in R.SERVICE_STATUS_VALUES
+ assert e["health"] in R.HEALTH_VALUES
+ assert e["operationalMode"] in R.OPERATIONAL_MODES
+ # both vocabularies stay 1:1 where status has an opinion
+ assert e["health"] == R.health_from_status(e["status"]) or \
+ e["healthReasonCode"] in ("stale_evidence", "no_evidence",
+ "constant_value", "not_deployed",
+ "dependency_unhealthy", "runtime_only")
+
+
+async def test_legacy_status_endpoint_carries_no_health_fields(monkeypatch):
+ """GET /status must keep its exact shape — health lives on /services only."""
+ async def fake_tkc_status():
+ return _tkc_status(), None
+
+ async def fake_probe_tkc(client):
+ return M.ServiceStatus(name="TKC", status="ok", detail="ok"), None, None, []
+
+ monkeypatch.setattr(M, "cached_tkc_status", fake_tkc_status)
+ monkeypatch.setattr(M, "probe_tkc", fake_probe_tkc)
+ monkeypatch.setattr(M, "probe_mcp", _probe_ok("MCP Server"))
+ monkeypatch.setattr(M, "probe_gateway", _probe_ok("Engineering Gateway"))
+ monkeypatch.setattr(M, "probe_all_repos", lambda: [])
+ monkeypatch.setattr(M.httpx, "AsyncClient", _NullClient)
+
+ body = await M.collect_status()
+ for service in body["services"]:
+ assert set(service) == {"name", "status", "detail"}
+ assert "health" not in service
+
+
+# ── 12. cache / single-flight keeps the health decision stable ───────────────
+
+async def test_repeated_requests_inside_the_ttl_return_the_same_health(monkeypatch):
+ calls = {"n": 0}
+
+ async def fake_tkc_status():
+ calls["n"] += 1
+ return _tkc_status(), None
+
+ monkeypatch.setattr(M, "cached_tkc_status", fake_tkc_status)
+ monkeypatch.setattr(M, "probe_mcp", _probe_ok("MCP Server"))
+ monkeypatch.setattr(M, "probe_gateway", _probe_ok("Engineering Gateway"))
+ monkeypatch.setattr(M, "probe_hermes", _probe_ok("Hermes Agent"))
+ monkeypatch.setattr(M, "backup_filesystem_usage", lambda: None)
+ monkeypatch.setattr(M.httpx, "AsyncClient", _NullClient)
+
+ first = await M.collect_services()
+ second = await M.collect_services()
+ assert first is second
+ assert calls["n"] == 1
+ assert all(e["health"] in R.HEALTH_VALUES for e in first["services"])
+
+
+def _probe_ok(name: str):
+ async def _probe(client):
+ return M.ServiceStatus(name=name, status="ok", detail="test")
+ return _probe
diff --git a/services/tars-status/tests/test_services_endpoint.py b/services/tars-status/tests/test_services_endpoint.py
new file mode 100644
index 0000000..da01bf9
--- /dev/null
+++ b/services/tars-status/tests/test_services_endpoint.py
@@ -0,0 +1,1056 @@
+"""
+tests/test_services_endpoint.py — Slice 1: read-only GET /services + registry.
+
+Covers the 18 acceptance cases of the Slice-1 task (T01..T18) plus three extras
+(X01..X03) for contract requirements added later:
+
+ * X01 maintenance window is metadata and never a health state
+ * X02 backup storage uses a real filesystem source (never invented numbers)
+ * X03 the BorgBackup entry reports no invented metrics
+
+No live network calls — every upstream probe is mocked. No production side
+effects: no container, unit, timer, database or backup is touched.
+Run with: pytest tests/test_services_endpoint.py -v
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import sys
+import copy
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import httpx
+import pytest
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
+
+from app.main import ServiceStatus, SubsystemStatus, app # noqa: E402
+import app.main as main # noqa: E402
+import app.services_registry as registry # noqa: E402
+from app.services_registry import ( # noqa: E402
+ ARCHITECTURE_STATES,
+ EVIDENCE_CLASSES,
+ INSTALL_STATES,
+ SERVICE_ID_RE,
+ SERVICE_KINDS,
+ SERVICE_STATES,
+ SERVICE_STATUS_VALUES,
+ SERVICES,
+)
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Fixtures — canned upstream payloads (shaped exactly like the live capture of
+# 2026-11-06, incl. the container status strings TKC really returns)
+# ─────────────────────────────────────────────────────────────────────────────
+
+TKC_STATUS_HEALTHY = {
+ "services": {
+ "tkc_service": {"state": "online", "health": "green"},
+ "knowledge_lifecycle": {"state": "active", "health": "green"},
+ "docker": {
+ "state": "online",
+ "health": "green",
+ "containers": {
+ "tkc-postgres": "Up 3 days (healthy)",
+ "milvus-standalone": "Up 3 days",
+ "milvus-etcd": "Up 3 days",
+ "milvus-minio": "Up 3 days",
+ "tkc-neo4j": "Up 3 days (healthy)",
+ "portainer": "Up 3 days",
+ },
+ "missing_expected": [],
+ },
+ },
+ "knowledge": {
+ "postgresql": {"state": "online", "health": "green", "knowledge_objects": 101,
+ "project_memories": 2},
+ "milvus": {"state": "online", "health": "green", "collections": ["tkc_objects"]},
+ "neo4j": {"state": "online", "health": "green", "nodes": 104, "relationships": 92},
+ },
+}
+
+HEALTH_SUBSYSTEMS = SubsystemStatus(
+ postgresql="unknown", milvus="online", neo4j="unknown", knowledge_lifecycle=None
+)
+
+
+@pytest.fixture(autouse=True)
+def _fresh_caches(monkeypatch):
+ """Every test starts with cold caches (module-level dicts persist across tests)."""
+ _reset_caches(monkeypatch)
+
+
+def _reset_caches(monkeypatch):
+ """Cold caches — callable directly from tests that switch scenario mid-test."""
+ for name in ("_cache", "_services_cache", "_tkc_status_cache"):
+ monkeypatch.setattr(main, name, {"data": None, "error": None, "expires_at": 0.0})
+ monkeypatch.setattr(main, "_inflight", {}) # no shared task leaking between tests
+ monkeypatch.setattr(_RecordingClient, "calls", [])
+
+
+def _patch_upstreams(monkeypatch, *, tkc_status=TKC_STATUS_HEALTHY, tkc_error=None,
+ mcp=None, gateway=None, hermes=None, backup_filesystem=None,
+ health_subsystems=HEALTH_SUBSYSTEMS):
+ """Mock every upstream probe of app.main (no network, no git, no statvfs)."""
+ monkeypatch.setattr(main, "cached_tkc_status",
+ AsyncMock(return_value=(tkc_status, tkc_error)))
+ monkeypatch.setattr(main, "probe_tkc", AsyncMock(return_value=(
+ ServiceStatus(name="TKC", status="ok", detail="ok"), health_subsystems, None, [])))
+ monkeypatch.setattr(main, "probe_mcp", AsyncMock(return_value=(
+ mcp if mcp is not None else ServiceStatus(name="MCP Server", status="ok", detail="v0.4.0"))))
+ monkeypatch.setattr(main, "probe_gateway", AsyncMock(return_value=(
+ gateway if gateway is not None else
+ ServiceStatus(name="Engineering Gateway", status="ok", detail="ok"))))
+ monkeypatch.setattr(main, "probe_hermes", AsyncMock(return_value=(
+ hermes if hermes is not None else
+ ServiceStatus(name="Hermes Agent", status="ok", detail="0.2.0"))))
+ monkeypatch.setattr(main, "backup_filesystem_usage", MagicMock(return_value=backup_filesystem))
+ monkeypatch.setattr(main, "probe_all_repos", MagicMock(return_value=[]))
+
+
+def _client() -> httpx.AsyncClient:
+ return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test")
+
+
+async def _get(path: str):
+ async with _client() as client:
+ return await client.get(path)
+
+
+async def _get_with(path: str, headers: dict):
+ async with _client() as client:
+ return await client.get(path, headers=headers)
+
+
+async def _entries() -> dict:
+ response = await _get("/services")
+ assert response.status_code == 200
+ return {entry["id"]: entry for entry in response.json()["services"]}
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# T01–T02 registry shape
+# ─────────────────────────────────────────────────────────────────────────────
+
+def test_T01_registry_ids_are_unique_and_use_the_host_prefix_convention():
+ ids = [spec.id for spec in SERVICES]
+ assert len(ids) == len(set(ids)), "duplicate service ids"
+ assert all(SERVICE_ID_RE.match(i) for i in ids), [i for i in ids if not SERVICE_ID_RE.match(i)]
+ assert not any(i.startswith("service:") for i in ids), "legacy 'service:' ids must be gone"
+ assert {i.split("__", 1)[0] for i in ids} == {"ton-01", "vps", "laptop"}
+ for spec in SERVICES:
+ assert spec.kind in SERVICE_KINDS
+ assert spec.state in SERVICE_STATES
+ assert spec.install_state in INSTALL_STATES
+ assert spec.architecture_state in ARCHITECTURE_STATES
+ assert spec.evidence_class in EVIDENCE_CLASSES
+
+
+async def test_T02_every_spec_yields_one_entry_in_registry_order(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ async with _client() as client:
+ response = await client.get("/services")
+ assert response.status_code == 200
+ body = response.json()
+ assert [e["id"] for e in body["services"]] == [s.id for s in SERVICES]
+ assert body["cache_ttl_seconds"] == main.STATUS_CACHE_TTL
+ assert body["checked_at"]
+ for entry in body["services"]:
+ assert {"id", "label", "kind", "status", "statusDetail", "statusSource", "state",
+ "installState", "evidenceClass", "architecture", "checkedAt",
+ "place", "identities", "dependencies"} <= set(entry)
+ assert entry["place"]["node"] == entry["id"].split("__", 1)[0]
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# T03–T06 live mapping from TKC /status
+# ─────────────────────────────────────────────────────────────────────────────
+
+async def test_T03_postgres_online_maps_to_ok(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ entry = (await _entries())["ton-01__postgresql"]
+ assert entry["status"] == "ok"
+ assert entry["statusSource"]["kind"] == "tkc_status"
+ assert "knowledge.postgresql" in entry["statusSource"]["reference"]
+ assert entry["identities"]["container"] == "tkc-postgres"
+ assert entry["architecture"]["state"] == "canonical"
+ assert "knowledge_objects=101" in entry["statusDetail"]
+
+
+async def test_T04_milvus_and_neo4j_online_map_to_ok(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ entries = await _entries()
+ assert entries["ton-01__milvus"]["status"] == "ok"
+ assert entries["ton-01__neo4j"]["status"] == "ok"
+ assert "nodes=104" in entries["ton-01__neo4j"]["statusDetail"]
+ edges = {d["target"] for d in entries["ton-01__milvus"]["dependencies"]}
+ assert edges == {"ton-01__milvus-etcd", "ton-01__milvus-minio"}
+ for dep in entries["ton-01__milvus"]["dependencies"]:
+ assert dep["confidence"] in ("inferred", "documented")
+ assert dep["evidence"]
+
+
+async def test_T05_container_inventory_drives_container_entries(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ entries = await _entries()
+ # real container strings are passed through, never re-worded
+ assert entries["ton-01__portainer"]["statusDetail"] == "Up 3 days"
+ assert entries["ton-01__milvus-etcd"]["statusDetail"] == "Up 3 days"
+ # ...but a service with its own authoritative block reports that block's evidence,
+ # including the raw state/health the status was derived from
+ assert entries["ton-01__postgresql"]["statusDetail"] == \
+ "state=online, health=green, knowledge_objects=101, project_memories=2"
+ for service_id in ("ton-01__milvus-etcd", "ton-01__milvus-minio", "ton-01__portainer",
+ "ton-01__neo4j"):
+ assert entries[service_id]["status"] == "ok", service_id
+ assert entries["ton-01__docker"]["status"] == "ok"
+ assert entries["ton-01__docker"]["statusSource"]["reference"].endswith("services.docker")
+
+
+async def test_T06_missing_expected_container_is_reported_as_error(monkeypatch):
+ payload = copy.deepcopy(TKC_STATUS_HEALTHY)
+ del payload["services"]["docker"]["containers"]["milvus-etcd"]
+ payload["services"]["docker"]["missing_expected"] = ["milvus-etcd"]
+ _patch_upstreams(monkeypatch, tkc_status=payload)
+ entries = await _entries()
+ assert entries["ton-01__milvus-etcd"]["status"] == "error"
+ assert "missing_expected" in entries["ton-01__milvus-etcd"]["statusDetail"]
+ # a container the platform never mentions is unknown, never "error"
+ assert entries["ton-01__milvus-minio"]["status"] == "ok"
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# T07–T10 degradation and vocabulary
+# ─────────────────────────────────────────────────────────────────────────────
+
+async def test_T07_tkc_unreachable_yields_unknown_and_keeps_the_source(monkeypatch):
+ _patch_upstreams(monkeypatch, tkc_status=None,
+ tkc_error="ConnectError: tkc unreachable")
+ entries = await _entries()
+ for service_id in ("ton-01__tkc-service", "ton-01__postgresql", "ton-01__milvus",
+ "ton-01__neo4j", "ton-01__docker"):
+ assert entries[service_id]["status"] == "unknown", service_id
+ # the attribution of a declared source survives an outage
+ assert entries[service_id]["statusSource"]["kind"] == "tkc_status"
+ assert "unreachable" in entries[service_id]["statusDetail"]
+ # independent probes keep working
+ assert entries["ton-01__mcp-server"]["status"] == "ok"
+ assert entries["ton-01__engineering-gateway"]["status"] == "ok"
+ # no live source at all ⇒ unknown with an 'unknown' source kind
+ assert entries["ton-01__borgbackup"]["status"] == "unknown"
+ assert entries["ton-01__borgbackup"]["statusSource"]["kind"] == "unknown"
+
+
+async def test_T08_database_states_mark_planned_vs_existing(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ databases = {d["name"]: d for d in (await _entries())["ton-01__postgresql"]["databases"]}
+ assert databases["tkc"]["state"] == "existing"
+ assert databases["tkc_dev"]["state"] == "planned"
+ assert databases["tkc_dev"]["architectureState"] == "unknown"
+ assert databases["tkc_backup"]["state"] == "existing"
+ assert databases["tkc_backup"]["evidenceClass"] == "operator_provided"
+ assert "planned" not in json.dumps(databases["tkc"]).lower()
+
+
+def test_T09_planned_or_not_installed_services_never_report_ok(monkeypatch):
+ synthetic = (
+ registry.ServiceSpec("ton-01__futuredb", "Future DB", "container",
+ registry.SRC_TKC_STATUS, container="tkc-postgres",
+ state="planned", install_state="not_installed"),
+ registry.ServiceSpec("ton-01__futureapi", "Future API", "api",
+ registry.SRC_TKC_STATUS, container="tkc-postgres"),
+ )
+ monkeypatch.setattr(registry, "SERVICES", synthetic)
+ entries = registry.build_service_entries(tkc_status=TKC_STATUS_HEALTHY)
+ assert entries[0]["status"] == "unknown"
+ assert "planned" in entries[0]["statusDetail"]
+ # control: the same spec without the planned flags does report ok
+ assert entries[1]["status"] == "ok"
+
+
+async def test_T10_status_values_are_inside_the_enum(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ entries = await _entries()
+ for entry in entries.values():
+ assert entry["status"] in SERVICE_STATUS_VALUES, entry
+
+ dead = {k: None for k in
+ ("tkc_status", "mcp", "gateway", "hermes")}
+ dead_entries = registry.build_service_entries(
+ tkc_status=dead["tkc_status"], tkc_error="all upstreams down",
+ mcp=dead["mcp"], gateway=dead["gateway"], hermes=dead["hermes"],
+ )
+ assert dead_entries and all(e["status"] in SERVICE_STATUS_VALUES for e in dead_entries)
+ assert all(e["status"] == "unknown" for e in dead_entries
+ if e["statusSource"]["kind"] == "unknown")
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# T11–T15 route contract
+# ─────────────────────────────────────────────────────────────────────────────
+
+async def test_T11_detail_route_returns_exactly_one_entry(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ async with _client() as client:
+ response = await client.get("/services/ton-01__borgbackup")
+ listing = await client.get("/services")
+ assert response.status_code == 200
+ entry = response.json()
+ assert entry["id"] == "ton-01__borgbackup"
+ assert "services" not in entry # a single entry, not a wrapped list
+ assert entry == [e for e in listing.json()["services"]
+ if e["id"] == "ton-01__borgbackup"][0]
+
+
+async def test_T12_unknown_id_returns_404(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ response = await _get("/services/ton-01__does-not-exist")
+ assert response.status_code == 404
+ assert "does-not-exist" in response.json()["detail"]
+
+
+async def test_T13_malformed_id_returns_400(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ for bad in ("ton-01-borgbackup", "ton-01__", "ton-01__BorgBackup", "service:borgbackup"):
+ response = await _get(f"/services/{bad}")
+ assert response.status_code == 400, bad
+
+
+async def test_T14_list_endpoint_returns_200_when_all_upstreams_fail(monkeypatch):
+ _patch_upstreams(
+ monkeypatch, tkc_status=None, tkc_error="TKC down",
+ mcp=ServiceStatus(name="MCP Server", status="error", detail="refused"),
+ gateway=ServiceStatus(name="Engineering Gateway", status="error", detail="refused"),
+ hermes=ServiceStatus(name="Hermes Agent", status="unknown", detail="refused"),
+ backup_filesystem=None, health_subsystems=None,
+ )
+ entries = await _entries()
+ assert len(entries) == len(SERVICES)
+ assert all(e["status"] in SERVICE_STATUS_VALUES for e in entries.values())
+ assert not any(e["status"] == "ok" for e in entries.values()
+ if e["statusSource"]["kind"] == "unknown")
+
+
+async def test_T15_response_contains_no_secrets(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ response = await _get("/services")
+ blob = json.dumps(response.json())
+ for needle in ("password", "passwd", "postgres://", "postgresql://", "Authorization",
+ "Bearer", "API_KEY", "apiKey", "token=", "secret", "PRIVATE KEY"):
+ assert needle not in blob, f"payload leaked {needle!r}"
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# T16–T18 backwards compatibility and the honest BorgBackup entry
+# ─────────────────────────────────────────────────────────────────────────────
+
+async def test_T16_existing_status_endpoint_shape_is_unchanged(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ response = await _get("/status")
+ assert response.status_code == 200
+ body = response.json()
+ assert set(body) == {"checked_at", "services", "subsystems", "knowledge_stats",
+ "knowledge_recent", "repositories"}
+ assert [s["name"] for s in body["services"]] == [
+ "TKC", "PostgreSQL", "Milvus", "Neo4j", "MCP Server", "Engineering Gateway"]
+ for service in body["services"]:
+ assert set(service) == {"name", "status", "detail"}
+ assert service["status"] in SERVICE_STATUS_VALUES
+ assert set(body["subsystems"]) == {"postgresql", "milvus", "neo4j", "knowledge_lifecycle"}
+
+
+async def test_T17_subsystem_block_uses_tkc_status_with_health_fallback(monkeypatch):
+ # (a) TKC /status available: real query results win — this is the defect fix
+ _patch_upstreams(monkeypatch)
+ body = (await _get("/status")).json()
+ # the block keeps TKC's own vocabulary (unchanged strings, corrected source)
+ assert body["subsystems"] == {"postgresql": "online", "milvus": "online",
+ "neo4j": "online", "knowledge_lifecycle": "active"}
+ # ...and the normalised services[] list now reports PostgreSQL/Neo4j as ok —
+ # the exact defect: both were permanently "unknown" while TKC was healthy
+ assert {s["name"]: s["status"] for s in body["services"]} == {
+ "TKC": "ok", "PostgreSQL": "ok", "Milvus": "ok", "Neo4j": "ok",
+ "MCP Server": "ok", "Engineering Gateway": "ok"}
+
+ # (b) /status gone: fall back to the /health-derived block, still no crash
+ _reset_caches(monkeypatch)
+ _patch_upstreams(monkeypatch, tkc_status=None, tkc_error="TKC /status down")
+ subsystems = (await _get("/status")).json()["subsystems"]
+ assert subsystems["milvus"] == "online"
+ assert subsystems["postgresql"] == "unknown" # from /health: no such key
+
+ # (c) /status present but unusable: also falls back (no partial guess)
+ _reset_caches(monkeypatch)
+ _patch_upstreams(monkeypatch, tkc_status={"services": {"docker": {}}})
+ subsystems = (await _get("/status")).json()["subsystems"]
+ assert subsystems["postgresql"] == "unknown" and subsystems["milvus"] == "online"
+
+
+async def test_T18_borgbackup_is_installed_but_never_reported_healthy(monkeypatch):
+ # (a) fully healthy platform must not make BorgBackup look green
+ _patch_upstreams(monkeypatch)
+ entry = (await _entries())["ton-01__borgbackup"]
+ assert entry["status"] == "unknown"
+ assert entry["statusSource"]["kind"] == "unknown"
+ assert entry["state"] == "existing"
+ assert entry["installState"] == "installed"
+ assert entry["architecture"]["state"] == "manual_verified"
+ assert entry["evidenceClass"] == "operator_provided"
+ assert entry["identities"]["unit"] == "tars-borg-daily.service"
+ assert set(entry["identities"]["units"]) == {
+ "tars-borg-daily.timer", "tars-borg-weekly.service", "tars-borg-weekly.timer"}
+
+ # (b) and it must not look *offline* either when the platform is down
+ _reset_caches(monkeypatch)
+ _patch_upstreams(monkeypatch, tkc_status=None, tkc_error="down")
+ assert (await _entries())["ton-01__borgbackup"]["status"] == "unknown"
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# X01–X03 extra contract requirements
+# ─────────────────────────────────────────────────────────────────────────────
+
+async def test_X01_maintenance_window_is_metadata_and_never_a_health_state(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ entries = await _entries()
+
+ window = entries["ton-01__borgbackup"]["maintenanceWindow"]
+ assert window["id"] == "mw-borg-weekly"
+ assert window["onCalendar"] == "Sun *-*-* 03:00:00 UTC"
+ assert window["maxDurationSeconds"] == 21600
+ assert window["active"] is None, "Slice 1b is excluded — no live window state yet"
+ assert entries["ton-01__borgbackup"]["maintenanceRole"] == "source"
+
+ impacted = set(window["expectedImpact"])
+ assert impacted == {"ton-01__tkc-service", "ton-01__milvus", "ton-01__milvus-etcd",
+ "ton-01__milvus-minio", "ton-01__neo4j", "ton-01__portainer"}
+
+ for service_id in impacted:
+ entry = entries[service_id]
+ assert entry["maintenanceRole"] == "impacted"
+ assert entry["maintenanceWindows"][0]["sourceService"] == "ton-01__borgbackup"
+ # the window never influences health: each entry still reports its own source
+ assert entry["status"] == "ok"
+
+ # PostgreSQL is not stopped by the weekly job and must not claim a window
+ # (absent values are explicit nulls, never silently missing keys)
+ assert entries["ton-01__postgresql"]["maintenanceWindow"] is None
+ assert entries["ton-01__postgresql"]["maintenanceWindows"] is None
+
+
+async def test_X02_backup_storage_uses_a_real_filesystem_source(monkeypatch):
+ _patch_upstreams(monkeypatch, backup_filesystem={
+ "mount": "/backup", "totalBytes": 500, "usedBytes": 100, "freeBytes": 400})
+ entry = (await _entries())["ton-01__backup-storage"]
+ assert entry["storage"]["mount"] == "/backup"
+ assert entry["storage"]["usedBytes"] == 100
+ assert entry["storage"]["evidenceClass"] == "machine_observed"
+ assert entry["statusSource"]["kind"] == "filesystem"
+ assert entry["kind"] == "storage"
+
+ # unreadable mountpoint ⇒ no storage numbers at all, never a guess
+ _reset_caches(monkeypatch)
+ _patch_upstreams(monkeypatch, backup_filesystem=None)
+ entry = (await _entries())["ton-01__backup-storage"]
+ assert "storage" in entry and entry["storage"] is None
+
+
+async def test_X03_borgbackup_reports_no_invented_metrics(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ entry = (await _entries())["ton-01__borgbackup"]
+
+ for field in ("retention", "lastSuccessfulRun", "nextScheduledRun",
+ "restoreVerification"):
+ assert entry[field] is None, field
+
+ assert entry["repository"]["path"] == "/backup/tars-tkc/borg"
+ assert entry["repository"]["inspectable"] is False
+ assert entry["encryption"]["enabled"] is False
+ assert entry["encryption"]["verified"] is False
+ assert entry["offHostCopy"] == {"present": False, "planned": ["second USB drive"]}
+
+ schedule = {s["unit"]: s for s in entry["schedule"]}
+ assert set(schedule) == {"tars-borg-daily.timer", "tars-borg-weekly.timer"}
+ assert schedule["tars-borg-daily.timer"]["onCalendar"] == "*-*-* 02:00:00"
+ assert schedule["tars-borg-weekly.timer"]["onCalendar"] == "Sun *-*-* 03:00:00 UTC"
+ for slot in schedule.values():
+ assert slot["enabled"] is True
+ assert slot["nextScheduledRun"] is None # Slice 1b excluded
+ assert slot["lastTriggeredRun"] is None
+
+ blob = json.dumps(entry)
+ # the PostgreSQL restore test is never mapped onto Borg, and no DR claim is made
+ assert "tkc_backup" not in blob
+ assert "disasterRecoveryTested" not in blob
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Quality patch — shared test doubles
+# ─────────────────────────────────────────────────────────────────────────────
+
+class _Resp:
+ """Minimal httpx.Response stand-in (no socket is ever opened)."""
+
+ def __init__(self, body=None, json_error=None, status_error=None):
+ self.body, self.json_error, self.status_error = body, json_error, status_error
+
+ def raise_for_status(self):
+ if self.status_error:
+ raise self.status_error
+
+ def json(self):
+ if self.json_error:
+ raise self.json_error
+ return self.body
+
+
+class _FakeUpstreamClient:
+ """Async httpx.AsyncClient stand-in that records the URLs it was asked for."""
+
+ def __init__(self, body=None, json_error=None, status_error=None, get_error=None):
+ self.resp = _Resp(body, json_error, status_error)
+ self.get_error, self.urls = get_error, []
+
+ async def get(self, url, *args, **kwargs):
+ self.urls.append(url)
+ if self.get_error:
+ raise self.get_error
+ return self.resp
+
+
+class _RecordingClient:
+ """Records the constructor kwargs of every HTTP client the code builds."""
+
+ calls: list = []
+
+ def __init__(self, *args, **kwargs):
+ _RecordingClient.calls.append(kwargs)
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *exc):
+ return False
+
+ async def get(self, *args, **kwargs):
+ raise AssertionError("no real network access is allowed in tests")
+
+
+def _http_status_error() -> httpx.HTTPStatusError:
+ return httpx.HTTPStatusError("500 Internal Server Error",
+ request=httpx.Request("GET", "http://upstream"),
+ response=httpx.Response(500))
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# H1 — TKC state AND health are evaluated jointly
+# ─────────────────────────────────────────────────────────────────────────────
+
+def test_H1_combination_matrix_is_conservative():
+ h = registry.combine_state_and_health
+ assert h({"state": "online", "health": "green"}) == "ok"
+ assert h({"state": "online", "health": "yellow"}) == "degraded"
+ assert h({"state": "online", "health": "red"}) == "error"
+ assert h({"state": "online"}) == "ok" # no health = no opinion
+ assert h({"state": "online", "health": "purple"}) == "ok" # unrecognised = no opinion
+ assert h({"state": "offline", "health": "green"}) == "error" # health never upgrades
+ assert h({"state": "degraded", "health": "red"}) == "error"
+ assert h({"state": "starting", "health": "green"}) == "unknown" # never upgraded
+ assert h({}) == "unknown"
+ assert h(None) == "unknown"
+ assert registry.health_status("RED") == "error"
+ assert registry.health_status("yellow") == "degraded"
+ assert registry.health_status(3) == "unknown"
+ assert registry.subsystem_status(None, "postgresql") is None
+ assert registry.subsystem_status({"services": {}}, "postgresql") is None
+ assert registry.subsystem_status({"knowledge": {}}, "postgresql") == "unknown"
+
+
+async def test_H1_yellow_health_never_reports_ok(monkeypatch):
+ payload = copy.deepcopy(TKC_STATUS_HEALTHY)
+ payload["knowledge"]["postgresql"]["health"] = "yellow"
+ _patch_upstreams(monkeypatch, tkc_status=payload)
+
+ entry = (await _entries())["ton-01__postgresql"]
+ assert entry["status"] == "degraded"
+ assert "health=yellow" in entry["statusDetail"]
+
+ body = (await _get("/status")).json()
+ assert {s["name"]: s["status"] for s in body["services"]}["PostgreSQL"] == "degraded"
+ # the raw subsystem block keeps TKC's own vocabulary (unchanged contract)
+ assert body["subsystems"]["postgresql"] == "online"
+
+
+async def test_H1_red_health_is_error(monkeypatch):
+ payload = copy.deepcopy(TKC_STATUS_HEALTHY)
+ payload["knowledge"]["milvus"]["health"] = "red"
+ payload["knowledge"]["neo4j"] = {"state": "degraded", "health": "green"}
+ _patch_upstreams(monkeypatch, tkc_status=payload)
+
+ entries = await _entries()
+ assert entries["ton-01__milvus"]["status"] == "error"
+ assert entries["ton-01__neo4j"]["status"] == "degraded"
+
+ body = (await _get("/status")).json()
+ statuses = {s["name"]: s["status"] for s in body["services"]}
+ assert statuses["Milvus"] == "error" and statuses["Neo4j"] == "degraded"
+
+
+async def test_H1_unknown_values_stay_visible(monkeypatch):
+ payload = copy.deepcopy(TKC_STATUS_HEALTHY)
+ payload["knowledge"]["postgresql"] = {"state": "starting", "health": "green"}
+ payload["knowledge"]["milvus"] = {"state": "online", "health": "purple"}
+ _patch_upstreams(monkeypatch, tkc_status=payload)
+
+ entries = await _entries()
+ assert entries["ton-01__postgresql"]["status"] == "unknown" # green cannot upgrade
+ assert entries["ton-01__milvus"]["status"] == "ok"
+ # the unrecognised raw values stay visible instead of being swallowed
+ assert "state=starting" in entries["ton-01__postgresql"]["statusDetail"]
+ assert "health=purple" in entries["ton-01__milvus"]["statusDetail"]
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# M1 — automated coverage for every new I/O function
+# ─────────────────────────────────────────────────────────────────────────────
+
+async def test_M1_probe_tkc_status_ok_invalid_json_http_error_and_network_error():
+ payload = {"knowledge": {"postgresql": {"state": "online"}}}
+ client = _FakeUpstreamClient(body=payload)
+ got, err = await main.probe_tkc_status(client)
+ assert got == payload and err is None
+ assert client.urls == [f"{main.TKC_BASE_URL}/status"]
+
+ got, err = await main.probe_tkc_status(_FakeUpstreamClient(body=["not", "a", "dict"]))
+ assert got is None and "non-object" in err
+
+ got, err = await main.probe_tkc_status(
+ _FakeUpstreamClient(json_error=ValueError("bad json")))
+ assert got is None and err is not None # invalid JSON never raises
+
+ got, err = await main.probe_tkc_status(_FakeUpstreamClient(status_error=_http_status_error()))
+ assert got is None and err is not None
+
+ got, err = await main.probe_tkc_status(
+ _FakeUpstreamClient(get_error=httpx.ConnectError("refused")))
+ assert got is None and "refused" in err
+
+
+async def test_M1_probe_hermes_maps_status_and_degrades():
+ got = await main.probe_hermes(_FakeUpstreamClient(body={"status": "ok", "version": "0.2.0"}))
+ assert (got.status, got.detail) == ("ok", "0.2.0")
+
+ got = await main.probe_hermes(_FakeUpstreamClient(body={"status": "unhealthy"}))
+ assert got.status == "degraded"
+
+ got = await main.probe_hermes(_FakeUpstreamClient(body=["nope"]))
+ assert got.status == "unknown" and got.detail # non-object JSON
+
+ got = await main.probe_hermes(_FakeUpstreamClient(get_error=httpx.ConnectError("no route")))
+ assert got.status == "unknown" and "no route" in got.detail
+ assert main.HERMES_HEALTH_URL.endswith("/v1/health")
+
+
+async def test_M1_cached_tkc_status_ttl_and_refetch(monkeypatch):
+ _reset_caches(monkeypatch)
+ calls = []
+
+ async def fake_probe(client):
+ calls.append(1)
+ return {"services": {}}, None
+
+ monkeypatch.setattr(main, "probe_tkc_status", fake_probe)
+ monkeypatch.setattr(main.httpx, "AsyncClient", _RecordingClient)
+
+ first = await main.cached_tkc_status()
+ second = await main.cached_tkc_status()
+ assert first == second == ({"services": {}}, None)
+ assert len(calls) == 1 # inside the TTL: served from cache
+ assert len(_RecordingClient.calls) == 1 # ...and no second client was built
+ assert _RecordingClient.calls[0]["timeout"] == main.HTTP_TIMEOUT
+
+ main._tkc_status_cache["expires_at"] = 0.0 # simulate TTL expiry
+ assert await main.cached_tkc_status() == first
+ assert len(calls) == 2 # refetched exactly once
+
+
+async def test_M1_cached_tkc_status_caches_errors(monkeypatch):
+ _reset_caches(monkeypatch)
+ calls = []
+
+ async def failing_probe(client):
+ calls.append(1)
+ return None, "connect refused"
+
+ monkeypatch.setattr(main, "probe_tkc_status", failing_probe)
+ monkeypatch.setattr(main.httpx, "AsyncClient", _RecordingClient)
+
+ assert await main.cached_tkc_status() == (None, "connect refused")
+ assert await main.cached_tkc_status() == (None, "connect refused")
+ assert len(calls) == 1 # a failing upstream is not hammered for the whole TTL
+
+
+def test_M1_backup_filesystem_usage_reads_the_mountpoint(monkeypatch):
+ seen = {}
+
+ def fake_disk_usage(path):
+ seen["path"] = path
+ return SimpleNamespace(total=500, used=100, free=400)
+
+ monkeypatch.setattr(main.shutil, "disk_usage", fake_disk_usage)
+ # Slice 1b: the readout now also records whether the target is really mounted.
+ monkeypatch.setattr(main.os.path, "ismount", lambda p: True)
+ usage = main.backup_filesystem_usage()
+ assert usage == {
+ "mount": main.BACKUP_MOUNT, "mounted": True,
+ "totalBytes": 500, "usedBytes": 100, "freeBytes": 400}
+ assert seen["path"] == main.BACKUP_MOUNT == "/backup"
+
+
+def test_M1_backup_filesystem_usage_is_fail_soft(monkeypatch):
+ def boom(path):
+ raise OSError("permission denied")
+
+ monkeypatch.setattr(main.shutil, "disk_usage", boom)
+ assert main.backup_filesystem_usage() is None # no invented numbers
+
+
+async def test_M1_http_clients_use_the_configured_timeout(monkeypatch):
+ _reset_caches(monkeypatch)
+ _patch_upstreams(monkeypatch)
+ monkeypatch.setattr(main.httpx, "AsyncClient", _RecordingClient)
+
+ await main.collect_services()
+ assert _RecordingClient.calls
+ assert all(call.get("timeout") == main.HTTP_TIMEOUT
+ for call in _RecordingClient.calls) # one timeout policy
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# M2 — single-flight for concurrent requests
+# ─────────────────────────────────────────────────────────────────────────────
+
+def _counting_probes(counts, delay=0.05):
+ async def tkc_status(): # cached_tkc_status() takes no client (M2 owns the client)
+ counts["tkc_status"] += 1
+ await asyncio.sleep(delay)
+ return TKC_STATUS_HEALTHY, None
+
+ async def tkc_health(client):
+ counts["tkc_health"] += 1
+ await asyncio.sleep(delay)
+ return (ServiceStatus(name="TKC", status="ok"), None, None, [])
+
+ async def probe(client):
+ counts["probe"] += 1
+ await asyncio.sleep(delay)
+ return ServiceStatus(name="p", status="ok", detail="v")
+
+ return tkc_status, tkc_health, probe
+
+
+async def test_M2_concurrent_services_requests_share_one_upstream_round(monkeypatch):
+ _reset_caches(monkeypatch)
+ counts = {"tkc_status": 0, "probe": 0}
+ tkc_status, _, probe = _counting_probes(counts)
+ monkeypatch.setattr(main, "cached_tkc_status", tkc_status)
+ monkeypatch.setattr(main, "probe_mcp", probe)
+ monkeypatch.setattr(main, "probe_gateway", probe)
+ monkeypatch.setattr(main, "probe_hermes", probe)
+ monkeypatch.setattr(main.httpx, "AsyncClient", _RecordingClient)
+
+ results = await asyncio.gather(*(main.collect_services() for _ in range(5)))
+
+ assert counts == {"tkc_status": 1, "probe": 3} # one round for all five callers
+ assert all(r is results[0] for r in results) # and one shared payload
+ assert len(_RecordingClient.calls) == 1
+ assert len(results[0]["services"]) == len(SERVICES)
+
+
+async def test_M2_concurrent_tkc_status_fetches_share_one_upstream_call(monkeypatch):
+ _reset_caches(monkeypatch)
+ calls = []
+
+ async def fake_probe(client):
+ calls.append(1)
+ await asyncio.sleep(0.05)
+ return {"knowledge": {}}, None
+
+ monkeypatch.setattr(main, "probe_tkc_status", fake_probe)
+ monkeypatch.setattr(main.httpx, "AsyncClient", _RecordingClient)
+
+ results = await asyncio.gather(*(main.cached_tkc_status() for _ in range(5)))
+ assert len(calls) == 1 # was 5 before the patch
+ assert all(r == results[0] for r in results)
+ assert len(_RecordingClient.calls) == 1
+
+
+async def test_M2_concurrent_status_requests_share_one_upstream_round(monkeypatch):
+ _reset_caches(monkeypatch)
+ counts = {"tkc_health": 0, "tkc_status": 0, "probe": 0}
+ tkc_status, tkc_health, probe = _counting_probes(counts)
+ monkeypatch.setattr(main, "cached_tkc_status", tkc_status)
+ monkeypatch.setattr(main, "probe_tkc", tkc_health)
+ monkeypatch.setattr(main, "probe_mcp", probe)
+ monkeypatch.setattr(main, "probe_gateway", probe)
+ monkeypatch.setattr(main, "probe_all_repos", MagicMock(return_value=[]))
+
+ results = await asyncio.gather(*(main.collect_status() for _ in range(5)))
+ assert counts == {"tkc_health": 1, "tkc_status": 1, "probe": 2}
+ assert all(r is results[0] for r in results)
+
+ again = await main.collect_status() # cache-hit path inside the TTL
+ assert again is results[0]
+ assert counts == {"tkc_health": 1, "tkc_status": 1, "probe": 2} # no extra round
+
+
+async def test_M2_sequential_requests_inside_the_ttl_do_not_refetch(monkeypatch):
+ _reset_caches(monkeypatch)
+ counts = {"tkc_status": 0, "probe": 0}
+ tkc_status, _, probe = _counting_probes(counts)
+ monkeypatch.setattr(main, "cached_tkc_status", tkc_status)
+ monkeypatch.setattr(main, "probe_mcp", probe)
+ monkeypatch.setattr(main, "probe_gateway", probe)
+ monkeypatch.setattr(main, "probe_hermes", probe)
+
+ first = await main.collect_services()
+ second = await main.collect_services()
+ assert first is second and counts == {"tkc_status": 1, "probe": 3}
+
+
+async def test_M2_one_disconnecting_caller_does_not_break_the_others(monkeypatch):
+ _reset_caches(monkeypatch)
+ counts = {"tkc_status": 0, "probe": 0}
+ tkc_status, _, probe = _counting_probes(counts, delay=0.1)
+ monkeypatch.setattr(main, "cached_tkc_status", tkc_status)
+ monkeypatch.setattr(main, "probe_mcp", probe)
+ monkeypatch.setattr(main, "probe_gateway", probe)
+ monkeypatch.setattr(main, "probe_hermes", probe)
+
+ tasks = [asyncio.create_task(main.collect_services()) for _ in range(3)]
+ await asyncio.sleep(0.02)
+ tasks[0].cancel() # client goes away mid-flight
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+
+ assert isinstance(results[0], asyncio.CancelledError)
+ for result in results[1:]:
+ assert isinstance(result, dict)
+ assert len(result["services"]) == len(SERVICES)
+ assert counts == {"tkc_status": 1, "probe": 3} # the shared round still happened once
+
+
+async def test_M2_recovers_after_the_shared_task_was_cancelled(monkeypatch):
+ _reset_caches(monkeypatch)
+ counts = {"tkc_status": 0, "probe": 0}
+ tkc_status, _, probe = _counting_probes(counts, delay=0.1)
+ monkeypatch.setattr(main, "cached_tkc_status", tkc_status)
+ monkeypatch.setattr(main, "probe_mcp", probe)
+ monkeypatch.setattr(main, "probe_gateway", probe)
+ monkeypatch.setattr(main, "probe_hermes", probe)
+
+ only = asyncio.create_task(main.collect_services())
+ await asyncio.sleep(0.02)
+ only.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await only
+
+ await asyncio.sleep(0.15) # shielded task finishes and caches
+ payload = await main.collect_services()
+ assert len(payload["services"]) == len(SERVICES)
+ assert counts["tkc_status"] == 1 # no duplicate upstream round
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# M3 — typed response models
+# ─────────────────────────────────────────────────────────────────────────────
+
+_ALL_FIELDS_ENTRY = {
+ "id": "ton-01__probe", "label": "Probe", "kind": "unit", "status": "unknown",
+ "statusDetail": "evidence", "statusSource": {"kind": "unknown", "reference": "none"},
+ "state": "existing", "installState": "unknown", "evidenceClass": "machine_observed",
+ "architecture": {"state": "unknown", "source": {"kind": "unknown", "reference": ""}},
+ "checkedAt": "2026-11-06T00:00:00+00:00", "place": {"node": "ton-01"},
+ "identities": {"container": None, "unit": "probe.service", "units": [], "endpoint": None},
+ "dependencies": [{"target": "ton-01__x", "kind": "dependency", "evidence": "e",
+ "confidence": "inferred"}],
+ "maintenanceRole": "impacted",
+ "maintenanceWindow": None,
+ "maintenanceWindows": [{"id": "mw-borg-weekly", "onCalendar": "Sun *-*-* 03:00:00 UTC",
+ "maxDurationSeconds": 21600, "active": None,
+ "sourceService": "ton-01__borgbackup"}],
+ "components": [{"name": "n", "value": "v"}], "notes": ["note"],
+ "databases": [{"name": "d", "state": "planned"}],
+ "repository": {"path": "/backup/tars-tkc/borg"},
+ "schedule": [{"unit": "tars-borg-daily.timer"}],
+ "encryption": {"enabled": False}, "retention": None, "lastSuccessfulRun": None,
+ "nextScheduledRun": None, "restoreVerification": None,
+ "offHostCopy": {"present": False}, "storage": {"mount": "/backup"},
+ "futureFieldNotInTheModel": {"anything": [1, 2]},
+}
+
+
+async def test_M3_openapi_declares_the_service_models(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ spec = (await _get("/openapi.json")).json()
+ schemas = spec["components"]["schemas"]
+ for model in ("ServiceEntry", "ServiceListResponse", "MaintenanceWindow",
+ "ServiceSource", "ServiceIdentities"):
+ assert model in schemas, model
+
+ for path, model in (("/services", "ServiceListResponse"),
+ ("/services/{service_id}", "ServiceEntry")):
+ schema = spec["paths"][path]["get"]["responses"]["200"]["content"]["application/json"]["schema"]
+ assert schema == {"$ref": f"#/components/schemas/{model}"}, (path, schema)
+
+ # the pre-existing endpoint keeps its own model
+ status_schema = spec["paths"]["/status"]["get"]["responses"]["200"]["content"]["application/json"]["schema"]
+ assert status_schema == {"$ref": "#/components/schemas/StatusResponse"}
+
+ props = schemas["ServiceEntry"]["properties"]
+ for field in ("id", "label", "kind", "status", "statusSource", "state", "installState",
+ "architecture", "maintenanceWindow", "maintenanceWindows", "storage",
+ "retention", "restoreVerification"):
+ assert field in props, field
+
+
+async def test_M3_response_model_drops_no_registry_field(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ monkeypatch.setattr(main, "build_service_entries",
+ MagicMock(return_value=[copy.deepcopy(_ALL_FIELDS_ENTRY)]))
+
+ response = await _get("/services")
+ assert response.status_code == 200
+ entry = response.json()["services"][0]
+
+ # nothing the registry produced is dropped or renamed
+ assert set(entry) >= set(_ALL_FIELDS_ENTRY)
+ for key, value in _ALL_FIELDS_ENTRY.items():
+ if key in ("maintenanceWindow", "maintenanceWindows"):
+ continue # a modelled sub-object may add declared-but-absent nulls
+ assert entry[key] == value, key
+
+ # a modelled sub-object keeps every value and only gains explicit nulls
+ window = entry["maintenanceWindows"][0]
+ assert window["id"] == "mw-borg-weekly"
+ assert window["onCalendar"] == "Sun *-*-* 03:00:00 UTC"
+ assert window["maxDurationSeconds"] == 21600
+ assert window["sourceService"] == "ton-01__borgbackup"
+ assert window["service"] is None # declared by the model, explicitly null
+ assert window["active"] is None
+
+ # extra="allow": a registry field the model does not know yet cannot be dropped
+ assert entry["futureFieldNotInTheModel"] == {"anything": [1, 2]}
+
+ detail = await _get("/services/ton-01__probe")
+ assert detail.status_code == 200
+ assert detail.json() == entry
+
+
+async def test_M3_absent_values_are_explicit_nulls(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ entry = (await _entries())["ton-01__backup-storage"]
+ for field in ("storage", "retention", "restoreVerification", "lastSuccessfulRun",
+ "nextScheduledRun", "maintenanceWindow", "maintenanceWindows"):
+ assert field in entry, field
+ assert entry[field] is None, field
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# M4 — docker runtime state is part of container evaluation
+# ─────────────────────────────────────────────────────────────────────────────
+
+def _with_docker_state(state, health="green", containers=True, missing=None):
+ payload = copy.deepcopy(TKC_STATUS_HEALTHY)
+ docker = payload["services"]["docker"]
+ docker["health"] = health
+ if state is None:
+ docker.pop("state", None)
+ else:
+ docker["state"] = state
+ if not containers:
+ docker["containers"] = {}
+ docker["missing_expected"] = missing or []
+ return payload
+
+
+async def test_M4_docker_runtime_error_downgrades_its_containers(monkeypatch):
+ _patch_upstreams(monkeypatch, tkc_status=_with_docker_state("error"))
+ entries = await _entries()
+
+ assert entries["ton-01__docker"]["status"] == "error"
+ for service_id in ("ton-01__milvus-etcd", "ton-01__milvus-minio", "ton-01__portainer",
+ "ton-01__postgresql", "ton-01__milvus", "ton-01__neo4j"):
+ assert entries[service_id]["status"] == "error", service_id
+ # the cause is visible instead of being a bare downgrade
+ assert "docker runtime: error" in entries["ton-01__milvus-etcd"]["statusDetail"]
+ assert "knowledge_objects=101" in entries["ton-01__postgresql"]["statusDetail"]
+
+
+async def test_M4_docker_runtime_degraded_downgrades_its_containers(monkeypatch):
+ _patch_upstreams(monkeypatch, tkc_status=_with_docker_state("online", health="yellow"))
+ entries = await _entries()
+ assert entries["ton-01__docker"]["status"] == "degraded"
+ assert entries["ton-01__milvus-etcd"]["status"] == "degraded"
+ assert entries["ton-01__postgresql"]["status"] == "degraded"
+
+
+async def test_M4_absent_runtime_state_never_invents_or_flips_a_container(monkeypatch):
+ # no runtime state reported: presence in the container list stays the evidence
+ _patch_upstreams(monkeypatch, tkc_status=_with_docker_state(None))
+ entries = await _entries()
+ assert entries["ton-01__docker"]["status"] == "unknown"
+ assert entries["ton-01__milvus-etcd"]["status"] == "ok"
+
+ # runtime in error, but this container is not reported at all: no invented failure
+ _reset_caches(monkeypatch)
+ _patch_upstreams(monkeypatch, tkc_status=_with_docker_state("error", containers=False))
+ entries = await _entries()
+ assert entries["ton-01__milvus-etcd"]["status"] == "unknown"
+ assert "not reported" in entries["ton-01__milvus-etcd"]["statusDetail"]
+
+ # an expected-but-missing container is a real error, even with a healthy runtime
+ _reset_caches(monkeypatch)
+ _patch_upstreams(monkeypatch,
+ tkc_status=_with_docker_state("online", containers=False,
+ missing=["milvus-minio"]))
+ entries = await _entries()
+ assert entries["ton-01__milvus-minio"]["status"] == "error"
+ assert "missing_expected" in entries["ton-01__milvus-minio"]["statusDetail"]
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# AUTH — bearer gate of the new endpoints
+# ─────────────────────────────────────────────────────────────────────────────
+
+_OPEN_PATHS = ("/services", "/services/ton-01__borgbackup")
+
+
+async def test_AUTH_services_require_bearer_when_key_is_set(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ monkeypatch.setattr(main, "STATUS_API_KEY", "test-secret-key")
+ for path in _OPEN_PATHS:
+ assert (await _get(path)).status_code == 401, path
+ assert (await _get_with(path, {"Authorization": "Bearer wrong"})).status_code == 401, path
+
+
+async def test_AUTH_services_accept_the_configured_bearer(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ monkeypatch.setattr(main, "STATUS_API_KEY", "test-secret-key")
+ for path in _OPEN_PATHS:
+ response = await _get_with(path, {"Authorization": "Bearer test-secret-key"})
+ assert response.status_code == 200, path
+
+
+async def test_AUTH_services_are_open_when_no_key_is_configured(monkeypatch):
+ _patch_upstreams(monkeypatch)
+ monkeypatch.setattr(main, "STATUS_API_KEY", "")
+ for path in _OPEN_PATHS:
+ assert (await _get(path)).status_code == 200, path
+
+
+async def test_AUTH_health_stays_unauthenticated(monkeypatch):
+ monkeypatch.setattr(main, "STATUS_API_KEY", "test-secret-key")
+ assert (await _get("/health")).status_code == 200
diff --git a/services/tars-status/tests/test_slice1b.py b/services/tars-status/tests/test_slice1b.py
new file mode 100644
index 0000000..564d925
--- /dev/null
+++ b/services/tars-status/tests/test_slice1b.py
@@ -0,0 +1,228 @@
+"""Slice 1b — container evidence, backup job evidence, honest maintenance.
+
+The 15 required cases, each driven from a crafted TKC /status payload or from
+unit properties. No network, no host systemd, no real backup job.
+"""
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+
+import pytest
+
+from app import main as M
+from app import services_registry as R
+
+NOW = datetime(2026, 11, 6, 12, 0, 0, tzinfo=timezone.utc)
+
+
+def _iso(dt: datetime) -> str:
+ return dt.astimezone(timezone.utc).isoformat()
+
+
+def _payload(containers=None, knowledge=None):
+ base = {
+ "generated_at": _iso(NOW),
+ "services": {"docker": {"state": "online", "health": "green",
+ "containers": containers or {}, "missing_expected": []}},
+ "knowledge": knowledge or {},
+ }
+ return base
+
+
+def _entries(**kwargs):
+ defaults = dict(
+ tkc_status=_payload(), tkc_error=None,
+ mcp={"status": "ok", "detail": "v0.4.0"},
+ gateway={"status": "ok", "detail": "ok"},
+ hermes={"status": "ok", "detail": "0.2.0"},
+ backup_filesystem=None, backup_job=None,
+ checked_at=_iso(NOW), health_max_age_seconds=90,
+ maintenance_now=NOW,
+ )
+ defaults.update(kwargs)
+ return {e["id"]: e for e in R.build_service_entries(**defaults)}
+
+
+def _containers(**overrides):
+ base = {"milvus-etcd": "Up 3 hours (healthy)",
+ "milvus-minio": "Up 3 hours (healthy)",
+ "milvus-standalone": "Up 3 hours (healthy)",
+ "portainer": "Up 3 hours",
+ "tkc-neo4j": "Up 3 hours",
+ "tkc-postgres": "Up 10 days"}
+ base.update(overrides)
+ return base
+
+
+# ── 1–5. Docker container states ─────────────────────────────────────────────
+
+def test_1_running_without_healthcheck_is_runtime_evidence_only():
+ e = _entries(tkc_status=_payload(_containers()))["ton-01__portainer"]
+ assert e["status"] == "ok"
+ assert e["health"] == "unknown"
+ assert e["healthReasonCode"] == "runtime_only"
+
+
+def test_2_exited_container_is_unhealthy_and_shows_exit_code():
+ e = _entries(tkc_status=_payload(_containers(portainer="Exited (1) 2 hours ago")))[
+ "ton-01__portainer"]
+ assert e["status"] == "error"
+ assert e["health"] == "unhealthy"
+ assert e["healthReasonCode"] == "container_exited"
+ assert "Exited (1)" in e["statusDetail"]
+
+
+def test_3_restarting_container_is_unhealthy():
+ e = _entries(tkc_status=_payload(_containers(portainer="Restarting (1) 5 seconds ago")))[
+ "ton-01__portainer"]
+ assert e["status"] == "error"
+ assert e["health"] == "unhealthy"
+ assert e["healthReasonCode"] == "container_restarting"
+
+
+def test_4_failed_healthcheck_is_unhealthy():
+ e = _entries(tkc_status=_payload(_containers(**{"milvus-etcd": "Up 3 hours (unhealthy)"})))[
+ "ton-01__milvus-etcd"]
+ assert e["status"] == "error"
+ assert e["health"] == "unhealthy"
+ assert e["healthReasonCode"] == "container_unhealthy"
+
+
+def test_5_container_absent_from_inventory_is_unknown_and_says_so():
+ containers = _containers()
+ del containers["milvus-etcd"]
+ e = _entries(tkc_status=_payload(containers))["ton-01__milvus-etcd"]
+ assert e["status"] == "unknown"
+ assert e["health"] == "unknown"
+ assert "not reported" in e["statusDetail"]
+
+
+# ── 6–9. Maintenance is evidence, not a schedule ─────────────────────────────
+
+def _period(start_min, end_min, **extra):
+ p = {"id": "mp-1", "reason": "declared window",
+ "startsAt": _iso(NOW + timedelta(minutes=start_min)),
+ "services": ["ton-01__postgresql"]}
+ if end_min is not None:
+ p["endsAt"] = _iso(NOW + timedelta(minutes=end_min))
+ p.update(extra)
+ return (p,)
+
+
+def _with_periods(monkeypatch, periods):
+ monkeypatch.setattr(R, "MAINTENANCE_PERIODS", periods)
+
+
+def _knowledge_online():
+ return {"postgresql": {"state": "online", "health": "green", "knowledge_objects": 101},
+ "milvus": {"state": "online", "health": "green"},
+ "neo4j": {"state": "online", "health": "green", "nodes": 104}}
+
+
+def test_6_explicitly_declared_maintenance_is_active_and_keeps_health(monkeypatch):
+ _with_periods(monkeypatch, _period(-10, 30))
+ e = _entries(tkc_status=_payload(_containers(), _knowledge_online()))[
+ "ton-01__postgresql"]
+ assert e["operationalMode"] == "maintenance"
+ assert e["maintenance"]["active"] is True
+ assert e["maintenance"]["kind"] == "declared"
+ assert e["health"] == "healthy" # maintenance never masks the truth
+
+
+def test_7_historical_maintenance_period_does_not_stay_active(monkeypatch):
+ _with_periods(monkeypatch, _period(-120, -60))
+ e = _entries(tkc_status=_payload(_containers(), _knowledge_online()))[
+ "ton-01__postgresql"]
+ assert e["operationalMode"] == "normal"
+ assert e["maintenance"] is None
+
+
+def test_8_stopped_unit_without_evidence_is_not_maintenance():
+ job = {"service": {"ActiveState": "inactive", "SubState": "dead",
+ "Result": "success", "ExecMainStatus": "0", "InvocationID": ""},
+ "timer": {"TimersCalendar": "*-*-* 02:00:00"}}
+ e = _entries(backup_job=job)["ton-01__borgbackup"]
+ assert e["status"] == "unknown" # stopped is not "healthy"
+ assert e["operationalMode"] == "normal" # and not maintenance either
+
+
+def test_9_maintenance_ends_and_returns_to_normal_by_itself(monkeypatch):
+ _with_periods(monkeypatch, _period(-10, 5))
+ later = NOW + timedelta(minutes=10)
+ e = _entries(tkc_status=_payload(_containers(), _knowledge_online()),
+ maintenance_now=later)["ton-01__postgresql"]
+ assert e["operationalMode"] == "normal"
+ assert e["maintenance"] is None
+
+
+# ── 10–13. BorgBackup job evidence ───────────────────────────────────────────
+
+def _job(result="success", exit_code="0", started=None, exited=None,
+ active="inactive", invocation="inv-1", calendar="*-*-* 02:00:00"):
+ return {"service": {"ActiveState": active, "SubState": "dead", "Result": result,
+ "ExecMainStatus": exit_code, "InvocationID": invocation,
+ "ExecMainStartTimestamp": started,
+ "ExecMainExitTimestamp": exited},
+ "timer": {"TimersCalendar": calendar}}
+
+
+def test_10_last_backup_success_is_healthy():
+ started = _iso(NOW - timedelta(hours=2))
+ exited = _iso(NOW - timedelta(hours=1, minutes=30))
+ e = _entries(backup_job=_job(started=started, exited=exited))["ton-01__borgbackup"]
+ assert e["status"] == "ok"
+ assert e["health"] == "healthy"
+ assert e["healthReasonCode"] == "backup_success"
+ assert e["lastSuccess"] == exited
+ assert e["statusSource"]["kind"] == "systemd"
+
+
+def test_11_last_backup_failure_is_unhealthy_and_never_masked():
+ started = _iso(NOW - timedelta(hours=2))
+ exited = _iso(NOW - timedelta(hours=1))
+ e = _entries(backup_job=_job(result="failed", exit_code="1",
+ started=started, exited=exited))["ton-01__borgbackup"]
+ assert e["status"] == "error"
+ assert e["health"] == "unhealthy"
+ assert e["healthReasonCode"] == "backup_failed"
+ assert e["lastSuccess"] is None # an older success must not cover this
+
+
+def test_12_backup_currently_running_is_degraded_not_healthy():
+ e = _entries(backup_job=_job(started=_iso(NOW - timedelta(minutes=20)),
+ exited=None, active="active"))["ton-01__borgbackup"]
+ assert e["status"] == "degraded"
+ assert e["health"] == "degraded"
+ assert e["healthReasonCode"] == "backup_running"
+
+
+def test_13_stale_success_is_degraded():
+ exited = _iso(NOW - timedelta(days=5))
+ e = _entries(backup_job=_job(started=_iso(NOW - timedelta(days=5, hours=1)),
+ exited=exited))["ton-01__borgbackup"]
+ assert e["status"] == "degraded"
+ assert e["health"] == "degraded"
+ assert e["healthReasonCode"] == "backup_stale"
+
+
+# ── 14–15. Storage vs job, and an unmounted target ───────────────────────────
+
+def test_14_storage_readable_without_any_backup_result():
+ fs = {"mount": "/backup", "mounted": True,
+ "totalBytes": 500, "usedBytes": 100, "freeBytes": 400}
+ entries = _entries(backup_filesystem=fs)
+ assert entries["ton-01__backup-storage"]["health"] == "healthy"
+ assert entries["ton-01__backup-storage"]["status"] == "ok"
+ # ...but a readable mount proves nothing about a successful backup
+ assert entries["ton-01__borgbackup"]["status"] == "unknown"
+ assert entries["ton-01__borgbackup"]["health"] == "unknown"
+
+
+def test_15_expected_device_not_mounted_is_a_concrete_failure():
+ fs = {"mount": "/backup", "mounted": False,
+ "totalBytes": 500, "usedBytes": 100, "freeBytes": 400}
+ e = _entries(backup_filesystem=fs)["ton-01__backup-storage"]
+ assert e["status"] == "error"
+ assert e["health"] == "unhealthy"
+ assert e["healthReasonCode"] == "storage_not_mounted"
+ assert "not mounted" in e["statusDetail"]
diff --git a/tars-backlog/tars-tkc-brain-graph/APPLY-INSTRUCTIONS.md b/tars-backlog/tars-tkc-brain-graph/APPLY-INSTRUCTIONS.md
new file mode 100644
index 0000000..b5b6852
--- /dev/null
+++ b/tars-backlog/tars-tkc-brain-graph/APPLY-INSTRUCTIONS.md
@@ -0,0 +1,169 @@
+# Phase B — Application Instructions
+
+## Prerequisites
+
+- [ ] Phase A complete: `tars-tkc` added to Engineering Gateway DEV + LIVE allowlists
+- [ ] `/opt/tars/dev/bob/tars-tkc` exists on `bob/dev` branch
+- [ ] Test venv present and all existing tests pass (establish baseline count before any changes)
+
+---
+
+## Step 1 — Read actual tars-tkc source
+
+Once the Gateway allows `tars-tkc` reads, Bob runs:
+
+```
+read_repository_file(repository="tars-tkc", path="service/app/graph_store.py")
+read_repository_file(repository="tars-tkc", path="service/app/main.py")
+read_repository_file(repository="tars-tkc", path="tests/conftest.py")
+```
+
+**Do not skip this step.** The staged files are reference implementations.
+The actual integration must match what the real source code contains:
+
+- Verify the Neo4j driver attribute name in GraphStore
+ (confirmed by human review: `self.driver` — not `self._driver`; verify this
+ is still the case in the current file before writing anything)
+- Verify the import structure used by existing modules
+- Verify where existing `/brain/*` routes appear in main.py
+- Verify the mock target path for `graph_store` in tests (actual variable name in main.py)
+- Check whether `models.py` exists or if Pydantic models live elsewhere
+
+---
+
+## Step 2 — Establish the real test baseline
+
+Before any changes to the tars-tkc DEV workspace, run the test suite and
+record the exact result:
+
+```bash
+cd /opt/tars/dev/bob/tars-tkc
+.venv/bin/python -m pytest tests/ -v 2>&1 | tail -5
+```
+
+Record: `X passed, Y failed, Z skipped` — this is the baseline.
+Do not proceed if any test already fails. Investigate first.
+
+---
+
+## Step 3 — Write new file: graph_models.py
+
+Source: `tars-backlog/tars-tkc-brain-graph/service/app/graph_models.py`
+
+This file is entirely new — no merging required.
+
+```
+write_development_file(
+ repository="tars-tkc",
+ path="service/app/graph_models.py",
+ content=<full content of staged graph_models.py>
+)
+```
+
+---
+
+## Step 4 — Integrate get_brain_graph() into graph_store.py
+
+Source: `tars-backlog/tars-tkc-brain-graph/service/app/graph_store_brain_graph.py`
+
+After reading the actual graph_store.py (Step 1), adapt the reference:
+
+1. Confirm the driver attribute name matches `self.driver` (or correct if different)
+2. Add `from app.graph_models import GraphEdge, GraphNode, GraphResponse` to imports —
+ using the same import style as the rest of the file
+3. Add the module-level helpers `_BRAIN_GRAPH_QUERY`, `_BLOCKED_PROPS`,
+ `_sanitise_props`, `_node_id` after existing module-level code
+4. Add `get_brain_graph()` to the GraphStore class after existing methods
+5. Write back the **complete modified file** via `write_development_file`
+
+---
+
+## Step 5 — Add route to main.py
+
+Source: `tars-backlog/tars-tkc-brain-graph/service/app/main_brain_graph_route.py`
+
+After reading the actual main.py (Step 1):
+
+1. Add `from app.graph_models import GraphResponse` to imports
+2. Add `@app.get("/brain/graph", ...)` route in the same block as other `/brain/*` routes
+3. Verify the `graph_store` variable name used in the route handler matches main.py
+4. Write back the **complete modified file** via `write_development_file`
+
+---
+
+## Step 6 — Write test file
+
+Source: `tars-backlog/tars-tkc-brain-graph/tests/test_brain_graph.py`
+
+Before writing, confirm:
+- The mock patch target `"app.main.graph_store"` matches the actual variable name
+- `from app.graph_store import _node_id` will resolve (it is module-level in the staged
+ implementation; verify it remains module-level after integration)
+
+```
+write_development_file(
+ repository="tars-tkc",
+ path="tests/test_brain_graph.py",
+ content=<adapted content>
+)
+```
+
+---
+
+## Step 7 — Run tests
+
+```bash
+cd /opt/tars/dev/bob/tars-tkc
+.venv/bin/python -m pytest tests/ -v
+```
+
+Required results:
+- All previously passing tests still pass (zero regressions against baseline from Step 2)
+- New unit tests in test_brain_graph.py pass (they are mocked, no live Neo4j needed)
+- Integration tests are skipped (marked `@pytest.mark.integration`)
+
+If any previously passing test now fails: STOP, investigate, fix before continuing.
+
+---
+
+## Step 8 — Diff and review
+
+```
+development_repository_diff(repository="tars-tkc")
+```
+
+Expected changed files:
+- `service/app/graph_models.py` (new)
+- `service/app/graph_store.py` (modified — new method + module-level helpers)
+- `service/app/main.py` (modified — new route + import)
+- `tests/test_brain_graph.py` (new)
+
+Present full diff to human for review before committing.
+
+---
+
+## Step 9 — Scoped commit (after Human Gate 1)
+
+```
+development_repository_commit(
+ repository="tars-tkc",
+ message="feat(tkc): add read-only brain graph endpoint",
+ files=[
+ "service/app/graph_models.py",
+ "service/app/graph_store.py",
+ "service/app/main.py",
+ "tests/test_brain_graph.py",
+ ]
+)
+```
+
+---
+
+## Step 10 — engineering_submit
+
+```
+engineering_submit(repository="tars-tkc")
+```
+
+Pushes `bob/dev` to GitHub for human review.
+Does NOT merge. Does NOT deploy. Does NOT restart the service.
diff --git a/tars-backlog/tars-tkc-brain-graph/README.md b/tars-backlog/tars-tkc-brain-graph/README.md
new file mode 100644
index 0000000..6d54a21
--- /dev/null
+++ b/tars-backlog/tars-tkc-brain-graph/README.md
@@ -0,0 +1,70 @@
+# TKC Brain Graph — Staged Implementation Package
+
+**Prepared by:** Bob (AI-001)
+**Date:** 2026-09-03
+**Status:** STAGED — awaiting tars-tkc DEV workspace enablement
+
+---
+
+## Purpose
+
+This directory contains the complete, ready-to-apply implementation of the
+`GET /brain/graph` read-only endpoint for the TKC service.
+
+Files here are staged because the Engineering Gateway currently does not
+expose `tars-tkc` as a DEV workspace. Once the Gateway is updated (see
+`gateway-patch/` below), these files move directly to the tars-tkc DEV
+workspace and can be committed.
+
+---
+
+## Target Repository
+
+`/opt/tars/dev/bob/tars-tkc` (branch: `bob/dev`)
+
+---
+
+## File Mapping
+
+| Staged file | Target path in tars-tkc |
+|---|---|
+| `service/app/graph_models.py` | `service/app/graph_models.py` (NEW) |
+| `service/app/graph_store.patch.py` | Patch to apply to `service/app/graph_store.py` |
+| `service/app/main.patch.py` | Patch to apply to `service/app/main.py` |
+| `tests/test_brain_graph.py` | `tests/test_brain_graph.py` (NEW) |
+
+---
+
+## Application Sequence
+
+After Gateway enablement:
+
+```
+1. Bob reads LIVE tars-tkc source via read_repository_file(repository="tars-tkc")
+ - service/app/graph_store.py
+ - service/app/main.py
+ - service/app/models.py (if exists)
+ - tests/conftest.py
+
+2. Bob writes to DEV workspace via write_development_file(repository="tars-tkc")
+ - Applies graph_models.py (new file)
+ - Integrates graph_store patch into actual graph_store.py
+ - Adds GET /brain/graph route to main.py
+ - Adds tests/test_brain_graph.py
+
+3. Bob runs tests:
+ cd /opt/tars/dev/bob/tars-tkc
+ .venv/bin/python -m pytest tests/ -v
+ (must pass: 82/82 existing + new graph tests)
+
+4. development_repository_diff → human review → scoped commit → engineering_submit
+```
+
+---
+
+## Stop Conditions (unchanged)
+
+- No deployment
+- No service restart
+- No modification of /opt/tars/apps/tkc-service
+- No production change without separate Human Gate
diff --git a/tars-backlog/tars-tkc-brain-graph/gateway-patch/GATEWAY-EXPANSION.md b/tars-backlog/tars-tkc-brain-graph/gateway-patch/GATEWAY-EXPANSION.md
new file mode 100644
index 0000000..afcb658
--- /dev/null
+++ b/tars-backlog/tars-tkc-brain-graph/gateway-patch/GATEWAY-EXPANSION.md
@@ -0,0 +1,124 @@
+# Engineering Gateway — tars-tkc Repository Expansion
+
+**Prepared by:** Bob (AI-001)
+**Status:** PENDING HUMAN APPLICATION
+**Target:** `/opt/tars/repos/tars-gateway/`
+
+---
+
+## What Must Be Changed
+
+The Engineering Gateway at `/opt/tars/repos/tars-gateway/` enforces its
+repository allowlist as an enum (Pydantic `Literal` or equivalent).
+
+Two allowlists must be extended:
+
+### 1. LIVE read allowlist
+
+Current:
+```
+tars-platform | tars-raspberry-v3 | tars-docs
+```
+
+Required addition:
+```
+tars-tkc → /opt/tars/repos/tars-tkc
+```
+
+### 2. DEV workspace allowlist
+
+Current:
+```
+tars-platform → /opt/tars/dev/bob/tars-platform
+tars-interaction-runtime → /opt/tars/dev/bob/tars-interaction-runtime
+```
+
+Required addition:
+```
+tars-tkc → /opt/tars/dev/bob/tars-tkc
+```
+
+---
+
+## What the Gateway Must Expose (DEV operations)
+
+All existing DEV operations, applied to `tars-tkc`:
+
+| Operation | Gateway endpoint |
+|---|---|
+| `development_repository_status` | `GET /dev/tars-tkc/status` |
+| `read_development_file` | `GET /dev/tars-tkc/file?path=...` |
+| `write_development_file` | `PUT /dev/tars-tkc/file` |
+| `write_development_file_lines` | `PUT /dev/tars-tkc/file-lines` |
+| `development_repository_diff` | `GET /dev/tars-tkc/diff` |
+| `development_repository_commit` | `POST /dev/tars-tkc/commit` |
+| `engineering_submit` | `POST /dev/tars-tkc/push-github` |
+
+And LIVE read:
+| `read_repository_file` | `GET /repos/tars-tkc/file?path=...` |
+| `repository_tree` | `GET /repos/tars-tkc/tree` |
+| `search_repository` | `GET /repos/tars-tkc/search` |
+| `repository_log` | `GET /repos/tars-tkc/log` |
+
+---
+
+## Security constraints (unchanged from existing pattern)
+
+- DEV writes enforce workspace escape protection (no `..` traversal)
+- `commit` requires explicit `files[]` — no `git add -A`
+- `push-github` enforces `bob/dev` branch
+- LIVE reads are read-only — no writes permitted to `/opt/tars/repos/tars-tkc`
+- No direct writes to `/opt/tars/apps/tkc-service` (runtime tree, not a repo)
+
+---
+
+## DEV Workspace Init (TON-01 — human action required)
+
+Before the Gateway can serve the DEV workspace, the workspace must exist:
+
+```bash
+# On TON-01 as tars-admin or equivalent:
+
+# Option A — separate clone (preferred for clean isolation)
+cd /opt/tars/dev/bob/
+git clone /opt/tars/repos/tars-tkc tars-tkc
+cd tars-tkc
+git checkout -b bob/dev
+
+# Option B — Git worktree from LIVE repo
+cd /opt/tars/repos/tars-tkc
+git worktree add /opt/tars/dev/bob/tars-tkc bob/dev
+
+# Restore test venv (from Phase-1 session — may already exist)
+cd /opt/tars/dev/bob/tars-tkc
+python3.12 -m venv .venv
+.venv/bin/pip install -r service/requirements.txt
+.venv/bin/pip install -r tests/requirements-test.txt
+# (or combined: pip install -r service/requirements.txt -r tests/requirements-test.txt)
+
+# Verify baseline tests still pass
+.venv/bin/python -m pytest tests/ -v
+# Expected: 82/82 passed
+```
+
+---
+
+## Verification After Gateway Change
+
+Once the Gateway is updated and restarted, Bob verifies by calling:
+
+```
+read_repository_file(repository="tars-tkc", path="service/app/main.py")
+```
+
+If this returns file content (not a 404 or validation error), Phase A is complete
+and Phase B (implementation) can begin.
+
+---
+
+## Commit this specification
+
+This file should be committed to tars-platform DEV as:
+`tars-backlog/tars-tkc-brain-graph/gateway-patch/GATEWAY-EXPANSION.md`
+
+It is the Change Record for the Gateway extension.
diff --git a/tars-backlog/tars-tkc-brain-graph/service/app/graph_models.py b/tars-backlog/tars-tkc-brain-graph/service/app/graph_models.py
new file mode 100644
index 0000000..94dd2b9
--- /dev/null
+++ b/tars-backlog/tars-tkc-brain-graph/service/app/graph_models.py
@@ -0,0 +1,112 @@
+"""
+graph_models.py — Pydantic response models for GET /brain/graph.
+
+These are NEW models added alongside the existing model set.
+Place in: service/app/graph_models.py
+
+Design constraints:
+- Read-only endpoint; no write models here.
+- object_id is the canonical cross-store identifier.
+- Nodes without object_id use a deterministic external identifier
+ (Neo4j elementId is NOT used — it is an internal implementation detail
+ and not stable across restores).
+- All fields Optional where Neo4j may not carry the property.
+- No secrets, no internal IDs, no Neo4j connection parameters returned.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from pydantic import BaseModel, Field
+
+
+class GraphNode(BaseModel):
+ """A single node in the knowledge graph response."""
+
+ id: str = Field(
+ ...,
+ description=(
+ "Canonical identifier. Equals object_id (UUID) when available. "
+ "Falls back to a deterministic external key when object_id is absent."
+ ),
+ )
+ name: str | None = Field(
+ None,
+ description="Human-readable node name (Neo4j 'name' property).",
+ )
+ labels: list[str] = Field(
+ default_factory=list,
+ description="All Neo4j labels on this node (e.g. ['KnowledgeObject', 'TARS']).",
+ )
+ object_id: str | None = Field(
+ None,
+ description="UUID from the TKC knowledge_objects table, if present.",
+ )
+ object_type: str | None = Field(
+ None,
+ description="TKC object_type (e.g. 'architecture_decision', 'conversation').",
+ )
+ layer: str | None = Field(
+ None,
+ description="TKC layer: 'raw' or 'wiki'.",
+ )
+ domain: str | None = Field(
+ None,
+ description="TKC domain: 'work', 'private', or 'unclassified'.",
+ )
+ status: str | None = Field(
+ None,
+ description="TKC lifecycle status: 'active', 'candidate', or 'superseded'.",
+ )
+ version: str | None = Field(
+ None,
+ description="Version string if present on the node.",
+ )
+ properties: dict[str, Any] = Field(
+ default_factory=dict,
+ description=(
+ "Additional non-sensitive Neo4j properties not covered by named fields. "
+ "Never includes passwords, tokens, or connection parameters."
+ ),
+ )
+
+
+class GraphEdge(BaseModel):
+ """A directed relationship in the knowledge graph."""
+
+ source: str = Field(
+ ...,
+ description="id of the source node (same namespace as GraphNode.id).",
+ )
+ target: str = Field(
+ ...,
+ description="id of the target node.",
+ )
+ type: str = Field(
+ ...,
+ description="Neo4j relationship type (e.g. 'DERIVED_FROM', 'HAS_COMPONENT').",
+ )
+ properties: dict[str, Any] = Field(
+ default_factory=dict,
+ description="Existing relationship properties from Neo4j.",
+ )
+
+
+class GraphResponse(BaseModel):
+ """Full graph topology response for GET /brain/graph."""
+
+ nodes: list[GraphNode] = Field(default_factory=list)
+ edges: list[GraphEdge] = Field(default_factory=list)
+ node_count: int = Field(0, description="Convenience count of nodes.")
+ edge_count: int = Field(0, description="Convenience count of edges.")
+
+ @classmethod
+ def from_parts(
+ cls, nodes: list[GraphNode], edges: list[GraphEdge]
+ ) -> "GraphResponse":
+ return cls(
+ nodes=nodes,
+ edges=edges,
+ node_count=len(nodes),
+ edge_count=len(edges),
+ )
diff --git a/tars-backlog/tars-tkc-brain-graph/service/app/graph_store_brain_graph.py b/tars-backlog/tars-tkc-brain-graph/service/app/graph_store_brain_graph.py
new file mode 100644
index 0000000..fccf8f7
--- /dev/null
+++ b/tars-backlog/tars-tkc-brain-graph/service/app/graph_store_brain_graph.py
@@ -0,0 +1,183 @@
+"""
+graph_store_brain_graph.py — Extension for GraphStore.get_brain_graph().
+
+INTEGRATION NOTE:
+This is a reference module, not the full graph_store.py replacement.
+It contains one new method to be added to the existing GraphStore class.
+
+When tars-tkc DEV workspace is accessible:
+1. Bob reads the actual service/app/graph_store.py
+2. Inspects the exact attribute name used for the Neo4j driver
+ (confirmed: self.driver — NOT self._driver)
+3. Verifies all existing method signatures and imports before writing
+4. Integrates get_brain_graph() into the real file — no mechanical paste
+
+The method is written to be self-contained:
+- Uses self.driver (verified attribute name in the live GraphStore)
+- No new imports beyond what graph_store.py already uses
+- No new credentials, no second Neo4j client
+- Read-only Cypher — no writes
+
+=============================================================================
+REFERENCE IMPLEMENTATION — adapt after reading actual graph_store.py:
+=============================================================================
+"""
+
+# ---------------------------------------------------------------------------
+# Imports to add at the top of graph_store.py (verify against actual file):
+# ---------------------------------------------------------------------------
+# from app.graph_models import GraphEdge, GraphNode, GraphResponse
+# ---------------------------------------------------------------------------
+
+_BRAIN_GRAPH_QUERY = """
+MATCH (n)
+OPTIONAL MATCH (n)-[r]->(m)
+RETURN
+ n,
+ labels(n) AS node_labels,
+ collect({
+ target_node: m,
+ target_labels: labels(m),
+ rel_type: type(r),
+ rel_props: properties(r)
+ }) AS rels
+"""
+
+# Sensitive property names that must never be returned in the API response.
+_BLOCKED_PROPS: frozenset[str] = frozenset({
+ "password", "token", "secret", "key", "credential",
+ "api_key", "auth_token", "bearer", "neo4j_password",
+ "postgres_password", "milvus_token",
+})
+
+
+def _sanitise_props(props: dict) -> dict:
+ """Remove any property whose name looks sensitive."""
+ return {k: v for k, v in props.items() if k.lower() not in _BLOCKED_PROPS}
+
+
+def _node_id(node_props: dict) -> str:
+ """Return the canonical identifier for a node.
+
+ Priority:
+ 1. object_id — UUID cross-referenced with PostgreSQL
+ 2. name — stable identifier (present on TARS/component nodes)
+ 3. hash — deterministic fallback; never a Neo4j internal ID
+
+ Neo4j internal IDs (element_id / legacy integer) are NOT used —
+ they are implementation details and not stable across database restores.
+ """
+ oid = node_props.get("object_id")
+ if oid:
+ return str(oid)
+ name = node_props.get("name")
+ if name:
+ return f"name:{name}"
+ import hashlib
+ import json
+ stable = hashlib.sha256(
+ json.dumps(sorted(node_props.items()), sort_keys=True).encode()
+ ).hexdigest()[:16]
+ return f"hash:{stable}"
+
+
+# =============================================================================
+# METHOD to add to class GraphStore — adapt to actual driver attribute name:
+# =============================================================================
+
+"""
+ def get_brain_graph(self) -> "GraphResponse":
+ \"\"\"Return the full knowledge graph topology as nodes and edges.
+
+ Read-only. No writes. Uses self.driver (existing Neo4j driver).
+ Sensitive properties are stripped from the response.
+
+ Returns GraphResponse with:
+ - nodes: all Neo4j nodes; canonical id = object_id or name fallback
+ - edges: all relationships between those nodes
+ \"\"\"
+ from app.graph_models import GraphEdge, GraphNode, GraphResponse
+
+ seen_node_ids: set[str] = set()
+ nodes: list[GraphNode] = []
+ edges: list[GraphEdge] = []
+
+ with self.driver.session() as session:
+ result = session.run(_BRAIN_GRAPH_QUERY)
+ for record in result:
+ n_node = record["n"]
+ n_props = dict(n_node.items())
+ n_labels = record["node_labels"] or []
+
+ n_id = _node_id(n_props)
+
+ if n_id not in seen_node_ids:
+ seen_node_ids.add(n_id)
+ safe_props = _sanitise_props(n_props)
+ named_keys = {
+ "object_id", "object_type", "name",
+ "layer", "domain", "status", "version",
+ }
+ extra_props = {
+ k: v for k, v in safe_props.items()
+ if k not in named_keys
+ }
+ nodes.append(GraphNode(
+ id=n_id,
+ name=n_props.get("name"),
+ labels=n_labels,
+ object_id=n_props.get("object_id"),
+ object_type=n_props.get("object_type"),
+ layer=n_props.get("layer"),
+ domain=n_props.get("domain"),
+ status=n_props.get("status"),
+ version=n_props.get("version"),
+ properties=extra_props,
+ ))
+
+ for rel in record["rels"]:
+ if rel["target_node"] is None:
+ continue # isolated node, no outgoing edge
+ m_node = rel["target_node"]
+ m_props = dict(m_node.items())
+ m_labels = rel["target_labels"] or []
+ m_id = _node_id(m_props)
+
+ if m_id not in seen_node_ids:
+ seen_node_ids.add(m_id)
+ safe_m = _sanitise_props(m_props)
+ named_keys_m = {
+ "object_id", "object_type", "name",
+ "layer", "domain", "status", "version",
+ }
+ extra_m = {
+ k: v for k, v in safe_m.items()
+ if k not in named_keys_m
+ }
+ nodes.append(GraphNode(
+ id=m_id,
+ name=m_props.get("name"),
+ labels=m_labels,
+ object_id=m_props.get("object_id"),
+ object_type=m_props.get("object_type"),
+ layer=m_props.get("layer"),
+ domain=m_props.get("domain"),
+ status=m_props.get("status"),
+ version=m_props.get("version"),
+ properties=extra_m,
+ ))
+
+ rel_type = rel["rel_type"]
+ if rel_type is not None:
+ edges.append(GraphEdge(
+ source=n_id,
+ target=m_id,
+ type=rel_type,
+ properties=_sanitise_props(dict(rel["rel_props"] or {})),
+ ))
+
+ return GraphResponse.from_parts(nodes=nodes, edges=edges)
+"""
+# =============================================================================
+# END OF REFERENCE METHOD
+# =============================================================================
diff --git a/tars-backlog/tars-tkc-brain-graph/service/app/main_brain_graph_route.py b/tars-backlog/tars-tkc-brain-graph/service/app/main_brain_graph_route.py
new file mode 100644
index 0000000..83ea9d2
--- /dev/null
+++ b/tars-backlog/tars-tkc-brain-graph/service/app/main_brain_graph_route.py
@@ -0,0 +1,56 @@
+"""
+main_brain_graph_route.py — The GET /brain/graph route addition for main.py.
+
+INTEGRATION NOTE:
+When tars-tkc DEV workspace is accessible, Bob reads the actual main.py
+and adds this route in the appropriate location (alongside other /brain/* routes).
+
+The existing /brain/query route is already confirmed live. This adds /brain/graph
+as a read-only companion.
+
+=============================================================================
+PASTE THIS BLOCK into main.py, after the existing /brain/query route:
+=============================================================================
+"""
+
+# ---------------------------------------------------------------------------
+# Import to add at the top of main.py (alongside existing imports):
+# ---------------------------------------------------------------------------
+# from app.graph_models import GraphResponse
+# ---------------------------------------------------------------------------
+
+# ---------------------------------------------------------------------------
+# Route to add to the FastAPI app in main.py:
+# ---------------------------------------------------------------------------
+
+"""
+@app.get(
+ "/brain/graph",
+ response_model=GraphResponse,
+ summary="Read-only knowledge graph topology — nodes and edges from Neo4j",
+ tags=["brain"],
+)
+async def brain_graph() -> GraphResponse:
+ \"\"\"Return the full knowledge graph as nodes and directed edges.
+
+ Data source: Neo4j (topology) + node properties (layer/domain/status
+ from Neo4j node properties, written there during knowledge object creation).
+
+ This endpoint is read-only. No writes to any backend.
+
+ Node IDs:
+ - object_id (UUID) where available — canonical cross-store identifier
+ - name: fallback for infrastructure/component nodes without object_id
+ - hash: deterministic fallback of last resort (no Neo4j internal IDs)
+
+ Sensitive properties (passwords, tokens, keys) are stripped before return.
+ \"\"\"
+ loop = asyncio.get_running_loop()
+ return await loop.run_in_executor(None, graph_store.get_brain_graph)
+"""
+
+# ---------------------------------------------------------------------------
+# NOTE: `graph_store` is the existing GraphStore instance already used by
+# other /brain/* routes. No new instance, no new credentials.
+# `asyncio` is already imported in main.py.
+# ---------------------------------------------------------------------------
diff --git a/tars-backlog/tars-tkc-brain-graph/tests/test_brain_graph.py b/tars-backlog/tars-tkc-brain-graph/tests/test_brain_graph.py
new file mode 100644
index 0000000..0579e63
--- /dev/null
+++ b/tars-backlog/tars-tkc-brain-graph/tests/test_brain_graph.py
@@ -0,0 +1,292 @@
+"""
+tests/test_brain_graph.py — Focused tests for GET /brain/graph.
+
+Target: tests/test_brain_graph.py in tars-tkc DEV workspace.
+
+Test strategy:
+- Unit tests: mock GraphStore.get_brain_graph() — no live Neo4j needed
+- Integration marker: @pytest.mark.integration — requires LIVE Neo4j
+- Read-only verification: confirm no write Cypher in the implementation
+- Secret stripping: confirm sensitive properties never appear in response
+- Deterministic ID: confirm Neo4j internal IDs are never in the response
+
+Follows the existing test pattern in the tars-tkc test suite.
+Verify before applying:
+- asyncio_mode setting (auto or explicit markers) from pytest.ini
+- httpx / AsyncClient import style from existing tests
+- exact mock patch target ("app.main.graph_store" or adjusted)
+"""
+
+from __future__ import annotations
+
+from unittest.mock import patch
+
+import pytest
+from httpx import AsyncClient, ASGITransport
+
+# Adjust import path if the actual tars-tkc structure differs.
+from app.main import app
+from app.graph_models import GraphEdge, GraphNode, GraphResponse
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _make_graph_response(
+ nodes: list[dict] | None = None,
+ edges: list[dict] | None = None,
+) -> GraphResponse:
+ n_list = [GraphNode(**n) for n in (nodes or [])]
+ e_list = [GraphEdge(**e) for e in (edges or [])]
+ return GraphResponse.from_parts(nodes=n_list, edges=e_list)
+
+
+SAMPLE_NODES = [
+ {
+ "id": "abc-uuid-1234",
+ "name": "TKC Phase-1 Session",
+ "labels": ["KnowledgeObject"],
+ "object_id": "abc-uuid-1234",
+ "object_type": "conversation",
+ "layer": "raw",
+ "domain": "work",
+ "status": "active",
+ "version": None,
+ "properties": {},
+ },
+ {
+ "id": "name:TARS",
+ "name": "TARS",
+ "labels": ["TARS", "KnowledgeCore"],
+ "object_id": None,
+ "object_type": None,
+ "layer": None,
+ "domain": None,
+ "status": None,
+ "version": "0.2.2",
+ "properties": {"component": "core"},
+ },
+]
+
+SAMPLE_EDGES = [
+ {
+ "source": "name:TARS",
+ "target": "abc-uuid-1234",
+ "type": "HAS_KNOWLEDGE",
+ "properties": {},
+ }
+]
+
+
+# ---------------------------------------------------------------------------
+# Unit tests — mocked GraphStore (no live Neo4j required)
+# ---------------------------------------------------------------------------
+
+class TestBrainGraphEndpoint:
+ """Unit tests for GET /brain/graph."""
+
+ async def test_returns_200_with_graph(self) -> None:
+ """Endpoint returns HTTP 200 and valid GraphResponse structure."""
+ mock_response = _make_graph_response(SAMPLE_NODES, SAMPLE_EDGES)
+
+ with patch("app.main.graph_store") as mock_store:
+ mock_store.get_brain_graph.return_value = mock_response
+
+ async with AsyncClient(
+ transport=ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ resp = await client.get("/brain/graph")
+
+ assert resp.status_code == 200
+ body = resp.json()
+ assert "nodes" in body
+ assert "edges" in body
+ assert body["node_count"] == 2
+ assert body["edge_count"] == 1
+
+ async def test_node_ids_are_canonical_not_neo4j_internal(self) -> None:
+ """Node IDs must not be raw Neo4j internal element IDs."""
+ mock_response = _make_graph_response(SAMPLE_NODES, SAMPLE_EDGES)
+
+ with patch("app.main.graph_store") as mock_store:
+ mock_store.get_brain_graph.return_value = mock_response
+
+ async with AsyncClient(
+ transport=ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ resp = await client.get("/brain/graph")
+
+ body = resp.json()
+ for node in body["nodes"]:
+ nid = node["id"]
+ assert not nid.isdigit(), (
+ f"Node ID must not be a bare integer (Neo4j internal): {nid!r}"
+ )
+ is_uuid = len(nid) == 36 and nid.count("-") == 4
+ is_named = nid.startswith("name:")
+ is_hashed = nid.startswith("hash:")
+ assert is_uuid or is_named or is_hashed, (
+ f"Node ID does not match any expected pattern: {nid!r}"
+ )
+
+ async def test_no_sensitive_properties_in_response(self) -> None:
+ """Sensitive property values must never appear in the API response."""
+ node_with_secrets = GraphNode(
+ id="test-id",
+ name="test",
+ labels=["Test"],
+ object_id="test-id",
+ properties={"password": "secret123", "token": "bearer-xyz"},
+ )
+ mock_response = GraphResponse.from_parts(nodes=[node_with_secrets], edges=[])
+
+ with patch("app.main.graph_store") as mock_store:
+ mock_store.get_brain_graph.return_value = mock_response
+
+ async with AsyncClient(
+ transport=ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ resp = await client.get("/brain/graph")
+
+ response_text = resp.text
+ assert "secret123" not in response_text
+ assert "bearer-xyz" not in response_text
+
+ async def test_empty_graph_returns_valid_response(self) -> None:
+ """Empty graph returns a valid 200 with empty lists."""
+ with patch("app.main.graph_store") as mock_store:
+ mock_store.get_brain_graph.return_value = GraphResponse.from_parts([], [])
+
+ async with AsyncClient(
+ transport=ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ resp = await client.get("/brain/graph")
+
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["nodes"] == []
+ assert body["edges"] == []
+ assert body["node_count"] == 0
+ assert body["edge_count"] == 0
+
+ async def test_post_is_not_allowed(self) -> None:
+ """POST /brain/graph must not be accepted (read-only endpoint)."""
+ async with AsyncClient(
+ transport=ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ resp = await client.post("/brain/graph", json={})
+
+ assert resp.status_code in (405, 404)
+
+ async def test_get_requires_no_request_body(self) -> None:
+ """GET endpoint must not require a request body."""
+ with patch("app.main.graph_store") as mock_store:
+ mock_store.get_brain_graph.return_value = GraphResponse.from_parts([], [])
+
+ async with AsyncClient(
+ transport=ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ resp = await client.get("/brain/graph")
+
+ assert resp.status_code == 200
+
+
+# ---------------------------------------------------------------------------
+# GraphNode / GraphEdge / GraphResponse model unit tests
+# ---------------------------------------------------------------------------
+
+class TestGraphModels:
+
+ def test_graph_node_minimal(self) -> None:
+ node = GraphNode(id="test-123")
+ assert node.id == "test-123"
+ assert node.labels == []
+ assert node.properties == {}
+ assert node.object_id is None
+
+ def test_graph_response_from_parts_counts(self) -> None:
+ nodes = [GraphNode(id=f"n{i}") for i in range(5)]
+ edges = [GraphEdge(source="n0", target="n1", type="RELATES") for _ in range(3)]
+ resp = GraphResponse.from_parts(nodes=nodes, edges=edges)
+ assert resp.node_count == 5
+ assert resp.edge_count == 3
+
+ def test_graph_edge_fields(self) -> None:
+ edge = GraphEdge(source="a", target="b", type="HAS_COMPONENT")
+ assert edge.source == "a"
+ assert edge.target == "b"
+ assert edge.type == "HAS_COMPONENT"
+ assert edge.properties == {}
+
+
+# ---------------------------------------------------------------------------
+# _node_id unit tests (module-level helper in graph_store.py)
+# ---------------------------------------------------------------------------
+
+class TestNodeIdDetermination:
+ """Tests for _node_id(). Import path must match actual graph_store structure."""
+
+ def test_object_id_takes_priority(self) -> None:
+ from app.graph_store import _node_id
+ assert _node_id({"object_id": "abc-123", "name": "X"}) == "abc-123"
+
+ def test_name_fallback(self) -> None:
+ from app.graph_store import _node_id
+ assert _node_id({"name": "TARS"}) == "name:TARS"
+
+ def test_hash_fallback_starts_with_hash_prefix(self) -> None:
+ from app.graph_store import _node_id
+ result = _node_id({"component": "relay"})
+ assert result.startswith("hash:")
+
+ def test_hash_is_deterministic(self) -> None:
+ from app.graph_store import _node_id
+ props = {"component": "relay", "version": "1.0"}
+ assert _node_id(props) == _node_id(props)
+
+
+# ---------------------------------------------------------------------------
+# Integration tests — require live Neo4j; skipped in default run
+# ---------------------------------------------------------------------------
+
+@pytest.mark.integration
+class TestBrainGraphIntegration:
+ """Run with: pytest tests/test_brain_graph.py -m integration -v"""
+
+ async def test_live_graph_returns_at_least_one_node(self) -> None:
+ async with AsyncClient(
+ transport=ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ resp = await client.get("/brain/graph")
+
+ assert resp.status_code == 200
+ assert resp.json()["node_count"] >= 1
+
+ async def test_live_response_contains_no_credentials(self) -> None:
+ async with AsyncClient(
+ transport=ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ resp = await client.get("/brain/graph")
+
+ body_text = resp.text.lower()
+ for pattern in ("neo4j://", "bolt://", "neo4j_password", "neo4j_auth"):
+ assert pattern not in body_text, (
+ f"Potential credential pattern in response: {pattern!r}"
+ )
+
+ async def test_live_edges_include_known_relationship_type(self) -> None:
+ known_types = {
+ "HAS_COMPONENT", "HAS_DECISION", "HAS_IDENTITY",
+ "HAS_KNOWLEDGE", "HAS_MILESTONE", "USES",
+ "SUPERSEDES", "DERIVED_FROM",
+ }
+ async with AsyncClient(
+ transport=ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ resp = await client.get("/brain/graph")
+
+ edge_types = {e["type"] for e in resp.json()["edges"]}
+ assert edge_types & known_types, (
+ f"No known relationship type in live graph. Found: {edge_types}"
+ )