压缩实际手部轨迹反馈并按已验证参考推进修订

This commit is contained in:
tfarcraw 2026-11-19 09:27:17 +08:00
parent d09665c6dc
commit ae0641c4bb
6 changed files with 62 additions and 14 deletions

View File

@ -90,7 +90,9 @@ public sealed class SopDraftVideoVerifier : ISopDraftVideoVerifier
var summary = test.IsCompleted && contradictory
? $"标准视频运行已完成 {draft.Steps.Count} 步,但完成/前序参考对照未通过,草稿未通过验收"
: test.Finish("标准视频草稿回测结束");
if (infrastructureFailure) summary = "标准视频参考复核服务未返回有效判定,尚未完成验收;不应据此放宽工艺要求";
if (infrastructureFailure) summary = references.Any(c => c.InfrastructureFailure)
? "标准视频参考复核服务未返回有效判定,尚未完成验收;不应据此放宽工艺要求"
: "标准视频回放期间视觉服务未返回有效判定,尚未完成验收;不应据此放宽工艺要求";
return new(test.IsCompleted && !contradictory && !infrastructureFailure, summary, test.StepResults,
images.Values.OrderBy(i => i.StepId).ToArray(), fingerprint, infrastructureFailure, diagnostics.Build(), references, test.IsCompleted);
}

View File

@ -130,10 +130,13 @@ public sealed class SopTriggerDiagnosticsCollector
s.WindowStart, s.WindowEnd, s.WindowFrames, s.WindowRawMatches, s.WindowMaxConsecutiveMatches, s.WindowFirstReadySeconds,
s.ArmedSeconds, s.CapturedSeconds, s.SubmittedAtSeconds, s.ConfirmedAtSeconds, s.EvaluatedFrames, s.ActualRawMatches, s.ActualMaxStableFrames }),
failure_details = relevant.Select(s => new { s.StepId,
image_events = Evenly(s.ImageEvents, 24),
image_events = Evenly(s.ImageEvents, 12),
probes = Evenly(s.Probes, 12),
hands_in_expected_window = Evenly(diagnostics.Trajectory.Where(f => f.Seconds >= s.WindowStart - .5 && f.Seconds <= s.WindowEnd + .5).ToArray(), 16) }),
semantics = "手部轨迹来自实际检测,像素坐标与原视频一致。hand:any 在进入/移动规则中优先右手;离开规则检查所有匹配手的接触框。Armed/Captured/Submitted/Confirmed 汇总为首次事件时间;逐次取图、发送和判定见 image_events。ImageSeconds 是原始取图时间,AtVideoSeconds 是事件发生时视频进度,不能混淆缓存取图与延迟送检。Window统计是从视频开头独立观察配置规则的反事实结果,不是实际触发;门控未启用时已有匹配,须先检查前序触发是否过晚;已缓存但判定失败时先检查是否取图过早。轨迹/探针/事件为有界抽样,计数为完整处理帧汇总;漏检不证明手或操作不存在。不得用视频时间点代替触发、降低AI阈值或改变工艺;结合轨迹、实际画面校正触发区、指定手和防抖,并保持送检范围覆盖判据。"
hands_in_expected_window = Evenly(diagnostics.Trajectory.Where(f => f.Seconds >= s.WindowStart - .5 && f.Seconds <= s.WindowEnd + .5).ToArray(), 12)
.Select(f => new { f.FrameId, Seconds = Math.Round(f.Seconds, 3), Hands = f.Hands.Select(h => new
{ h.Hand, Center = new[] { Math.Round(h.X, 1), Math.Round(h.Y, 1) },
Contact = new[] { Math.Round(h.ContactX1, 1), Math.Round(h.ContactY1, 1), Math.Round(h.ContactX2, 1), Math.Round(h.ContactY2, 1) } }) }) }),
semantics = "手部轨迹来自实际检测,Center=[x,y],Contact=[x1,y1,x2,y2],原图像素取0.1精度、时间取毫秒,仅压缩模型反馈,原始日志不变。hand:any 进入/移动优先右手;离开检查所有匹配手接触框。Armed/Captured/Submitted/Confirmed 是首次事件时间;逐次事件见 image_events。ImageSeconds 是取图时间,AtVideoSeconds 是事件时视频进度,不能混淆缓存取图与延迟送检。Window统计是独立观察规则的反事实结果,不是实际触发。轨迹/探针/事件有界抽样,计数为完整帧汇总;漏检不证明操作不存在。不得用视频时间点代替触发、降低AI阈值或改变工艺;结合轨迹和原图校正触发与送检范围。"
};
}
private static T[] Evenly<T>(IReadOnlyList<T> values, int maximum) => values.Count <= maximum ? values.ToArray()

View File

@ -38,6 +38,8 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
var verificationAttempts = 0;
var referenceAttempts = 0;
var referenceBlockingId = 1;
var runtimeBlockingId = 1;
var confirmedReferences = new Dictionary<int, string>();
var maxTurns = request.CheckReference is null ? 12 : 20;
var pendingCompression = "";
List<object>? verificationBase = null;
@ -274,6 +276,8 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
draft.Verification = report;
referenceBlockingId = report.Steps.FirstOrDefault(s => !s.Completed)?.Id
?? (report.ReferenceChecks ?? []).FirstOrDefault(c => c.Contradicts)?.StepId ?? 1;
runtimeBlockingId = referenceBlockingId;
confirmedReferences.Clear();
request.Trace?.Invoke(new("verification_result", turn + 1, SopAgentJson.Serialize(new
{
report.Passed, report.RuntimePassed, report.Summary, report.Steps, report.InfrastructureFailure, report.TriggerDiagnostics, report.ReferenceChecks,
@ -412,24 +416,41 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
}
else if (name == "check_draft_reference" && request.CheckReference is { } check)
{
if (++referenceAttempts > 6) throw new ArgumentException("参考检查预算已用尽,请提交草稿或明确阻塞原因");
if (referenceAttempts >= 6) throw new ArgumentException("参考检查预算已用尽,请提交草稿或明确阻塞原因");
var candidate = args.RootElement.GetProperty("draft").Deserialize<SopVideoDraft>(new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
?? throw new ArgumentException("缺少完整候选草稿");
SopVideoDraftClient.ValidateCapabilities(candidate, request);
var idToCheck = args.RootElement.GetProperty("step_id").GetInt32();
if (idToCheck < 1 || idToCheck > candidate.Steps.Count) throw new ArgumentException("步骤编号无效");
referenceBlockingId = runtimeBlockingId;
while (referenceBlockingId < candidate.Steps.Count
&& confirmedReferences.TryGetValue(referenceBlockingId, out var confirmed)
&& confirmed == ReferenceSignature(candidate, referenceBlockingId)) referenceBlockingId++;
if (idToCheck < referenceBlockingId || idToCheck > referenceBlockingId + 1)
throw new ArgumentException($"先解决当前阻塞步骤 {referenceBlockingId} 及紧邻下一步,再回放验证;不要无目标检查后续步骤");
SopVideoDraftClient.Validate(candidate, request.Video with { Frames = observed }, request.Regions, request.RegionDefinitions);
var names = verificationStepNames ?? request.CurrentDraft?.Steps.Select(s => s.Name).ToArray();
if (names is not null && !names.SequenceEqual(candidate.Steps.Select(s => s.Name)))
throw new ArgumentException("参考检查须保留当前工艺的步骤名称、数量和顺序");
referenceAttempts++;
var checks = await check(candidate, request.Video with { Frames = observed }, idToCheck, token).ConfigureAwait(false);
foreach (var group in checks.GroupBy(c => c.StepId))
if (group.Key > 0 && group.Key <= candidate.Steps.Count
&& group.Any(c => c.Kind == "completion" && c.Accepted == true)
&& group.Any(c => c.Kind == "previous_state" && c.Accepted == false)
&& group.All(c => !c.InfrastructureFailure && (c.Kind == "completion" ? c.Accepted == true : c.Accepted == false)))
confirmedReferences[group.Key] = ReferenceSignature(candidate, group.Key);
while (referenceBlockingId < candidate.Steps.Count
&& confirmedReferences.TryGetValue(referenceBlockingId, out var confirmedNext)
&& confirmedNext == ReferenceSignature(candidate, referenceBlockingId)) referenceBlockingId++;
result = SopAgentJson.Serialize(new { reference_checks = checks, remaining_reference_checks = Math.Max(0, 6 - referenceAttempts),
next_reference_step = referenceBlockingId == candidate.Steps.Count
&& confirmedReferences.TryGetValue(referenceBlockingId, out var finalReference)
&& finalReference == ReferenceSignature(candidate, referenceBlockingId) ? (int?)null : referenceBlockingId,
reference_ready = checks.Any(c => c.Kind == "completion") && checks.Any(c => c.Kind == "previous_state")
&& checks.Where(c => c.Kind == "completion").All(c => c.Accepted == true)
&& checks.Where(c => c.Kind == "previous_state").All(c => c.Accepted == false),
note = "completion 应通过;previous_state 是前序/起始对照,若也通过说明未区分相邻步骤。参考图/片段检查不等于手部触发或流程通过;基础设施故障不能作为放宽工艺依据。" });
note = "completion 应通过,previous_state 应不通过。两者正确且判据/范围/证据未变时继续 next_reference_step,不重复检查;为null则提交完整草稿做真实回放。修改已确认步骤须重新检查。参考不替代回放,服务故障不能作为放宽工艺依据。" });
foreach (var reference in checks.Where(c => c.Jpeg.Length > 0))
{
imageParts.Add(new { type = "text", text = $"候选参考裁剪:步骤{reference.StepId},类型{reference.Kind},源 evidence_frame={reference.EvidenceFrame},{reference.Seconds:F3}s,范围{reference.Scope},判定{reference.Accepted};previous_state应不满足本步,不能用作完成证据。不是实际触发。" });
@ -462,6 +483,16 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
(connection.ContextLength - connection.MaxTokens - estimatedInput - 1024) / 1700));
}
private static string ReferenceSignature(SopVideoDraft draft, int id)
{
var step = draft.Steps[id - 1];
var keys = new[] { step.Region, step.ToRegion, step.ImageRegion };
return SopAgentJson.Serialize(new { step.Description, step.EvidenceFrame, step.ImageMode, step.ImageRegion,
step.Region, step.ToRegion, step.Inspection, PreviousEvidence = id > 1 ? draft.Steps[id - 2].EvidenceFrame : -1,
Regions = draft.RegionAdjustments.Where(r => keys.Contains(r.Key, StringComparer.OrdinalIgnoreCase))
.OrderBy(r => r.Key, StringComparer.OrdinalIgnoreCase).Select(r => new { r.Key, r.X1, r.Y1, r.X2, r.Y2 }) });
}
private async Task<string> SummarizeHistoryAsync(object[] history, SopVideoAnalysisRequest request,
SopAgentConnection connection, CancellationToken token)
{

View File

@ -10,7 +10,7 @@ internal static class ReferenceToolChecks
var sample = video with { Frames = SopVideoSampler.ReadFrames(video, [.5, 1.5, 2.5, 3.5], 0, default) };
var current = new SopVideoDraft { Steps = Enumerable.Range(0, 4).Select(i => new SopDraftStep
{ Name = "保留工艺" + i, Description = "主体与可见完成关系", Region = "work", StartSeconds = i, EndSeconds = i + 1, EvidenceFrame = i }).ToList() };
foreach (var mode in new[] { "valid", "renamed", "bad_evidence", "extra_argument", "out_of_focus" })
foreach (var mode in new[] { "valid", "renamed", "bad_evidence", "extra_argument", "out_of_focus", "advance", "advance_changed" })
{
var candidate = JsonSerializer.Deserialize<SopVideoDraft>(JsonSerializer.Serialize(current))!;
if (mode == "renamed") candidate.Steps[0].Name = "另一工艺";
@ -24,17 +24,21 @@ internal static class ReferenceToolChecks
CheckReference: (_, observed, id, _) =>
{
checks++;
Check(observed.Frames.Count == 4 && id == 1, "候选参考检查只能使用实际读取的证据");
Check(observed.Frames.Count == 4 && (id == 1 || mode == "advance" && id == 3), "候选参考检查只能使用实际读取的证据");
if (mode is "advance" or "advance_changed")
return Task.FromResult<IReadOnlyList<SopDraftReferenceCheck>>(new[] { id, id + 1 }.SelectMany(step => new SopDraftReferenceCheck[]
{ new(step, step - 1, step - .5, "work", true, .95, "完成参考", sample.Frames[step - 1].Jpeg),
new(step, -1, 0, "work", false, .1, "前序反例", [], "previous_state") }).ToArray());
return Task.FromResult<IReadOnlyList<SopDraftReferenceCheck>>([new(1, 0, .5, "work", true, .95, "静态参考通过", sample.Frames[0].Jpeg),
new(1, -1, 0, "work", false, .1, "起始对照不满足", [], "previous_state")]);
}), new("https://probe.invalid/v1", "model", "", ContextLength: 131702), default);
Check(result.Draft?.Verification?.Passed == true && replays == 2 && checks == (mode == "valid" ? 1 : 0),
Check(result.Draft?.Verification?.Passed == true && replays == 2 && checks == (mode == "advance" ? 2 : mode is "valid" or "advance_changed" ? 1 : 0),
"参考检查不替代真实回放,改工艺、伪造证据或额外路径参数不得进入本地检查");
using var final = JsonDocument.Parse(handler.Bodies[1]);
var resultText = final.RootElement.GetProperty("messages").EnumerateArray().Single(m => m.GetProperty("role").GetString() == "tool").GetProperty("content").GetString()!;
Check(resultText.Contains(mode == "valid" ? "reference_checks" : "error"), "真实参考结果或具体参数错误须反馈给模型");
var resultText = final.RootElement.GetProperty("messages").EnumerateArray().First(m => m.GetProperty("role").GetString() == "tool").GetProperty("content").GetString()!;
Check(resultText.Contains(mode is "valid" or "advance" or "advance_changed" ? "reference_checks" : "error"), "真实参考结果或具体参数错误须反馈给模型");
}
Console.WriteLine("PASS: 候选参考工具、真实回放不可替代、工艺/证据/参数保护与完整结果反馈");
Console.WriteLine("PASS: 候选参考工具、正反对照逐步推进与修改失效、真实回放不可替代、工艺/证据/参数保护与完整结果反馈");
}
private static void Check(bool value, string message) { if (!value) throw new Exception(message); }
private sealed class ProbeHttp(SopVideoDraft current, SopVideoDraft candidate, string mode) : HttpMessageHandler
@ -43,9 +47,11 @@ internal static class ReferenceToolChecks
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
{
Bodies.Add(await request.Content!.ReadAsStringAsync(token));
var arguments = JsonSerializer.Serialize(new { step_id = mode == "out_of_focus" ? 4 : 1, draft = candidate });
if (mode == "advance_changed" && Bodies.Count == 2) candidate.Steps[0].Description = "已改变的要求";
var arguments = JsonSerializer.Serialize(new { step_id = mode == "out_of_focus" ? 4
: mode is "advance" or "advance_changed" && Bodies.Count == 2 ? 3 : 1, draft = candidate });
if (mode == "extra_argument") arguments = arguments[..^1] + ",\"path\":\"other.avi\"}";
object response = Bodies.Count == 1
object response = Bodies.Count == 1 || mode is "advance" or "advance_changed" && Bodies.Count == 2
? new { choices = new[] { new { finish_reason = "tool_calls", message = new { role = "assistant", content = (string?)null,
tool_calls = new[] { new { id = "probe", type = "function", function = new { name = "check_draft_reference", arguments } } } } } } }
: new { choices = new[] { new { finish_reason = "stop", message = new { content = JsonSerializer.Serialize(new { reply = "依据检查修订", draft = current }) } } } };

View File

@ -50,6 +50,10 @@ internal static class TriggerDiagnosticsChecks
"失败反馈必须包含阻塞步骤及其前序的轨迹和时序,明确区分反事实匹配与实际触发");
var decoded = JsonDocument.Parse(compact).RootElement.GetProperty("semantics").GetString()!;
Check(decoded.Contains("反事实") && decoded.Contains("不得用视频时间点代替触发"), "统计的适用范围和单帧安全约束须明确告知模型");
var detail = JsonDocument.Parse(compact).RootElement.GetProperty("failure_details")[0];
var hands = detail.GetProperty("hands_in_expected_window")[0].GetProperty("Hands")[0];
Check(hands.GetProperty("Center").GetArrayLength() == 2 && hands.GetProperty("Contact").GetArrayLength() == 4
&& result.Trajectory[0].Hands[0].X == 50, "精简反馈须保留可解释的中心与接触框且不修改原始轨迹");
Console.WriteLine("PASS: 实际手部轨迹、any选手、稳定帧、门控启用与取图/发送/确认时间、诊断旁路和前序阻塞反馈");
}
private static void Check(bool condition, string message) { if (!condition) throw new Exception(message); }

View File

@ -112,6 +112,7 @@ internal static class AgentBenchmarkChecks
var watch = Stopwatch.StartNew();
var report = await new SopDraftVideoVerifier().VerifyAsync(current, observed, template, progress, token);
Save($"round-{index}-config.json", SopDraftConfigBuilder.Build(template, current));
File.WriteAllText(Path.Combine(reportPath, $"round-{index}-config.yaml"), SopConfigLoader.ToYaml(SopDraftConfigBuilder.Build(template, current)));
playback.Add(new { Round = index, Seconds = watch.Elapsed.TotalSeconds, report.Passed, report.Summary, report.InfrastructureFailure, Images = report.Images.Count });
Save($"round-{index}-draft.json", current); Save($"round-{index}-result.json", report);
foreach (var image in report.Images) File.WriteAllBytes(Path.Combine(reportPath, $"round-{index}-step-{image.StepId}-frame-{image.FrameId}.jpg"), image.Jpeg);
@ -149,6 +150,7 @@ internal static class AgentBenchmarkChecks
}, connection, cancellation.Token);
final = result.Draft;
Save("final-draft.json", final);
if (final is not null) File.WriteAllText(Path.Combine(reportPath, "final-config.yaml"), SopConfigLoader.ToYaml(SopDraftConfigBuilder.Build(template, final)));
if (final?.Verification?.Passed != true) throw new InvalidOperationException("回测未通过:" + final?.Verification?.Summary);
}
catch (Exception failure) { error = failure.Message; Log("失败:" + error); throw; }