diff --git a/skills/video-recording/SKILL.md b/skills/video-recording/SKILL.md
index 6d09daa..a2231ea 100644
--- a/skills/video-recording/SKILL.md
+++ b/skills/video-recording/SKILL.md
@@ -8,6 +8,7 @@ description: Implement and validate Heimdall Agent video segments, central recor
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.
@@ -19,7 +20,9 @@ Recording is opt-in per camera (`RecordingEnabled`, default false). Agent captur
- 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, refreshed through 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.
-Current product gaps are event-trigger capture and validation against real cameras/codecs. Keep FEAT-02 open until these are addressed and validated.
+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.
diff --git a/src/Heimdall.Agent/AgentOptions.cs b/src/Heimdall.Agent/AgentOptions.cs
index 98eab52..c70d437 100644
--- a/src/Heimdall.Agent/AgentOptions.cs
+++ b/src/Heimdall.Agent/AgentOptions.cs
@@ -55,6 +55,10 @@ public sealed class AgentOptions
[Range(5, 300)]
public int RecordingSegmentSeconds { get; init; } = 60;
+ /// Seconds to keep event-triggered capture running after the latest detection.
+ [Range(5, 300)]
+ public int RecordingEventPostRollSeconds { get; init; } = 30;
+
/// Upper bound for queued completed recordings kept locally while Central is unavailable.
[Range(typeof(long), "16777216", "107374182400")]
public long RecordingSpoolMaxBytes { get; init; } = 1_073_741_824;
diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs
index 5185838..d4c4719 100644
--- a/src/Heimdall.Agent/Program.cs
+++ b/src/Heimdall.Agent/Program.cs
@@ -132,6 +132,7 @@ builder.Services.AddHostedService(sp => sp.GetRequi
builder.Services.AddSingleton();
builder.Services.AddSingleton(sp => sp.GetRequiredService());
builder.Services.AddHostedService(sp => sp.GetRequiredService());
+builder.Services.AddSingleton();
builder.Services.AddSingleton();
builder.Services.AddSingleton();
builder.Services.AddSingleton();
diff --git a/src/Heimdall.Agent/Services/AgentCameraConfig.cs b/src/Heimdall.Agent/Services/AgentCameraConfig.cs
index 0603193..3f6d1b4 100644
--- a/src/Heimdall.Agent/Services/AgentCameraConfig.cs
+++ b/src/Heimdall.Agent/Services/AgentCameraConfig.cs
@@ -12,7 +12,8 @@ public sealed record AgentCameraConfig(
string? SubRtspUrl,
bool Enabled,
Heimdall.Application.DTOs.DetectionProfileDto? DetectionProfile = null,
- bool RecordingEnabled = false)
+ bool RecordingEnabled = false,
+ bool EventRecordingEnabled = false)
{
///
/// URL used for AI capture: the low-res sub-stream when available,
diff --git a/src/Heimdall.Agent/Services/AgentRecordingService.cs b/src/Heimdall.Agent/Services/AgentRecordingService.cs
index ad0dba2..3ffdbca 100644
--- a/src/Heimdall.Agent/Services/AgentRecordingService.cs
+++ b/src/Heimdall.Agent/Services/AgentRecordingService.cs
@@ -21,12 +21,14 @@ public sealed class AgentRecordingService : BackgroundService
private readonly AgentOptions _options;
private readonly IHttpClientFactory _clients;
private readonly ILogger _logger;
+ private readonly RecordingTriggerStore _triggers;
private readonly Dictionary _sessions = [];
private readonly SemaphoreSlim _lifecycle = new(1, 1);
private string _spoolRoot = string.Empty;
public AgentRecordingService(CameraConfigStore cameras, CameraStreamService streams, AgentState state,
- IOptions options, IHttpClientFactory clients, ILogger logger)
+ IOptions options, IHttpClientFactory clients, ILogger logger,
+ RecordingTriggerStore? triggers = null)
{
_cameras = cameras;
_streams = streams;
@@ -34,6 +36,7 @@ public sealed class AgentRecordingService : BackgroundService
_options = options.Value;
_clients = clients;
_logger = logger;
+ _triggers = triggers ?? new RecordingTriggerStore(options);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
@@ -77,31 +80,45 @@ public sealed class AgentRecordingService : BackgroundService
try
{
var configured = _cameras.Cameras.ToDictionary(c => c.CameraId);
+ await _triggers.ClearExceptAsync(configured.Values
+ .Where(camera => camera.Enabled && camera.EventRecordingEnabled)
+ .Select(camera => camera.CameraId).ToHashSet(), ct).ConfigureAwait(false);
foreach (var (cameraId, session) in _sessions.ToArray())
{
- if (!configured.TryGetValue(cameraId, out var camera) || !camera.Enabled || !camera.RecordingEnabled ||
+ if (!configured.TryGetValue(cameraId, out var camera) || !camera.Enabled ||
camera.RtspUrl != session.RtspUrl || !_streams.IsStreamActive(cameraId) || session.Process.HasExited)
+ {
+ await StopSessionCoreAsync(cameraId, session, ct).ConfigureAwait(false);
+ continue;
+ }
+ if (!camera.RecordingEnabled && !(camera.EventRecordingEnabled &&
+ (await _triggers.GetStatusAsync(cameraId, ct).ConfigureAwait(false)).IsActive))
await StopSessionCoreAsync(cameraId, session, ct).ConfigureAwait(false);
}
- foreach (var camera in configured.Values.Where(c => c.Enabled && c.RecordingEnabled &&
+ foreach (var camera in configured.Values.Where(c => c.Enabled &&
+ (c.RecordingEnabled || c.EventRecordingEnabled) &&
!string.IsNullOrWhiteSpace(c.RtspUrl)))
{
- if (_streams.IsStreamActive(camera.CameraId) && !_sessions.ContainsKey(camera.CameraId))
- StartSession(camera);
+ var triggerStatus = camera.EventRecordingEnabled
+ ? await _triggers.GetStatusAsync(camera.CameraId, ct).ConfigureAwait(false)
+ : RecordingTriggerStore.RecordingTriggerStatus.Inactive;
+ var shouldRecord = camera.RecordingEnabled || triggerStatus.IsActive;
+ if (shouldRecord && _streams.IsStreamActive(camera.CameraId) && !_sessions.ContainsKey(camera.CameraId))
+ StartSession(camera, camera.RecordingEnabled ? null : triggerStatus.FirstTriggeredAtUtc);
}
}
finally { _lifecycle.Release(); }
}
- private void StartSession(AgentCameraConfig camera)
+ private void StartSession(AgentCameraConfig camera, DateTime? triggeredAtUtc)
{
var cameraRoot = Path.Combine(_spoolRoot, camera.CameraId.ToString("N"));
var sessionDirectory = Path.Combine(cameraRoot, Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(sessionDirectory);
if (OperatingSystem.IsLinux())
File.SetUnixFileMode(sessionDirectory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
- var startedAt = DateTime.UtcNow;
+ var startedAt = triggeredAtUtc ?? DateTime.UtcNow;
File.WriteAllText(Path.Combine(sessionDirectory, "started-at.txt"), startedAt.ToString("O", CultureInfo.InvariantCulture));
var startInfo = CreateStartInfo(_options.RecordingFfmpegPath, camera.RtspUrl!, sessionDirectory,
_options.RecordingSegmentSeconds);
diff --git a/src/Heimdall.Agent/Services/CameraConfigStore.cs b/src/Heimdall.Agent/Services/CameraConfigStore.cs
index fb94add..b48b32b 100644
--- a/src/Heimdall.Agent/Services/CameraConfigStore.cs
+++ b/src/Heimdall.Agent/Services/CameraConfigStore.cs
@@ -103,6 +103,7 @@ public sealed class CameraConfigStore
"sub_rtsp" => existing with { SubRtspUrl = value },
"enabled" => existing with { Enabled = ParseBool(value) },
"recording_enabled" => existing with { RecordingEnabled = ParseBool(value) },
+ "event_recording_enabled" => existing with { EventRecordingEnabled = ParseBool(value) },
"profile" => existing with { DetectionProfile = ParseProfile(value) },
_ => throw new ArgumentException($"Unknown camera configuration field: {field}", nameof(field))
};
diff --git a/src/Heimdall.Agent/Services/DetectionReporterService.cs b/src/Heimdall.Agent/Services/DetectionReporterService.cs
index 089ce48..f1406f9 100644
--- a/src/Heimdall.Agent/Services/DetectionReporterService.cs
+++ b/src/Heimdall.Agent/Services/DetectionReporterService.cs
@@ -46,6 +46,8 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo
private readonly AgentState _state;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger _logger;
+ private readonly CameraConfigStore? _cameras;
+ private readonly RecordingTriggerStore? _recordingTriggers;
private readonly string _databasePath;
private readonly PooledDbContextFactory _contextFactory;
private readonly ConcurrentDictionary<(Guid CameraId, EventType Type), DateTime> _lastQueued = new();
@@ -72,10 +74,23 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo
IHttpClientFactory httpClientFactory,
ILogger logger,
IOptions options)
+ : this(state, httpClientFactory, logger, options, null, null)
+ {
+ }
+
+ public DetectionReporterService(
+ AgentState state,
+ IHttpClientFactory httpClientFactory,
+ ILogger logger,
+ IOptions options,
+ CameraConfigStore? cameras,
+ RecordingTriggerStore? recordingTriggers)
{
_state = state;
_httpClientFactory = httpClientFactory;
_logger = logger;
+ _cameras = cameras;
+ _recordingTriggers = recordingTriggers;
var stateDirectory = options.Value.StateDirectory
?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory());
_databasePath = Path.Combine(stateDirectory, "agent-events.db");
@@ -118,6 +133,21 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo
if (!queued)
return false;
+ if (ShouldTriggerRecording(type) && _cameras?.Cameras.Any(camera =>
+ camera.CameraId == cameraId && camera.EventRecordingEnabled) == true && _recordingTriggers is not null)
+ {
+ try
+ {
+ await _recordingTriggers.RegisterAsync(cameraId, request.OccurredAt ?? now, ct).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
+ catch (Exception ex)
+ {
+ _logger.LogWarning("Could not persist event recording trigger for camera {CameraId} (error type {ErrorType})",
+ cameraId, ex.GetType().Name);
+ }
+ }
+
if (type != EventType.ManualSnapshot) _lastQueued[key] = now;
try { _wake.Release(); }
catch (SemaphoreFullException) { }
@@ -438,6 +468,10 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo
or System.Net.HttpStatusCode.Gone
or System.Net.HttpStatusCode.UnprocessableEntity;
+ private static bool ShouldTriggerRecording(EventType type) => type is
+ EventType.MotionDetected or EventType.PersonDetected or EventType.VehicleDetected or
+ EventType.UnknownPerson or EventType.FaceRecognized or EventType.LicensePlateDetected;
+
/// Map a detection label to its event category.
public static EventType? MapDetectionToEventType(string label)
{
diff --git a/src/Heimdall.Agent/Services/RecordingTriggerStore.cs b/src/Heimdall.Agent/Services/RecordingTriggerStore.cs
new file mode 100644
index 0000000..eaacd3e
--- /dev/null
+++ b/src/Heimdall.Agent/Services/RecordingTriggerStore.cs
@@ -0,0 +1,122 @@
+using System.Text.Json;
+using Heimdall.Domain.Entities;
+using Heimdall.Domain.Enums;
+using Microsoft.Extensions.Options;
+
+namespace Heimdall.Agent.Services;
+
+/// Durable, bounded post-event windows used to start event-only recording after Agent restarts.
+public sealed class RecordingTriggerStore : IDisposable
+{
+ private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
+ private readonly string _root;
+ private readonly TimeSpan _postRoll;
+ private readonly SemaphoreSlim _gate = new(1, 1);
+
+ public RecordingTriggerStore(IOptions options)
+ {
+ var stateDirectory = options.Value.StateDirectory ??
+ (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory());
+ _root = Path.GetFullPath(Path.Combine(stateDirectory, "recording-triggers"));
+ _postRoll = TimeSpan.FromSeconds(options.Value.RecordingEventPostRollSeconds);
+ }
+
+ public async Task RegisterAsync(Guid cameraId, DateTime occurredAt, CancellationToken ct = default)
+ {
+ if (cameraId == Guid.Empty) throw new ArgumentException("Camera ID is required", nameof(cameraId));
+ var normalizedOccurredAt = CameraEvent.NormalizeOccurredAt(occurredAt);
+ var directory = Path.Combine(_root, cameraId.ToString("N"));
+ var path = Path.Combine(directory, "trigger.json");
+ var temporaryPath = Path.Combine(directory, "trigger.json.tmp");
+ await _gate.WaitAsync(ct).ConfigureAwait(false);
+ try
+ {
+ Directory.CreateDirectory(directory);
+ if (OperatingSystem.IsLinux())
+ {
+ File.SetUnixFileMode(_root, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
+ File.SetUnixFileMode(directory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
+ }
+ var previous = await ReadTriggerAsync(path, ct).ConfigureAwait(false);
+ var trigger = new RecordingTrigger(
+ previous is { } existing && existing.ExpiresAtUtc > DateTime.UtcNow
+ ? Min(existing.OccurredAtUtc, normalizedOccurredAt)
+ : normalizedOccurredAt,
+ DateTime.UtcNow.Add(_postRoll));
+ await using (var stream = new FileStream(temporaryPath, FileMode.Create, FileAccess.Write,
+ FileShare.None, 4096, FileOptions.Asynchronous | FileOptions.WriteThrough))
+ await JsonSerializer.SerializeAsync(stream, trigger, Json, ct).ConfigureAwait(false);
+ File.Move(temporaryPath, path, overwrite: true);
+ }
+ finally
+ {
+ if (File.Exists(temporaryPath)) File.Delete(temporaryPath);
+ _gate.Release();
+ }
+ }
+
+ public async Task GetStatusAsync(Guid cameraId, CancellationToken ct = default)
+ {
+ var directory = Path.Combine(_root, cameraId.ToString("N"));
+ if (!Directory.Exists(directory)) return RecordingTriggerStatus.Inactive;
+ await _gate.WaitAsync(ct).ConfigureAwait(false);
+ try
+ {
+ var now = DateTime.UtcNow;
+ var path = Path.Combine(directory, "trigger.json");
+ var trigger = await ReadTriggerAsync(path, ct).ConfigureAwait(false);
+ if (trigger is null || trigger.ExpiresAtUtc <= now)
+ {
+ try { File.Delete(path); }
+ catch (IOException) { }
+ return RecordingTriggerStatus.Inactive;
+ }
+ return new RecordingTriggerStatus(trigger.OccurredAtUtc, trigger.ExpiresAtUtc);
+ }
+ finally { _gate.Release(); }
+ }
+
+ private static async Task ReadTriggerAsync(string path, CancellationToken ct)
+ {
+ if (!File.Exists(path)) return null;
+ try
+ {
+ await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
+ 4096, FileOptions.Asynchronous | FileOptions.SequentialScan);
+ return await JsonSerializer.DeserializeAsync(stream, Json, ct).ConfigureAwait(false);
+ }
+ catch (JsonException) { return null; }
+ catch (IOException) { return null; }
+ }
+
+ private static DateTime Min(DateTime left, DateTime right) => left <= right ? left : right;
+
+ public async Task ClearExceptAsync(IReadOnlySet enabledCameraIds, CancellationToken ct = default)
+ {
+ if (!Directory.Exists(_root)) return;
+ await _gate.WaitAsync(ct).ConfigureAwait(false);
+ try
+ {
+ foreach (var directory in Directory.EnumerateDirectories(_root))
+ {
+ ct.ThrowIfCancellationRequested();
+ if (Guid.TryParseExact(Path.GetFileName(directory), "N", out var cameraId) &&
+ enabledCameraIds.Contains(cameraId)) continue;
+ try { Directory.Delete(directory, recursive: true); }
+ catch (IOException) { }
+ catch (UnauthorizedAccessException) { }
+ }
+ }
+ finally { _gate.Release(); }
+ }
+
+ public sealed record RecordingTriggerStatus(DateTime? FirstTriggeredAtUtc, DateTime? ActiveUntilUtc)
+ {
+ public static RecordingTriggerStatus Inactive { get; } = new(null, null);
+ public bool IsActive => ActiveUntilUtc is { } activeUntil && activeUntil > DateTime.UtcNow;
+ }
+
+ private sealed record RecordingTrigger(DateTime OccurredAtUtc, DateTime ExpiresAtUtc);
+
+ public void Dispose() => _gate.Dispose();
+}
diff --git a/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs b/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs
index 30f1abc..467bb11 100644
--- a/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs
+++ b/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs
@@ -53,5 +53,5 @@ public class CreateCameraCommandHandler : IRequestHandler>;
+ bool? RecordingEnabled = null,
+ bool? EventRecordingEnabled = null) : IRequest>;
public class UpdateCameraCommandHandler : IRequestHandler>
{
@@ -50,6 +51,7 @@ public class UpdateCameraCommandHandler : IRequestHandlerCamera response including all discovery and stream test metadata.
public record CameraResponse(
@@ -47,4 +48,5 @@ public record CameraResponse(
bool HasAudio,
bool HasMotionDetection,
DateTime CreatedAt,
- bool RecordingEnabled = false);
+ bool RecordingEnabled = false,
+ bool EventRecordingEnabled = false);
diff --git a/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs b/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs
index 32d698e..8a6c59f 100644
--- a/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs
+++ b/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs
@@ -62,6 +62,17 @@ public class CreateEventHandler : IRequestHandler recording.CameraId == request.CameraId &&
+ occurredAt >= recording.Timestamp &&
+ occurredAt < recording.Timestamp.AddSeconds(recording.DurationSeconds))
+ .OrderBy(recording => recording.Timestamp)
+ .Select(recording => (Guid?)recording.Id)
+ .FirstOrDefaultAsync(ct)
+ .ConfigureAwait(false);
+ if (matchingRecordingId.HasValue)
+ ev.AssignRecording(matchingRecordingId.Value);
+
_context.CameraEvents.Add(ev);
try
{
diff --git a/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs b/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs
index 92f12bd..2c072da 100644
--- a/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs
+++ b/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs
@@ -45,7 +45,7 @@ public class GetCamerasByGroupHandler : IRequestHandler>.Success(
diff --git a/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs b/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs
index d6a95c8..bafb172 100644
--- a/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs
+++ b/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs
@@ -33,9 +33,9 @@ public sealed class UploadRecordingHandler(
var camera = await db.Cameras.AsNoTracking()
.Where(c => c.Id == request.CameraId && !c.IsDeleted)
- .Select(c => new { c.Id, c.AgentId, c.StoragePolicyId, c.RecordingEnabled })
+ .Select(c => new { c.Id, c.AgentId, c.StoragePolicyId, c.RecordingEnabled, c.EventRecordingEnabled })
.SingleOrDefaultAsync(ct).ConfigureAwait(false);
- if (camera?.AgentId != request.AgentId || !camera.RecordingEnabled)
+ if (camera?.AgentId != request.AgentId || !(camera.RecordingEnabled || camera.EventRecordingEnabled))
return ServiceResult.NotFound("Camera not found");
var existing = await db.Recordings.AsNoTracking()
diff --git a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs
index 5b97fd2..2e847b7 100644
--- a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs
+++ b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs
@@ -122,6 +122,7 @@ public class GetEffectiveAgentConfigQueryHandler
config[$"{prefix}.sub_rtsp"] = camera.SubRtspUrl;
config[$"{prefix}.enabled"] = camera.Status != CameraStatus.Disabled ? "true" : "false";
config[$"{prefix}.recording_enabled"] = camera.RecordingEnabled ? "true" : "false";
+ config[$"{prefix}.event_recording_enabled"] = camera.EventRecordingEnabled ? "true" : "false";
}
return ServiceResult>.Success(config);
diff --git a/src/Heimdall.Domain/Entities/Camera.cs b/src/Heimdall.Domain/Entities/Camera.cs
index fac65dd..63ff4b5 100644
--- a/src/Heimdall.Domain/Entities/Camera.cs
+++ b/src/Heimdall.Domain/Entities/Camera.cs
@@ -15,6 +15,8 @@ public class Camera : Entity, IAuditableEntity, ISoftDeletable
public CameraStatus Status { get; private set; } = CameraStatus.Disabled;
/// Whether the assigned Agent stores bounded video segments for this camera.
public bool RecordingEnabled { get; private set; }
+ /// Whether detection events trigger short video captures while this camera is assigned.
+ public bool EventRecordingEnabled { get; private set; }
// ── Discovery ───────────────────────────────────────────────────
/// How this camera was discovered (manual, ONVIF, mDNS, etc.).
@@ -114,6 +116,7 @@ public class Camera : Entity, IAuditableEntity, ISoftDeletable
public void SetStatus(CameraStatus status) => Status = status;
public void SetRecordingEnabled(bool enabled) => RecordingEnabled = enabled;
+ public void SetEventRecordingEnabled(bool enabled) => EventRecordingEnabled = enabled;
public void SetCapabilities(bool ptz, bool audio, bool motion)
{
diff --git a/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs
index 9648181..465b033 100644
--- a/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs
+++ b/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs
@@ -39,6 +39,10 @@ public class CameraConfiguration : IEntityTypeConfiguration
.HasDefaultValue(false)
.IsRequired();
+ builder.Property(c => c.EventRecordingEnabled)
+ .HasDefaultValue(false)
+ .IsRequired();
+
// ── Discovery ───────────────────────────────────────────────
builder.Property(c => c.DiscoveryMethod)
.HasConversion()
diff --git a/src/Heimdall.Infrastructure/Migrations/20261105162836_AddEventTriggeredCameraRecording.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20261105162836_AddEventTriggeredCameraRecording.Designer.cs
new file mode 100644
index 0000000..b71b8fb
--- /dev/null
+++ b/src/Heimdall.Infrastructure/Migrations/20261105162836_AddEventTriggeredCameraRecording.Designer.cs
@@ -0,0 +1,2897 @@
+//
+using System;
+using Heimdall.Infrastructure.Data;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
+
+#nullable disable
+
+namespace Heimdall.Infrastructure.Migrations
+{
+ [DbContext(typeof(AppDbContext))]
+ [Migration("20261105162836_AddEventTriggeredCameraRecording")]
+ partial class AddEventTriggeredCameraRecording
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "10.0.13")
+ .HasAnnotation("Relational:MaxIdentifierLength", 63);
+
+ NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("ApiKeyHash")
+ .HasMaxLength(128)
+ .IsUnicode(false)
+ .HasColumnType("character varying(128)");
+
+ b.Property("ApiKeyPrefix")
+ .HasMaxLength(8)
+ .IsUnicode(false)
+ .HasColumnType("character varying(8)");
+
+ b.Property("Arch")
+ .HasColumnType("text");
+
+ b.Property("ContainerCpuLimit")
+ .HasColumnType("bigint");
+
+ b.Property("ContainerId")
+ .HasColumnType("text");
+
+ b.Property("ContainerImage")
+ .HasColumnType("text");
+
+ b.Property("ContainerMemoryLimitBytes")
+ .HasColumnType("bigint");
+
+ b.Property("CpuArchitecture")
+ .HasColumnType("text");
+
+ b.Property("CpuCacheBytes")
+ .HasColumnType("bigint");
+
+ b.Property("CpuCores")
+ .HasColumnType("integer");
+
+ b.Property("CpuFlags")
+ .HasColumnType("text");
+
+ b.Property("CpuFrequencyMhz")
+ .HasColumnType("double precision");
+
+ b.Property("CpuModel")
+ .HasColumnType("text");
+
+ b.Property("CpuUsagePercent")
+ .HasColumnType("double precision");
+
+ b.Property("CpuVendor")
+ .HasColumnType("text");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("DeletedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("DiskInventoryJson")
+ .HasColumnType("text");
+
+ b.Property("DiskUsagePercent")
+ .HasColumnType("double precision");
+
+ b.Property("GpuInventoryJson")
+ .HasColumnType("text");
+
+ b.Property("GpuLoadPercent")
+ .HasColumnType("double precision");
+
+ b.Property("GpuName")
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("GpuType")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("HasGpu")
+ .HasColumnType("boolean");
+
+ b.Property("Hostname")
+ .IsRequired()
+ .HasMaxLength(255)
+ .IsUnicode(false)
+ .HasColumnType("character varying(255)");
+
+ b.Property("InventoryObservedAtUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("IsDeleted")
+ .HasColumnType("boolean");
+
+ b.Property("KernelVersion")
+ .HasColumnType("text");
+
+ b.Property("LastAppliedCameraConfigAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("LastAppliedCameraConfigVersion")
+ .HasMaxLength(64)
+ .IsUnicode(false)
+ .HasColumnType("character varying(64)");
+
+ b.Property("LastHeartbeat")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("LogicalCores")
+ .HasColumnType("integer");
+
+ b.Property("MemAvailableBytes")
+ .HasColumnType("bigint");
+
+ b.Property("MemTotalBytes")
+ .HasColumnType("bigint");
+
+ b.Property("MemoryMb")
+ .HasColumnType("bigint");
+
+ b.Property("MemoryUsageBytes")
+ .HasColumnType("bigint");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("NetworkInterfacesJson")
+ .HasColumnType("text");
+
+ b.Property("OsName")
+ .HasColumnType("text");
+
+ b.Property("PhysicalCores")
+ .HasColumnType("integer");
+
+ b.Property("PublicIp")
+ .HasMaxLength(45)
+ .IsUnicode(false)
+ .HasColumnType("character varying(45)");
+
+ b.Property("SiteId")
+ .HasColumnType("uuid");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("SwapFreeBytes")
+ .HasColumnType("bigint");
+
+ b.Property("SwapTotalBytes")
+ .HasColumnType("bigint");
+
+ b.Property("TemperatureJson")
+ .HasColumnType("text");
+
+ b.Property("ThreadsPerCore")
+ .HasColumnType("integer");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("UptimeMachineSeconds")
+ .HasColumnType("bigint");
+
+ b.Property("UptimeSeconds")
+ .HasColumnType("bigint");
+
+ b.Property("Version")
+ .IsRequired()
+ .HasMaxLength(50)
+ .IsUnicode(false)
+ .HasColumnType("character varying(50)");
+
+ b.Property("VramMb")
+ .HasColumnType("bigint");
+
+ b.Property("VramUsageBytes")
+ .HasColumnType("bigint");
+
+ b.HasKey("Id");
+
+ b.HasIndex("LastHeartbeat")
+ .HasFilter("\"Status\" = 'Online'");
+
+ b.HasIndex("SiteId");
+
+ b.ToTable("agents", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AgentId")
+ .HasColumnType("uuid");
+
+ b.Property("Exception")
+ .HasMaxLength(4000)
+ .HasColumnType("character varying(4000)");
+
+ b.Property("Level")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("Message")
+ .IsRequired()
+ .HasMaxLength(2000)
+ .HasColumnType("character varying(2000)");
+
+ b.Property("Source")
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("TimestampUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AgentId", "TimestampUtc");
+
+ b.ToTable("agent_log_entries", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AgentMetricSample", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid")
+ .HasDefaultValueSql("gen_random_uuid()");
+
+ b.Property("AgentId")
+ .HasColumnType("uuid");
+
+ b.Property("CapturedAtUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("CpuUsagePercent")
+ .HasColumnType("double precision");
+
+ b.Property("DiskUsagePercent")
+ .HasColumnType("double precision");
+
+ b.Property("GpuTemperatureCelsius")
+ .HasColumnType("double precision");
+
+ b.Property("GpuUtilizationPercent")
+ .HasColumnType("double precision");
+
+ b.Property("InventoryObservedAtUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("LogicalCores")
+ .HasColumnType("integer");
+
+ b.Property("MemAvailableBytes")
+ .HasColumnType("bigint");
+
+ b.Property("MemTotalBytes")
+ .HasColumnType("bigint");
+
+ b.Property("MemoryUsageBytes")
+ .HasColumnType("bigint");
+
+ b.Property("SiteId")
+ .HasColumnType("uuid");
+
+ b.Property("TemperatureJson")
+ .HasColumnType("text");
+
+ b.HasKey("Id");
+
+ b.HasIndex("CapturedAtUtc");
+
+ b.HasIndex("AgentId", "CapturedAtUtc")
+ .IsUnique();
+
+ b.HasIndex("SiteId", "CapturedAtUtc");
+
+ b.ToTable("agent_metric_samples", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AgentId")
+ .HasColumnType("uuid")
+ .HasColumnName("agent_id");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_at");
+
+ b.Property("Key")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("character varying(200)")
+ .HasColumnName("key");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("updated_at");
+
+ b.Property("Value")
+ .IsRequired()
+ .HasColumnType("text")
+ .HasColumnName("value");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AgentId", "Key")
+ .IsUnique();
+
+ b.ToTable("agent_settings", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AnalysisJob", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AssignedAgentId")
+ .HasColumnType("uuid");
+
+ b.Property("AttemptId")
+ .HasColumnType("uuid");
+
+ b.Property("CameraId")
+ .HasColumnType("uuid");
+
+ b.Property("CompletedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("DispatchedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("ErrorMessage")
+ .HasMaxLength(2000)
+ .HasColumnType("character varying(2000)");
+
+ b.Property("JobType")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)");
+
+ b.Property("MaxExecutionTime")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint")
+ .HasDefaultValue(3000000000L);
+
+ b.Property("MaxRetries")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer")
+ .HasDefaultValue(3);
+
+ b.Property("ParametersJson")
+ .HasColumnType("jsonb");
+
+ b.Property("Priority")
+ .HasColumnType("integer");
+
+ b.Property("RequiredCpuCores")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer")
+ .HasDefaultValue(0);
+
+ b.Property("RequiredMemoryMb")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint")
+ .HasDefaultValue(0L);
+
+ b.Property("RequiresGpu")
+ .HasColumnType("boolean");
+
+ b.Property("ResultJson")
+ .HasColumnType("jsonb");
+
+ b.Property("RetryCount")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer")
+ .HasDefaultValue(0);
+
+ b.Property("SiteId")
+ .HasColumnType("uuid");
+
+ b.Property("StartedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.HasKey("Id");
+
+ b.HasIndex("CameraId")
+ .HasDatabaseName("ix_analysis_jobs_camera");
+
+ b.HasIndex("AssignedAgentId", "Status")
+ .HasDatabaseName("ix_analysis_jobs_agent_workload")
+ .HasFilter("\"AssignedAgentId\" IS NOT NULL");
+
+ b.HasIndex("Status", "DispatchedAt")
+ .HasDatabaseName("ix_analysis_jobs_timeout");
+
+ b.HasIndex("Status", "Priority", "CreatedAt")
+ .HasDatabaseName("ix_analysis_jobs_pending");
+
+ b.ToTable("analysis_jobs", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("CreatedByUserId")
+ .HasColumnType("uuid");
+
+ b.Property("Enabled")
+ .HasColumnType("boolean");
+
+ b.Property("ExpiresAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("KeyHash")
+ .IsRequired()
+ .HasMaxLength(128)
+ .IsUnicode(false)
+ .HasColumnType("character varying(128)");
+
+ b.Property("KeyPrefix")
+ .IsRequired()
+ .HasMaxLength(8)
+ .IsUnicode(false)
+ .HasColumnType("character varying(8)");
+
+ b.Property("LastUsedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("SiteId")
+ .HasColumnType("uuid");
+
+ b.HasKey("Id");
+
+ b.HasIndex("KeyHash");
+
+ b.HasIndex("KeyPrefix");
+
+ b.HasIndex("SiteId");
+
+ b.ToTable("api_keys", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AppSetting", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AgentScoped")
+ .HasColumnType("boolean");
+
+ b.Property("AllowedValues")
+ .HasMaxLength(2000)
+ .HasColumnType("character varying(2000)")
+ .HasColumnName("allowed_values");
+
+ b.Property("Category")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)")
+ .HasColumnName("category");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_at");
+
+ b.Property("Description")
+ .HasMaxLength(500)
+ .HasColumnType("character varying(500)")
+ .HasColumnName("description");
+
+ b.Property("Key")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("character varying(200)")
+ .HasColumnName("key");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("updated_at");
+
+ b.Property("Value")
+ .IsRequired()
+ .HasColumnType("text")
+ .HasColumnName("value");
+
+ b.Property("ValueType")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("value_type");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Key")
+ .IsUnique();
+
+ b.ToTable("app_settings", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("Action")
+ .IsRequired()
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)");
+
+ b.Property("IpAddress")
+ .HasMaxLength(45)
+ .IsUnicode(false)
+ .HasColumnType("character varying(45)");
+
+ b.Property("NewValue")
+ .HasColumnType("text");
+
+ b.Property("OldValue")
+ .HasColumnType("text");
+
+ b.Property("ResourceId")
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)");
+
+ b.Property("ResourceType")
+ .IsRequired()
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)");
+
+ b.Property("Timestamp")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("UserId")
+ .HasColumnType("uuid");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Timestamp")
+ .IsDescending();
+
+ b.HasIndex("UserId");
+
+ b.HasIndex("ResourceType", "ResourceId", "Timestamp")
+ .IsDescending(false, false, true);
+
+ b.ToTable("audit_logs", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AgentId")
+ .HasColumnType("uuid");
+
+ b.Property("Capabilities")
+ .IsRequired()
+ .HasMaxLength(64)
+ .IsUnicode(false)
+ .HasColumnType("character varying(64)");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("DeletedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("DetectedType")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("DiscoveryMethod")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("EventRecordingEnabled")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("boolean")
+ .HasDefaultValue(false);
+
+ b.Property("HasAudio")
+ .HasColumnType("boolean");
+
+ b.Property("HasMotionDetection")
+ .HasColumnType("boolean");
+
+ b.Property("HasPtz")
+ .HasColumnType("boolean");
+
+ b.Property("HttpPort")
+ .HasColumnType("integer");
+
+ b.Property("IpAddress")
+ .HasMaxLength(45)
+ .HasColumnType("character varying(45)");
+
+ b.Property("IsDeleted")
+ .HasColumnType("boolean");
+
+ b.Property("LastDiscoveredAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("LastStreamTestAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("LastTestedCodecs")
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("LastTestedHeight")
+ .HasColumnType("integer");
+
+ b.Property("LastTestedLatencyMs")
+ .HasColumnType("bigint");
+
+ b.Property("LastTestedWidth")
+ .HasColumnType("integer");
+
+ b.Property("MacAddress")
+ .HasMaxLength(17)
+ .HasColumnType("character varying(17)");
+
+ b.Property("Manufacturer")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property("Model")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("OnvifPort")
+ .HasColumnType("integer");
+
+ b.Property("RecordingEnabled")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("boolean")
+ .HasDefaultValue(false);
+
+ b.Property("RtspPort")
+ .HasColumnType("integer");
+
+ b.Property("RtspUrl")
+ .HasMaxLength(1000)
+ .IsUnicode(false)
+ .HasColumnType("character varying(1000)");
+
+ b.Property("SiteId")
+ .HasColumnType("uuid");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("StoragePolicyId")
+ .HasColumnType("uuid");
+
+ b.Property("SubRtspUrl")
+ .HasMaxLength(1000)
+ .IsUnicode(false)
+ .HasColumnType("character varying(1000)");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AgentId");
+
+ b.HasIndex("IpAddress");
+
+ b.HasIndex("MacAddress");
+
+ b.HasIndex("SiteId");
+
+ b.HasIndex("StoragePolicyId");
+
+ b.ToTable("cameras", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AgentId")
+ .HasColumnType("uuid");
+
+ b.Property("AssignedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("CameraId")
+ .HasColumnType("uuid");
+
+ b.Property("Reason")
+ .IsRequired()
+ .HasMaxLength(50)
+ .IsUnicode(false)
+ .HasColumnType("character varying(50)");
+
+ b.Property("ReleasedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AssignedAt");
+
+ b.HasIndex("AgentId", "ReleasedAt")
+ .HasFilter("\"ReleasedAt\" IS NULL");
+
+ b.HasIndex("CameraId", "ReleasedAt")
+ .IsUnique()
+ .HasFilter("\"ReleasedAt\" IS NULL");
+
+ b.ToTable("camera_assignments", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b =>
+ {
+ b.Property("CameraId")
+ .HasColumnType("uuid");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("OnvifPassword")
+ .IsRequired()
+ .HasMaxLength(500)
+ .IsUnicode(false)
+ .HasColumnType("character varying(500)");
+
+ b.Property("OnvifUsername")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)")
+ .HasDefaultValue("admin");
+
+ b.Property("RtspPassword")
+ .IsRequired()
+ .HasMaxLength(500)
+ .IsUnicode(false)
+ .HasColumnType("character varying(500)");
+
+ b.Property("RtspUsername")
+ .IsRequired()
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.HasKey("CameraId");
+
+ b.ToTable("camera_credentials", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b =>
+ {
+ b.Property("CameraId")
+ .HasColumnType("uuid");
+
+ b.Property("ActiveIntervalMs")
+ .HasColumnType("integer");
+
+ b.Property("AnimalCooldownSec")
+ .HasColumnType("integer");
+
+ b.Property("DetectAnimal")
+ .HasColumnType("boolean");
+
+ b.Property("DetectMotion")
+ .HasColumnType("boolean");
+
+ b.Property("DetectPackage")
+ .HasColumnType("boolean");
+
+ b.Property("DetectPerson")
+ .HasColumnType("boolean");
+
+ b.Property("DetectVehicle")
+ .HasColumnType("boolean");
+
+ b.Property("ExecutionProfileJson")
+ .HasColumnType("text");
+
+ b.Property("FaceRecognition")
+ .HasColumnType("boolean");
+
+ b.Property("IdleIntervalMs")
+ .HasColumnType("integer");
+
+ b.Property("IoUThreshold")
+ .HasColumnType("double precision");
+
+ b.Property("LicensePlateRecognition")
+ .HasColumnType("boolean");
+
+ b.Property("MaxEventsPerMinute")
+ .HasColumnType("integer");
+
+ b.Property("MinConfidence")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("double precision")
+ .HasDefaultValue(0.40000000000000002);
+
+ b.Property("MotionIntervalMs")
+ .HasColumnType("integer");
+
+ b.Property("MotionThreshold")
+ .HasColumnType("double precision");
+
+ b.Property("PersonCooldownSec")
+ .HasColumnType("integer");
+
+ b.Property("RequireMotionForAI")
+ .HasColumnType("boolean");
+
+ b.Property("VehicleCooldownSec")
+ .HasColumnType("integer");
+
+ b.Property("YoloModel")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(50)
+ .IsUnicode(false)
+ .HasColumnType("character varying(50)")
+ .HasDefaultValue("yolov8n");
+
+ b.HasKey("CameraId");
+
+ b.ToTable("camera_detection_profiles", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("DetectedType")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("DiscoveryMethod")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("HomeKitCategory")
+ .HasColumnType("integer");
+
+ b.Property("HomeKitDeviceId")
+ .HasMaxLength(50)
+ .IsUnicode(false)
+ .HasColumnType("character varying(50)");
+
+ b.Property("HomeKitIsPaired")
+ .HasColumnType("boolean");
+
+ b.Property("HomeKitModel")
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("HomeKitName")
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("HomeKitPort")
+ .HasColumnType("integer");
+
+ b.Property("Hostname")
+ .HasMaxLength(255)
+ .IsUnicode(false)
+ .HasColumnType("character varying(255)");
+
+ b.Property("HttpPort")
+ .HasColumnType("integer");
+
+ b.Property("HttpServerHeader")
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("HttpStatusCode")
+ .HasColumnType("integer");
+
+ b.Property("IpAddress")
+ .IsRequired()
+ .HasMaxLength(45)
+ .IsUnicode(false)
+ .HasColumnType("character varying(45)");
+
+ b.Property("IsHomeKitCamera")
+ .HasColumnType("boolean");
+
+ b.Property("IsProcessed")
+ .HasColumnType("boolean");
+
+ b.Property("IsReachable")
+ .HasColumnType("boolean");
+
+ b.Property("MacAddress")
+ .HasMaxLength(17)
+ .IsUnicode(false)
+ .HasColumnType("character varying(17)");
+
+ b.Property("OnvifDeviceServiceUrl")
+ .HasMaxLength(500)
+ .IsUnicode(false)
+ .HasColumnType("character varying(500)");
+
+ b.Property("OnvifHardware")
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("OnvifName")
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("OnvifPort")
+ .HasColumnType("integer");
+
+ b.PrimitiveCollection("OpenPorts")
+ .IsRequired()
+ .IsUnicode(false)
+ .HasColumnType("integer[]");
+
+ b.Property("ProbedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("SiteId")
+ .HasColumnType("uuid");
+
+ b.Property("Vendor")
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)");
+
+ b.HasKey("Id");
+
+ b.HasIndex("IpAddress");
+
+ b.HasIndex("IsProcessed");
+
+ b.HasIndex("SiteId");
+
+ b.ToTable("camera_discovery_results", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b =>
+ {
+ b.Property("Id")
+ .HasColumnType("uuid");
+
+ b.Property("OccurredAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("AgentId")
+ .HasColumnType("uuid");
+
+ b.Property("CameraId")
+ .HasColumnType("uuid");
+
+ b.Property("Confidence")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("double precision")
+ .HasDefaultValue(0.0);
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("DetectionHash")
+ .HasMaxLength(128)
+ .IsUnicode(false)
+ .HasColumnType("character varying(128)");
+
+ b.Property("IsSuppressed")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("boolean")
+ .HasDefaultValue(false);
+
+ b.Property("Label")
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("MetadataJson")
+ .HasColumnType("jsonb");
+
+ b.Property("ParentEventId")
+ .HasColumnType("uuid");
+
+ b.Property("PersonId")
+ .HasColumnType("uuid");
+
+ b.Property