droboticflow/internal/api/slice_disposition.go

707 lines
28 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package api
import (
"context"
"fmt"
"math"
"net/http"
"reflect"
stdslices "slices"
"strings"
"droboticflow/internal/domain"
"github.com/go-chi/chi/v5"
)
func sliceDisposition(s domain.SliceSegment) string {
if s.DeliveryDisposition == "" {
return "keep"
}
return s.DeliveryDisposition
}
func allSlicesDiscarded(slices []domain.SliceSegment, segments []domain.AnnotationSegment) bool {
if len(slices) == 0 || len(segments) > 0 {
return false
}
for _, s := range slices {
if !s.IsDiscarded() {
return false
}
}
return true
}
// Disposition changes require an explicit action or a verified cancel-cut.
// Ordinary description saves cannot silently drop policy or forge audit identity.
func (s *server) canonicalSliceDispositions(ctx context.Context, item *domain.HumanItemRecord, slices []domain.SliceSegment, operations ...[]domain.SliceOperation) ([]domain.SliceSegment, []validationIssue) {
next, issues := s.canonicalSliceDispositionState(ctx, item, slices, operations...)
if len(issues) == 0 {
issues = s.validateProjectSliceNames(ctx, item, next, "draft")
}
return next, issues
}
func (s *server) canonicalSliceDispositionState(ctx context.Context, item *domain.HumanItemRecord, slices []domain.SliceSegment, operations ...[]domain.SliceOperation) ([]domain.SliceSegment, []validationIssue) {
previous := decodeMaterializationValue[domain.SliceSegment](annotationWorkspacePayload(item)["sliceSegments"])
if len(previous) == 0 && item.LegacyTaskID != "" {
revisions, err := s.store.ListSliceRevisions(ctx, item.OrganizationID, item.LegacyTaskID)
if err != nil {
return nil, []validationIssue{{Field: "sliceSegments", Message: "无法读取已保存的切片用途"}}
}
for _, r := range revisions {
if r.Revision == item.CurrentRevision || len(previous) == 0 {
previous = r.Segments
}
}
}
trustedPrevious := previousForSliceMergeUndo(item, previous, slices)
var localMerges []sliceMergeEvidence
phase := stringValue(mapValue(item.Subject.Payload["sliceWorkflow"])["phase"])
if len(operations) > 0 && (phase == "slice" || phase == "") {
if replayed, merges := replayLocalSliceMerges(trustedPrevious, slices, operations[0]); replayed != nil {
trustedPrevious, localMerges = replayed, merges
}
}
next, issues := canonicalDispositions(trustedPrevious, slices)
applySliceArchiveEdits(next, currentSliceArchiveEdits(item))
// In-place structure editing is unlocked in every annotate pass (spec
// §3.4): first-pass and rework share this one path. Boundary moves and
// merges of discarded evidence stay explicit operations, and the
// submit-time containment and status-whitelist validations are the
// bottom line that keeps every action inside exactly one slice.
if len(issues) == 0 {
recordSliceMerges(item, trustedPrevious, next, localMerges...)
}
return next, issues
}
func canonicalDispositions(previous, slices []domain.SliceSegment) ([]domain.SliceSegment, []validationIssue) {
old := map[string]domain.SliceSegment{}
proposed := map[string]domain.SliceSegment{}
for _, p := range previous {
if _, duplicate := old[p.ID]; duplicate {
return nil, []validationIssue{{Field: "sliceSegments", Message: "已保存的切片 ID 重复"}}
}
old[p.ID] = p
}
for _, candidate := range slices {
if _, duplicate := proposed[candidate.ID]; duplicate {
return nil, []validationIssue{{Field: "sliceSegments", Message: "切片 ID 必须唯一"}}
}
proposed[candidate.ID] = candidate
}
next := append([]domain.SliceSegment(nil), slices...)
seen := map[string]bool{}
issues := []validationIssue{}
mergedSources := map[string]bool{}
for i, c := range next {
if sources := explicitSliceMerge(previous, c); len(sources) > 0 {
next[i] = clearedMergedSlice(c)
for _, source := range sources {
mergedSources[source.ID] = true
}
seen[c.ID] = true
continue
}
p, exists := old[c.ID]
inherited := false
if !exists && c.IsDiscarded() {
// Source IDs are flattened by repeated local cuts. Resolve only against
// this task's saved slices; never trust client-supplied audit fields.
for _, sourceID := range c.SourceIDs {
if source, ok := old[sourceID]; ok {
p, exists, inherited = source, true, true
break
}
}
}
seen[c.ID] = true
if sliceDisposition(c) != "keep" && sliceDisposition(c) != "discard" {
issues = append(issues, validationIssue{Field: fmt.Sprintf("sliceSegments.%d.deliveryDisposition", i), Message: "切片用途必须为 keep 或 discard"})
continue
}
if (!exists && c.IsDiscarded()) || (exists && (sliceDisposition(p) != sliceDisposition(c) || p.DiscardReason != c.DiscardReason)) {
issues = append(issues, validationIssue{Field: fmt.Sprintf("sliceSegments.%d.deliveryDisposition", i), Code: "explicit_disposition_required", Message: "请通过舍弃/恢复操作保存切片用途"})
}
if exists {
next[i].SourceIDs = append([]string(nil), p.SourceIDs...)
if inherited {
next[i].SourceIDs = append([]string{p.ID}, next[i].SourceIDs...)
// Preserve intermediate parents from several cuts in one unsaved
// edit, so a later undo can rejoin exactly those siblings.
for _, sourceID := range c.SourceIDs {
ancestor, ok := proposed[sourceID]
if ok && sourceID != c.ID && ancestor.IsDiscarded() && ancestor.DiscardReason == p.DiscardReason &&
stdslices.Contains(ancestor.SourceIDs, p.ID) && !stdslices.Contains(next[i].SourceIDs, sourceID) {
next[i].SourceIDs = append(next[i].SourceIDs, sourceID)
}
}
}
}
next[i].DiscardReasonLabelID = p.DiscardReasonLabelID
next[i].DiscardReasonVersion = p.DiscardReasonVersion
next[i].DiscardReasonName = p.DiscardReasonName
next[i].DiscardReasonDictionary = p.DiscardReasonDictionary
next[i].DiscardReasonNote = p.DiscardReasonNote
next[i].DiscardedByUserID = p.DiscardedByUserID
next[i].DiscardedAt = p.DiscardedAt
next[i].DiscardedAnnotations = append([]domain.AnnotationSegment(nil), p.DiscardedAnnotations...)
if next[i].IsDiscarded() {
next[i].Name, next[i].TaskLabelID, next[i].TaskLabel = "", "", ""
}
}
for _, p := range previous {
if p.IsDiscarded() && !seen[p.ID] && !mergedSources[p.ID] {
// Undoing a split can reunite a child with its original discarded
// parent, but cannot silently absorb it into a kept/differently judged slice.
rejoined := false
for i, candidate := range next {
if candidate.IsDiscarded() && stdslices.Contains(p.SourceIDs, candidate.ID) &&
candidate.Start <= p.Start && candidate.End >= p.End &&
candidate.DiscardReason == p.DiscardReason &&
candidate.DiscardReasonLabelID == p.DiscardReasonLabelID &&
candidate.DiscardReasonVersion == p.DiscardReasonVersion {
// The child may have been restored and edited since the split.
// Its current archive owns its interval, even when a parent still
// retains an older, wider original for boundary undo.
childEvidence := restoredDiscardAnnotations(p)
parentWindow := candidate
parentWindow.Start, parentWindow.End = p.Start, p.End
if !sameArchiveContent(restoredDiscardAnnotations(parentWindow), childEvidence) {
next[i].DiscardedAnnotations = append(archiveOutsideIntervals(candidate.DiscardedAnnotations, candidate.ID, p), childEvidence...)
}
rejoined = true
break
}
}
if !rejoined {
issues = append(issues, validationIssue{Field: "sliceSegments", Message: "不能直接删除或合并舍弃片段,请先恢复"})
}
}
}
return next, issues
}
// Server-owned recovery evidence is separate from the public discard archive:
// a kept slice has no discarded annotations. Workspace snapshot writes must not
// replace this payload field with client evidence. One entry per slice bounds
// storage, and revision/phase checks prevent replay across materialization.
const sliceRestoreEvidenceKey = "sliceRestoreEvidence"
type sliceRestoreEvidence struct {
Slice domain.SliceSegment `json:"slice"`
Restored []domain.AnnotationSegment `json:"restored"`
Revision int `json:"revision"`
Phase string `json:"phase"`
}
func sameRestoredAnnotations(active, restored []domain.AnnotationSegment) bool {
remaining := append([]domain.AnnotationSegment(nil), active...)
unchanged := len(remaining) == len(restored)
for _, expected := range restored {
found := -1
for i, a := range remaining {
if reflect.DeepEqual(a, expected) {
found = i
break
}
}
if found < 0 {
unchanged = false
break
}
remaining = append(remaining[:found], remaining[found+1:]...)
}
return unchanged
}
func discardArchiveAfterRestore(e sliceRestoreEvidence, next domain.SliceSegment, active []domain.AnnotationSegment) []domain.AnnotationSegment {
if sameRestoredAnnotations(active, e.Restored) {
return append([]domain.AnnotationSegment(nil), e.Slice.DiscardedAnnotations...)
}
// Edits/deletions supersede only the exposed and current intervals.
return append(append([]domain.AnnotationSegment(nil), active...), archiveOutsideIntervals(e.Slice.DiscardedAnnotations, next.ID, e.Slice, next)...)
}
// Only a changed restore->discard writes ownership. Inherited archive records
// are not writes. Empty replacement content is an authoritative deletion.
const sliceArchiveEditsKey = "sliceArchiveEdits"
type sliceArchiveEdit struct {
Owner domain.SliceSegment `json:"owner"`
Intervals []domain.SliceSegment `json:"intervals"`
Annotations []domain.AnnotationSegment `json:"annotations"`
Version int `json:"version"`
Revision int `json:"revision"`
Phase string `json:"phase"`
}
func currentSliceArchiveEdits(item *domain.HumanItemRecord) []sliceArchiveEdit {
var result []sliceArchiveEdit
phase := stringValue(mapValue(item.Subject.Payload["sliceWorkflow"])["phase"])
for _, edit := range decodeMaterializationValue[sliceArchiveEdit](item.Subject.Payload[sliceArchiveEditsKey]) {
if edit.Revision == item.CurrentRevision && edit.Phase == phase {
result = append(result, edit)
}
}
stdslices.SortStableFunc(result, func(a, b sliceArchiveEdit) int {
if a.Version < b.Version {
return -1
}
if a.Version > b.Version {
return 1
}
return 0
})
return result
}
func applySliceArchiveEdits(slices []domain.SliceSegment, edits []sliceArchiveEdit) {
for _, edit := range edits {
for i := range slices {
target := &slices[i]
// The owner and its saved ancestors may recover this write. Do not turn
// a sibling's inherited full archive or client SourceIDs into ownership.
if !target.IsDiscarded() || (target.ID != edit.Owner.ID && !stdslices.Contains(edit.Owner.SourceIDs, target.ID)) {
continue
}
for _, interval := range edit.Intervals {
replacement := interval
replacement.ID = edit.Owner.ID
replacement.DiscardedAnnotations = edit.Annotations
content := restoredDiscardAnnotations(replacement)
window := *target
window.Start, window.End = interval.Start, interval.End
if sameArchiveContent(restoredDiscardAnnotations(window), content) {
continue
}
target.DiscardedAnnotations = append(archiveOutsideIntervals(target.DiscardedAnnotations, target.ID, interval), content...)
}
}
}
}
func sameArchiveContent(a, b []domain.AnnotationSegment) bool {
if len(a) != len(b) {
return false
}
for i := range a {
left, right := a[i], b[i]
left.ID, right.ID = "", ""
if !reflect.DeepEqual(left, right) {
return false
}
}
return true
}
func archiveOutsideIntervals(originals []domain.AnnotationSegment, sliceID string, intervals ...domain.SliceSegment) []domain.AnnotationSegment {
var archive []domain.AnnotationSegment
for _, original := range originals {
parts := []domain.AnnotationSegment{original}
for _, interval := range intervals {
var kept []domain.AnnotationSegment
for _, a := range parts {
if a.End <= interval.Start || a.Start >= interval.End {
kept = append(kept, a)
continue
}
for _, bounds := range [][2]float64{{a.Start, math.Min(a.End, interval.Start)}, {math.Max(a.Start, interval.End), a.End}} {
if bounds[1] <= bounds[0] {
continue
}
part := a
part.Start, part.End = bounds[0], bounds[1]
part.ID = fmt.Sprintf("%s@%s:%g:%g", original.ID, sliceID, part.Start, part.End)
part.StartTimestampUS, part.EndTimestampUS = 0, 0
kept = append(kept, part)
}
}
parts = kept
}
archive = append(archive, parts...)
}
return archive
}
// Keep the original archive intact for boundary undo. Restoring a child only
// reactivates the part of that evidence inside its current interval.
func restoredDiscardAnnotations(slice domain.SliceSegment) []domain.AnnotationSegment {
var result []domain.AnnotationSegment
for _, annotation := range slice.DiscardedAnnotations {
start, end := math.Max(annotation.Start, slice.Start), math.Min(annotation.End, slice.End)
if end <= start {
continue
}
if start != annotation.Start || end != annotation.End {
annotation.ID += "@" + slice.ID
annotation.StartTimestampUS, annotation.EndTimestampUS = 0, 0
}
annotation.Start, annotation.End = start, end
result = append(result, annotation)
}
return result
}
type sliceDispositionInput struct {
combinedAnnotationDraftInput
RestoreClassifications bool `json:"restoreClassifications,omitempty"`
SliceID string `json:"sliceId"`
Disposition string `json:"disposition"`
Reason string `json:"reason"`
ReasonLabelID string `json:"reasonLabelId"`
ReasonVersion int `json:"reasonVersion"`
ReasonNote string `json:"reasonNote"`
RestorePreviousName bool `json:"restorePreviousName,omitempty"`
ResetToPending bool `json:"resetToPending,omitempty"`
RestoreNameFromVersion int `json:"restoreNameFromVersion,omitempty"`
}
func sliceNameBeforeDiscard(item *domain.HumanItemRecord, sliceID string, version int) (string, bool) {
prior := sliceBeforeDiscard(item, sliceID, version)
if prior == nil {
return "", false
}
return prior.Name, true
}
func sliceBeforeDiscard(item *domain.HumanItemRecord, sliceID string, version int) *domain.SliceSegment {
history, _ := normalizeStructuredValue(item.Subject.Payload["sliceDispositionHistory"]).([]any)
resets, _ := normalizeStructuredValue(item.Subject.Payload["sliceResetHistory"]).([]any)
resetVersion := 0
if len(resets) > 0 {
resetVersion = intValue(mapValue(resets[len(resets)-1])["itemVersion"])
}
for i := len(history) - 1; i >= 0; i-- {
entry := mapValue(history[i])
entryVersion := intValue(entry["itemVersion"])
if entryVersion <= resetVersion {
break
}
if stringValue(entry["sliceId"]) != sliceID || (version != 0 && entryVersion != version) {
continue
}
before := decodeMaterializationValue[domain.SliceSegment]([]any{entry["before"]})
after := decodeMaterializationValue[domain.SliceSegment]([]any{entry["after"]})
if len(before) == 1 && len(after) == 1 && !before[0].IsDiscarded() && after[0].IsDiscarded() {
copy := before[0]
return &copy
}
}
return nil
}
func (s *server) handleSliceDisposition(w http.ResponseWriter, r *http.Request) {
task, err := s.store.GetAnnotationTask(r.Context(), chi.URLParam(r, "id"))
if err != nil {
renderError(w, 500, err)
return
}
if task == nil {
renderJSON(w, 404, map[string]string{"error": "Annotation task not found"})
return
}
p, _, ok := s.ensureAnnotationTaskAccess(w, r, *task)
if !ok {
return
}
if p == nil || p.User.Role != domain.UserRoleAnnotator {
renderJSON(w, 403, map[string]string{"error": "只有标注员可设置舍弃/恢复,审核员请通过审核意见打回"})
return
}
item, ok := s.requireLegacyHumanItemClaim(w, r, *task, domain.FanyuV58StageAnnotationCombined)
if !ok {
return
}
if rejectPendingCombinedSubmission(w, item) {
return
}
workflow := mapValue(item.Subject.Payload["sliceWorkflow"])
if stringValue(workflow["status"]) == "processing" {
renderJSON(w, 409, map[string]string{"error": "切片正在生成,请完成后再设置用途"})
return
}
var body sliceDispositionInput
if !decodeJSON(w, r, &body) {
return
}
if body.Version != item.Version {
renderJSON(w, 409, map[string]string{"code": "version_conflict", "error": "任务已变化,请刷新后重试"})
return
}
workspace, next, prepared := s.prepareSliceDisposition(w, r, task, item, p.User.ID, body)
if !prepared {
return
}
version := item.Version
item.Version++
item.UpdatedAt = nowISO()
won, e := s.store.UpdateHumanItemVersioned(r.Context(), *item, version)
if e != nil {
renderError(w, 500, e)
return
}
if !won {
renderJSON(w, 409, map[string]string{"code": "version_conflict", "error": "任务已变化,请刷新后重试"})
return
}
_ = s.appendHumanEvent(r.Context(), *item, "slice_disposition_changed", p.User.ID, map[string]any{"sliceId": next.ID, "disposition": body.Disposition, "reason": next.DiscardReason, "reasonLabelId": next.DiscardReasonLabelID, "reasonVersion": next.DiscardReasonVersion, "reasonNote": next.DiscardReasonNote, "start": next.Start, "end": next.End})
renderJSON(w, 200, map[string]any{"item": item, "workspace": workspace})
}
// prepareSliceDisposition updates only this in-memory item. Callers commit one CAS
// after every command and structure validation succeeds.
func (s *server) prepareSliceDisposition(w http.ResponseWriter, r *http.Request, task *domain.AnnotationTaskRecord, item *domain.HumanItemRecord, actorID string, body sliceDispositionInput) (map[string]any, domain.SliceSegment, bool) {
workflow := mapValue(item.Subject.Payload["sliceWorkflow"])
if body.Disposition != "keep" && body.Disposition != "discard" {
renderValidationError(w, validationIssue{Field: "disposition", Message: "用途必须为 keep 或 discard"})
return nil, domain.SliceSegment{}, false
}
body.Reason = strings.TrimSpace(body.Reason)
body.ReasonNote = strings.TrimSpace(body.ReasonNote)
var reasonLabel *domain.AnnotationLabelRecord
if body.Disposition == "discard" {
var issues []validationIssue
reasonLabel, issues = s.resolveDiscardReason(r.Context(), item, body)
if len(issues) > 0 {
renderValidationError(w, issues...)
return nil, domain.SliceSegment{}, false
}
if reasonLabel != nil {
body.Reason = reasonLabel.Name
if body.ReasonNote != "" {
body.Reason += ":" + body.ReasonNote
}
} else {
body.ReasonNote = ""
}
}
slices, issues := s.canonicalSliceDispositionState(r.Context(), item, body.normalizedSliceSegments(), body.normalizedOperations())
issues = append(issues, s.validateProjectSliceNames(r.Context(), item, slices, "restore")...)
if task.SourceIsFullVideo {
timeline, e := s.annotationFrameTimelineForTask(r.Context(), *task, "left")
if e != nil {
renderJSON(w, 422, map[string]string{"error": e.Error()})
return nil, domain.SliceSegment{}, false
}
task.CoverageStartSecond = floatValue(timeline["rangeStartSecond"])
task.CoverageEndSecond = floatValue(timeline["rangeEndSecond"])
task.CoverageMode = "full_common_range"
}
issues = append(issues, validateSliceSegments(slices, *task)...)
issues = append(issues, validateCompleteSliceCoverage(slices, *task)...)
issues = append(issues, s.canonicalActionDictionaries(r.Context(), item, body.Segments, dispositionDictionaryMode(body))...)
issues = append(issues, validateDraftCombinedAnnotationEvents(body.Segments, *task)...)
idx := -1
for i, v := range slices {
if v.ID == body.SliceID {
idx = i
}
}
if idx < 0 {
issues = append(issues, validationIssue{Field: "sliceId", Message: "请选择当前切片"})
}
if len(issues) > 0 {
renderValidationError(w, describeSliceNameIssues(issues, slices)...)
return nil, domain.SliceSegment{}, false
}
before := slices[idx]
if body.ResetToPending && (body.Disposition != "keep" || !before.IsDiscarded()) {
renderValidationError(w, validationIssue{Field: "resetToPending", Message: "只能在明确取消舍弃时重置待标注区间"})
return nil, domain.SliceSegment{}, false
}
restoredName := ""
if body.RestorePreviousName || body.RestoreNameFromVersion != 0 {
var found bool
restoredName, found = sliceNameBeforeDiscard(item, before.ID, body.RestoreNameFromVersion)
if body.RestoreNameFromVersion != 0 && (!found || !before.IsDiscarded() || body.Disposition != "keep") {
renderValidationError(w, validationIssue{Field: "restoreNameFromVersion", Message: "只能恢复当前切片本轮编辑中已记录的舍弃前名称"})
return nil, domain.SliceSegment{}, false
}
}
next := before
evidence := decodeMaterializationValue[sliceRestoreEvidence](item.Subject.Payload[sliceRestoreEvidenceKey])
phase := stringValue(workflow["phase"])
archiveEdits := currentSliceArchiveEdits(item)
var retainedEvidence []sliceRestoreEvidence
var recovery *sliceRestoreEvidence
for _, e := range evidence {
if e.Revision != item.CurrentRevision || e.Phase != phase {
continue
}
if e.Slice.ID == next.ID {
copy := e
recovery = &copy
} else {
for _, candidate := range slices {
if candidate.ID == e.Slice.ID && !candidate.IsDiscarded() {
retainedEvidence = append(retainedEvidence, e)
break
}
}
}
}
// Blank annotations are valid. Keep an allocated empty slice so restore
// (including restore with no archived descriptions) serializes [] not null.
segments := append([]domain.AnnotationSegment{}, body.Segments...)
if body.Disposition == "discard" {
next.DeliveryDisposition = "discard"
next.Name, next.TaskLabelID, next.TaskLabel = "", "", ""
next.Dictionary = nil
next.DiscardReason = body.Reason
next.DiscardReasonLabelID = ""
next.DiscardReasonVersion = 0
next.DiscardReasonName = ""
next.DiscardReasonDictionary = nil
if reasonLabel != nil {
next.DiscardReasonLabelID = reasonLabel.ID
next.DiscardReasonVersion = reasonLabel.Version
next.DiscardReasonName = reasonLabel.Name
next.DiscardReasonDictionary = reasonLabel.Selection()
if body.RestoreClassifications {
next.DiscardReasonDictionary = savedDictionarySelection(item, &domain.DictionarySelection{ID: reasonLabel.ID, Version: reasonLabel.Version}, "discard_reason")
}
}
next.DiscardReasonNote = body.ReasonNote
next.DiscardedByUserID = actorID
next.DiscardedAt = nowISO()
next.AnnotationStatus = domain.SliceAnnotationPending
kept := []domain.AnnotationSegment{}
var archived []domain.AnnotationSegment
for _, a := range segments {
if a.Start >= next.Start && a.End <= next.End {
archived = append(archived, a)
} else if a.Start < next.End && a.End > next.Start {
renderValidationError(w, validationIssue{Field: "segments", Message: "描述跨越切片边界,请先修正"})
return nil, domain.SliceSegment{}, false
} else {
kept = append(kept, a)
}
}
if !before.IsDiscarded() && recovery != nil {
next.DiscardedAnnotations = discardArchiveAfterRestore(*recovery, next, archived)
if !sameRestoredAnnotations(archived, recovery.Restored) {
intervals := []domain.SliceSegment{{Start: recovery.Slice.Start, End: recovery.Slice.End}, {Start: next.Start, End: next.End}}
if intervals[0].Start <= intervals[1].End && intervals[1].Start <= intervals[0].End {
intervals = []domain.SliceSegment{{Start: math.Min(recovery.Slice.Start, next.Start), End: math.Max(recovery.Slice.End, next.End)}}
}
archiveEdits = append(archiveEdits, sliceArchiveEdit{Owner: domain.SliceSegment{ID: next.ID, SourceIDs: append([]string(nil), next.SourceIDs...)}, Intervals: intervals, Annotations: append([]domain.AnnotationSegment(nil), archived...), Version: item.Version + 1, Revision: item.CurrentRevision, Phase: phase})
}
} else {
next.DiscardedAnnotations = append(next.DiscardedAnnotations, archived...)
}
if archiveIssues := validateDraftCombinedAnnotationEvents(next.DiscardedAnnotations, *task); len(archiveIssues) > 0 {
renderValidationError(w, archiveIssues...)
return nil, domain.SliceSegment{}, false
}
segments = kept
} else {
if before.IsDiscarded() {
restored := restoredDiscardAnnotations(before)
if body.ResetToPending || len(restored) == 0 {
// Explicit restore starts fresh; legacy empty archives still need
// a real pending partition. Original evidence remains server-owned.
keptSlice := before
keptSlice.DeliveryDisposition = "keep"
restored = fillPendingActionGaps([]domain.SliceSegment{keptSlice}, nil)
}
if body.ResetToPending {
outside := []domain.AnnotationSegment{}
for _, action := range segments {
if action.End <= before.Start || action.Start >= before.End {
outside = append(outside, action)
} else if action.Start < before.Start || action.End > before.End {
renderValidationError(w, validationIssue{Field: "segments", Message: "动作跨越切片边界,不能取消舍弃"})
return nil, domain.SliceSegment{}, false
}
}
segments = outside
}
used := map[string]bool{}
for _, a := range segments {
used[a.ID] = true
}
for i := range restored {
base := restored[i].ID
for n := 1; used[restored[i].ID]; n++ {
restored[i].ID = fmt.Sprintf("%s@%s:%d", base, next.ID, n)
}
used[restored[i].ID] = true
}
segments = append(segments, restored...)
retainedEvidence = append(retainedEvidence, sliceRestoreEvidence{Slice: before, Restored: restored, Revision: item.CurrentRevision, Phase: phase})
} else if recovery != nil {
retainedEvidence = append(retainedEvidence, *recovery)
}
next.DeliveryDisposition = "keep"
if before.IsDiscarded() {
next.Name, next.TaskLabelID, next.TaskLabel = "", "", ""
// Precise undo targets a server-recorded discard, even after later
// undo/redo writes. Ordinary restore deliberately remains unnamed.
next.Name = restoredName
next.Dictionary = nil
if body.RestorePreviousName || body.RestoreNameFromVersion != 0 {
if prior := sliceBeforeDiscard(item, before.ID, body.RestoreNameFromVersion); prior != nil {
next.Dictionary = prior.Dictionary
}
}
}
next.DiscardReason = ""
next.DiscardReasonLabelID = ""
next.DiscardReasonVersion = 0
next.DiscardReasonName = ""
next.DiscardReasonDictionary = nil
next.DiscardReasonNote = ""
next.DiscardedByUserID = ""
next.DiscardedAt = ""
next.DiscardedAnnotations = nil
next.AnnotationStatus = domain.SliceAnnotationPending
}
slices[idx] = next
applySliceArchiveEdits(slices, archiveEdits)
next = slices[idx]
// Disposition is an incremental edit, not confirmation of the whole slicing
// plan. Other slices may still have draft names; confirmation validates them.
issues = s.validateProjectSliceNames(r.Context(), item, slices, "restore")
issues = append(issues, s.canonicalActionDictionaries(r.Context(), item, segments, "restore")...)
issues = append(issues, validateDraftCombinedAnnotationEvents(segments, *task)...)
if len(issues) > 0 {
renderValidationError(w, describeSliceNameIssues(issues, slices)...)
return nil, domain.SliceSegment{}, false
}
statuses := body.normalizedStatuses()
statuses[next.ID] = domain.SliceAnnotationPending
if issues := rememberDictionarySelections(item, sliceDictionarySelections(slices)...); len(issues) > 0 {
renderValidationError(w, issues...)
return nil, domain.SliceSegment{}, false
}
workspace := map[string]any{"sliceSegments": slices, "segments": segments, "statuses": statuses, "operations": body.normalizedOperations(), "userId": actorID, "savedAt": nowISO()}
if item.Subject.Payload == nil {
item.Subject.Payload = map[string]any{}
}
history, _ := normalizeStructuredValue(item.Subject.Payload["sliceDispositionHistory"]).([]any)
history = append(history, map[string]any{"sliceId": next.ID, "before": before, "after": next, "actorUserId": actorID, "at": nowISO(), "itemVersion": item.Version + 1})
item.Subject.Payload["sliceDispositionHistory"] = history
item.Subject.Payload[sliceRestoreEvidenceKey] = retainedEvidence
item.Subject.Payload[sliceArchiveEditsKey] = archiveEdits
item.Subject.Payload["annotationWorkspace"] = workspace
delete(item.Subject.Payload, "annotationDraft")
if body.Disposition == "discard" {
// Frame validation can be slow; reject a dictionary change made while it ran.
if _, issues := s.resolveDiscardReason(r.Context(), item, body); len(issues) > 0 {
renderValidationError(w, issues...)
return nil, domain.SliceSegment{}, false
}
}
return workspace, next, true
}
func dispositionDictionaryMode(body sliceDispositionInput) string {
if body.RestoreClassifications {
return "restore"
}
return "draft"
}