Files
cutdex/lib/integrations/agent/editor_acceptance.dart
T
lingjhf 06f1c26681
Gitea CI / Assemble and validate CI artifacts (push) Successful in 1m47s
Gitea CI / Check code and tests (push) Successful in 7m15s
Gitea CI / Build Android APK (push) Successful in 4m6s
Gitea CI / Build Windows x64 app (push) Successful in 3m34s
Gitea CI / Audit and package Windows x64 (push) Successful in 1m29s
Gitea CI / Gitea CI passed (push) Successful in 1s
Gitea Release / Prepare draft Release (push) Failing after 8s
Gitea Release / Upload Android to draft Release (push) Skipped
Gitea Release / Upload Windows to draft Release (push) Skipped
Gitea Release / Verify and publish Release (push) Skipped
Move editor UI into the app and release verified Core dependencies (#14)
2026-10-11 19:59:40 +00:00

449 lines
16 KiB
Dart

import 'dart:convert';
import 'package:cutdex_core/editor.dart';
import 'package:cutdex_agent/cutdex_agent.dart';
/// Deterministic, read-only acceptance for explicitly declared editor outcomes.
/// Contracts live in successful tool results, so compaction and restart cannot
/// erase or silently weaken them. Semantic quality is deliberately out of scope.
class EditorAcceptance {
EditorAcceptance(Iterable<AgentTool> tools)
: _tools = {for (final tool in tools) tool.name: tool};
final Map<String, AgentTool> _tools;
static const _registration = {
'editor_expect_clips',
'editor_expect_translation',
'timeline_planBeatCuts',
};
static const _coveredWrites = {'clip_setAudio', 'caption_addTranslations'};
List<AgentTool> get tools => [
AgentTool(
name: 'editor_expect_clips',
description: 'Before changing clips, declare expected final names and static parameter default values. Captures exact clip count, ordering, timing and connections to preserve. Every declared clip is checked from CURRENT project state before completion. Register all requested targets, not only those already edited. Re-registering cannot weaken an earlier contract in the same user task. Animated keyframe values are not checked by this tool.',
parameters: {
'type': 'object',
'properties': {
'workspaceId': {'type': 'string'},
'preserveLayout': {
'type': 'boolean',
'description': 'Default true; false only when the user also requests layout or timing changes.',
},
'clips': {
'type': 'array',
'minItems': 1,
'maxItems': 200,
'items': {
'type': 'object',
'additionalProperties': false,
'properties': {
'clipId': {'type': 'string'},
'name': {'type': 'string'},
'parameters': {
'type': 'array',
'maxItems': 32,
'items': {
'type': 'object',
'additionalProperties': false,
'properties': {
'parameterId': {'type': 'string'},
'value': {'type': 'number'},
},
'required': ['parameterId', 'value'],
},
},
},
'required': ['clipId'],
},
},
},
'required': ['workspaceId', 'clips'],
'additionalProperties': false,
},
validate: _validateClips,
execute: (call, context) async {
final args = call.arguments;
final view = await _read('timeline_query', {
'workspaceId': args['workspaceId'],
'includeParameters': false,
}, context);
final ids = (view.data['clips'] as List)
.map((c) => (c as Map)['clipId'])
.toSet();
final contracts = <Object?>[];
for (final row in args['clips'] as List) {
if (!ids.contains(row['clipId'])) {
return ToolResult('Unknown clipId ${row['clipId']}', isError: true);
}
contracts.add({
'kind': 'clip',
'workspaceId': args['workspaceId'],
'expected': row,
if (args['preserveLayout'] != false)
'layoutHash': editorEvidenceHash(editorLayout(view.data)),
});
}
return ToolResult(
'Registered deterministic clip outcomes; semantic quality is not certified',
data: {'contracts': contracts, 'version': view.version},
);
},
// A started registration with no durable result must not recapture a new
// baseline after concurrent edits. The normal unknown-outcome path applies.
),
AgentTool(
name: 'editor_expect_translation',
description: 'After creating the new target track and BEFORE writing translations, register sourceRoleId and targetRoleId. Reads all source pages at one version. Completion checks source unchanged, track identities/count unchanged, target cue count and timing multiset equal source, unique target IDs and nonempty text. This does NOT certify translation meaning or fluency; semantic concerns are review suggestions, never automatic rewrite instructions.',
parameters: {
'type': 'object',
'additionalProperties': false,
'properties': {
for (final key in ['workspaceId', 'sourceRoleId', 'targetRoleId'])
key: {'type': 'string'},
},
'required': ['workspaceId', 'sourceRoleId', 'targetRoleId'],
},
validate: (a) =>
[
'workspaceId',
'sourceRoleId',
'targetRoleId',
].any((k) => a[k] is! String || (a[k] as String).isEmpty) ||
a['sourceRoleId'] == a['targetRoleId']
? 'Supply distinct source and target tracks and a workspace'
: null,
execute: (call, context) async {
final a = call.arguments;
final tracks = await _read('caption_list', {
'workspaceId': a['workspaceId'],
}, context);
final ids = editorTrackIds(tracks.data);
if (!ids.contains(a['sourceRoleId']) ||
!ids.contains(a['targetRoleId'])) {
return ToolResult(
'Source or target track does not exist',
isError: true,
);
}
final source = await _cues(
a['workspaceId'] as String,
a['sourceRoleId'] as String,
context,
tracks.version,
);
return ToolResult(
'Registered translation structure; semantic quality remains unverified',
data: {
'contracts': [
{
'kind': 'translation',
...a,
'trackIds': ids,
'sourceHash': editorEvidenceHash(source),
'sourceCount': source.length,
},
],
'version': tracks.version,
},
);
},
),
];
String? _validateClips(Map<String, Object?> a) {
if (a['workspaceId'] is! String ||
(a['workspaceId'] as String).isEmpty ||
a['clips'] is! List ||
(a['clips'] as List).isEmpty ||
(a['clips'] as List).length > 200 ||
(a['preserveLayout'] != null && a['preserveLayout'] is! bool)) {
return 'Invalid clip expectations';
}
final ids = <String>{};
for (final row in a['clips'] as List) {
if (row is! Map ||
row['clipId'] is! String ||
!ids.add(row['clipId'] as String) ||
(row['name'] != null && row['name'] is! String)) {
return 'Supply unique clip IDs and valid names';
}
final parameters = row['parameters'];
if (parameters != null && parameters is! List) {
return 'parameters must be an array';
}
if (row['name'] == null &&
(parameters == null || (parameters as List).isEmpty)) {
return 'Declare a name or parameter value';
}
final params = <String>{};
for (final p in parameters as List? ?? const []) {
if (p is! Map ||
p['parameterId'] is! String ||
!params.add(p['parameterId'] as String) ||
p['value'] is! num ||
!(p['value'] as num).isFinite) {
return 'Supply unique parameter IDs and finite values';
}
}
}
return null;
}
Future<ToolResult> check(
SessionSnapshot snapshot,
CancellationToken token,
) async {
final calls = <String, ToolCall>{};
final contracts = <String, Map<String, Object?>>{};
final issues = <Map<String, Object?>>[];
final writes = <ToolCall>[];
for (final message in snapshot.history.skip(snapshot.runStart)) {
for (final call in message.calls) {
calls[call.id] = call;
}
if (message.role != MessageRole.tool || message.isError) continue;
final call = calls[message.callId];
if (call == null) continue;
if (_coveredWrites.contains(call.name)) writes.add(call);
if (!_registration.contains(call.name)) continue;
final result = jsonDecode(message.text) as Map;
final payload = result['data'] as Map;
final List<dynamic> registrations;
if (call.name == 'timeline_planBeatCuts') {
final plan = payload['data'] as Map;
if (plan['requireCuts'] != true) continue;
registrations = [
{
...(plan['contract'] as Map),
'workspaceId': call.arguments['workspaceId'],
},
];
} else {
registrations = payload['contracts'] as List;
}
for (final raw in registrations) {
final c = (raw as Map).cast<String, Object?>();
final key =
'${c['workspaceId']}:${c['kind']}:${c['kind'] == 'clip' ? (c['expected'] as Map)['clipId'] : c['targetRoleId']}';
if (contracts.containsKey(key) &&
editorEvidenceHash(contracts[key]) != editorEvidenceHash(c)) {
issues.add({
'kind': 'contractChanged',
'target': key,
'reason': 'Earlier acceptance criteria cannot be replaced within this task.',
});
} else {
contracts[key] = c;
}
}
}
// Never infer a complete user goal from writes alone. Require explicit
// expectations for supported editing operations and disclose coverage.
for (final call in writes) {
final workspace = call.arguments['workspaceId'];
final covered = contracts.values.any((c) {
if (c['workspaceId'] != workspace) return false;
if (call.name == 'clip_setAudio') {
if (c['kind'] != 'clip') return false;
final expected = c['expected'] as Map;
if (expected['clipId'] != call.arguments['clipId']) return false;
final parameters = (expected['parameters'] as List? ?? const [])
.map((p) => (p as Map)['parameterId'])
.toSet();
return (!call.arguments.containsKey('db') ||
parameters.contains('cutdex.audio.gainDb')) &&
(!call.arguments.containsKey('muted') ||
parameters.contains('cutdex.audio.mute'));
}
return c['kind'] == 'translation' &&
c['targetRoleId'] == call.arguments['roleId'];
});
if (!covered) {
issues.add({
'kind': 'missingExpectation',
'tool': call.name,
'arguments': call.arguments,
'reason': 'Declare the original requested outcomes with editor_expect_clips or editor_expect_translation. Include every requested target, not just successful writes.',
});
}
}
if (issues.isNotEmpty) {
return ToolResult(
'Acceptance requirements are unresolved',
isError: true,
data: {'issues': issues},
);
}
final context = ToolContext(
sessionId: snapshot.id,
runId: snapshot.runId!,
operationId:
'verification:${snapshot.id}:${snapshot.runId}:${snapshot.turns}',
cancellation: token,
onProgress: (_) {},
);
final versions = <String, String>{};
final views = <String, _View>{};
try {
for (final c in contracts.values) {
token.throwIfCancelled();
final workspace = c['workspaceId'] as String;
final view = views[workspace] ??= await _read('timeline_query', {
'workspaceId': workspace,
}, context);
versions[workspace] = view.version;
if (view.data['saveState'] != 'saved') {
issues.add({
'kind': 'saveState',
'workspaceId': workspace,
'actual': view.data['saveState'],
'expected': 'saved',
'action': 'Use project_save, then recheck.',
});
}
Map<String, Object?>? tracks;
List<Map<String, Object?>> source = const [], target = const [];
final expectation = EditorExpectation.fromJson(c);
if (expectation.needsCaptions) {
final page = await _read('caption_list', {
'workspaceId': workspace,
}, context);
_sameVersion(page.version, view.version);
tracks = page.data;
source = await _cues(
workspace,
c['sourceRoleId'] as String,
context,
view.version,
);
target = await _cues(
workspace,
c['targetRoleId'] as String,
context,
view.version,
);
}
issues.addAll(
verifyEditorOutcome(
expectation,
EditorOutcomeEvidence(
timeline: view.data,
tracks: tracks,
sourceCues: source,
targetCues: target,
),
),
);
}
// No receipt is reused as current evidence. Catch edits during multi-page
// reads as well as changes between workspaces while verification runs.
for (final entry in versions.entries) {
final current = await _read('timeline_query', {
'workspaceId': entry.key,
'includeParameters': false,
}, context);
_sameVersion(current.version, entry.value);
}
} on AgentCancelled {
rethrow;
} catch (_) {
return ToolResult(
'Current project evidence unavailable or changed during verification; query current state and retry. No acceptance granted.',
isError: true,
data: {
'issues': [
...issues,
{'kind': 'unavailableEvidence'},
],
},
);
}
return ToolResult(
issues.isEmpty
? 'Declared deterministic outcomes verified from current project state; semantic quality is not certified.'
: 'Current project differs from the requested outcomes. Repair these specific differences and recheck.',
isError: issues.isNotEmpty,
data: {
'scope': 'declaredDeterministicOutcomes',
'semanticQuality': 'unverified',
'contracts': contracts.length,
'versions': versions,
'issues': issues,
'artifactHashes': {
for (final e in views.entries)
e.key: editorEvidenceHash(e.value.data),
},
},
);
}
Future<_View> _read(
String name,
Map<String, Object?> arguments,
ToolContext context,
) async {
context.cancellation.throwIfCancelled();
final tool = _tools[name];
if (tool == null || tool.validate(arguments) != null) {
throw StateError('Query unavailable');
}
final result = await tool.execute(
ToolCall(id: context.operationId, name: name, arguments: arguments),
context,
);
context.cancellation.throwIfCancelled();
final version = result.data['version'];
final data = result.data['data'];
if (result.isError || version is! String || data is! Map) {
throw StateError('Invalid current state');
}
return _View(data.cast<String, Object?>(), version);
}
Future<List<Map<String, Object?>>> _cues(
String workspace,
String role,
ToolContext context,
String version,
) async {
final cues = <Map<String, Object?>>[];
var offset = 0;
while (true) {
final page = await _read('caption_list', {
'workspaceId': workspace,
'roleId': role,
'offset': offset,
'limit': 100,
}, context);
_sameVersion(page.version, version);
final rows = (page.data['cues'] as List)
.map((e) => (e as Map).cast<String, Object?>())
.toList();
cues.addAll(rows);
if (cues.length > 20000) throw StateError('Caption verification limit');
final next = page.data['nextOffset'];
if (next == null) {
if (cues.length != page.data['total']) {
throw StateError('Incomplete caption read');
}
return cues;
}
if (next is! int || next <= offset || rows.isEmpty) {
throw StateError('Invalid cursor');
}
offset = next;
}
}
static void _sameVersion(String a, String b) {
if (a != b) throw StateError('State changed during verification');
}
}
class _View {
const _View(this.data, this.version);
final Map<String, Object?> data;
final String version;
}