Repository navigation
Expand file tree
/
Copy paththeoremKnowledgeMetadata.ts
More file actions
160 lines (155 loc) · 5.8 KB
/
Copy paththeoremKnowledgeMetadata.ts
File metadata and controls
160 lines (155 loc) · 5.8 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
import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo';
import { readKnowledgeSource, type TheoremKnowledgeBase } from './theoremKnowledge';
import { knowledgeSearchGroup, knowledgeVersionSummary } from './theoremKnowledgeSearch';
import { largestFittingPage, splitsSurrogate } from './textPage';
const fieldNames = [
'name',
'file',
'type',
'premises',
'environmentDigest',
'description',
'dependencies',
'provenance',
'relatedVersions',
'files',
'elaboration',
'applicationHints',
'libraryMetadata',
] as const;
export type KnowledgeMetadataField = (typeof fieldNames)[number];
export type KnowledgeMetadataOptions = { field?: KnowledgeMetadataField; startOffset?: number; maxBytes?: number };
type FieldDescriptor = {
format: 'text' | 'json';
sha256: string;
bytes: number;
count?: number;
complete: boolean;
value?: unknown;
read?: { field: KnowledgeMetadataField; startOffset: number };
};
const invalidOptions = (): never => {
throw new Error('math_knowledge_metadata_options_invalid');
};
const validInteger = (value: unknown, minimum: number, maximum: number) =>
typeof value === 'number' && Number.isSafeInteger(value) && value >= minimum && value <= maximum;
/** Keep archived proof bodies out of metadata; every deferred field has an exact continuation. */
export function getKnowledgeMetadata(base: TheoremKnowledgeBase, id: string, options: KnowledgeMetadataOptions = {}) {
if (!options || typeof options !== 'object' || Array.isArray(options)) invalidOptions();
const { field: selected, startOffset, maxBytes = 16000 } = options;
if (
(selected !== undefined && !fieldNames.includes(selected)) ||
(startOffset !== undefined && !validInteger(startOffset, 0, Number.MAX_SAFE_INTEGER)) ||
(selected === undefined && startOffset !== undefined) ||
!validInteger(maxBytes, 1024, 65536)
)
invalidOptions();
const { entry, files } = readKnowledgeSource(base, id);
const prepare = (name: KnowledgeMetadataField) => {
let value: unknown;
if (name === 'relatedVersions') {
const group = knowledgeSearchGroup(entry);
value = base.entries
.filter(other => knowledgeSearchGroup(other) === group)
.map(other => knowledgeVersionSummary(other))
.sort((left, right) => left.id.localeCompare(right.id));
} else if (name === 'files')
value = Object.keys(files)
.sort()
.map(file => ({ file, sha256: files[file]! }));
else
value =
name === 'environmentDigest'
? (entry.environmentDigest ?? null)
: name === 'elaboration'
? (entry.elaboration ?? null)
: name === 'applicationHints'
? (entry.applicationHints ?? [])
: name === 'libraryMetadata'
? (entry.libraryMetadata ?? null)
: entry[name];
const format = typeof value === 'string' ? ('text' as const) : ('json' as const);
const text = format === 'text' ? (value as string) : canonicalMathJson(value);
return {
value,
format,
text,
sha256: mathDigest(text),
bytes: Buffer.byteLength(text),
...(Array.isArray(value) ? { count: value.length } : {}),
};
};
const identity = {
schema: 'theorem-os.theorem-knowledge-metadata.v1' as const,
id: entry.id,
contextDigest: entry.contextDigest,
sourceSha256: files[entry.file]!,
typeKind: entry.typeKind,
kind: entry.kind,
evidence: base.evidence,
requiresFreshCheck: true as const,
contextCoverage: 'metadata-only-not-complete-lean-context' as const,
};
const fits = (packet: unknown) => Buffer.byteLength(JSON.stringify(packet)) + 1 <= maxBytes;
if (selected !== undefined) {
const current = prepare(selected),
begin = startOffset ?? 0;
if (begin > current.text.length || splitsSurrogate(current.text, begin))
throw new Error('math_knowledge_metadata_position_invalid');
const packet = (end: number) => ({
...identity,
mode: 'field' as const,
field: selected,
format: current.format,
sha256: current.sha256,
bytes: current.bytes,
offsetEncoding: 'utf16-code-unit' as const,
endOffsetExclusive: true as const,
display: { startOffset: begin, endOffset: end, bytes: Buffer.byteLength(current.text.slice(begin, end)) },
text: current.text.slice(begin, end),
truncated: end < current.text.length,
...(end < current.text.length ? { nextOffset: end } : {}),
});
return largestFittingPage(
current.text,
begin,
current.text.length,
maxBytes,
packet,
'math_knowledge_metadata_budget_too_small',
);
}
const visibleFields = fieldNames.filter(name => name !== 'libraryMetadata' || entry.libraryMetadata);
const prepared = visibleFields.map(name => ({ name, ...prepare(name) }));
const fields = Object.fromEntries(
prepared.map(({ name, format, sha256, bytes, count }) => {
return [
name,
{
format,
sha256,
bytes,
...(count === undefined ? {} : { count }),
complete: false,
read: { field: name, startOffset: 0 },
} satisfies FieldDescriptor,
];
}),
) as Record<KnowledgeMetadataField, FieldDescriptor>;
const packet = {
...identity,
mode: 'summary' as const,
allFieldsComplete: false,
fields,
proofSource: { readWith: 'knowledge source', fileField: 'file', nameField: 'name' },
};
if (!fits(packet)) throw new Error('math_knowledge_metadata_budget_too_small');
for (const { name, value } of prepared) {
const deferred = fields[name],
{ read: _read, ...details } = deferred;
fields[name] = { ...details, complete: true, value };
if (!fits(packet)) fields[name] = deferred;
}
packet.allFieldsComplete = visibleFields.every(name => fields[name].complete);
return packet;
}