Share transcript envelope validation

This commit is contained in:
2026-12-02 21:34:28 +00:00
parent a623ecb518
commit 3d09745a79
10 changed files with 79 additions and 56 deletions

View File

@@ -0,0 +1,28 @@
package contracts
import (
"encoding/json"
"fmt"
)
// TranscriptDecodeError identifies invalid JSON or a non-object root.
type TranscriptDecodeError struct{ Err error }
func (e *TranscriptDecodeError) Error() string { return "decode json: " + e.Err.Error() }
func (e *TranscriptDecodeError) Unwrap() error { return e.Err }
// ValidateTranscriptEnvelope checks the shared minimal transcript JSON shape.
func ValidateTranscriptEnvelope(data []byte) error {
var payload map[string]any
if err := json.Unmarshal(data, &payload); err != nil {
return &TranscriptDecodeError{Err: err}
}
segments, ok := payload["segments"]
if !ok {
return fmt.Errorf("top-level segments is required")
}
if _, ok := segments.([]any); !ok {
return fmt.Errorf("top-level segments must be an array")
}
return nil
}

View File

@@ -0,0 +1,23 @@
package contracts
import "testing"
func TestValidateTranscriptEnvelope(t *testing.T) {
for _, tc := range []struct {
name, input string
valid bool
}{
{"empty segments", `{"segments":[]}`, true},
{"other members", `{"extra":true,"segments":[null,{"anything":1}]}`, true},
{"malformed", `{`, false}, {"missing", `{}`, false}, {"null segments", `{"segments":null}`, false},
{"object segments", `{"segments":{}}`, false}, {"string segments", `{"segments":"x"}`, false},
{"null root", `null`, false}, {"array root", `[]`, false}, {"string root", `"text"`, false},
} {
t.Run(tc.name, func(t *testing.T) {
err := ValidateTranscriptEnvelope([]byte(tc.input))
if (err == nil) != tc.valid {
t.Fatalf("error = %v, valid = %t", err, tc.valid)
}
})
}
}