forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnowledgeLedgerPromptProjection.swift
More file actions
221 lines (198 loc) · 7.67 KB
/
Copy pathKnowledgeLedgerPromptProjection.swift
File metadata and controls
221 lines (198 loc) · 7.67 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
import Foundation
/// The client-side prompt view of `knowledge_ledger.v1`.
///
/// This is a pure projection over a caller-proven authoritative snapshot, not a
/// second storage authority. A bounded local cache can never prove completeness
/// and therefore cannot activate this renderer during the migration window.
struct KnowledgeLedgerPromptProjection: Equatable, Sendable {
static let schemaVersion = "knowledge_ledger.v1"
static let profileCharacterBudget = 2_400
static let playbookCharacterBudget = 800
struct Row: Equatable, Sendable {
let id: String
let content: String
let createdAt: Date
let metadata: [String: String]
let userReview: Bool?
init(
id: String,
content: String,
createdAt: Date = Date(),
metadata: [String: String] = [:],
userReview: Bool? = nil
) {
self.id = id
self.content = content
self.createdAt = createdAt
self.metadata = metadata
self.userReview = userReview
}
init(memory: ServerMemory) {
self.init(
id: memory.id,
content: memory.content,
createdAt: memory.createdAt,
metadata: memory.ledgerMetadata,
userReview: memory.userReview
)
}
var schemaVersion: String? { metadata["ledger_schema_version"] }
var kind: String? { metadata["kind"] }
var subjectScope: String? { metadata["subject_scope"] }
var slot: String? { Self.normalized(metadata["slot"]) }
var intentBacked: Bool { metadata["intent_backed"] == "true" }
var curationWeight: Int { Int(metadata["curation_weight"] ?? "") ?? 0 }
var validAt: String { metadata["valid_at"] ?? "" }
var isOpen: Bool {
let status = metadata["status"]?.lowercased()
guard status == nil || status == "active" else { return false }
return Self.isBlank(metadata["invalid_at"])
&& Self.isBlank(metadata["valid_to"])
&& Self.isBlank(metadata["superseded_by"])
}
var trimmedContent: String { content.trimmingCharacters(in: .whitespacesAndNewlines) }
private static func normalized(_ value: String?) -> String? {
guard let value else { return nil }
let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
}
private static func isBlank(_ value: String?) -> Bool {
guard let value else { return true }
let normalized = value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
return normalized.isEmpty || normalized == "null"
}
}
let rows: [Row]
private let hasAuthoritativeSnapshot: Bool
/// Ledger-shaped rows alone are not migration proof. Rendering requires an
/// explicit completeness proof from the owning storage boundary as well as a
/// homogeneous schema, so a truncated local prefix cannot hide older facts.
var isCompleteLedgerSnapshot: Bool {
hasAuthoritativeSnapshot
&& rows.allSatisfy { $0.schemaVersion == Self.schemaVersion }
}
init(memories: [ServerMemory], hasAuthoritativeSnapshot: Bool) {
self.init(
rows: memories.map(Row.init(memory:)),
hasAuthoritativeSnapshot: hasAuthoritativeSnapshot)
}
init(rows: [Row], hasAuthoritativeSnapshot: Bool) {
self.rows = rows
self.hasAuthoritativeSnapshot = hasAuthoritativeSnapshot
}
/// Render the complete bounded context, or nil when no canonical row is
/// present. The nil result is the fail-safe for old payloads.
func render(
userName: String?,
marker: ((String) -> String?)? = nil
) -> String? {
guard isCompleteLedgerSnapshot else { return nil }
let facts = eligibleFacts
let profileLines = boundedLines(
facts.compactMap { row in
guard let slot = row.slot else { return nil }
let citation = marker?(row.id).map { " \($0)" } ?? ""
return "\(slot): \(row.trimmedContent)\(citation)"
},
budget: Self.profileCharacterBudget
)
let displayName = userName?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let profile = profileLines.isEmpty ? "(no current slotted facts)" : profileLines
var sections = ["Current profile for \(displayName.isEmpty ? "the user" : displayName):\n\(profile)"]
let playbookLines = boundedLines(
eligiblePlaybooks.map { row in
let citation = marker?(row.id).map { " \($0)" } ?? ""
return "\(row.id): \(row.trimmedContent)\(citation)"
},
budget: Self.playbookCharacterBudget
)
if !playbookLines.isEmpty {
sections.append(
"Available playbooks (call read_playbook for the body; do not infer it from the title):\n\(playbookLines)"
)
}
return sections.joined(separator: "\n\n") + "\n"
}
/// Sources admitted into the citation ledger. Bodies and excluded rows are
/// never represented here, so markers cannot grant them prompt authority.
var citationSources: [ChatPromptCitationSource] {
guard isCompleteLedgerSnapshot else { return [] }
let factSources = eligibleFacts.map {
ChatPromptCitationSource(
kind: .memory,
sourceID: $0.id,
title: $0.slot ?? "Memory",
preview: $0.trimmedContent,
createdAt: ISO8601DateFormatter().string(from: $0.createdAt)
)
}
let playbookSources = eligiblePlaybooks.map {
ChatPromptCitationSource(
kind: .memory,
sourceID: $0.id,
title: $0.trimmedContent,
preview: $0.trimmedContent,
createdAt: ISO8601DateFormatter().string(from: $0.createdAt)
)
}
return factSources + playbookSources
}
private var eligibleFacts: [Row] {
rows
.filter {
$0.schemaVersion == Self.schemaVersion
&& $0.kind == "fact"
&& $0.subjectScope == "primary_user"
&& $0.intentBacked
&& $0.userReview != false
&& $0.isOpen
&& $0.slot != nil
&& !$0.trimmedContent.isEmpty
}
.sorted {
if $0.curationWeight != $1.curationWeight { return $0.curationWeight > $1.curationWeight }
if $0.slot != $1.slot { return ($0.slot ?? "") < ($1.slot ?? "") }
if $0.validAt != $1.validAt { return $0.validAt < $1.validAt }
return $0.id < $1.id
}
}
private var eligiblePlaybooks: [Row] {
rows
.filter {
$0.schemaVersion == Self.schemaVersion
&& $0.kind == "document"
&& $0.userReview != false
&& $0.isOpen
&& !$0.trimmedContent.isEmpty
}
.sorted {
if $0.curationWeight != $1.curationWeight { return $0.curationWeight > $1.curationWeight }
if $0.trimmedContent != $1.trimmedContent { return $0.trimmedContent < $1.trimmedContent }
return $0.id < $1.id
}
}
private func boundedLines(_ lines: [String], budget: Int) -> String {
var result: [String] = []
var used = 0
for line in lines {
let separator = result.isEmpty ? 0 : 1
guard used + separator + line.count <= budget else { continue }
result.append(line)
used += separator + line.count
}
return result.joined(separator: "\n")
}
}
/// One prompt turn must have exactly one profile authority. The legacy
/// synthesized profile is compatibility-only and cannot be layered beside an
/// authoritative ledger, including an authoritative empty ledger.
struct ChatPromptKnowledgeSelection: Equatable, Sendable {
let authoritativeLedger: KnowledgeLedgerPromptProjection?
var shouldLoadLegacyAIProfile: Bool { authoritativeLedger == nil }
func legacyAIProfileSection(profileText: String) -> String {
guard shouldLoadLegacyAIProfile else { return "" }
let trimmed = profileText.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return "" }
return "\n<ai_user_profile>\n\(profileText)\n</ai_user_profile>"
}
}