@soulcraft/brainy 2.10.0 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +10 -10
  2. package/dist/augmentations/apiServerAugmentation.js +2 -2
  3. package/dist/augmentations/display/fieldPatterns.d.ts +1 -1
  4. package/dist/augmentations/display/fieldPatterns.js +1 -1
  5. package/dist/augmentations/display/intelligentComputation.d.ts +2 -2
  6. package/dist/augmentations/display/intelligentComputation.js +4 -4
  7. package/dist/augmentations/display/types.d.ts +1 -1
  8. package/dist/augmentations/neuralImport.js +4 -4
  9. package/dist/augmentations/synapseAugmentation.js +3 -3
  10. package/dist/augmentations/typeMatching/brainyTypes.d.ts +83 -0
  11. package/dist/augmentations/typeMatching/brainyTypes.js +425 -0
  12. package/dist/augmentations/universalDisplayAugmentation.d.ts +1 -1
  13. package/dist/augmentations/universalDisplayAugmentation.js +1 -1
  14. package/dist/brainyData.d.ts +15 -33
  15. package/dist/brainyData.js +1210 -1203
  16. package/dist/chat/BrainyChat.js +11 -11
  17. package/dist/examples/basicUsage.js +4 -1
  18. package/dist/importManager.js +2 -2
  19. package/dist/index.d.ts +3 -1
  20. package/dist/index.js +5 -1
  21. package/dist/neural/embeddedPatterns.d.ts +1 -1
  22. package/dist/neural/embeddedPatterns.js +2 -2
  23. package/dist/storage/adapters/fileSystemStorage.d.ts +2 -2
  24. package/dist/storage/adapters/fileSystemStorage.js +2 -2
  25. package/dist/storage/adapters/memoryStorage.d.ts +4 -4
  26. package/dist/storage/adapters/memoryStorage.js +4 -4
  27. package/dist/storage/adapters/opfsStorage.d.ts +2 -2
  28. package/dist/storage/adapters/opfsStorage.js +2 -2
  29. package/dist/storage/adapters/s3CompatibleStorage.d.ts +2 -2
  30. package/dist/storage/adapters/s3CompatibleStorage.js +2 -2
  31. package/dist/storage/baseStorage.d.ts +12 -2
  32. package/dist/storage/baseStorage.js +32 -0
  33. package/dist/types/brainyDataInterface.d.ts +2 -5
  34. package/dist/utils/brainyTypes.d.ts +217 -0
  35. package/dist/utils/brainyTypes.js +261 -0
  36. package/dist/utils/typeValidation.d.ts +25 -0
  37. package/dist/utils/typeValidation.js +127 -0
  38. package/package.json +1 -1
@@ -0,0 +1,261 @@
1
+ /**
2
+ * BrainyTypes - Complete type management for Brainy
3
+ *
4
+ * Provides type lists, validation, and intelligent suggestions
5
+ * for nouns and verbs using semantic embeddings.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { BrainyTypes } from '@soulcraft/brainy'
10
+ *
11
+ * // Get all available types
12
+ * const nounTypes = BrainyTypes.nouns // ['Person', 'Organization', ...]
13
+ * const verbTypes = BrainyTypes.verbs // ['Contains', 'Creates', ...]
14
+ *
15
+ * // Validate types
16
+ * BrainyTypes.isValidNoun('Person') // true
17
+ * BrainyTypes.isValidVerb('Unknown') // false
18
+ *
19
+ * // Get intelligent suggestions
20
+ * const personData = {
21
+ * name: 'John Doe',
22
+ * email: 'john@example.com'
23
+ * }
24
+ * const suggestion = await BrainyTypes.suggestNoun(personData)
25
+ * console.log(suggestion.type) // 'Person'
26
+ * console.log(suggestion.confidence) // 0.92
27
+ * ```
28
+ */
29
+ import { NounType, VerbType } from '../types/graphTypes.js';
30
+ import { BrainyTypes as InternalBrainyTypes } from '../augmentations/typeMatching/brainyTypes.js';
31
+ /**
32
+ * BrainyTypes - Complete type management for Brainy
33
+ *
34
+ * Static class providing type lists, validation, and intelligent suggestions.
35
+ * No instantiation needed - all methods are static.
36
+ */
37
+ export class BrainyTypes {
38
+ /**
39
+ * Get or create the internal matcher instance
40
+ */
41
+ static async getInternalMatcher() {
42
+ if (!this.instance) {
43
+ this.instance = new InternalBrainyTypes();
44
+ await this.instance.init();
45
+ this.initialized = true;
46
+ }
47
+ return this.instance;
48
+ }
49
+ /**
50
+ * Check if a string is a valid noun type
51
+ *
52
+ * @param type The type string to check
53
+ * @returns True if valid noun type
54
+ *
55
+ * @example
56
+ * ```typescript
57
+ * BrainyTypes.isValidNoun('Person') // true
58
+ * BrainyTypes.isValidNoun('Unknown') // false
59
+ * BrainyTypes.isValidNoun('Contains') // false (it's a verb)
60
+ * ```
61
+ */
62
+ static isValidNoun(type) {
63
+ return this.nouns.includes(type);
64
+ }
65
+ /**
66
+ * Check if a string is a valid verb type
67
+ *
68
+ * @param type The type string to check
69
+ * @returns True if valid verb type
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * BrainyTypes.isValidVerb('Contains') // true
74
+ * BrainyTypes.isValidVerb('Unknown') // false
75
+ * BrainyTypes.isValidVerb('Person') // false (it's a noun)
76
+ * ```
77
+ */
78
+ static isValidVerb(type) {
79
+ return this.verbs.includes(type);
80
+ }
81
+ /**
82
+ * Suggest the most appropriate noun type for an object
83
+ *
84
+ * @param data The object or data to analyze
85
+ * @returns Promise resolving to type suggestion with confidence score
86
+ *
87
+ * @example
88
+ * ```typescript
89
+ * const data = {
90
+ * title: 'Quarterly Report',
91
+ * author: 'Jane Smith',
92
+ * pages: 42
93
+ * }
94
+ * const suggestion = await BrainyTypes.suggestNoun(data)
95
+ * console.log(suggestion.type) // 'Document'
96
+ * console.log(suggestion.confidence) // 0.88
97
+ *
98
+ * // Check alternatives if confidence is low
99
+ * if (suggestion.confidence < 0.8) {
100
+ * console.log('Also consider:', suggestion.alternatives)
101
+ * }
102
+ * ```
103
+ */
104
+ static async suggestNoun(data) {
105
+ const matcher = await this.getInternalMatcher();
106
+ const result = await matcher.matchNounType(data);
107
+ return {
108
+ type: result.type,
109
+ confidence: result.confidence,
110
+ reason: result.reasoning,
111
+ alternatives: result.alternatives?.map(alt => ({
112
+ type: alt.type,
113
+ confidence: alt.confidence
114
+ }))
115
+ };
116
+ }
117
+ /**
118
+ * Suggest the most appropriate verb type for a relationship
119
+ *
120
+ * @param source The source entity
121
+ * @param target The target entity
122
+ * @param hint Optional hint about the relationship
123
+ * @returns Promise resolving to type suggestion with confidence score
124
+ *
125
+ * @example
126
+ * ```typescript
127
+ * const source = { type: 'Person', name: 'Alice' }
128
+ * const target = { type: 'Document', title: 'Research Paper' }
129
+ *
130
+ * const suggestion = await BrainyTypes.suggestVerb(source, target, 'authored')
131
+ * console.log(suggestion.type) // 'CreatedBy'
132
+ * console.log(suggestion.confidence) // 0.91
133
+ *
134
+ * // Without hint
135
+ * const suggestion2 = await BrainyTypes.suggestVerb(source, target)
136
+ * console.log(suggestion2.type) // 'RelatedTo' (more generic)
137
+ * ```
138
+ */
139
+ static async suggestVerb(source, target, hint) {
140
+ const matcher = await this.getInternalMatcher();
141
+ const result = await matcher.matchVerbType(source, target, hint);
142
+ return {
143
+ type: result.type,
144
+ confidence: result.confidence,
145
+ reason: result.reasoning,
146
+ alternatives: result.alternatives?.map(alt => ({
147
+ type: alt.type,
148
+ confidence: alt.confidence
149
+ }))
150
+ };
151
+ }
152
+ /**
153
+ * Get a noun type by name (with validation)
154
+ *
155
+ * @param name The noun type name
156
+ * @returns The NounType enum value
157
+ * @throws Error if invalid noun type
158
+ *
159
+ * @example
160
+ * ```typescript
161
+ * const type = BrainyTypes.getNoun('Person') // NounType.Person
162
+ * const bad = BrainyTypes.getNoun('Unknown') // throws Error
163
+ * ```
164
+ */
165
+ static getNoun(name) {
166
+ if (!this.isValidNoun(name)) {
167
+ throw new Error(`Invalid noun type: '${name}'. Valid types are: ${this.nouns.join(', ')}`);
168
+ }
169
+ return name;
170
+ }
171
+ /**
172
+ * Get a verb type by name (with validation)
173
+ *
174
+ * @param name The verb type name
175
+ * @returns The VerbType enum value
176
+ * @throws Error if invalid verb type
177
+ *
178
+ * @example
179
+ * ```typescript
180
+ * const type = BrainyTypes.getVerb('Contains') // VerbType.Contains
181
+ * const bad = BrainyTypes.getVerb('Unknown') // throws Error
182
+ * ```
183
+ */
184
+ static getVerb(name) {
185
+ if (!this.isValidVerb(name)) {
186
+ throw new Error(`Invalid verb type: '${name}'. Valid types are: ${this.verbs.join(', ')}`);
187
+ }
188
+ return name;
189
+ }
190
+ /**
191
+ * Clear the internal cache
192
+ * Useful when processing many different types of data
193
+ */
194
+ static clearCache() {
195
+ this.instance?.clearCache();
196
+ }
197
+ /**
198
+ * Dispose of resources
199
+ * Call when completely done using BrainyTypes
200
+ */
201
+ static async dispose() {
202
+ if (this.instance) {
203
+ await this.instance.dispose();
204
+ this.instance = null;
205
+ this.initialized = false;
206
+ }
207
+ }
208
+ /**
209
+ * Get noun types as a plain object (for iteration)
210
+ * @returns Object with noun type names as keys
211
+ */
212
+ static getNounMap() {
213
+ const map = {};
214
+ for (const noun of this.nouns) {
215
+ map[noun] = noun;
216
+ }
217
+ return map;
218
+ }
219
+ /**
220
+ * Get verb types as a plain object (for iteration)
221
+ * @returns Object with verb type names as keys
222
+ */
223
+ static getVerbMap() {
224
+ const map = {};
225
+ for (const verb of this.verbs) {
226
+ map[verb] = verb;
227
+ }
228
+ return map;
229
+ }
230
+ }
231
+ BrainyTypes.instance = null;
232
+ BrainyTypes.initialized = false;
233
+ /**
234
+ * All available noun types
235
+ * @example
236
+ * ```typescript
237
+ * BrainyTypes.nouns.forEach(type => console.log(type))
238
+ * // 'Person', 'Organization', 'Location', ...
239
+ * ```
240
+ */
241
+ BrainyTypes.nouns = Object.freeze(Object.values(NounType));
242
+ /**
243
+ * All available verb types
244
+ * @example
245
+ * ```typescript
246
+ * BrainyTypes.verbs.forEach(type => console.log(type))
247
+ * // 'Contains', 'Creates', 'RelatedTo', ...
248
+ * ```
249
+ */
250
+ BrainyTypes.verbs = Object.freeze(Object.values(VerbType));
251
+ // Re-export the enums for convenience
252
+ export { NounType, VerbType };
253
+ export async function suggestType(kind, ...args) {
254
+ if (kind === 'noun') {
255
+ return BrainyTypes.suggestNoun(args[0]);
256
+ }
257
+ else {
258
+ return BrainyTypes.suggestVerb(args[0], args[1], args[2]);
259
+ }
260
+ }
261
+ //# sourceMappingURL=brainyTypes.js.map
@@ -0,0 +1,25 @@
1
+ import { NounType, VerbType } from '../types/graphTypes.js';
2
+ export declare function isValidNounType(type: unknown): type is NounType;
3
+ export declare function isValidVerbType(type: unknown): type is VerbType;
4
+ export declare function validateNounType(type: unknown): NounType;
5
+ export declare function validateVerbType(type: unknown): VerbType;
6
+ export interface ValidatedGraphNoun {
7
+ noun: NounType;
8
+ [key: string]: any;
9
+ }
10
+ export interface ValidatedGraphVerb {
11
+ verb: VerbType;
12
+ [key: string]: any;
13
+ }
14
+ export declare function validateGraphNoun(noun: unknown): ValidatedGraphNoun;
15
+ export declare function validateGraphVerb(verb: unknown): ValidatedGraphVerb;
16
+ export declare function validateNounTypes(types: unknown[]): NounType[];
17
+ export declare function validateVerbTypes(types: unknown[]): VerbType[];
18
+ export interface ValidationStats {
19
+ validated: number;
20
+ failed: number;
21
+ inferred: number;
22
+ suggestions: number;
23
+ }
24
+ export declare function getValidationStats(): ValidationStats;
25
+ export declare function resetValidationStats(): void;
@@ -0,0 +1,127 @@
1
+ import { NounType, VerbType } from '../types/graphTypes.js';
2
+ // Type sets for O(1) validation
3
+ const VALID_NOUN_TYPES = new Set(Object.values(NounType));
4
+ const VALID_VERB_TYPES = new Set(Object.values(VerbType));
5
+ // Type guards
6
+ export function isValidNounType(type) {
7
+ return typeof type === 'string' && VALID_NOUN_TYPES.has(type);
8
+ }
9
+ export function isValidVerbType(type) {
10
+ return typeof type === 'string' && VALID_VERB_TYPES.has(type);
11
+ }
12
+ // Validators with helpful errors
13
+ export function validateNounType(type) {
14
+ if (!isValidNounType(type)) {
15
+ const suggestion = findClosestMatch(String(type), VALID_NOUN_TYPES);
16
+ throw new Error(`Invalid noun type: '${type}'. ${suggestion ? `Did you mean '${suggestion}'?` : ''} ` +
17
+ `Valid types are: ${[...VALID_NOUN_TYPES].sort().join(', ')}`);
18
+ }
19
+ return type;
20
+ }
21
+ export function validateVerbType(type) {
22
+ if (!isValidVerbType(type)) {
23
+ const suggestion = findClosestMatch(String(type), VALID_VERB_TYPES);
24
+ throw new Error(`Invalid verb type: '${type}'. ${suggestion ? `Did you mean '${suggestion}'?` : ''} ` +
25
+ `Valid types are: ${[...VALID_VERB_TYPES].sort().join(', ')}`);
26
+ }
27
+ return type;
28
+ }
29
+ export function validateGraphNoun(noun) {
30
+ if (!noun || typeof noun !== 'object') {
31
+ throw new Error('Invalid noun: must be an object');
32
+ }
33
+ const n = noun;
34
+ if (!n.noun) {
35
+ throw new Error('Invalid noun: missing required "noun" type field');
36
+ }
37
+ n.noun = validateNounType(n.noun);
38
+ return n;
39
+ }
40
+ export function validateGraphVerb(verb) {
41
+ if (!verb || typeof verb !== 'object') {
42
+ throw new Error('Invalid verb: must be an object');
43
+ }
44
+ const v = verb;
45
+ if (!v.verb) {
46
+ throw new Error('Invalid verb: missing required "verb" type field');
47
+ }
48
+ v.verb = validateVerbType(v.verb);
49
+ return v;
50
+ }
51
+ // Helper for suggestions using Levenshtein distance
52
+ function findClosestMatch(input, validSet) {
53
+ if (!input)
54
+ return null;
55
+ const lower = input.toLowerCase();
56
+ let bestMatch = null;
57
+ let bestScore = Infinity;
58
+ for (const valid of validSet) {
59
+ const validLower = valid.toLowerCase();
60
+ // Exact match (case-insensitive)
61
+ if (validLower === lower) {
62
+ return valid;
63
+ }
64
+ // Substring match
65
+ if (validLower.includes(lower) || lower.includes(validLower)) {
66
+ return valid;
67
+ }
68
+ // Calculate Levenshtein distance
69
+ const distance = levenshteinDistance(lower, validLower);
70
+ if (distance < bestScore && distance <= 3) { // Threshold of 3 for suggestions
71
+ bestScore = distance;
72
+ bestMatch = valid;
73
+ }
74
+ }
75
+ return bestMatch;
76
+ }
77
+ // Levenshtein distance implementation
78
+ function levenshteinDistance(str1, str2) {
79
+ const m = str1.length;
80
+ const n = str2.length;
81
+ const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
82
+ for (let i = 0; i <= m; i++) {
83
+ dp[i][0] = i;
84
+ }
85
+ for (let j = 0; j <= n; j++) {
86
+ dp[0][j] = j;
87
+ }
88
+ for (let i = 1; i <= m; i++) {
89
+ for (let j = 1; j <= n; j++) {
90
+ if (str1[i - 1] === str2[j - 1]) {
91
+ dp[i][j] = dp[i - 1][j - 1];
92
+ }
93
+ else {
94
+ dp[i][j] = 1 + Math.min(dp[i - 1][j], // deletion
95
+ dp[i][j - 1], // insertion
96
+ dp[i - 1][j - 1] // substitution
97
+ );
98
+ }
99
+ }
100
+ }
101
+ return dp[m][n];
102
+ }
103
+ // Batch validation helpers
104
+ export function validateNounTypes(types) {
105
+ return types.map(validateNounType);
106
+ }
107
+ export function validateVerbTypes(types) {
108
+ return types.map(validateVerbType);
109
+ }
110
+ let stats = {
111
+ validated: 0,
112
+ failed: 0,
113
+ inferred: 0,
114
+ suggestions: 0
115
+ };
116
+ export function getValidationStats() {
117
+ return { ...stats };
118
+ }
119
+ export function resetValidationStats() {
120
+ stats = {
121
+ validated: 0,
122
+ failed: 0,
123
+ inferred: 0,
124
+ suggestions: 0
125
+ };
126
+ }
127
+ //# sourceMappingURL=typeValidation.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soulcraft/brainy",
3
- "version": "2.10.0",
3
+ "version": "2.11.0",
4
4
  "description": "Universal Knowledge Protocol™ - World's first Triple Intelligence database unifying vector, graph, and document search in one API. 31 nouns × 40 verbs for infinite expressiveness.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",