-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransform_record.go
More file actions
414 lines (392 loc) · 11.4 KB
/
Copy pathtransform_record.go
File metadata and controls
414 lines (392 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
package contexty
import "fmt"
// TransformAction classifies what the compile pipeline did to a message.
type TransformAction string
const (
ActionEvicted TransformAction = "evicted"
ActionTruncated TransformAction = "truncated"
ActionFormatted TransformAction = "formatted"
ActionPassed TransformAction = "passed"
)
const (
ReasonProtectedPending = "protected_pending"
ReasonCurrentTurnProjection = "current_turn_projection"
ReasonSegmentFormatter = "segment_formatter"
ReasonReplacedByFormatter = "replaced_by_formatter"
ReasonTransformHook = "transform_hook"
ReasonReplacedByHook = "replaced_by_hook"
ReasonReplacedByDeferred = "replaced_by_deferred"
ReasonEphemeralPatch = "ephemeral_patch"
ReasonTokenBudgetExceeded = "token_budget_exceeded" //nolint:gosec // reason label, not a credential
)
// TransformRecord describes a single message transformation.
type TransformRecord struct {
Action TransformAction
Reason string
}
// CompileResult is the immutable compile output plus O(1) traceability by Message.ID.
type CompileResult struct {
Payload AbstractPayload
Transformations map[string]TransformRecord
Source CompileRequest // immutable freeze after Normalize, before pipeline mutations
Introduced map[string]Message // deep-cloned baseline for payload-born IDs (post-deferred, pre-hooks/patches)
Artifacts []ContextArtifact
NormalizedSnapshot ConversationSnapshot
Writeback CompileWritebackIntent
Projections map[string]CompileProjection
}
// CompileRequest is the single exhaustive compile input (including stateless CompileSnapshot).
type CompileRequest struct {
TurnID string
System []Message
History []Message
Memory []Message
Tools []Message
Pending []Message
CurrentTurn *CurrentTurn
Artifacts []ContextArtifact
Options []CompileOption
IdentityPolicy MessageIdentityPolicy
RequireDurableIdentity bool
Targets []CompileTarget
}
// Normalize ensures every message has a non-empty ID and returns durable ID
// writebacks for messages whose IDs were assigned during normalization.
func (r CompileRequest) Normalize() (CompileRequest, []MessageIdentityWriteback, error) {
return normalizeCompileRequest(r)
}
// Freeze returns a deep copy of all messages for immutable CompileResult.Source.
func (r CompileRequest) Freeze() CompileRequest {
return CompileRequest{ //nolint:exhaustruct // Options omitted from immutable source snapshot
TurnID: r.TurnID,
System: cloneMessageSlice(r.System),
History: cloneMessageSlice(r.History),
Memory: cloneMessageSlice(r.Memory),
Tools: cloneMessageSlice(r.Tools),
Pending: cloneMessageSlice(r.Pending),
CurrentTurn: cloneCurrentTurnPtr(r.CurrentTurn),
Artifacts: mergeArtifacts(r.Artifacts),
IdentityPolicy: r.IdentityPolicy,
RequireDurableIdentity: r.RequireDurableIdentity,
Targets: append([]CompileTarget(nil), r.Targets...),
}
}
// Validate checks compile input invariants after Normalize.
func (r CompileRequest) Validate() error {
if r.CurrentTurn != nil {
if err := r.CurrentTurn.validate(); err != nil {
return err
}
}
if err := validateUniqueMessageIDs(r.AllMessages()); err != nil {
return err
}
if err := validateUniqueArtifactIDs(r.Artifacts); err != nil {
return err
}
return validateCompileTargets(r.Targets)
}
func normalizeCompileRequest(r CompileRequest) (CompileRequest, []MessageIdentityWriteback, error) {
var writebacks []MessageIdentityWriteback
var err error
next := CompileRequest{
TurnID: r.TurnID,
System: nil,
History: nil,
Memory: nil,
Tools: nil,
Pending: nil,
CurrentTurn: nil,
Artifacts: mergeArtifacts(r.Artifacts),
Options: r.Options,
IdentityPolicy: r.IdentityPolicy,
RequireDurableIdentity: r.RequireDurableIdentity,
Targets: append([]CompileTarget(nil), r.Targets...),
}
next.System, writebacks, err = normalizeMessagesForCompile(
r.System,
SegmentSystem,
0,
r.TurnID,
r.IdentityPolicy,
r.RequireDurableIdentity,
writebacks,
)
if err != nil {
return CompileRequest{}, nil, err
}
next.History, writebacks, err = normalizeMessagesForCompile(
r.History,
SegmentHistory,
0,
r.TurnID,
r.IdentityPolicy,
r.RequireDurableIdentity,
writebacks,
)
if err != nil {
return CompileRequest{}, nil, err
}
next.Memory, writebacks, err = normalizeMessagesForCompile(
r.Memory,
SegmentMemory,
0,
r.TurnID,
r.IdentityPolicy,
r.RequireDurableIdentity,
writebacks,
)
if err != nil {
return CompileRequest{}, nil, err
}
next.Tools, writebacks, err = normalizeMessagesForCompile(
r.Tools,
SegmentTools,
0,
r.TurnID,
r.IdentityPolicy,
r.RequireDurableIdentity,
writebacks,
)
if err != nil {
return CompileRequest{}, nil, err
}
next.Pending, writebacks, err = normalizeMessagesForCompile(
r.Pending,
SegmentHistory,
len(next.History),
r.TurnID,
r.IdentityPolicy,
r.RequireDurableIdentity,
writebacks,
)
if err != nil {
return CompileRequest{}, nil, err
}
next.CurrentTurn, writebacks, err = normalizeCurrentTurnForCompile(
r.CurrentTurn,
r.TurnID,
len(next.History)+len(next.Pending),
r.IdentityPolicy,
r.RequireDurableIdentity,
writebacks,
)
if err != nil {
return CompileRequest{}, nil, err
}
return next, writebacks, nil
}
func normalizeMessagesForCompile(
msgs []Message,
seg SegmentName,
indexOffset int,
turnID string,
policy MessageIdentityPolicy,
requireDurable bool,
writebacks []MessageIdentityWriteback,
) ([]Message, []MessageIdentityWriteback, error) {
if len(msgs) == 0 {
return nil, writebacks, nil
}
out := make([]Message, len(msgs))
for i, msg := range msgs {
normalized, wb, err := normalizeMessageForCompile(
msg,
MessageIdentityContext{
Segment: seg,
Index: indexOffset + i,
TurnID: turnID,
TargetName: "",
CurrentTurn: false,
PromptProjection: false,
},
policy,
requireDurable,
)
if err != nil {
return nil, nil, err
}
out[i] = normalized
if wb != nil {
writebacks = append(writebacks, *wb)
}
}
return out, writebacks, nil
}
func normalizeMessageForCompile(
msg Message,
idCtx MessageIdentityContext,
policy MessageIdentityPolicy,
requireDurable bool,
) (Message, *MessageIdentityWriteback, error) {
if msg.ID != "" {
return msg.Clone(), nil, nil
}
if policy == nil && requireDurable {
return Message{}, nil, ErrMissingIdentityPolicy
}
normalized := msg.Clone()
if policy == nil {
normalized = EnsureMessageID(normalized)
} else {
id, err := policy.ResolveMessageID(idCtx, msg.Clone())
if err != nil {
return Message{}, nil, fmt.Errorf("contexty: identity policy: %w", err)
}
if id == "" {
return Message{}, nil, ErrMissingIdentityPolicy
}
normalized.ID = id
}
return normalized, &MessageIdentityWriteback{
Segment: idCtx.Segment,
Index: idCtx.Index,
ID: normalized.ID,
Before: msg.Clone(),
After: normalized.Clone(),
CurrentTurn: idCtx.CurrentTurn,
}, nil
}
func normalizeCurrentTurnForCompile(
turn *CurrentTurn,
turnID string,
index int,
policy MessageIdentityPolicy,
requireDurable bool,
writebacks []MessageIdentityWriteback,
) (*CurrentTurn, []MessageIdentityWriteback, error) {
if turn == nil || !turn.hasRaw() {
return nil, writebacks, nil
}
raw, wb, err := normalizeMessageForCompile(
turn.Raw,
MessageIdentityContext{
Segment: SegmentHistory,
Index: index,
TurnID: turnID,
TargetName: "",
CurrentTurn: true,
PromptProjection: false,
},
policy,
requireDurable,
)
if err != nil {
return nil, nil, err
}
if wb != nil {
writebacks = append(writebacks, *wb)
}
normalized := CurrentTurn{
Raw: raw,
PromptSafe: Message{},
Persistence: turn.Persistence,
}
if turn.hasPromptSafe() {
prompt := turn.PromptSafe.Clone()
if prompt.ID != "" && raw.ID != "" && prompt.ID != raw.ID {
return nil, nil, ErrCurrentTurnIDMismatch
}
prompt.ID = raw.ID
normalized.PromptSafe = prompt
}
return &normalized, writebacks, nil
}
func validateUniqueArtifactIDs(artifacts []ContextArtifact) error {
seen := make(map[string]struct{}, len(artifacts))
for _, artifact := range artifacts {
if artifact.ID == "" {
continue
}
if _, dup := seen[artifact.ID]; dup {
return ErrDuplicateMessageID
}
seen[artifact.ID] = struct{}{}
}
return nil
}
// validateUniqueMessageIDs returns ErrDuplicateMessageID when any non-empty ID repeats.
func validateUniqueMessageIDs(msgs []Message) error {
seen := make(map[string]struct{}, len(msgs))
for _, m := range msgs {
if m.ID == "" {
continue
}
if _, dup := seen[m.ID]; dup {
return ErrDuplicateMessageID
}
seen[m.ID] = struct{}{}
}
return nil
}
// validateSnapshotUniqueIDs ensures all messages in snapshot segments have unique IDs.
func validateSnapshotUniqueIDs(snap ConversationSnapshot) error {
var msgs []Message
for _, seg := range snapshotSegmentOrder() {
msgs = append(msgs, snap.Segment(seg)...)
}
return validateUniqueMessageIDs(msgs)
}
// snapshotSegmentOrder returns stable segment enumeration for validation and recorder helpers.
func snapshotSegmentOrder() []SegmentName {
return []SegmentName{
SegmentSystem,
SegmentHistory,
SegmentMemory,
SegmentTools,
}
}
// AllMessages returns every input message in stable segment order for recorder init.
func (r CompileRequest) AllMessages() []Message {
var out []Message
out = append(out, r.System...)
out = append(out, r.History...)
out = append(out, r.Memory...)
out = append(out, r.Tools...)
out = append(out, r.Pending...)
if r.CurrentTurn != nil && r.CurrentTurn.hasRaw() {
out = append(out, r.CurrentTurn.Raw)
}
return out
}
// RequestFromSnapshot builds a CompileRequest from snapshot segments (no Pending).
func RequestFromSnapshot(snap ConversationSnapshot) CompileRequest {
return CompileRequest{ //nolint:exhaustruct // Pending is compile-time only
System: snap.Segment(SegmentSystem),
History: snap.Segment(SegmentHistory),
Memory: snap.Segment(SegmentMemory),
Tools: snap.Segment(SegmentTools),
Artifacts: snap.Artifacts(),
}
}
// ToSnapshot builds a conversation snapshot from request segments (excludes Pending).
func (r CompileRequest) ToSnapshot() ConversationSnapshot {
snap := EmptySnapshot()
if len(r.System) > 0 {
snap = snap.WithSegment(SegmentSystem, cloneMessageSlice(r.System))
}
if len(r.History) > 0 {
snap = snap.WithSegment(SegmentHistory, cloneMessageSlice(r.History))
}
if len(r.Memory) > 0 {
snap = snap.WithSegment(SegmentMemory, cloneMessageSlice(r.Memory))
}
if len(r.Tools) > 0 {
snap = snap.WithSegment(SegmentTools, cloneMessageSlice(r.Tools))
}
if len(r.Artifacts) > 0 {
snap = snap.WithArtifacts(r.Artifacts)
}
return snap
}
func (r CompileRequest) WritebackSnapshot() ConversationSnapshot {
snap := r.ToSnapshot()
if r.CurrentTurn != nil {
if msg, ok := r.CurrentTurn.persistedMessage(); ok {
history := snap.Segment(SegmentHistory)
history = append(history, msg)
snap = snap.WithSegment(SegmentHistory, history)
}
}
return snap.WithArtifacts(persistentArtifacts(r.Artifacts))
}