Просмотр исходного кода

feat(data-platform): 交付工厂数据接入助手

覆盖 WBS 1.4.1–1.4.5 的设备注册、采集转发、断网续传、状态监控与受控升级。Web 2.4.434 / Server 1.0.623。
YY968XX 21 часов назад
Родитель
Сommit
dc44cba668
33 измененных файлов с 2651 добавлено и 6 удалено
  1. 1 1
      Web/package.json
  2. 2 0
      Web/src/views/aidop/data-platform/components/DatasetReleasePanel.vue
  3. 203 0
      Web/src/views/aidop/data-platform/components/EdgeDeviceWorkspace.vue
  4. 17 0
      server/Admin.NET.DataPlatform.Edge/Admin.NET.DataPlatform.Edge.csproj
  5. 203 0
      server/Admin.NET.DataPlatform.Edge/EdgeEngine.cs
  6. 112 0
      server/Admin.NET.DataPlatform.Edge/EdgeLocalState.cs
  7. 129 0
      server/Admin.NET.DataPlatform.Edge/EdgePush.cs
  8. 241 0
      server/Admin.NET.DataPlatform.Edge/EdgeQueue.cs
  9. 58 0
      server/Admin.NET.DataPlatform.Edge/EdgeRelease.cs
  10. 91 0
      server/Admin.NET.DataPlatform.Edge/EdgeTransport.cs
  11. 123 0
      server/Admin.NET.DataPlatform.Edge/Program.cs
  12. 57 0
      server/Admin.NET.DataPlatform.Edge/README.md
  13. 21 0
      server/Admin.NET.DataPlatform.Edge/deploy/Install-EdgeService.ps1
  14. 59 0
      server/Admin.NET.DataPlatform.Edge/deploy/Switch-EdgeRelease.ps1
  15. 23 0
      server/Admin.NET.DataPlatform.Edge/deploy/aidop-edge.service
  16. 37 0
      server/Admin.NET.DataPlatform.Edge/deploy/switch-release.sh
  17. 11 3
      server/Admin.NET.Web.Entry/Admin.NET.Web.Entry.csproj
  18. 48 0
      server/Admin.NET.Web.Entry/UpdateScripts/1.0.623.sql
  19. 22 0
      server/Admin.NET.Web.Entry/UpdateScripts/1.0.623.verify.sql
  20. 14 0
      server/Admin.NET.sln
  21. 90 0
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Edge/EdgeProtocol.cs
  22. 56 0
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Edge/EdgeTimeWatermark.cs
  23. 72 0
      server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpEdgeReceiptTests.cs
  24. 1 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpApiPullService.cs
  25. 76 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpEdgeDeviceController.cs
  26. 198 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpEdgeDeviceService.ApiRecovery.cs
  27. 311 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpEdgeDeviceService.Receive.cs
  28. 265 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpEdgeDeviceService.cs
  29. 34 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpEdgeRoute.cs
  30. 68 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestDatasetController.Edge.cs
  31. 5 2
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestReceiveService.cs
  32. 1 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestServiceCollectionExtensions.cs
  33. 2 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpRelationalSyncService.cs

+ 1 - 1
Web/package.json

@@ -1,7 +1,7 @@
 {
 	"name": "admin.net",
 	"type": "module",
-	"version": "2.4.433",
+	"version": "2.4.434",
 	"packageManager": "pnpm@10.32.1",
 	"lastBuildTime": "2026.03.15",
 	"description": "Admin.NET 站在巨人肩膀上的 .NET 通用权限开发框架",

+ 2 - 0
Web/src/views/aidop/data-platform/components/DatasetReleasePanel.vue

@@ -2,6 +2,7 @@
 import { computed, onMounted, ref } from 'vue';
 import { ElMessage, ElMessageBox } from 'element-plus';
 import ApiPullWorkspace from './ApiPullWorkspace.vue';
+import EdgeDeviceWorkspace from './EdgeDeviceWorkspace.vue';
 import IngestBatchStatus from './IngestBatchStatus.vue';
 import IngestPushSample from './IngestPushSample.vue';
 import RelationalTrialPanel from './RelationalTrialPanel.vue';
@@ -213,6 +214,7 @@ async function lifecycle(action: string) {
 		<IngestBatchStatus :key="factoryId + '/' + dataset.id" :dataset-id="dataset.id" :factory-id="factoryId" :has-schema="!!dataset.activeSchemaVersion" />
 		<IngestPushSample v-if="dataset.activeSchemaVersion" :key="'sample/' + factoryId + '/' + dataset.id" :dataset-id="dataset.id" :factory-id="factoryId" />
 		<ApiPullWorkspace v-if="model?.canTrial" :key="factoryId + '/api-pull/' + dataset.id" :dataset="dataset" :factory-id="factoryId" />
+		<EdgeDeviceWorkspace v-if="model?.canTrial" :key="factoryId + '/edge/' + dataset.id" :dataset="dataset" :factory-id="factoryId" />
 		<RelationalTrialPanel v-if="model?.canTrial" :dataset-id="dataset.id" :factory-id="factoryId" :active="model.lifecycle === 'ACTIVE' && dataset.enabled" />
 		<el-collapse v-if="model?.timeline.length">
 			<el-collapse-item title="查看操作记录" name="history">

+ 203 - 0
Web/src/views/aidop/data-platform/components/EdgeDeviceWorkspace.vue

@@ -0,0 +1,203 @@
+<script setup lang="ts">
+import { computed, ref } from 'vue';
+import service from '/@/utils/request';
+import type { IngestDataset } from '../api/ingestDatasets';
+
+interface Device {
+	deviceId: string;
+	deviceName: string;
+	sourceId: string;
+	state: string;
+	phase?: string;
+	certificateExpires?: string;
+	seenAt?: string;
+	online: boolean;
+	watermark?: string;
+	rejectedRawId?: string;
+	rejectedDigest?: string;
+	pageCount: number;
+	rowCount: number;
+	report?: { version: string; pending: number; bufferedBytes: number; freeBytes: number; lastError?: string };
+}
+interface Workspace { devices: Device[]; canApprove: boolean }
+const props = defineProps<{ dataset: IngestDataset; factoryId: string }>();
+const route = computed(() => '/api/DataPlatform/ingest-datasets/' + props.dataset.id + '/edge');
+const request = computed(() => ({ params: { factoryId: props.factoryId } }));
+const sources = computed(() => props.dataset.bindings.filter(source => source.sourceEnabled));
+const workspace = ref<Workspace>();
+const busy = ref(false);
+const feedback = ref('');
+const sourceId = ref('');
+const name = ref('');
+const activation = ref<{ deviceId: string; activation: string }>();
+const task = ref<{ deviceId: string; mode: string; config: string }>();
+
+interface Preview { batchId: string; digest: string; count: number; valid: number; isolated: number; hasNext: boolean; token: string }
+const recovery = ref<{ deviceId: string; batchId: string; digest: string; mode: 'reparse' | 'refetch'; path: string; reason: string }>();
+const preview = ref<{ path: string; result: Preview }>();
+const approvedPreview = computed(() => {
+	const result = preview.value;
+	return result && result.path === recovery.value?.path.trim() ? result.result : undefined;
+});
+
+function openRecovery(device: Device) {
+	if (!device.rejectedRawId || !device.rejectedDigest) return;
+	preview.value = undefined;
+	recovery.value = { deviceId: device.deviceId, batchId: device.rejectedRawId, digest: device.rejectedDigest,
+		mode: 'reparse', path: '', reason: '' };
+}
+
+function previewPage() {
+	const model = recovery.value;
+	if (!model) return;
+	const path = model.path.trim();
+	preview.value = undefined;
+	return run(async () => {
+		const { data } = await service.post<Preview>(route.value + '/' + model.deviceId + '/recovery/preview',
+			{ batchId: model.batchId, responsePath: path }, request.value);
+		preview.value = { path, result: data };
+	});
+}
+
+function recoverPage() {
+	const model = recovery.value;
+	if (!model || !model.reason.trim() || (model.mode === 'reparse' && !approvedPreview.value)) return;
+	return run(async () => {
+		await service.post(route.value + '/' + model.deviceId + '/recovery', {
+			batchId: model.batchId, digest: model.digest, mode: model.mode, reason: model.reason.trim(),
+			responsePath: model.mode === 'reparse' ? model.path.trim() : null,
+			previewToken: model.mode === 'reparse' ? approvedPreview.value?.token : null,
+		}, request.value);
+		recovery.value = undefined;
+	});
+}
+
+async function run(action?: () => Promise<void>) {
+	if (busy.value) return;
+	busy.value = true;
+	feedback.value = '';
+	try {
+		if (action) await action();
+		workspace.value = (await service.get<Workspace>(route.value, request.value)).data;
+	} catch (failure) {
+		const response = (failure as { response?: { status?: number; data?: { code?: string } } }).response;
+		feedback.value = response?.data?.code ?? (response?.status === 404 ? '设备接入尚未启用' : '设备操作失败');
+	} finally {
+		busy.value = false;
+	}
+}
+
+function approve() {
+	activation.value = undefined;
+	return run(async () => {
+		const input = { name: name.value.trim(), sourceId: sourceId.value };
+		activation.value = (await service.post<{ deviceId: string; activation: string }>(route.value, input, request.value)).data;
+		name.value = '';
+	});
+}
+
+function configure() {
+	const model = task.value;
+	if (!model) return;
+	return run(async () => {
+		let relational: unknown;
+		if (model.mode === 'database') {
+			try { relational = JSON.parse(model.config); }
+			catch { feedback.value = '数据库配置必须是有效 JSON'; return; }
+		}
+		await service.put(route.value + '/' + model.deviceId + '/task',
+			{ mode: model.mode, apiPlan: model.mode === 'api-pull' ? model.config : null, relational }, request.value);
+		task.value = undefined;
+	});
+}
+</script>
+
+<template>
+	<el-collapse>
+		<el-collapse-item title="工厂数据接入助手" name="edge">
+			<el-button :loading="busy" @click="run()">加载设备状态</el-button>
+			<p v-if="feedback" role="alert">{{ feedback }}</p>
+			<el-form v-if="workspace?.canApprove" inline @submit.prevent="approve">
+				<el-form-item label="设备名称"><el-input v-model="name" maxlength="120" /></el-form-item>
+				<el-form-item label="绑定来源">
+					<el-select v-model="sourceId" style="min-width: 160px">
+						<el-option v-for="source in sources" :key="source.sourceId" :value="source.sourceId" :label="source.sourceName || source.sourceId" />
+					</el-select>
+				</el-form-item>
+				<el-button native-type="submit" :disabled="busy || !sourceId || !name.trim()">审批并生成激活码</el-button>
+			</el-form>
+			<div v-if="activation">
+				<p>激活码有效期 15 分钟,仅可使用一次。</p>
+				<code>{{ activation.activation }}</code>
+				<el-button link @click="activation = undefined">隐藏激活码</el-button>
+			</div>
+			<el-table v-if="workspace" :data="workspace.devices" empty-text="暂无绑定设备">
+				<el-table-column prop="deviceName" label="设备" />
+				<el-table-column prop="sourceId" label="来源" />
+				<el-table-column prop="state" label="注册状态" />
+				<el-table-column prop="phase" label="任务状态" />
+				<el-table-column prop="report.version" label="版本" />
+				<el-table-column prop="certificateExpires" label="证书到期" />
+				<el-table-column label="在线状态">
+					<template #default="{ row }">{{ row.online ? '在线' : '离线' }}</template>
+				</el-table-column>
+				<el-table-column prop="seenAt" label="最近心跳" />
+				<el-table-column prop="pageCount" label="确认页" />
+				<el-table-column prop="watermark" label="数据库水位" />
+				<el-table-column prop="report.pending" label="积压批次" />
+				<el-table-column prop="report.freeBytes" label="可用磁盘(字节)" />
+				<el-table-column prop="report.lastError" label="诊断" />
+				<el-table-column v-if="workspace.canApprove" label="操作" min-width="120">
+					<template #default="{ row }">
+						<el-button v-if="row.state !== 'REVOKED' && (!row.phase || row.phase === 'COMPLETE')" link :disabled="busy"
+							@click="task = { deviceId: row.deviceId, mode: 'api-push', config: '' }">下发任务</el-button>
+						<el-button v-if="row.rejectedRawId" link :disabled="busy" @click="openRecovery(row)">恢复异常页</el-button>
+						<el-popconfirm v-if="row.state !== 'REVOKED'" title="吊销后设备将无法访问平台。"
+							@confirm="run(async () => { await service.post(route + '/' + row.deviceId + '/revoke', undefined, request) })">
+							<template #reference><el-button link :disabled="busy" type="danger">吊销</el-button></template>
+						</el-popconfirm>
+					</template>
+				</el-table-column>
+			</el-table>
+			<el-dialog v-if="task" :model-value="true" title="下发采集任务" @close="task = undefined">
+				<el-form label-position="top">
+					<el-form-item label="采集方式">
+						<el-select v-model="task.mode">
+							<el-option label="内网 API 推送" value="api-push" />
+							<el-option label="内网 API 拉取" value="api-pull" />
+							<el-option label="数据库同步" value="database" />
+						</el-select>
+					</el-form-item>
+					<el-form-item v-if="task.mode !== 'api-push'" label="已核对的来源配置 JSON">
+						<el-input v-model="task.config" type="textarea" :rows="8" />
+					</el-form-item>
+				</el-form>
+				<template #footer>
+					<el-button type="primary" :disabled="busy || (task.mode !== 'api-push' && !task.config.trim())" @click="configure">下发</el-button>
+				</template>
+			</el-dialog>
+			<el-dialog v-if="recovery" :model-value="true" title="恢复设备 API 异常页" @close="recovery = undefined">
+				<p>Raw 批次号 {{ recovery.batchId }}</p>
+				<el-form label-position="top" :disabled="busy">
+					<el-form-item label="恢复方式">
+						<el-radio-group v-model="recovery.mode">
+							<el-radio value="reparse">原文重解析</el-radio>
+							<el-radio value="refetch">原位重取</el-radio>
+						</el-radio-group>
+					</el-form-item>
+					<el-form-item v-if="recovery.mode === 'reparse'" label="本页数组路径">
+						<el-input v-model="recovery.path" maxlength="112" placeholder="响应根节点为数组时留空" />
+						<el-button @click="previewPage">预演原文</el-button>
+						<span v-if="approvedPreview">共 {{ approvedPreview.count }} 行,合格 {{ approvedPreview.valid }},隔离 {{ approvedPreview.isolated }}</span>
+					</el-form-item>
+					<el-form-item label="恢复原因"><el-input v-model="recovery.reason" type="textarea" maxlength="240" /></el-form-item>
+				</el-form>
+				<p v-if="feedback" role="alert">{{ feedback }}</p>
+				<template #footer>
+					<el-button type="primary" :disabled="busy || !recovery.reason.trim() || (recovery.mode === 'reparse' && !approvedPreview)"
+						@click="recoverPage">确认恢复</el-button>
+				</template>
+			</el-dialog>
+		</el-collapse-item>
+	</el-collapse>
+</template>

+ 17 - 0
server/Admin.NET.DataPlatform.Edge/Admin.NET.DataPlatform.Edge.csproj

@@ -0,0 +1,17 @@
+<Project Sdk="Microsoft.NET.Sdk.Web">
+  <PropertyGroup>
+    <TargetFrameworks>net8.0;net10.0</TargetFrameworks>
+    <ImplicitUsings>enable</ImplicitUsings>
+    <Nullable>enable</Nullable>
+  </PropertyGroup>
+  <ItemGroup>
+    <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.9" />
+    <PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.9" />
+    <PackageReference Include="System.Security.Cryptography.ProtectedData" Version="8.0.0" />
+    <ProjectReference Include="../Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/Admin.NET.Plugin.AiDOP.DataPlatform.Relational.csproj" />
+    <Compile Include="../Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpApiPullPlan.cs" Link="Api/MdpApiPullPlan.cs" />
+    <Compile Include="../Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpApiPullEgress.cs" Link="Api/MdpApiPullEgress.cs" />
+    <Compile Include="../Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpApiPullClient.cs" Link="Api/MdpApiPullClient.cs" />
+    <Compile Include="../Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestProtocol.cs" Link="Api/MdpIngestProtocol.cs" />
+  </ItemGroup>
+</Project>

+ 203 - 0
server/Admin.NET.DataPlatform.Edge/EdgeEngine.cs

@@ -0,0 +1,203 @@
+using System.Data.Common;
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Relational;
+using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+namespace Admin.NET.DataPlatform.Edge;
+
+internal sealed class EdgeEngine(EdgeLocalState local, byte[] key, EdgeQueue queue, EdgeTransport transport, IConfiguration config)
+{
+    private readonly MdpApiPullClient api = new(new MdpApiPullEgress(config), config);
+    private readonly Queue<DateTimeOffset> requests = new();
+    private EdgeTask? current = local.ReadTask(key);
+    private string? lastError;
+    private DateTimeOffset retryAfter;
+    private int failures;
+
+    internal EdgeTask? Current => Volatile.Read(ref current);
+
+    internal async Task<bool> WorkAsync(CancellationToken token)
+    {
+        try
+        {
+            if (retryAfter > DateTimeOffset.UtcNow) return true;
+            using var certificate = local.ReadCertificate(key) ?? throw new EdgeContractException("EDGE_NOT_REGISTERED");
+            if (certificate.NotAfter.ToUniversalTime() <= DateTime.UtcNow.AddDays(1))
+                await transport.RotateAsync(local, key, certificate, token);
+            using var active = local.ReadCertificate(key) ?? throw new EdgeContractException("EDGE_NOT_REGISTERED");
+            using var client = transport.Connect(active);
+            var usage = queue.Usage();
+            var report = new EdgeReport(typeof(EdgeEngine).Assembly.GetName().Version?.ToString() ?? "1.0.0",
+                usage.Pending, usage.Bytes, usage.FreeBytes, lastError);
+            var task = await EdgeTransport.PostAsync<EdgeReport, EdgeTask>(client, "/api/v1/edge/heartbeat", report, token);
+            if (task is not null) local.WriteTask(task, key);
+            Volatile.Write(ref current, task);
+            foreach (var settled in task?.SettledPages ?? [])
+            {
+                if (queue.ReadRejected(settled) is not { } archived) continue;
+                var recovered = await transport.SendAsync(client, archived, token);
+                queue.SettleRejection(archived, recovered);
+            }
+            if (queue.Next() is { } pending)
+                await SendAsync(client, pending, token);
+            else if (task is { State: "READY" } && task.LeaseUntil > DateTimeOffset.UtcNow)
+            {
+                if (task.Mode == EdgeProtocol.ApiPull)
+                {
+                    var batch = await ReadApiAsync(task, token);
+                    queue.Buffer(batch);
+                    await SendAsync(client, batch, token);
+                }
+                else if (task.Mode == EdgeProtocol.Database)
+                {
+                    await CaptureDatabaseAsync(task, token);
+                    if (queue.Next(task.Stream) is { } first) await SendAsync(client, first, token);
+                }
+            }
+            EdgeLocalState.AtomicWrite(Path.Combine(local.DirectoryPath, "health"), Encoding.UTF8.GetBytes(DateTimeOffset.UtcNow.ToString("O")));
+            failures = 0;
+            lastError = null;
+            return true;
+        }
+        catch (Exception error) when (!token.IsCancellationRequested && error is EdgeContractException or MdpApiPullException
+            or ConnectorContractException or DbException or HttpRequestException or IOException or CryptographicException
+            or JsonException or OperationCanceledException)
+        {
+            lastError = error switch
+            {
+                EdgeContractException edge => edge.Code,
+                MdpApiPullException pull => pull.Code,
+                ConnectorContractException connector => connector.Code.ToString(),
+                _ => error.GetType().Name
+            };
+            if (lastError == "EDGE_DEVICE_FORBIDDEN") Volatile.Write(ref current, null);
+            failures = Math.Min(failures + 1, 8);
+            var delay = error is MdpApiPullException { Retry: { } retry }
+                ? Math.Max(Math.Pow(2, failures), retry.TotalSeconds) : Math.Pow(2, failures);
+            retryAfter = DateTimeOffset.UtcNow.AddSeconds(Math.Clamp(delay, 2, 86400));
+            Console.Error.WriteLine(lastError);
+            return false;
+        }
+    }
+
+    private async Task SendAsync(HttpClient client, EdgeBatch batch, CancellationToken token)
+    {
+        var receipt = await transport.SendAsync(client, batch, token);
+        queue.Record(batch, receipt);
+        if (receipt.Status == EdgeProtocol.Rejected)
+            Console.Error.WriteLine("EDGE_REMOTE_REJECTED");
+    }
+
+    private async Task<EdgeBatch> ReadApiAsync(EdgeTask task, CancellationToken token)
+    {
+        if (task.ApiPlan is null || task.Position is null)
+            throw new EdgeContractException("EDGE_TASK_INVALID");
+        var plan = JsonSerializer.Deserialize<MdpApiPullPlan>(task.ApiPlan, EdgeProtocol.Json)
+            ?? throw new EdgeContractException("EDGE_TASK_INVALID");
+        plan.Validate();
+        if (task.PageCount >= plan.MaxPages) throw new EdgeContractException("PULL_PAGE_LIMIT");
+        var position = JsonSerializer.Deserialize<MdpApiPullPosition>(task.Position, EdgeProtocol.Json)
+            ?? throw new EdgeContractException("EDGE_TASK_INVALID");
+        var response = await api.FetchAsync(task.TenantId, task.SourceId, plan, position, token, _ =>
+        {
+            var now = DateTimeOffset.UtcNow;
+            while (requests.TryPeek(out var oldest) && oldest.AddMinutes(1) <= now) requests.Dequeue();
+            var cap = Math.Clamp(config.GetValue("Edge:SourceRequestsPerMinute", 60), 1, 1000);
+            if (requests.Count >= cap)
+                throw new MdpApiPullException("PULL_LOCAL_RATE_LIMITED", TimeSpan.FromSeconds(60));
+            requests.Enqueue(now);
+            return Task.CompletedTask;
+        });
+        return EdgeBatch.Create(task.Stream, task.PageKey(), task.Position,
+            null, response.Body) with
+        {
+            EffectiveUrl = response.Effective.AbsoluteUri[..Math.Min(response.Effective.AbsoluteUri.Length, 2048)],
+            NextLink = response.NextLink, Diagnostic = response.LinkDiagnostic, ReceiverConfirmsNext = true
+        };
+    }
+
+    private async Task CaptureDatabaseAsync(EdgeTask task, CancellationToken token)
+    {
+        var approved = task.Relational ?? throw new EdgeContractException("EDGE_TASK_INVALID");
+        var localMapping = config.GetSection("Edge:Relational").Get<EdgeRelationalSettings>();
+        if (!Equivalent(approved, localMapping))
+            throw new EdgeContractException("EDGE_RELATIONAL_TARGET_FORBIDDEN");
+        var connection = LocalCredential(approved.SecretRef) ?? throw new EdgeContractException("EDGE_SOURCE_CREDENTIAL_UNAVAILABLE");
+        var binding = new ConnectorBinding(new(task.TenantId, task.FactoryId, task.SourceId, task.DatasetId, task.SourceCode, task.DatasetKey),
+            task.SchemaVersion, task.ConfigVersion);
+        var execution = new ConnectorExecution(binding, approved.Driver, NativeRelationalDriver.Version,
+            ConnectorManifest.FactoryAgent, ConnectorManifest.Database);
+        var mapping = new RelationalSourceMapping(execution, approved.SecretRef, approved.Database, approved.Schema, approved.Table,
+            approved.PositionColumn, approved.Columns)
+        {
+            IncludeFactoryInEnvelope = true,
+            ChangeVersionColumn = approved.ChangeVersionColumn,
+            DeleteColumn = approved.DeleteColumn
+        };
+        Task<string> Resolve(ConnectorBinding _, string __, CancellationToken ___) => Task.FromResult(connection);
+        IRelationalSourceDriver driver = approved.Driver == OdbcRelationalDriver.Id
+            ? new OdbcRelationalDriver(mapping, approved.OdbcFamily ?? "", Resolve) : new NativeRelationalDriver(mapping, Resolve);
+        await using var session = await driver.OpenReadOnlyAsync(execution, approved.SecretRef, token);
+        if (task.Position != task.StartPosition || task.PageCount != 0)
+            throw new EdgeContractException("EDGE_SNAPSHOT_REQUIRES_ORIGINAL_OUTBOX");
+        if (approved.Time is { } time)
+        {
+            if (session is not IRelationalTimeSnapshotSource timeSnapshots)
+                throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
+            var timePosition = task.Position;
+            var completed = approved.Incremental ? EdgeTimeWatermark.Decode(timePosition) : (DateTimeOffset?)null;
+            var request = new RelationalTimeCapture(time.Column, completed, time.DelaySeconds, time.LookbackSeconds,
+                time.RetentionSeconds, ReplayOnly: false);
+            await queue.BufferSnapshotAsync(async add =>
+            {
+                var snapshot = await timeSnapshots.CaptureTimeAsync(approved.PageSize, (candidate, ordinal, _) =>
+                {
+                    var next = EdgeTimeWatermark.Page(candidate.NextCheckpoint ?? throw new EdgeContractException("EDGE_POSITION_INVALID"));
+                    add(EdgeBatch.Create(task.Stream, $"db-{ordinal}", timePosition, next, candidate.Payload.ToArray()));
+                    timePosition = next;
+                    return Task.CompletedTask;
+                }, request, token);
+                add(EdgeBatch.Create(task.Stream, "db-end", timePosition, EdgeTimeWatermark.Encode(snapshot.To), []));
+            });
+            return;
+        }
+        if (session is not IRelationalSnapshotSource snapshots)
+            throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
+        var position = task.Position;
+        var log = approved.Incremental ? new RelationalLogWindow(position is null ? null :
+            long.Parse(position, CultureInfo.InvariantCulture)) : null;
+        await queue.BufferSnapshotAsync(async add =>
+        {
+            await snapshots.CaptureAsync(approved.PageSize, (candidate, ordinal, _) =>
+            {
+                var batch = EdgeBatch.Create(task.Stream, $"db-{ordinal}", position, candidate.NextCheckpoint, candidate.Payload.ToArray());
+                add(batch);
+                position = candidate.NextCheckpoint;
+                return Task.CompletedTask;
+            }, token, log);
+            add(EdgeBatch.Create(task.Stream, "db-end", position, position, []));
+        });
+    }
+
+    private static bool Equivalent(EdgeRelationalSettings allowed, EdgeRelationalSettings? local) =>
+        local is not null && allowed.Columns is not null && local.Columns is not null
+        && allowed.Columns.SequenceEqual(local.Columns, StringComparer.Ordinal)
+        && (allowed with { Columns = local.Columns, Incremental = local.Incremental, PageSize = local.PageSize })
+            == local;
+
+    internal static string? LocalCredential(string name)
+    {
+        if (!name.StartsWith("MDP_EDGE_SECRET_", StringComparison.Ordinal) || name.Length > 80
+            || name.Any(ch => !(char.IsAsciiLetterUpper(ch) || char.IsAsciiDigit(ch) || ch == '_')))
+            return null;
+        var directory = Environment.GetEnvironmentVariable("CREDENTIALS_DIRECTORY");
+        if (!string.IsNullOrEmpty(directory) && File.Exists(Path.Combine(directory, name)))
+            return File.ReadAllText(Path.Combine(directory, name)).Trim();
+        return Environment.GetEnvironmentVariable(name);
+    }
+}

+ 112 - 0
server/Admin.NET.DataPlatform.Edge/EdgeLocalState.cs

@@ -0,0 +1,112 @@
+using System.Runtime.Versioning;
+using System.Security.Cryptography;
+using System.Security.Cryptography.X509Certificates;
+using System.Text;
+using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
+
+namespace Admin.NET.DataPlatform.Edge;
+
+internal sealed class EdgeLocalState(string directory)
+{
+    internal string DirectoryPath { get; } = Path.GetFullPath(directory);
+    private string KeyPath => Path.Combine(DirectoryPath, "queue-key.dpapi");
+
+    internal void Initialize()
+    {
+        Directory.CreateDirectory(DirectoryPath);
+        if (!OperatingSystem.IsWindows())
+            File.SetUnixFileMode(DirectoryPath, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
+    }
+
+    internal byte[] ReadKey()
+    {
+        if (OperatingSystem.IsWindows()) return WindowsKey();
+        var credentials = Environment.GetEnvironmentVariable("CREDENTIALS_DIRECTORY");
+        var path = Environment.GetEnvironmentVariable("MDP_EDGE_KEY_FILE")
+            ?? (string.IsNullOrEmpty(credentials) ? null : Path.Combine(credentials, "edge-queue-key"));
+        if (string.IsNullOrEmpty(path)) throw new EdgeContractException("EDGE_QUEUE_KEY_REQUIRED");
+        if ((File.GetUnixFileMode(path) & (UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.OtherRead | UnixFileMode.OtherWrite)) != 0)
+            throw new EdgeContractException("EDGE_QUEUE_KEY_PERMISSIONS");
+        var key = Convert.FromBase64String(File.ReadAllText(path).Trim());
+        return key.Length == 32 ? key : throw new EdgeContractException("EDGE_QUEUE_KEY_INVALID");
+    }
+
+    [SupportedOSPlatform("windows")]
+    private byte[] WindowsKey()
+    {
+        if (File.Exists(KeyPath))
+            return ProtectedData.Unprotect(File.ReadAllBytes(KeyPath), null, DataProtectionScope.CurrentUser);
+        var key = RandomNumberGenerator.GetBytes(32);
+        var wrapped = ProtectedData.Protect(key, null, DataProtectionScope.CurrentUser);
+        AtomicWrite(KeyPath, wrapped);
+        return key;
+    }
+
+    internal X509Certificate2? ReadCertificate(byte[] key, bool pending = false)
+    {
+        var data = ReadEncrypted(pending ? "certificate.pending" : "certificate", key);
+        if (data is null) return null;
+        try { return new X509Certificate2(data, (string?)null, X509KeyStorageFlags.EphemeralKeySet); }
+        finally { CryptographicOperations.ZeroMemory(data); }
+    }
+
+    internal void WriteCertificate(X509Certificate2 certificate, byte[] key, bool pending = false)
+    {
+        var bytes = certificate.Export(X509ContentType.Pfx);
+        try { WriteEncrypted(pending ? "certificate.pending" : "certificate", key, bytes); }
+        finally { CryptographicOperations.ZeroMemory(bytes); }
+    }
+
+    internal void PromoteCertificate() =>
+        File.Move(Path.Combine(DirectoryPath, "certificate.pending"), Path.Combine(DirectoryPath, "certificate"), overwrite: true);
+
+    internal EdgeTask? ReadTask(byte[] key)
+    {
+        var bytes = ReadEncrypted("task", key);
+        if (bytes is null) return null;
+        try { return JsonSerializer.Deserialize<EdgeTask>(bytes, EdgeProtocol.Json); }
+        finally { CryptographicOperations.ZeroMemory(bytes); }
+    }
+
+    internal void WriteTask(EdgeTask task, byte[] key)
+    {
+        var bytes = JsonSerializer.SerializeToUtf8Bytes(task, EdgeProtocol.Json);
+        try { WriteEncrypted("task", key, bytes); }
+        finally { CryptographicOperations.ZeroMemory(bytes); }
+    }
+
+    private byte[]? ReadEncrypted(string name, byte[] key)
+    {
+        var path = Path.Combine(DirectoryPath, name);
+        if (!File.Exists(path)) return null;
+        var body = File.ReadAllBytes(path);
+        if (body.Length < 28) throw new EdgeContractException("EDGE_LOCAL_STATE_INVALID");
+        var bytes = new byte[body.Length - 28];
+        using var aes = new AesGcm(key, 16);
+        aes.Decrypt(body.AsSpan(0, 12), body.AsSpan(28), body.AsSpan(12, 16), bytes, Encoding.ASCII.GetBytes(name.Split('.')[0]));
+        return bytes;
+    }
+
+    private void WriteEncrypted(string name, byte[] key, byte[] value)
+    {
+        var body = new byte[28 + value.Length];
+        RandomNumberGenerator.Fill(body.AsSpan(0, 12));
+        using var aes = new AesGcm(key, 16);
+        aes.Encrypt(body.AsSpan(0, 12), value, body.AsSpan(28), body.AsSpan(12, 16), Encoding.ASCII.GetBytes(name.Split('.')[0]));
+        AtomicWrite(Path.Combine(DirectoryPath, name), body);
+    }
+
+    internal static void AtomicWrite(string path, byte[] bytes)
+    {
+        var temporary = path + ".tmp";
+        using (var file = new FileStream(temporary, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough))
+        {
+            if (!OperatingSystem.IsWindows())
+                File.SetUnixFileMode(temporary, UnixFileMode.UserRead | UnixFileMode.UserWrite);
+            file.Write(bytes);
+            file.Flush(flushToDisk: true);
+        }
+        File.Move(temporary, path, overwrite: true);
+    }
+}

+ 129 - 0
server/Admin.NET.DataPlatform.Edge/EdgePush.cs

@@ -0,0 +1,129 @@
+using System.Globalization;
+using System.Net;
+using System.Security.Cryptography;
+using System.Text;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
+using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+namespace Admin.NET.DataPlatform.Edge;
+
+internal static class EdgePush
+{
+    internal static void Map(WebApplication app, EdgeEngine engine, EdgeQueue queue, IConfiguration config)
+    {
+        string access = config["Edge:PushAccessKey"] ?? throw new EdgeContractException("EDGE_PUSH_ACCESS_KEY_REQUIRED");
+        var peerStrings = config.GetSection("Edge:PushPeers").Get<string[]>() ?? [];
+        if (peerStrings.Length == 0 || peerStrings.Any(value => !IPAddress.TryParse(value, out _)))
+            throw new EdgeContractException("EDGE_PUSH_PEERS_REQUIRED");
+        var peers = peerStrings.Select(IPAddress.Parse).Select(Normalize).ToHashSet();
+        var secret = Convert.FromBase64String(EdgeEngine.LocalCredential("MDP_EDGE_SECRET_PUSH") ?? "");
+        if (secret.Length != 32 || access.Length is < 12 or > 96)
+            throw new EdgeContractException("EDGE_PUSH_KEY_INVALID");
+        var limiter = new Queue<DateTimeOffset>();
+        var rate = Math.Clamp(config.GetValue("Edge:PushRequestsPerMinute", 60), 1, 1000);
+        var endpoint = app.MapPost("/api/v1/edge/push/{datasetKey}", async (HttpContext context, string datasetKey) =>
+        {
+            context.Response.Headers.CacheControl = "no-store";
+            if (!AllowedPeer(context, peers)) return Failure(403, "EDGE_PUSH_FORBIDDEN");
+            var task = engine.Current;
+            if (task is not { Mode: EdgeProtocol.ApiPush, State: "READY" } || task.LeaseUntil <= DateTimeOffset.UtcNow
+                || !string.Equals(task.DatasetKey, datasetKey, StringComparison.Ordinal))
+                return Failure(503, "EDGE_PUSH_UNAVAILABLE");
+            var request = context.Request;
+            var media = request.ContentType?.Split(';', 2)[0].ToLowerInvariant();
+            if (media is not ("application/json" or "application/x-ndjson") || request.Headers.ContainsKey("Content-Encoding"))
+                return Failure(415, "EDGE_PUSH_MEDIA_INVALID");
+            var key = Header(request, "X-Idempotency-Key", 128);
+            var nonce = Header(request, "X-Nonce", 128);
+            var timestamp = Header(request, "X-Timestamp", 20);
+            var suppliedAccess = Header(request, "X-Access-Key", 96);
+            var signature = Header(request, "X-Signature", 64);
+            var digest = Header(request, "X-Content-SHA256", 64);
+            if (key is null || nonce is null || suppliedAccess != access || digest is null
+                || !InTime(timestamp) || signature is null)
+                return Failure(403, "EDGE_PUSH_FORBIDDEN");
+
+            // Validate signed headers before reading the bounded request.
+            var canonical = MdpIngestProtocol.CanonicalSignature("POST", request.Path, access, timestamp!, nonce, digest, key,
+                true, media, task.FactoryId.ToString(CultureInfo.InvariantCulture), task.SchemaVersion);
+            var expected = HMACSHA256.HashData(secret, Encoding.UTF8.GetBytes(canonical));
+            var provided = new byte[32];
+            if (!Convert.TryFromBase64String(signature, provided, out var count) || count != expected.Length
+                || !CryptographicOperations.FixedTimeEquals(expected, provided))
+                return Failure(403, "EDGE_PUSH_FORBIDDEN");
+            lock (limiter)
+            {
+                var now = DateTimeOffset.UtcNow;
+                while (limiter.TryPeek(out var oldest) && oldest.AddMinutes(1) <= now) limiter.Dequeue();
+                if (limiter.Count >= rate) return Failure(429, "EDGE_PUSH_RATE_LIMITED");
+                limiter.Enqueue(now);
+            }
+
+            using var body = new MemoryStream();
+            var bytes = new byte[8192];
+            while (true)
+            {
+                var read = await request.Body.ReadAsync(bytes, context.RequestAborted);
+                if (read == 0) break;
+                if (body.Length + read > EdgeProtocol.MaxBodyBytes) return Failure(413, "EDGE_PUSH_TOO_LARGE");
+                body.Write(bytes, 0, read);
+            }
+            var batch = EdgeBatch.Create(task.Stream, key, null, null, body.ToArray()) with { Ndjson = media == "application/x-ndjson" };
+            if (batch.Digest != digest || batch.Body.Length == 0) return Failure(400, "EDGE_PUSH_DIGEST_INVALID");
+            try
+            {
+                var nonceHash = EdgeProtocol.Digest(Encoding.UTF8.GetBytes(task.SourceId.ToString(CultureInfo.InvariantCulture) + ":" + nonce));
+                var receipt = queue.Buffer(batch, nonceHash);
+                return Results.Json(receipt, EdgeProtocol.Json, statusCode: receipt.Status == EdgeProtocol.Buffered ? 202 : 200);
+            }
+            catch (EdgeContractException error)
+            {
+                return Failure(error.Code == "EDGE_STORAGE_LIMIT" ? 429 : 409, error.Code);
+            }
+            catch (Microsoft.Data.Sqlite.SqliteException)
+            {
+                return Failure(503, "EDGE_STORAGE_UNAVAILABLE");
+            }
+        });
+        endpoint.WithMetadata(new Microsoft.AspNetCore.Mvc.RequestSizeLimitAttribute(EdgeProtocol.MaxBodyBytes));
+
+        app.MapGet("/api/v1/edge/push/{datasetKey}/receipts/{key}", (HttpContext context, string datasetKey, string key) =>
+        {
+            context.Response.Headers.CacheControl = "no-store";
+            if (!AllowedPeer(context, peers) || engine.Current is not { Mode: EdgeProtocol.ApiPush } task || task.DatasetKey != datasetKey)
+                return Failure(403, "EDGE_PUSH_FORBIDDEN");
+            var request = context.Request;
+            var timestamp = Header(request, "X-Timestamp", 20);
+            var signature = Header(request, "X-Signature", 64);
+            if (!InTime(timestamp) || Header(request, "X-Access-Key", 96) != access || signature is null)
+                return Failure(403, "EDGE_PUSH_FORBIDDEN");
+            var canonical = string.Join('&', "GET", request.Path.Value, access, timestamp, key);
+            var expected = HMACSHA256.HashData(secret, Encoding.UTF8.GetBytes(canonical));
+            var provided = new byte[32];
+            if (!Convert.TryFromBase64String(signature, provided, out var count) || count != 32
+                || !CryptographicOperations.FixedTimeEquals(expected, provided))
+                return Failure(403, "EDGE_PUSH_FORBIDDEN");
+            if (key.Length is < 1 or > 128 || !key.All(ch => ch is >= '!' and <= '~'))
+                return Failure(400, "EDGE_PUSH_KEY_INVALID");
+            var receipt = queue.Lookup(EdgeBatch.Create(task.Stream, key, null, null, []).BatchId);
+            return receipt is null ? Results.NotFound() : Results.Json(receipt, EdgeProtocol.Json);
+        });
+    }
+
+    private static IResult Failure(int status, string code) => Results.Json(new { code }, statusCode: status);
+
+    private static string? Header(HttpRequest request, string name, int max) =>
+        request.Headers[name] is { Count: 1 } values && values[0] is { Length: > 0 } value
+            && value.Length <= max && value.All(ch => ch is >= '!' and <= '~') ? value : null;
+
+    private static bool InTime(string? timestamp)
+    {
+        var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
+        return long.TryParse(timestamp, NumberStyles.None, CultureInfo.InvariantCulture, out var signed)
+            && signed >= now - 300 && signed <= now + 300;
+    }
+
+    private static IPAddress Normalize(IPAddress value) => value.IsIPv4MappedToIPv6 ? value.MapToIPv4() : value;
+    private static bool AllowedPeer(HttpContext context, HashSet<IPAddress> peers) =>
+        context.Request.IsHttps && context.Connection.RemoteIpAddress is { } peer && peers.Contains(Normalize(peer));
+}

+ 241 - 0
server/Admin.NET.DataPlatform.Edge/EdgeQueue.cs

@@ -0,0 +1,241 @@
+using System.Security.Cryptography;
+using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
+using Microsoft.Data.Sqlite;
+
+namespace Admin.NET.DataPlatform.Edge;
+
+/// <summary>The payload, batch identifier and candidate watermark are one encrypted transaction.</summary>
+public sealed class EdgeQueue
+{
+    private const int NonceSize = 12;
+    private const int TagSize = 16;
+    private readonly string connectionString;
+    private readonly string drive;
+    private readonly byte[] key;
+    private readonly long maxBytes;
+    private readonly long minFree;
+
+    public EdgeQueue(string path, byte[] key, long maxBytes, long minFree)
+    {
+        if (key.Length != 32 || maxBytes <= 0 || minFree < 0)
+            throw new ArgumentException("Invalid queue policy.");
+        this.key = key.ToArray();
+        this.maxBytes = maxBytes;
+        this.minFree = minFree;
+        drive = Path.GetPathRoot(Path.GetFullPath(path))!;
+        connectionString = new SqliteConnectionStringBuilder { DataSource = path, Pooling = false, DefaultTimeout = 5 }.ToString();
+
+        using var db = Open();
+        using var setup = db.CreateCommand();
+        setup.CommandText = """
+            PRAGMA journal_mode=WAL;
+            CREATE TABLE IF NOT EXISTS batch (
+                id TEXT PRIMARY KEY, stream TEXT NOT NULL, digest TEXT NOT NULL,
+                snapshot BLOB, receipt BLOB, terminal INT NOT NULL DEFAULT 0
+            );
+            CREATE INDEX IF NOT EXISTS ix_pending ON batch(terminal,stream);
+            CREATE TABLE IF NOT EXISTS push_nonce(value TEXT PRIMARY KEY, expires INTEGER NOT NULL);
+            CREATE INDEX IF NOT EXISTS ix_nonce_expiry ON push_nonce(expires);
+            """;
+        setup.ExecuteNonQuery();
+    }
+
+    public EdgeReceipt Buffer(EdgeBatch batch, string? nonce = null)
+    {
+        using var db = Open();
+        using var tx = db.BeginTransaction();
+        if (nonce is not null)
+            ReserveNonce(db, tx, nonce);
+        var result = BufferCore(db, tx, batch);
+        tx.Commit();
+        return result;
+    }
+
+    public async Task BufferSnapshotAsync(Func<Action<EdgeBatch>, Task> capture)
+    {
+        using var db = Open();
+        using var tx = db.BeginTransaction();
+        await capture(batch => BufferCore(db, tx, batch));
+        tx.Commit();
+    }
+
+    private EdgeReceipt BufferCore(SqliteConnection db, SqliteTransaction tx, EdgeBatch batch)
+    {
+        batch.Validate();
+        using var known = db.CreateCommand();
+        known.Transaction = tx;
+        known.CommandText = "SELECT digest,receipt FROM batch WHERE id=$id";
+        known.Parameters.AddWithValue("$id", batch.BatchId.ToString("D"));
+        using (var found = known.ExecuteReader())
+        {
+            if (found.Read())
+            {
+                if (found.GetString(0) != batch.Digest)
+                    throw new EdgeContractException("EDGE_BATCH_CONFLICT");
+                return found.IsDBNull(1) ? Buffered(batch) : Decode<EdgeReceipt>(batch.BatchId, (byte[])found[1], receipt: true);
+            }
+        }
+
+        var sealedBatch = Encode(batch.BatchId, batch, receipt: false);
+        using var insert = db.CreateCommand();
+        insert.Transaction = tx;
+        insert.CommandText = """
+            INSERT INTO batch(id,stream,digest,snapshot)
+            SELECT $id,$stream,$digest,$snapshot
+            WHERE (SELECT COALESCE(SUM(length(snapshot)),0) FROM batch) + length($snapshot) <= $maxBytes
+            """;
+        insert.Parameters.AddWithValue("$id", batch.BatchId.ToString("D"));
+        insert.Parameters.AddWithValue("$stream", batch.Stream);
+        insert.Parameters.AddWithValue("$digest", batch.Digest);
+        insert.Parameters.AddWithValue("$snapshot", sealedBatch);
+        insert.Parameters.AddWithValue("$maxBytes", maxBytes);
+        if (new DriveInfo(drive).AvailableFreeSpace < minFree + sealedBatch.Length || insert.ExecuteNonQuery() != 1)
+            throw new EdgeContractException("EDGE_STORAGE_LIMIT");
+        return Buffered(batch);
+    }
+
+    public EdgeBatch? Next(string? stream = null)
+    {
+        using var db = Open();
+        using var cmd = db.CreateCommand();
+        cmd.CommandText = """
+            SELECT id,snapshot FROM batch WHERE terminal=0 AND ($stream IS NULL OR stream=$stream) ORDER BY rowid LIMIT 1
+            """;
+        cmd.Parameters.AddWithValue("$stream", (object?)stream ?? DBNull.Value);
+        using var row = cmd.ExecuteReader();
+        if (!row.Read()) return null;
+        var batch = Decode<EdgeBatch>(Guid.Parse(row.GetString(0)), (byte[])row[1], receipt: false);
+        batch.Validate();
+        return batch;
+    }
+
+    public EdgeReceipt? Lookup(Guid id)
+    {
+        using var db = Open();
+        using var cmd = db.CreateCommand();
+        cmd.CommandText = "SELECT digest,receipt FROM batch WHERE id=$id";
+        cmd.Parameters.AddWithValue("$id", id.ToString("D"));
+        using var row = cmd.ExecuteReader();
+        return !row.Read() ? null : row.IsDBNull(1)
+            ? new EdgeReceipt(id, row.GetString(0), EdgeProtocol.Buffered, null, null)
+            : Decode<EdgeReceipt>(id, (byte[])row[1], receipt: true);
+    }
+
+    public void Record(EdgeBatch batch, EdgeReceipt receipt)
+    {
+        var accepted = receipt.Confirms(batch);
+        if (!accepted && !receipt.Rejects(batch))
+            throw new EdgeContractException("EDGE_RECEIPT_MISMATCH");
+        using var db = Open();
+        using var cmd = db.CreateCommand();
+        cmd.CommandText = """
+            UPDATE batch SET terminal=1,receipt=$receipt,snapshot=CASE WHEN $accepted THEN NULL ELSE snapshot END
+            WHERE id=$id AND stream=$stream AND digest=$digest AND terminal=0
+            """;
+        cmd.Parameters.AddWithValue("$id", batch.BatchId.ToString("D"));
+        cmd.Parameters.AddWithValue("$stream", batch.Stream);
+        cmd.Parameters.AddWithValue("$digest", batch.Digest);
+        cmd.Parameters.AddWithValue("$receipt", Encode(batch.BatchId, receipt, receipt: true));
+        cmd.Parameters.AddWithValue("$accepted", accepted);
+        if (cmd.ExecuteNonQuery() != 1 && Lookup(batch.BatchId) != receipt)
+            throw new EdgeContractException("EDGE_RECEIPT_MISMATCH");
+    }
+
+    public EdgeBatch? ReadRejected(Guid id)
+    {
+        using var db = Open();
+        using var cmd = db.CreateCommand();
+        cmd.CommandText = "SELECT snapshot FROM batch WHERE id=$id AND terminal=1 AND snapshot IS NOT NULL";
+        cmd.Parameters.AddWithValue("$id", id.ToString("D"));
+        return cmd.ExecuteScalar() is byte[] encrypted ? Decode<EdgeBatch>(id, encrypted, receipt: false) : null;
+    }
+
+    // This is called only for IDs named in the authenticated settlement list.
+    public void SettleRejection(EdgeBatch batch, EdgeReceipt receipt)
+    {
+        batch.Validate();
+        if ((!receipt.Confirms(batch) && !receipt.Rejects(batch)) || Lookup(batch.BatchId)?.Rejects(batch) != true)
+            throw new EdgeContractException("EDGE_RECEIPT_MISMATCH");
+        using var db = Open();
+        using var cmd = db.CreateCommand();
+        cmd.CommandText = "UPDATE batch SET snapshot=NULL,receipt=$receipt WHERE id=$id AND digest=$digest AND terminal=1";
+        cmd.Parameters.AddWithValue("$id", batch.BatchId.ToString("D"));
+        cmd.Parameters.AddWithValue("$digest", batch.Digest);
+        cmd.Parameters.AddWithValue("$receipt", Encode(batch.BatchId, receipt, receipt: true));
+        if (cmd.ExecuteNonQuery() != 1)
+            throw new EdgeContractException("EDGE_RECEIPT_MISMATCH");
+    }
+
+    public (int Pending, long Bytes, long FreeBytes) Usage()
+    {
+        using var db = Open();
+        using var cmd = db.CreateCommand();
+        cmd.CommandText = "SELECT COUNT(snapshot),COALESCE(SUM(length(snapshot)),0) FROM batch";
+        using var row = cmd.ExecuteReader();
+        row.Read();
+        return (row.GetInt32(0), row.GetInt64(1), new DriveInfo(drive).AvailableFreeSpace);
+    }
+
+    private static void ReserveNonce(SqliteConnection db, SqliteTransaction tx, string nonce)
+    {
+        using var cmd = db.CreateCommand();
+        cmd.Transaction = tx;
+        cmd.CommandText = "DELETE FROM push_nonce WHERE expires<=$now";
+        cmd.Parameters.AddWithValue("$now", DateTimeOffset.UtcNow.ToUnixTimeSeconds());
+        cmd.ExecuteNonQuery();
+        cmd.CommandText = "INSERT OR IGNORE INTO push_nonce(value,expires) VALUES($nonce,$now+660)";
+        cmd.Parameters.AddWithValue("$nonce", nonce);
+        if (cmd.ExecuteNonQuery() != 1)
+            throw new EdgeContractException("EDGE_PUSH_REPLAY");
+    }
+
+    private SqliteConnection Open()
+    {
+        var db = new SqliteConnection(connectionString);
+        try
+        {
+            db.Open();
+            using var cmd = db.CreateCommand();
+            cmd.CommandText = "PRAGMA synchronous=FULL;";
+            cmd.ExecuteNonQuery();
+            return db;
+        }
+        catch
+        {
+            db.Dispose();
+            throw;
+        }
+    }
+
+    private byte[] Encode<T>(Guid id, T value, bool receipt)
+    {
+        var clear = JsonSerializer.SerializeToUtf8Bytes(value, EdgeProtocol.Json);
+        try
+        {
+            var output = new byte[NonceSize + TagSize + clear.Length];
+            RandomNumberGenerator.Fill(output.AsSpan(0, NonceSize));
+            using var cipher = new AesGcm(key, TagSize);
+            cipher.Encrypt(output.AsSpan(0, NonceSize), clear, output.AsSpan(NonceSize + TagSize),
+                output.AsSpan(NonceSize, TagSize), Scope(id, receipt));
+            return output;
+        }
+        finally { CryptographicOperations.ZeroMemory(clear); }
+    }
+
+    private T Decode<T>(Guid id, byte[] value, bool receipt)
+    {
+        var clear = new byte[value.Length - NonceSize - TagSize];
+        try
+        {
+            using var cipher = new AesGcm(key, TagSize);
+            cipher.Decrypt(value.AsSpan(0, NonceSize), value.AsSpan(NonceSize + TagSize),
+                value.AsSpan(NonceSize, TagSize), clear, Scope(id, receipt));
+            return JsonSerializer.Deserialize<T>(clear, EdgeProtocol.Json) ?? throw new EdgeContractException("EDGE_STORAGE_INVALID");
+        }
+        finally { CryptographicOperations.ZeroMemory(clear); }
+    }
+
+    private static byte[] Scope(Guid id, bool receipt) => [..id.ToByteArray(), receipt ? (byte)1 : (byte)0];
+    private static EdgeReceipt Buffered(EdgeBatch batch) => new(batch.BatchId, batch.Digest, EdgeProtocol.Buffered, null, null);
+}

+ 58 - 0
server/Admin.NET.DataPlatform.Edge/EdgeRelease.cs

@@ -0,0 +1,58 @@
+using System.IO.Compression;
+using System.Runtime.InteropServices;
+using System.Security.Cryptography;
+using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
+
+namespace Admin.NET.DataPlatform.Edge;
+
+internal sealed record EdgeReleaseManifest(string Version, string Platform, string Sha256, int QueueFormat);
+
+internal static class EdgeRelease
+{
+    internal static string Stage(string stateDirectory, string trustedPublisherKey, string manifestFile, string signatureFile, string archiveFile)
+    {
+        var manifestBytes = File.ReadAllBytes(manifestFile);
+        if (manifestBytes.Length is < 1 or > 4096) throw new EdgeContractException("EDGE_RELEASE_MANIFEST_INVALID");
+        using var signer = ECDsa.Create();
+        signer.ImportFromPem(File.ReadAllText(trustedPublisherKey));
+        var signature = Convert.FromBase64String(File.ReadAllText(signatureFile).Trim());
+        if (!signer.VerifyData(manifestBytes, signature, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence))
+            throw new EdgeContractException("EDGE_RELEASE_SIGNATURE_INVALID");
+        var manifest = JsonSerializer.Deserialize<EdgeReleaseManifest>(manifestBytes, EdgeProtocol.Json)
+            ?? throw new EdgeContractException("EDGE_RELEASE_MANIFEST_INVALID");
+        var platform = (OperatingSystem.IsWindows() ? "win-" : "linux-") + RuntimeInformation.OSArchitecture.ToString().ToLowerInvariant();
+        var current = typeof(EdgeRelease).Assembly.GetName().Version!;
+        if (!Version.TryParse(manifest.Version, out var target) || target <= current || manifest.Platform != platform ||
+            manifest.QueueFormat != 1)
+            throw new EdgeContractException("EDGE_RELEASE_INCOMPATIBLE");
+
+        using var archive = File.OpenRead(archiveFile);
+        if (archive.Length is < 1 or > 536870912 || Convert.ToHexString(SHA256.HashData(archive)).ToLowerInvariant() != manifest.Sha256)
+            throw new EdgeContractException("EDGE_RELEASE_DIGEST_INVALID");
+        archive.Position = 0;
+        var releases = Path.Combine(stateDirectory, "releases");
+        Directory.CreateDirectory(releases);
+        var final = Path.Combine(releases, target.ToString());
+        if (Directory.Exists(final)) throw new EdgeContractException("EDGE_RELEASE_ALREADY_STAGED");
+        var temporary = Path.Combine(releases, ".stage-" + Guid.NewGuid().ToString("N"));
+        Directory.CreateDirectory(temporary);
+        try
+        {
+            using var zip = new ZipArchive(archive, ZipArchiveMode.Read);
+            if (zip.Entries.Count > 4096 || zip.Entries.Sum(entry => entry.Length) > 1073741824)
+                throw new EdgeContractException("EDGE_RELEASE_TOO_LARGE");
+            zip.ExtractToDirectory(temporary);
+            var binary = Path.Combine(temporary, OperatingSystem.IsWindows() ? "Admin.NET.DataPlatform.Edge.exe" : "Admin.NET.DataPlatform.Edge");
+            if (!File.Exists(binary)) throw new EdgeContractException("EDGE_RELEASE_EXECUTABLE_MISSING");
+            if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(binary, UnixFileMode.UserRead | UnixFileMode.UserExecute);
+            EdgeLocalState.AtomicWrite(Path.Combine(temporary, "verified-manifest.json"), manifestBytes);
+            Directory.Move(temporary, final);
+            return final;
+        }
+        finally
+        {
+            if (Directory.Exists(temporary)) Directory.Delete(temporary, recursive: true);
+        }
+    }
+}

+ 91 - 0
server/Admin.NET.DataPlatform.Edge/EdgeTransport.cs

@@ -0,0 +1,91 @@
+using System.Net;
+using System.Net.Http.Json;
+using System.Security.Cryptography;
+using System.Security.Cryptography.X509Certificates;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
+
+namespace Admin.NET.DataPlatform.Edge;
+
+internal sealed class EdgeTransport(Uri origin)
+{
+    internal HttpClient Connect(X509Certificate2? certificate)
+    {
+        if (origin.Scheme != "https" || origin.UserInfo.Length != 0 || origin.Query.Length != 0 || origin.Fragment.Length != 0
+            || origin.AbsolutePath != "/")
+            throw new EdgeContractException("EDGE_PLATFORM_URL_INVALID");
+        var handler = new HttpClientHandler { AllowAutoRedirect = false, UseProxy = false, UseCookies = false };
+        if (certificate is not null) handler.ClientCertificates.Add(certificate);
+        return new HttpClient(handler) { BaseAddress = origin, Timeout = TimeSpan.FromSeconds(30) };
+    }
+
+    internal async Task EnrollAsync(EdgeLocalState local, byte[] key, string activation, CancellationToken token)
+    {
+        if (File.Exists(Path.Combine(local.DirectoryPath, "certificate")))
+            throw new EdgeContractException("EDGE_ALREADY_REGISTERED");
+        using var client = Connect(null);
+        using var privateKey = ECDsa.Create(ECCurve.NamedCurves.nistP256);
+        var csr = new CertificateRequest("CN=AiDOP Edge", privateKey, HashAlgorithmName.SHA256);
+        var result = await PostAsync<EdgeRegistration, EdgeCertificate>(client, "/api/v1/edge/register",
+            new(activation, csr.CreateSigningRequestPem()), token) ?? throw new EdgeContractException("EDGE_REGISTRATION_RESPONSE_INVALID");
+        using var leaf = X509Certificate2.CreateFromPem(result.CertificatePem);
+        using var verified = leaf.CopyWithPrivateKey(privateKey);
+        local.WriteCertificate(verified, key);
+    }
+
+    internal async Task RotateAsync(EdgeLocalState local, byte[] queueKey, X509Certificate2 current, CancellationToken token)
+    {
+        using var previouslyPending = local.ReadCertificate(queueKey, pending: true);
+        if (previouslyPending is not null)
+        {
+            try
+            {
+                await ConfirmAsync(previouslyPending, token);
+                local.PromoteCertificate();
+                return;
+            }
+            catch (EdgeContractException error) when (error.Code == "EDGE_DEVICE_FORBIDDEN") { }
+        }
+
+        using var client = Connect(current);
+        using var privateKey = ECDsa.Create(ECCurve.NamedCurves.nistP256);
+        var csr = new CertificateRequest("CN=AiDOP Edge", privateKey, HashAlgorithmName.SHA256);
+        var issued = await PostAsync<EdgeRenewal, EdgeCertificate>(client, "/api/v1/edge/certificate/renew",
+            new(csr.CreateSigningRequestPem()), token) ?? throw new EdgeContractException("EDGE_RENEWAL_RESPONSE_INVALID");
+        using var leaf = X509Certificate2.CreateFromPem(issued.CertificatePem);
+        using var pending = leaf.CopyWithPrivateKey(privateKey);
+        local.WriteCertificate(pending, queueKey, pending: true);
+        await ConfirmAsync(pending, token);
+        local.PromoteCertificate();
+    }
+
+    internal async Task<EdgeReceipt> SendAsync(HttpClient client, EdgeBatch batch, CancellationToken token)
+    {
+        using var status = await client.GetAsync("/api/v1/edge/batches/" + batch.BatchId.ToString("D"), token);
+        if (status.StatusCode != HttpStatusCode.NotFound)
+            return await ReadAsync<EdgeReceipt>(status, token) ?? throw new EdgeContractException("EDGE_RECEIPT_MISSING");
+        return await PostAsync<EdgeBatch, EdgeReceipt>(client, "/api/v1/edge/batches", batch, token)
+            ?? throw new EdgeContractException("EDGE_RECEIPT_MISSING");
+    }
+
+    private async Task ConfirmAsync(X509Certificate2 certificate, CancellationToken token)
+    {
+        using var client = Connect(certificate);
+        using var response = await client.PostAsync("/api/v1/edge/certificate/confirm", null, token);
+        if (!response.IsSuccessStatusCode)
+            throw new EdgeContractException(response.StatusCode == HttpStatusCode.Forbidden ? "EDGE_DEVICE_FORBIDDEN" : "EDGE_CONFIRM_FAILED");
+    }
+
+    internal static async Task<TResponse?> PostAsync<TInput, TResponse>(HttpClient client, string route, TInput input, CancellationToken token)
+    {
+        using var response = await client.PostAsJsonAsync(route, input, EdgeProtocol.Json, token);
+        return await ReadAsync<TResponse>(response, token);
+    }
+
+    private static async Task<T?> ReadAsync<T>(HttpResponseMessage response, CancellationToken token)
+    {
+        if (response.StatusCode == HttpStatusCode.Forbidden) throw new EdgeContractException("EDGE_DEVICE_FORBIDDEN");
+        if (!response.IsSuccessStatusCode) throw new EdgeContractException($"EDGE_PLATFORM_HTTP_{(int)response.StatusCode}");
+        if (response.StatusCode == HttpStatusCode.NoContent) return default;
+        return await response.Content.ReadFromJsonAsync<T>(EdgeProtocol.Json, token);
+    }
+}

+ 123 - 0
server/Admin.NET.DataPlatform.Edge/Program.cs

@@ -0,0 +1,123 @@
+using System.Net;
+using System.Security.Cryptography;
+using Admin.NET.DataPlatform.Edge;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
+
+if (args is ["--stage-release", var dataPath, var publisherKey, var manifest, var signature, var archive])
+{
+    try
+    {
+        Console.WriteLine(EdgeRelease.Stage(Path.GetFullPath(dataPath), publisherKey, manifest, signature, archive));
+        return 0;
+    }
+    catch (Exception error)
+    {
+        Console.Error.WriteLine(error is EdgeContractException edge ? edge.Code : error.GetType().Name);
+        return 1;
+    }
+}
+
+var mode = args.Length == 0 ? "--run" : args[0];
+var configPath = args.Length == 2 ? args[1] : Environment.GetEnvironmentVariable("MDP_EDGE_CONFIG");
+if (mode is not ("--run" or "--enroll" or "--once" or "--status" or "--rotate") || args.Length > 2)
+{
+    Console.Error.WriteLine("Usage: edge [--run|--enroll|--once|--status|--rotate] [config-path]");
+    return 2;
+}
+var settings = new ConfigurationBuilder();
+if (!string.IsNullOrWhiteSpace(configPath)) settings.AddJsonFile(Path.GetFullPath(configPath), optional: false);
+var config = settings.AddEnvironmentVariables().Build();
+
+using var stopping = new CancellationTokenSource();
+Console.CancelKeyPress += (_, eventArgs) => { eventArgs.Cancel = true; stopping.Cancel(); };
+
+try
+{
+    var local = new EdgeLocalState(config["Edge:DataDirectory"] ?? throw new EdgeContractException("EDGE_DATA_PATH_REQUIRED"));
+    local.Initialize();
+    using var ownership = new FileStream(Path.Combine(local.DirectoryPath, "device.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
+    var key = local.ReadKey();
+    try
+    {
+        var queue = new EdgeQueue(Path.Combine(local.DirectoryPath, "outbox.db"), key, config.GetValue("Edge:MaxBufferedBytes", 268435456L),
+            config.GetValue("Edge:MinimumFreeBytes", 67108864L));
+        if (mode == "--status")
+        {
+            using var certificate = local.ReadCertificate(key);
+            var usage = queue.Usage();
+            Console.WriteLine($"registered={certificate is not null} backlog={usage.Pending} bytes={usage.Bytes} free={usage.FreeBytes}");
+            return 0;
+        }
+
+        var transport = new EdgeTransport(new Uri(config["Edge:Platform"] ?? throw new EdgeContractException("EDGE_PLATFORM_URL_REQUIRED")));
+        if (mode == "--enroll")
+        {
+            var activation = Environment.GetEnvironmentVariable("MDP_EDGE_ACTIVATION")
+                ?? Console.ReadLine() ?? throw new EdgeContractException("EDGE_ACTIVATION_REQUIRED");
+            await transport.EnrollAsync(local, key, activation, stopping.Token);
+            Console.WriteLine("EDGE_REGISTERED");
+            return 0;
+        }
+        if (mode == "--rotate")
+        {
+            using var certificate = local.ReadCertificate(key) ?? throw new EdgeContractException("EDGE_NOT_REGISTERED");
+            await transport.RotateAsync(local, key, certificate, stopping.Token);
+            return 0;
+        }
+
+        if (mode == "--run" && !File.Exists(Path.Combine(local.DirectoryPath, "certificate")))
+        {
+            var credentials = Environment.GetEnvironmentVariable("CREDENTIALS_DIRECTORY");
+            var bootstrap = config["Edge:ActivationFile"] ??
+                (string.IsNullOrEmpty(credentials) ? null : Path.Combine(credentials, "edge-activation"));
+            if (!string.IsNullOrEmpty(bootstrap) && File.Exists(bootstrap))
+            {
+                await transport.EnrollAsync(local, key, File.ReadAllText(bootstrap).Trim(), stopping.Token);
+                if (config["Edge:ActivationFile"] is not null) File.Delete(bootstrap);
+            }
+        }
+        var engine = new EdgeEngine(local, key, queue, transport, config);
+        if (mode == "--once") return await engine.WorkAsync(stopping.Token) ? 0 : 1;
+        if (config["Edge:PushListen"] is { } listener)
+        {
+            var uri = new Uri(listener);
+            if (uri.Scheme != "https" || !IPAddress.TryParse(uri.Host, out var ip) || ip.Equals(IPAddress.Any)
+                || ip.Equals(IPAddress.IPv6Any) || uri.AbsolutePath != "/" || uri.Query.Length != 0 || uri.UserInfo.Length != 0)
+                throw new EdgeContractException("EDGE_PUSH_LISTENER_INVALID");
+            var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = [] });
+            builder.Configuration.AddConfiguration(config);
+            builder.Host.UseWindowsService();
+            builder.WebHost.UseUrls(listener);
+            builder.Services.AddHostedService(_ => new EdgeWorker(engine));
+            var app = builder.Build();
+            EdgePush.Map(app, engine, queue, config);
+            await app.RunAsync(stopping.Token);
+        }
+        else
+        {
+            using var host = Host.CreateDefaultBuilder([]).UseWindowsService()
+                .ConfigureServices(services => services.AddHostedService(_ => new EdgeWorker(engine))).Build();
+            await host.RunAsync(stopping.Token);
+        }
+        return 0;
+    }
+    finally { CryptographicOperations.ZeroMemory(key); }
+}
+catch (OperationCanceledException) when (stopping.IsCancellationRequested) { return 0; }
+catch (Exception error)
+{
+    Console.Error.WriteLine(error is EdgeContractException edge ? edge.Code : error.GetType().Name);
+    return 1;
+}
+
+internal sealed class EdgeWorker(EdgeEngine engine) : BackgroundService
+{
+    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+    {
+        while (!stoppingToken.IsCancellationRequested)
+        {
+            await engine.WorkAsync(stoppingToken);
+            await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
+        }
+    }
+}

+ 57 - 0
server/Admin.NET.DataPlatform.Edge/README.md

@@ -0,0 +1,57 @@
+# 工厂数据接入助手
+
+助手在工厂内网运行,支持关系库稳定快照及有序日志增量、HTTPS API 拉取、签名 API 转发。数据沿设备 mTLS 通道交给 Ai-DOP 设备入口,统一 Raw 接收后进入现有采购 Worker。
+
+## 云端准备
+
+1. 在统一接收和采购迁移之后,应用 `1.0.623.sql`,并执行 `1.0.623.verify.sql` 核验设备、回执和异常页恢复表。
+2. 为设备入口准备 HTTPS 监听及可验证客户端证书的 TLS 配置。可用 Kestrel 的设备 HTTPS 端点设置 ClientCertificateMode 为 AllowCertificate,注册请求允许无客户端证书,运行请求由控制器校验客户端证书。将设备信任链安装到该监听的受控信任设施。
+3. 开启 MdpEdge:Enabled,从受限文件和密钥配置提供 MdpEdge:CaPfxPath 和 MdpEdge:CaPfxPassword。签发 CA 支持 RSA 或 ECDSA。客户端证书按已登记指纹和实时状态验权。
+4. 在 Ai-DOP 数据源管理的接收数据集中展开工厂数据接入助手。为已发布的来源审批设备,保存短期激活码并选择采集任务。操作权限复用数据集试跑与发布按钮权限。
+
+管理接口位于 api/DataPlatform/ingest-datasets/{datasetId}/edge,设备接口位于 api/v1/edge。启用时同一来源的直连写入须取得互斥执行资格。具有旧直连运行记录的关系库和 API 拉取来源暂由交接门禁保护,适用于新建的受控试点来源。已接受的 API 推送保留来源幂等键。
+
+## 设备配置
+
+运行入口为 Admin.NET.DataPlatform.Edge。参数支持 --run、--enroll、--status、--rotate,后接绝对配置文件路径。--enroll 从标准输入或 MDP_EDGE_ACTIVATION 读取激活码。Windows 服务也可一次性读取 ACL 保护的 Edge:ActivationFile。Linux 系统服务从 systemd 的 edge-activation 读取启动凭据。
+
+| 配置项 | 用途 |
+| --- | --- |
+| Edge:Platform | 云端设备 HTTPS 源站,形如 https://gateway.example.com/ |
+| Edge:DataDirectory | 由专用服务身份独占的绝对数据目录,保存密文队列、证书、任务和健康状态 |
+| Edge:MaxBufferedBytes / MinimumFreeBytes | 可积压密文上限和预留磁盘空间 |
+| Edge:Relational | 本机批准的驱动、库、Schema、表、位置字段、列清单和凭据引用,须与云端任务匹配 |
+| MdpApiPull:Targets / Credentials | 现有出站允许清单和凭据引用,按租户与来源配置 |
+| Edge:PushListen / PushPeers | 启用本机 HTTPS 推送接收时设置实际内网监听地址及允许的来源 IP |
+| Edge:PushAccessKey | 已登记推送来源凭据的标识,HMAC 密钥由 MDP_EDGE_SECRET_PUSH 提供 |
+
+Windows 队列主密钥用服务账号的 DPAPI 保护,部署时确认账号可加载自己的用户配置和安全存储。Linux 通过 systemd 的 edge-queue-key 加载 32 字节 Base64 密钥,或使用权限为 0600 的 MDP_EDGE_KEY_FILE。关系库的 MDP_EDGE_SECRET_ 前缀凭据从服务的受保护凭据目录或受信执行环境解析。凭据、数据目录、队列备份和制品签名公钥均按独立权限配置。
+
+### 数据库任务
+
+全量任务使用支持一致性快照的只读驱动,一次快照的所有分页在本地事务封存后可发送。数据库增量可使用已批准的连续、单调变更日志位置。开启增量并留空 `resumePosition` 时,同设备上一轮完成的关系库水位作为起点。
+
+PostgreSQL 还支持时间列与并列键组成的水位。在云端任务和本机 `Edge:Relational` 中使用一致的 `time` 配置,其中 `column` 为带时区的变更时间列,`delaySeconds`、`lookbackSeconds`、`retentionSeconds` 分别控制安全延迟、回看长度和可补读范围。`positionColumn` 提供同一时间内的稳定行顺序。设备保留分页确认位置,在整窗最后一页确认后才推进时间水位。增量任务沿用同一来源在上一轮完成的时间水位。
+
+采购版本场景在关系库任务设定正数 sourceGeneration、changeVersionColumn、可选 deleteColumn,并在来源列中投影版本及删除字段。采购活跃记录提供契约所需的带时区 sourceUpdatedAt,验证各驱动的时间值表达和删除字段类型。完成空页会保留回执,记录该快照的最后位置。
+
+### API 拉取异常恢复
+
+在接入中心打开被阻断设备的恢复入口。响应结构需要重新映射时,先按新数组路径预演,再根据有效行和隔离行结果审批。原文重解析沿用原 Raw 与批次号。源端修复后可审批原位重取,旧拒收 Raw 保留,修复后的响应进入新批次。设备取得云端结算回执后回收本地拒收缓存。
+
+### 内网推送
+
+由 HTTPS 向 POST api/v1/edge/push/{datasetKey} 发送 JSON 或 NDJSON。采用已有 v2 签名语义,签名路径为该本地入口,包含方法、来源键、时间、Nonce、摘要、幂等键、媒体类型、工厂及版本。服务停机、身份、签名、大小及配额均有可识别的拒绝响应。
+
+返回 202 和 buffered 时,原文已经本地持久化。业务方可使用有签名的 GET api/v1/edge/push/{datasetKey}/receipts/{key} 查询,签名串依次为 GET、路径、来源键、时间戳和幂等键,以 & 连接并进行 HMAC-SHA256。accepted 返回云端 Raw 批次号,代表持久接收。后续 Worker 与交接状态在 Ai-DOP 批次查询中查看。
+
+## 安装和升级
+
+- Linux 使用 deploy/aidop-edge.service,预先创建专用账号、安装目录、配置及加密凭据文件。当前制品由 /opt/aidop-edge/current 指向,状态保存在 /var/lib/aidop-edge。
+- Windows 使用 deploy/Install-EdgeService.ps1,以专用低权限服务账号安装。制品和发布公钥由运维目录 ACL 保护,服务账号仅获所需读权限,设备状态目录单独授权。
+- 升级制品为签名清单和 ZIP。清单包含 version、platform、sha256、queueFormat,签名使用 ECDSA SHA-256 DER 后 Base64。设备验证签名、摘要、平台、版本方向和队列兼容号后才允许进入分版本目录。
+- Linux 和 Windows 使用 deploy 下的切换脚本。用设备上传成功后的健康文件判定新制品是否可用。失败时启动前一版本,恢复后用同一队列继续发送未确认数据。记录已批准的版本、公钥、制品摘要、健康证据和回滚结果。
+
+## 当前联调边界
+
+目标部署前继续验证正式 Windows 服务安装和服务切换,以及有历史运行的云边位置接续。当前维修操作通过受控安装和升级脚本执行。已有隔离环境覆盖 MySQL 整数顺序日志与 PostgreSQL 复合时间水位。其他驱动组合按各自适用环境验证。

+ 21 - 0
server/Admin.NET.DataPlatform.Edge/deploy/Install-EdgeService.ps1

@@ -0,0 +1,21 @@
+#Requires -Version 7.0
+#Requires -RunAsAdministrator
+[CmdletBinding()]
+param(
+    [Parameter(Mandatory)][string] $Executable,
+    [Parameter(Mandatory)][string] $Config,
+    [Parameter(Mandatory)][pscredential] $ServiceCredential
+)
+
+$ErrorActionPreference = 'Stop'
+$exePath = (Resolve-Path -LiteralPath $Executable).Path
+$configPath = (Resolve-Path -LiteralPath $Config).Path
+if ([System.IO.Path]::GetFileName($exePath) -ne 'Admin.NET.DataPlatform.Edge.exe') {
+    throw 'Expected the published Edge executable.'
+}
+if (Get-Service -Name 'AiDopDataEdge' -ErrorAction SilentlyContinue) {
+    throw 'Service already exists.'
+}
+$binary = "`"$exePath`" --run `"$configPath`""
+New-Service -Name 'AiDopDataEdge' -DisplayName 'Ai-DOP Factory Data Ingress' -BinaryPathName $binary -Credential $ServiceCredential -StartupType Automatic
+Start-Service -Name 'AiDopDataEdge'

+ 59 - 0
server/Admin.NET.DataPlatform.Edge/deploy/Switch-EdgeRelease.ps1

@@ -0,0 +1,59 @@
+#Requires -Version 7.0
+#Requires -RunAsAdministrator
+[CmdletBinding()]
+param(
+    [Parameter(Mandatory)][string] $InstallRoot,
+    [Parameter(Mandatory)][string] $DataDirectory,
+    [Parameter(Mandatory)][string] $Config,
+    [Parameter(Mandatory)][string] $Manifest,
+    [Parameter(Mandatory)][string] $Signature,
+    [Parameter(Mandatory)][string] $Archive,
+    [ValidateRange(4, 90)][int] $HealthSeconds = 20
+)
+
+$ErrorActionPreference = 'Stop'
+$name = 'AiDopDataEdge'
+$root = (Resolve-Path -LiteralPath $InstallRoot).Path
+$publisher = Join-Path $root 'publisher.pem'
+$cfg = (Resolve-Path -LiteralPath $Config).Path
+$health = Join-Path (Resolve-Path -LiteralPath $DataDirectory).Path 'health'
+$service = Get-CimInstance -ClassName Win32_Service -Filter "Name='AiDopDataEdge'"
+if (!$service -or $service.PathName -notmatch '^"([^"]+)" --run "[^"]+"$') {
+    throw 'Expected the service created by Install-EdgeService.'
+}
+$previousCommand = $service.PathName
+$previousExecutable = $Matches[1]
+$stage = & $previousExecutable --stage-release $root $publisher $Manifest $Signature $Archive
+if ($LASTEXITCODE -ne 0) { throw 'Release verification failed.' }
+$next = (Resolve-Path -LiteralPath (Join-Path $stage 'Admin.NET.DataPlatform.Edge.exe')).Path
+$releaseRoot = Join-Path $root 'releases'
+if (!$next.StartsWith($releaseRoot + [System.IO.Path]::DirectorySeparatorChar, [StringComparison]::OrdinalIgnoreCase)) {
+    throw 'Staged release is outside the installation root.'
+}
+
+function Set-ServiceBinary([string] $Binary) {
+    & sc.exe config $name 'binPath=' $Binary | Out-Null
+    if ($LASTEXITCODE -ne 0) { throw 'Service binary configuration failed.' }
+}
+Stop-Service -Name $name
+try {
+    $cutover = [DateTime]::UtcNow
+    Set-ServiceBinary ('"{0}" --run "{1}"' -f $next, $cfg)
+    Start-Service -Name $name
+    $deadline = [DateTime]::UtcNow.AddSeconds($HealthSeconds)
+    do {
+        if ((Get-Service -Name $name).Status -eq 'Running' -and
+            (Test-Path -LiteralPath $health) -and (Get-Item -LiteralPath $health).LastWriteTimeUtc -gt $cutover) {
+            Write-Output ('Activated ' + $next)
+            return
+        }
+        Start-Sleep -Milliseconds 500
+    } while ([DateTime]::UtcNow -lt $deadline)
+    throw 'New service version did not report health.'
+}
+catch {
+    Stop-Service -Name $name -ErrorAction SilentlyContinue
+    Set-ServiceBinary $previousCommand
+    Start-Service -Name $name
+    throw
+}

+ 23 - 0
server/Admin.NET.DataPlatform.Edge/deploy/aidop-edge.service

@@ -0,0 +1,23 @@
+[Unit]
+Description=Ai-DOP Factory Data Ingress
+After=network-online.target
+Wants=network-online.target
+
+[Service]
+Type=simple
+User=aidop-edge
+Group=aidop-edge
+UMask=0077
+ExecStart=/opt/aidop-edge/current/Admin.NET.DataPlatform.Edge --run /etc/aidop-edge/edge.json
+LoadCredentialEncrypted=edge-queue-key:/etc/aidop-edge/credentials/edge-queue-key
+LoadCredentialEncrypted=edge-activation:/etc/aidop-edge/credentials/edge-activation
+StateDirectory=aidop-edge
+NoNewPrivileges=yes
+PrivateTmp=yes
+ProtectSystem=strict
+ProtectHome=yes
+Restart=on-failure
+RestartSec=5s
+
+[Install]
+WantedBy=multi-user.target

+ 37 - 0
server/Admin.NET.DataPlatform.Edge/deploy/switch-release.sh

@@ -0,0 +1,37 @@
+#!/usr/bin/env bash
+set -euo pipefail
+[[ $# == 5 ]] || { echo "usage: switch-release.sh publisher.pem manifest.json signature.txt release.zip health-seconds" >&2; exit 2; }
+root=/opt/aidop-edge
+data=/var/lib/aidop-edge
+config=/etc/aidop-edge/edge.json
+unit=aidop-edge.service
+health="$5"
+[[ "$health" =~ ^[1-9][0-9]?$ && "$health" -ge 4 ]]
+exec 9>/run/lock/aidop-edge-upgrade.lock
+flock -n 9
+prior="$(realpath "$root/current")"
+[[ "$prior" == "$root/"* || "$prior" == "$data/releases/"* ]]
+candidate="$("$prior/Admin.NET.DataPlatform.Edge" --stage-release "$root" "$1" "$2" "$3" "$4")"
+[[ "$candidate" == "$root/releases/"* && -x "$candidate/Admin.NET.DataPlatform.Edge" ]]
+chown -R root:aidop-edge "$candidate"
+chmod -R u=rwX,g=rX,o= "$candidate"
+switch_link() {
+  local target="$1"
+  ln -s "$target" "$root/current.pending"
+  mv -Tf "$root/current.pending" "$root/current"
+}
+rollback() {
+  systemctl stop "$unit"
+  switch_link "$prior"
+  systemctl start "$unit"
+  logger -t aidop-edge-upgrade "rolled back to $(basename "$prior")"
+}
+systemctl stop "$unit"
+if ! switch_link "$candidate" || ! systemctl start "$unit"; then rollback; exit 1; fi
+sleep "$health"
+if ! systemctl is-active --quiet "$unit" || [[ ! -f "$data/health" ]] ||
+   [[ "$(stat -c %Y "$data/health")" -le "$(stat -c %Y "$root/current")" ]]; then
+  rollback
+  exit 1
+fi
+logger -t aidop-edge-upgrade "activated $(basename "$candidate")"

+ 11 - 3
server/Admin.NET.Web.Entry/Admin.NET.Web.Entry.csproj

@@ -11,9 +11,9 @@
     <GenerateSatelliteAssembliesForCore>true</GenerateSatelliteAssembliesForCore>
     <Copyright>Admin.NET</Copyright>
     <Description>Admin.NET 通用权限开发平台</Description>
-    <AssemblyVersion>1.0.622</AssemblyVersion>
-    <FileVersion>1.0.622</FileVersion>
-    <Version>1.0.622</Version>
+    <AssemblyVersion>1.0.623</AssemblyVersion>
+    <FileVersion>1.0.623</FileVersion>
+    <Version>1.0.623</Version>
   </PropertyGroup>
 
   <ItemGroup>
@@ -1070,6 +1070,14 @@
       <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
       <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
     </None>
+    <None Update="UpdateScripts\1.0.623.sql">
+      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
+    </None>
+    <None Update="UpdateScripts\1.0.623.verify.sql">
+      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
+    </None>
     <None Update="UpdateScripts\MDP-PURCHASE-DISPATCH-GUARDS.ops.sql" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
     <None Update="UpdateScripts\UAT-PLACEHOLDER-MENU-HIDE.ops.sql">
       <CopyToOutputDirectory>Always</CopyToOutputDirectory>

+ 48 - 0
server/Admin.NET.Web.Entry/UpdateScripts/1.0.623.sql

@@ -0,0 +1,48 @@
+-- Apply after unified Raw, dataset release and purchase handoff migrations.
+CREATE TABLE IF NOT EXISTS mdp_edge_device (
+    device_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY,
+    tenant_id BIGINT NOT NULL, factory_id BIGINT NOT NULL, dataset_id BIGINT NOT NULL, source_id BIGINT NOT NULL,
+    device_name VARCHAR(120) NOT NULL,
+    state VARCHAR(16) NOT NULL,
+    active_slot TINYINT NULL,
+    activation_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL,
+    activation_expires DATETIME(6) NULL,
+    certificate_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL,
+    certificate_expires DATETIME(6) NULL,
+    next_certificate_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL,
+    next_certificate_expires DATETIME(6) NULL,
+    config_generation BIGINT NOT NULL DEFAULT 0,
+    config_json JSON NULL, position_text MEDIUMTEXT NULL, task_phase VARCHAR(16) NULL,
+    seen_at DATETIME(6) NULL, report_json JSON NULL,
+    page_count INT NOT NULL DEFAULT 0, row_count BIGINT NOT NULL DEFAULT 0,
+    created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
+    UNIQUE KEY uk_edge_binding (tenant_id,factory_id,dataset_id,source_id,active_slot),
+    UNIQUE KEY uk_edge_activation (activation_hash),
+    UNIQUE KEY uk_edge_certificate (certificate_hash),
+    UNIQUE KEY uk_edge_pending_certificate (next_certificate_hash),
+    KEY ix_edge_devices (tenant_id,factory_id,dataset_id)
+) ENGINE=InnoDB;
+
+CREATE TABLE IF NOT EXISTS mdp_edge_receipt (
+    batch_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY,
+    device_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+    tenant_id BIGINT NOT NULL, factory_id BIGINT NOT NULL, dataset_id BIGINT NOT NULL, source_id BIGINT NOT NULL,
+    generation BIGINT NOT NULL, idem_key VARBINARY(128) NOT NULL,
+    digest CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+    position_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL,
+    receipt_json JSON NOT NULL, created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
+    KEY ix_edge_receipt_position (device_id,generation,position_hash),
+    KEY ix_edge_receipt_binding (tenant_id,factory_id,dataset_id,source_id,created_at)
+) ENGINE=InnoDB;
+
+-- Recovery records reference the existing Raw batch and device.
+CREATE TABLE IF NOT EXISTS mdp_edge_api_rejected_page (
+    batch_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY,
+    device_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+    generation BIGINT NOT NULL,
+    position_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+    effective_url VARCHAR(2048) NULL, next_link VARCHAR(2048) NULL, link_diagnostic VARCHAR(80) NULL,
+    settlement VARCHAR(16) NULL, response_path VARCHAR(112) NULL, settled_at DATETIME(6) NULL,
+    KEY ix_edge_api_reject_position (device_id,generation,position_hash),
+    KEY ix_edge_api_reject_settlement (device_id,settled_at)
+) ENGINE=InnoDB;

+ 22 - 0
server/Admin.NET.Web.Entry/UpdateScripts/1.0.623.verify.sql

@@ -0,0 +1,22 @@
+SELECT IF(COUNT(*)=3,1,0) AS edge_tables
+FROM information_schema.TABLES
+WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN ('mdp_edge_device','mdp_edge_receipt','mdp_edge_api_rejected_page');
+
+SELECT IF(GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX)='tenant_id,factory_id,dataset_id,source_id,active_slot',1,0) AS edge_exclusive_binding
+FROM information_schema.STATISTICS
+WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='mdp_edge_device' AND INDEX_NAME='uk_edge_binding' AND NON_UNIQUE=0;
+
+SELECT IF(COUNT(*)=3,1,0) AS edge_credential_uniqueness
+FROM information_schema.STATISTICS
+WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='mdp_edge_device' AND NON_UNIQUE=0
+    AND ((INDEX_NAME='uk_edge_activation' AND COLUMN_NAME='activation_hash')
+      OR (INDEX_NAME='uk_edge_certificate' AND COLUMN_NAME='certificate_hash')
+      OR (INDEX_NAME='uk_edge_pending_certificate' AND COLUMN_NAME='next_certificate_hash'));
+
+SELECT IF(COUNT(*)=1,1,0) AS edge_batch_once
+FROM information_schema.STATISTICS
+WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='mdp_edge_receipt' AND INDEX_NAME='PRIMARY' AND COLUMN_NAME='batch_id';
+
+SELECT IF(GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX)='device_id,generation,position_hash',1,0) AS edge_recovery_position
+FROM information_schema.STATISTICS
+WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='mdp_edge_api_rejected_page' AND INDEX_NAME='ix_edge_api_reject_position';

+ 14 - 0
server/Admin.NET.sln

@@ -42,6 +42,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Admin.NET.DataPlatform.Work
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Admin.NET.Plugin.AiDOP.DataPlatform.Relational", "Plugins\Admin.NET.Plugin.AiDOP.DataPlatform.Relational\Admin.NET.Plugin.AiDOP.DataPlatform.Relational.csproj", "{D9C4FD67-1CE6-4A8D-9A9F-A83E97D0D561}"
 EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Admin.NET.DataPlatform.Edge", "Admin.NET.DataPlatform.Edge\Admin.NET.DataPlatform.Edge.csproj", "{A1E20F93-CB01-4571-BED4-BD1FE1F106B1}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Any CPU = Debug|Any CPU
@@ -243,6 +245,18 @@ Global
 		{D9C4FD67-1CE6-4A8D-9A9F-A83E97D0D561}.Release|x64.Build.0 = Release|Any CPU
 		{D9C4FD67-1CE6-4A8D-9A9F-A83E97D0D561}.Release|x86.ActiveCfg = Release|Any CPU
 		{D9C4FD67-1CE6-4A8D-9A9F-A83E97D0D561}.Release|x86.Build.0 = Release|Any CPU
+		{A1E20F93-CB01-4571-BED4-BD1FE1F106B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{A1E20F93-CB01-4571-BED4-BD1FE1F106B1}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{A1E20F93-CB01-4571-BED4-BD1FE1F106B1}.Debug|x64.ActiveCfg = Debug|Any CPU
+		{A1E20F93-CB01-4571-BED4-BD1FE1F106B1}.Debug|x64.Build.0 = Debug|Any CPU
+		{A1E20F93-CB01-4571-BED4-BD1FE1F106B1}.Debug|x86.ActiveCfg = Debug|Any CPU
+		{A1E20F93-CB01-4571-BED4-BD1FE1F106B1}.Debug|x86.Build.0 = Debug|Any CPU
+		{A1E20F93-CB01-4571-BED4-BD1FE1F106B1}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{A1E20F93-CB01-4571-BED4-BD1FE1F106B1}.Release|Any CPU.Build.0 = Release|Any CPU
+		{A1E20F93-CB01-4571-BED4-BD1FE1F106B1}.Release|x64.ActiveCfg = Release|Any CPU
+		{A1E20F93-CB01-4571-BED4-BD1FE1F106B1}.Release|x64.Build.0 = Release|Any CPU
+		{A1E20F93-CB01-4571-BED4-BD1FE1F106B1}.Release|x86.ActiveCfg = Release|Any CPU
+		{A1E20F93-CB01-4571-BED4-BD1FE1F106B1}.Release|x86.Build.0 = Release|Any CPU
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

+ 90 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Edge/EdgeProtocol.cs

@@ -0,0 +1,90 @@
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
+
+public static class EdgeProtocol
+{
+    public const int MaxBodyBytes = 1024 * 1024;
+    public const int MaxPositionLength = 8192;
+    public const string Buffered = "buffered";
+    public const string Accepted = "accepted";
+    public const string Empty = "empty";
+    public const string Rejected = "rejected";
+    public const string Database = "database";
+    public const string ApiPull = "api-pull";
+    public const string ApiPush = "api-push";
+
+    public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
+
+    public static string Digest(ReadOnlySpan<byte> bytes) => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
+}
+
+public sealed record EdgeBatch(Guid BatchId, string Stream, string Key, string Digest, string? Position,
+    string? NextPosition, byte[] Body, string? EffectiveUrl = null, string? NextLink = null, string? Diagnostic = null,
+    bool Ndjson = false, bool ReceiverConfirmsNext = false)
+{
+    public static EdgeBatch Create(string stream, string key, string? position, string? nextPosition, byte[] body)
+    {
+        var batch = new EdgeBatch(StableId(stream, key), stream, key, EdgeProtocol.Digest(body), position, nextPosition, body.ToArray());
+        batch.Validate();
+        return batch;
+    }
+
+    public void Validate()
+    {
+        if (!ValidKey(Stream, 96) || !ValidKey(Key, 128)
+            || Body is null || Body.Length > EdgeProtocol.MaxBodyBytes || BatchId != StableId(Stream, Key)
+            || Digest != EdgeProtocol.Digest(Body)
+            || Position?.Length > EdgeProtocol.MaxPositionLength || NextPosition?.Length > EdgeProtocol.MaxPositionLength
+            || EffectiveUrl?.Length > 2048 || NextLink?.Length > 2048 || Diagnostic?.Length > 80)
+            throw new EdgeContractException("EDGE_BATCH_INVALID");
+    }
+
+    private static bool ValidKey(string? value, int limit) =>
+        value is { Length: > 0 } && value.Length <= limit && value.All(ch => ch is >= '!' and <= '~');
+
+    private static Guid StableId(string stream, string key) =>
+        new(SHA256.HashData(Encoding.UTF8.GetBytes(stream + "\n" + key)).AsSpan(0, 16));
+}
+
+public sealed record EdgeReceipt(Guid BatchId, string Digest, string Status, Guid? RawBatchId, string? ConfirmedPosition,
+    string? Diagnostic = null, string? SourcePosition = null)
+{
+    public bool Confirms(EdgeBatch batch) =>
+        BatchId == batch.BatchId && Digest == batch.Digest && RawBatchId is { } id && id != Guid.Empty
+        && Status is EdgeProtocol.Accepted or EdgeProtocol.Empty
+        && (batch.ReceiverConfirmsNext ? SourcePosition == batch.Position : ConfirmedPosition == batch.NextPosition);
+
+    public bool Rejects(EdgeBatch batch) =>
+        BatchId == batch.BatchId && Digest == batch.Digest && RawBatchId is { } id && id != Guid.Empty
+        && Status == EdgeProtocol.Rejected && ConfirmedPosition == batch.Position;
+}
+
+public sealed record EdgeRegistration(string Activation, string RequestPem);
+public sealed record EdgeCertificate(Guid DeviceId, string CertificatePem);
+public sealed record EdgeRenewal(string RequestPem);
+public sealed record EdgeReport(string Version, int Pending, long BufferedBytes, long FreeBytes, string? LastError);
+public sealed record EdgeRelationalSettings(string Driver, string Database, string Schema, string Table,
+    string PositionColumn, string[] Columns, string SecretRef, int PageSize = 100, bool Incremental = false,
+    string? OdbcFamily = null, long? UpperPosition = null, string? ChangeVersionColumn = null,
+    string? DeleteColumn = null, long? SourceGeneration = null, EdgeRelationalTimeSettings? Time = null);
+public sealed record EdgeTask(string Stream, string Mode, long TenantId, long FactoryId, long SourceId, long DatasetId,
+    string SourceCode, string DatasetKey, string SchemaVersion, string ConfigVersion, string? Position,
+    string State, string? ApiPlan = null, EdgeRelationalSettings? Relational = null, DateTimeOffset? LeaseUntil = null, int PageCount = 0, long RowCount = 0,
+    int RecoveryAttempt = 0, IReadOnlyList<Guid>? SettledPages = null, string? StartPosition = null)
+{
+    public string PageKey()
+    {
+        if (Mode != EdgeProtocol.ApiPull || Position is null || RecoveryAttempt < 0)
+            throw new EdgeContractException("EDGE_POSITION_INVALID");
+        var hash = EdgeProtocol.Digest(Encoding.UTF8.GetBytes(Position));
+        return RecoveryAttempt == 0 ? "page-" + hash : FormattableString.Invariant($"page-{hash}-{RecoveryAttempt}");
+    }
+}
+
+public sealed class EdgeContractException(string code) : Exception(code)
+{
+    public string Code { get; } = code;
+}

+ 56 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Edge/EdgeTimeWatermark.cs

@@ -0,0 +1,56 @@
+using System.Globalization;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
+
+public sealed record EdgeRelationalTimeSettings(string Column, int DelaySeconds, int LookbackSeconds, int RetentionSeconds)
+{
+    public bool IsValid() => Column is { Length: > 0 and <= 63 } && Column.All(ch => char.IsAsciiLetterOrDigit(ch) || ch == '_')
+        && DelaySeconds > 0 && LookbackSeconds >= DelaySeconds && RetentionSeconds > (long)LookbackSeconds + DelaySeconds;
+}
+
+public static class EdgeTimeWatermark
+{
+    private const string BoundaryPrefix = "until:";
+    private const string PagePrefix = "page:";
+
+    public static string Encode(DateTimeOffset value) => FormattableString.Invariant($"{BoundaryPrefix}{value.UtcTicks}");
+
+    public static DateTimeOffset Decode(string? value)
+    {
+        if (value is null || !value.StartsWith(BoundaryPrefix, StringComparison.Ordinal)
+            || !long.TryParse(value.AsSpan(BoundaryPrefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out var ticks)
+            || ticks < 0 || ticks > DateTime.MaxValue.Ticks)
+            throw new EdgeContractException("EDGE_TIME_BOUNDARY_INVALID");
+        return new DateTimeOffset(ticks, TimeSpan.Zero);
+    }
+
+    public static string Page(string checkpoint) => PagePrefix + checkpoint;
+
+    public static bool AdvancesPage(string? from, string? to, bool incremental)
+    {
+        if (to?.StartsWith(PagePrefix, StringComparison.Ordinal) != true) return false;
+        try
+        {
+            if (incremental)
+            {
+                var next = RelationalTimePosition.Parse(to[PagePrefix.Length..]);
+                if (from?.StartsWith(BoundaryPrefix, StringComparison.Ordinal) == true)
+                {
+                    _ = Decode(from);
+                    return true;
+                }
+                return from?.StartsWith(PagePrefix, StringComparison.Ordinal) == true
+                    && next.CompareTo(RelationalTimePosition.Parse(from[PagePrefix.Length..])) > 0;
+            }
+            return long.TryParse(to.AsSpan(PagePrefix.Length), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var nextKey)
+                && (from is null || (from.StartsWith(PagePrefix, StringComparison.Ordinal)
+                    && long.TryParse(from.AsSpan(PagePrefix.Length), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var previous)
+                    && nextKey > previous));
+        }
+        catch (ConnectorContractException)
+        {
+            return false;
+        }
+    }
+}

+ 72 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpEdgeReceiptTests.cs

@@ -0,0 +1,72 @@
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+using Xunit;
+
+namespace Admin.NET.Plugin.AiDOP.Tests.DataPlatform;
+
+public sealed class MdpEdgeReceiptTests
+{
+    [Fact]
+    public void OnlyMatchingCloudReceiptCanCommitPosition()
+    {
+        var batch = EdgeBatch.Create("run-A", "page-1", "initial", "next", [1, 2, 3]);
+        var cached = new EdgeReceipt(batch.BatchId, batch.Digest, "buffered", null, null);
+        Assert.False(cached.Confirms(batch));
+
+        var accepted = cached with { Status = "accepted", RawBatchId = Guid.NewGuid(), ConfirmedPosition = "next" };
+        Assert.True(accepted.Confirms(batch));
+        Assert.False((accepted with { BatchId = Guid.NewGuid() }).Confirms(batch));
+        Assert.False((accepted with { Digest = new string('a', 64) }).Confirms(batch));
+        Assert.False((accepted with { RawBatchId = null }).Confirms(batch));
+        Assert.False((accepted with { ConfirmedPosition = "old" }).Confirms(batch));
+    }
+
+    [Fact]
+    public void ApiPageUsesCloudComputedPositionOnlyForTheOriginalPage()
+    {
+        var batch = EdgeBatch.Create("run-A", "page-first", "from", null, [1]) with { ReceiverConfirmsNext = true };
+        var accepted = new EdgeReceipt(batch.BatchId, batch.Digest, "accepted", Guid.NewGuid(), "cursor-2", SourcePosition: "from");
+        Assert.True(accepted.Confirms(batch));
+        Assert.False((accepted with { SourcePosition = "different" }).Confirms(batch));
+    }
+
+    [Fact]
+    public void AuthorizedRefetchUsesNewIdentityAtTheSamePosition()
+    {
+        var task = new EdgeTask("run-A", EdgeProtocol.ApiPull, 1, 2, 3, 4, "S", "test", "schema", "config", "page-2", "READY");
+        var rejected = EdgeBatch.Create(task.Stream, task.PageKey(), task.Position, null, [1]);
+        var retry = task with { RecoveryAttempt = 1 };
+        var replacement = EdgeBatch.Create(retry.Stream, retry.PageKey(), retry.Position, null, [2]);
+        Assert.Equal(rejected.Position, replacement.Position);
+        Assert.NotEqual(rejected.BatchId, replacement.BatchId);
+        Assert.Equal(retry.PageKey(), (retry with { State = "BLOCKED" }).PageKey());
+    }
+
+    [Fact]
+    public void TemporalPagesUseTieBreakAndWindowCompletionAdvancesOnlyTheBoundary()
+    {
+        var lower = DateTimeOffset.Parse("2026-11-24T00:00:00Z");
+        var upper = lower.AddSeconds(30);
+        var start = EdgeTimeWatermark.Encode(lower);
+        var a = "page:" + new RelationalTimePosition(lower, 10).Encode();
+        var b = "page:" + new RelationalTimePosition(lower, 11).Encode();
+
+        Assert.True(EdgeTimeWatermark.AdvancesPage(start, a, incremental: true));
+        Assert.True(EdgeTimeWatermark.AdvancesPage(a, b, incremental: true));
+        Assert.False(EdgeTimeWatermark.AdvancesPage(b, a, incremental: true));
+        Assert.False(EdgeTimeWatermark.AdvancesPage(b, EdgeTimeWatermark.Encode(upper), incremental: true));
+        Assert.Equal(upper, EdgeTimeWatermark.Decode(EdgeTimeWatermark.Encode(upper)));
+        Assert.Throws<EdgeContractException>(() => EdgeTimeWatermark.Decode(b));
+    }
+
+    [Fact]
+    public void RequestKeepsBytesAndBatchIdentityForRetries()
+    {
+        var original = new byte[] { 4, 7, 2 };
+        var batch = EdgeBatch.Create("run-A", "page-2", "initial", "next", original);
+        original[0] = 9;
+        Assert.Equal(new byte[] { 4, 7, 2 }, batch.Body);
+        Assert.Equal(batch.BatchId, EdgeBatch.Create("run-A", "page-2", "initial", "next", batch.Body).BatchId);
+        Assert.NotEqual(batch.BatchId, EdgeBatch.Create("run-B", "page-2", "initial", "next", batch.Body).BatchId);
+    }
+}

+ 1 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpApiPullService.cs

@@ -160,6 +160,7 @@ public sealed partial class MdpApiPullService(ISqlSugarClient host, MdpApiPullCl
 
     private async Task RequireWriterAsync(ISqlSugarClient db, Profile profile, Published bound)
     {
+        await MdpEdgeRoute.RequireDirectAsync(db, configuration, profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId);
         var migration = await MdpPurchaseMigrationStore.LockNewAsync(db, profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId);
         MdpPurchaseMigrationStore.RequireAdmission(migration, MdpPurchaseMigrationStore.Unified);
         if (migration is null)

+ 76 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpEdgeDeviceController.cs

@@ -0,0 +1,76 @@
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+[ApiController, AllowAnonymous, NonUnify]
+[Route("api/v1/edge")]
+public sealed class MdpEdgeDeviceController(MdpEdgeDeviceService devices) : ControllerBase
+{
+    [HttpPost("register"), RequestSizeLimit(12288)]
+    public Task<IActionResult> Register(EdgeRegistration input, CancellationToken token) =>
+        Execute(async () => Ok(await devices.RegisterAsync(input, token)));
+
+    [HttpPost("certificate/renew"), RequestSizeLimit(12288)]
+    public Task<IActionResult> Renew(EdgeRenewal input, CancellationToken token) =>
+        Execute(async () => Ok(await devices.RenewAsync(await DeviceCertificate(token), input, token)));
+
+    [HttpPost("certificate/confirm"), RequestSizeLimit(1024)]
+    public Task<IActionResult> Confirm(CancellationToken token) => Execute(async () =>
+    {
+        await devices.ConfirmCertificateAsync(await DeviceCertificate(token), token);
+        return NoContent();
+    });
+
+    [HttpPost("heartbeat"), RequestSizeLimit(4096)]
+    public Task<IActionResult> Poll(EdgeReport report, CancellationToken token) =>
+        Execute(async () => Ok(await devices.PollAsync(await DeviceCertificate(token), report)));
+
+    [HttpGet("batches/{id:guid}")]
+    public Task<IActionResult> Status(Guid id, CancellationToken token) => Execute(async () =>
+    {
+        var receipt = await devices.FindReceiptAsync(await DeviceCertificate(token), id);
+        return receipt is null ? NotFound() : Ok(receipt);
+    });
+
+    [HttpPost("batches"), RequestSizeLimit(1500000)]
+    public Task<IActionResult> Upload(EdgeBatch batch, CancellationToken token) =>
+        Execute(async () => Ok(await devices.ReceiveAsync(await DeviceCertificate(token), batch, token)));
+
+    private async Task<System.Security.Cryptography.X509Certificates.X509Certificate2> DeviceCertificate(CancellationToken token) =>
+        await HttpContext.Connection.GetClientCertificateAsync(token) ?? throw new EdgeContractException("EDGE_DEVICE_FORBIDDEN");
+
+    private async Task<IActionResult> Execute(Func<Task<IActionResult>> action)
+    {
+        if (!Request.IsHttps) return StatusCode(403, new { code = "EDGE_TLS_REQUIRED" });
+        Response.Headers.CacheControl = "no-store";
+        try { return await action(); }
+        catch (Exception error) when (error is EdgeContractException or MdpIngestHttpException or IngestContractException
+            or System.Data.Common.DbException or SqlSugarException)
+        {
+            return EdgeFailure(error);
+        }
+    }
+
+    internal static ObjectResult EdgeFailure(Exception error)
+    {
+        var code = error switch
+        {
+            EdgeContractException edge => edge.Code,
+            MdpIngestHttpException http => http.Code,
+            IngestContractException ingest => ingest.Code.ToString(),
+            _ => "EDGE_STORE_UNAVAILABLE"
+        };
+        var status = error is MdpIngestHttpException custom ? custom.StatusCode : code switch
+        {
+            "EDGE_DISABLED" or "EDGE_DEVICE_NOT_FOUND" => 404,
+            "EDGE_DEVICE_FORBIDDEN" or "EDGE_ACTIVATION_INVALID" or "EDGE_WRITER_FORBIDDEN" => 403,
+            "EDGE_REPORT_INVALID" or "EDGE_CERT_REQUEST_INVALID" or "EDGE_BATCH_INVALID" or "EDGE_TASK_INVALID" => 400,
+            "EDGE_STORE_UNAVAILABLE" or "EDGE_CA_UNAVAILABLE" => 503,
+            _ => 409
+        };
+        return new ObjectResult(new { code }) { StatusCode = status };
+    }
+}

+ 198 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpEdgeDeviceService.ApiRecovery.cs

@@ -0,0 +1,198 @@
+using System.Text;
+using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+public sealed record MdpEdgePagePreviewInput(Guid BatchId, string ResponsePath);
+public sealed record MdpEdgePageApproval(Guid BatchId, string Digest, string Mode, string Reason, string? ResponsePath, string? PreviewToken);
+public sealed record MdpEdgePagePreview(Guid BatchId, string Digest, int Count, int Valid, int Isolated, bool HasNext, string Token);
+
+public sealed partial class MdpEdgeDeviceService
+{
+    public async Task<MdpEdgePagePreview> PreviewPageAsync(long tenant, long factory, long dataset, Guid id, MdpEdgePagePreviewInput input)
+    {
+        RequireEnabled();
+        using var db = MdpIngestDatabase.Open(host);
+        var (device, task, page, batch) = await RecoveryContextAsync(db, tenant, factory, dataset, id, input.BatchId, false);
+        var shadow = await ReparseAsync(db, device, task, page, batch, input.ResponsePath, lockDataset: false);
+        return shadow.Preview;
+    }
+
+    public async Task RecoverPageAsync(long tenant, long factory, long dataset, Guid id, long actor,
+        MdpEdgePageApproval input, CancellationToken token)
+    {
+        RequireEnabled();
+        var reason = input.Reason?.Trim();
+        Require(actor > 0 && reason is { Length: > 0 and <= 240 } && !reason.Any(char.IsControl)
+            && (input.Mode == "reparse" || input.Mode == "refetch" && input.ResponsePath is null && input.PreviewToken is null),
+            "EDGE_RECOVERY_INVALID");
+
+        using var db = MdpIngestDatabase.Open(host);
+        await Tx(db, async () =>
+        {
+            var (device, task, page, batch) = await RecoveryContextAsync(db, tenant, factory, dataset, id, input.BatchId, true);
+            Require(input.Digest == batch.Digest, "EDGE_CAPTURE_MISMATCH");
+
+            if (input.Mode == "refetch")
+            {
+                var scope = await BoundAsync(db, tenant, factory, dataset, device.SourceId, true);
+                Require(scope.SourceSchemaVersion == task.SchemaVersion, "EDGE_CONFIGURATION_STALE");
+                await RequireWriterAsync(db, device, scope.SourceCode);
+                await db.Ado.ExecuteCommandAsync("""
+                    UPDATE mdp_edge_device SET task_phase='READY' WHERE device_id=@DeviceId
+                    """, new { device.DeviceId });
+            }
+            else
+            {
+                var shadow = await ReparseAsync(db, device, task, page, batch, input.ResponsePath, lockDataset: true);
+                Require(shadow.Preview.Token == input.PreviewToken, "EDGE_RECOVERY_PREVIEW_REQUIRED");
+                var count = shadow.Result.Prepared.Events.Count;
+                if (count > 0)
+                {
+                    var originalTime = new DateTimeOffset(DateTime.SpecifyKind(page.ReceivedAt, DateTimeKind.Utc));
+                    var prepared = shadow.Result.Prepared with
+                    {
+                        Batch = shadow.Result.Prepared.Batch with { BatchId = batch.BatchId, ReceivedAt = originalTime },
+                        Events = shadow.Result.Prepared.Events.Select(row => row with { BatchId = batch.BatchId }).ToArray()
+                    };
+                    var key = Encoding.ASCII.GetBytes("\0edge-" + page.BatchId);
+                    await MdpIngestReceiveService.PersistAcceptedBatchAsync(db, prepared, key, factory, token, useCapturedRaw: true);
+                }
+                var next = shadow.Result.ConfirmedPosition;
+                var receipt = new EdgeReceipt(batch.BatchId, batch.Digest,
+                    count == 0 ? EdgeProtocol.Empty : EdgeProtocol.Accepted, batch.BatchId, next, SourcePosition: batch.Position);
+                await db.Ado.ExecuteCommandAsync("""
+                    UPDATE mdp_edge_receipt SET receipt_json=@receipt WHERE batch_id=@BatchId AND device_id=@DeviceId
+                    """, new { page.BatchId, device.DeviceId, receipt = JsonSerializer.Serialize(receipt, EdgeProtocol.Json) });
+                await db.Ado.ExecuteCommandAsync("""
+                    UPDATE mdp_edge_device SET position_text=@next,task_phase=@phase,
+                        page_count=page_count+1,row_count=row_count+@count WHERE device_id=@DeviceId
+                    """, new { device.DeviceId, next, phase = next is null ? "COMPLETE" : "READY", count });
+            }
+            await db.Ado.ExecuteCommandAsync("""
+                UPDATE mdp_edge_api_rejected_page SET settlement=@Mode,response_path=@ResponsePath,settled_at=UTC_TIMESTAMP(6)
+                WHERE batch_id=@BatchId AND device_id=@DeviceId AND settled_at IS NULL
+                """, new { page.BatchId, device.DeviceId, input.Mode, input.ResponsePath });
+            await AuditAsync(db, dataset, actor, "EDGE_PAGE_RECOVERY", $"{page.BatchId} {input.Mode} {reason}");
+            token.ThrowIfCancellationRequested();
+            return true;
+        });
+    }
+
+    private static async Task<(Device Device, EdgeTask Task, RejectedPage Page, EdgeBatch Batch)> RecoveryContextAsync(
+        ISqlSugarClient db, long tenant, long factory, long dataset, Guid id, Guid raw, bool locked)
+    {
+        var deviceId = id.ToString("D");
+        var batchId = raw.ToString("D");
+        var device = await db.Ado.SqlQuerySingleAsync<Device>(Devices + """
+             WHERE device_id=@deviceId AND tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset
+              AND state='ACTIVE' AND task_phase='BLOCKED'
+            """ + (locked ? " FOR UPDATE" : ""), new { deviceId, tenant, factory, dataset })
+            ?? throw new EdgeContractException("EDGE_PAGE_NOT_BLOCKED");
+
+        var task = ReadTask(device);
+        Require(task.Mode == EdgeProtocol.ApiPull && task.Position is not null, "EDGE_PAGE_NOT_BLOCKED");
+        var page = await db.Ado.SqlQuerySingleAsync<RejectedPage>("""
+            SELECT p.batch_id AS BatchId,p.effective_url AS EffectiveUrl,p.next_link AS NextLink,p.link_diagnostic AS LinkDiagnostic,
+                r.idem_key AS IdemKey,r.digest AS Digest,r.receipt_json AS ReceiptJson,b.payload AS Body,b.received_at AS ReceivedAt
+            FROM mdp_edge_api_rejected_page p JOIN mdp_edge_receipt r ON r.batch_id=p.batch_id AND r.device_id=p.device_id
+            JOIN mdp_ingest_raw_batch b ON b.batch_id=r.batch_id AND b.tenant_id=r.tenant_id AND b.factory_id=r.factory_id
+                AND b.dataset_id=r.dataset_id AND b.source_id=r.source_id AND b.payload_sha256=r.digest
+            WHERE p.batch_id=@batchId AND p.device_id=@deviceId AND p.generation=@Generation AND p.position_hash=@positionHash
+                AND p.settled_at IS NULL AND r.tenant_id=@tenant AND r.factory_id=@factory AND r.dataset_id=@dataset
+                AND r.source_id=@SourceId AND b.accepted_record_count=0
+            """, new { batchId, deviceId, tenant, factory, dataset, device.Generation, device.SourceId, positionHash = HashText(task.Position!) })
+            ?? throw new EdgeContractException("EDGE_CAPTURE_MISSING");
+
+        var batch = EdgeBatch.Create(task.Stream, Encoding.ASCII.GetString(page.IdemKey), task.Position, null, page.Body) with
+        {
+            EffectiveUrl = page.EffectiveUrl, NextLink = page.NextLink, Diagnostic = page.LinkDiagnostic, ReceiverConfirmsNext = true
+        };
+        var receipt = JsonSerializer.Deserialize<EdgeReceipt>(page.ReceiptJson, EdgeProtocol.Json);
+        Require(batch.BatchId == raw && batch.Digest == page.Digest && receipt?.Rejects(batch) == true, "EDGE_CAPTURE_MISMATCH");
+        return (device, task, page, batch);
+    }
+
+    private static async Task<(MdpEdgePagePreview Preview, PageResult Result)> ReparseAsync(ISqlSugarClient db, Device device, EdgeTask task,
+        RejectedPage page, EdgeBatch batch, string? path, bool lockDataset)
+    {
+        Require(path is { Length: <= 112 }, "EDGE_RECOVERY_INVALID");
+        var plan = ParseApiPlan(task.ApiPlan) with { ResponsePath = path! };
+        plan.Validate();
+        var bound = await BoundAsync(db, task.TenantId, task.FactoryId, task.DatasetId, task.SourceId, lockDataset);
+        Require(bound.SourceSchemaVersion == task.SchemaVersion, "EDGE_CONFIGURATION_STALE");
+        if (lockDataset) await RequireWriterAsync(db, device, bound.SourceCode);
+        var (schemas, contract) = await new MdpIngestContractBinder(new MdpIngestDatasetRegistry(db)).ReadContractAsync(bound);
+        Require(contract.ConfigVersion == task.ConfigVersion, "EDGE_CONFIGURATION_STALE");
+        var scope = new IngestDatasetIdentity(task.TenantId, task.FactoryId, task.SourceId, task.DatasetId, bound.SourceCode, bound.DatasetKey);
+        var window = new IngestSourceWindow(null, null, IngestSourceWindow.PurchaseApiTime);
+        var result = await ParseApiPageAsync(db, device, task, batch, new IngestBatchPreparer(schemas), scope, window, plan);
+        Require(MdpBatchFactory.RowsMatch(result.Prepared), "EDGE_BATCH_SCOPE_INVALID");
+        var count = result.Prepared.Events.Count;
+        var processed = count == 0 ? null : PurchaseBatchProcessor.Process(result.Prepared, "");
+        var valid = processed?.Package.Items.Count ?? 0;
+        var isolated = processed?.Quarantines.Select(row => row.RawEventId).Distinct().Count() ?? 0;
+        var evidence = JsonSerializer.SerializeToUtf8Bytes(new { task.Stream, task.Position, task.ConfigVersion,
+            page.BatchId, batch.Digest, Path = path, count, valid, isolated, result.ConfirmedPosition }, EdgeProtocol.Json);
+        return (new MdpEdgePagePreview(batch.BatchId, batch.Digest, count, valid, isolated, result.ConfirmedPosition is not null,
+            EdgeProtocol.Digest(evidence)), result);
+    }
+
+    private static async Task<PageResult> ParseApiPageAsync(ISqlSugarClient db, Device device, EdgeTask task, EdgeBatch batch,
+        IngestBatchPreparer preparer, IngestDatasetIdentity scope, IngestSourceWindow window, MdpApiPullPlan plan)
+    {
+        Require(device.PageCount < plan.MaxPages, "PULL_PAGE_LIMIT");
+        if (batch.Diagnostic is not null) throw new EdgeContractException("PULL_LINK_INVALID");
+        var prepared = preparer.PrepareApiPage(scope, task.SchemaVersion, batch.Body, MdpIngestProtocol.Limits,
+            MdpApiPullPlan.Path(plan.ResponsePath), window);
+        using var json = JsonDocument.Parse(batch.Body);
+        Require(Uri.TryCreate(batch.EffectiveUrl, UriKind.Absolute, out var effective) && MdpApiPullEgress.SameOrigin(plan.Endpoint, effective),
+            "PULL_LINK_FORBIDDEN");
+        var next = plan.Next(JsonSerializer.Deserialize<MdpApiPullPosition>(batch.Position!, EdgeProtocol.Json)!,
+            json.RootElement, prepared.Events.Count, effective!, batch.NextLink, device.RowCount);
+        var position = next is null ? null : JsonSerializer.Serialize(next, EdgeProtocol.Json);
+        if (position is not null)
+            Require(await db.Ado.GetIntAsync("""
+                SELECT COUNT(*) FROM mdp_edge_receipt WHERE device_id=@DeviceId AND generation=@Generation AND position_hash=@hash
+                """, new { device.DeviceId, device.Generation, hash = HashText(position) }) == 0, "PULL_POSITION_STALLED");
+        return new PageResult(prepared, position);
+    }
+
+    private static Task<int> RecordRejectedPageAsync(ISqlSugarClient db, Device device, EdgeBatch batch) =>
+        db.Ado.ExecuteCommandAsync("""
+            INSERT INTO mdp_edge_api_rejected_page(batch_id,device_id,generation,position_hash,effective_url,next_link,link_diagnostic)
+            VALUES (@id,@DeviceId,@Generation,@position,@EffectiveUrl,@NextLink,@Diagnostic)
+            """, new { id = batch.BatchId.ToString("D"), device.DeviceId, device.Generation, position = HashText(batch.Position!),
+                batch.EffectiveUrl, batch.NextLink, batch.Diagnostic });
+
+    private static async Task<EdgeTask> RecoveryTaskAsync(ISqlSugarClient db, Device device, bool includeSettled)
+    {
+        var task = ReadTask(device);
+        var attempt = task.Mode == EdgeProtocol.ApiPull && task.Position is not null ? await db.Ado.GetIntAsync("""
+            SELECT COUNT(*) FROM mdp_edge_api_rejected_page WHERE device_id=@DeviceId AND generation=@Generation
+              AND position_hash=@hash AND settlement='refetch'
+            """, new { device.DeviceId, device.Generation, hash = HashText(task.Position) }) : 0;
+        var settled = includeSettled ? await db.Ado.SqlQueryAsync<string>("""
+            SELECT CONCAT(batch_id,'') FROM mdp_edge_api_rejected_page WHERE device_id=@DeviceId AND settled_at IS NOT NULL
+            ORDER BY settled_at DESC LIMIT 100
+            """, new { device.DeviceId }) : [];
+        return task with { RecoveryAttempt = attempt, SettledPages = settled.Select(Guid.Parse).ToArray() };
+    }
+
+    private sealed record PageResult(PreparedIngestBatch Prepared, string? ConfirmedPosition);
+
+    private sealed class RejectedPage
+    {
+        public string BatchId { get; set; } = "";
+        public string? EffectiveUrl { get; set; }
+        public string? NextLink { get; set; }
+        public string? LinkDiagnostic { get; set; }
+        public byte[] IdemKey { get; set; } = [];
+        public string Digest { get; set; } = "";
+        public string ReceiptJson { get; set; } = "";
+        public byte[] Body { get; set; } = [];
+        public DateTime ReceivedAt { get; set; }
+    }
+}

+ 311 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpEdgeDeviceService.Receive.cs

@@ -0,0 +1,311 @@
+using System.Globalization;
+using System.Security.Cryptography.X509Certificates;
+using System.Text;
+using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+public sealed record MdpEdgeTaskInput(string Mode, string? ApiPlan, EdgeRelationalSettings? Relational, string? ResumePosition = null);
+
+public sealed partial class MdpEdgeDeviceService
+{
+    public async Task ConfigureAsync(long tenant, long factory, long dataset, Guid id, long actor, MdpEdgeTaskInput input)
+    {
+        RequireEnabled();
+        using var db = MdpIngestDatabase.Open(host);
+        await Tx(db, async () =>
+        {
+            var deviceId = id.ToString("D");
+            var device = await db.Ado.SqlQuerySingleAsync<Device>(Devices + """
+                 WHERE device_id=@deviceId AND tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset
+                  AND state IN ('APPROVED','ACTIVE') FOR UPDATE
+                """, new { deviceId, tenant, factory, dataset }) ?? throw new EdgeContractException("EDGE_DEVICE_NOT_FOUND");
+            var binding = await BoundAsync(db, tenant, factory, dataset, device.SourceId, true);
+            Require(device.Phase is null or "COMPLETE", "EDGE_TASK_ACTIVE");
+            await MdpEdgeRoute.RequireNoDirectRunAsync(db, tenant, factory, dataset, device.SourceId, allowHistory: input.Mode == EdgeProtocol.ApiPush);
+            Require(await db.Ado.GetIntAsync("""
+                SELECT COUNT(*) FROM mdp_edge_device WHERE tenant_id=@tenant AND factory_id=@factory
+                  AND dataset_id=@dataset AND source_id=@SourceId AND device_id<>@deviceId AND config_json IS NOT NULL
+                """, new { tenant, factory, dataset, device.SourceId, deviceId }) == 0, "EDGE_HANDOFF_REQUIRED");
+
+            string? position = input.ResumePosition;
+            if (input.Mode == EdgeProtocol.ApiPull)
+            {
+                var api = ParseApiPlan(input.ApiPlan);
+                Require(input.Relational is null && position is null, "EDGE_TASK_INVALID");
+                position = JsonSerializer.Serialize(api.Begin(DateTimeOffset.UtcNow, null), EdgeProtocol.Json);
+            }
+            else if (input.Mode == EdgeProtocol.Database)
+            {
+                Require(input.ApiPlan is null && input.Relational is { PageSize: >= 1 and <= 100, Columns.Length: > 0 and <= 100 },
+                    "EDGE_TASK_INVALID");
+                var relational = input.Relational!;
+                if (relational.Time is { } time)
+                {
+                    Require(relational.Driver == Admin.NET.Plugin.AiDOP.DataPlatform.Relational.NativeRelationalDriver.PostgreSqlId
+                        && relational.SourceGeneration is > 0 && time.IsValid(), "EDGE_TIME_SOURCE_UNSUPPORTED");
+                    if (relational.Incremental)
+                    {
+                        var previous = device.ConfigJson is null ? null : ReadTask(device).Relational;
+                        Require(previous is not null && SameTimeSource(previous, relational) && device.Position is not null
+                            && (position is null || position == device.Position), "EDGE_TIME_BASELINE_REQUIRED");
+                        position = device.Position;
+                        _ = EdgeTimeWatermark.Decode(position);
+                    }
+                    else
+                    {
+                        Require(position is null, "EDGE_TIME_BASELINE_REQUIRED");
+                    }
+                }
+                else
+                {
+                    if (relational.Incremental && position is null) position = device.Position;
+                    Require(position is null || long.TryParse(position, NumberStyles.Integer, CultureInfo.InvariantCulture, out _), "EDGE_TASK_INVALID");
+                }
+                if (relational.SourceGeneration is > 0)
+                    Require(relational.ChangeVersionColumn is { Length: > 0 } column && relational.Columns.Contains(column)
+                        && (relational.DeleteColumn is null || relational.Columns.Contains(relational.DeleteColumn)), "EDGE_TASK_INVALID");
+                else
+                    Require(relational.SourceGeneration is null && relational.ChangeVersionColumn is null && relational.DeleteColumn is null,
+                        "EDGE_TASK_INVALID");
+            }
+            else
+            {
+                Require(input.Mode == EdgeProtocol.ApiPush && input.ApiPlan is null && input.Relational is null && position is null, "EDGE_TASK_INVALID");
+            }
+            var (_, contract) = await new MdpIngestContractBinder(new MdpIngestDatasetRegistry(db)).ReadContractAsync(binding);
+            var generation = checked(device.Generation + 1);
+            var task = new EdgeTask(deviceId + "-" + generation.ToString(CultureInfo.InvariantCulture), input.Mode,
+                tenant, factory, device.SourceId, dataset, binding.SourceCode, binding.DatasetKey, binding.SourceSchemaVersion,
+                contract.ConfigVersion, position, "READY", input.ApiPlan, input.Relational);
+            await db.Ado.ExecuteCommandAsync("""
+                UPDATE mdp_edge_device SET config_generation=@generation,config_json=@json,position_text=@position,
+                    task_phase='READY',page_count=0,row_count=0 WHERE device_id=@deviceId
+                """, new { deviceId, generation, position, json = JsonSerializer.Serialize(task, EdgeProtocol.Json) });
+            await AuditAsync(db, dataset, actor, "EDGE_TASK_APPROVED", task.Stream);
+            return true;
+        });
+    }
+
+    public async Task<EdgeReceipt?> FindReceiptAsync(X509Certificate2 certificate, Guid id)
+    {
+        RequireEnabled();
+        using var db = MdpIngestDatabase.Open(host);
+        var device = await AuthenticateAsync(db, certificate, false);
+        return await FindAsync(db, device, id);
+    }
+
+    public async Task<EdgeReceipt> ReceiveAsync(X509Certificate2 certificate, EdgeBatch batch, CancellationToken token)
+    {
+        RequireEnabled();
+        batch.Validate();
+        using var db = MdpIngestDatabase.Open(host);
+        return await Tx(db, async () =>
+        {
+            var device = await AuthenticateAsync(db, certificate, true);
+            var previous = await FindAsync(db, device, batch.BatchId);
+            if (previous is not null)
+            {
+                Require(previous.Confirms(batch) || previous.Rejects(batch), "EDGE_BATCH_CONFLICT");
+                return previous;
+            }
+
+            var task = await RecoveryTaskAsync(db, device, includeSettled: false);
+            Require(task.Stream == batch.Stream && task.State == "READY" && device.SeenAt is { } seen
+                && DateTime.UtcNow - seen < TimeSpan.FromSeconds(60), "EDGE_TASK_STALE");
+            Require(task.Mode == EdgeProtocol.ApiPush ? batch.Position is null && batch.NextPosition is null
+                : batch.Position == device.Position && !batch.Ndjson, "EDGE_POSITION_STALE");
+            Require(batch.ReceiverConfirmsNext == (task.Mode == EdgeProtocol.ApiPull)
+                && (!batch.ReceiverConfirmsNext || batch.NextPosition is null && batch.Key == task.PageKey()), "EDGE_POSITION_INVALID");
+            var binding = await BoundAsync(db, device.TenantId, device.FactoryId, device.DatasetId, device.SourceId, true);
+            Require(binding.SourceSchemaVersion == task.SchemaVersion, "EDGE_CONFIGURATION_STALE");
+            await RequireWriterAsync(db, device, binding.SourceCode);
+            var (schemas, contract) = await new MdpIngestContractBinder(new MdpIngestDatasetRegistry(db)).ReadContractAsync(binding);
+            Require(contract.ConfigVersion == task.ConfigVersion, "EDGE_CONFIGURATION_STALE");
+            if (task.Mode == EdgeProtocol.ApiPush && await ExistingPushAsync(db, device, batch, task.SchemaVersion) is { } replay)
+                return replay;
+            var preparer = new IngestBatchPreparer(schemas);
+            var scope = new IngestDatasetIdentity(task.TenantId, task.FactoryId, task.SourceId, task.DatasetId, binding.SourceCode, binding.DatasetKey);
+            var limits = MdpIngestProtocol.Limits;
+            var window = task.Mode switch
+            {
+                EdgeProtocol.ApiPull => new IngestSourceWindow(null, null, IngestSourceWindow.PurchaseApiTime),
+                EdgeProtocol.Database when task.Relational?.SourceGeneration is > 0 =>
+                    new IngestSourceWindow(null, null, IngestSourceWindow.VerifiedRelationalSnapshot) { SourceGeneration = task.Relational.SourceGeneration },
+                _ => null
+            };
+            var archiveKey = Encoding.ASCII.GetBytes("\0edge-" + batch.BatchId.ToString("D"));
+            var captured = preparer.CaptureApiPage(scope, task.SchemaVersion, batch.Body, limits, window) with { BatchId = batch.BatchId };
+            await MdpIngestReceiveService.PersistRawAsync(db, captured, [], batch.Body, archiveKey, captured.ReceivedAt, token);
+            var confirmation = batch.NextPosition;
+            var isCompleted = false;
+            PreparedIngestBatch? prepared = null;
+            string? code = null;
+            try
+            {
+                if (task.Mode == EdgeProtocol.ApiPull)
+                {
+                    var result = await ParseApiPageAsync(db, device, task, batch, preparer, scope, window!, ParseApiPlan(task.ApiPlan));
+                    prepared = result.Prepared;
+                    confirmation = result.ConfirmedPosition;
+                    isCompleted = confirmation is null;
+                }
+                else if (task.Mode == EdgeProtocol.Database && batch.Body.Length == 0)
+                {
+                    if (task.Relational?.Time is not null)
+                    {
+                        var boundary = EdgeTimeWatermark.Decode(batch.NextPosition);
+                        Require(boundary <= DateTimeOffset.UtcNow.AddMinutes(5) &&
+                            (task.StartPosition is null || boundary >= EdgeTimeWatermark.Decode(task.StartPosition)), "EDGE_TIME_BOUNDARY_INVALID");
+                    }
+                    else
+                    {
+                        Require(batch.NextPosition == batch.Position, "EDGE_POSITION_INVALID");
+                    }
+                    isCompleted = true;
+                }
+                else
+                {
+                    prepared = preparer.Prepare(scope, task.SchemaVersion, batch.Body, limits,
+                        window, format: batch.Ndjson ? IngestPayloadFormat.Ndjson : IngestPayloadFormat.Json);
+                    if (task.Mode == EdgeProtocol.Database)
+                    {
+                        if (task.Relational?.Time is not null)
+                            Require(EdgeTimeWatermark.AdvancesPage(batch.Position, batch.NextPosition, task.Relational.Incremental),
+                                "EDGE_POSITION_INVALID");
+                        else
+                        {
+                            var from = batch.Position is null ? long.MinValue : ParsePosition(batch.Position);
+                            var to = ParsePosition(batch.NextPosition);
+                            Require(to > from, "EDGE_POSITION_INVALID");
+                            if (task.Relational?.UpperPosition is { } upper)
+                                Require(to <= upper, "EDGE_POSITION_INVALID");
+                        }
+                    }
+                }
+                Require(prepared is null || MdpBatchFactory.RowsMatch(prepared), "EDGE_BATCH_SCOPE_INVALID");
+            }
+            catch (Exception error) when (error is EdgeContractException or MdpApiPullException or IngestContractException or JsonException)
+            {
+                code = error switch
+                {
+                    EdgeContractException edge => edge.Code,
+                    MdpApiPullException pull => pull.Code,
+                    IngestContractException contractError => "EDGE_" + contractError.Code.ToString().ToUpperInvariant(),
+                    _ => "EDGE_INVALID_JSON"
+                };
+            }
+
+            var count = code is null ? prepared?.Events.Count ?? 0 : 0;
+            var key = task.Mode == EdgeProtocol.ApiPush ? Encoding.ASCII.GetBytes(batch.Key) : archiveKey;
+            if (count > 0)
+            {
+                var accepted = prepared! with { Batch = prepared!.Batch with { BatchId = batch.BatchId, ReceivedAt = captured.ReceivedAt },
+                    Events = prepared.Events.Select(item => item with { BatchId = batch.BatchId }).ToArray() };
+                await MdpIngestReceiveService.PersistAcceptedBatchAsync(db, accepted, key, device.FactoryId, token, useCapturedRaw: true);
+            }
+
+            var status = code is not null ? EdgeProtocol.Rejected : count == 0 ? EdgeProtocol.Empty : EdgeProtocol.Accepted;
+            var receipt = new EdgeReceipt(batch.BatchId, batch.Digest, status, batch.BatchId, code is null ? confirmation : batch.Position, code, batch.Position);
+            await db.Ado.ExecuteCommandAsync("""
+                INSERT INTO mdp_edge_receipt(batch_id,device_id,tenant_id,factory_id,dataset_id,source_id,generation,
+                    idem_key,digest,position_hash,receipt_json)
+                VALUES (@batchId,@DeviceId,@TenantId,@FactoryId,@DatasetId,@SourceId,@Generation,@key,@Digest,@positionHash,@json)
+                """, new { batchId = batch.BatchId.ToString("D"), device.DeviceId, device.TenantId, device.FactoryId,
+                    device.DatasetId, device.SourceId, device.Generation, key = Encoding.ASCII.GetBytes(batch.Key), batch.Digest,
+                    positionHash = batch.Position is null ? null : HashText(batch.Position), json = JsonSerializer.Serialize(receipt, EdgeProtocol.Json) });
+            if (task.Mode == EdgeProtocol.ApiPull && code is not null)
+                await RecordRejectedPageAsync(db, device, batch);
+            if (task.Mode != EdgeProtocol.ApiPush)
+                await db.Ado.ExecuteCommandAsync("""
+                    UPDATE mdp_edge_device SET position_text=@ConfirmedPosition,task_phase=@phase,
+                        page_count=page_count+@pages,row_count=row_count+@count WHERE device_id=@DeviceId
+                    """, new { device.DeviceId, receipt.ConfirmedPosition, phase = code is not null ? "BLOCKED" : isCompleted ? "COMPLETE" : "READY",
+                        pages = code is null ? 1 : 0, count });
+            token.ThrowIfCancellationRequested();
+            return receipt;
+        });
+    }
+
+    private static async Task<EdgeReceipt?> ExistingPushAsync(ISqlSugarClient db, Device device, EdgeBatch batch, string schema)
+    {
+        var stored = await db.Ado.SqlQuerySingleAsync<PushReceipt>("""
+            SELECT b.batch_id AS BatchId,b.payload_sha256 AS Digest,b.source_schema_version AS SchemaVersion,
+                (SELECT e.source_position FROM mdp_ingest_raw_event e WHERE e.batch_id=b.batch_id AND e.record_ordinal=0) AS FirstPosition
+            FROM mdp_ingest_raw_batch b WHERE b.tenant_id=@TenantId AND b.factory_id=@FactoryId AND b.source_id=@SourceId
+                AND b.dataset_id=@DatasetId AND b.idempotency_key=@key AND b.accepted_record_count>0
+            """, new { device.TenantId, device.FactoryId, device.SourceId, device.DatasetId, key = Encoding.ASCII.GetBytes(batch.Key) });
+        if (stored is null) return null;
+        Require(stored.Digest == batch.Digest && stored.SchemaVersion == schema &&
+            batch.Ndjson == (stored.FirstPosition?.StartsWith("/lines/", StringComparison.Ordinal) == true), "EDGE_BATCH_CONFLICT");
+        return new EdgeReceipt(batch.BatchId, batch.Digest, EdgeProtocol.Accepted, Guid.Parse(stored.BatchId), null);
+    }
+
+    private sealed class PushReceipt
+    {
+        public string BatchId { get; set; } = "";
+        public string Digest { get; set; } = "";
+        public string SchemaVersion { get; set; } = "";
+        public string? FirstPosition { get; set; }
+    }
+
+    private static long ParsePosition(string? value) =>
+        long.TryParse(value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var parsed)
+            ? parsed : throw new EdgeContractException("EDGE_POSITION_INVALID");
+
+    private static async Task<EdgeReceipt?> FindAsync(ISqlSugarClient db, Device device, Guid id)
+    {
+        var json = await db.Ado.SqlQuerySingleAsync<string>("""
+            SELECT receipt_json FROM mdp_edge_receipt WHERE batch_id=@batchId AND device_id=@DeviceId
+              AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId
+            """, new { batchId = id.ToString("D"), device.DeviceId, device.TenantId, device.FactoryId, device.DatasetId, device.SourceId });
+        return string.IsNullOrEmpty(json) ? null : JsonSerializer.Deserialize<EdgeReceipt>(json, EdgeProtocol.Json);
+    }
+
+    private static EdgeTask ReadTask(Device device)
+    {
+        var configured = device.ConfigJson is null ? null : JsonSerializer.Deserialize<EdgeTask>(device.ConfigJson, EdgeProtocol.Json);
+        if (configured is null) throw new EdgeContractException("EDGE_TASK_ABSENT");
+        return configured with { StartPosition = configured.Position, Position = device.Position,
+            State = device.Phase!, PageCount = device.PageCount, RowCount = device.RowCount };
+    }
+
+    private static bool SameTimeSource(EdgeRelationalSettings previous, EdgeRelationalSettings next) =>
+        previous.Time == next.Time && previous.Driver == next.Driver && previous.Database == next.Database &&
+        previous.Schema == next.Schema && previous.Table == next.Table && previous.PositionColumn == next.PositionColumn &&
+        previous.SourceGeneration == next.SourceGeneration && previous.ChangeVersionColumn == next.ChangeVersionColumn &&
+        previous.DeleteColumn == next.DeleteColumn && previous.Columns.SequenceEqual(next.Columns, StringComparer.Ordinal);
+
+    private static MdpApiPullPlan ParseApiPlan(string? json)
+    {
+        Require(json is { Length: > 0 and <= 65536 }, "EDGE_TASK_INVALID");
+        var plan = JsonSerializer.Deserialize<MdpApiPullPlan>(json!, EdgeProtocol.Json) ?? throw new EdgeContractException("EDGE_TASK_INVALID");
+        plan.Validate();
+        return plan;
+    }
+
+    private static async Task<MdpIngestActiveBinding> BoundAsync(ISqlSugarClient db, long tenant, long factory, long dataset, long source, bool locked)
+    {
+        var key = await db.Ado.GetStringAsync("""
+            SELECT dataset_key FROM mdp_ingest_dataset WHERE id=@dataset AND tenant_id=@tenant AND factory_id=@factory AND enabled=1
+            """ + (locked ? " FOR UPDATE" : ""), new { tenant, factory, dataset });
+        Require(!string.IsNullOrEmpty(key), "EDGE_SCOPE_UNAVAILABLE");
+        return await new MdpIngestDatasetRegistry(db).ResolveActiveBindingAsync(tenant, factory, source, key)
+            ?? throw new EdgeContractException("EDGE_SCOPE_UNAVAILABLE");
+    }
+
+    private static async Task RequireWriterAsync(ISqlSugarClient db, Device device, string sourceCode)
+    {
+        var migration = await MdpPurchaseMigrationStore.LockNewAsync(db, device.TenantId, device.FactoryId, device.DatasetId, device.SourceId);
+        MdpPurchaseMigrationStore.RequireAdmission(migration, MdpPurchaseMigrationStore.Unified);
+        if (migration is not null)
+        {
+            Require(migration.NewSourceCode == sourceCode, "EDGE_WRITER_FORBIDDEN");
+            return;
+        }
+        var authority = await new MdpTenantStdSourceResolver(db).GetSourceForShareAsync(device.TenantId, "PURCHASE");
+        Require(string.Equals(authority?.SourceSystem, sourceCode, StringComparison.OrdinalIgnoreCase), "EDGE_WRITER_FORBIDDEN");
+    }
+}

+ 265 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpEdgeDeviceService.cs

@@ -0,0 +1,265 @@
+using System.Security.Cryptography;
+using System.Security.Cryptography.X509Certificates;
+using System.Text;
+using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
+using Microsoft.Extensions.Configuration;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+public sealed partial class MdpEdgeDeviceService(ISqlSugarClient host, IConfiguration settings)
+{
+    private const string Devices = """
+        SELECT device_id AS DeviceId,tenant_id AS TenantId,factory_id AS FactoryId,dataset_id AS DatasetId,
+            source_id AS SourceId,device_name AS DeviceName,state AS State,activation_expires AS ActivationExpires,
+            certificate_expires AS CertificateExpires,config_json AS ConfigJson,config_generation AS Generation,
+            position_text AS Position,task_phase AS Phase,seen_at AS SeenAt,report_json AS ReportJson,
+            page_count AS PageCount,row_count AS RowCount,
+            (SELECT p.batch_id FROM mdp_edge_api_rejected_page p WHERE p.device_id=mdp_edge_device.device_id
+                AND p.generation=mdp_edge_device.config_generation AND p.settled_at IS NULL AND mdp_edge_device.task_phase='BLOCKED'
+                ORDER BY p.batch_id LIMIT 1) AS RejectedRawId,
+            (SELECT r.digest FROM mdp_edge_api_rejected_page p JOIN mdp_edge_receipt r ON r.batch_id=p.batch_id
+                WHERE p.device_id=mdp_edge_device.device_id AND p.generation=mdp_edge_device.config_generation
+                  AND p.settled_at IS NULL AND mdp_edge_device.task_phase='BLOCKED' ORDER BY p.batch_id LIMIT 1) AS RejectedDigest
+        FROM mdp_edge_device
+        """;
+
+    public async Task<object> ListAsync(long tenant, long factory, long dataset)
+    {
+        RequireEnabled();
+        using var db = MdpIngestDatabase.Open(host);
+        var devices = await db.Ado.SqlQueryAsync<Device>(Devices + """
+             WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset ORDER BY created_at DESC LIMIT 100
+            """, new { tenant, factory, dataset });
+        return devices.Select(x => new
+        {
+            x.DeviceId, x.DeviceName, SourceId = x.SourceId.ToString(System.Globalization.CultureInfo.InvariantCulture),
+            x.State, x.CertificateExpires, x.Generation, x.Phase, x.SeenAt, x.PageCount, x.RowCount,
+            x.RejectedRawId, x.RejectedDigest,
+            Online = x.State == "ACTIVE" && x.SeenAt >= DateTime.UtcNow.AddSeconds(-60),
+            Watermark = long.TryParse(x.Position, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var value)
+                ? value.ToString(System.Globalization.CultureInfo.InvariantCulture) : null,
+            Report = x.ReportJson is null ? null : JsonSerializer.Deserialize<EdgeReport>(x.ReportJson, EdgeProtocol.Json)
+        }).ToArray();
+    }
+
+    public async Task<object> ApproveAsync(long tenant, long factory, long dataset, long source, string name, long actor)
+    {
+        RequireEnabled();
+        Require(name is { Length: > 0 and <= 120 } && !name.Any(char.IsControl), "EDGE_DEVICE_NAME_INVALID");
+        var deviceId = Guid.NewGuid().ToString("D");
+        var activation = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
+        using var db = MdpIngestDatabase.Open(host);
+        return await Tx(db, async () =>
+        {
+            _ = await BoundAsync(db, tenant, factory, dataset, source, true);
+            Require(await db.Ado.GetIntAsync("""
+                SELECT COUNT(*) FROM mdp_edge_device
+                WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset AND source_id=@source AND active_slot=1
+                """, new { tenant, factory, dataset, source }) == 0, "EDGE_BINDING_ACTIVE");
+            await db.Ado.ExecuteCommandAsync("""
+                INSERT INTO mdp_edge_device(device_id,tenant_id,factory_id,dataset_id,source_id,device_name,state,
+                    active_slot,activation_hash,activation_expires)
+                VALUES (@deviceId,@tenant,@factory,@dataset,@source,@name,'APPROVED',1,@hash,TIMESTAMPADD(MINUTE,15,UTC_TIMESTAMP(6)))
+                """, new { deviceId, tenant, factory, dataset, source, name, hash = HashText(activation) });
+            await AuditAsync(db, dataset, actor, "EDGE_APPROVED", deviceId);
+            return new { deviceId, activation, validForSeconds = 900 };
+        });
+    }
+
+    public async Task<EdgeCertificate> RegisterAsync(EdgeRegistration input, CancellationToken token)
+    {
+        RequireEnabled();
+        Require(input.Activation is { Length: 64 } && input.Activation.All(Uri.IsHexDigit), "EDGE_ACTIVATION_INVALID");
+        var hash = HashText(input.Activation);
+        using var db = MdpIngestDatabase.Open(host);
+        return await Tx(db, async () =>
+        {
+            var device = await db.Ado.SqlQuerySingleAsync<Device>(Devices + """
+                 WHERE activation_hash=@hash AND activation_expires>UTC_TIMESTAMP(6) AND state='APPROVED' FOR UPDATE
+                """, new { hash }) ?? throw new EdgeContractException("EDGE_ACTIVATION_INVALID");
+            using var certificate = Sign(device.DeviceId, input.RequestPem);
+            await UpdateCertificateAsync(db, device, certificate);
+            await AuditAsync(db, device.DatasetId, 0, "EDGE_REGISTERED", device.DeviceId);
+            token.ThrowIfCancellationRequested();
+            return new EdgeCertificate(Guid.Parse(device.DeviceId), certificate.ExportCertificatePem());
+        });
+    }
+
+    public async Task<EdgeCertificate> RenewAsync(X509Certificate2 issued, EdgeRenewal input, CancellationToken token)
+    {
+        RequireEnabled();
+        using var db = MdpIngestDatabase.Open(host);
+        return await Tx(db, async () =>
+        {
+            var device = await AuthenticateAsync(db, issued, true);
+            using var certificate = Sign(device.DeviceId, input.RequestPem);
+            // The currently verified certificate remains current until explicit confirmation using the pending certificate.
+            await db.Ado.ExecuteCommandAsync("""
+                UPDATE mdp_edge_device SET next_certificate_hash=@hash,next_certificate_expires=@expiry WHERE device_id=@DeviceId
+                """, new { device.DeviceId, hash = EdgeProtocol.Digest(certificate.RawData), expiry = certificate.NotAfter.ToUniversalTime() });
+            await AuditAsync(db, device.DatasetId, 0, "EDGE_RENEWAL_ISSUED", device.DeviceId);
+            token.ThrowIfCancellationRequested();
+            return new EdgeCertificate(Guid.Parse(device.DeviceId), certificate.ExportCertificatePem());
+        });
+    }
+
+    public async Task ConfirmCertificateAsync(X509Certificate2 certificate, CancellationToken token)
+    {
+        RequireEnabled();
+        using var db = MdpIngestDatabase.Open(host);
+        var hash = CertificateHash(certificate);
+        await Tx(db, async () =>
+        {
+            var device = await db.Ado.SqlQuerySingleAsync<Device>(Devices + """
+                 WHERE next_certificate_hash=@hash AND next_certificate_expires>UTC_TIMESTAMP(6) AND state='ACTIVE' FOR UPDATE
+                """, new { hash });
+            if (device is null)
+            {
+                _ = await AuthenticateAsync(db, certificate, true);
+                return true;
+            }
+            await db.Ado.ExecuteCommandAsync("""
+                UPDATE mdp_edge_device SET certificate_hash=next_certificate_hash,certificate_expires=next_certificate_expires,
+                    next_certificate_hash=NULL,next_certificate_expires=NULL WHERE device_id=@DeviceId
+                """, new { device.DeviceId });
+            await AuditAsync(db, device.DatasetId, 0, "EDGE_CERT_ROTATED", device.DeviceId);
+            token.ThrowIfCancellationRequested();
+            return true;
+        });
+    }
+
+    public async Task RevokeAsync(long tenant, long factory, long dataset, Guid id, long actor)
+    {
+        RequireEnabled();
+        var deviceId = id.ToString("D");
+        using var db = MdpIngestDatabase.Open(host);
+        await Tx(db, async () =>
+        {
+            var changed = await db.Ado.ExecuteCommandAsync("""
+                UPDATE mdp_edge_device SET state='REVOKED',active_slot=NULL,activation_hash=NULL,
+                    certificate_hash=NULL,next_certificate_hash=NULL,task_phase='PAUSED'
+                WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset AND device_id=@deviceId
+                   AND state<>'REVOKED'
+                """, new { tenant, factory, dataset, deviceId });
+            Require(changed == 1, "EDGE_DEVICE_NOT_FOUND");
+            await AuditAsync(db, dataset, actor, "EDGE_REVOKED", deviceId);
+            return true;
+        });
+    }
+
+    public async Task<EdgeTask?> PollAsync(X509Certificate2 certificate, EdgeReport report)
+    {
+        RequireEnabled();
+        Require(report.Version is { Length: > 0 and <= 32 } && report.Pending >= 0 && report.BufferedBytes >= 0
+            && report.FreeBytes >= 0 && (report.LastError?.Length ?? 0) <= 100, "EDGE_REPORT_INVALID");
+        using var db = MdpIngestDatabase.Open(host);
+        return await Tx(db, async () =>
+        {
+            var device = await AuthenticateAsync(db, certificate, true);
+            await db.Ado.ExecuteCommandAsync("""
+                UPDATE mdp_edge_device SET seen_at=UTC_TIMESTAMP(6),report_json=@json WHERE device_id=@DeviceId
+                """, new { device.DeviceId, json = JsonSerializer.Serialize(report, EdgeProtocol.Json) });
+            if (device.ConfigJson is null) return null;
+            var task = await RecoveryTaskAsync(db, device, includeSettled: true);
+            return task with { LeaseUntil = DateTimeOffset.UtcNow.AddSeconds(60) };
+        });
+    }
+
+    private static string CertificateHash(X509Certificate2 certificate)
+    {
+        var now = DateTime.UtcNow;
+        Require(now >= certificate.NotBefore.ToUniversalTime() && now < certificate.NotAfter.ToUniversalTime(), "EDGE_DEVICE_FORBIDDEN");
+        return EdgeProtocol.Digest(certificate.RawData);
+    }
+
+    private static async Task<Device> AuthenticateAsync(ISqlSugarClient db, X509Certificate2 certificate, bool locked) =>
+        await db.Ado.SqlQuerySingleAsync<Device>(Devices + """
+             WHERE certificate_hash=@hash AND certificate_expires>UTC_TIMESTAMP(6) AND state='ACTIVE'
+            """ + (locked ? " FOR UPDATE" : ""), new { hash = CertificateHash(certificate) })
+        ?? throw new EdgeContractException("EDGE_DEVICE_FORBIDDEN");
+
+    private X509Certificate2 Sign(string deviceId, string pem)
+    {
+        Require(pem is { Length: > 0 and <= 8192 }, "EDGE_CERT_REQUEST_INVALID");
+        var path = settings["MdpEdge:CaPfxPath"];
+        Require(!string.IsNullOrWhiteSpace(path), "EDGE_CA_UNAVAILABLE");
+        try
+        {
+            using var ca = new X509Certificate2(path!, settings["MdpEdge:CaPfxPassword"], X509KeyStorageFlags.EphemeralKeySet);
+            var loaded = CertificateRequest.LoadSigningRequestPem(pem, HashAlgorithmName.SHA256);
+            using var publicKey = loaded.PublicKey.GetECDsaPublicKey();
+            Require(publicKey?.KeySize == 256, "EDGE_CERT_REQUEST_INVALID");
+            var request = new CertificateRequest(new X500DistinguishedName("CN=" + deviceId), loaded.PublicKey, HashAlgorithmName.SHA256);
+            request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
+            request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true));
+            request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new("1.3.6.1.5.5.7.3.2") }, true));
+            var end = DateTimeOffset.UtcNow.AddDays(Math.Clamp(settings.GetValue("MdpEdge:CertificateDays", 30), 1, 90));
+            if (end.UtcDateTime > ca.NotAfter.ToUniversalTime()) end = ca.NotAfter.ToUniversalTime();
+            using var rsa = ca.GetRSAPrivateKey();
+            using var ec = ca.GetECDsaPrivateKey();
+            var signature = rsa is not null
+                ? X509SignatureGenerator.CreateForRSA(rsa, RSASignaturePadding.Pkcs1)
+                : ec is not null ? X509SignatureGenerator.CreateForECDsa(ec) : throw new EdgeContractException("EDGE_CA_UNAVAILABLE");
+            var start = DateTimeOffset.UtcNow.AddSeconds(-10);
+            if (start.UtcDateTime < ca.NotBefore.ToUniversalTime()) start = ca.NotBefore.ToUniversalTime();
+            return request.Create(ca.SubjectName, signature, start, end, RandomNumberGenerator.GetBytes(20));
+        }
+        catch (Exception error) when (error is ArgumentException or CryptographicException)
+        {
+            throw new EdgeContractException("EDGE_CERT_REQUEST_INVALID");
+        }
+    }
+
+    private static Task<int> UpdateCertificateAsync(ISqlSugarClient db, Device device, X509Certificate2 certificate) =>
+        db.Ado.ExecuteCommandAsync("""
+            UPDATE mdp_edge_device SET state='ACTIVE',activation_hash=NULL,activation_expires=NULL,
+                certificate_hash=@hash,certificate_expires=@expiry WHERE device_id=@DeviceId
+            """, new { device.DeviceId, hash = EdgeProtocol.Digest(certificate.RawData), expiry = certificate.NotAfter.ToUniversalTime() });
+
+    private static Task<int> AuditAsync(ISqlSugarClient db, long dataset, long actor, string action, string detail) =>
+        db.Ado.ExecuteCommandAsync("""
+            INSERT INTO mdp_ingest_release_log(dataset_id,action,actor,detail,created_at)
+            VALUES (@dataset,@action,@actor,@detail,UTC_TIMESTAMP(6))
+            """, new { dataset, action, actor, detail });
+
+    private void RequireEnabled() => Require(settings.GetValue<bool>("MdpEdge:Enabled"), "EDGE_DISABLED");
+    private static string HashText(string value) => EdgeProtocol.Digest(Encoding.UTF8.GetBytes(value));
+
+    private static void Require(bool condition, string code)
+    {
+        if (!condition) throw new EdgeContractException(code);
+    }
+
+    private static async Task<T> Tx<T>(ISqlSugarClient db, Func<Task<T>> run)
+    {
+        var result = await db.Ado.UseTranAsync(run);
+        if (result.IsSuccess) return result.Data;
+        if (result.ErrorException is { } failure) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(failure);
+        throw new EdgeContractException("EDGE_STORE_UNAVAILABLE");
+    }
+
+    private sealed class Device
+    {
+        public string DeviceId { get; set; } = "";
+        public long TenantId { get; set; }
+        public long FactoryId { get; set; }
+        public long DatasetId { get; set; }
+        public long SourceId { get; set; }
+        public string DeviceName { get; set; } = "";
+        public string State { get; set; } = "";
+        public DateTime? ActivationExpires { get; set; }
+        public DateTime? CertificateExpires { get; set; }
+        public string? ConfigJson { get; set; }
+        public long Generation { get; set; }
+        public string? Position { get; set; }
+        public string? Phase { get; set; }
+        public DateTime? SeenAt { get; set; }
+        public string? ReportJson { get; set; }
+        public int PageCount { get; set; }
+        public long RowCount { get; set; }
+        public string? RejectedRawId { get; set; }
+        public string? RejectedDigest { get; set; }
+    }
+}

+ 34 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpEdgeRoute.cs

@@ -0,0 +1,34 @@
+using Microsoft.Extensions.Configuration;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+internal static class MdpEdgeRoute
+{
+    // The existing command already holds the dataset row. This is the same lock used by edge approval.
+    internal static async Task RequireDirectAsync(ISqlSugarClient db, IConfiguration? configuration, long tenant,
+        long factory, long dataset, long source)
+    {
+        if (configuration?.GetValue<bool>("MdpEdge:Enabled") != true) return;
+        if (await db.Ado.GetIntAsync("""
+            SELECT COUNT(*) FROM mdp_edge_device WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset
+                AND source_id=@source AND config_json IS NOT NULL
+            """, new { tenant, factory, dataset, source }) != 0)
+            throw new MdpIngestHttpException(409, "EDGE_ROUTE_OWNED");
+    }
+
+    internal static async Task RequireNoDirectRunAsync(ISqlSugarClient db, long tenant, long factory, long dataset, long source, bool allowHistory)
+    {
+        foreach (var table in new[] { "mdp_connector_api_pull_run", "mdp_connector_relational_sync_run" })
+        {
+            if (await db.Ado.GetIntAsync("""
+                SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=@table
+                """, new { table }) == 0)
+                continue;
+            if (await db.Ado.GetIntAsync($"""
+                SELECT COUNT(*) FROM {table} WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset
+                    AND source_id=@source AND (active_slot=1 OR @allowHistory=0)
+                """, new { tenant, factory, dataset, source, allowHistory }) != 0)
+                throw new MdpIngestHttpException(409, "EDGE_DIRECT_HANDOFF_REQUIRED");
+        }
+    }
+}

+ 68 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestDatasetController.Edge.cs

@@ -0,0 +1,68 @@
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+public sealed partial class MdpIngestDatasetController
+{
+    [HttpGet("{id:long}/edge")]
+    public Task<IActionResult> ListEdgeDevices(long id, long? factoryId) =>
+        EdgeAction(id, factoryId, TrialPermission, async (service, scope) =>
+            Ok(new { devices = await service.ListAsync(scope.TenantId, scope.FactoryId, id), canApprove = await Can(PublishPermission) }));
+
+    [HttpPost("{id:long}/edge"), RequestSizeLimit(4096)]
+    public Task<IActionResult> ApproveEdgeDevice(long id, long? factoryId, MdpEdgeApproveInput input) =>
+        EdgeAction(id, factoryId, PublishPermission, async (service, scope) =>
+            Ok(await service.ApproveAsync(scope.TenantId, scope.FactoryId, id, input.SourceId, input.Name, user.UserId)));
+
+    [HttpPut("{id:long}/edge/{device:guid}/task"), RequestSizeLimit(98304)]
+    public Task<IActionResult> ConfigureEdgeDevice(long id, Guid device, long? factoryId, MdpEdgeTaskInput input) =>
+        EdgeAction(id, factoryId, PublishPermission, async (service, scope) =>
+        {
+            await service.ConfigureAsync(scope.TenantId, scope.FactoryId, id, device, user.UserId, input);
+            return NoContent();
+        });
+
+    [HttpPost("{id:long}/edge/{device:guid}/recovery/preview"), RequestSizeLimit(4096)]
+    public Task<IActionResult> PreviewEdgePage(long id, Guid device, long? factoryId, MdpEdgePagePreviewInput input) =>
+        EdgeAction(id, factoryId, TrialPermission, async (service, scope) =>
+            Ok(await service.PreviewPageAsync(scope.TenantId, scope.FactoryId, id, device, input)));
+
+    [HttpPost("{id:long}/edge/{device:guid}/recovery"), RequestSizeLimit(4096)]
+    public Task<IActionResult> RecoverEdgePage(long id, Guid device, long? factoryId, MdpEdgePageApproval input, CancellationToken token) =>
+        EdgeAction(id, factoryId, PublishPermission, async (service, scope) =>
+        {
+            await service.RecoverPageAsync(scope.TenantId, scope.FactoryId, id, device, user.UserId, input, token);
+            return NoContent();
+        });
+
+    [HttpPost("{id:long}/edge/{device:guid}/revoke")]
+    public Task<IActionResult> RevokeEdgeDevice(long id, Guid device, long? factoryId) =>
+        EdgeAction(id, factoryId, PublishPermission, async (service, scope) =>
+        {
+            await service.RevokeAsync(scope.TenantId, scope.FactoryId, id, device, user.UserId);
+            return NoContent();
+        });
+
+    private Task<IActionResult> EdgeAction(long id, long? factoryId, string permission, Func<MdpEdgeDeviceService, DatasetScope, Task<IActionResult>> action)
+        => WithScope(factoryId, async scope =>
+        {
+            if (!await Can(permission)) return Forbid();
+            if (!await Datasets(scope).AnyAsync(row => row.Id == id)) return NotFound();
+            Response.Headers.CacheControl = "no-store";
+            try { return await action(HttpContext.RequestServices.GetRequiredService<MdpEdgeDeviceService>(), scope); }
+            catch (Exception error) when (error is EdgeContractException or MdpIngestHttpException or IngestContractException
+                or System.Data.Common.DbException or SqlSugarException)
+            {
+                return MdpEdgeDeviceController.EdgeFailure(error);
+            }
+            catch (Exception error) when (error is System.Text.Json.JsonException or ArgumentException or MdpApiPullException)
+            {
+                return BadRequest(new { code = "EDGE_TASK_INVALID" });
+            }
+        });
+}
+
+public sealed record MdpEdgeApproveInput(long SourceId, string Name);

+ 5 - 2
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestReceiveService.cs

@@ -1,6 +1,7 @@
 using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
 using Microsoft.AspNetCore.Http;
 using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Configuration;
 using System.Data.Common;
 using System.Runtime.ExceptionServices;
 using System.Security.Cryptography;
@@ -9,7 +10,7 @@ using System.Text.Json;
 
 namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
 
-public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpIngestReceiveService> logger) : ITransient
+public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpIngestReceiveService> logger, IConfiguration? configuration = null) : ITransient
 {
     private const string Accepted = "accepted";
     private static readonly TimeSpan ReplayDuration = TimeSpan.FromDays(7);
@@ -42,7 +43,7 @@ public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpInges
         }
     }
 
-    private static async Task<MdpIngestReceipt> ReceiveInTransactionAsync(
+    private async Task<MdpIngestReceipt> ReceiveInTransactionAsync(
         ISqlSugarClient db, MdpIngestSubmission submission, CancellationToken cancellationToken)
     {
         var datasetKey = submission.DatasetKey.Trim().ToLowerInvariant();
@@ -113,6 +114,8 @@ public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpInges
             return Replay(previous, submission.Payload);
         }
 
+        await MdpEdgeRoute.RequireDirectAsync(db, configuration, scope.TenantId, scope.FactoryId, datasetId.Value, scope.SourceId);
+
         var migration = await MdpPurchaseMigrationStore.LockNewAsync(
             db, scope.TenantId, scope.FactoryId, datasetId.Value, scope.SourceId);
         MdpPurchaseMigrationStore.RequireAdmission(migration, MdpPurchaseMigrationStore.Unified);

+ 1 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestServiceCollectionExtensions.cs

@@ -11,6 +11,7 @@ public static class MdpIngestServiceCollectionExtensions
         services.AddSingleton<MdpApiPullEgress>();
         services.AddSingleton<MdpApiPullClient>();
         services.AddScoped<MdpApiPullService>();
+        services.AddScoped<MdpEdgeDeviceService>();
         services.AddTransient<MdpIngestBatchStatusService>();
         services.AddScoped<MdpIngestAdmissionStore>();
         services.AddSingleton<MdpIngestExternalIdentities>();

+ 2 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpRelationalSyncService.cs

@@ -40,6 +40,8 @@ public sealed partial class MdpRelationalSyncService(
                 "SELECT state FROM mdp_ingest_lifecycle WHERE dataset_id=@DatasetId", new { profile.DatasetId }) != "ACTIVE")
             throw new MdpIngestHttpException(409, "DATASET_UNAVAILABLE");
 
+        await MdpEdgeRoute.RequireDirectAsync(store, settings, profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId);
+
         var (_, binding, configuration) = await CreateRelationalTrial(store, profile, dataset, source);
         var signature = Signature(profile, binding);
         var runId = (prior ?? Guid.NewGuid()).ToString("D");