docs: centralize Heimdall agent guidance (#418) (#420)
Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s

Co-authored-by: Arnaud Dartois <admin@tordais.cc>
This commit was merged in pull request #420.
This commit is contained in:
arnaud.dartois authored and Arnaud Dartois committed 2026-11-19 21:07:51 +01:00
1 parent 383205b9fc
commit 5009c96120
88 files changed
+232 -2065

No files matched your search

@@ -1,28 +0,0 @@
---
name: secure-env-secrets
description: Store or retrieve a user-provided secret as a local environment variable outside repositories, without exposing its value in commands or output. Does not configure CI or remote services.
---
# Secure local environment secrets
Use this skill only for secrets the user supplied or explicitly authorized you to retrieve. Keep values outside repositories and never repeat them in commentary, tool output, logs, diffs, or a final response.
## Choose scope and storage
- Prefer the operating system credential store or an existing secret manager, and expose a value only to the process that needs it.
- A secret in an environment variable is available to same-user processes and is not a secure store. Do not add secrets to global shell startup files by default.
- If the user needs persistence and no credential store is available, use a user-owned directory outside every repository, with directory permissions `0700` and file permissions `0600`. Explain that permissions restrict other accounts but do not encrypt the file. Avoid synced/shared locations unless requested.
- Keep a persistent file inert data (for example, base64-encoded values keyed by validated variable names); do not source a file containing arbitrary shell code. Load a requested value only in the shell/process that needs it, without printing it.
## Read or write safely
1. Establish the variable name, intended scope (one command, one shell, or persistent local use), and destination. Ask only for details that change the safe implementation.
2. Before writing, check for an existing value without displaying it. Preserve it unless the user explicitly requests replacement; do not silently delete credentials.
3. Accept the secret through a masked prompt or credential-store protected input. Never place it in a command string, here-document, argument, URL, exported helper variable, or ordinary prompt. If the interface would expose input through tool history/output, ask the user to enter it locally and continue with metadata-only checks.
4. Resolve and verify the destination is outside all involved repositories. Create owner-only directories and set owner-only file permissions before writing.
5. Disable shell tracing and avoid commands that dump environment or variable values. Expose the variable only for the requested operation.
6. Verify presence and permissions without printing or deriving information from the value. Report only the variable name, storage scope/path, and set/unset state.
Never use `env`, `printenv`, `set`, `echo "$SECRET"`, shell tracing, or a diff to inspect secret values. Do not place secrets in project `.env` files, Compose definitions, source code, CI workflows, or test fixtures. This skill does not configure remote CI, cloud, registry, or account secrets.
If a value appears in output or is committed, stop using it and tell the user it should be rotated. Do not rotate credentials in an external service unless separately authorized.
@@ -1,4 +0,0 @@
interface:
display_name: "Secure Environment Secrets"
short_description: "Keep user secrets outside repositories"
default_prompt: "Safely read or store the user-provided secret as a local environment variable outside the repository."
+5 -5
View File
@@ -2,13 +2,14 @@
name: "🐛 Bug"
about: "Comportement incorrect, régression ou risque fonctionnel détecté"
title: "BUG: "
labels: ["bug"]
labels: ["type:bug"]
body:
- type: markdown
attributes:
value: |
## Bug — à remplir avant de commencer
> Si le bug est un écart par rapport à la spec, citer `docs/MASTER_SPECIFICATION.md`.
> Avant de commencer, ajouter les labels `priority:P0`…`priority:P3` et `area:*` adaptés.
- type: textarea
id: contexte
@@ -22,7 +23,7 @@ body:
id: observe
attributes:
label: "🐞 Comportement observé"
description: "Ce qui se passe réellement (avec logs/erreurs si dispo)"
description: "Ce qui se passe réellement (avec logs/erreurs expurgés de toute donnée sensible)"
validations:
required: true
@@ -38,7 +39,7 @@ body:
id: repro
attributes:
label: "🔁 Reproduction"
description: "Étapes pour reproduire + environnement (dev/prod, docker, env vars)"
description: "Étapes pour reproduire + environnement (dev/prod, Docker, noms de variables sans leurs valeurs)"
placeholder: "1. …\n2. …\n3. …"
- type: input
@@ -69,5 +70,4 @@ body:
options:
- label: "Bug reproduit avant fix (test qui échoue)"
- label: "Fix implémenté + tests verts (`make test`)"
- label: "Statut du ticket mis à jour (via skill forgejo-issues)"
- label: "Carte kanban Hermes mise à jour (lien vers l'issue)"
- label: "Issue et preuves mis à jour dans Gitea selon le workflow commun"
+3 -2
View File
@@ -2,12 +2,13 @@
name: "🔧 Maintenance / Chore"
about: "Tâche de maintenance, mise à jour de dépendance, CI, outillage"
title: "CHORE: "
labels: ["chore"]
labels: ["type:maintenance"]
body:
- type: markdown
attributes:
value: |
## Maintenance / Chore
Avant de commencer, ajouter les labels `priority:P0`…`priority:P3` et `area:*` adaptés.
- type: textarea
id: contexte
@@ -44,4 +45,4 @@ body:
label: "✅ Definition of Done"
options:
- label: "Tâche réalisée + vérifiée"
- label: "Statut du ticket mis à jour (via skill forgejo-issues)"
- label: "Issue et preuves mis à jour dans Gitea selon le workflow commun"
+4 -4
View File
@@ -2,13 +2,14 @@
name: "✨ Feature"
about: "Nouvelle fonctionnalité ou implémentation manquante par rapport à la spécification"
title: "FEAT: "
labels: ["feature"]
labels: ["type:feature"]
body:
- type: markdown
attributes:
value: |
## Feature — à remplir avant de commencer
> Source de vérité : `docs/MASTER_SPECIFICATION.md` (v2.0). Citer les numéros de partie/phase/étape.
> Décrire le résultat attendu à partir de la documentation produit actuelle pertinente; les documents marqués historiques ne décrivent pas nécessairement le comportement livré.
> Avant de commencer, ajouter les labels `priority:P0`…`priority:P3` et `area:*` adaptés.
- type: textarea
id: contexte
@@ -75,5 +76,4 @@ body:
- label: "Code implémenté + tests verts (`make test`)"
- label: "Migration EF ajoutée si le schéma change"
- label: "Documentation/readme mis à jour si pertinent"
- label: "Statut du ticket mis à jour (via skill forgejo-issues)"
- label: "Carte kanban Hermes mise à jour (lien vers l'issue)"
- label: "Issue et preuves mis à jour dans Gitea selon le workflow commun"
+3 -3
View File
@@ -2,12 +2,13 @@
name: "🧹 Dette technique"
about: "Dette technique, obsolescence, drift documentation, amélioration de code"
title: "TECH: "
labels: ["tech-debt"]
labels: ["type:maintenance"]
body:
- type: markdown
attributes:
value: |
## Dette technique — à remplir avant de commencer
Ajouter les labels `priority:P0`…`priority:P3` et `area:*` adaptés.
- type: textarea
id: contexte
@@ -53,5 +54,4 @@ body:
label: "✅ Definition of Done"
options:
- label: "Correctif appliqué + vérifié"
- label: "Statut du ticket mis à jour (via skill forgejo-issues)"
- label: "Carte kanban Hermes mise à jour (lien vers l'issue)"
- label: "Issue et preuves mis à jour dans Gitea selon le workflow commun"
+20 -14
View File
@@ -1,25 +1,31 @@
## Problème et résultat
## Résultat et périmètre
<!-- Décrire le déclencheur, le comportement corrigé et le périmètre. -->
<!-- Décrire le besoin, le résultat et les critères de l'issue couverts par cette PR. -->
Refs #
## Vérification
<!-- Issue Gitea liée, liens des runs Gitea, suites exécutées et résultats observés. -->
<!-- Commandes, preuves observées, limites et SHA du commit vérifié. Pour un diff Markdown-only, noter les contrôles de diff/liens; ne pas lancer de build ou de stack applicative sans raison. -->
- [ ] Build and tests : compilation, PostgreSQL, Chromium, archives et images
- [ ] Contrôles NuGet et images sans HIGH/CRITICAL
- [ ] Limites et tests non exécutés explicitement documentés
- [ ] Aucun secret dans les logs/artefacts
- [ ] Issue Gitea liée et critères satisfaits/restants précisés
- [ ] Contrôles pertinents exécutés; commandes et résultats indiqués
- [ ] Recette Compose indépendante indiquée lorsqu'elle est requise, avec preuves de nettoyage
- [ ] Limites et validations externes non réalisées explicitement documentées
- [ ] Aucun secret dans le diff, les logs ou les artefacts
## Livraison
## Évaluation de release
<!-- Voir docs/gitea-builds.md. Pas de merge/déploiement implicite. -->
<!-- Appliquer la skill globale release-assessment et la politique de version Heimdall. -->
- [ ] Traçabilité commit → résultats → SHA256 des archives → digests images
- [ ] Revue des changements de contrats/migrations/configuration
- [ ] Si la PR change un graphe d’image : seules les images affectées ont été construites/scannées; publication Docker Hub vérifiée après merge
- [ ] Si elle change la livraison : le workflow de tag versionné et la release Gitea versionnée sont documentés et acceptés
Release assessment: <none | patch | minor | major> — rationale
SonarQube, matériel et autres contrôles externes ne sont considérés validés que si une preuve réelle est jointe. Une protection de branche doit exiger le contexte Gitea constaté sur le run avant de compter sur le blocage d’un merge.
## Livraison Heimdall
<!-- Voir docs/gitea-builds.md si la PR touche CI, publication ou assets de release. -->
- [ ] Compatibilité contrats/migrations/configuration revue si concernée
- [ ] Si le graphe d'image change : images affectées construites/scannées; publication Docker Hub observée après merge
- [ ] Si les assets changent : noms, SHA-256/signature et format de release documentés; aucun claim externe sans run réel
SonarQube, runner, matériel, registre, site et stockage distant ne sont considérés validés que si une preuve réelle est jointe. Aucun merge ou déploiement n'est implicite.
-18
View File
@@ -1,18 +0,0 @@
# Heimdall contributor rules
- For every feature, fix, operational change, or meaningful documentation change, create or update a focused skill under `skills/` in the same PR. The skill must capture the project-specific implementation and acceptance workflow, not restate generic guidance.
- Every behavior or deployment change must pass an acceptance recipe in a disposable Docker Compose project built from the changed source. Use isolated generated credentials, ports, volumes, project names, and unique tags for locally built acceptance images; never reuse production configuration/data. Tear down only that project and confirm its containers/volumes/networks are gone, then remove and verify absence of only the exact image tags built by that recipe. Keep shared upstream/base images. Never use broad image pruning. Do not skip this recipe silently when Docker is unavailable.
- Use Gitea project issues as the sole backlog and work-status source. Before changing code, find or create the focused issue, keep its acceptance evidence current, and link the issue from the PR (`Closes #N` only when all criteria are complete; otherwise `Refs #N`). Follow [skills/gitea-ticket-workflow/SKILL.md](skills/gitea-ticket-workflow/SKILL.md). Do not create or maintain a `todo.md` backlog.
- Keep `Domain` independent of infrastructure. Put use cases and interfaces in `Application`, adapters and EF Core persistence in `Infrastructure`, HTTP/UI composition in `Web`, and camera/runtime behavior in `Agent`.
- Target the SDK pinned by `global.json` and .NET 10 or newer. Use nullable reference types, cancellation tokens for I/O, and explicit options validation. Do not weaken locked restore or suppress a new warning without a reason.
- Use EF Core for production database reads and writes. Do not use direct ADO.NET or provider commands in production code; provider-specific EF SQL is allowed only for capabilities LINQ cannot express, with a nearby rationale and a test. The CI persistence policy enforces this boundary. Preserve PostgreSQL behavior, add migrations for schema changes, and verify translation, concurrency, and deletion semantics with relational tests. Never reuse a `DbContext` across concurrent operations.
- Keep tenant/site and camera authorization checks at API and application boundaries. Do not log credentials, RTSP URLs, embeddings, or raw tokens.
- CI jobs run only on `[ubuntu-latest, build-agent]`. Keep `runner-aaja` outside that label. Never use release credentials in pull request jobs.
- A PR touching deployment or publication must document required secrets and prove the relevant script locally. Do not claim a runner, registry, camera, or object store was validated without a real run.
See [skills/heimdall-dotnet/SKILL.md](skills/heimdall-dotnet/SKILL.md) for project-specific implementation guidance.
For Penpot design work, follow [skills/penpot-design-sync/SKILL.md](skills/penpot-design-sync/SKILL.md): always open Penpot and establish the authenticated session through the Orca browser, and keep the connected design synchronized with relevant shipped UI changes.
When work can be split safely, follow [skills/parallel-development/SKILL.md](skills/parallel-development/SKILL.md) to dispatch independent investigations and implementation through Orca, then integrate and validate the combined change once.
For database access, also follow [skills/ef-core-persistence/SKILL.md](skills/ef-core-persistence/SKILL.md); the CI persistence policy checks production source for direct database commands and requires documented provider-specific exceptions.
For behavior changes, use [skills/compose-disposable-recipe/SKILL.md](skills/compose-disposable-recipe/SKILL.md); account bootstrap changes also use [skills/first-admin-bootstrap/SKILL.md](skills/first-admin-bootstrap/SKILL.md).
For Central installer, Compose, or server image update changes, also use [skills/central-auto-updates/SKILL.md](skills/central-auto-updates/SKILL.md).
+2 -2
View File
@@ -3,7 +3,7 @@
> **Version :** 2.0 | **Date :** 2026-07-16
> **Stack de la baseline :** .NET 10+ / Blazor MudBlazor / PostgreSQL / ONNX Runtime (agents)
> **Statut :** baseline de conception historique datée du 2026-07-16; ce document n'est pas la source de vérité sur l'implémentation livrée.
> **État livré :** voir [spécifications actuelles](specs.md), [hubs SignalR mappés](signalr-usage.md), [déploiement Compose et live view](docker-compose.md), et [skill live-view](../skills/webrtc-live/SKILL.md).
> **État livré :** voir [spécifications actuelles](specs.md), [hubs SignalR mappés](signalr-usage.md), [déploiement Compose et live view](docker-compose.md).
>
> **Documents sources fusionnés :** `specs.md`, `implementation.md`, `notifications.md`, `signalr-usage.md`,
> `auth-roles.md`, `pwa.md`, `hangfire-usage.md`, `ui-pages.md`
@@ -682,7 +682,7 @@ builder.Services.AddSignalR()
> Les sections ci-dessous conservent l'ancienne proposition P2P/SIPSorcery et
> ses objectifs de latence, pas le comportement livré. Le chemin actuel est
> Agent RTSP(S) → MediaMTX → navigateur WHEP/WebRTC; voir le
> [guide Compose](docker-compose.md) et le [skill live-view](../skills/webrtc-live/SKILL.md).
> [guide Compose](docker-compose.md).
### 6.1 Stack
+13
View File
@@ -72,6 +72,13 @@ Heimdall/
| `hangfire-usage.md` | Description des jobs Hangfire présents au Central et à l’Agent |
| `metrics.md` | Métriques exportées par Central et les Agents, avec leur portée et limites |
| `signalr-usage.md` | Hubs SignalR et contrats documentés; voir l’audit pour les capacités effectivement livrées |
| `gpu-runtime.md` | Capacités GPU Agent, configuration et limites de validation matérielle |
| `development-workflow.md` | Règles opérationnelles Heimdall, CI et recettes d'acceptance |
Les exigences produit supplémentaires pour l'installation et les mises à jour
Agent sont décrites dans `agent-release-signing.md` et `docker-compose.md`.
Le parcours et les états visibles du panneau d'installation sont décrits dans
`ui-pages.md`. Les procédures exécutables restent dans `scripts/acceptance/`.
L'audit est la source de vérité pour les constats actuels, leur statut et les travaux
restants. Les documents de spécification décrivent parfois la cible initiale; leurs
@@ -79,6 +86,12 @@ mentions de fonctionnalités ne prouvent pas leur livraison.
**Total : ~5 600 lignes de documentation**
Les règles et critères d’acceptation propres au produit sont maintenus dans ces
guides et les autres documents de ce répertoire. Les pratiques génériques sont
fournies par le catalogue partagé installé au niveau utilisateur; ce dépôt ne
contient aucune skill locale. Les recettes exécutables sont rangées sous
`scripts/acceptance/` et les contrôles automatisés sous `scripts/ci/`.
## Audit du 20 octobre 2026
- [Issues et preuves courantes](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues)
+12
View File
@@ -1,5 +1,17 @@
# Signatures des mises à jour Agent
## Installation et mises à jour Agent
Linux and Windows installers verify the signed manifest and archive checksums
before activation. An update preserves the previous release until the candidate
reports the expected version and remains healthy for the stability interval; a
startup failure restores the previous release. Linux metadata lookup retries
transport errors, HTTP 408/425/429, and 5xx at most three times with bounded
delays; other HTTP errors fail immediately. A published release must include
the signed manifest, asset checksums, and required image digest; building a
`main` image alone does not produce release metadata. Windows service paths
and update/rollback still require validation on a real Windows host.
Les mises à jour natives et Docker sont acceptées uniquement si le manifeste de release est signé par la clé de publication. La release publie aussi la clé publique ECDSA P-256. Pour le premier déploiement, l’installateur la récupère via Central sur HTTPS; l’Agent la conserve ensuite localement (Linux) ou dans la configuration générée par l’IHM (Docker/Windows). Central ne peut donc pas remplacer silencieusement la clé déjà épinglée par un Agent existant.
## Préparer les clés
+8 -3
View File
@@ -240,9 +240,14 @@ droits de ressource à partir des accès courants. Pour les caméras, ce modèle
est centralisé dans `ICameraAccessService`/`CameraAccessService`; pour une
ressource précise, `ResourceAccess` effectue le contrôle demandé par le
contrôleur. Cela inclut les accès directs, les accès de site, les anciennes
affectations et les groupes caméra. Voir
[`skills/camera-access-groups/SKILL.md`](../skills/camera-access-groups/SKILL.md)
pour maintenir cette union sans la réimplémenter dans un contrôleur.
affectations et les groupes caméra. Maintenir cette union dans le service
partagé et ses tests, sans la réimplémenter dans un contrôleur.
The shared camera-access service combines direct camera grants, site grants,
legacy assignments, and camera groups. API endpoints and application queries
both enforce access at their boundaries; UI visibility is not an authorization
check. When changing a camera-scoped flow, cover direct and inherited grants,
denials, and current access revocation in the service/controller tests.
---
+65
View File
@@ -0,0 +1,65 @@
# Règles de développement et acceptance Heimdall
Ce document conserve les exigences opérationnelles propres au dépôt. Les
pratiques générales des agents relèvent du catalogue partagé. Utiliser les
issues Gitea comme backlog du projet et suivre le cycle commun de livraison.
## Architecture et implémentation
- `Domain` reste indépendant de l'infrastructure. Placer les cas d'usage et
interfaces dans `Application`, les adaptateurs et la persistance EF Core
dans `Infrastructure`, la composition HTTP/UI dans `Web`, et le comportement
caméra/runtime dans `Agent`.
- Cibler le SDK épinglé dans `global.json` et .NET 10 ou plus récent.
- Utiliser EF Core pour les lectures et écritures de production. Les commandes
ADO.NET ou spécifiques au fournisseur sont interdites en production. Une
requête SQL EF propre au fournisseur n'est admise que si LINQ ne peut exprimer
la capacité requise, avec justification adjacente et test relationnel. Le
contrôle CI de persistance vérifie cette limite. Préserver PostgreSQL,
ajouter les migrations de schéma et tester traduction, concurrence et
suppression sur une base relationnelle. Ne jamais partager un `DbContext`
entre opérations concurrentes.
- Vérifier l'autorisation tenant/site et caméra aux frontières API et
application. Ne jamais journaliser identifiants, URL RTSP, embeddings ou
jetons bruts.
## CI, déploiement et validations
- Les jobs Gitea s'exécutent sur `[ubuntu-latest, build-agent]`. Ne pas placer
`runner-aaja` sur ce label. Ne jamais exposer d'identifiants de publication
dans un job de pull request.
- Pour les recettes d'intégration, appliquer `disposable-test-environment` et
choisir le script pertinent dans `scripts/acceptance/`.
- Les validations de runner, registre, site, caméra ou stockage distant exigent
une preuve d'exécution sur la cible concernée; les recettes locales ne
constituent pas cette preuve.
## Recettes conservées
Les scripts Compose d'acceptance sont exécutables dans `scripts/acceptance/` :
- `agent-heartbeat-timeout.sh` — heartbeat Agent et expiration;
- `agent-startup-composition.sh` — composition et démarrage Agent;
- `camera-toggle-acceptance.sh` — activation et désactivation caméra;
- `database-migration-startup.sh` — migration et reprise au démarrage;
- `heimdall-identity.sh` — création/connexion et flux de cookie 2FA;
- `optional-server-services.sh` — services optionnels et sauvegarde/restauration;
- `renovate-automation.sh` — acceptance de l'automatisation Renovate;
- `webrtc-live-source-change.sh` — changement de source du live view.
Les contrôles de build et de politique restent dans `scripts/ci/`. Voir
[`gitea-builds.md`](gitea-builds.md) pour les workflows et contraintes de
runners, et [`docker-compose.md`](docker-compose.md) pour les recettes jetables.
Pour les changements d'installation Agent, préserver la vérification de
signature et de sommes de contrôle, ainsi que le rollback vers la release
précédente si le démarrage échoue; voir
[`agent-release-signing.md`](agent-release-signing.md). Les tests locaux de
rollback ne remplacent pas la validation d'un service Linux ou Windows réel.
## Collaboration et conception
Pour les changements d'interface issus de Penpot, ouvrir le document avec la
session authentifiée du navigateur Orca et synchroniser le design connecté avec
les changements UI livrés. Si le travail est découpé en lots indépendants,
coordonner les lots via Orca et intégrer puis valider le résultat combiné.
+45 -5
View File
@@ -112,9 +112,18 @@ camera detail page. Processing runs on Central; the temporary crop is removed
after processing, while the candidate text and history event are persisted.
The feature limits uploads to 512 KiB and images to four megapixels. It does
not detect plates in video or perform face recognition, and the OCR result is
not a verified identity. Review retention/privacy implications in
[`skills/vision-identity/SKILL.md`](../skills/vision-identity/SKILL.md) before
enabling it.
not a verified identity. Review the retention and privacy implications
documented for the product before enabling it.
OCR runs only after an authorized operator selects a JPEG/PNG crop. Central
deletes the temporary image after processing and stores a normalized candidate,
confidence, and history event; it does not link a person or vehicle
automatically. An operator must confirm a proposed vehicle association through
the authorized workflow. Candidate observations and detection events are
retained for 30 days; snapshots are removed from their recorded storage
destination before event deletion. Rows with incomplete storage provenance are
retained rather than deleted from a guessed location. Face matching remains
disabled until the exact model weights and training-data rights are reviewed.
The development Compose builds Central from the local source and starts only
Central plus PostgreSQL:
@@ -129,8 +138,20 @@ values, and choose unused loopback ports. Use a unique Compose project name and
`HEIMDALL_NETWORK_NAME`; after checking `/healthz`, stop only that project with
`docker compose -p <project> ... down --volumes --remove-orphans`. Verify its
containers, volumes, and network are gone. Never use `.env.example` unchanged
for an exposed or production deployment. The disposable recipe is maintained
in [`skills/deployment-guide-acceptance/SKILL.md`](../skills/deployment-guide-acceptance/SKILL.md).
for an exposed or production deployment.
### Disposable Compose acceptance
For a product behavior or deployment change that needs integration acceptance,
use a unique Compose project built from the changed source, generated synthetic
credentials and data, loopback-only ports, and project-scoped volumes and
network. Install cleanup before the first build or start. After exercising the
changed behavior through its HTTP, UI, or Agent boundary, remove only that
project and verify its containers, volumes, and network are absent. Remove and
verify absence of each exact locally built image tag; retain upstream base
images. Keep the original check result if cleanup fails and report the cleanup
failure. Synthetic acceptance does not establish deployed-host, external
network, or physical-camera behavior.
## Agent
@@ -161,6 +182,25 @@ docker compose up -d` so the non-root Agent process can access hosts whose
socket is owned by the Docker group. The UI's `docker run` command determines
this group ID from the host socket automatically.
The Agent applies a complete camera-configuration snapshot atomically and
acknowledges the exact digest to Central. Transient network failures and HTTP
408/429/5xx acknowledgements are retried at most three times with bounded
delays; permanent 4xx responses stop retries. Keep the previous applied
snapshot active after a rejected acknowledgement. Do not log API keys, camera
URLs, configuration payloads, or response bodies. Camera disable acceptance
must distinguish Central's requested state, the digest acknowledged by the
Agent, and actual FFmpeg process release. Reconnection tests verify full
replacement including removed assignments; real-camera stability and LAN
discovery remain separate hardware/network validation.
The Agent reports log levels using the exact names `Trace`, `Debug`,
`Information`, `Warning`, `Error`, and `Critical`; Central does not accept
`Info` or `Warn` aliases. The Central `HttpClient` timeout is ten seconds. A
heartbeat timeout is transient and the service continues its loop; cancellation
caused by host shutdown still propagates cooperatively. Keep timeout and
continued-service behavior in separate acceptance assertions.
## Optional software
Start Central first to create the shared `heimdall-net` network. Optional
+2 -2
View File
@@ -6,12 +6,12 @@
| Sujet | Source actuelle |
|---|---|
| Installation Central, Compose et services optionnels | [Guide Docker Compose](docker-compose.md), [skill d’acceptation du déploiement](../skills/deployment-guide-acceptance/SKILL.md) |
| Installation Central, Compose et services optionnels | [Guide Docker Compose](docker-compose.md) |
| CI, builds et publication | [CI Gitea et images](gitea-builds.md), [signatures des mises à jour Agent](agent-release-signing.md) |
| Authentification, rôles et permissions | [Guide rôles et permissions](auth-roles.md) |
| Pages, routes et navigation UI | [Inventaire des pages UI](ui-pages.md) |
| Hubs SignalR et Hangfire | [Guide SignalR](signalr-usage.md), [Guide Hangfire](hangfire-usage.md) |
| Vidéo live, caméra et capacités livrées | [État produit courant](specs.md), [guide live view](../skills/webrtc-live/SKILL.md) |
| Vidéo live, caméra et capacités livrées | [État produit courant](specs.md), [guide Docker Compose](docker-compose.md) |
| Notifications | [Guide notifications](notifications.md) |
| Métriques et alertes | [Guide Prometheus](metrics.md) |
| PWA et validation appareils/déploiement | [Audit PWA](pwa.md) |
+9
View File
@@ -21,6 +21,15 @@ Ces constats sont une vérification statique des sources, pas une validation de
serveur SMTP, de serveur ntfy ni d’un déploiement. La configuration de ces
services dépend de l’opérateur.
Le traitement des notifications utilise une outbox durable avec des tentatives
rejouables; une acceptation fournisseur suivie d'une perte de l'accusé de
persistance peut produire un doublon. Une configuration et un transport
simulés peuvent être vérifiés localement, mais ne prouvent pas la livraison vers
un serveur externe ou un appareil utilisateur. Pour ntfy, les réponses succès,
429 et 5xx sont réessayées avec délai borné; les erreurs permanentes restent en
échec et les secrets ne doivent apparaître ni dans les réponses ni dans les
journaux.
Sources principales :
- [`NotificationChannel`](../src/Heimdall.Domain/Enums/NotificationChannel.cs)
+7
View File
@@ -1,5 +1,12 @@
# Audit PWA du serveur Heimdall et plan de réalisation
L’acceptance locale du code source couvre le manifeste, les icônes publiques,
le contenu exact du cache et la navigation hors ligne dans un navigateur.
L’installation sur appareils, les mises à jour multi-onglets, le rollback,
HTTPS de déploiement, la reprise après veille et l’usage hors connexion des
données métier restent des validations distinctes; un test navigateur local ne
prouve pas leur fonctionnement sur appareil ou déploiement réel.
Mis à jour le 24 octobre 2026. Périmètre : `src/Heimdall.Web`, API, authentification, hubs, notifications et déploiement. L’application native a été retirée à la demande du propriétaire ; la cible mobile est désormais l’application web existante. La PR #64 livre le manifeste, une icône SVG, l’enregistrement d’un service worker et une page hors connexion statique. Ce socle ne rend pas les écrans métier utilisables hors ligne : les composants Interactive Server dépendent toujours du serveur.
## Décision recommandée
+5 -1
View File
@@ -95,7 +95,11 @@ Seuls les Administrateurs peuvent établir une connexion Admin et joindre le bro
- Les messages sont des signaux, pas une file durable : un client déconnecté doit relire l’état via l’API.
- Les abonnements sont suivis par connexion et leur accès est réévalué à l’envoi; ne pas remplacer ce contrôle par un groupe global accessible à tout utilisateur.
- Les hôtes et méthodes listés ici sont extraits de `Program.cs`, des classes `*Hub` et des services de broadcast. Les tests unitaires d’isolation ne valident ni un proxy WebSocket, ni une installation réelle.
- Avant d’ajouter un hub ou un événement, mettre à jour les tests d’autorisation et ce guide dans le même changement; suivre `skills/signalr-documentation/SKILL.md`.
- Avant d’ajouter un hub ou un événement, mettre à jour les tests d’autorisation et ce guide dans le même changement.
- Agent log levels sent to Central use the exact names `Trace`, `Debug`,
`Information`, `Warning`, `Error`, and `Critical`; `Info` and `Warn` are not
accepted aliases. Preserve these values in the Agent serialization and
Central parser tests.
## Sources locales
+21
View File
@@ -100,6 +100,13 @@ Sources : [`Site`](../src/Heimdall.Domain/Entities/Site.cs), [`Agent`](../src/He
- Création de Site avec token d'enregistrement Agent
- Agent bootstrap : token → register → heartbeat
- L'Agent récupère une configuration caméra complète, en vérifie le digest et
accuse réception de cette version; après reconnexion il rejoint son groupe et
recharge l'instantané complet, y compris les affectations supprimées.
- L'état demandé par Central, la version accusée par l'Agent et l'arrêt effectif
du processus FFmpeg sont distincts. Les changements activation, désactivation,
réaffectation et redémarrage doivent vérifier le digest appliqué et l'arrêt du
processus séparément; un statut seul ne prouve pas l'arrêt du flux.
- Cycle de vie : Registration → Heartbeat (30s) → Offline (90s)
- API dédiée : POST /api/agents/register
- Voir `docs/auth-roles.md` §11 pour le détail complet
@@ -138,6 +145,20 @@ flux principal) et redémarre le processus après un changement de source pour l
même CameraId. Ce comportement est couvert par les tests Agent et l’acceptance
locale de #355; aucune caméra réelle ni réseau externe n’a été validé.
## Inference et jobs Agent
Les travaux d'analyse utilisent uniquement des types autorisés à la frontière
Web, dans le planificateur Central et dans le parseur Agent. La détection
d'objets est plafonnée à 500 résultats dans l'ordre du modèle; la détection de
personne filtre la classe COCO 0 avant plafonnement. La classification véhicule
retient les classes COCO 2, 3, 5 et 7, dans l'ordre d'origine. Le détecteur de
mouvement CPU compare deux images du flux actif séparées de 500 ms, redimensionne
à 32×18, compare la luminance normalisée à 0,12 par pixel et déclenche à partir
de 2 % de pixels changés. Le résultat porte l'étiquette `motion`, des limites
normalisées de zone et le ratio de pixels changés comme confiance. L'éclairage
et les vibrations peuvent produire de faux positifs; ces seuils doivent être
mesurés sur des caméras représentatives avant de dépendre des alertes.
## Temps réel (SignalR) — `docs/signalr-usage.md`
Résumé des cinq hubs actuellement mappés :
+8
View File
@@ -260,6 +260,14 @@ Dashboard shows agent offline state
Le panneau suit le parcours de l'installateur Pangolin : choix de plateforme en tuiles, choix de méthode en tuiles, configuration optionnelle puis étapes de commandes. Les tuiles sont en trois colonnes sur écran large et s'empilent sur petit écran; les méthodes prennent toute la largeur disponible. La tuile sélectionnée garde un contour et un fond teinté de la couleur primaire.
Seuls Linux, Windows et Docker sont proposés. Les commandes natives exigent
une release signée disponible; les commandes Docker utilisent l'image signée
épinglée par digest et `pull_policy: always`. Les valeurs d'enrôlement ne sont
pas incluses dans les commandes Linux: l'installateur les demande à l'exécution
et les transmet via des fichiers temporaires protégés, supprimés à la sortie.
Les textes visibles proviennent des ressources de localisation. Vérifier aussi
les états sans release signée ou sans image GPU publiée.
```text
Système d'exploitation
[Linux] [Windows] [Docker]
File renamed without changes.
-21
View File
@@ -1,21 +0,0 @@
---
name: agent-heartbeat-timeout
description: Diagnose and validate Central heartbeat timeouts without terminating the Heimdall Agent background service.
---
# Agent heartbeat timeout
`AgentRegistrationService` sends periodic Central heartbeats through the named `Central` `HttpClient`, whose timeout is configured in `src/Heimdall.Agent/Program.cs`. An `HttpClient.Timeout` surfaces as `OperationCanceledException`/`TaskCanceledException`, even though the host's `stoppingToken` is not canceled. `SendHeartbeatAsync` must log this as a transient timeout and return to the loop. Preserve cancellation when `stoppingToken.IsCancellationRequested` so host shutdown remains cooperative.
## Change and test
- Keep the timeout handling local to `SendHeartbeatAsync`; registration cancellation and shutdown semantics have different retry behavior.
- Catch `OperationCanceledException` only under `!stoppingToken.IsCancellationRequested`, log it as a timeout, and allow the next loop iteration to retry. The existing general exception handler continues to cover other transient failures.
- In `tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs`, use an asynchronous HTTP handler that waits on the request cancellation token. Give its `HttpClient` a short timeout, then assert that a second heartbeat arrives. This verifies both the timeout source and continued service operation without waiting 10 seconds.
- Run `dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --filter FullyQualifiedName~Heartbeat_HttpTimeout_DoesNotStopService_AndNextHeartbeatSucceeds`, then the full Agent test project.
## Disposable Compose acceptance
Run `bash skills/agent-heartbeat-timeout/acceptance.sh` from the repository root. The recipe builds the Agent image from `docker/Dockerfile.agent` in this checkout and a small local fake Central image. The fake Central delays the first heartbeat for 12 seconds (longer than the Agent's configured 10-second `Central` client timeout), then accepts later heartbeats. Acceptance requires the Agent health endpoint to respond after the timeout and the fake Central to observe a subsequent heartbeat. The script uses a random Compose project, random site token, Compose-managed isolated volume/network, dynamically assigned loopback Agent port, and unique local image tags. Its `EXIT` trap tears down only that project, verifies its containers/volumes/networks are gone, removes and verifies absence of both exact image tags, and removes temporary files. It retains shared SDK/runtime/base images.
This synthetic recipe proves local retry behavior only. It does not validate a production runner, Central instance, or post-deployment GlitchTip telemetry; record that follow-up on Gitea issue #248.
-14
View File
@@ -1,14 +0,0 @@
---
name: heimdall-agent-install-assets
description: Serve and validate native Heimdall Agent installer assets from Central.
---
# Native Agent installer assets
Read `AGENTS.md`, the `AGENT-INSTALL-ASSETS` Gitea issue, and `skills/compose-disposable-recipe/SKILL.md` before changing Central asset delivery.
`Heimdall.Web.csproj` publishes the Linux/Windows installers and supervisors under `wwwroot/install/`; `Program.ConfigureMiddleware` serves them through ASP.NET Core static files. The default MIME table does not recognize `.py`, so explicitly map `.py` with `FileExtensionContentTypeProvider`; otherwise the supervisor returns 404 even when the file exists in the publish output.
For acceptance, build Central from the changed source in a disposable Compose project. Require `/healthz` healthy and GET `/install/install-agent.sh` plus `/install/agent-supervisor.py`; both must return HTTP 200 and byte-for-byte match `install/` sources. Use generated credentials, isolated ports/project volumes/network, a unique local image tag, and an EXIT cleanup trap installed before build. Verify no project containers, volumes, or networks remain and remove/verify absence of the exact built tag. Keep shared base images.
This proves only source-built Central behavior. Verify the deployed Central after its image has been published and restarted before considering a field incident resolved.
-41
View File
@@ -1,41 +0,0 @@
---
name: agent-runtime-acceptance
description: Validate Heimdall Agent reconnect, camera configuration replacement, acknowledgement, and runtime diagnostics without camera hardware.
---
# Heimdall Agent runtime acceptance
Read `AGENTS.md`, the relevant Agent Gitea issue, and `skills/heimdall-dotnet/SKILL.md` before changing Agent runtime behavior.
## Camera configuration synchronization
- `ConfigReceiverService` fetches the complete camera settings snapshot after initial connection and reconnection; `CameraConfigStore.ReplaceCentral` validates the digest and publishes all assignments atomically.
- The Central acknowledgement is keyed to that exact digest. Retry network failures and HTTP 408/429/5xx at most three times with short bounded delays; stop on permanent 4xx responses. Do not log the API key, camera URLs, configuration payload, or response body.
- Keep the latest applied snapshot active when an acknowledgement is rejected. A later config reload/reconnect fetches and acknowledges the current snapshot again.
- `FetchFullConfigAsync_RetriesTransientAcknowledgementUntilCentralPersistsIt` uses an in-process Kestrel Central simulator: config GET is served once; ACK receives 503 then 204; both posts must carry the same digest; the camera snapshot change event fires once; and Central records one successful ACK. `HEIMDALL_ACK_FIXTURE_PORT` pins the listener for Compose, while the API key fixture can be injected through `HEIMDALL_ACK_FIXTURE_API_KEY`.
- Also retain the SignalR reconnect test that proves rejoin, full replacement (including removals), and applied values.
## Central log upload contract
- Agent log levels must use the exact `AgentLogLevel` names accepted by Central's parser: `Information` and `Warning` (not the common aliases `Info`/`Warn`), alongside `Trace`, `Debug`, `Error`, and `Critical`.
- Keep `ToCentralLevel_MapsMicrosoftNamesToAgentContract` asserting both the emitted name and that Central's enum parser accepts it at the corresponding severity.
- Agent logging is API-key authenticated. A source-built disposable Compose check can register a synthetic Agent, submit one entry at each severity to `/api/agents/{id}/logs`, and read them back through the authorized Central log query. Keep generated credentials and project resources isolated and clean up exact locally built tags per the Compose recipe.
## Local checks
```bash
dotnet restore tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --locked-mode
dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore
```
For `NetworkCameraScanner` TCP probes, bound connects with a linked cancellation token and await the connect task on both success and timeout. Do not race a live `TcpClient.ConnectAsync` against `Task.Delay` and return while the connect task is still running: closing the client can surface a later socket cancellation as an unobserved task exception. Keep a focused test proving the timeout cancels and observes the pending connect, and that caller cancellation still propagates.
For the focused Kestrel ACK acceptance, copy only the test project's source dependencies into a temporary directory outside the repository. Use a uniquely named Compose project with the pinned .NET SDK image, the temporary source mounted at `/workspace`, a project-scoped NuGet/result volume, a project-scoped bridge, a generated fixture API key, and a loopback-only port. Put the two locked restore/test commands in `/workspace/run-ack-test.sh` and set `entrypoint: ["/bin/bash", "/workspace/run-ack-test.sh"]`; avoid a scalar `command` with `bash -lc`, which Compose passes as multiple arguments and can run `dotnet` without its subcommand. The test itself proves Central returns a transient 503 and then persists the exact digest once. This SDK-only recipe builds no local images; keep the shared upstream SDK image. Install an EXIT cleanup trap before starting, tear down only that project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, and remove the temporary source even on failure. The acceptance record must state `local image tags: none`; if future changes add a local image build, record its unique tag and remove/verify that exact tag in the same trap. Serialize Docker acceptance when another source build is using the shared daemon.
This SDK-only recipe does not build a local Heimdall image; keep the shared upstream SDK image. If the recipe is extended to build an app image, assign a project-unique tag and remove/verify that exact tag after teardown per `skills/compose-disposable-recipe/SKILL.md`.
For camera enable/disable timing, distinguish Central's requested state, the exact configuration digest acknowledged by the Agent, and actual FFmpeg process release. A status transition alone is not proof that capture stopped. Poll `/proc/<pid>/comm` (or an equivalent exact process identity that cannot match the harness command); measure stop convergence separately from config ACK convergence. The synthetic-camera acceptance must cover initial OFF, ON, OFF, ON, restart while ON, then OFF and restart while OFF with the persisted Agent identity, asserting the newest digest after each update. Record the observed OFF latency and keep the item open if it exceeds the product's 2-second expectation. Every attempt uses a new project and exact source-built Central/Agent tags, records both before build, and removes/verifies them plus all project resources in its EXIT trap.
## Acceptance boundary
In-memory SignalR/HTTP fixtures and a local Agent container validate reconnect and runtime behavior without a physical camera. Mark real-camera stream stability, resource release on the deployed host, and LAN discovery as open until they pass on representative hardware and network equipment.
-38
View File
@@ -1,38 +0,0 @@
---
name: agent-startup-composition
description: Validate Heimdall Agent dependency-injection composition by starting its source-built container without a Central dependency.
---
# Agent startup composition
`src/Heimdall.Agent/Program.cs` constructs `SnapshotPipelineServiceOptions` in
the service-registration factory before registering the hosted service. Do not
register `SnapshotPipelineService` with the generic `AddHostedService<T>()`
unless every constructor dependency, including that options record, is
registered in DI. A missing dependency can prevent `Host.StartAsync` and leave
the Agent container unable to start.
## Acceptance
Run `bash skills/agent-startup-composition/acceptance.sh` from the repository
root. The recipe builds only the CPU Agent image from the current checkout with
a unique local tag and starts it in a disposable Compose project with generated
site-token data and an internal-only network. Its Central URL points to the
Agent container's own unused loopback port; it cannot reach a deployment.
The recipe proves that:
1. The Agent host starts and remains running with its production service
registrations, including `SnapshotPipelineService`.
2. `/health/live` responds successfully before registration with Central; the
readiness endpoint `/healthz` is intentionally not used because it reports
Unhealthy until Central registration succeeds.
3. Startup logs do not contain the missing
`SnapshotPipelineServiceOptions` dependency or a host-start failure.
4. Cleanup removes the exact Compose project, generated state volume/network,
and this recipe's one exact Agent image tag, then verifies their absence.
This checks DI and host startup only. It does not validate Central registration,
camera discovery, model inference, a published Agent, or a deployed installation.
The EXIT trap preserves the test result, attempts each cleanup independently,
and reports cleanup failures. The Dockerfile's shared .NET base images remain.
-98
View File
@@ -1,98 +0,0 @@
---
name: heimdall-agent-update-acceptance
description: Validate Heimdall native Agent install, signed update, startup health, and rollback behavior.
---
# Native Agent update acceptance
Use this skill when changing `install/install-agent.sh`, `install/install-agent.ps1`, `install/agent-supervisor.py`, or `install/agent-update-supervisor.ps1`.
For Docker Agent install/update changes, also inspect the generated Compose and
`docker run` commands in `SiteInstallPanel.razor`, plus both CPU and NVIDIA
Agent images. The Docker updater shells out to the Docker CLI and therefore
requires the CLI in the image and `/var/run/docker.sock` mounted into the
container. Validate the generated Compose and Docker-run command together;
document that mounting this socket grants broad control of the host. The Docker
Run panel must provide POSIX and PowerShell commands, use an immutable signed
image reference, initialize the state volume, and keep the health endpoint
reachable for update rollback checks. A disposable image acceptance should
build with a project-unique tag and assert `docker --version` inside the image,
then remove and verify absence of that exact tag. When Compose has multiple
services using the built Agent image, the acceptance override must retag every
service, including one-shot volume initialization, so it does not create an
untracked `:local` image.
For Windows Service installation, set `MODEL_PATH` to the installed
`current\models\yolov8n.onnx` path because the Service Control Manager does not
start services from the Agent release directory. Validate the service's model
path, enrollment, startup, signed update, and rollback on a real Windows host;
PowerShell parsing on Linux is not a substitute for that run.
For Linux systemd installs, preserve the site display name through the existing
`LoadCredential=agent-name` credential and `AgentOptions` fallback. The
foreground installer may pass `Agent__AgentName` directly; do not put arbitrary
site names in an unescaped systemd `Environment=` assignment.
Linux enrollment values must be passed to `install/install-agent.sh` using
`--central-url-file` and `--site-token-file`, each pointing to a regular file
with no group/other permissions. Reject legacy `--central-url` and
`--site-token` values because they are visible in process listings. The site
token is persisted only in root-owned and Agent-owned mode-0600 credential
files and loaded by systemd `LoadCredential`; generated command text must not
contain either enrollment value. Keep the temporary prompt files mode 0600 in
a mode-0700 directory and remove them on every exit path. Verify generated
Linux command text has no Central URL or site token, both legacy value flags
fail before installation, and unsafe/symlink/empty files are rejected.
Keep the Central URL out of process arguments and unit contents. The Linux
installer stores it in the Agent release's `appsettings.json` with mode 0640
inside the mode-0750 Agent release tree; a new Agent may alternatively load it
from a systemd `central-url` credential through `CREDENTIALS_DIRECTORY`.
Agent logs must not include the Central URL.
The server installer Compose project/network must use Compose's project-scoped
resource names rather than fixed global `name:` values. The interactive
installer should default CORS to the configured public HTTPS origin when one
is supplied and otherwise use a restrictive placeholder that the operator
must replace; do not default a new installation to wildcard CORS.
Before accepting a native or Docker install flow, verify that Central's global
`updates.forgepublicurl` contains only the HTTPS public Forgejo origin and that
Central constructs `api/v1/repos/arnaud.dartois/Heimdall/releases/latest` from
it. The calculated API URL is read-only in Settings. A published release must
contain the signed manifest, asset checksums, and required image digest. A
`main` Docker image build alone cannot supply the signed Agent release metadata
used by installers and the IHM.
Forgejo releases may omit the optional `asset.digest` API field. In that case,
Central may fetch the public key, manifest, and signature only from HTTPS URLs
on the configured Forgejo origin, then must verify the ECDSA P-256 signature,
release tag, manifest schema, archive SHA-256 values, and image digests before
returning metadata. Use the hashes from the verified signed manifest for
downloadable archives. Reject cross-origin asset URLs, redirects to another
origin, bad signatures, malformed digests, and tag mismatches. Do not replace
missing API digests with unchecked archive metadata or disable verification.
Validate both an actual release whose API omits `asset.digest` and synthetic
tampered metadata in a source-built Compose acceptance.
## Linux rollback simulation
- Run `python3 -m unittest discover -s scripts/ci -p 'test_*.py' -k supervisor_rolls_back_failed_startup_to_previous_release`.
- The test creates two synthetic release directories and a `current` link to the candidate, writes a pending-update marker, and injects a fake `dotnet` executable that exits immediately with failure.
- Verify the supervisor returns 75, atomically points `current` back at the prior release, removes `pending-update.json`, and reports that the previous release was restored. The fixture must live in `TemporaryDirectory` and leave no files behind.
- This covers only the startup-failure rollback branch. It does not validate HTTP update discovery, signed archive verification, a 60-second healthy startup window, systemd, Windows service behavior, or a real Agent host.
## Local and host acceptance boundary
- Keep `HEIMDALL_SOURCE_BASE_URL` limited to Heimdall-owned installer assets; vendor runtimes and dependencies must use their official distribution channels.
- For updates, exercise both successful and rejected signatures before installation. Preserve the previous release until the candidate has reported the expected version and stayed healthy for the configured stability interval.
- Use a temporary install root and fake runtime for local failure/rollback tests. Never point these tests at `/usr/local`, a real systemd service, production credentials, or an installed Agent state directory.
- Report Linux and Windows real-host install/update/rollback as open until each OS has been exercised with a real service and the expected signing configuration.
- The Linux installer retries the release metadata request at most three times for transport failures, HTTP 408/425/429, and HTTP 5xx, with 2s then 4s waits. Other HTTP statuses fail immediately. Acceptance should verify transient-then-success, persistent-5xx bounded failure, permanent-4xx no-retry behavior, and that release signature and archive digest checks remain required.
## Central installer asset delivery
- `Heimdall.Web.csproj` publishes the Linux/Windows Agent installers and their supervisors under `wwwroot/install/`; `Program.ConfigureMiddleware` serves them through ASP.NET Core static files.
- ASP.NET Core's default MIME table does not recognize `.py`. Add `.py` to a `FileExtensionContentTypeProvider` explicitly or `/install/agent-supervisor.py` returns 404 despite being present in `wwwroot`.
- For changes to these assets or static-file configuration, build Central from the current source in a disposable Compose project and GET `/install/install-agent.sh` and `/install/agent-supervisor.py`. Require HTTP 200 and byte-for-byte equality with their source files. Also require `/healthz` healthy.
- Follow `skills/compose-disposable-recipe/SKILL.md`: use generated credentials, isolated ports/project volumes/network, a unique Central image tag, and an EXIT trap installed before build. Verify all project containers, volumes, and networks are gone and remove/verify absence of the exact local image tag. Keep shared base images.
- A successful local acceptance proves the source-built Central serves the files; it does not prove a deployed Central image has been rebuilt or restarted. Confirm deployed endpoints separately before calling an incident resolved.
-41
View File
@@ -1,41 +0,0 @@
---
name: analysis-job-pipeline
description: Implement and verify analysis job types across Heimdall Central scheduling and Agent inference.
---
# Heimdall analysis job pipeline
Read `AGENTS.md`, the PIPE-01/02 Gitea issue, and `skills/heimdall-dotnet/SKILL.md`. For database behavior, also follow `skills/ef-core-persistence/SKILL.md`.
## Current supported job types
- `ObjectDetection`: return detections produced by the configured YOLO COCO model in model order, capped at 500 because Central rejects larger successful results. The Agent truncates deterministically before serialization so the result can be persisted; detections after the first 500 are intentionally omitted.
- `PersonDetection`: use the same frame/model path and return only COCO class 0 (`person`), capped at 500 after filtering while preserving model order.
- `VehicleClassification`: use the same frame/model path and return COCO motor-vehicle classes 2 (`car`), 3 (`motorcycle`), 5 (`bus`) and 7 (`truck`), capped at 500 after filtering while preserving model order. Keep the model label, confidence, box and class index in the result.
- `MotionDetection`: capture two frames from the already active RTSP stream 500 ms apart, downscale both to 32×18, and compare normalized luminance. A changed pixel must differ by at least 0.12; at least 2% changed pixels returns one `motion` detection with changed-region bounds and changed-pixel ratio as confidence. This CPU-only temporal detector does not require the YOLO model; lighting changes and camera shake may produce motion, so tune/measure it against representative cameras before relying on alerts.
- The Web request whitelist, Central scheduler whitelist/capability requirements, and Agent parser must agree. The Agent accepts enum names and numeric enum values on the wire. Reject unsupported kinds instead of recording a successful empty result.
- Face and plate recognition have separate model/license/privacy requirements; anomaly and full-scene analysis are not implemented. Do not advertise them as available or map them to generic object detection.
- Jobs stay assigned to the Agent currently responsible for the camera. Keep the attempt ID, atomic claims, retries and late-result rejection intact when adding types.
- For every job type, cap successful result detections at Central’s 500-item limit in stable model order. For filtered types, filter first and then cap so unrelated model classes do not consume the result budget. Add boundary tests proving the output count and retained order for ObjectDetection and filtered types. This prevents Central’s permanent HTTP 400 rejection from silently discarding the whole result, while making the truncation explicit.
- Result delivery retries transport failures, timeouts and HTTP 5xx with bounded backoff. A 409/404 attempt is no longer current and stops immediately; other HTTP 4xx responses are permanent for that submission and must also stop immediately so a bad result cannot block the Agent's next poll. Log the status code and job ID only; do not read or log Central response bodies.
## Required validation
1. Unit-test Agent type parsing, motion comparison for identical/changed frames, and exact COCO class filtering for the object/person/vehicle types, including empty results and unsupported types.
2. Run PostgreSQL scheduler tests proving CPU/RAM requirements for supported types and refusal of unsupported types. Do not substitute EF InMemory for relational behavior.
3. Run the PostgreSQL integration scenario through the Web API: create each supported job, dispatch to the assigned online Agent, claim it with the Agent API key, submit a result, and verify persisted completion. Verify unsupported type requests receive HTTP 400.
4. Build Central from the changed source in a uniquely tagged disposable Compose project with generated credentials, loopback-only ports, project-owned volumes/network, empty Sentry DSN, and OCR disabled unless the scenario explicitly needs it. Bootstrap synthetic Admin/site/camera, register and heartbeat a synthetic Agent, assign the camera, submit supported and unsupported job types, and verify the lease/result boundary where practical.
5. Tear down that exact Compose project, verify zero project containers/volumes/networks, remove every source-built image tag from this recipe and verify each exact tag is absent. Retain shared Postgres/.NET base images. Never use broad prune commands.
6. Keep hardware, camera-stream inference, and real multi-Agent deployment claims separate from synthetic database/API acceptance.
For event-handler unit tests, initialize every queried set on the `IApplicationDbContext` substitute with `MockDbSetHelper`, including empty optional sets such as `Recordings`. An unconfigured NSubstitute `DbSet` throws from EF's `IQueryable.Provider` when the handler applies `AsNoTracking` or async LINQ. Use PostgreSQL integration tests for provider translation and persistence behavior; this unit fixture is only for handler branching and notification behavior.
The shared Playwright `E2ETestBase.GotoWithCircuitAsync` dismisses the install-help banner after each navigation. Loopback is a secure browser context, so PWA UI appears in these tests and can intercept clicks on dialogs; browser E2E assertions should exercise the intended application controls after dismissing that unrelated notice.
## Current local acceptance evidence
Result delivery has a focused Agent test: `SendResultAsync_DoesNotRetryPermanentClientRejection` returns after one HTTP 400. The supported result JSON uses web defaults (`classIndex`, not `ClassIndex`). The disposable source Compose acceptance below validates the Central job API and persisted result contract; keep transport retry behavior covered by the Agent HTTP-handler test.
On 5 November 2026, Agent selection tests passed 10/10, PostgreSQL scheduler tests passed 10/10, and the integration scenario for the two filtered types passed 2/2. Disposable source-built Compose project `hmd-analysis-1793881315-5ba569` bootstrapped synthetic Admin/site/Agent, registered and heartbeated the Agent, assigned a synthetic camera, rejected `MotionDetection` with HTTP 400, then created, dispatched, claimed, completed and read back persisted `PersonDetection` and `VehicleClassification` results. Teardown verified zero containers, volumes and networks and removed/verified absence of `heimdall:hmd-analysis-1793881315-5ba569-central`. This exercises scheduling and result contracts with synthetic detections, not video inference.
Motion detection implementation and acceptance (5 November 2026): Agent compares two frames 500 ms apart from the active stream at 32×18 luminance; threshold is 0.12 per pixel and 2% changed pixels, and output is one normalized `motion` region. Central API/scheduler accept the type and its 1-core/512-MB/3-minute capability limits. Tests passed: Agent selection/comparison 13/13, PostgreSQL scheduler 27/27, Web/PostgreSQL API contract 3/3. Source-built disposable Compose project `hmd-motion-1793890915-22844` registered a real Agent container, started a synthetic moving RTSP stream, assigned the camera, created a MotionDetection job, and verified the Agent result with label `motion` and normalized bounds persisted in PostgreSQL. The project was torn down and verified at zero containers/volumes/networks; unique Central/Agent tags were removed and verified absent. Camera shake, exposure/lighting changes and representative real-camera thresholds remain unvalidated.
@@ -1,23 +0,0 @@
---
name: api-key-last-used-throttle
description: Preserve Heimdall API-key authentication while limiting LastUsedAt persistence to one atomic EF Core update per minute.
---
# API-key activity timestamp
`ApiKeyAuthenticationHandler` authenticates an agent API key for every protected request. `LastUsedAt` is an operator-facing activity indicator; it does not need request-level precision. Keep API-key validation, agent binding, authorization claims, and expiry checks on every request, while avoiding a database write for every heartbeat or telemetry call.
## Implementation
- Pass `HttpContext.RequestAborted` to each database read and write in the authentication handler.
- Update `LastUsedAt` with EF Core `ExecuteUpdateAsync`, using a database-side predicate that permits the write only when the timestamp is null or at least one minute old. The predicate and update must be one SQL statement so concurrent requests using the same key collapse to one write.
- Do not call `SaveChangesAsync` for this timestamp. The handler has no other pending changes, and the tracked API-key entity is only needed for validation and claims.
- Keep the timestamp semantics visible to operators: after a burst of requests, it reports recent use with up to one minute of delay.
## Acceptance
1. A PostgreSQL relational test verifies that a null timestamp is written, requests inside the one-minute window do not rewrite it, an expired window refreshes it, and concurrent requests produce no duplicate update within the window.
2. API-key authentication tests verify valid, expired, unbound, and invalid keys retain their existing outcomes and claims.
3. Run the CI EF Core persistence policy and the focused Infrastructure/Web test suites.
4. Run the disposable Compose recipe from `skills/compose-disposable-recipe/SKILL.md` with unique credentials, project name, ports, volumes, and local image tag. Verify authentication behavior, then verify that project resources and the exact locally built tag are absent after teardown.
5. Link the change to Gitea GlitchTip issues #200, #201, #202, #203, and #205. Record the actual local/CI/Compose results and keep post-deployment GlitchTip evidence distinct.
-25
View File
@@ -1,25 +0,0 @@
---
name: api-key-localization
description: Maintain and verify French and English localization for Heimdall's API key administration page and dialogs.
---
# API key localization
The API key administration UI is `src/Heimdall.Web/Components/Pages/Admin/ApiKeysPage.razor`. Its text comes from `AdminApiKeys_*` entries in `src/Heimdall.Web/Localization/SharedResources.*.resx` through `UiText`; the active culture is selected by `UiLanguageService`.
## Updating strings
1. Keep every `AdminApiKeys_*` key present in the neutral resource and localized resources. Use `SharedResources.en.resx` as the English wording reference and translate all visible create, one-time-secret, revoke, validation, helper, and empty-state copy in `SharedResources.fr.resx`.
2. Replace placeholder values that repeat a key suffix (such as `ExpiryHelp`) with actual English fallback copy in `SharedResources.resx` and an actual French translation in `SharedResources.fr.resx`. Check the related `AdminAllAgents_EmptyDescription` entry when auditing the French admin empty states.
3. Preserve formatting tokens such as `{0}` in interpolated resource values and preserve the API date format when translating optional date labels.
4. Add or update focused bUnit tests under `tests/Heimdall.Web.Tests/Components/Pages/`. Render the page with `PageTestBase`, serve an empty API key list via `api/api-keys`, and assert the French empty-state description and create-dialog labels with key-suffix placeholders absent. For other dialogs, exercise the corresponding UI action and assert the rendered localized text.
## Acceptance
Run the focused tests with:
```sh
dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --no-restore --filter 'FullyQualifiedName~ApiKeysPageTests|FullyQualifiedName~AllAgentsPageTests'
```
The acceptance evidence should record the command and result. A test run blocked by shared-runner contention is not a pass; rerun it when the runner is available. This localization-only change does not need a disposable Compose acceptance recipe because it changes no runtime behavior or deployment configuration.
-33
View File
@@ -1,33 +0,0 @@
---
name: backup-restore
description: Validate Heimdall PostgreSQL and protected-volume backups using isolated Compose projects and the production backup/restore scripts.
---
# Heimdall backup and restore
For an explicitly authorized real backup/restore operation, follow [Infisical secrets](../infisical-secrets/SKILL.md) and retrieve only the selected environment's required key. Use generated credentials and disposable volumes for acceptance.
Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/restore*.sh`, the backup Compose, or the disaster-recovery runbook.
## Project-specific behavior
- PostgreSQL backups use `docker/scripts/backup.sh` and restores use `restore.sh`. Supply credentials through a generated `POSTGRES_PASSWORD_FILE` or a generated environment file; never reuse `docker/.env`, production secrets, or live volumes.
- `backup-protected-data.sh` archives the Central data volume, including local objects and `dp-keys`. Restore with `restore-protected-data.sh` only while Central is stopped. The script overlays files and deliberately keeps unrelated target files.
- Preserve the entire Data Protection ring and `dp-cert.pfx` together. Expired keys can still be required to unprotect stored payloads; never replace/delete one file as part of a restore. Heimdall has no validated manual rotation process for the certificate that protects the ring at rest; keep certificate rotation separate until tested against existing payloads. See `docker/backup/README.md`.
- PostgreSQL and protected-volume archives are separate snapshots. The application does not coordinate them into one atomic point in time.
- The scheduled backup Compose installs Alpine `aws-cli`, `bash`, and GNU `coreutils`; it does not install MinIO Client (`mc`). `backup-rustfs.sh` uses `aws s3 sync` in this shipped container and only selects `mc mirror` when `mc` is already present in a customized environment. Keep `docker/backup/README.md` aligned with this effective default and never document a retired `mc` download as an installer step.
- The scheduled Compose sets `TZ` to `Europe/Paris` by default. Cron times in `docker-compose.backup.yml` use the container timezone, while scripts use UTC for archive timestamps and retention cutoffs. Document both clocks separately and describe any changed `TZ` as an operator configuration, not as UTC scheduling.
- `test-backup-restore.sh` uses a named isolated network, `tmpfs` for its disposable PostgreSQL data directory, and a temporary host directory. Its cleanup must leave no container, network, or anonymous volume.
## Acceptance
1. Read `docker/backup/README.md` and `docker/scripts/test-backup-restore.sh` before changing the flow.
2. Run the script and require all assertions to pass, including row/FK integrity, object/key digests, and Data Protection key permissions.
3. For changes to volume-level restore or Compose behavior, build a disposable Compose project from the checkout with unique project name, generated credentials, and generated named volumes. Dump from one PostgreSQL volume and restore into a different volume; check a known row. Archive and remove synthetic files from the protected volume, restore them, and compare digests and key permissions.
4. Measure only the synthetic restore duration and label it as a local fixture measurement. Do not present it as a production RTO. Derive the configured backup interval separately; do not imply it is a measured production RPO. For actual RPO/RTO drills, use the timestamp, resource, host, and repeated-run procedure in `docker/backup/README.md` and record the operator-approved target separately.
5. Install an EXIT cleanup trap before build/start. Tear down only the disposable project with `docker compose -p <name> down --volumes --remove-orphans`; query its Compose project labels and confirm zero containers, volumes, and networks. Remove generated files even on a failed assertion. These fixtures use upstream PostgreSQL/RustFS images and build no local image unless a recipe change explicitly adds one; retain those upstream images. If adding a local build, record its unique tag and remove/verify that exact tag in the same trap after teardown. Never use `--rmi all` or broad prune commands.
6. The scheduled backup image installs Alpine's `aws-cli`, `bash`, and GNU `coreutils` (`date -d` retention cutoffs do not work in BusyBox), not MinIO Client. `backup-rustfs.sh` therefore uses `aws s3 sync`; its `mc mirror` branch is only a fallback when a customized image already provides `mc`. Do not rely on the retired MinIO client download URL. The AWS CLI path passes configured S3 credentials explicitly for each invocation.
7. Validate S3 behavior with a disposable RustFS service, unique Compose project/network/volumes and generated keys. Create a synthetic row, run `backup.sh`, verify both dated and `latest.sql.gz` objects, mutate the row, then run `restore.sh --latest --yes` and verify the prior value. Add ancient synthetic daily and weekly keys and confirm both retention jobs delete them. Also exercise `backup-protected-data.sh` upload and `backup-rustfs.sh` mirror/manifest where changed.
8. Keep real-volume production recovery and production RPO/RTO open until validated on their actual service and data.
These backup recipes use shared upstream PostgreSQL/RustFS images and do not build a Heimdall image by default; retain those base images. Record `local image tags: none` for such a run. If a changed recipe adds any local build, tag it uniquely for the Compose project and remove/verify that exact tag after teardown in the same EXIT trap, even on failure. Do not use image-prune commands.
@@ -1,16 +0,0 @@
---
name: camera-access-async-admin-check
description: Keep camera and site authorization admin-role checks asynchronous in Heimdall.
---
# Async administrator checks in camera access
`CameraAccessService` uses `IIdentityPersistenceContext` for Identity role membership. Never call synchronous EF operators on `UserRoles` or `Roles` in this authorization path. The filter API is asynchronous because the admin bypass must be decided before building the grant-filtered camera query.
When changing this behavior:
- Use `AnyAsync` and pass the caller's `CancellationToken` through the role lookup and final camera/site query.
- Preserve the empty-user rejection and `AppRoles.Admin` predicate; ordinary users continue to use direct, site-wide, legacy, and live group grants.
- Keep camera scoping at API/application boundaries. Update `ICameraAccessService` consumers when changing its async filter contract.
- Run `CameraAccessServiceTests`, `ResourceAccessTests`, and `CameraAccessAdminPostgresTests`; mocks alone do not establish relational behavior.
- Run the EF Core persistence policy and disposable source-based Compose acceptance. Record exact image tags and cleanup evidence on the Gitea issue.
-23
View File
@@ -1,23 +0,0 @@
---
name: camera-access-groups
description: Implement and validate Heimdall user-to-camera grants and group camera access through the administration UI and API.
---
# Camera access and groups
Camera visibility is the union of direct camera grants, site-wide grants, legacy user site assignments, and cameras granted to groups the user belongs to. Keep that union in `CameraAccessService` and `ResourceAccess`; do not reimplement partial scope rules in controllers or UI queries. Site and camera resource checks must continue to run at API/application boundaries, including snapshots, events, hubs, and agent assignment.
When editing authorization examples in `docs/auth-roles.md`, verify routes against the actual controller mappings and explain the query/service-level access filtering. Human JWTs carry role/permission and session claims, not a frozen list of site IDs; do not describe a global `SiteScopeMiddleware` unless one is implemented.
Manage group-camera membership through the authenticated `api/groups/{groupId}/cameras` endpoints. The administration page loads all sites and their cameras with bounded paging, displays site names beside cameras, and adds/removes grants through the API. Treat failed loads and mutations as errors; do not optimistically report success.
When changing this area, verify:
- `ResourceAccessTests` for the role/grant matrix, live group membership revocation, and union of direct plus group grants.
- `HttpIsolationTests` and the affected API integration tests for real HTTP authorization outcomes.
- `GroupsPageTests` for site/camera labels and the UI add/remove request sequence.
- PostgreSQL integration tests for persistence or query changes; do not use EF InMemory as relational proof.
- The disposable Compose recipe in `skills/compose-disposable-recipe/SKILL.md` for behavior or deployment changes, using a unique project, network, credentials, ports, and volumes.
- If Compose builds Central from source, record a project-unique tag and install an EXIT cleanup trap before build/start. After teardown remove and verify absence of that exact tag even on failure; retain shared base images and report cleanup errors.
Use synthetic camera metadata in automated tests. Physical RTSP, snapshot and reconnect behavior is a separate Agent/camera acceptance and must be reported as unverified unless run against real hardware.
@@ -1,17 +0,0 @@
---
name: camera-access-nullable-select
description: Keep nullable camera-access grant selectors type-consistent in the Heimdall Blazor UI and verify site-wide and camera-specific grants.
---
# Camera access nullable selectors
The grant form in `src/Heimdall.Web/Components/Pages/CameraAccessPanel.razor` stores the selected site and camera as `Guid?` because the form supports an unset selection. Keep each corresponding `MudSelect` and all of its `MudSelectItem` children explicitly typed as `Guid?`; cast non-nullable model IDs with `(Guid?)` in each item value. A plain `Guid` item can compile yet fail at runtime when MudBlazor dispatches the option click to its nullable parent.
When editing this form, preserve the two grant modes: site-wide grants save a site ID and null camera ID, while camera-specific grants save both IDs. Validate both selection interactions and the serialized saved grants.
## Acceptance workflow
1. Run the focused Web tests with `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --no-restore` and build `src/Heimdall.Web/Heimdall.Web.csproj` using the SDK pinned in `global.json`.
2. For behavior changes, follow [the disposable Compose recipe](../compose-disposable-recipe/SKILL.md): build the changed source using unique local image tags and isolated credentials, project, ports, network, and volumes.
3. Bootstrap an isolated administrator, use a real browser/UI-capable test to select a site-wide option and a camera option, and verify the saved grants contain respectively a null and non-null camera ID with no `InvalidCastException`.
4. Tear down only that Compose project. Verify its containers, volumes, and networks are absent; remove and verify absence of only the recipe's exact locally built tags, preserving shared base images.
-17
View File
@@ -1,17 +0,0 @@
---
name: camera-assignment
description: Implement and verify assignment of Heimdall cameras to online Agents using persisted assignment history and actual Agent capabilities.
---
# Heimdall camera assignment
Read `AGENTS.md`, the camera/Agent assignment Gitea issue, and `skills/heimdall-dotnet/SKILL.md`. For persistence changes, also follow `skills/ef-core-persistence/SKILL.md`.
- Keep assignment scoped to the camera's site and online Agents. Persist assignment/release history and update `Camera.AgentId` in the same EF Core unit of work.
- Assignment strategy must use evidence actually supplied by the relevant entity. Do not infer Agent inference hardware from camera-side protocol flags such as PTZ or camera-native motion detection.
- `GpuPriority` prefers Agents reporting `HasGpu`; if none are GPU-capable, it falls back to all online Agents. Workload balancing remains deterministic within the eligible candidates.
- Camera discovery currently does not populate `Camera.HasMotionDetection`; treat that legacy field as unknown/false and do not use it for Agent placement until a camera capability probe supplies verified data.
- Add PostgreSQL relational tests for strategy selection, failover, and assignment history. Do not use EF InMemory to verify concurrency or transaction semantics.
- For every behavior change, build a uniquely tagged disposable Docker Compose acceptance stack from the changed source, exercise the changed assignment through the API or service boundary against PostgreSQL, and use generated credentials, ports, volumes, and project name. Install an EXIT trap before build/start; tear down only that project, verify zero project containers/volumes/networks, remove each locally built image tag and verify it absent. Preserve shared base images and test exit status. Follow `skills/compose-disposable-recipe/SKILL.md`.
Current validated behavior: `GpuPriority` selects a GPU Agent for a camera even when camera motion capability is false; PostgreSQL test evidence is recorded in the linked Gitea issue.
-74
View File
@@ -1,74 +0,0 @@
---
name: camera-toggle-acceptance
description: Validate that Central camera enable/disable changes stop and resume the real Agent FFmpeg capture process and persist across Agent restarts.
---
# Camera enable/disable lifecycle
Read `AGENTS.md`, the Toggle caméra #59/#199 Gitea issue, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing this flow.
## Implementation path
- `POST /api/cameras/{id}/toggle-status` requires the normal camera-write permission and persists `Camera.Status` in Central. Enabling a Disabled camera sets it to Offline (enabled, connectivity not yet confirmed); only an Agent status report can set it Online. Toggling any enabled status sets it to Disabled.
- Agent status reports require the API key to resolve to the same Agent ID in the route and the camera to be assigned to that Agent. Authenticate and authorize both resources with `ResourceAccess`; never trust the route ID alone. Keep the existing same-site camera check in `ReportCameraStatusCommandHandler`.
- `AppDbContext.SaveChangesAsync` publishes a payload-free config invalidation after camera/assignment/profile changes. Agent refetches its authorized full camera snapshot over its ConfigHub/API path and acknowledges the digest.
- `GetEffectiveAgentConfigQuery` emits `camera.<id>.enabled` from the persisted status. `CameraConfigStore` atomically replaces the snapshot and raises `Changed`.
- `SnapshotPipelineService` reconciles enabled assignments with `CameraStreamService`; disabling/removing an assignment kills FFmpeg, awaits its read loop cleanup and releases its stream permit. Enabling starts the stream. Keep central status authoritative; an Agent status report must not re-enable a disabled camera.
- `SnapshotPipelineService` reconciles configuration on `CameraConfigStore.Changed`, while retaining a one-second config-change poll and the existing 30-second full resync as recovery. Coalesce notifications and ensure there is only one waiter on the config signal.
- Camera counts and lists consider only Online cameras connected. An enabled Offline/Error camera remains enabled in the Agent configuration but is not counted as Online. UI toggle messages treat every status except Disabled as enabled.
- Agent identity and API key are protected in `AgentState` under the configured state directory. Mount a project-scoped volume there so a restart reuses the same Agent identity and the Central configuration is refetched from persistent camera state.
## Local verification
The Central status contract is covered by `ToggleCameraStatusCommandTests` and the `CamerasControllerTests.ToggleStatus_WithAuth_TogglesCamera` relational API test: activation persists Offline, the authorized same-site Agent status endpoint can confirm Online, and a subsequent administrative toggle persists Disabled. Run these focused tests alongside the Agent lifecycle suites when changing this contract.
Run the focused Agent lifecycle suites:
```bash
dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --filter 'FullyQualifiedName~CameraStreamServiceTests|FullyQualifiedName~SnapshotPipelineServiceTests' --no-restore
```
These tests cover session idempotence, process termination, and synchronization without claiming a full Central/Agent workflow.
## Central + Agent disposable acceptance
Run `skills/camera-toggle-acceptance/acceptance.sh` from the repository root. It builds both application images from source, bootstraps synthetic Central/site/camera data, registers the real Agent container, repeats three ON/OFF cycles, checks the OFF PID bound, restarts Agent and Central while OFF, correlates the final applied config digest, and verifies exact project/tag cleanup in its EXIT trap.
- Build Central and Agent from this checkout with unique tags recorded before the first build. Retain upstream Postgres, MediaMTX, FFmpeg, SDK and ASP.NET base images.
- Use a fresh project-scoped database, JWT/site credentials, loopback-only Central/Postgres ports, network and volumes. Add a project network Agent and a synthetic MediaMTX RTSP publisher. Do not use host networking or real camera credentials.
- Bootstrap a synthetic Admin/site, create a camera pointed at the synthetic RTSP path, register the actual Agent container with the generated site token, and assign the camera to that Agent.
- Toggle ON and confirm an Agent `ffmpeg` pull process exists against the synthetic path. Toggle OFF and verify the API says Disabled, Agent reports no assigned stream via its active process count and the FFmpeg process disappears in under 2 seconds. Toggle ON and verify the process returns within 10 seconds.
- Restart the Agent while ON; verify it reuses its single existing identity and restarts capture within 10 seconds. Then toggle OFF, restart again, and verify the camera remains Disabled and no capture process returns.
- Use `docker top` only to count FFmpeg processes; never print its command lines because they contain the RTSP URL. Record elapsed durations and sanitized HTTP statuses only.
- Install an EXIT cleanup trap before the first build/start. Teardown only the named Compose project, verify zero containers/volumes/networks, remove each exact project-unique Central/Agent image tag and verify absent, then delete the temporary environment and scripts. Keep the original test status and fail if cleanup verification fails.
This acceptance proves the source-built Central/Agent software lifecycle with a synthetic RTSP stream. It does not validate hardware codecs, physical cameras, LAN multicast, or deployed-host timing.
## Observed simulator pitfalls
- Do not count `docker top` output when the runtime's `top` implementation differs. Prefer an in-container process identity check (`/proc/*/comm` equals `ffmpeg`) and ensure the inspection process cannot match itself. A shell command line containing the text `ffmpeg` creates a false positive if the check scans all command lines.
- Before asserting lifecycle timing, first confirm Agent `Online`, persisted camera assignment, effective config enabled value and version, and `LastAppliedCameraConfigVersion` acknowledgement. A failed precondition is not an OFF/ON timing result.
- On failed acceptance, collect sanitized Central, Agent, RTSP server and publisher diagnostics before the cleanup trap runs. Then verify project resource counts and exact image tags as described above.
- Earlier disposable attempts proved bootstrap, registration, assignment and Disabled config acknowledgement, but did not prove toggle timing or restart persistence. The completed source-built run below supersedes those incomplete attempts; physical camera and deployed-host validation remain external.
## Latest source-built run
The fifth disposable Compose attempt used `/proc/*/comm == ffmpeg`, avoiding self-counting by the measurement shell. It confirmed the Disabled baseline at zero processes and progressed through ON, OFF, ON, then Agent restart while ON with capture restored. The next OFF returned Central state Disabled and effective Agent config `enabled=false`, with zero FFmpeg processes, but the latest config digest was not acknowledged inside the two-second OFF bound. Therefore the full OFF/ON/restart acceptance is still incomplete; do not mark #59/#199 complete. Investigate whether Agent ACK version is stale or the API config digest changes after toggle, while keeping the OFF process release measurement distinct from ACK convergence.
## Sixth source-built run
The sixth historical run kept the FFmpeg process deadline separate from the config ACK deadline and verified exact initial digest equality between the Central config version and Agent `LastAppliedCameraConfigVersion`. It failed the OFF process bound and did not run restart-OFF acceptance. The subsequent 2026-11-12 acceptance below supersedes that incomplete result for current source.
## Immediate config reconciliation regression test
`SnapshotPipelineServiceTests.CameraConfigChanged_ReconcilesWithoutWaitingForPeriodicSync` starts the pipeline, lets its initial synchronization complete, then changes the Central snapshot and requires the assigned camera's Error report (FFmpeg deliberately unavailable) within 500ms. This proves event-driven reconciliation ahead of the one-second config-change poll and 30-second full resync; it does not prove process termination or the full camera lifecycle. Run it with the focused camera stream suite before Compose acceptance.
## Source-built acceptance — 2026-11-12
`acceptance.sh` passed with project `heimdall-157-1794488199-31533`, Central tag `heimdall:heimdall-157-1794488199-31533-central`, and Agent tag `heimdall-agent:heimdall-157-1794488199-31533-agent`. Central and PostgreSQL published only on `127.0.0.1`. After confirming the ON config digest ACK, it exercised three ON/OFF cycles with FFmpeg release at 1,386ms, 555ms, and 410ms, then a final OFF at 810ms before restart. Each transition verified the exact Central config digest ACK and expected `camera.<id>.enabled` value. The process monitor rejected counts above one. After Agent restart while OFF, the same Agent reported Online with a heartbeat and config ACK timestamp newer than the Compose restart command's return; after Central restart it again reported Online with a fresh ACK for the persisted Disabled digest newer than the restart command's return. Agent restart while ON preserved its identity and resumed capture. Cleanup verified zero project containers, volumes, and networks and absence of both exact local image tags. This is synthetic source-built software evidence, not camera hardware or deployed-host timing.
## Camera status contract acceptance
For status semantics (issue #291), run `CamerasControllerTests.ToggleStatus_WithAuth_TogglesCamera` against PostgreSQL and the `ToggleCameraStatusCommandTests` suite. The relational test must assert Disabled → Offline and the online counter remains zero before connectivity, register and heartbeat a synthetic same-site Agent, reject its report before camera assignment, assign the synthetic camera, accept that Agent's Online report, reject a request that uses its API key with a different route Agent ID, and then confirm admin toggle → Disabled.
A source-built disposable Central + PostgreSQL Compose run on 2026-11-11 used project `heimdall-291-acceptance-1794427561-8428`, synthetic bootstrap/site/Agent/camera data, loopback ports 18543/15439, and image `heimdall:heimdall-291-acceptance-1794427561-8428-central`. It observed health HTTP 200, activation Offline, online count 0, then Agent-confirmed Online and online count 1. Cleanup verified zero project containers, volumes and networks, the exact image tag absent, and temporary files removed. This is software acceptance only; it does not satisfy `validation:field` hardware/deployment evidence.
-58
View File
@@ -1,58 +0,0 @@
---
name: central-auto-updates
description: Maintain Central server installation, Compose refresh, and Docker image auto-updates for Heimdall deployments.
---
# Central installation and image updates
For credentials needed by an explicitly requested real deployment, follow [Infisical secrets](../infisical-secrets/SKILL.md). Disposable Compose acceptance continues to use generated credentials and isolated resources.
Use this skill when changing the Linux or Windows Central installer, its generated Compose, or Central container update behavior.
For installer, Compose, image, and documentation work that can proceed independently, use [parallel development with Orca](../parallel-development/SKILL.md). Keep shared deployment contracts and the final isolated acceptance run coordinated and integrated before recording evidence.
## Central and release endpoints
- The Central address embedded in generated Agent installation commands must come from the browser's exposed `NavigationManager.BaseUri`; do not store a deployment hostname in a Razor page or installer template. Preserve the path base and trim only its trailing slash.
- The release source is the global `updates.forgepublicurl` setting edited in Settings. It stores only the public HTTPS Forgejo origin; `ForgeReleaseApiAddress` constructs the fixed Heimdall `api/v1/repos/arnaud.dartois/Heimdall/releases/latest` endpoint, which Settings displays read-only. Startup migrates legacy `updates.releaseapiurl` values to their origin and removes the old row. Agent release checks must go through the authenticated Central `/api/updates/agent/latest` endpoint, which returns the configured manifest and asset URLs.
- Native Agent installers require an explicit Central URL, and Docker Agent configuration must pass `Agent:CentralUrl` from the generated command or deployment environment. Localhost defaults are permitted only in explicitly local development Compose/configuration.
- Optional Agent public-IP discovery has no built-in provider hostname; configure `Agent:PublicIpResolverUrl` with an HTTPS endpoint or leave it empty to report no public IP. Validate the URL before creating the HTTP client.
- Server-side API calls from Blazor circuits must prefer the process's Kestrel loopback binding over a retained browser `Host`; a public reverse-proxy host may not be reachable from inside the Central container. Normalize wildcard Kestrel binds (`0.0.0.0`, `[::]`, and `+`) to loopback while preserving the bound port.
- Installer scripts should embed the official Heimdall source base as their standalone default and allow `HEIMDALL_SOURCE_BASE_URL` to override it for reviewed revisions or mirrors. Use it only for Heimdall-owned source assets; keep vendor dependencies on their official distribution sources.
- Configure the Forgejo API endpoint used by Renovate through the Actions variable `FORGEJO_API_ENDPOINT`; Forgejo reserves variable names beginning with `GITEA_`. Do not embed the forge hostname in workflow YAML. Track credential/run validation in its Gitea issue.
- Keep Compose network names project-scoped by omitting a fixed `networks.*.name`, especially for disposable validation projects.
## Deployment behavior
- Keep the installer-generated core stack limited to PostgreSQL, Central, and the updater. Only Central receives the Watchtower enable label; do not update PostgreSQL automatically.
- Use the maintained `nickfedor/watchtower` image at an explicit version, `--label-enable`, a 24-hour interval, and `--cleanup`. Cleanup removes superseded images after an update; it must never remove Docker volumes or database files.
- Apply `pull_policy: always` to published Docker images in deployment Compose files so a manual `docker compose up` checks the registry. Leave local development-only images alone and keep the updater itself version-pinned.
- The Docker socket mount grants Watchtower broad control of the host. Document this risk and the lack of staged rollout/rollback; do not describe automatic updates as a production-safe rollback system.
- For each published Ubuntu-based Central, CPU Agent, or CUDA Agent runtime image, update the package index, apply the package security updates required by current Trivy findings, install runtime packages, and clear apt lists in one layer. Keep a broader OS upgrade only where that image already establishes the policy (the CUDA image); verify every final image with the pinned Trivy scanner at HIGH/CRITICAL severity. A passing application build does not clear OS package advisories.
## Runtime image package security
- The server and CPU Agent runtime images inherit Ubuntu 24.04 from the pinned ASP.NET image. When Trivy identifies a fixed Ubuntu package in the shared base, remediate both Dockerfiles and enforce the minimum patched version at build time. For `CVE-2026-109518`, explicitly upgrade `apt` and `libapt-pkg6.0t64` to at least Ubuntu `2.8.4ubuntu0.1` before runtime packages. The NVIDIA Agent runtime keeps its existing full OS upgrade and asserts the patched APT version too.
- Run Central + PostgreSQL from source in a disposable Compose project, verify health and native Agent asset URLs, then scan Central, CPU Agent, and any changed CUDA image with the same pinned Trivy scanner and HIGH/CRITICAL policy used by CI. Require no findings and perform exact-tag cleanup. See `skills/container-image-security/SKILL.md`.
## Re-running the installer
- A complete existing install can regenerate its Compose after validating the candidate. Keep a timestamped backup of the previous Compose before atomic replacement.
- If the operator selects an existing optional service again, refresh its source assets through a temporary file and back up each replaced local asset.
- Preserve `.env`, the PostgreSQL secret file, and Docker named volumes. Do not rotate existing credentials during an update.
- When a newer Compose needs an absent env key, append a generated secret or documented default only if that key is missing. Never print secret values. Refuse to continue if the existing database URL or password file needed by PostgreSQL is missing.
- If the user declines the Compose refresh, exit without changing the install. If only part of an install is present, stop and explain what is missing instead of creating a second set of credentials.
## Live Linux deployment evidence
For an explicitly authorized host validation, inspect existing services and data before mutation, use only that environment's protected credentials, and scope reset to the named Heimdall Compose projects. Install Central and Agent through the released `.sh` installers. Record image digest, Agent version/identity/site association, `/healthz`, local Agent version endpoint, heartbeat status, credential modes, listener bindings, and sanitized logs. Restart Central and Agent and verify health and persisted volumes/site identity. Do not infer Windows, GPU, camera, multicast, TURN, backup, or long-load acceptance from a single Linux host.
## Acceptance
Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. For the Site Install UI, assert generated CPU/GPU Compose and `docker run` references use their corresponding immutable `repository@sha256:digest` Agent image, Compose sets `pull_policy: always`, Docker Run commands set `--pull always`, all paths mount `/var/run/docker.sock`, and the non-root Agent receives the socket group (`DOCKER_GID` in Compose; detected socket GID for Linux `docker run`). Keep signed digest validation for updates dispatched by Central. A signed Agent manifest always requires the CPU image repository and digest; GPU image metadata is optional for CPU-only releases, and must be present as a valid repository/digest pair when either field is supplied. Unit tests cover CPU-only and CPU+GPU signed manifests plus a malformed half-pair. Source-built Compose acceptance probes Central's latest-release API against the configured public Forgejo source and verifies the returned signature and required CPU digest; record whether the current release also carries GPU metadata. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and an EXIT cleanup trap installed before build/start. Never connect the recipe to a deployed Docker daemon or production data.
When a runtime Dockerfile changes for OS security updates, source-build and health-check the corresponding Central/Agent image, then scan its saved image archive with the pinned Trivy version and the same `HIGH,CRITICAL` severities used by CI. Record the finding IDs and fixed package versions; do not hide a nonzero scan behind application acceptance.
If acceptance builds a local Central/helper image, record its project-unique tag before build and remove/verify that exact tag in the same cleanup trap, including on failure. Do not remove registry/base images or use `--rmi all` or broad image pruning; Watchtower's deployment `--cleanup` behavior is separate from disposable-test cleanup.
- The Site Install UI must retain the CPU/GPU image digest returned by Central and generate immutable `repository@sha256:digest` references for both Compose and Docker Run. Never reduce a verified release image to a mutable `:latest` tag. Test with distinct CPU/GPU digests and reject malformed/missing digest values by disabling Docker install generation.
-98
View File
@@ -1,98 +0,0 @@
---
name: compose-disposable-recipe
description: Build and acceptance-test Heimdall changes in a disposable Docker Compose stack, isolated from deployed data and configuration.
---
# Disposable Compose acceptance
Follow [Infisical secrets](../infisical-secrets/SKILL.md) when the surrounding task also needs real credentials. Acceptance projects must always use generated synthetic values and must never retrieve deployment secrets from Infisical.
Use this skill for every Heimdall behavior, deployment, or operational change. Read the relevant project skill too; for first administrator setup, use `first-admin-bootstrap`.
When implementation or acceptance preparation has independent branches, use [parallel development with Orca](../parallel-development/SKILL.md) to assign bounded work. Keep the final Compose run, cleanup verification, and acceptance evidence under one coordinator so the combined change is validated as a whole.
Track the change and its acceptance evidence in a Gitea issue; follow [the Gitea ticket workflow](../gitea-ticket-workflow/SKILL.md). Put the project name, exact local image tags and cleanup verification in the issue or linked PR, and close the ticket only after the recipe and other required gates pass.
## Safety and isolation
- Build from the current source with a unique Compose project name. Do not test against the production hostname, database, image volumes, secrets, or credentials.
- Put generated `.env` and secret files under a temporary directory outside the repository. Use synthetic test identities and cryptographically random local passwords.
- Use an unused loopback host port and Compose-managed volumes whose names include the unique project name. Do not join production or shared networks.
- Give each locally built acceptance image a project-unique tag, for example `heimdall:<project>-acceptance`; do not build under `latest`, `local`, or a tag that existed before the recipe. Use a temporary Compose override to set the unique image tag while preserving the source build context. Record all generated tags before starting.
- Never use broad Docker cleanup such as `docker system prune`, `docker image prune`, or `docker rmi $(docker images -q)`. Remove only the test project with `docker compose -p <unique-name> down --volumes --remove-orphans`.
- After teardown, check that the project has no containers, volumes, or networks. For every locally built image tag, run `docker image rm <exact-recipe-tag>` if it exists, then verify `docker image inspect <exact-recipe-tag>` fails. Remove the temporary Compose override/env/source files. Do not remove shared upstream base images (for example PostgreSQL, .NET SDK, or MediaMTX) or images owned by another recipe/project.
- Put teardown and exact-tag image removal in the same cleanup trap so both success and failure paths clean up. Do not reuse another acceptance recipe's locally built image: build a uniquely tagged image for this recipe and remove it in this recipe's cleanup path.
- A recipe is not complete until every local application image tag created by that recipe has been removed and verified absent. `docker compose down` does not remove images. Apply this even when the behavioral assertion fails; keep generated upstream/base images and unrelated project images untouched.
- These requirements apply to every Docker-based acceptance recipe, including SDK-only test containers, third-party mocks, one-shot helpers, and failure/partial-build paths. Such recipes must explicitly state whether they build any local images. If they build none, leave upstream images intact and still verify cleanup of project containers, volumes, and networks. If they build any local image (Heimdall or helper), record its unique tag before build and remove/verify it absent in the same `EXIT` cleanup trap, even if Compose startup or the build fails.
- Cleanup must preserve the recipe's original exit status, attempt teardown and removal of every recorded tag independently, and report cleanup failures rather than silently declaring acceptance complete. Never use `--rmi all` because it can remove shared or unrelated images.
- **Mandatory local image cleanup:** before the first build, enumerate and record every recipe-owned image tag that may be created (application, SDK/test harness, mock, one-shot helper). Use a unique tag for each locally built image. The EXIT trap must remove each exact recorded tag after project teardown and verify it is absent, regardless of whether build, startup, assertions, or teardown failed. Do not count an image as shared merely because its Dockerfile uses a shared base; only remove recipe-built tags, and retain upstream images. If no image is built locally, explicitly say so and verify the project resources are gone. Never leave recipe-created local images behind.
### Required cleanup trap pattern
Use one `EXIT` trap installed before the first build or Compose start. Record
exact local tags in an array before building; leave the array empty when the
recipe builds no images. Cleanup actions must be independent so a failed
Compose teardown cannot skip image and temporary-file cleanup. Preserve the
original status and return a failure if any cleanup verification fails:
```bash
# Initialize these exact paths before installing the trap. Omit source_copy if
# the recipe does not create a source archive.
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
env_file="$temp_dir/acceptance.env"
compose_override="$temp_dir/compose.override.yml"
source_copy="$temp_dir/source-copy.tar"
cleanup() {
status=$?
trap - EXIT
cleanup_failed=0
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
down --volumes --remove-orphans || cleanup_failed=1
# Query all three resource kinds by Compose project label; do not infer
# absence from `compose down`'s exit code alone.
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
[[ -z "$containers" && -z "$volumes" && -z "$networks" ]] || cleanup_failed=1
for tag in "${local_image_tags[@]}"; do
docker image rm "$tag" >/dev/null 2>&1 || true
docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1
done
# Remove only the files this recipe generated; rmdir fails visibly if
# anything unexpected remains in the temporary directory.
rm -f -- "$env_file" "$compose_override" "$source_copy" || cleanup_failed=1
rmdir -- "$temp_dir" || cleanup_failed=1
if (( cleanup_failed )); then
printf 'Disposable recipe cleanup failed for project %s\\n' "$project" >&2
status=1
fi
exit "$status"
}
trap cleanup EXIT
```
The label queries must succeed and return empty results for containers,
volumes, and networks. Do not include upstream images in `local_image_tags`. Recipe records must state
the project name, whether local images were built, exact tags and absence
checks (or explicitly “none”), plus project-resource cleanup results. A Docker
recipe that reports teardown without the image-tag check is incomplete.
## Acceptance workflow
1. Inspect the Compose file and interpolation requirements before starting it. Generate a temporary environment file with unique database/JWT secrets and a distinct loopback port.
2. Generate a temporary Compose image override. For example:
```yaml
services:
heimdall:
image: heimdall:${ACCEPTANCE_PROJECT}-central
```
Put `ACCEPTANCE_PROJECT=<unique-name>` in the temporary env file and include both Compose files in every command. This overrides only the image tag; the checked-in source build context is retained. Use similarly unique tags for any Agent or helper image built from this checkout.
3. Start the minimal Central + PostgreSQL stack from source with `docker compose -p <unique-name> --env-file <temp-env> -f docker/docker-compose.yml -f <temp-image-override> up -d --build`.
4. Wait for the Central health check and probe the changed behavior through its HTTP/API/UI boundary. Exercise both the expected success path and the relevant rejection/restart path.
5. Capture only sanitized logs or response codes needed to explain a failure. Never print passwords, tokens, connection strings, or full environment files.
6. Install an `EXIT` trap before the first build/start operation. The trap must preserve the test command's exit status, run `docker compose ... down --volumes --remove-orphans`, verify no project containers/volumes/networks remain, remove every recorded project-unique locally built image tag and verify each is absent, then delete each explicitly named generated environment, secret, override, and copied-source file with `rm -f`. Finish with `rmdir` on the one temporary directory; a non-empty directory must make cleanup fail visibly. Attempt each cleanup action even if an earlier action fails. Retain shared upstream/base images. Do not use recursive deletion, Compose `--rmi all`, or broad prune commands.
If Docker access is unavailable, request the required local permission or explain the blocker; do not substitute a production deployment or claim the recipe passed.
-16
View File
@@ -1,16 +0,0 @@
---
name: heimdall-container-image-security
description: Diagnose and repair vulnerabilities in Heimdall Central and Agent container images.
---
# Container image security updates
Read `AGENTS.md`, the image-scan/acceptance Gitea issue, `skills/compose-disposable-recipe/SKILL.md`, and `skills/central-auto-updates/SKILL.md` before changing runtime images or their publication path.
Heimdall server, CPU Agent, and NVIDIA Agent images use Ubuntu 24.04 runtime layers. When Trivy reports a fixed Ubuntu package, update the affected packages unless the image already establishes a broader OS-upgrade policy. For `CVE-2026-109518`, all three runtime Dockerfiles explicitly upgrade `apt` and `libapt-pkg6.0t64` after `apt-get update` and assert that `apt` is at least `2.8.4ubuntu0.1` before installing runtime tools. The NVIDIA image retains its existing full OS upgrade as well. Keep Trivy severity and exit thresholds unchanged.
For acceptance, build Central, CPU Agent, and NVIDIA Agent from the changed checkout under unique Compose image tags with synthetic credentials, loopback ports, project-scoped volumes/network, and an EXIT cleanup trap. Verify Central health and the native Agent installer and supervisor URLs; build the NVIDIA image without claiming GPU runtime validation. Scan all three built images with the same pinned Trivy version, vulnerability DB repositories, and HIGH/CRITICAL exit policy used by `scripts/ci/security.sh`. A passing acceptance requires zero HIGH/CRITICAL findings, successful teardown, no project containers/volumes/networks, and removal plus absence checks for every exact local tag. Retain upstream base and scanner images.
When Trivy reports fixed .NET runtime advisories, update the pinned SDK and ASP.NET runtime manifest-list digests together across all three Dockerfiles and every SDK container in `.gitea/workflows/build.yml`. CI must use the SDK matching the updated lockfile, or locked restore fails against stale SDK reference assets. Confirm the new tags and digests against Microsoft's .NET release notes and `docker buildx imagetools inspect`; keep the SDK major/minor aligned with `global.json`. For the November 2026 ASP.NET Core 10.0.15 security update, the `10.0-noble` tags must resolve to images containing runtime 10.0.15, which fixes CVE-2026-114146, CVE-2026-114147, and CVE-2026-114149. Do not suppress these findings or change the CI severity threshold.
The CI image scan is a merge gate. Do not publish or merge around a failed scan; inspect the report and correct the affected package, then rerun the complete workflow. Keep Gitea issue evidence split between disposable local acceptance and the actual CI publication run.
@@ -1,17 +0,0 @@
---
name: dashboard-refresh-lifecycle
description: Maintain the Heimdall Web dashboard's post-render agent refresh loop and component shutdown behavior.
---
# Dashboard refresh lifecycle
The dashboard starts its 15-second agent refresh only after the first interactive render. Keep the loop task and its `CancellationTokenSource` owned by the component. Capture the token once when starting the loop; do not read the mutable source inside the loop because disposal or a restart can replace it.
When the component is disposed, mark it disposed under the same synchronization used to start the loop, cancel the source, and let the loop finish before disposing that source. Handle a request cancellation as a normal shutdown, keep transient/401 load failures from escaping the renderer, and do not schedule `StateHasChanged` after disposal.
## Acceptance
- Exercise component disposal while a refresh is pending and confirm no renderer exception escapes.
- Exercise an agent request failure (including unauthorized) and confirm dashboard rendering remains stable and no periodic work survives component disposal.
- Run `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj`.
- For behavior changes, run the disposable Central + PostgreSQL Compose recipe from `skills/compose-disposable-recipe/SKILL.md`, then verify project resource and exact locally built image tag cleanup.
@@ -1,28 +0,0 @@
---
name: dashboard-welcome-punctuation
description: Keep Heimdall's localized dashboard greeting punctuation consistent across its route aliases.
---
# Dashboard welcome punctuation
`Dashboard.razor` serves both `/` and `/dashboard`. The `WelcomeUser` resource
owns the punctuation at the end of the localized greeting (French and English
currently both end in a comma); the Razor markup must add only a space before
the display name.
## Change and acceptance workflow
1. Inspect `Dashboard.razor` and the `WelcomeUser` values in
`SharedResources.fr.resx` and `SharedResources.en.resx` before changing the
greeting. Keep one punctuation owner instead of composing punctuation in
both places.
2. In `DashboardTests`, render the component with `UiLanguageService` set to
each supported language and assert the rendered greeting contains exactly
the expected localized punctuation and display name.
3. Since `/` and `/dashboard` are aliases on the same component, verify both
route templates remain declared on the component and exercise this same
rendering assertion for the shared output.
4. Run the focused web test project. For behavior changes, also run the
disposable Compose acceptance recipe from
`compose-disposable-recipe/SKILL.md`, using unique project resources and
removing only recipe-owned image tags during cleanup.
@@ -1,22 +0,0 @@
---
name: database-migration-startup
description: Diagnose and validate Heimdall Central's EF Core PostgreSQL migration startup, including first boot, restart, retry exhaustion, and recovery.
---
# Database migration startup
`src/Heimdall.Web/Program.cs` calls `Program.ApplyMigrationsAsync` before configuring recurring Hangfire jobs and seeding identity data. The method uses one `AppDbContext`, retries a failed `Database.MigrateAsync` five times with exponential delays, logs the terminal exception at Critical, then rethrows so Central cannot become ready with a failed migration.
For startup incidents, correlate the EF `CommandError` with the following `Program` retry/final logs. A failed EF command log alone does not prove that startup failed: a later retry may have succeeded. Preserve the provider exception and SQLSTATE when available, but never record a connection string, password, user identifier, or database row. Do not suppress EF command errors to hide a symptom.
## Acceptance
Run `bash skills/database-migration-startup/acceptance.sh` from a clean checkout. The recipe builds Central from this source with one unique local image tag, uses a fresh PostgreSQL database and generated credentials, and checks:
1. First boot applies migrations and `/healthz` becomes healthy.
2. A second startup against the migrated database remains healthy.
3. A synthetic database role with access to the database/schema but no `SELECT` on `public.__EFMigrationsHistory` causes migration startup to exhaust all five attempts, emit the final Critical failure, and exit nonzero without logging migration success.
4. Granting that role `SELECT` and restarting Central allows migration startup and health checks to succeed.
5. The EXIT trap removes only this Compose project and its exact image tag, then verifies that its containers, volumes, network, and image are absent. Shared PostgreSQL and .NET base images are retained.
This synthetic permission failure verifies fail-closed and recovery behavior; it does not establish the cause of a separate deployment's EF error. Record production evidence only when an event includes the provider exception/SQLSTATE and correlated startup outcome.
@@ -1,12 +0,0 @@
---
name: dependency-security-acceptance
description: Update vulnerable NuGet dependencies and prove Heimdall's locked dependency security gate.
---
# NuGet dependency security acceptance
Before changing a dependency after a CI advisory failure, read `AGENTS.md`, `skills/gitea-ticket-workflow/SKILL.md`, and the relevant component skill. Reuse or create a focused Gitea issue before editing; record the advisory IDs, resolved package version, failing CI run, and any behavior changes announced by the upstream fix. Do not suppress an advisory or weaken `scripts/ci/security.sh` thresholds.
Update the direct `PackageReference` to an upstream patched release, then regenerate every affected `packages.lock.json` using the SDK pinned by `global.json`. Inspect all projects that transitively reference the package, run `dotnet restore --locked-mode`, and run focused tests for the consuming application. Review upstream release notes for compatibility changes and add or adjust regression coverage if the changed behavior reaches Heimdall code.
Acceptance requires a clean locked restore, passing focused tests, and `scripts/ci/security.sh dependencies` reporting no applicable high or critical advisories. Keep the issue and linked PR open until those checks and the required CI run pass. Document the CI run and exact package version in Gitea without copying credentials or sensitive build output. No disposable Compose project is needed for a library-only dependency update that does not change deployment behavior; when the dependency changes runtime or deployment behavior, also follow `skills/compose-disposable-recipe/SKILL.md`.
@@ -1,37 +0,0 @@
---
name: deployment-guide-acceptance
description: Keep Heimdall's Docker installation and backup guides aligned with the actual Compose assets and validate source-built installation flows in a disposable project.
---
# Heimdall deployment guide acceptance
Read `AGENTS.md`, the linked Gitea issue, `docs/docker-compose.md`, and the relevant Compose and focused skills before changing deployment instructions. Follow [the Gitea ticket workflow](../gitea-ticket-workflow/SKILL.md) for status and acceptance evidence.
## Project-specific documentation checks
- Treat `docs/implementation.md` as a July 2026 historical MVP archive in its entirety. Do not use its old phase statuses, paths, commands, endpoint tables, or counts as current guidance; direct readers to the current focused docs and use Gitea issues for live status.
- When changing document structure, section numbering, or a product status summarized in `docs/specs.md`, verify the entry points in `docs/README.md`: every section/document reference must resolve, and summary wording must preserve optional, partial, and externally unvalidated states.
- Central production is PostgreSQL plus Heimdall Web. The development Compose builds Central from source; the interactive Linux/Windows installers create deployment files without cloning the repository.
- Production Agent Compose is generated in Central for the selected site and pins the image digest. The repository's Agent Compose files are development or optional hardware overlays only.
- Recording quota is configured through `RECORDING_STORAGE_QUOTA_MAX_BYTES`; absent an override, Central uses 1 TiB.
- The Central image installs Tesseract plus English language data. `PLATE_OCR_ENABLED` is mapped to `PlateOcr__Enabled` by the development and production Compose files and both Linux/Windows installer templates. New installs default it to false; upgrades preserve an existing value and add false if absent. If documented, explain that OCR is an operator-uploaded crop processed locally, not automatic video detection or face recognition; mention temporary crop deletion and that OCR candidates do not establish identity.
- Recording status must be traced across `AgentRecordingService` (primary RTSP stream, local MP4 segment spool, Central API upload), `RecordingsController`/Application storage, and the camera detail playback UI. Do not say recording is missing or that the Agent writes directly to S3; distinguish implemented code from real-camera/deployment validation.
- Live relay source tracking uses `AgentCameraConfig.EffectiveRtspUrl` (configured substream, otherwise primary RTSP). After a source change, `LiveCameraRelayService` stops and disposes the old FFmpeg process before starting the new source; do not retain the former renewal-delay caveat after issue #355.
- The current PWA baseline includes a manifest, bounded service worker, and static offline page. Web Push backend/client and offline business screens are not implemented; use `docs/pwa.md` for device and deployment validation status.
- The scheduled backup service installs AWS CLI, Bash, and GNU coreutils. The backup scripts select AWS CLI in this image and use S3-compatible configuration; do not instruct operators to download the retired MinIO `mc` URL.
- Optional Compose projects depend on the documented external core network and, where stated, the Central data volume. Do not describe an optional service as part of required startup.
## Disposable installation acceptance
1. Follow the local development installation commands in `docs/docker-compose.md` from the changed checkout. Create a unique project, isolated bridge, generated database/JWT credentials and unused loopback ports under a temporary directory. Do not copy production `.env`, use the default credentials unchanged, or use deployed volumes/networks.
2. Run Compose config validation, build Central from source, start PostgreSQL and Central, then verify PostgreSQL health, Central `/healthz`, bootstrap status, and the documented opt-in default for OCR.
3. When documentation covers OCR enablement, set `PLATE_OCR_ENABLED=true` in the generated temporary env and verify the option reaches the container, then exercise the synthetic crop path. Also verify false by default. Do not infer real camera accuracy.
4. Install an EXIT cleanup trap before build/start. Tear down only the named project with `down --volumes --remove-orphans`; verify zero project containers, volumes, and networks. Remove temporary environment and secret files even if build or assertions fail.
5. Record a unique tag for each locally built Central/helper image before build. After teardown, remove and verify absence of each exact tag. Keep shared upstream runtime/database images, preserve test exit status, report cleanup errors, and never use `--rmi all` or prune images broadly.
6. Keep Windows installer execution, production recovery, external S3 services, and real hardware acceptance open unless independently run on those targets.
When the Docker daemon is reserved by another acceptance, perform static source/config review and record the Compose run as pending. Never launch an overlapping project to satisfy this recipe.
## Latest local attempt
On 5 November 2026, Compose configuration and installer-source assertions passed, but the source build acceptance did not complete: BuildKit's docker-buildx client remained blocked for over eight minutes after its compiler child disappeared, with no project containers created. The command was interrupted; its cleanup trap confirmed zero project containers, volumes, and networks and removed the generated env. A follow-up Compose project hmd-ocr-env-safe-1793874420 reused the previously source-built Central OCR image (the current checkout rebuild was still blocked) to exercise the changed Compose wiring: default PlateOcr__Enabled=false and explicit true after recreate both reported healthy. Sentry__Dsn was explicitly empty. Cleanup verified zero containers, volumes, and networks. These are partial recipe results: the reused application image was not a uniquely built image for this recipe, and no exact-tag removal/absence check is recorded. Repeat the source build and probe with a fresh project tag before treating deployment-guide Compose acceptance as complete. An earlier attempt without the Sentry override emitted synthetic EF log events to the configured GlitchTip; no real credentials/data were used. The Compose environment mapping is verified; rebuilding this exact checkout and Windows installer execution remain unverified. pwsh was not installed, so the Windows installer was reviewed statically only.
-25
View File
@@ -1,25 +0,0 @@
---
name: detail-route-not-found
description: Keep Heimdall detail pages consistent when an API object no longer exists.
---
# Missing objects on detail routes
Use this workflow when a detail page already has an explicit “not found” state and an API read can return HTTP 404. Current routes covered are Agent (`AgentDetail.razor`), Camera (`CameraDetail.razor`), and Person (`PersonDetailPage.razor`).
## Implementation
- Keep the API client's normal `GetFromJsonAsync` behavior. A 404 raises `HttpRequestException` with `StatusCode == NotFound`. Agent and Camera resource-boundary checks intentionally return 403 for missing or out-of-scope records; treat that expected privacy response like the existing not-found rendering too. Person reads use 404.
- Preserve the generic error notification for unexpected failures. Do not treat 401, server, timeout, or malformed-response errors as “not found”.
- Do not fetch dependent page data after the primary object is absent. In particular, Camera must not load events, recordings, snapshots, or start periodic refresh, and Person must not load faces, vehicles, or events.
- Keep authorization and API responses unchanged. The UI behavior handles stale links and objects deleted between navigation and load.
## Acceptance
1. Add a component test for each route with a synthetic UUID and its expected hidden/missing response (Agent/Camera 403, Person 404).
2. Assert the existing not-found state is rendered, no snackbar is shown, and no dependent API call is made.
3. Retain or add an unexpected HTTP failure check proving the generic notification still appears.
4. Run the focused Web tests and Web build.
5. Run the disposable Compose recipe from `skills/compose-disposable-recipe/SKILL.md`; verify all three routes through the app boundary using isolated synthetic data and record exact project/image cleanup evidence.
The route-level checks require an authenticated synthetic account. Do not create or retain real people, cameras, Agents, or camera connection data for acceptance.
-29
View File
@@ -1,29 +0,0 @@
---
name: ef-core-persistence
description: Implement or review database persistence in Heimdall with Entity Framework Core, including SQLite Agent stores and PostgreSQL behavior.
---
# Heimdall EF Core persistence
Use this skill whenever changing how application or Agent data is read or written.
For work spanning multiple persistence concerns, use [parallel development with Orca](../parallel-development/SKILL.md). Keep each `DbContext` operation isolated; assign migration/model ownership clearly and serialize edits that touch the same entity configuration or migration chain.
- Use EF Core LINQ and entity configurations for CRUD. Prefer projections, bounded result sets, asynchronous APIs, and `CancellationToken`; use `AsNoTracking` for read-only entity queries.
- Create a short-lived `DbContext` per operation. Hosted services and concurrent workers should use `IDbContextFactory<TContext>` and dispose each context; never share a context across parallel work.
- Evolve schemas through reviewed EF Core migrations. Preserve deployed data and test upgrades from every supported on-disk schema, including Agent-local SQLite outboxes.
- Verify PostgreSQL translation, transaction boundaries, concurrency and deletion semantics against PostgreSQL integration tests when those behaviors matter. Do not use EF InMemory as proof of relational behavior.
- Do not issue CRUD through ADO.NET or hand-written SQL. Raw SQL through EF is an exception for database-specific capabilities that LINQ cannot express or for measured performance needs. Keep it parameterized, add an adjacent `EF Core exception:` comment with the reason, and add a test for its behavior.
- Migrations, test database setup, PostgreSQL maintenance/partition DDL, and locks with no portable EF equivalent are valid exceptions. Keep provider-specific code in Infrastructure or a dedicated adapter; do not spread it into use cases.
- When adding an approved raw EF operation, add its exact source path and a short capability rationale to `scripts/ci/check-efcore-usage.py`'s `EF_CORE_EXCEPTIONS` allowlist, keep an adjacent `EF Core exception:` comment, and cover the behavior with a relational test. The scanner intentionally ignores comments when locating a call; a comment alone does not allowlist a new production source.
- Never enable sensitive-data logging in production. Do not log connection strings or persisted secret values.
Before editing, inspect this repository's `AGENTS.md`, the linked Gitea issue, model configuration, latest migration, and callers. After editing, run the relevant suite and CI persistence policy check, then update the issue with evidence and remaining deployment checks.
## Microsoft references
- [EF Core efficient querying](https://learn.microsoft.com/en-us/ef/core/performance/efficient-querying)
- [EF Core tracking and no-tracking](https://learn.microsoft.com/en-us/ef/core/querying/tracking)
- [EF Core raw SQL queries](https://learn.microsoft.com/en-us/ef/core/querying/sql-queries)
- [EF Core migrations](https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/)
- [SQLite provider for EF Core](https://learn.microsoft.com/en-us/ef/core/providers/sqlite/)
-20
View File
@@ -1,20 +0,0 @@
---
name: first-admin-bootstrap
description: Implement or diagnose Heimdall's mandatory first administrator setup and restrict later account creation to admins.
---
# First administrator setup
For deployment bootstrap credentials, follow [Infisical secrets](../infisical-secrets/SKILL.md) and retrieve only the explicitly selected environment's required keys. Disposable acceptance must use generated accounts and passwords, never vault credentials.
Use this skill when changing account bootstrap, signup, login routing, user creation, or initial deployment guidance.
- The first account is created through a dedicated setup assistant that is reachable only while the database has no users. Do not seed a production password or print credentials to logs.
- Make first-admin creation one-time and race-safe at the server/API boundary. The UI hiding a link is not an authorization control.
- After bootstrap, disable anonymous registration regardless of old public-registration settings. Further accounts are created through authenticated, admin-authorized user-management endpoints only.
- Existing installations with users skip setup and keep their accounts. The bootstrap flow must not overwrite or replace existing users.
- Update FR/EN resources, route behavior, API client behavior, and tests together. Remove public registration links and ensure direct calls to the old registration route are rejected after setup.
- For every implementation change, follow `compose-disposable-recipe` and validate both an empty database (setup and first admin) and an initialized database (setup closed, anonymous registration rejected, admin account creation available).
- Record a unique tag for every source-built Central image and install an EXIT cleanup trap before build/start. Remove the project and verify zero containers/volumes/networks, then remove and verify absence of each exact local tag even after failure; retain shared PostgreSQL/.NET base images and report cleanup errors.
Never use credentials supplied for a real deployment in tests. Use generated credentials in the disposable Compose environment and sanitize logs.
-97
View File
@@ -1,97 +0,0 @@
---
name: gitea-ticket-workflow
description: Create, maintain, link, and close Heimdall project tickets in Gitea as the sole work tracking system.
---
# Gitea ticket workflow
For credentials used while investigating or validating tickets, follow [Infisical secrets](../infisical-secrets/SKILL.md). Never put secret values in issue descriptions or comments; use metadata-only existence checks when documenting prerequisites.
When a change is delivered through a PR, include its automatic release assessment using [pull request release assessment](../pr-release-versioning/SKILL.md); do not ask the user to choose whether or which version to release.
Gitea issues are the source of truth for planned work, acceptance evidence, operational follow-up, and completion. Do not use a repository markdown checklist as a parallel backlog.
For implementation work that has independent tasks, use [parallel development with Orca](../parallel-development/SKILL.md). Keep Gitea as the work-status source: create linked issues for independently deliverable outcomes, while Orca Runs/Tasks coordinate the execution and dependencies.
## Before implementation
1. Read `AGENTS.md` and the focused skill(s) for the affected area.
2. Identify the repository from `git remote get-url origin`; use the configured Gitea API/CLI credentials without printing them. Never put tokens in URLs, command output, issue text, or PR descriptions.
3. Search open and closed issues for the topic, identifiers, PRs, and acceptance gaps. Reuse the matching issue: reopen it when required work remains, or add a clearly scoped follow-up issue when the old issue is closed and represents a completed unit.
4. Create one issue per independently deliverable behavior or operational validation. An issue must include:
- a concise, outcome-oriented title and relevant component/priority labels;
- a plain-language summary explaining the user/operator impact and why the work matters;
- a short current-state section separating implemented behavior, local evidence, CI evidence, and real deployment/hardware evidence;
- an analysis of the actual gap: what fails or is missing, what evidence proves it, likely causes where known, and what remains uncertain;
- scope and explicit out-of-scope items, dependencies, risks, assumptions, and the expected owner/environment for external checks;
- numbered implementation/validation steps in dependency order, including safe test data, observable outcomes, and cleanup;
- independently checkable acceptance criteria, with no generic placeholder criteria;
- relevant files, prior issue/PR/run links, and the focused skill.
5. Apply the ticket labels described in **Ticket labels** below before handing the issue to implementation. Labels are metadata for filtering and triage; they do not replace the title, scope, or acceptance criteria.
6. For UI/product work, decide whether a mockup materially clarifies the acceptance criteria. If needed, attach a mockup or link to a Penpot/Figma artifact; state the viewport, states, responsive breakpoints, and interactions it must cover. Do not block infrastructure work on an unnecessary mockup.
7. Confirm the created/updated issue through the API and record its canonical URL/number in the branch/PR context.
## Ticket labels
Every issue should have, at minimum, one **type** label, one **priority** label, and one **domain** label. Add a **validation** label when the ticket is mainly about an acceptance/deployment check. Apply existing repository labels through the Gitea issue API or UI; if a required label is missing, create it once with a clear description and reuse it rather than inventing synonyms.
Use this vocabulary consistently:
| Group | Labels | Use |
|---|---|---|
| Type | `type:feature`, `type:bug`, `type:maintenance`, `type:docs`, `type:security` | Main nature of the work; select one. |
| Priority | `priority:P0`, `priority:P1`, `priority:P2`, `priority:P3` | `P0` blocks release/security or causes an active outage; `P1` is important for the current release or core journey; `P2` is normal planned work; `P3` is low urgency. Select one and state why in the issue if not obvious. |
| Domain | `area:ci`, `area:release`, `area:install`, `area:agent`, `area:camera`, `area:analysis`, `area:storage`, `area:notifications`, `area:auth`, `area:ui`, `area:monitoring`, `area:docs` | Main owning subsystem; use multiple only when work genuinely crosses boundaries. |
| Validation | `validation:field`, `validation:deployment`, `validation:hardware`, `validation:backup-restore` | Add when closure depends on the corresponding real environment or external evidence. Do not apply to ordinary code-only acceptance. |
| State marker | `blocked`, `needs-design`, `needs-decision` | Add only while the named condition is true; remove it when resolved. Explain the blocker/decision in the issue body. |
Before creating a label, search all repository labels and use an existing equivalent. Keep labels lowercase except the conventional priority spelling above. Do not create status labels such as `open`, `closed`, `in progress`, or `done`; Gitea issue state and assignee/project workflow own those concepts. Do not use labels to encode dynamic details such as a PR number, release version, user, camera, or site.
On backlog review, correct missing or stale labels when the scope changes. When splitting an issue, label each child for its own type, priority, domain, and validation requirement; do not blindly copy every parent label. A label change alone does not satisfy acceptance criteria or close the ticket.
## During implementation
- Keep the issue current with material discoveries, decisions, blockers, and validation evidence. Do not duplicate long-lived status in a local markdown backlog.
- Reference the issue in branch and commit context where useful. Every PR body must link the issue with `Closes #N` when merge should close it, or `Refs #N` when the issue tracks work that remains after this PR.
- A PR touching a subset of a larger ticket must say exactly which acceptance criteria it satisfies and which remain open. Split follow-up tickets when the remaining work is independently actionable.
- Keep project-specific implementation and acceptance procedures in `skills/`; link the relevant skill from the issue and PR.
- For external validation, create/update a focused ticket with owner, prerequisites, safe test data, procedure, expected evidence, and cleanup. Never mark an external integration validated based on mocks or configuration presence.
## Mockups and attachments
- Attach a mockup when layout, hierarchy, responsive behavior, or interaction flow is a substantial part of acceptance. Prefer an existing project design artifact; otherwise create a focused Penpot/Figma frame and attach/link it from the issue.
- The issue describes what the mockup demonstrates and its status (proposed/approved/superseded). Keep source design links and exported images free of secrets or real customer data.
- API, persistence, CI, and maintenance tickets generally need no mockup; state that only when ambiguity might otherwise cause delay.
## Human-readable issue layout
Use this order and keep each section focused:
1. **Résumé** — one or two sentences describing the intended result.
2. **Pourquoi** — user/operator impact and the reason for prioritizing the work.
3. **État actuel et preuves** — what is already implemented and exactly what tests/runs prove; distinguish synthetic/local/CI/production evidence.
4. **Écart à résoudre** — the remaining failure or uncertainty in concrete terms; avoid starting with a fragment copied from a longer checklist sentence.
5. **Analyse** — known cause, constraints, failure modes, security/data impact, assumptions, and unanswered decisions.
6. **Plan de travail** — ordered steps with dependencies and observable outputs. Split independent work into linked child issues instead of making one ticket cover unrelated deliverables.
7. **Critères d’acceptation** — concise checkboxes with measurable outcomes and evidence required.
8. **Hors périmètre / dépendances** — identify related capabilities that must not be mistaken as delivered, required owners/access/hardware, and blockers.
9. **Maquette** — attach/link only where UI design materially affects acceptance; otherwise say `Aucune maquette requise : ...` with a short reason.
10. **Liens** — PRs, runs, skills, related issues and design artifacts.
Render long historical logs as a clearly separated `<details><summary>Historique détaillé</summary>` appendix. Lead with the latest state and the exact open work; do not make readers infer the task from a 1,000-word pasted paragraph. Use short paragraphs, bullets, and headings; expand acronyms on first use when the audience may not know them.
## Pull requests and closure
- Before opening/updating a PR, verify the issue number, link, acceptance criteria, focused skill, and test/acceptance evidence are present.
- Keep `.gitea/PULL_REQUEST_TEMPLATE.md` aligned with this workflow: request the linked Gitea issue and observed CI/acceptance evidence; never direct contributors to update a markdown backlog.
- Use `Closes #N` only when the PR completes every criterion owned by that issue. For partial work use `Refs #N` and leave the issue open with unchecked criteria and evidence updated.
- Gitea closes a `Closes #N` issue when the PR merges. After merge, verify the issue state changed; if not, close it manually only after checking all criteria and posting the merge/CI/acceptance evidence.
- Do not close tickets merely because code was merged when required acceptance (including the disposable Compose recipe, CI gate, external deployment, camera, storage, or release run) remains outstanding. Create a separate validation issue if code delivery and external validation have different owners or timelines.
- On completion, leave a concise final issue comment linking merged PR/commit, successful checks and acceptance record, plus explicit limits. Keep the ticket searchable; don't erase the completion trace.
## Backlog maintenance
- Review open issues before planning work; deduplicate, label, prioritize, split oversized work, and refresh stale acceptance criteria.
- For discovered follow-up work during a PR, create/link a ticket before treating it as deferred. Avoid checklist fragments in commits, skills, or docs that become a second backlog.
- Repository skills contain durable workflows, not per-task status. Update the relevant skill in the same PR when implementation or acceptance procedure changes.
- When migrating a legacy backlog, carry each actionable incomplete item to an open issue; carry completed entries to closed issue history or a closed migration/traceability issue with original PR/run references. Verify issue counts, titles, states, and links before deleting the file.
-35
View File
@@ -1,35 +0,0 @@
---
name: heimdall-gpu-inference
description: Build and verify Agent ONNX Runtime provider selection, CPU fallback, and GPU package variants in Heimdall.
---
# Heimdall Agent ONNX inference
Use this skill when changing ONNX Runtime packages, execution provider configuration, Agent inference startup, or GPU deployment support.
## Project-specific workflow
- The default Agent build and published `docker/Dockerfile.agent` remain CPU-only. Do not add NVIDIA runtime/device requirements to the default Agent Compose files. CUDA support is opt-in through `docker/Dockerfile.agent.gpu`, `docker/docker-compose.agent.dev.gpu-nvidia.yml`, and a separately signed release image manifest.
- Keep the GPU summary in `docs/README.md` aligned with `docs/gpu-runtime.md`: the default Agent remains CPU-only, an optional signed NVIDIA/CUDA amd64 image is published, and physical CUDA execution remains unvalidated until exercised on compatible hardware. Do not collapse these states into “published inference is CPU-only” or imply hardware validation from package/image publication.
- Keep technical-spec summaries consistent with `AgentOptions`, `AnalysisMode`, ONNX provider selection, and `docs/gpu-runtime.md`: distinguish CPU-default inference and optional NVIDIA/CUDA inference from GPU inventory and FFmpeg media handling. AMD/Intel device visibility or detected NVENC/QSV/VAAPI capability is not evidence that ONNX inference or a media pipeline uses those accelerators. Treat remote broker mode as configurable behavior, not a validated inter-site deployment; do not publish throughput estimates without reproducible measurements and hardware/method details.
- Configure provider choice through `Agent:InferenceExecutionProvider` (environment variable `Agent__InferenceExecutionProvider`). `CPU` is the default. `CUDA` is optional and valid only in a runtime containing the official ONNX Runtime GPU package plus compatible CUDA/cuDNN native libraries and host driver access.
- Keep the CPU and GPU NuGet dependency graphs in their separate lock files. Restore each variant explicitly and in locked mode after changing dependencies:
```sh
dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj --locked-mode
dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj -p:HeimdallOnnxRuntime=GPU --locked-mode
```
- The Agent checks for detected NVIDIA hardware before enumerating ONNX providers or creating a session; some ONNX Runtime GPU builds can fault during native provider discovery when no driver device is attached, before managed fallback handling is possible. It reports the provider configured on the resulting session. If CUDA is requested but unavailable or session construction fails, log the reason without sensitive payloads and construct a CPU session. Keep provider selection isolated behind `OnnxExecutionProviderSelection` so the fallback can be tested without hardware.
- Add tests for CPU-only selection, successful CUDA selection, missing CUDA provider, and CUDA session initialization failure. Also exercise the repository YOLO fixture with the CPU provider so package changes preserve real inference.
- Test the default Agent test suite and the GPU package variant where the local machine permits. GPU package tests may need a larger non-`/tmp` output directory because ONNX GPU and image-processing NuGet packages ship native assets for multiple operating systems. The real-model test searches upward from the test output for `models/yolov8n.onnx`; keep output under the repository or place the fixture alongside the test output.
- Any runtime/image or Compose behavior change requires the disposable Compose recipe in `skills/compose-disposable-recipe/SKILL.md`. Keep hardware-only validation open unless NVIDIA, AMD, or Intel hardware is actually exercised. A successful CPU fallback test does not prove GPU execution.
- Record unique tags for the locally built CUDA Agent and any Central/helper fixture image before building. Install an EXIT trap before the build/start; after stopping the project, remove each exact local tag independently and verify it is absent, including after failed builds/assertions. Preserve the test exit status and report cleanup errors. Retain shared CUDA/runtime base layers; never use `--rmi all` or `docker image prune`.
- The current pinned GPU image pairs ONNX Runtime 1.22 with NVIDIA CUDA 12.8.1/cuDNN 9.8.0.87 on amd64. The CUDA runtime base is pinned by the architecture-specific manifest digest in `docker/Dockerfile.agent.gpu`; the dev overlay targets `linux/amd64` and the Dockerfile uses that target rather than a constant `FROM --platform` override. Refresh the digest only after checking the ONNX Runtime compatibility table and obtaining the matching NVIDIA registry digest.
## Current limitation
The optional GPU image, signed manifest publication, installer selection, and Docker auto-update variant are implemented. On 5 November 2026, the post-fix GPU image built from this source with locked GPU restore. Rendered Compose confirmed CPU has no NVIDIA device requirement and the opt-in overlay selects the GPU image. A local disposable runtime check launched the GPU image without NVIDIA devices on an isolated network and tmpfs state: logs confirmed no GPU detection, fallback to `CPUExecutionProvider`, and YOLO model initialization; a synthetic HTTP Central mock accepted registration and heartbeat (200/204), and `/healthz` returned 200. The repository `RealOnnx_CpuModel_ProcessesFullHdImage` test passed 1/1 with `HeimdallOnnxRuntime=GPU`. The mock did not implement configuration/jobs, so no camera frame traversed the Agent/Central loop; a synthetic frame and persisted inference observation remain open. The exact acceptance image tag and container were removed and verified absent; tmpfs, mock listener, and temporary state were gone. The earlier disposable Central/PostgreSQL bootstrap also passed. Physical CUDA execution still requires NVIDIA hardware.
Additional full-loop acceptance attempt, 5 November 2026: disposable Compose project `hmgpu-loop-929b670e` rendered with CUDA package selection, no NVIDIA reservation, and empty Sentry DSN. Central and the Agent GPU image were built from this checkout under `heimdall:hmgpu-loop-929b670e-central` and `heimdall-agent:hmgpu-loop-929b670e-gpu` (GPU image inspected at 3.56 GB). The Compose/Buildx client remained waiting after image export and before any service/container was created, so no Central bootstrap, Agent health, camera configuration, job, frame processing, or database observation was exercised. After stopping only that build handle, cleanup verified 0 containers/0 volumes/0 networks, both exact image tags absent, and the temporary directory absent. `docker buildx ls` and `docker ps` responded afterward; this does not establish successful runtime acceptance. Keep the frame-through-job-loop evidence open. An earlier duplicate-target attempt (`hmgpu-loop-e9377c0b`) was also cleaned with 0/0/0 and both exact image tags absent.
-38
View File
@@ -1,38 +0,0 @@
---
name: group-access
description: Implement and accept Heimdall group membership and camera grants through the Admin UI and protected API.
---
# Group membership and camera access
The Admin group editor is `src/Heimdall.Web/Components/Pages/Admin/GroupsPage.razor`.
Its API adapter is `HeimdallApiClient`; route templates must match
`GroupsController`. Member listing is `GET /api/groups/{groupId}/users`, add is
`POST /api/groups/{groupId}/users/{userId}`, and removal is
`DELETE /api/groups/{groupId}/users/{userId}`. Camera grants use the sibling
`/cameras` endpoints. Keep member selection name/email based in the UI; do not
ask administrators to copy opaque user IDs.
Authorization is additive: effective camera access is the union of active
site-wide, direct, legacy, and live group grants, subject to role permissions
and deleted-resource checks. Removing one grant must preserve another valid
grant. Soft-deleted groups must stop granting access immediately.
## Acceptance
1. Run focused Web tests for `GroupsPageTests`, `HeimdallApiClientTests`, and
`ResourceAccessTests`. Assert API HTTP method/path, UI member identity and
camera/site labels, and add/remove behavior.
2. Build the source in a uniquely named disposable Compose project with
generated PostgreSQL/JWT credentials, loopback port, named volumes, and a
project-specific network. Bootstrap the first Admin through the setup API;
create a group, add a member using the production route, read the member
list, remove the member, and verify the empty list. Use only synthetic data.
3. Install an EXIT cleanup trap before build/start. Tear down that exact project
with volumes and orphans, verify there are no project containers, volumes,
or networks, remove exact local image tags and verify they are absent, and
delete generated secret files even if an assertion fails.
4. Record each project-unique local image tag before build. Retain shared
upstream PostgreSQL/.NET runtime images; never use `--rmi all` or prune.
5. Update the linked Gitea issue with the exact evidence and keep physical/deployment-only
claims separate from local acceptance.
-25
View File
@@ -1,25 +0,0 @@
---
name: hangfire-startup-lock
description: Diagnose and recover Heimdall startup from transient Hangfire PostgreSQL recurring-job lock contention.
---
# Hangfire startup lock recovery
Heimdall registers all recurring jobs synchronously after database migrations in `src/Heimdall.Web/Program.cs`. Hangfire's PostgreSQL storage acquires a distributed lock per recurring-job id during `AddOrUpdate`; `agent-failover` is currently the first registration after removing the legacy `heartbeat-monitor` id.
The Central dashboard route is mapped from the same Program.cs with `MapHangfireDashboard("/hangfire", ...)`, guarded by `HangfireAdminAuthorizationFilter` for `Admin.Jobs` or the Admin role, and omitted in `Testing`. When updating `docs/hangfire-usage.md`, verify the route and filter against these sources; do not copy a stale `UseHangfireDashboard` or `/admin/jobs` example.
## Implementation and diagnosis
- Inspect the GlitchTip event stack, app start time, event timestamps, and `Program.cs`/`JobSetup.cs` line references. A timeout names the contended job key; it proves lock contention, not the number or identity of competing processes.
- Because registration is on the startup path, an unhandled provider lock timeout terminates startup even when caused by another instance. Retry only `Hangfire.PostgreSql.PostgreSqlDistributedLockException`; do not retry arbitrary registration/configuration failures.
- Retry the complete idempotent `ConfigureRecurringJobs` sequence with a new DI scope per attempt. Keep delay bounded, observe application shutdown cancellation, log attempts without connection details, and propagate the final exception so missing recurring schedules are not reported as successful startup.
- Cover transient recovery with a focused test that injects the provider exception and verifies a subsequent full registration attempt.
## Acceptance
1. Run `dotnet test tests/Heimdall.Api.Tests/Heimdall.Api.Tests.csproj --no-restore --filter FullyQualifiedName~RecurringJobStartupRetryTests` and build the Web project using the SDK pinned in `global.json`.
2. Run a disposable Compose project from the changed source with unique project name, generated credentials, loopback port, volume names, and a unique Heimdall image tag. Confirm the Web service becomes healthy and recurring Hangfire jobs are available in the isolated PostgreSQL storage.
3. Use an EXIT trap to tear down only that Compose project, verify its containers, volumes, and networks are absent, remove and verify absence of its exact locally built image tag, and remove temporary files. Preserve the original status and report cleanup failures.
The Compose check demonstrates isolated startup and Hangfire storage integration; the synthetic unit test demonstrates contention recovery. Neither establishes that a particular production deployment had one or multiple replicas. Record deployed telemetry separately in Gitea issue #214.
-27
View File
@@ -1,27 +0,0 @@
---
name: heartbeat-failover
description: Validate that stale Agents are marked offline and assigned cameras move safely to online peers.
---
# Heimdall heartbeat and Agent failover
Read `AGENTS.md`, the Heartbeat/failover Gitea issue, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing this path.
## Behavior contract
- Use the configured global heartbeat interval or per-Agent override, bounded to 5–300 seconds. A stale Agent is not eligible for new work.
- The failover sweep owns the stale-to-Offline transition and camera reassignment. Do not add a competing heartbeat monitor that races this transition.
- Preserve camera assignment history: close the old row and create a new active row for an online Agent in the same site. If there is no replacement, clear the active assignment and let periodic reconciliation retry when an Agent recovers.
- Use short-lived EF Core contexts and test status, camera ownership, and assignment history against PostgreSQL.
## Required validation
1. Run the PostgreSQL tests in `HeartbeatMonitorJobTests`, `AgentFailoverJobTests`, and `CameraAssignmentServiceTests`.
2. Run the integration scenario with two registered Agents: heartbeat both, assign a camera to the source, age only the source heartbeat past the maximum accepted timeout, execute the real `AgentFailoverJob` and `CameraAssignmentService`, then verify the source is Offline, the online peer owns the camera, and both assignment records retain the correct released/active state.
3. Before any build/start, install an EXIT cleanup trap. Build Central from the changed source in a unique disposable Compose project. Generate database/JWT credentials, use unique loopback ports, network, volumes and image tag, empty Sentry DSN, bootstrap a synthetic admin/site and two synthetic Agents, and assign a synthetic camera. Age the source heartbeat only in the disposable PostgreSQL fixture and let the real Hangfire recurring failover job run; verify the active assignment and historical rows through API/PostgreSQL.
4. The trap tears down that project with volumes/orphans, verifies zero project containers, volumes and networks, then removes and verifies absence of the exact source-built Central image tag even on failure. Keep upstream Postgres/.NET base images, preserve test exit status, report cleanup failures, and never use `--rmi all` or broad image pruning.
5. Mark physical Agent loss, network partitions and multi-host timing as unverified unless exercised against deployed Agents.
## Current local evidence
5 November 2026: new relational integration scenario passed 1/1. Disposable source-built project `hmd-failover-1793882220-a9bc9c` registered two Agents, assigned the synthetic camera to the first, aged its heartbeat to 900 seconds, and observed the real Hangfire failover mark it Offline and move the camera to the still-online peer. PostgreSQL confirmed the previous assignment was released and the replacement assignment active. Teardown left zero containers/volumes/networks and removed/verified absence of the exact Central image tag. This proves the local scheduled path and relational state, not a real network partition or deployed multi-host timing.
-20
View File
@@ -1,20 +0,0 @@
---
name: heimdall-dotnet
description: Implement or review Heimdall .NET 10 application, EF Core persistence, and agent changes while preserving its clean architecture and audit backlog.
---
# Heimdall .NET work
Read `AGENTS.md`, the relevant Gitea issue, and [the Gitea ticket workflow](../gitea-ticket-workflow/SKILL.md) first. Trace a feature through `Domain` → `Application` → `Infrastructure` → `Web` or `Agent` before editing; update only the layers that own the behavior.
For multi-layer work, use [parallel development with Orca](../parallel-development/SKILL.md) to dispatch non-overlapping layer tasks early, sequence shared contract decisions, and integrate the result before running combined verification.
For persistence changes, inspect the entity configuration and latest migration, then verify PostgreSQL translation and transactions with focused integration tests. Keep migrations compatible with existing rows, record the data backfill or rollback requirement, and avoid client-side filtering on access-controlled queries.
For detailed database access rules and the allowlist for unavoidable provider-specific SQL, follow [the EF Core persistence skill](../ef-core-persistence/SKILL.md).
When updating the domain model summary in `docs/specs.md`, verify entity and property names against `Domain/Entities` and `Domain/Enums`. The site registration token is persisted only as `RegistrationTokenHash` plus its expiry; never describe a stored plaintext token. Distinguish the `CameraEvent` type from conceptual event wording, and `Person` from its related `KnownFace` embeddings.
For application commands, validate at the boundary, enforce site/camera scope in the use case, and make external side effects retry-safe. For agent work, account for disconnected operation, bounded queues, cancellation, and resource disposal.
After the change, run the smallest meaningful test suite plus the build when public contracts change. Update the issue with what passed and what still requires a deployed runner, camera, network, or object store. Link it from the PR and close it only when all acceptance criteria are verified.
-42
View File
@@ -1,42 +0,0 @@
---
name: heimdall-identity
description: Implement and review Heimdall account, password, session, email confirmation, lockout, and two-factor authentication flows built on ASP.NET Core Identity.
---
# Heimdall Identity workflow
Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../gitea-ticket-workflow/SKILL.md), and the Identity wiring in `Infrastructure/DependencyInjection.cs` and `Web/Program.cs` before changing authentication.
When maintaining `docs/auth-roles.md` or identity summaries in `docs/specs.md`, verify their role names and default permission summaries against `Infrastructure/Security/AppPermissions.cs` and `Domain/Enums/UserRole.cs`. Heimdall has `Admin`, `Supervisor`, and `Viewer`; site/camera access is separately enforced through resource-access services, not represented by a generic `User` role. Keep the authentication summary in `docs/README.md` aligned with that guide and model.
Verify identity model examples against `Infrastructure/Identity/IdentityAppUser.cs`, `Domain/Entities/UserSite.cs`, and `Infrastructure/Data/Configurations/UserSiteConfiguration.cs`. Keep ASP.NET Identity in Infrastructure; `UserSite` stores the user ID without an Identity navigation, and Infrastructure maps that foreign key.
Before documenting UI/API authorization examples in `docs/auth-roles.md`, verify referenced pages, methods, policies, and routes against `Components/Routes.razor`, the page components, controllers, and `ResourceAccess`. Do not preserve generic authorization snippets that reference services or callbacks absent from the application; distinguish page authentication from API resource filtering.
- Identity owns password hashing, normalized account lookup, role membership, lockout, authenticator tokens, and email/password tokens. Do not duplicate password or token cryptography in Heimdall.
- Keep ASP.NET Core Identity packages and types inside Infrastructure. Domain must not reference Identity; Application uses `IIdentityAccountService` and `IdentityAccount` only. Put Identity EF entities (`IdentityAppUser`, `IdentityAppRole`) and `UserManager`/`RoleManager` adapters in Infrastructure. Keep user-related Domain relationships keyed by `Guid UserId`; configure their foreign keys to the Infrastructure user entity.
- When creating an Identity user, copy the generated `SecurityStamp` back into the application account before building the first session/JWT. Cover bootstrap and regular user creation with a relational session validation test.
- Moving Identity model classes without changing tables should produce an explicit empty EF migration and a snapshot containing the Infrastructure entity types. Verify migration compatibility against PostgreSQL before release.
- Keep bootstrap one-time and PostgreSQL-serializable. Anonymous registration stays disabled after bootstrap; role and account creation failures must not be reported as success.
- Keep public login/reset responses generic so they do not reveal account existence, lockout state, or Identity policy details. Logs must not contain emails, passwords, tokens, authenticator keys, recovery codes, or Identity error descriptions; log safe error codes only when needed.
- Rotate `SecurityStamp` after password changes/resets, email or role changes, lock/unlock, and 2FA changes. Verify existing cookies, JWTs, and refresh tokens are rejected after the change.
- Cookie principal validation runs on every authenticated HTTP request. Keep it asynchronous and use `AccountSessionPolicy.IsValidLiveAsync` with `IIdentityAccountService.GetSessionRecordAsync` plus an `IApplicationDbContext` projection; this bypasses Identity's tracked-user cache and avoids repeated `UserManager` database round trips while preserving fresh security-stamp, lockout, and email-confirmation checks. Do not replace it with claims-only validation.
- The Blazor cookie bridge runs through `heimdallAuth.signIn` → `POST /_auth/signin`. Have JavaScript return only the HTTP status code (or `0` for a network failure); classify `JSDisconnectedException` separately from non-2xx responses. Log only the failure stage, HTTP status, or exception type—never exception messages, emails, user IDs, access tokens, cookies, or request bodies. Return generic public errors from the endpoint. Integration coverage should verify a successful 2FA response can create a usable cookie and that malformed tokens reveal no validation details.
- For cookie failures reported after 2FA, inspect only sanitized event breadcrumbs around the JS bridge; distinguish a circuit/WebSocket disconnect from a `/_auth/signin` HTTP rejection, and do not infer cookie serialization failure when the event has no exception. Keep a Playwright E2E path that submits an authenticator code through `/login`, observes the real HttpOnly auth cookie, and proves that cookie authorizes `/api/users/me`; remove the temporary Identity account in `finally`.
- Enroll an authenticator in two steps: create/show the setup key while 2FA remains disabled; renew the user's access token and cookie after Identity rotates the security stamp; verify a TOTP code before enabling 2FA and creating one-time recovery codes. Persist only hashes of recovery codes, redeem each atomically once, and clear them when 2FA is disabled.
- Check every `IdentityResult` before proceeding. Avoid partial account creation; clean up the created user if role assignment fails.
- Keep first-account provisioning on `/setup` → `/api/auth/bootstrap-admin`; later accounts and role assignment use `/users` → `/api/users`. Do not reintroduce a second Admin-registration endpoint.
- Keep the three supported role names seeded by Identity. Seed their default permission claims once using a durable role-claim marker; the Admin permission set stays immutable. Manage Supervisor/Viewer permission claims from `/admin/claims`, then include those persisted claims in login, refresh, cookie, and 2FA auth responses.
- When role membership or role permissions change, rotate every affected user's security stamp and record the acting administrator in the audit log. Protect last-admin demotion, deletion, and lockout based on unlocked Admin accounts.
- Apply `[Collection("E2E")]` on each concrete Playwright test class deriving from `E2ETestBase`; xUnit does not reliably inherit the PostgreSQL fixture attribute from its abstract base.
- Configure Identity options explicitly and review changes to password, unique email, confirmed email, lockout, cookie, token-provider, and Data Protection behavior.
- CI installs Chromium through the Playwright CLI already copied beside the Release E2E test assembly (`node tests/Heimdall.E2E.Tests/bin/Release/net10.0/.playwright/package/cli.js install --with-deps chromium`). This keeps browser tooling on the test project's locked Playwright dependency graph and avoids an independently restored C# script project.
- Keep PostgreSQL-specific transaction and concurrency guarantees in Infrastructure. Use relational integration tests for bootstrap races, recovery-code redemption, session revocation, and migration compatibility.
- For cookie session validation changes, prove a freshly issued cookie succeeds before account mutation and fails afterward for lockout, role/security-stamp, email, and password changes. Treat GlitchTip blocking warnings as hypotheses: inspect the full async stack and do not claim a synchronous block solely from the warning title.
- For behavior changes, update FR/EN resources and UI/API contracts, add focused tests, update the Gitea issue, and run the disposable Compose acceptance recipe with unique credentials, ports, volumes, project name, and network.
- Acceptance must exercise bootstrap through the setup UI, user lifecycle and role editing through `/users`, permission editing through `/admin/claims`, and verify the resulting JWT/API allow and deny decisions. Check that stale sessions fail after a role/permission change and that the last usable Admin cannot be demoted, deleted, or locked.
- For account-creation password regressions, cover the real `/users` dialog for Viewer and Supervisor with the role selected both before and after password entry. Confirm the new account's email through the admin row action, then authenticate through `/api/auth/login` using the exact synthetic password entered in the form; assert only the status/token presence and never log the password. Keep this as a Playwright E2E test under the `E2E` collection.
- The disposable Compose recipe defaults to the account-creation path; `HEIMDALL_ACCEPTANCE_FLOW=2fa-cookie` runs the complete authenticator challenge → `/_auth/signin` → cookie-authorized `/api/users/me` path. Each invocation uses a unique project, generated PostgreSQL/JWT credentials, a free loopback port, and a project-specific Central image tag. Build from the checkout and wait for `/healthz`; the separate Playwright E2E test covers the real browser UI bridge. Teardown only that Compose project and verify its containers, volumes, and network are gone; remove and verify absence of the exact Central tag while retaining PostgreSQL and other shared base images.
- Record a project-unique tag for each source-built Central acceptance image and install an EXIT cleanup trap before build/start. After scoped Compose teardown, verify zero containers/volumes/networks and remove/verify absence of each exact local tag even on failure. Keep shared upstream base images, preserve test exit status, report cleanup failures, and avoid `--rmi all` or broad image-prune commands.
Useful official references: [ASP.NET Core Identity configuration](https://learn.microsoft.com/aspnet/core/security/authentication/identity-configuration), [Two-factor authentication](https://learn.microsoft.com/aspnet/core/security/authentication/identity-enable-qrcodes), and [Data Protection](https://learn.microsoft.com/aspnet/core/security/data-protection/introduction).
-30
View File
@@ -1,30 +0,0 @@
---
name: infisical-secrets
description: Retrieve and maintain Heimdall project credentials in the connected Infisical instance while keeping secret values out of repository files, transcripts, and logs.
---
# Heimdall secrets in Infisical
Use this workflow whenever a Heimdall skill needs a real credential, and link this skill from any skill that adds or changes a credential workflow. The connected MCP server is the supported interface to Infisical.
## Vault and scope
- Select project **Orca** (`orca-cc2-m`) explicitly; its project ID is `96fb3628-2ee3-45b5-b6a8-66a0212a5b46`. Use `dev`, `staging`, or `prod` only when the task names that environment. Never silently fall back from one environment to another.
- Use the MCP tools `list-projects`, `list-secrets`, `get-secret`, and `create-secret`. They are allowlisted in the local MCP configuration. Never use `create-secret` as an implicit overwrite operation: check the key first and explain/ask before replacing an existing value.
- `list-secrets` returns secret values as well as names. Treat its full response as sensitive even when only checking availability. Do not print, quote, summarize, or copy values into tool output, chat, shell history, command arguments, files in the repository, issue/PR text, or logs.
- Prefer retrieving only the needed key with `get-secret`. Pass the value directly to the one process that needs it using a protected stdin/temporary file outside the repository with mode `0600`, then remove that exact file. Never interpolate it into a command string or a checked-in Compose file.
- Use metadata-only checks to report which keys exist. Never test access by dumping a value. If a diagnostic accidentally emits a value, stop, do not repeat it, and tell the user that the credential should be rotated. Do not rotate it unless the user explicitly asks.
## Using secrets in skill workflows
- Distinguish real deployment credentials from disposable acceptance credentials. Compose acceptance recipes must generate unique synthetic credentials and must not fetch production or staging values from Infisical.
- For local manual integration work, fetch only the named development key needed by that skill. For a deployment task, use the explicitly requested environment and target. Never place fetched values in `.env.example`, tracked configuration, source, fixtures, or documentation.
- CI secrets remain in the CI secret store unless a task explicitly migrates the CI workflow. Infisical presence alone does not configure Gitea Actions or prove a runner can access the vault.
- When a workflow needs a credential not present in the selected environment, report its exact key name and purpose; do not substitute a similarly named credential or a different environment.
- When asked to persist a newly provided credential, use `create-secret` in the selected project/environment/path. First verify the key is absent, then create it, then verify presence by listing metadata only. Do not echo the supplied value.
## Current inventory verified 2026-11-10
The `dev` root currently contains `GITEA_ORCA_TOKEN`, `HEIMDALL_LOGIN`, `HEIMDALL_PASSWORD`, `HEIMDALL_PRIVATE_KEY_B64`, `HEIMDALL_URL`, `PENPOT_LOGIN`, `PENPOT_PASSWORD`, and `PENPOT_URL`. The `staging` and `prod` roots were empty at verification time. Treat this inventory as a dated snapshot; check metadata again before relying on it.
The development inventory does not include Heimdall deployment/database/JWT, RustFS, Agent site-token, Coturn, Redis, Sentry, Docker Hub, or release-signing credentials. Some are generated for disposable acceptance, some are optional, and CI publication credentials belong in Gitea Actions. Do not add real values simply to make the inventory look complete; report only keys required by the active task.
@@ -1,23 +0,0 @@
---
name: installer-checksum-acceptance
description: Build and verify the versioned Central installer checksum asset and both server bootstrap verification paths.
---
# Central installer checksum acceptance
Use this workflow when changing `install/install-server.sh`, `install/install-server.ps1`, `scripts/ci/package.sh`, or the release asset set in `scripts/ci/release-gitea.py`.
## Release contract
- `package.sh` creates `heimdall-installers-<version>.zip.sha256` beside the ZIP. Its single standard `sha256sum` line names the ZIP asset exactly, with no workspace-relative path.
- `release-gitea.py` requires and publishes both files before making a release visible. The sidecar is part of the exact expected asset set for already-published releases.
- The raw Linux and Windows bootstraps prefer a valid `sha256:<64 hex>` digest from the matching release API asset. If the digest is absent or null, they find the correspondingly named checksum asset, require an HTTPS download URL and exactly one checksum line naming the ZIP, download the ZIP, and compare its SHA-256 before extraction or execution.
- A malformed, non-null API digest fails closed. Do not fall back from an invalid digest or calculate the expected checksum from the ZIP that is being verified.
## Acceptance
1. Run `python3 scripts/ci/accept-release-offline.py` in a clean dedicated checkout. Its TLS loopback Gitea double and fake Docker CLI must prove release asset publication, the API digest-present path, the Forgejo-compatible `digest: null` sidecar path, rejection of a mismatched sidecar, and fail-closed behavior for a malformed non-null API digest. Assert the expected installer asset names and the sidecar content against the produced ZIP.
2. Run `python3 -m unittest scripts.ci.test_ci` (or the repository's equivalent CI policy test command) and verify release asset fixtures include the sidecar.
3. Run `bash -n install/install-server.sh`; if `pwsh` is available, parse `install/install-server.ps1` without invoking Windows-only installation actions.
4. For any disposable Compose validation required by the behavior change, follow `skills/compose-disposable-recipe/SKILL.md`: use source-built unique tags and isolated credentials/ports/volumes, install cleanup before build/start, and verify project resources and exact image tags are absent afterward.
5. Record local and CI evidence in the Gitea issue and PR. Do not claim a production Gitea release, `/releases/latest`, Docker Hub, runner, or deployed installer was validated by the offline API double.
-17
View File
@@ -1,17 +0,0 @@
---
name: mcp-global-configuration
description: Keep Heimdall developer MCP integrations available across projects without storing machine credentials in the repository.
---
# Heimdall developer MCP configuration
MCP integrations used while maintaining Heimdall belong in the developer's global Codex configuration, not in a repository `.mcp.json`. This keeps each project checkout free of personal service tokens and makes the integrations available in other projects.
## Configuration workflow
1. Before changing MCP setup, read this skill and the linked Gitea issue.
2. Configure the intended servers in `~/.codex/config.toml`. Keep authentication values in user-level configuration or environment variables; never copy them into tracked files, examples, logs, or acceptance output.
3. Remove any repository `.mcp.json` that duplicates global server configuration and contains credentials.
4. Validate that the global TOML parses and run `codex mcp list`. Check that each expected server appears once and is enabled.
5. For a server needed by the task, make a harmless read-only request (for example, list accessible GlitchTip organizations) to confirm authentication. Do not claim remote access from config presence alone.
6. Update the corresponding Gitea issue with the local verification and any limits. Do not add an application Compose acceptance recipe for a developer-only MCP configuration change.
-35
View File
@@ -1,35 +0,0 @@
---
name: mdns-camera-discovery
description: Implement and validate HomeKit camera discovery from DNS-SD mDNS announcements in Heimdall Agent.
---
# Heimdall mDNS camera discovery
Read `AGENTS.md`, the focused mDNS Gitea issue, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing discovery behavior.
## Ownership and data flow
- `Heimdall.Mdns/MdnsClient` owns UDP multicast and DNS-SD PTR/SRV/TXT/A parsing. Keep network operations cancellable and dispose sockets per operation.
- `HomeKitMdnsProbe` maps only categories 17 (camera) and 18 (doorbell) into Agent discovery records.
- `NetworkCameraScanner` is the Agent-side source of LAN probes. Preserve HomeKit metadata when its TCP scan has already found the same IP. Central persists and returns metadata; it must not probe the camera LAN.
- Resolve an accessory address from an A record attached to the instance or from the exact SRV target hostname. Never use another advertisement's arbitrary A record as a fallback.
- At Central confirmation, persist only capabilities proven by the discovery result and selected stream. Derive RTSP port from the selected RTSP URL (554 default for RTSP, 322 for RTSPS when omitted) or a probed RTSP port, HTTP port from the HTTP probe, and ONVIF service port from the device-service URL. Do not confuse UDP WS-Discovery port 3702 with the camera's HTTP ONVIF service port. Do not claim PTZ, audio, snapshot, or native motion support unless the probe actually verifies it.
## Synthetic acceptance
- Build synthetic DNS response packets with PTR `_hap._tcp.local` → instance, SRV instance → hostname/port, TXT `ci`, `sf`, `id`, `md`, and A hostname → address. Include an unrelated A record to verify strict SRV association.
- Verify camera and doorbell categories are kept, unrelated categories are filtered, `sf=0` maps to paired, and missing SRV-target A does not invent an address.
- Verify `HomeKitMdnsProbe` maps address/name/id/model/category/pairing/port into its Agent contract, and cancellation yields an empty result.
- Run the focused Agent tests and the full Agent test project after changes.
- The synthetic packet path validates DNS assembly and mapping only. A disposable Compose test can exercise the Agent source in isolation; only a real camera on a representative LAN validates multicast routing and hardware behavior. Keep that item open until such a run exists.
- The PostgreSQL integration scenario `ConfirmDiscovery_PersistsOnlyVerifiedPortsAndCapabilities` exercises confirmation from discovery metadata through persisted camera fields, including an ONVIF service port distinct from UDP 3702. Preserve that relational coverage when changing confirmation mapping.
## UDP receive lifetime at shutdown
`MdnsClient` owns each `UdpClient` for one probe/discovery call. When a receive window expires, cancel the receive with a linked token and await its task before leaving the socket scope; this observes the expected cancellation and prevents a pending receive task from surfacing later as `UnobservedTaskException`. Do not swallow unrelated `SocketException` failures: keep them observable (or log a sanitized exception type at the discovery boundary). The focused regression test `ObserveCanceledReceiveAsync_ObservesExpectedCancellationAndPropagatesSocketFailures` covers expected cancellation and an unexpected socket failure. Run the focused and full `Heimdall.Agent.Tests` suites after changes to this lifecycle.
## Disposable Compose
Run a one-shot isolated Compose test from the changed source with the SDK pinned by `global.json` (currently `mcr.microsoft.com/dotnet/sdk:10.0.100`). Copy only the Agent test project and its recursively referenced source projects, plus root build props/targets and `global.json`, into a temporary archive outside the repository. Mount the archive read-only, extract it inside the SDK container with `tar --no-same-owner` into `/tmp` (the container filesystem there is writable), and restore with `--locked-mode`. For mDNS lifecycle changes, run `HomeKitMdnsProbeTests` and the focused receive-cancellation regression test; otherwise run the relevant focused Agent tests. Use a unique Compose project, project-scoped NuGet package volume, and isolated bridge; publish no ports and never use host networking. The container is read-only except for `/tmp`, `/root/.local/share/NuGet` (NuGet HTTP cache), and the project-scoped package volume. Do not mark the bridge `internal`: locked restore may need NuGet network access; the bridge remains isolated from host/production networks. Install an EXIT cleanup trap before starting. This recipe builds no local images: remove only the named project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, then delete the archive and Compose file, retaining the shared SDK image. Record `local image tags: none` in the acceptance result. If a future variant builds an app/helper image, tag it uniquely and remove/verify that exact tag in the same cleanup trap. This proves source/test behavior in a container, not multicast delivery or camera discovery on a real LAN.
This SDK-only recipe creates no local Heimdall image. Retain the shared SDK base image; if future changes add a local build, use a project-unique tag and remove/verify that exact tag after teardown under `skills/compose-disposable-recipe/SKILL.md`.
-21
View File
@@ -1,21 +0,0 @@
---
name: notification-center
description: Implement and accept the authenticated Heimdall in-app notification center.
---
# Notification center
The header bell is rendered by `Components/Shared/NotificationBadge.razor`; it displays the unread count delivered by `NotificationsHubClient` and must navigate to `/notifications`. The page reads the signed-in user's list through `HeimdallApiClient` and the existing `GET /api/notifications` endpoint. Read actions use the existing per-user `POST /api/notifications/{id}/read` and `POST /api/notifications/mark-all-read` endpoints, then refresh the hub count. Keep authorization on the page and user scoping in the API/application handlers; never accept a user id from the browser.
When documenting delivery channels in `docs/notifications.md` or its summary in `docs/specs.md`, verify `NotificationChannel`, `SendNotificationJob`, `NotificationSettingsSection.razor`, `Profile.razor`, the delivery services, and `BackgroundJobs/JobSetup.cs`. The shipped external channels are SMTP email and ntfy; do not describe Gotify as integrated. `/settings` owns global SMTP/ntfy settings and test actions, while `/profile` owns user preferences. Check both digest job implementations and their schedules before documenting cadence. Distinguish source inspection from validation against a real SMTP/ntfy deployment. Remove obsolete channel integrations, editor flows, and test claims from `docs/notifications.md` and `docs/specs.md`; if a historical example must remain, label that exact heading/table/snippet locally rather than relying on a broad notice elsewhere in the guide. When the notification guide’s scope or delivered status changes, update both notification summaries in `docs/README.md` to match it.
When legacy notification designs remain in `docs/MASTER_SPECIFICATION.md`, put a local dated historical/non-shipped note beside each section, queue example, or UI mockup, and link to `docs/notifications.md`. A document-level historical header alone is not sufficient for Gotify or template-editor claims.
## Acceptance
1. Build `Heimdall.Web` with the SDK from `global.json` and run focused Web tests.
2. In disposable Central + PostgreSQL Compose, create only synthetic notifications for the disposable admin, open `/notifications` from the header bell, confirm notification content appears and `/events` is not loaded.
3. Mark one item read and all items read; verify displayed state and unread badge refresh. Confirm empty and API failure states render.
4. Use unique Compose project, generated credentials, loopback port, and project-owned image tag. Follow `compose-disposable-recipe` exactly: remove only that project and exact local tag, verify project containers/volumes/networks and image tag are absent, and retain shared images.
The empty and failed API states have focused bUnit coverage in `NotificationsPageTests`. Simulate the API error with an HTTP 500 response for `GET /api/notifications`; taking PostgreSQL offline also breaks server-side session validation before the page can handle the notification request.
@@ -1,27 +0,0 @@
---
name: notification-delivery-acceptance
description: Validate Heimdall's global SMTP and ntfy settings, test actions, and notification delivery without external providers.
---
# Heimdall notification delivery acceptance
Read `AGENTS.md`, the PIPE-10/FEAT-05 Gitea issue, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing notification delivery.
## Configuration contract
- Settings created through the UI are stored with lowercase keys. `AppSettingReader` must normalize requested keys before its exact EF query; callers use mixed-case literals for legacy reasons.
- SMTP reads `email.smtphost`, `email.smtpport`, `email.username`, `email.password`, `email.fromaddress`, `email.fromname`, and `email.usessl`.
- ntfy reads `ntfy.baseurl` and `ntfy.token`; test messages use the same configured service and should fail visibly when it rejects or cannot be reached.
- Keep SMTP/ntfy secrets out of responses and logs. Outbox delivery remains at-least-once; a provider acceptance followed by a lost DB acknowledgement can duplicate a notification.
## Required simulated validation
1. Run `AppSettingReaderTests`, notification service/outbox tests, and the PostgreSQL outbox integration tests.
2. Use a disposable Compose project from the changed Central source with PostgreSQL, an isolated ntfy service and Mailpit. Generate database/JWT credentials, use an internal project-only network and no published ports, explicitly empty the Sentry DSN, and keep real SMTP/ntfy credentials out of the environment.
3. Bootstrap a synthetic Admin and save SMTP/ntfy settings through `/api/settings`, matching UI key names. Call `/api/settings/ntfy/test` and `/api/settings/email/test`; verify ntfy returns success and Mailpit stores the synthetic recipient message.
4. Install an EXIT cleanup trap before build/start. Tear down only the project with volumes/orphans, verify zero project containers/volumes/networks, then remove/verify absence of the exact source-built Central image tag even on failure. Retain shared ntfy/Mailpit/PostgreSQL/Python base images, preserve test exit status, report cleanup failures, and never use `--rmi all` or broad prune commands.
5. Report local service acceptance separately from delivery to a real SMTP relay, hosted ntfy server, or user device.
## Current local evidence
On 5 November 2026, `AppSettingReaderTests` passed 9/9. The first disposable provider run showed ntfy success but SMTP failure: the UI stored lowercase keys while `EmailService` queried mixed-case values. `AppSettingReader.GetAsync` now lowercases trimmed keys; tests cover the SMTP and AI URL callers. The source-built isolated project `hmd-notify-mock-1793882996-2efa06` then passed both Admin settings/API test routes, ntfy HTTP 2xx, and SMTP test delivery captured in Mailpit. No ports were published and the bridge was internal. Cleanup verified zero containers/volumes/networks and removed/verified absence of the exact Central image tag. Real external delivery remains unvalidated.
-30
View File
@@ -1,30 +0,0 @@
---
name: optional-server-services
description: Keep installer-managed RustFS and coturn Compose services aligned with the server installer's paths and networking.
---
# Installer-managed optional services
The Linux and Windows server installers save service secrets in `<install-root>/optional/secrets/`, backup scripts in `<install-root>/optional/scripts/`, and pass the root `.env` for interpolation. Compose resolves relative paths from its project directory, which otherwise defaults to the directory containing the first `-f` file. RustFS and coturn Compose files reference `./optional/secrets/<name>`, so start them with `--project-directory <install-root>`. The backup Compose references `./scripts` and `./secrets/db_password`, so start it with `--project-directory <install-root>/optional`. Preserve these service-specific bases; applying the installation root to every optional Compose breaks the backup mounts.
## RustFS
- Keep `rustfs_access_key` and `rustfs_secret_key` file paths aligned with the generated files from both installers.
- Installers create these bind-mounted secret files as owner-only (`0600`), which the official RustFS process (`10001:10001`) cannot read directly. Keep a short root initializer, copy the files into the service's private tmpfs, `chown` the copies to UID/GID 10001, then drop to the `rustfs` account before executing the upstream entrypoint. Keep the root filesystem read-only and provide tmpfs only for runtime paths that RustFS writes (`/logs`, `/tmp`, and its secret copies).
- Verify actual optional-service invocations use the right project directory: `<install-root>` for RustFS/coturn and `<install-root>/optional` for backup. Confirm normalized secret and script bind sources point to exact generated files/directories. A successful `config` without checking normalized source paths is insufficient because Compose can accept an unintended path that happens to exist.
- Keep the named data volume and shared `heimdall-net` behavior intact.
## coturn
- Coturn is an optional live-view relay consumed by Central through `LiveMedia:Turn:Urls` and `LiveMedia:Turn:SharedSecret`. Central returns short-lived TURN REST credentials to the browser; the shared secret stays server-side. Keep this service optional and do not describe its integration as future or external-only.
- Keep `coturn_secret` sourced from `./optional/secrets/coturn_secret`.
- coturn 4.6 does not support `--static-auth-secret-file`; read the mounted Docker secret in a short root initializer and write its configuration into private tmpfs. Do not print the value or pass it in the server process arguments.
- Local Compose secrets are owner-only bind mounts too. Start the initializer as root, make the temporary config readable by the image's `nobody` account, then `exec` `turnserver` as `nobody` with `no-new-privileges` enabled. Keep the root init transient; do not run the TURN daemon as root.
- Use a shell entrypoint that executes `turnserver`, bridge networking, and explicit TCP/UDP listener and UDP relay port publications; the upstream image has a `turnadmin` entrypoint, and host networking cannot be combined with useful Compose port mappings.
- Keep the published relay range identical to coturn's `--min-port`/`--max-port` options. Make listener and relay settings configurable with documented defaults.
- Keep `COTURN_EXTERNAL_IP` optional; when set in the installer root `.env`, add Coturn's `external-ip` directive so it advertises the public address across NAT. The operator must forward the listener and relay range through firewalls/NAT. Do not set a guessed public address.
- Do not claim public TURN reachability from a local container startup. It requires an external ICE/TURN client on a real network.
## Acceptance
Run `skills/optional-server-services/acceptance.sh`. It creates a uniquely named disposable Compose project, generated owner-only secrets, an isolated install root, unique listener and relay ports, then validates Compose with each installer's explicit project directory. It asserts the normalized RustFS/coturn secret paths and backup secret/script bind sources exactly match the generated files before starting containers. It verifies RustFS `/health`, signs a real S3 bucket-creation request with the generated keys, and runs `turnutils_uclient` inside the Compose network with TURN REST credentials. This proves local container-network allocation only; it does not prove external firewall/NAT reachability. The trap tears down only that project and verifies its containers, volumes, and networks are absent. The recipe builds no local images and retains upstream images.
-45
View File
@@ -1,45 +0,0 @@
---
name: parallel-development
description: Plan and coordinate parallel Heimdall implementation work with Orca workers while preserving architecture, issue tracking, and acceptance evidence.
---
# Parallel development with Orca
Use this workflow for a Heimdall change that can be split into independent investigations or implementation tasks. Read `AGENTS.md`, the focused Gitea issue, the relevant domain skills, and the installed Orca `orchestration` guide first. The Orca CLI guide is also required when creating or managing worktrees. The version-matched instructions come from `orca-ide skills get orchestration` and `orca-ide skills get orca-cli`; follow the resolved executable specified by those guides.
## Find parallel work early
1. Map the requested outcome to the Heimdall boundaries: `Domain`, `Application`, `Infrastructure`, `Web`, and `Agent`. Also identify tests, migrations, documentation, and disposable acceptance work.
2. List concrete work packages with a single owner, bounded files or components, required inputs, and an observable deliverable. Mark each dependency explicitly.
3. Start every ready, independent investigation or implementation promptly. Keep sequential work (shared contract decisions, migration ordering, integration, final acceptance, ticket update, and PR) with the coordinator unless it is itself safely isolated.
4. Split independent, user-visible deliverables into linked Gitea issues before dispatch, following `gitea-ticket-workflow`. Keep one issue for coordinated subtasks that do not ship independently.
Choose the Orca coordination shape that matches the dependency graph:
- For a small set of independent tasks with clear, separate outputs, use the version-matched `worker-start --spec` workflow. Give workers precise scope and tell them to report evidence and blockers.
- For dependent tasks or several waves of work, create an Orca Run and Tasks with explicit dependencies, then start all Tasks reported ready. Recheck readiness after each worker report and start newly unblocked work without waiting for unrelated branches.
- Use a shared current worktree only when workers cannot conflict in files. If edits overlap or cannot be partitioned confidently, assign separate Orca worktrees and integrate their changes deliberately. Do not start concurrent workers that edit the same files.
- Do not parallelize a decision that needs one owner, duplicate the same task across workers, or turn a straightforward isolated change into coordination overhead.
## Heimdall task contracts
Every worker brief must include the user outcome, issue number, exact component/file ownership, architectural constraints, dependencies, acceptance evidence, and what to return. Ask for a concise report with files changed, commands/evidence, remaining risks, and any files or decisions needed from the coordinator. Do not provide credentials, production data, RTSP URLs, raw tokens, or real customer information in a worker prompt.
Workers must preserve these boundaries:
- Domain stays independent of infrastructure; use cases and interfaces belong in Application; adapters and EF Core persistence belong in Infrastructure; HTTP/UI composition belongs in Web; camera/runtime behavior belongs in Agent.
- EF Core and PostgreSQL requirements remain in force. Do not share a `DbContext` across concurrent work. Schema changes include reviewed migrations and relational verification.
- Each worker edits only its assigned scope. When shared contracts must change, have one owner define the contract first, then unblock dependent tasks in the Orca DAG.
- Each independent implementation still follows its focused skill and records results against the Gitea issue. Delegation does not waive authorization, security, CI runner, secret, or review rules.
## Integrate and validate once
1. Coordinate through Orca messages and worker reports, not by polling or steering worker terminals. Follow the version-matched guide's wake, recovery, and completion rules; do not treat silence as proof of completion.
2. Review each returned diff against its assigned scope and the issue criteria. Resolve overlapping changes in the coordinator's integration step; do not accept a report as proof without inspecting the relevant change/evidence.
3. Run shared builds, tests, persistence checks, and disposable Compose acceptance after integrating dependent changes. Avoid making every worker rerun the same full suite; ask each worker for focused evidence, then run the smallest combined checks once at integration.
4. Keep required project-specific acceptance intact. Behavior and deployment changes still use `compose-disposable-recipe`; account bootstrap and Central update changes use their additional focused recipes. Never claim external runner, registry, camera, or storage evidence from a worker's local mock.
5. Update the issue with completed criteria and actual evidence, create/update the PR with `Closes #N` only when every criterion is complete (otherwise `Refs #N`), and record unresolved external validation separately.
## Completion record
The issue or PR should make the coordination auditable without duplicating a long-lived backlog: note the Orca work packages at a high level, which were integrated, the combined checks actually run, and any tasks or acceptance gates still open. Close or settle worker Tasks only when their evidence is received; a reported failure remains open work.
-38
View File
@@ -1,38 +0,0 @@
---
name: penpot-design-sync
description: Open Heimdall's connected Penpot workspace through Orca, authenticate safely, update design source alongside UI work, and verify the saved frames.
---
# Heimdall Penpot design sync
Heimdall's connected Penpot file is part of the UI source of truth. Whenever a change affects a screen, interaction, responsive layout, installer, or visible state, update the corresponding Penpot design in the same change. Do not leave a known implementation/design mismatch for a later task. When a UI change does not affect the design, state why in the Gitea issue evidence.
## Required entry path: Orca browser
1. Read the Orca `orca-cli` and `orca-computer-use` skills when not already loaded. Use the Orca CLI to list/open tabs and inspect browser state; use computer-use only when a visible GUI action is necessary.
2. Open the Penpot site in the Orca browser and sign in there using credentials already present in the environment or Orca-managed account. Never echo, log, paste into issue comments, or otherwise expose credential values. Do not try public Penpot Cloud as a substitute when Heimdall uses its connected self-hosted Penpot instance.
3. Confirm the signed-in team, Heimdall file, and target page before editing. The current Heimdall file is `aadb42b1-1e8d-8014-8008-7dc15de6e3ff`, team `073c6639-4451-8006-8008-e66329727382`. Resolve the current page from the file; do not assume page IDs remain stable.
4. Use Penpot MCP design operations only after Orca has opened the authenticated workspace and the correct file. The browser is the required way to establish and verify the user session, even when MCP is used for precise shape edits.
5. If login, workspace access, or the connected Penpot tool fails, diagnose the actual browser/session path first. Do not claim that the design was updated. Continue independent code work when possible, then report the concrete access blocker and leave the issue open.
## Design update workflow
1. Read `AGENTS.md`, the focused UI skill (for the site Agent installer, `site-agent-installer-ui/SKILL.md`), the UI implementation, and `docs/ui-pages.md`. Review the current Penpot page in Orca before changing it.
2. Compare the shipped behavior with the existing frames. Preserve Heimdall's established visual language and component patterns while representing every meaningful state introduced by the change. Cover loading, success, error/unavailable, permissions, and empty states when they are relevant.
3. For responsive UI, represent desktop and narrow/mobile widths. For installers, show platform and method selection, optional configuration, copyable commands, and unavailable signed-release/image states. Keep fake credentials, real tokens, private URLs, and customer data out of design content.
4. Update the existing relevant frame in place where practical. Rename frames so their platform, viewport, and state are clear. Remove obsolete competing mockups or stale secret-bearing examples when they would mislead implementers; preserve unrelated page content.
5. Match text, labels, command behavior, option availability, selected states, and copy affordances to the implementation and localization. Do not introduce unsupported options simply to imitate another product. Keep `docs/ui-pages.md` consistent when it describes the same UI.
6. Save/commit the design through Penpot, then verify the resulting frames in the Orca browser. Inspect the actual canvas at a useful zoom and check hierarchy, clipping, responsive composition, and stale content. A successful MCP response alone is not visual acceptance.
7. Record the Penpot file/page link, frame names/states changed, and visual review outcome in the linked Gitea issue. Distinguish verified Penpot design work from code tests and real release/deployment evidence.
## Installer design reference
The installer should follow the interaction hierarchy represented by `site-agent-installer-ui/SKILL.md`: platform choices, platform-specific method choices, optional configuration, then titled command cards with deliberate copy controls. For the current Agent installer, keep the design aligned with supported Linux, Windows, and Docker options, release signing/update-key gates, Docker installation pinned to the immutable signed `repository@sha256:digest`, signed digest validation for updates dispatched by Central, and the actual command builders. Keep desktop and mobile layouts, plus release-unavailable states, represented. Update the existing installer frame and any relevant variations in the connected file on every behavior or layout change.
## Acceptance evidence
- Orca browser opened the self-hosted Penpot workspace and authenticated session was confirmed without exposing credentials.
- Correct Heimdall file and target page were confirmed before edits.
- Changed frames were inspected visually in the browser after the edit; list their names/states and link the file/page in the Gitea issue.
- Design and shipped UI/docs agree on supported choices, labels, states, and interaction behavior.
- If an external Penpot outage prevents completion, record the exact blocked step in Gitea and do not mark the design acceptance complete.
-32
View File
@@ -1,32 +0,0 @@
---
name: pr-release-versioning
description: Assess whether a Heimdall pull request needs a published release and select its SemVer increment from the change impact without asking the user.
---
# Pull request release assessment
Apply this assessment while preparing every Heimdall PR. Do not ask the user whether to release or which version to use. Record the decision, rationale, and proposed version in the PR description; update it if the diff changes.
## Decide whether a release is needed
- **No release** for documentation, skills, tests, CI-only changes, refactors with no externally observable change, or internal tooling changes. State `Release: no` and keep the current version unchanged.
- **Release required** when the PR changes behavior shipped to Heimdall users or operators, published images/installers/Agent assets, compatibility contracts, or security fixes that users need to receive.
- Do not create a release tag for a PR. A release tag points to a commit on `main`; assess the merged change after required checks pass and then follow the tag workflow in `release-automation`.
## Select the version automatically
Use the latest stable SemVer tag reachable from the integration branch (`MAJOR.MINOR.PATCH`); ignore prerelease tags when selecting the stable base. For multiple merged, unreleased changes, assess all changes since that tag together and use the highest required increment.
- **MAJOR** for a breaking API, configuration, data, or install/upgrade compatibility change.
- **MINOR** for a backward-compatible user-facing capability or operator feature.
- **PATCH** for backward-compatible bug fixes, security fixes, performance fixes, and shipped compatibility corrections.
- No release-worthy changes means no tag and no version increment.
Increment only the selected component and reset lower components to zero. For example, from `1.4.7`: breaking becomes `2.0.0`, a compatible feature becomes `1.5.0`, and a fix becomes `1.4.8`. If no stable tag exists, use `1.0.0` as the base only when the repository's first-release policy confirms that baseline; otherwise report the missing baseline instead of inventing one.
## PR and post-merge steps
- Put a short `Release assessment` section in every PR: `no release (reason)` or `release required; proposed version X.Y.Z (reason)`.
- For no-release PRs, do not create or push a tag. Keep the version unchanged.
- For a release-required PR, determine the exact next version from the current `main` tags after merge, verify it is unused, and create an annotated tag on the merged `main` commit only after required CI succeeds. If another merge changes the base before tagging, recalculate from the latest stable tag and all unreleased changes.
- Never overwrite or move an existing tag. If the change is prerelease-only or an emergency exception, explain the project-specific suffix/tag choice in the PR without asking the user to choose it.
-24
View File
@@ -1,24 +0,0 @@
---
name: heimdall-pwa
description: Implement and accept Heimdall's root-hosted, online-first Blazor PWA without persisting private application data.
---
# Heimdall PWA
The supported PWA deployment is at the web origin root (`/`). The Blazor app uses Interactive Server, so camera, event, account and administration screens require a live server circuit. Offline mode is an informational page only; never add authenticated HTML, API results, media, credentials or SignalR traffic to CacheStorage or replay mutations offline.
## Implementation map
- `src/Heimdall.Web/Components/App.razor` links the web manifest and raster/Apple icons and loads `js/pwa-register.js`.
- `wwwroot/manifest.webmanifest` defines stable root scope, standalone display and PNG/SVG icons.
- `wwwroot/service-worker.js` caches only `/offline.html`, `/manifest.webmanifest` and `/pwa-icon.svg`. It falls back only for failed same-origin GET navigations and excludes API, auth, Blazor, hubs, health, metrics and operational/documentation paths.
- The worker must remain waiting after an update. `pwa-register.js` shows a reload action for a waiting worker; only that action sends `ACTIVATE_UPDATE`, then reloads after `controllerchange`. Do not unconditionally call `skipWaiting()` or `clients.claim()` because this can replace resources during an active form or live session.
- Installation UI is progressive: use `beforeinstallprompt` where the browser provides it; otherwise explain the platform's browser-menu installation steps. Browsers without PWA installation support must keep the site usable.
## Acceptance
1. Run `tests/Heimdall.E2E.Tests` with its disposable PostgreSQL fixture and Chromium. Check unauthenticated manifest and icon access, exact public-shell contents, offline navigation fallback, and absence of cached private content.
2. Build the changed source through the disposable Central + PostgreSQL Compose recipe in `skills/compose-disposable-recipe/SKILL.md`; probe `/healthz`, `/manifest.webmanifest`, `/service-worker.js` and the offline page. Use unique project/ports/credentials/volumes and install an EXIT cleanup trap before build/start. Remove the project, verify zero containers/volumes/networks, then remove and verify absence of each exact project-unique local image tag, even after failure; retain shared upstream images and report cleanup errors.
Assign the locally built Central image a project-unique tag; remove and verify that exact tag after teardown, while retaining shared .NET/PostgreSQL bases.
3. Review `docs/pwa.md` and deployment instructions for HTTPS, root hosting, reverse proxy/WebSocket support, update and rollback behavior. Report physical iOS/Android/desktop installation, HTTPS proxy, and mobile sleep/network testing only when run on those real environments.
4. Keep the PWA backlog open for validations that require real browsers/devices or remote push infrastructure. Do not claim Web Push exists without a tested VAPID backend, subscriptions, revocation and permission-aware delivery.
-22
View File
@@ -1,22 +0,0 @@
---
name: release-api-responses
description: Safely consume configured Forgejo release manifests in Heimdall Central.
---
# Release API responses
The Central `UpdatesController` reads a configured Forgejo latest-release endpoint and serves the result to anonymous update checks and authenticated agents. Treat both the JSON document and subsequent release assets as untrusted network input.
## Implementation
- Keep the release endpoint HTTPS-only and preserve its current upstream failure behavior (`null` internally and HTTP 502 at the API boundary).
- Read the release document with a fixed byte limit before deserialization. Check `Content-Length` as an early rejection, but enforce the limit while streaming because the header can be missing or incorrect.
- Catch `JsonException` at the provider parsing boundary. Return unavailable data without logging response bodies; do not convert request cancellation into an ordinary provider failure.
- Keep asset downloads independently bounded and digest-verified. Do not expand this change to provider retries, endpoint configuration, or public response contracts without a separate acceptance requirement.
## Acceptance workflow
1. Run `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --no-restore` for malformed HTML, invalid JSON, a valid release document, and the response size limit.
2. Run the Web project build with the SDK pinned by `global.json`.
3. Run the disposable Compose procedure in `compose-disposable-recipe` from the exact changed source. Configure a synthetic HTTPS provider endpoint that can return a valid Forgejo document and an HTML 200 response; probe the public update endpoint and verify valid data succeeds while malformed provider data yields the established 502 response.
4. Record the unique Compose project, exact built image tag, sanitized HTTP outcomes, teardown verification for containers/volumes/networks, and tag absence in the linked Gitea issue. Never use production provider configuration or credentials.
-41
View File
@@ -1,41 +0,0 @@
---
name: release-automation
description: Build and validate changed Heimdall images on pushes, then publish versioned Docker Hub images and signed installer assets for semver tags.
---
# Heimdall build and release workflow
For every PR, follow [pull request release assessment](../pr-release-versioning/SKILL.md). Determine and record whether a release is needed and the proposed SemVer from the change impact; do not ask the user to decide. Documentation and skills-only changes do not create a release or change the version. Only tag a release after the merged commit is on `main` and required checks pass.
For any local release investigation that needs credentials, follow [Infisical secrets](../infisical-secrets/SKILL.md). Keep publication credentials in Gitea Actions as specified below; do not assume that a key in Infisical is available to CI.
Use this skill for changes to `.gitea/workflows/build.yml`, `scripts/ci/change_scope.py`, image build/push scripts, installer packages, release signing, or the Gitea release job.
## Delivery contract
- Pull requests run `verify` and build/scan only images affected by the changed project graph. They never receive Docker Hub or Gitea publication credentials.
- `test-plan.py` computes both affected test suites and build targets from transitive `ProjectReference` edges. PRs build only those test projects and any changed source projects not covered by them; the solution is built only for main/tag runs or broad CI/build-configuration changes. The solution restore remains locked and solution-wide for the dependency security report.
- A push to `main` validates the changed source and builds/scans/pushes only affected images. The affected image gets immutable `sha-<full-sha>` and mutable `latest` tags on Docker Hub. Main pushes do not create Gitea releases.
- Runs for the same ref are serialized so a slower older `main` run cannot overwrite a newer `latest` image.
- A `MAJOR.MINOR.PATCH` tag (optional prerelease suffix allowed) is a version release. It validates the complete source and builds/scans server, Agent CPU, and Agent GPU images once each. The verified images are pushed to Docker Hub as `sha-<full-sha>` and the application version.
- After merge of a release-worthy PR, use the current stable tag and all unreleased changes to calculate the SemVer increment according to `pr-release-versioning`. Fetch `main`, verify the merged commit is reachable from it, verify the selected tag is unused, create an annotated tag at the merged commit, and push it to trigger this workflow. Never ask the user to choose a version or release, infer a version from the PR title alone, or force-update an existing tag. Documentation and skills-only changes do not get a tag.
- The tag release job does not build or scan Docker images. It pulls the already scanned immutable image refs to verify their source revision, then resolves canonical digests from Docker Hub Registry v2 using the immutable commit tags. It creates a signed Gitea release containing `heimdall-installers-<version>.zip`, its `heimdall-installers-<version>.zip.sha256` sidecar, framework-dependent Agent archives, the public key, signed update manifest, and CPU/GPU image digest manifests. Local Docker `RepoDigests` can contain multiple values and must not be used as a uniqueness check. Build provenance, image-digest bookkeeping, and unrelated checksums stay in CI package output and are not uploaded as end-user release assets. It never uploads Docker image archives to Gitea.
- The package script uses fast gzip compression for the framework-dependent release archives to reduce release-job CPU time; keep the archive names and layout stable for Linux and Windows installers.
- The installer ZIP preserves the `install/` and `docker/` layout consumed by the Linux and Windows server installers. The package job writes a checksum sidecar with the archive's exact asset filename. A raw-branch `.sh` or `.ps1` bootstrap resolves Gitea's latest stable version (or an explicit `HEIMDALL_INSTALLER_VERSION`), uses a valid Gitea SHA-256 asset digest when present and otherwise downloads and parses the published sidecar, then verifies the ZIP before running its version-pinned script. A malformed non-null Gitea digest is a hard failure; it must not be silently replaced by the sidecar. Versioned bundle scripts pin their source assets and server image to the same tag and do not resolve a moving release. Direct Agent install scripts served by Central continue to download Agent payloads through Central's configured Gitea release API.
- Gitea release creation is idempotent by version tag. A release remains draft until every expected asset is uploaded; stable versions publish as releases and versions with a prerelease suffix publish as prereleases.
- Central stores only the public Forgejo origin in `updates.forgepublicurl` and constructs the canonical Heimdall `releases/latest` API route in code. Preserve the legacy setting migration and never make the derived API route editable in Settings.
- The Site Install panel displays the configured signed release version and only exposes native install commands when the signed manifest, key, and platform assets are available. Docker commands also require a verified image digest.
- Required publication secrets are `DOCKERHUB_USERNAME`, `DOCKERHUB_TOKEN`, and `RELEASE_SIGNING_KEY_B64`; `RELEASE_SERVER_URL` must match the HTTPS origin in `BUILD_SERVER_URL`. Do not create or use a long-lived `RELEASE_TOKEN` PAT. The tag-only `publish` job gets Gitea's built-in `GITEA_TOKEN`, scoped to `contents: write` and `pull-requests: read`; PR jobs retain read-only contents access and never receive publication credentials.
- For the first signed release, when no Agent or signed manifest has been distributed, create one ECDSA P-256 key pair and save only the base64-encoded private PEM as the repository Actions secret `RELEASE_SIGNING_KEY_B64`. Keep an offline backup in an approved secret vault. The release publishes the derived public key, which becomes the trust root for new Agents; never rotate it after adoption without following the documented key-rotation procedure. Set `RELEASE_SERVER_URL` as an Actions variable to the exact HTTPS origin.
## Image change scope
`scripts/ci/change_scope.py` maps changed paths to the exact Docker build graphs. Shared build configuration and shared Domain/Application/Contracts projects affect both Central and Agent. Web/Infrastructure/installer assets affect Central; Agent and mDNS projects plus the model affect Agent CPU and GPU; each Dockerfile affects only its own image. Keep this map aligned with the `COPY` instructions and project references in the Dockerfiles. A version tag deliberately selects every image.
## Offline end-to-end acceptance
Run `python3 scripts/ci/accept-release-offline.py` from a clean dedicated worktree. It invokes package, release-note, and release scripts with disposable ECDSA P-256 credentials, a loopback-only TLS Gitea API double, synthetic pull request data, and a fake Docker CLI. It checks the version-pinned Linux/Windows installer ZIP and its published checksum sidecar, installer bootstrap with both a valid API digest and `digest: null`, Agent archive checksums, manifest signature, Docker Hub immutable refs/digests, the exact minimal release asset set, and proves the publication script does not build or scan images. The fake Docker CLI must never contact a registry; the API double must reject non-synthetic authorization and suppress request logging.
For build-scope changes, validate that documentation-only, Central-only, Agent-only, and shared-project file sets produce the intended image outputs. For behavior/deployment changes, also run the required disposable source-built Compose recipe with generated credentials, ports, project name, and unique local image tags. Its EXIT trap must verify project containers, volumes, and networks are gone and remove/verify absence of only its exact image tags.
These simulations do not prove Actions permissions, signing secret availability, runner network, Docker Hub/Gitea publication, Central production configuration, or native Agent hardware/OS behavior. Record actual remote evidence in the focused Gitea issue; do not mark it complete based on offline simulation.
-17
View File
@@ -1,17 +0,0 @@
---
name: renovate-automation
description: Diagnose and maintain Renovate dependency updates through Gitea Actions without exposing bot credentials.
---
# Heimdall Renovate workflow
Use this skill for `.gitea/workflows/renovate.yml`, `renovate.json`, or dependency-update failures.
- Renovate runs only on its weekly schedule or manual dispatch, on `[ubuntu-latest, build-agent]`, in the pinned Renovate container. Keep `RENOVATE_TOKEN` in Actions secrets and `FORGEJO_API_ENDPOINT` in Actions variables; do not add either credential or forge hostname to repository files. Forgejo reserves variable names beginning with `GITEA_` and rejects them.
- The endpoint must be the HTTPS Forgejo API root ending in `/api/v1`. The workflow checks that the token can call `/user` and read `arnaud.dartois/Heimdall` before Renovate starts. Preflight logs only response status and a safe diagnosis; never print request headers, response bodies, or token values.
- HTTP 401/403 means the secret is missing, expired, revoked, or lacks repository access. Configure a bot token with repository read and write access so Renovate can open pull requests. Read preflight success does not prove write access; confirm a successful run that opens or updates a PR.
- Use `node --test scripts/ci/renovate-preflight.test.mjs` to test endpoint validation and sanitized auth failures locally. Do not run Renovate locally with production credentials.
- Run `bash skills/renovate-automation/acceptance.sh` after changing the preflight or its endpoint wiring. It exercises valid and rejected synthetic credentials over an isolated HTTPS mock in Compose; the test container trusts only the generated self-signed certificate for its local fixture.
- For a changed preflight/deployment path, validate a disposable Compose project with a mock HTTPS API, a synthetic token, no host-published ports or persistent data, and both accepted and rejected credentials. Install an EXIT cleanup trap before startup, preserve the test exit status, remove that exact project, and confirm it leaves no containers, volumes, or networks; if pulling the Node base image is unavailable, record the blocker and rerun the recipe when registry access is restored.
- The mock-preflight recipe uses a shared upstream Node image and creates no local images. Retain that base image. If the recipe adds a locally built mock/helper/application image, record its unique tag and remove/verify only that exact tag in the same cleanup trap, including on failure. Do not use `--rmi all` or broad prune commands.
- For operational changes, update the Renovate Gitea issue with the workflow run and the remaining remote-secret validation. Never claim the bot works based only on configuration presence.
-25
View File
@@ -1,25 +0,0 @@
---
name: sentry-telemetry-privacy
description: Keep Heimdall Sentry events free of authentication material while preserving safe diagnostic metadata.
---
# Sentry telemetry privacy
Sentry event and transaction processing are configured in `src/Heimdall.Web/Program.cs`. `SetBeforeSend` and `SetBeforeSendTransaction` are separate SDK callbacks, so apply `SentryTelemetryPrivacy` to both. Before either payload is sent, filter request `Headers`, `Env`, and `Other` maps; remove request/response cookies, query strings, and bodies; strip URL user information; and filter sensitive values in event extras, transaction contexts, tags, spans, and breadcrumbs. Keep the helper in the Web boundary; do not move request telemetry into Domain or Application.
When changing this behavior:
- Add focused tests under `tests/Heimdall.Web.Tests/Security/` using synthetic `SENTINEL_` values only. Serialize final events and transactions through the Sentry SDK serializers and assert no sentinel survives. Also assert safe diagnostic metadata remains.
- Treat header names case-insensitively and normalize common separators before matching names that indicate authorization, API keys, tokens, secrets, passwords, credentials, or cookies.
- Clear entire fields such as cookie strings, query strings, and request bodies when selective redaction could miss nested or encoded credentials. Strip URL user information, query, and fragment while retaining the safe path.
- Apply the same sensitive-key filtering to event extras and breadcrumbs. Preserve the existing rate-limit breadcrumb filter.
- Recursively inspect string-keyed maps in extras and custom contexts. Replace arrays, other collections, and opaque object graphs with `[Filtered]` instead of allowing uninspected JSON serialization; retain safe primitive values and safe map entries.
- Filter sensitive-name tags on both `SentryEvent` and `SentryTransaction`; sanitize trace custom data, response headers, and span data/tags.
- Include synthetic request `env`/`other`, sensitive event tags, nested maps, arrays, and opaque values in serializer-level tests.
- Never copy actual event headers, API keys, cookies, tokens, or request bodies into issue comments, test fixtures, logs, or acceptance evidence. Record only field names and synthetic test outcomes.
## Acceptance
Run `skills/sentry-telemetry-privacy/acceptance.sh`. The recipe runs the focused .NET test from the current checkout in a uniquely named disposable Compose project using the upstream .NET SDK image. It publishes no ports, creates no application image, uses no deployed configuration, and removes and verifies the project's containers, volumes, and network. Its `EXIT` trap disables inherited `errexit`/`nounset` while attempting each independent cleanup step, preserves the original test status, and reports cleanup failures. Upstream SDK images remain cached. Record the project name, test result, `local images built: none`, and resource-cleanup verification in the linked Gitea issue/PR.
This proves local sanitization logic and event/transaction payload handling only. It does not claim a live Sentry/GlitchTip delivery or rotate any external credential.
-25
View File
@@ -1,25 +0,0 @@
---
name: server-healthchecks
description: Keep Heimdall container health probes aligned with the HTTP methods accepted by its ASP.NET health endpoints.
---
# Heimdall server health checks
Use this workflow when changing `Dockerfile` health checks, Central Compose health checks, or Web health endpoint routing.
- Central and Agent containers probe `/healthz` on port 8080 (the development Agent may bind its host-mapped port). ASP.NET maps this route for `GET`; a `HEAD` request returns 405 and marks a live server unhealthy.
- When documenting health status, compare each summary with the registered check names/tags, endpoint filters, and HTTP status mapping in Web and Agent. Web `/healthz` is liveness (`200`), `/readyz` checks the `ready` PostgreSQL and selected-storage dependencies (`200` only when healthy, otherwise `503`), and `/health/live` selects the `live` PostgreSQL and optional configured AI backend check (`503` when degraded). Agent `/healthz` runs its registered checks (`Degraded` maps to `200`, `Unhealthy` to `503`); `/health/live` selects only the Agent pipeline-degradation check (`503` when degraded). Do not claim a Central broker health check unless one is registered.
- Ollama is optional; its URL can be configured in Central settings, the admin connectivity action can ping it, and `AiHealthCheck` probes `/api/tags`. That endpoint check proves availability only, not model inference or summary generation. Do not document LLM-generated summaries until a production caller for a model generation/chat API is implemented.
- In the Alpine image, use BusyBox `wget` with `-O /dev/null` to issue a GET and discard the body. Do not use `--spider`, because BusyBox implements it as HEAD.
- Apply this to both `docker/Dockerfile`/Central Compose and `docker/Dockerfile.agent`/Agent development Compose. Keep the image and Compose probes consistent, with bounded timeout/retries and no published health endpoint required.
- For acceptance, build the changed Central or Agent image from source under a project-unique tag in a unique Compose project with a generated `.env`, synthetic credentials, a loopback-only unused port, and project-scoped volumes/network. Install an EXIT cleanup trap before build/start. Verify a GET health probe succeeds and an equivalent HEAD receives the endpoint's 405; then confirm the changed service reports healthy. In cleanup remove only that project with `down --volumes --remove-orphans`, verify no labeled containers/volumes/networks remain, remove and inspect each exact local image tag even on failure, and retain shared base images. Preserve the test exit status and report cleanup failures.
## Metrics scrape acceptance
For a Central scrape check, the source-built server image exposes GET /metrics as Prometheus text and includes ASP.NET Core instrumentation after a request. Use the same disposable Compose isolation and an explicitly empty Sentry DSN; scrape the host loopback port, assert HTTP 200 plus Prometheus # HELP/# TYPE and an ASP.NET request metric, then remove the project and verify zero containers, volumes, and networks. Remove and verify absence of that recipe's unique server image tag afterward.
When updating implementation-status documentation, verify both `src/Heimdall.Web/Program.cs` and `src/Heimdall.Agent/Program.cs` for exporter registration and `/metrics` mapping, then compare the documented signal inventory with `docs/metrics.md` and example alert rules with `deploy/prometheus/heimdall-alerts.yml`. Mark exporter implementation separately from an operator's Prometheus scrape, deployed alerting, or threshold validation; local or CI evidence does not establish those external states.
On 5 November 2026, project hmd-metrics-scrape-1793874584 reused the prior source-built OCR Central image (no code changes between that image and this scrape). It returned HTTP 200 with Prometheus exposition and ASP.NET metrics; Sentry DSN was empty and teardown verified 0/0/0. This is a partial Docker recipe result: it did not build a unique image for this scrape, so no exact-tag image removal was performed. Repeat the check with a fresh project-unique source-built tag before treating the Docker acceptance as complete. This local check does not validate a deployed Prometheus server or alert thresholds.
PostgreSQL readiness regression checks were also rerun locally on 5 November 2026: HealthControllerTests passed 5/5 with the disposable Testcontainers database. The Testcontainers reaper and database stopped after the run; unrelated labeled database services were left untouched.
-25
View File
@@ -1,25 +0,0 @@
---
name: signalr-client-lifecycle
description: Avoid blocking SignalR client teardown in Heimdall Blazor components and services.
---
# Heimdall SignalR client lifecycle
`NotificationsHubClient` is scoped to a Blazor circuit and owns a `HubConnection`. Components that use it should implement `IAsyncDisposable`, unsubscribe their event handlers, then await `Hub.DisposeAsync()`.
## Implementation
- Do not call `.Wait()`, `.Result`, or `GetAwaiter().GetResult()` on SignalR stop/dispose operations. Network shutdown can block a renderer or request thread.
- Centralize teardown in one asynchronous helper. Atomically detach the owned connection before awaiting shutdown so repeated disposal cannot dispose it twice.
- `DisposeAsync()` awaits `StopAsync` and `DisposeAsync`, handling shutdown failures independently so failed stop still attempts resource disposal.
- If compatibility requires synchronous `IDisposable`, it must return without blocking and start best-effort asynchronous cleanup. Keep `GC.SuppressFinalize(this)` on both dispose paths.
- Log cleanup failures at debug level without access tokens, URLs containing credentials, or message payloads.
## Acceptance
1. Build `src/Heimdall.Web/Heimdall.Web.csproj` with the SDK pinned by `global.json`; do not suppress analyzer warnings for blocking calls.
2. Verify the component unsubscribes handlers and awaits async disposal.
3. Run the disposable Central + PostgreSQL Compose recipe from `skills/compose-disposable-recipe/SKILL.md` with unique generated credentials, ports, project, and image tag; check `/healthz` and verify cleanup of project resources and that exact tag.
4. Treat production GlitchTip recurrence as external evidence: local build and Compose do not prove the deployed client has stopped emitting events.
See Gitea issue [#233](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues/233) for the current incident evidence.
-33
View File
@@ -1,33 +0,0 @@
---
name: signalr-documentation
description: Keep the Heimdall SignalR guide aligned with mapped routes, Hub RPC methods, broadcast events, authentication and resource authorization.
---
# Heimdall SignalR documentation workflow
Use this skill when changing a hub, SignalR authentication, subscription handling, broadcast contract or `docs/signalr-usage.md`.
## Source of truth
- Routes are mapped in `src/Heimdall.Web/Program.cs` beside the `MapHub<T>` calls.
- Client-invokable Hub methods belong inside the concrete `Hub` subclass. Nearby `*BroadcastService` methods are server-side application services and must not be documented as client RPC methods.
- Server-to-client event names and payload arguments are the `SendAsync` calls in the corresponding broadcast service.
- Authentication schemes and token extraction come from each Hub's `[Authorize]` attribute, `ConfigureJwtBearerAuthentication` in `Program.cs`, and `ApiKeyAuthenticationHandler.ResolveApiKeyFromRequest`.
- Resource-level subscriptions and reauthorization are implemented by the Hub methods, `ResourceAccess`, and `LiveSubscriptions.AuthorizedAsync`.
- Actual clients are `src/Heimdall.Agent/Services/ConfigReceiverService.cs` and `src/Heimdall.Web/Services/NotificationsHubClient.cs`.
- Hub authorization/isolation tests are under `tests/Heimdall.Web.Tests/Hubs/`.
## Update procedure
1. Read the route map and inspect the full Hub subclass before listing its public methods.
2. Record separately: auth scheme, caller join/leave methods, site/camera/Agent checks, group/channel key, broadcast messages, and payload shape.
3. Follow every broadcast message to the actual `SendAsync` call; omit planned or legacy messages that are not sent by current code.
4. Check whether recipients are filtered at subscribe time, reauthorized at send time, or both. Never describe a global group as unrestricted when a current access check exists.
5. Inspect the real clients for token providers, initial API loads, retries/reconnect behavior and fallback. Do not expose token values or imply browser cookie auth where the Hub requires JWT.
6. Confirm every documented route appears in `Program.cs`; explicitly label absent routes as planned/unmapped rather than available.
7. Link the focused tests and distinguish unit/CI evidence from proxy, network or deployment validation.
8. Review `docs/signalr-usage.md` for unsupported event names, copied pseudocode, stale security claims, and missing limits on delivery/replay.
When the SignalR or live-view summary in `docs/MASTER_SPECIFICATION.md` changes, treat that file's dated architecture sections as historical unless verified against the mapped routes and current media path. Keep the mapped hub list exact, do not describe a planned hub or peer-to-peer media path as shipped, and link readers to `docs/signalr-usage.md` and `docs/docker-compose.md` for current contracts and deployment guidance. If retaining superseded material, put a historical-status note immediately before each affected diagram, roadmap phase, UI mockup, or target-results block; a header-only disclaimer is insufficient for those detailed examples.
Do not add runtime behavior in a documentation-only change. If the audit reveals a behavior defect, create a separate Gitea issue before implementation and keep the documentation explicit about the current state.
-26
View File
@@ -1,26 +0,0 @@
---
name: site-agent-installer-ui
description: Maintain and accept the Heimdall site Agent installer panel using Pangolin's platform/method/configuration/commands interaction pattern.
---
# Site Agent installer UI
Keep the site Agent installer in `src/Heimdall.Web/Components/SiteInstallPanel.razor`. Its interaction model follows Pangolin's `OptionSelect` and `CopyTextBox`: platform tiles, platform-specific method tiles, optional configuration, then titled command blocks with an inline copy control. Keep `docs/ui-pages.md` and the connected Penpot installer frames aligned with the shipped flow; cover desktop and narrow/mobile widths plus the signed-release-unavailable state. Always open Penpot and authenticate through the Orca browser before editing the design; follow [penpot-design-sync/SKILL.md](../penpot-design-sync/SKILL.md) for the full workflow and evidence requirements.
## Project-specific rules
- Offer only Heimdall-supported platforms: Linux, Windows, and Docker. Keep method choices mapped in `AvailableMethods` and reset to that platform's sensible default in `SelectOperatingSystem`.
- Keep generated command content in the existing builders and `Commands` projection. Platform selection controls the builders; do not duplicate generated commands in markup.
- Native install commands require a latest signed release with update key, signed manifest, signature, and Agent archive assets. Docker commands additionally require verified CPU/GPU image metadata and the update key, and install the corresponding immutable `repository@sha256:digest` reference. Generated Compose uses `pull_policy: always`; generated Docker Run commands use `--pull always`. Preserve signed digest validation for Agent updates dispatched later by Central.
- Treat site tokens and generated configuration as secrets: show them only in the authenticated site's installer view and copy only after a deliberate click. Do not log generated content.
- The Linux generated installer command must not embed Central URL or site token in its text or process arguments. Prompt for both at execution time, hide token input, use protected temporary files and the installer's file-based flags, and clean those files on all exits.
- For live installer verification, use the authenticated Orca browser session. Check for the dedicated Heimdall login only in the user secret store at `~/.config/heimdall/credentials.json`; never put account passwords in this skill, repository config, shell arguments, or Orca `fill` commands. The file fallback is owner-only (`0700` directory, `0600` file) and base64-encoded, not encrypted. If it is absent, provide the user-run masked helper `~/.local/bin/store-heimdall-credentials`; do not report the credentials as persisted until that helper succeeds. If Orca has no safe autofill path, ask the user to enter the password in the visible browser.
- Keep all visible strings in `SharedResources.resx`, `SharedResources.en.resx`, and `SharedResources.fr.resx`.
- Match Pangolin's control hierarchy and compact copy affordance while using Heimdall's MudBlazor theme and supported installation choices. Keep selection and copy feedback accessible with selected styling, tooltips/aria labels, and a check icon after copying.
## Acceptance workflow
1. Run the focused component suite: `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --filter FullyQualifiedName~SiteDetailTests`.
2. Inspect rendered coverage for each platform and method, including the release-unavailable state and Docker image-unavailable state. Verify localization resources parse and `git diff --check` is clean.
3. For UI or install behavior changes, follow `compose-disposable-recipe/SKILL.md`: build from the changed source in an isolated Compose project, record exact generated image tags, then tear down only that project and verify its containers, volumes, network, and exact image tags are absent. Keep shared base images.
4. Update the linked Gitea issue with the observed results; distinguish component/local Compose evidence from real release, registry, or host installation evidence.
-32
View File
@@ -1,32 +0,0 @@
---
name: site-camera-credentials
description: Maintain the per-site camera credential API and its Site Detail and Cameras page flows.
---
# Site camera credentials
The Web client calls `api/sites/{id}/credentials` from both `SiteDetail.razor`
and `CamerasPage.razor`. Keep the GET, POST, and DELETE endpoints in
`SitesController` aligned with those client paths. Apply the existing
`Site.Read` or `Site.Write` policy and the global site resource-access filter
to every credential route.
Credential passwords are write-only. `SiteCredentialResponse` contains only
the credential ID, site ID, label, username, and timestamps; never return,
render, or log the stored password. Use the Application handlers and EF Core
through the existing application context for persistence.
## Change and acceptance workflow
1. Verify the client path and controller route agree for all three methods.
2. Test a site with no credentials and a site with a credential in both
`/sites/{id}` and `/sites/{id}/cameras`; distinguish a failed request from
a normal empty list.
3. Exercise add/list/delete with synthetic credentials. Assert the response
and list never contain the submitted password.
4. Verify unauthenticated requests are rejected and users without access to
the site receive a forbidden response.
5. Run focused Web and PostgreSQL integration tests, then follow
`compose-disposable-recipe` with an isolated Central/PostgreSQL project.
Record exact project resources and local image tags, and verify their
removal after teardown.
-17
View File
@@ -1,17 +0,0 @@
---
name: site-create-permission
description: Keep the Sites page site-creation controls aligned with Heimdall's Site.Write permission.
---
# Site creation permission in the Sites page
`AuthState` resolves role permissions into `Permissions`; check creation with `Auth.HasPermission("Site.Write")` in `SitesPage.razor`. Render both the create affordance and its overlay/dialog only when that permission exists, and route the button through a guarded open method so an event cannot set the dialog visible after access changes.
The API remains the enforcement boundary. Do not remove or weaken its `Site.Write` authorization policy as part of this UI behavior.
## Acceptance workflow
1. Add a focused bUnit test using `PageTestBase.LoginAs("Viewer")`; assert the create button and dialog fields/actions are absent after page load.
2. Keep an authorized creation test using an authorized role; exercise opening the dialog and completing a successful create response.
3. Run the focused test with `dotnet test tests/Heimdall.Web.Tests --filter FullyQualifiedName~SitesPageTests`.
4. For behavior acceptance, run the disposable Compose recipe from `skills/compose-disposable-recipe/SKILL.md`, record its isolated project/tag and cleanup evidence on the Gitea issue. UI component tests do not prove API authorization or field deployment behavior.
-14
View File
@@ -1,14 +0,0 @@
---
name: site-ntfy-creation
description: Maintain and accept the site-specific ntfy topic through Heimdall site creation.
---
# Site ntfy creation
The site topic is an optional destination used by notification delivery. Creation crosses a JSON DTO, `SitesController`, `CreateSiteCommand`, `CreateSiteHandler`, and `Site`; every layer must carry `NtfyTopic`. Keep the optional DTO parameter last/defaulted to preserve existing clients. The Sites page already sends it in `CreateSiteAsync`.
## Acceptance
1. Extend the PostgreSQL API integration test to POST a unique site name and `ntfyTopic`, then GET that site and assert `SiteResponse.NtfyTopic` equals the submitted topic. This catches JSON binding, controller mapping, and relational persistence together.
2. Run the focused integration test against the repository PostgreSQL fixture.
3. Follow `skills/compose-disposable-recipe/SKILL.md` to run a source-built disposable Compose stack. Bootstrap an isolated admin, create a site with a topic through `POST /api/sites`, read it back, and verify the topic. Remove the exact project and locally built tags and verify no project containers, volumes, or networks remain.
@@ -1,16 +0,0 @@
---
name: snapshot-gallery-responsive-filters
description: Keep the Heimdall snapshot gallery's search, event type, and load controls usable on phone widths while preserving the desktop row.
---
# Snapshot gallery responsive filters
The snapshot filter controls are owned by `src/Heimdall.Web/Components/Pages/SnapshotsPage.razor`. Keep them together in `.snapshot-filters`: its desktop grid uses three columns for search, event type, and load, and its 600 px breakpoint stacks those controls. Use `minmax(0, ...)` tracks and controls without fixed minimum widths so the page can shrink to a 320 px viewport.
## Acceptance workflow
1. Read Gitea issue [#285](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues/285) and retain its criteria for 390 px, narrower phone widths, and desktop.
2. Update the `SnapshotsPageTests` bUnit coverage to check that search, event type, and load remain inside the filter layout and that the desktop and phone grid rules remain present without the old 300 px/180 px minimums.
3. Run `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --filter FullyQualifiedName~SnapshotsPageTests`.
4. For behavior changes, follow `skills/compose-disposable-recipe/SKILL.md` and record the disposable acceptance result, cleanup verification, and any browser viewport evidence on issue #285. A bUnit structure/CSS assertion does not by itself measure rendered document width; use a browser at 390 px and 320 px when available.
5. Keep issue #285 open until its desktop, 390 px, narrow-screen, and operational acceptance evidence is complete.
-19
View File
@@ -1,19 +0,0 @@
---
name: ui-unknown-route
description: Diagnose and verify unknown-route rendering in Heimdall's interactive Blazor UI.
---
# Unknown UI routes
Heimdall renders its root `Routes` component in an interactive server circuit with prerendering disabled (`Components/App.razor`). In .NET 10, configure `Router.NotFoundPage`; the legacy `<NotFound>` fragment is not supported by Blazor Web Apps. Unknown direct browser requests have no matched endpoint and cannot start the circuit, so `Program` must render a small static HTML 404 using the same `NotFoundPage_*` resources and `/dashboard` link. Skip API, hub, health, Hangfire, non-HTML, and file-like requests so their 404 responses keep their native format.
The reusable interactive error screen is `Components/Pages/NotFound.razor`. It owns its `MainLayout`, title/body localization, and the return link to `/dashboard`. Keep it assigned as `Router.NotFoundPage` for client-side unknown navigation. Keep the static HTTP fallback's resource keys and link target aligned with this component.
When maintaining route documentation or the UI summary in `docs/specs.md`, verify current routes against the Razor `@page` directives and point detailed inventories to `docs/ui-pages.md` instead of copying a hard page count. Also check route examples in navigation and authorization guides against the current layout links and their visibility conditions. Mark removed mockups as historical and link to the replacement pages; do not preserve a retired route such as `/admin` as if it were still mapped.
## Acceptance workflow
1. In `tests/Heimdall.E2E.Tests/Pages/PageRenderTests.cs`, verify a direct unknown URL returns HTTP 404 and displays the localized title and return link in its static response.
2. Verify client-side navigation from a known route to an unknown URL (for example `Blazor.navigateTo(...)`) and confirm the same page renders.
3. Confirm `/not-found` and a known route still render. Verify API 404 responses remain API responses and do not receive the UI document, even when the request accepts HTML.
4. Run the focused Playwright E2E tests and the disposable Central + PostgreSQL Compose acceptance from `compose-disposable-recipe`. Use generated credentials, unique project/port/volume/image names, probe the route through a browser after the health check, and verify cleanup of project resources and every exact local image tag.
-28
View File
@@ -1,28 +0,0 @@
---
name: video-recording
description: Implement and validate Heimdall Agent video segments, central recording storage, access checks, ranges, and retention.
---
# Heimdall video recording
Recording is opt-in per camera (`RecordingEnabled`, default false). Agent capture is a separate FFmpeg process and only runs while the assigned camera's RTSP stream is already active. Keep RTSP values out of logs, command strings printed to logs, and failure responses.
- Bound segment duration, size, and Agent spool usage through validated `AgentOptions`; preserve incomplete uploads for retry and make completed segment identifiers stable across retries.
- Keep continuous recording (`RecordingEnabled`) and event-triggered recording (`EventRecordingEnabled`) as separate per-camera opt-ins. Event mode watches the same active Agent stream, durably records detection trigger windows under the Agent state directory with owner-only permissions, starts FFmpeg on the event, and stops 30 seconds after the latest event by default (`Agent:RecordingEventPostRollSeconds`, validated from 5 to 300 seconds). It does not record pre-roll. Disabling event mode, disabling/removing the camera assignment, or stopping its stream clears pending trigger windows and stops the process.
- Map the primary video stream and optional first audio stream into MP4 segments. Copy compatible video without re-encoding and encode optional audio as AAC at a bounded 128 kbit/s so common RTSP audio codecs are playable in browsers; feeds without audio must still record successfully. Keep privacy/operator consent in the per-camera recording opt-in.
- Upload only MP4 content from the Agent API-key boundary. Validate camera assignment at the API and application boundaries. Persist metadata through `IApplicationDbContext` and use `IRecordingStorage` as the Application port.
- Capture storage destination at upload time. Downloads must check camera access before opening the stored object. Implement byte ranges in the storage adapter rather than downloading whole objects for partial playback.
- Central quota is configured with `RECORDING_STORAGE_QUOTA_MAX_BYTES` in Compose (application key `Recordings:StorageQuota:MaxBytes`, default 1 TiB). Options are validated on startup; a segment that would exceed the aggregate persisted recording bytes receives HTTP 507 and its uploaded object is removed. The PostgreSQL advisory transaction lock makes the aggregate check atomic across simultaneous Agent uploads; upload bytes finish before acquiring the short metadata lock. Give each upload attempt a unique object key below its recording ID so a racing idempotent retry cannot overwrite the winning segment; remove the losing attempt's object even when both use the same camera.
- The CameraDetail recording list/player uses the authorized API client for metadata and same-origin `/api/recordings/{id}/content` URLs for browser Range requests. Keep the export link on that authorized endpoint and never render an arbitrary storage URL.
- Preserve the existing recording retention policy and storage-final orphan sweep. Ensure recording rows are removed only after object deletion succeeds; do not guess destinations for legacy rows without provenance.
- Add PostgreSQL tests for migration, metadata/idempotency, quota concurrency/cleanup, camera access, range translation, and retention semantics when touching those paths. Agent tests should cover bounded argument construction, defaults, and spool/config behavior.
- `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` seeds a manifest and MP4 into a temporary spool, returns 503 then 204 from a mock Central, and proves the segment remains through failure, reuses the same idempotency URL/API-key boundary, and is deleted only after success.
- For acceptance, install an EXIT cleanup trap before build/start, then build Central and Agent from this changed source with unique image tags in a disposable Compose project. Publish a synthetic RTSP stream containing H.264 video and AAC-compatible audio through MediaMTX; register and assign the Agent, enable recording, and prove a segment reaches Central through the live Agent RTSP loop. Verify ffprobe sees video and audio in a downloaded segment, scoped listing/range download, and unauthorized denial. Remove only that Compose project, confirm its containers/volumes/network are gone, and remove/verify every recipe-built local image tag.
- For quota acceptance, set `RECORDING_STORAGE_QUOTA_MAX_BYTES` to a small positive value such as 32, build Central from source, and probe `/healthz` plus `/api/auth/bootstrap-status` to prove startup validation. Run the PostgreSQL API test with concurrent uploads to prove the 507 boundary, idempotent retry, unique keys, and cleanup of over-quota/duplicate objects. Tear down the named Compose project and verify zero containers, volumes, and networks.
- Run `RecordingEventAssociationTests` against PostgreSQL: upload a segment and verify that only same-camera events in the half-open interval `[timestamp, timestamp + duration)` receive its recording ID; events at either outside boundary remain unlinked. This confirms relational translation and event/recording association without claiming event-triggered capture.
- Event recording is an independent opt-in from continuous recording. Central sends `event_recording_enabled` in the per-Agent camera configuration; the Agent persists one atomic marker per camera before attempting the HTTP event outbox write, so outbox capacity or delivery cannot suppress capture. Each qualifying event refreshes the configured post-roll (5–300 seconds, default 30). Motion, person, vehicle, unknown-person, face, and plate events can refresh that window. The Agent starts FFmpeg only while the camera stream is active and the marker remains live. Clear markers when event recording is disabled, the camera is disabled, or assignment is removed. The marker is bounded to one file per camera and survives Agent restart.
- For event-triggered acceptance, enable only `EventRecordingEnabled` through CameraDetail/API, use an assigned Agent and active synthetic RTSP stream, and prove the Agent starts capture and uploads a segment. Verify event association for both event-first and recording-first arrival. Restart the Agent during an active window and prove capture resumes from the marker; disable the toggle and prove uploads stop after configuration settles. Keep real-camera codec and timing validation separate.
- For each recording recipe, record project-unique tags for locally built Central, Agent, or helper images and remove/verify those exact tags after Compose teardown in the same EXIT trap, including on build/assertion failure. Retain shared PostgreSQL/MediaMTX base images, preserve test exit status, report cleanup failures, and never use `--rmi all` or `image prune`. Follow `skills/compose-disposable-recipe/SKILL.md`.
- Do not reuse an app/helper tag built by a different acceptance recipe. Build this recipe's changed source under fresh project-unique tags; record `local image tags: none` only for genuinely upstream-only test containers. Every run note must list the exact local tags as absent, or explicitly state no local images were built.
On 5 November 2026, disposable Compose project `hmd-event-e2e-1793899172-25617` built Central and Agent from this source with locked .NET 10 restore. The actual Agent registered from the generated site token, consumed an animated H.264/AAC RTSP stream, emitted MotionDetected, uploaded an event-only segment while continuous recording remained off, and Central associated the event with that recording. Restarting the Agent while the post-roll marker was active produced another segment; disabling event recording through the API left the recording count stable after configuration settled. PostgreSQL event-first and recording-first association tests both pass. The focused `RecordingTriggerStoreTests` passed 3/3 in SDK Compose project `hmd-trigger-unit-1793899683-6893`. Cleanup traps removed exact local tags `heimdall:hmd-event-e2e-1793899172-25617-central` and `heimdall-agent:hmd-event-e2e-1793899172-25617-agent`, verified both absent, and confirmed zero project containers, volumes, and networks; the unit-test recipe built no local images and also left zero project resources. Synthetic motion thresholds were lowered for deterministic event generation. Real-camera codecs/timing remain unvalidated.
-48
View File
@@ -1,48 +0,0 @@
---
name: vision-identity
description: Implement Heimdall's opt-in, self-hosted plate OCR and preserve the licensing/privacy gates for camera face and plate identity.
---
# Vision identity in Heimdall
Read `AGENTS.md` and the focused Gitea issue for FEAT-03/UI-02. Current API contract only supports a human-triggered OCR request with an operator-supplied JPEG/PNG plate crop. It does not infer plate boxes from video frames or recognize faces.
## Plate OCR currently implemented
- `PlateOcr:Enabled` defaults to false. Explicitly enable the on-prem Central option to offer OCR; the camera detail UI sends only the file the user selected.
- Central uses the system Tesseract executable and English LSTM data. Tesseract engine and the official `tessdata_best` model data declare Apache-2.0. Do not add other OCR or detection weights without reviewing their exact asset licenses and provenance.
- The controller requires a human principal with `Camera.Write`, camera scope, JPEG/PNG signature, configured byte limit (at most 512 KiB), and rate limits. OCR rejects malformed, oversized, or over-4-megapixel crops and times out after a bounded interval.
- OCR runs on the Heimdall Central host. The image is written to a random temporary path and deleted in `finally`; do not log the crop, extracted text, embedding, or raw image path.
- Store only the normalized plate candidate, confidence, and a `LicensePlateDetected` event. The API may return a unique exact vehicle/person as a suggestion, but it does not persist identity links during OCR. `CameraDetail` presents the suggestion for operator review; the operator must explicitly confirm a vehicle. The confirmation API requires a human principal with both camera and vehicle write permissions, verifies access to the camera, the event-to-observation association, and an exact normalized plate match, and writes the observation/event links together. Never treat OCR output as verified identity.
- OCR observations remain unassigned until a human confirms an association; unassigned plate rows are purged after 30 days. `CleanupLicensePlatesJob` also removes `LicensePlateDetected` events older than 30 days, including their label and metadata. If an event has stored snapshots, it deletes those objects from the exact captured destination before deleting the database row. Events with missing/incomplete storage provenance are retained with a warning rather than deleting from a guessed destination. Vehicle-owned plate records remain governed by their explicit vehicle lifecycle. Keep the wider privacy review open before production enablement.
## Face-model gate
ONNX Runtime is already used by the Agent and is MIT licensed. A model runtime license does not grant rights to a particular model's weights or training data. InsightFace's model-zoo documentation restricts its distributed pretrained weights to non-commercial research. ONNX Model Zoo's ArcFace/UltraFace listing points to sourced models but does not establish one blanket weight/data license. Do not bundle SFace, ArcFace, YuNet, or plate-detector weights unless the exact asset and training-data rights are reviewed. An operator-provided model also needs a documented tensor/preprocessing contract, stable model ID stored with enrollments, explicit opt-in, deletion/retention semantics, and representative accuracy testing before face matches can create events.
Official sources reviewed:
- [Tesseract engine license and command-line formats](https://github.com/tesseract-ocr/tesseract)
- [Official `tessdata_best` license](https://github.com/tesseract-ocr/tessdata_best)
- [Official `tessdata` language-data license](https://github.com/tesseract-ocr/tessdata)
- [Official Tesseract data-file compatibility guidance](https://github.com/tesseract-ocr/tessdoc/blob/main/Data-Files.md)
- [ONNX Runtime repository license](https://github.com/microsoft/onnxruntime)
- [ONNX Model Zoo sourcing and model catalog](https://github.com/onnx/models/blob/main/README.md)
- [InsightFace model-zoo license statement](https://github.com/deepinsight/insightface/blob/master/python-package/docs/model_zoo.md)
## Human confirmation workflow
- Keep mismatches and ambiguous candidate lists unlinked until an operator selects a vehicle and confirms.
- Confirm with the observation ID, event ID and selected vehicle ID; reject anonymous or camera-scoped requests, mismatched plates, unrelated events, and conflicting existing links.
- Preserve the matching UI/API behavior with component/controller tests and handler tests. API authorization and camera scope stay at the Web boundary; the application handler independently checks camera access before persistence.
## Acceptance
1. Local targeted tests passed: `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, `PlateRecognitionControllerTests` 1/1. These unit/component tests do not replace a browser-driven UI test.
2. Compose source build passed in isolated project `hmd-plate-20261105094933-31487`. It used a generated database/JWT credential set, unused `127.0.0.1` ports, unique network/image/project, and project-scoped volumes. `PlateOcr` was enabled only through a temporary Compose override. The `synthetic-plate.png` fixture returned `AB-123-CD` with Tesseract confidence `0.912` through the authenticated multipart API; `/api/events` page 1 contained the created event. The historical entry does not record removal and exact-tag absence verification for the image; treat this recipe's image cleanup as unverified and repeat it before relying on that portion of acceptance.
3. The invalid JPEG signature returned HTTP 400. PostgreSQL inspection confirmed the plate observation and history event were persisted with no Person/Vehicle link and no event snapshot. The random OCR temp path was absent after processing.
4. `down --volumes --remove-orphans` cleanup verified `containers=0 volumes=0 networks=0`. The historical record for this bootstrap does not name a locally built image tag or document an exact image absence check; treat image cleanup as unverified and repeat it before relying on that part of the acceptance. The first admin bootstrap also called the existing HaveIBeenPwned breach checker with a generated synthetic password; that code uses k-anonymity, so the Compose exercise was not fully offline. No real password, camera, image, or release secret was used.
5. Human confirmation acceptance passed in source-built disposable project `hmd-plate-link-1793880442-bff1ca`: the synthetic OCR crop returned `AB-123-CD` at confidence 0.912; a vehicle with another plate was rejected with HTTP 422; PostgreSQL showed both links null before confirmation; explicit confirmation returned 200 and both `license_plates.VehicleId` and `camera_events.VehicleId` were populated; anonymous confirmation returned 401. Cleanup verified zero containers, volumes and networks and removed/verified absence of the exact `heimdall:hmd-plate-link-1793880442-bff1ca-central` image tag. Two earlier recipe attempts had harness-only readiness/SQL identifier mistakes; each exact project and tag was cleaned and absence checked.
6. Keep assigning the locally built Central image a unique project tag and remove/verify that exact tag on every recipe completion, including failure paths. Retain shared .NET/ASP.NET base images and never use broad image pruning.
7. These acceptances cover one synthetic crop and the API persistence/confirmation path only. They do not establish OCR accuracy in real scenes, video plate detection, face recognition, browser-driven upload behavior, camera hardware behavior, or the suitability of the retention period under an external privacy review.
8. Plate-event retention is covered by `CleanupLicensePlatesJobTests` (SQLite: expired plate event removed, recent plate and unrelated events retained; captured snapshot objects removed first; storage deletion failure retains the event) and `PlateEventRetentionPostgresTests` (PostgreSQL EF translation/deletion). The disposable Compose project `hmd-plate-retention-pg-1793885533-16210` ran the PostgreSQL test from the mounted changed source with locked restore, generated credentials, and project-scoped database/NuGet volumes; result 1/1. Teardown removed and verified zero project containers/volumes/networks. The recipe builds no Heimdall image; shared PostgreSQL/SDK base images are retained. This validates the local retention mechanics, not the external privacy policy or any production retention requirement.
-137
View File
@@ -1,137 +0,0 @@
# Live WebRTC implementation and acceptance
The current vertical provides Agent RTSP re-publishing, Central camera-scoped
Data Protection tickets and MediaMTX auth, and a camera detail WHEP player.
`FEAT-01` stays open until the disposable synthetic acceptance below passes
and external network behavior is measured.
## Required architecture
- Keep camera assignment and stream lifecycle in Agent. Only an enabled camera
present in the current Central assignment snapshot may be published. Stop the
publisher when assignment, enablement, or Agent lifetime ends. A source URL
change for the same camera must also stop the old publisher and start one from
the new configuration before synchronization is considered complete.
- Use MediaMTX as the WebRTC/WHEP media server. Agent publishes the camera's
browser-compatible H.264 stream to a camera-ID path. The relay passes video
through and optionally maps the first audio track, transcoding it to Opus for
WebRTC browser compatibility; a source without audio must still publish.
Prefer passthrough when the source video codec is compatible; otherwise make
video transcoding an explicit, bounded option. PTZ remains separate.
- Central issues random, short-lived, purpose-separated publish and read claims
scoped to one camera and one action. Protect claims with the shared Heimdall
Data Protection key ring. MediaMTX HTTP auth must validate exact path, action,
protocol, expiry, Agent assignment for publish, and current user camera rights
for read. Never put RTSP credentials, Central API keys, or reusable TURN
credentials in browser-visible URLs or logs.
- Browser obtains a read session from the authenticated camera API and performs
WHEP with that short-lived bearer token. ICE servers and public WHEP URL must
come from deployment configuration, never source-code hostnames. Do not issue
static TURN credentials to the browser.
- Bound simultaneous Agent publishers and viewers, request duration, retries,
FFmpeg process count, and session lifetime. Ensure cancellation/config changes
reap child processes and release permits.
## Source-change lifecycle acceptance
`LiveCameraRelayService` compares the effective RTSP source configured for each
camera (substream when configured, otherwise primary stream) with the source attached to its running FFmpeg relay. If the source
changes while the CameraId remains assigned and enabled, synchronization stops
and disposes the old process before starting a relay with the updated source.
The normal synchronization interval is five seconds.
Run `bash skills/webrtc-live/source-change-acceptance.sh` for the focused
disposable Compose acceptance. It packages tracked and non-ignored source into
an isolated .NET 10 SDK container and runs the Agent relay tests, including the
same-CameraId primary and substream source changes, unchanged-source stability, renewal-boundary,
child-process stop, and log-redaction assertions. It publishes no host ports,
uses no persistent volumes or deployment credentials, builds no local image,
and keeps only the upstream SDK image. The EXIT trap tears down the unique
Compose project and verifies its containers, volumes, and network are absent.
## Implementation references
Use MediaMTX's maintained documentation as the protocol reference:
- [WHEP/WebRTC read](https://mediamtx.org/docs/read/webrtc)
- [HTTP authentication callbacks](https://mediamtx.org/docs/features/authentication)
- [ICE, TURN, codec and latency details](https://mediamtx.org/docs/features/webrtc-specific-features)
- [Configuration reference](https://mediamtx.org/docs/references/configuration-file)
- [RTSP camera/source behavior](https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/08-rtsp-cameras-and-servers.md)
- [MediaMTX license](https://github.com/bluenviron/mediamtx/blob/main/LICENSE)
Use H.264 without B-frames for browser compatibility and latency. Validate
actual negotiation in browsers; a successful RTSP publish does not prove WHEP.
## User-facing documentation source of truth
When updating `docs/specs.md` or `docs/ui-pages.md`, trace each shipped claim to
the current implementation:
- The camera detail route and embedded Watch/Stop controls are in
`src/Heimdall.Web/Components/Pages/CameraDetail.razor`; the browser module is
`src/Heimdall.Web/wwwroot/js/live-view.js`. Do not document a separate
`/cameras/{id}/live` route or rename the module to `liveView.js`.
- When documenting role visibility in `docs/auth-roles.md`, use the camera detail route for the embedded live-view and trace session permission to `LiveMediaController`; the endpoint requires `Camera.Read` plus camera-level access, not a separate `Camera.Live` endpoint policy.
- Session creation/release, authorization, short-lived tickets, WHEP URL and
ICE configuration are in `src/Heimdall.Web/Controllers/LiveMediaController.cs`.
- Agent RTSP publication and FFmpeg lifecycle are in
`src/Heimdall.Agent/Services/LiveCameraRelayService.cs`.
- Describe the current media path as Agent RTSP(S) publication to MediaMTX and
browser WHEP/WebRTC playback. SignalR hubs carry no video media or live-view
SDP/ICE signaling.
- Separate implementation and synthetic acceptance evidence from real camera,
external ICE/TURN and latency measurements. Track those external results in
#161; keep the 503/configuration investigation in #341.
- Before preserving a proposed control or performance target in a UI mockup,
mark it as planned and verify it is not presented as shipped behavior.
## Required acceptance
Run from changed source in an isolated disposable Compose project with unique
project name, generated credentials, ports and volumes. The optional
`docker/docker-compose.webrtc-test.yml` starts a local-only generated H.264
camera feed. Use `docker/docker-compose.webrtc-local-test.yml` plus
`docker/docker-compose.webrtc-test.yml` with the core `docker-compose.yml` in one
unique project. Set unique generated database/JWT credentials, loopback ports,
`HEIMDALL_NETWORK_NAME`, `HEIMDALL_MEDIAMTX_AUTH_URL`, WHEP/publish URLs, and the
Central browser origin in an env file outside the repository. Start Central,
MediaMTX and the synthetic feed first; bootstrap the first admin and site, then
place the generated synthetic site token in the disposable env file and start
the Agent. Configure its assigned camera against the host loopback RTSP port. Do not depend on a physical camera. Verify all of the following:
1. An assigned Agent receives only its assigned camera's short-lived publish
credential and publishes synthetic H.264 to that camera path.
2. An authorized user obtains a short-lived read claim and a browser-compatible
WHEP session; the browser receives decoded frames. With synthetic audio,
prove the browser negotiates audio and video; playback starts muted for
autoplay compatibility and the native controls allow the viewer to enable it.
3. An unassigned Agent, cross-camera claim, wrong action/path/protocol, expired
token, and user without camera access are rejected.
4. Disable/reassign camera, stop Agent, end viewer, and expire claim; verify the
matching processes/sessions terminate and resource counts return to baseline.
5. Logs and API errors contain no credentials, raw tokens, RTSP URLs, or ICE
secrets. Verify configured ICE/TURN candidate behavior separately.
6. Install an EXIT trap before the first image build/start. Tear down only that
Compose project with volumes/orphans, then verify its containers, volumes
and network are gone. Independently remove and verify absence of every
project-unique local image tag built by this recipe (Central, Agent, or
helper), even after a failed build/assertion; preserve shared MediaMTX and
other upstream base images. Preserve the test exit status and report cleanup
failures. Do not use `--rmi all` or broad image-prune commands.
For this recipe the locally built tags are Central and Agent; record their
exact project-unique values before building. The synthetic RTSP source uses
the upstream MediaMTX and FFmpeg images, which remain installed. The cleanup
record is complete only after both local tags have been removed and an
exact-tag `docker image inspect` confirms absence.
Record LAN browser and external TURN runs independently. Focused API/Web ticket/session tests (7/7) and Agent relay tests pass. On 5 November 2026, disposable project `hmd-wrtc-75d1f49f` was built from this source with a synthetic H.264 RTSP source. Central bootstrap/site creation, Agent registration and camera assignment passed. Headless Chromium ran the actual `live-view.js` WHEP path and decoded a 640×360 frame (one video track); WHEP resource deletion returned 200 and Central session release 204. The MediaMTX auth callback accepted the valid read ticket and rejected altered action/path/protocol and a forged ticket (401); unknown camera access was denied. The API disable action stopped the scoped Agent publisher process from one to zero. Log scans found no admin/session/site credentials or RTSP source URL. The run exposed and fixed MediaMTX env interpolation and Docker ICE port mapping in the local recipe. The project was torn down with `down --volumes --remove-orphans`; project-scoped checks found zero containers, volumes and networks, and temporary secrets were deleted. Its historical record lacks exact-tag image absence checks, so repeat this recipe under the cleanup requirements above before treating cleanup as fully verified. Physical camera, LAN, external TURN and PTZ remain unvalidated. Synthetic audio codec and browser-track acceptance is recorded separately below; keep FEAT-01 open for its remaining external items.
## Synthetic audio acceptance
Run a disposable Compose source build plus a synthetic H.264+sine RTSP publisher. The source-built Agent tests must assert the relay command maps `0:a:0?`, converts audio to Opus, and does not disable audio. The Compose stream must be pulled from the relay and inspected to confirm H.264 video and Opus audio. Also run the authenticated WHEP browser flow and assert its media stream contains both tracks; no physical camera or external TURN claim follows from this recipe. Build app images with unique tags and remove/verify those exact tags in the same EXIT cleanup trap, or explicitly record `local image tags: none` for SDK/upstream-only test runs.
`LiveViewTests.Live_view_negotiates_audio_and_video_and_starts_muted_for_autoplay` uses its fake peer by default for an isolated UI contract test. For the real-media path, set `HEIMDALL_TEST_LIVE_WHEP_URL` to the disposable MediaMTX `/path/whep` endpoint before running the same test. It then uses Chromium's real RTCPeerConnection and waits for a decoded video frame (`videoWidth > 0`) plus a live audio track. Pair this with a project-isolated MediaMTX service and synthetic H.264/Opus publisher, configured with a loopback WHEP port, a matching loopback ICE UDP candidate, and wildcard origins only on the throwaway test server. The test still mocks only Central's short-lived read-session response; the earlier Central permission/ticket test remains the evidence for that boundary. Teardown must remove and verify all project resources and any exact local image tags.
On 5 November 2026, disposable project `hmd-whep-audio-1793905588-381987` ran MediaMTX plus an animated 640×360 H.264 and 48 kHz sine/Opus publisher. The source-built Web/E2E assembly used the real `live-view.js` and Chromium against `http://127.0.0.1:<ephemeral>/live/whep`; `LiveViewTests` passed 1/1 with a decoded video frame, live audio track, and muted autoplay. Central's session response was stubbed, so this proves browser/media negotiation and decoding, not production auth or external ICE/TURN. Cleanup verified zero project containers, volumes and networks; no local images were built and the temporary Compose file was removed.