-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmetadata.ts
More file actions
327 lines (269 loc) · 9.55 KB
/
metadata.ts
File metadata and controls
327 lines (269 loc) · 9.55 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
import semver from "semver";
import type {
CorpusMetadata,
EmbeddingMetadata,
FileMeta,
TaxonomyField,
TaxonomyValueProperties,
ToolDescriptions,
} from "./types.js";
/**
* Returns taxonomy keys that have `vector_collapse: true`, i.e. dimensions
* whose values should be collapsed at search time.
*/
export function getCollapseKeys(taxonomy: Record<string, TaxonomyField>): string[] {
return Object.entries(taxonomy)
.filter(([, field]) => field.vector_collapse === true)
.map(([key]) => key);
}
const LIMITS = {
maxKeys: 64,
maxKeyLength: 64,
maxValuesPerKey: 512,
maxValueLength: 128,
} as const;
export interface NormalizeMetadataOptions {
supportedMajor?: number;
}
export function normalizeMetadata(
input: unknown,
options: NormalizeMetadataOptions = {},
): CorpusMetadata {
if (!input || typeof input !== "object") {
throw new Error("metadata must be an object");
}
const metadata = input as Record<string, unknown>;
const supportedMajor = options.supportedMajor ?? 1;
const metadataVersion = asNonEmptyString(metadata.metadata_version, "metadata_version");
if (!semver.valid(metadataVersion)) {
throw new Error("metadata_version must be valid semver");
}
const parsed = semver.parse(metadataVersion);
if (!parsed || parsed.major !== supportedMajor) {
throw new Error(
`Unsupported metadata_version major: expected ${supportedMajor}.x.x, got ${metadataVersion}`,
);
}
const corpusDescription = asNonEmptyString(metadata.corpus_description, "corpus_description");
const taxonomy = normalizeTaxonomy(metadata.taxonomy);
const stats = normalizeStats(metadata.stats);
const embedding = normalizeEmbedding(metadata.embedding);
const toolDescriptions = normalizeToolDescriptions(metadata.tool_descriptions);
const mcpServerInstructions = normalizeInstructions(metadata.mcpServerInstructions);
const files = normalizeFiles(metadata.files);
return {
metadata_version: metadataVersion,
corpus_description: corpusDescription,
taxonomy,
stats,
embedding,
files,
...(toolDescriptions ? { tool_descriptions: toolDescriptions } : {}),
...(mcpServerInstructions ? { mcpServerInstructions } : {}),
};
}
function normalizeTaxonomy(value: unknown): Record<string, TaxonomyField> {
if (!value || typeof value !== "object") {
throw new Error("taxonomy must be an object");
}
const raw = value as Record<string, unknown>;
const entries = Object.entries(raw);
if (entries.length > LIMITS.maxKeys) {
throw new Error(`taxonomy has too many keys (max ${LIMITS.maxKeys})`);
}
const normalized: Record<string, TaxonomyField> = {};
for (const [rawKey, rawField] of entries) {
const key = rawKey.trim();
if (!key) {
throw new Error("taxonomy keys cannot be empty");
}
if (key.length > LIMITS.maxKeyLength) {
throw new Error(`taxonomy key '${key}' exceeds max length ${LIMITS.maxKeyLength}`);
}
if (!rawField || typeof rawField !== "object") {
throw new Error(`taxonomy field '${key}' must be an object`);
}
const field = rawField as Record<string, unknown>;
const values = normalizeValues(field.values, key);
const description =
field.description === undefined ? undefined : asTrimmedString(field.description);
const vectorCollapse = field.vector_collapse === true ? true : undefined;
const properties = normalizeProperties(field.properties, key);
normalized[key] = {
...(description ? { description } : {}),
values,
...(vectorCollapse ? { vector_collapse: true } : {}),
...(properties ? { properties } : {}),
};
}
return normalized;
}
function normalizeValues(value: unknown, key: string): string[] {
if (!Array.isArray(value)) {
throw new Error(`taxonomy['${key}'].values must be an array`);
}
if (value.length > LIMITS.maxValuesPerKey) {
throw new Error(`taxonomy['${key}'].values exceeds max length ${LIMITS.maxValuesPerKey}`);
}
const deduped = new Set<string>();
for (const raw of value) {
const normalized = asTrimmedString(raw);
if (!normalized) {
throw new Error(`taxonomy['${key}'].values cannot include empty strings`);
}
if (normalized.length > LIMITS.maxValueLength) {
throw new Error(
`taxonomy['${key}'].value '${normalized}' exceeds max length ${LIMITS.maxValueLength}`,
);
}
deduped.add(normalized);
}
return [...deduped].sort((a, b) => a.localeCompare(b));
}
function normalizeProperties(
value: unknown,
taxonomyKey: string,
): Record<string, TaxonomyValueProperties> | undefined {
if (value === undefined || value === null) {
return undefined;
}
if (typeof value !== "object" || Array.isArray(value)) {
throw new Error(`taxonomy['${taxonomyKey}'].properties must be an object`);
}
const raw = value as Record<string, unknown>;
const result: Record<string, TaxonomyValueProperties> = {};
let hasAny = false;
for (const [valKey, valProps] of Object.entries(raw)) {
if (!valProps || typeof valProps !== "object") {
throw new Error(`taxonomy['${taxonomyKey}'].properties['${valKey}'] must be an object`);
}
const props = valProps as Record<string, unknown>;
if (props.mcp_resource === true) {
result[valKey] = { mcp_resource: true };
hasAny = true;
}
}
return hasAny ? result : undefined;
}
function normalizeStats(value: unknown): CorpusMetadata["stats"] {
if (!value || typeof value !== "object") {
throw new Error("stats must be an object");
}
const stats = value as Record<string, unknown>;
const totalChunks = asPositiveInteger(stats.total_chunks, "stats.total_chunks", true);
const totalFiles = asPositiveInteger(stats.total_files, "stats.total_files", true);
const indexedAt = asNonEmptyString(stats.indexed_at, "stats.indexed_at");
const sourceCommitRaw = stats.source_commit;
let sourceCommit: string | null | undefined;
if (sourceCommitRaw === undefined) {
sourceCommit = undefined;
} else if (sourceCommitRaw === null) {
sourceCommit = null;
} else {
sourceCommit = asTrimmedString(sourceCommitRaw);
if (!/^[a-f0-9]{40}$/.test(sourceCommit)) {
throw new Error("stats.source_commit must be a 40-char lowercase SHA-1");
}
}
const result: CorpusMetadata["stats"] = {
total_chunks: totalChunks,
total_files: totalFiles,
indexed_at: indexedAt,
};
if (sourceCommit !== undefined) {
result.source_commit = sourceCommit;
}
return result;
}
function normalizeEmbedding(value: unknown): EmbeddingMetadata | null {
if (value === null || value === undefined) {
return null;
}
if (typeof value !== "object") {
throw new Error("embedding must be null or an object");
}
const embedding = value as Record<string, unknown>;
const provider = asNonEmptyString(embedding.provider, "embedding.provider");
const model = asNonEmptyString(embedding.model, "embedding.model");
const dimensions = asPositiveInteger(embedding.dimensions, "embedding.dimensions", false);
return { provider, model, dimensions };
}
function normalizeToolDescriptions(value: unknown): ToolDescriptions | undefined {
if (value === null || value === undefined) {
return undefined;
}
if (typeof value !== "object") {
throw new Error("tool_descriptions must be an object");
}
const raw = value as Record<string, unknown>;
const result: ToolDescriptions = {};
let hasAny = false;
if (raw.search_docs !== undefined) {
result.search_docs = asNonEmptyString(raw.search_docs, "tool_descriptions.search_docs");
hasAny = true;
}
if (raw.get_doc !== undefined) {
result.get_doc = asNonEmptyString(raw.get_doc, "tool_descriptions.get_doc");
hasAny = true;
}
return hasAny ? result : undefined;
}
function normalizeInstructions(value: unknown): string | undefined {
if (value === null || value === undefined) {
return undefined;
}
return asNonEmptyString(value, "mcpServerInstructions");
}
function normalizeFiles(value: unknown): Record<string, FileMeta> {
if (value === null || value === undefined) {
return {};
}
if (typeof value !== "object" || Array.isArray(value)) {
throw new Error("files must be an object");
}
const raw = value as Record<string, unknown>;
const result: Record<string, FileMeta> = {};
let hasAny = false;
for (const [filepath, entry] of Object.entries(raw)) {
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
throw new Error(`files['${filepath}'] must be an object`);
}
const meta = entry as Record<string, unknown>;
const fileMeta: FileMeta = {};
if (meta.title !== undefined) {
if (typeof meta.title !== "string") {
throw new Error(`files['${filepath}'].title must be a string`);
}
const trimmed = meta.title.trim();
if (trimmed) {
fileMeta.title = trimmed;
}
}
result[filepath] = fileMeta;
hasAny = true;
}
return result;
}
function asTrimmedString(value: unknown): string {
if (typeof value !== "string") {
throw new Error("expected string");
}
return value.trim();
}
function asNonEmptyString(value: unknown, fieldName: string): string {
const normalized = asTrimmedString(value);
if (!normalized) {
throw new Error(`${fieldName} must be a non-empty string`);
}
return normalized;
}
function asPositiveInteger(value: unknown, fieldName: string, allowZero: boolean): number {
if (!Number.isInteger(value)) {
throw new Error(`${fieldName} must be an integer`);
}
const min = allowZero ? 0 : 1;
if ((value as number) < min) {
throw new Error(`${fieldName} must be >= ${min}`);
}
return value as number;
}