context-pilot-engine 0.2.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 (49) hide show
  1. package/dist/embedder/embedder.d.ts +4 -0
  2. package/dist/embedder/embedder.d.ts.map +1 -0
  3. package/dist/embedder/embedder.js +37 -0
  4. package/dist/engine.d.ts +89 -0
  5. package/dist/engine.d.ts.map +1 -0
  6. package/dist/engine.js +314 -0
  7. package/dist/engine.test.d.ts +2 -0
  8. package/dist/engine.test.d.ts.map +1 -0
  9. package/dist/engine.test.js +9 -0
  10. package/dist/graph/graph.d.ts +46 -0
  11. package/dist/graph/graph.d.ts.map +1 -0
  12. package/dist/graph/graph.js +110 -0
  13. package/dist/index.d.ts +4 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +3 -0
  16. package/dist/indexer/chunker.d.ts +12 -0
  17. package/dist/indexer/chunker.d.ts.map +1 -0
  18. package/dist/indexer/chunker.js +89 -0
  19. package/dist/indexer/indexer.d.ts +17 -0
  20. package/dist/indexer/indexer.d.ts.map +1 -0
  21. package/dist/indexer/indexer.js +247 -0
  22. package/dist/indexer/languages.d.ts +6 -0
  23. package/dist/indexer/languages.d.ts.map +1 -0
  24. package/dist/indexer/languages.js +47 -0
  25. package/dist/search/search.d.ts +12 -0
  26. package/dist/search/search.d.ts.map +1 -0
  27. package/dist/search/search.js +38 -0
  28. package/dist/storage/schema.d.ts +3 -0
  29. package/dist/storage/schema.d.ts.map +1 -0
  30. package/dist/storage/schema.js +91 -0
  31. package/dist/storage/sqlite.d.ts +63 -0
  32. package/dist/storage/sqlite.d.ts.map +1 -0
  33. package/dist/storage/sqlite.js +255 -0
  34. package/dist/types.d.ts +162 -0
  35. package/dist/types.d.ts.map +1 -0
  36. package/dist/types.js +2 -0
  37. package/package.json +31 -0
  38. package/src/embedder/embedder.ts +46 -0
  39. package/src/engine.ts +425 -0
  40. package/src/graph/graph.ts +136 -0
  41. package/src/index.ts +15 -0
  42. package/src/indexer/chunker.ts +115 -0
  43. package/src/indexer/indexer.ts +297 -0
  44. package/src/indexer/languages.ts +55 -0
  45. package/src/search/search.ts +48 -0
  46. package/src/storage/schema.ts +92 -0
  47. package/src/storage/sqlite.ts +353 -0
  48. package/src/types.ts +137 -0
  49. package/tsconfig.json +19 -0
@@ -0,0 +1,255 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ import { mkdirSync } from "fs";
3
+ import { dirname } from "path";
4
+ import { applySchema } from "./schema.js";
5
+ export function openDatabase(dbPath) {
6
+ mkdirSync(dirname(dbPath), { recursive: true });
7
+ const db = new DatabaseSync(dbPath);
8
+ db.exec("PRAGMA journal_mode = WAL");
9
+ db.exec("PRAGMA foreign_keys = ON");
10
+ applySchema(db);
11
+ return db;
12
+ }
13
+ // ── Vector serialization ──────────────────────────────────────────────────────
14
+ // Bit-compatible with Python's struct.pack(f"{n}f", *vector) — little-endian f32
15
+ export function vectorToBlob(vector) {
16
+ return Buffer.from(vector.buffer, vector.byteOffset, vector.byteLength);
17
+ }
18
+ export function blobToVector(blob) {
19
+ const buf = Buffer.isBuffer(blob) ? blob : Buffer.from(blob);
20
+ const copy = Buffer.allocUnsafe(buf.length);
21
+ buf.copy(copy);
22
+ return new Float32Array(copy.buffer);
23
+ }
24
+ function tx(db, fn) {
25
+ db.exec("BEGIN");
26
+ try {
27
+ fn();
28
+ db.exec("COMMIT");
29
+ }
30
+ catch (err) {
31
+ db.exec("ROLLBACK");
32
+ throw err;
33
+ }
34
+ }
35
+ // ── Project ───────────────────────────────────────────────────────────────────
36
+ export function upsertProject(db, projectId, rootPath) {
37
+ db.prepare(`
38
+ INSERT INTO projects (id, name, root_path, created_at)
39
+ VALUES (?, ?, ?, ?)
40
+ ON CONFLICT(id) DO UPDATE SET root_path = excluded.root_path
41
+ `).run(projectId, rootPath, rootPath, Date.now());
42
+ }
43
+ export function markProjectIndexed(db, projectId) {
44
+ db.prepare(`UPDATE projects SET indexed_at = ? WHERE id = ?`).run(Date.now(), projectId);
45
+ }
46
+ export function getProject(db, projectId) {
47
+ return db
48
+ .prepare(`SELECT root_path, indexed_at FROM projects WHERE id = ?`)
49
+ .get(projectId);
50
+ }
51
+ // ── Files ─────────────────────────────────────────────────────────────────────
52
+ export function upsertFile(db, fileId, projectId, relPath, language, hash, lastModified) {
53
+ db.prepare(`
54
+ INSERT INTO files (id, project_id, path, language, hash, last_modified)
55
+ VALUES (?, ?, ?, ?, ?, ?)
56
+ ON CONFLICT(project_id, path) DO UPDATE SET
57
+ id = excluded.id,
58
+ language = excluded.language,
59
+ hash = excluded.hash,
60
+ last_modified = excluded.last_modified
61
+ `).run(fileId, projectId, relPath, language, hash, lastModified);
62
+ }
63
+ export function getFileHash(db, projectId, relPath) {
64
+ const row = db
65
+ .prepare(`SELECT hash FROM files WHERE project_id = ? AND path = ?`)
66
+ .get(projectId, relPath);
67
+ return row?.hash;
68
+ }
69
+ export function deleteFileChunks(db, fileId) {
70
+ db.prepare(`DELETE FROM chunks WHERE file_id = ?`).run(fileId);
71
+ }
72
+ export function getProjectFiles(db, projectId) {
73
+ return db
74
+ .prepare(`SELECT id, path FROM files WHERE project_id = ?`)
75
+ .all(projectId);
76
+ }
77
+ // ── Chunks ────────────────────────────────────────────────────────────────────
78
+ export function insertChunks(db, chunks) {
79
+ const stmt = db.prepare(`
80
+ INSERT OR REPLACE INTO chunks
81
+ (id, file_id, chunk_type, name, content, start_line, end_line, token_count)
82
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
83
+ `);
84
+ tx(db, () => {
85
+ for (const c of chunks) {
86
+ stmt.run(c.id, c.fileId, c.chunkType, c.name ?? null, c.content, c.startLine, c.endLine, c.tokenCount);
87
+ }
88
+ });
89
+ }
90
+ // ── Embeddings ────────────────────────────────────────────────────────────────
91
+ export function upsertEmbeddings(db, entries) {
92
+ const stmt = db.prepare(`
93
+ INSERT OR REPLACE INTO embeddings (chunk_id, model, vector, dims, created_at)
94
+ VALUES (?, ?, ?, ?, ?)
95
+ `);
96
+ tx(db, () => {
97
+ for (const item of entries) {
98
+ stmt.run(item.chunkId, item.model, vectorToBlob(item.vector), item.vector.length, Date.now());
99
+ }
100
+ });
101
+ }
102
+ export function getAllEmbeddings(db, projectId) {
103
+ const rows = db.prepare(`
104
+ SELECT
105
+ e.chunk_id,
106
+ e.vector,
107
+ c.content,
108
+ c.chunk_type,
109
+ c.name,
110
+ c.start_line,
111
+ c.end_line,
112
+ f.path,
113
+ f.last_modified
114
+ FROM embeddings e
115
+ JOIN chunks c ON c.id = e.chunk_id
116
+ JOIN files f ON f.id = c.file_id
117
+ WHERE f.project_id = ?
118
+ `).all(projectId);
119
+ return rows.map((r) => ({
120
+ chunkId: r.chunk_id,
121
+ vector: blobToVector(r.vector),
122
+ content: r.content,
123
+ chunkType: r.chunk_type,
124
+ name: r.name,
125
+ startLine: r.start_line,
126
+ endLine: r.end_line,
127
+ path: r.path,
128
+ lastModified: r.last_modified ?? undefined,
129
+ }));
130
+ }
131
+ export function getProjectStats(db, projectId) {
132
+ const files = db
133
+ .prepare(`SELECT COUNT(*) as n FROM files WHERE project_id = ?`)
134
+ .get(projectId).n;
135
+ const chunks = db
136
+ .prepare(`
137
+ SELECT COUNT(*) as n FROM chunks c
138
+ JOIN files f ON f.id = c.file_id
139
+ WHERE f.project_id = ?
140
+ `)
141
+ .get(projectId).n;
142
+ return { files, chunks };
143
+ }
144
+ // ── Graph edges ───────────────────────────────────────────────────────────────
145
+ export function insertGraphEdges(db, projectId, edges) {
146
+ const stmt = db.prepare(`
147
+ INSERT OR REPLACE INTO graph_edges (id, project_id, from_chunk, to_chunk, edge_type, weight)
148
+ VALUES (?, ?, ?, ?, ?, ?)
149
+ `);
150
+ tx(db, () => {
151
+ for (const e of edges) {
152
+ stmt.run(`${e.from}:${e.to}:${e.edgeType}`, projectId, e.from, e.to, e.edgeType, e.weight);
153
+ }
154
+ });
155
+ }
156
+ export function getProjectGraphEdges(db, projectId) {
157
+ return db
158
+ .prepare(`SELECT from_chunk, to_chunk, edge_type, weight FROM graph_edges WHERE project_id = ?`)
159
+ .all(projectId);
160
+ }
161
+ export function getFileRepresentativeChunk(db, fileId) {
162
+ const row = db
163
+ .prepare(`SELECT id FROM chunks WHERE file_id = ? ORDER BY start_line LIMIT 1`)
164
+ .get(fileId);
165
+ return row?.id;
166
+ }
167
+ export function deleteProjectGraphEdges(db, projectId) {
168
+ db.prepare(`DELETE FROM graph_edges WHERE project_id = ?`).run(projectId);
169
+ }
170
+ export function upsertMemoryEmbedding(db, memoryId, vector, model) {
171
+ db.prepare(`
172
+ INSERT OR REPLACE INTO memory_embeddings (memory_id, model, vector, dims, created_at)
173
+ VALUES (?, ?, ?, ?, ?)
174
+ `).run(memoryId, model, vectorToBlob(vector), vector.length, Date.now());
175
+ }
176
+ export function getMemoryEmbeddings(db, projectId) {
177
+ const rows = db.prepare(`
178
+ SELECT me.memory_id, me.vector, m.memory_type, m.content, m.created_at
179
+ FROM memory_embeddings me
180
+ JOIN memories m ON m.id = me.memory_id
181
+ WHERE m.project_id = ?
182
+ ORDER BY m.created_at DESC
183
+ `).all(projectId);
184
+ return rows.map((r) => ({
185
+ memoryId: r.memory_id,
186
+ vector: blobToVector(r.vector),
187
+ memoryType: r.memory_type,
188
+ content: r.content,
189
+ createdAt: r.created_at,
190
+ }));
191
+ }
192
+ // ── Co-edit tracking ──────────────────────────────────────────────────────────
193
+ /**
194
+ * Record that a set of files were edited in the same session window.
195
+ * Increments the co-edit count for every pair in the set.
196
+ */
197
+ export function recordCoEdits(db, projectId, relPaths) {
198
+ if (relPaths.length < 2)
199
+ return;
200
+ const stmt = db.prepare(`
201
+ INSERT INTO file_coedits (id, project_id, file_a, file_b, count, last_seen)
202
+ VALUES (?, ?, ?, ?, 1, ?)
203
+ ON CONFLICT(project_id, file_a, file_b) DO UPDATE SET
204
+ count = count + 1,
205
+ last_seen = excluded.last_seen
206
+ `);
207
+ const now = Date.now();
208
+ tx(db, () => {
209
+ for (let i = 0; i < relPaths.length; i++) {
210
+ for (let j = i + 1; j < relPaths.length; j++) {
211
+ // Store canonically sorted to avoid (A,B) and (B,A) duplicates
212
+ const [a, b] = [relPaths[i], relPaths[j]].sort();
213
+ stmt.run(`${projectId}:${a}:${b}`, projectId, a, b, now);
214
+ }
215
+ }
216
+ });
217
+ }
218
+ /**
219
+ * For a given active file, return normalized co-edit scores [0,1] for candidate paths.
220
+ * Score of 1 = always edited together with activeFilePath; 0 = never.
221
+ */
222
+ export function getCoEditScores(db, projectId, activeFilePath, candidatePaths) {
223
+ if (candidatePaths.length === 0)
224
+ return {};
225
+ const rows = db.prepare(`
226
+ SELECT
227
+ CASE WHEN file_a = ? THEN file_b ELSE file_a END AS other_file,
228
+ count
229
+ FROM file_coedits
230
+ WHERE project_id = ? AND (file_a = ? OR file_b = ?)
231
+ `).all(activeFilePath, projectId, activeFilePath, activeFilePath);
232
+ if (rows.length === 0)
233
+ return {};
234
+ const maxCount = Math.max(...rows.map((r) => r.count));
235
+ const scoreMap = new Map(rows.map((r) => [r.other_file, r.count / maxCount]));
236
+ const result = {};
237
+ for (const path of candidatePaths) {
238
+ result[path] = scoreMap.get(path) ?? 0;
239
+ }
240
+ return result;
241
+ }
242
+ export function getChunksByIds(db, ids) {
243
+ if (ids.length === 0)
244
+ return [];
245
+ const placeholders = ids.map(() => "?").join(",");
246
+ return db
247
+ .prepare(`
248
+ SELECT c.id, c.chunk_type, c.name, f.path
249
+ FROM chunks c
250
+ JOIN files f ON f.id = c.file_id
251
+ WHERE c.id IN (${placeholders})
252
+ `)
253
+ .all(...ids);
254
+ }
255
+ //# sourceMappingURL=sqlite.js.map
@@ -0,0 +1,162 @@
1
+ export interface Chunk {
2
+ id: string;
3
+ fileId: string;
4
+ chunkType: "function" | "class" | "module";
5
+ name: string | null;
6
+ content: string;
7
+ startLine: number;
8
+ endLine: number;
9
+ tokenCount: number;
10
+ metadata?: Record<string, unknown>;
11
+ }
12
+ export interface EmbeddingCandidate {
13
+ chunkId: string;
14
+ vector: Float32Array;
15
+ content: string;
16
+ chunkType: string;
17
+ name: string | null;
18
+ path: string;
19
+ startLine: number;
20
+ endLine: number;
21
+ lastModified?: number;
22
+ }
23
+ export interface SearchResult {
24
+ chunk_id: string;
25
+ score: number;
26
+ content: string;
27
+ chunk_type: string;
28
+ name: string | null;
29
+ path: string;
30
+ start_line: number;
31
+ end_line: number;
32
+ last_modified?: number;
33
+ }
34
+ export interface MemorySearchResult {
35
+ id: string;
36
+ memory_type: string;
37
+ content: string;
38
+ score: number;
39
+ created_at: number;
40
+ }
41
+ export interface MemoryRecord {
42
+ id: string;
43
+ memory_type: string;
44
+ content: string;
45
+ session_id: string | null;
46
+ relevance_score: number;
47
+ created_at: number;
48
+ }
49
+ export interface GraphNode {
50
+ id: string;
51
+ chunkType: string;
52
+ name: string | null;
53
+ path: string;
54
+ }
55
+ export interface GraphEdge {
56
+ from: string;
57
+ to: string;
58
+ edgeType: "calls" | "extends" | "imports";
59
+ weight: number;
60
+ }
61
+ export interface SubgraphResult {
62
+ nodes: GraphNode[];
63
+ edges: GraphEdge[];
64
+ error?: string;
65
+ }
66
+ export interface IndexResult {
67
+ success: boolean;
68
+ projectId: string;
69
+ projectPath: string;
70
+ filesIndexed: number;
71
+ filesSkipped: number;
72
+ totalFiles: number;
73
+ error?: string;
74
+ }
75
+ export interface StatusResult {
76
+ indexed: boolean;
77
+ projectId?: string;
78
+ projectPath: string;
79
+ files?: number;
80
+ chunks?: number;
81
+ indexedAt?: number;
82
+ }
83
+ export interface IContextEngine {
84
+ init(): Promise<void>;
85
+ index(params: {
86
+ projectPath: string;
87
+ force?: boolean;
88
+ paths?: string[];
89
+ }): Promise<IndexResult>;
90
+ search(params: {
91
+ query: string;
92
+ projectPath: string;
93
+ k?: number;
94
+ filterType?: string;
95
+ }): Promise<{
96
+ results: SearchResult[];
97
+ }>;
98
+ status(params: {
99
+ projectPath: string;
100
+ }): Promise<StatusResult>;
101
+ graph(params: {
102
+ target: string;
103
+ projectPath: string;
104
+ depth?: number;
105
+ direction?: string;
106
+ }): Promise<SubgraphResult>;
107
+ graphDistances(params: {
108
+ projectPath: string;
109
+ activeChunkId: string;
110
+ candidateIds: string[];
111
+ }): Promise<{
112
+ distances: Record<string, number>;
113
+ }>;
114
+ remember(params: {
115
+ projectPath: string;
116
+ sessionId: string;
117
+ memoryType: "decision" | "pattern" | "todo" | "context_note";
118
+ content: string;
119
+ }): Promise<{
120
+ id: string;
121
+ success: boolean;
122
+ }>;
123
+ searchMemories(params: {
124
+ query: string;
125
+ projectPath: string;
126
+ k?: number;
127
+ }): Promise<{
128
+ results: MemorySearchResult[];
129
+ }>;
130
+ getCoEditScores(params: {
131
+ projectPath: string;
132
+ activeFilePath: string;
133
+ candidatePaths: string[];
134
+ }): Record<string, number>;
135
+ getFileGraph(params: {
136
+ projectPath: string;
137
+ }): Promise<{
138
+ nodes: Array<{
139
+ id: string;
140
+ path: string;
141
+ language: string;
142
+ chunkCount: number;
143
+ }>;
144
+ edges: Array<{
145
+ from: string;
146
+ to: string;
147
+ }>;
148
+ }>;
149
+ listMemories(params: {
150
+ projectPath: string;
151
+ }): Promise<{
152
+ memories: MemoryRecord[];
153
+ }>;
154
+ deleteMemory(params: {
155
+ projectPath: string;
156
+ memoryId: string;
157
+ }): Promise<{
158
+ success: boolean;
159
+ }>;
160
+ close(): void;
161
+ }
162
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,KAAK;IACpB,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,UAAU,GAAG,OAAO,GAAG,QAAQ,CAAC;IAC3C,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM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EAAE,MAAM,EAAE,CAAC;KAC1B,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC3B,YAAY,CAAC,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC;QACrD,KAAK,EAAE,KAAK,CAAC;YAAE,EAAE,EAAE,MAAM,CAAC;YAAC,IAAI,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,MAAM,CAAC;YAAC,UAAU,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;QACjF,KAAK,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,EAAE,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;KAC5C,CAAC,CAAC;IACH,YAAY,CAAC,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC;QAAE,QAAQ,EAAE,YAAY,EAAE,CAAA;KAAE,CAAC,CAAC;IACrF,YAAY,CAAC,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;IAC/F,KAAK,IAAI,IAAI,CAAC;CACf"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "context-pilot-engine",
3
+ "version": "0.2.0",
4
+ "description": "Context-pilot embedding engine — TypeScript-native, no Python required",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": "./dist/index.js",
10
+ "./types": "./dist/types.js"
11
+ },
12
+ "scripts": {
13
+ "build": "tsc",
14
+ "dev": "tsc --watch",
15
+ "test": "echo 'No tests yet for engine package'"
16
+ },
17
+ "dependencies": {
18
+ "@huggingface/transformers": "^3.0.0",
19
+ "tree-sitter-javascript": "^0.23.0",
20
+ "tree-sitter-python": "^0.23.0",
21
+ "tree-sitter-typescript": "^0.23.0",
22
+ "uuid": "^10.0.0",
23
+ "web-tree-sitter": "^0.24.0"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "^22.0.0",
27
+ "@types/uuid": "^10.0.0",
28
+ "typescript": "^5.5.0",
29
+ "vitest": "^2.0.0"
30
+ }
31
+ }
@@ -0,0 +1,46 @@
1
+ import { pipeline, env } from "@huggingface/transformers";
2
+ import { join } from "path";
3
+ import { homedir } from "os";
4
+
5
+ const MODEL_NAME = "Xenova/all-MiniLM-L6-v2";
6
+
7
+ type FeatureExtractionPipeline = Awaited<ReturnType<typeof pipeline>>;
8
+ let embedder: FeatureExtractionPipeline | null = null;
9
+
10
+ export async function initEmbedder(): Promise<void> {
11
+ if (embedder) return;
12
+
13
+ // Cache models in ~/.context-pilot/models
14
+ env.cacheDir = join(homedir(), ".context-pilot", "models");
15
+
16
+ // Disable remote model fetching in offline mode if needed
17
+ // env.allowRemoteModels = false;
18
+
19
+ embedder = await pipeline("feature-extraction", MODEL_NAME, {
20
+ dtype: "fp32",
21
+ });
22
+ }
23
+
24
+ export async function embedTexts(texts: string[]): Promise<Float32Array[]> {
25
+ if (!embedder) await initEmbedder();
26
+
27
+ const BATCH_SIZE = 64;
28
+ const results: Float32Array[] = [];
29
+
30
+ for (let i = 0; i < texts.length; i += BATCH_SIZE) {
31
+ const batch = texts.slice(i, i + BATCH_SIZE);
32
+ const output = await (embedder as Function)(batch, { pooling: "mean", normalize: true });
33
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
34
+ const list: number[][] = (output as any).tolist();
35
+ for (const vec of list) {
36
+ results.push(new Float32Array(vec));
37
+ }
38
+ }
39
+
40
+ return results;
41
+ }
42
+
43
+ export async function embedSingle(text: string): Promise<Float32Array> {
44
+ const [vec] = await embedTexts([text]);
45
+ return vec;
46
+ }