@principal-ai/subsystems-studio 0.20.6 → 0.20.7

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.
@@ -18,13 +18,15 @@ var __toESM = (mod, isNodeMode, target) => {
18
18
  return cached;
19
19
  }
20
20
  target = mod != null ? __create(__getProtoOf(mod)) : {};
21
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
- for (let key of __getOwnPropNames(mod))
23
- if (!__hasOwnProp.call(to, key))
24
- __defProp(to, key, {
25
- get: __accessProp.bind(mod, key),
26
- enumerable: true
27
- });
21
+ const to = isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ if (mod && typeof mod === "object" || typeof mod === "function") {
23
+ for (let key of __getOwnPropNames(mod))
24
+ if (!__hasOwnProp.call(to, key))
25
+ __defProp(to, key, {
26
+ get: __accessProp.bind(mod, key),
27
+ enumerable: true
28
+ });
29
+ }
28
30
  if (canCache)
29
31
  cache.set(mod, to);
30
32
  return to;
@@ -33,7 +35,7 @@ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports,
33
35
  var __require = import.meta.require;
34
36
 
35
37
  // node_modules/@principal-ai/agent-monitoring/dist/index.cjs
36
- var require_dist = __commonJS((exports) => {
38
+ var require_dist = __commonJS(function(exports) {
37
39
  var __filename = "/Users/griever/Developer/principal-ai/subsystem-modeling/packages/subsystems-studio/node_modules/@principal-ai/agent-monitoring/dist/index.cjs";
38
40
  var fs = __require("fs");
39
41
  var os = __require("os");
@@ -4946,7 +4948,7 @@ var require_dist = __commonJS((exports) => {
4946
4948
  });
4947
4949
 
4948
4950
  // node_modules/@principal-ai/subsystems-core/dist/opencode/node-path-adapter.js
4949
- var require_node_path_adapter = __commonJS((exports) => {
4951
+ var require_node_path_adapter = __commonJS(function(exports) {
4950
4952
  var __importDefault = exports && exports.__importDefault || function(mod) {
4951
4953
  return mod && mod.__esModule ? mod : { default: mod };
4952
4954
  };
@@ -5006,16 +5008,16 @@ var require_node_path_adapter = __commonJS((exports) => {
5006
5008
  const target = (0, node_path_1.resolve)(absolutePath);
5007
5009
  let bestMatch = null;
5008
5010
  let bestLen = 0;
5009
- for (const [root, info2] of this.knownRoots) {
5011
+ for (const [root, info] of this.knownRoots) {
5010
5012
  const rootCanon = (0, node_path_1.resolve)(root);
5011
5013
  if ((target === rootCanon || target.startsWith(`${rootCanon}/`)) && rootCanon.length > bestLen) {
5012
- bestMatch = info2;
5014
+ bestMatch = info;
5013
5015
  bestLen = rootCanon.length;
5014
5016
  }
5015
5017
  }
5016
5018
  if (bestMatch) {
5017
- const canonicalRoot2 = await this.canonicalizeCase(bestMatch.root);
5018
- return { ...bestMatch, root: canonicalRoot2 };
5019
+ const canonicalRoot = await this.canonicalizeCase(bestMatch.root);
5020
+ return { ...bestMatch, root: canonicalRoot };
5019
5021
  }
5020
5022
  const gitRoot = await this.findGitRoot(target);
5021
5023
  if (!gitRoot)
@@ -5096,7 +5098,7 @@ var require_node_path_adapter = __commonJS((exports) => {
5096
5098
  });
5097
5099
 
5098
5100
  // node_modules/@principal-ai/subsystems-core/dist/opencode/pipeline.js
5099
- var require_pipeline = __commonJS((exports) => {
5101
+ var require_pipeline = __commonJS(function(exports) {
5100
5102
  Object.defineProperty(exports, "__esModule", { value: true });
5101
5103
  exports.collectRepositories = exports.accumulateEvents = exports.normalizeEventsWithAdapter = exports.normalizeEvents = exports.opencodeRowsToUniversalEvents = exports.NodePathNormalizationAdapter = undefined;
5102
5104
  var agent_monitoring_1 = require_dist();
@@ -8128,1580 +8130,162 @@ function createLocalRepoPurl(path) {
8128
8130
  name: encodedPath
8129
8131
  });
8130
8132
  }
8131
- // node_modules/@principal-ai/alexandria-core-library/dist/test-adapters/InMemoryFileSystemAdapter.js
8132
- class InMemoryFileSystemAdapter {
8133
- files = new Map;
8134
- binaryFiles = new Map;
8135
- exists(path) {
8136
- return this.files.has(path) || this.binaryFiles.has(path) || this.isDirectory(path);
8133
+ // node_modules/@principal-ai/alexandria-core-library/dist/projects-core/ProjectRegistryStore.js
8134
+ class ProjectRegistryStore {
8135
+ fs;
8136
+ registryPath;
8137
+ constructor(fileSystemAdapter, homeDir) {
8138
+ this.fs = fileSystemAdapter;
8139
+ this.registryPath = this.fs.join(homeDir, ".alexandria", "projects.json");
8137
8140
  }
8138
- readFile(path) {
8139
- if (!this.files.has(path)) {
8140
- throw new Error(`File not found: ${path}`);
8141
+ ensureRegistryDir() {
8142
+ const registryDir = this.fs.dirname(this.registryPath);
8143
+ if (!this.fs.exists(registryDir)) {
8144
+ this.fs.createDir(registryDir);
8141
8145
  }
8142
- return this.files.get(path);
8143
8146
  }
8144
- writeFile(path, content) {
8145
- const dir = this.dirname(path);
8146
- if (dir && dir !== "/" && dir !== path) {
8147
- this.createDir(dir);
8147
+ loadRegistry() {
8148
+ this.ensureRegistryDir();
8149
+ if (!this.fs.exists(this.registryPath)) {
8150
+ return {
8151
+ version: "1.0.0",
8152
+ projects: []
8153
+ };
8148
8154
  }
8149
- this.files.set(path, content);
8150
- }
8151
- deleteFile(path) {
8152
- this.files.delete(path);
8153
- this.binaryFiles.delete(path);
8154
- }
8155
- readBinaryFile(path) {
8156
- if (!this.binaryFiles.has(path)) {
8157
- throw new Error(`Binary file not found: ${path}`);
8155
+ try {
8156
+ const content = this.fs.readFile(this.registryPath);
8157
+ return JSON.parse(content);
8158
+ } catch {
8159
+ return {
8160
+ version: "1.0.0",
8161
+ projects: []
8162
+ };
8158
8163
  }
8159
- return this.binaryFiles.get(path);
8160
8164
  }
8161
- writeBinaryFile(path, content) {
8162
- const dir = this.dirname(path);
8163
- if (dir && dir !== "/" && dir !== path) {
8164
- this.createDir(dir);
8165
- }
8166
- this.binaryFiles.set(path, content);
8165
+ saveRegistry(registry) {
8166
+ this.ensureRegistryDir();
8167
+ this.fs.writeFile(this.registryPath, JSON.stringify(registry, null, 2));
8167
8168
  }
8168
- createDir(path) {
8169
- if (!path || path === "/")
8170
- return;
8171
- this.files.set(path + "/.dir", "");
8169
+ extractGitHubId(remoteUrl) {
8170
+ const match = remoteUrl.match(/github\.com[:/]([^/]+)\/([^/.]+)(\.git)?$/);
8171
+ if (!match)
8172
+ return null;
8173
+ return `${match[1]}/${match[2]}`;
8172
8174
  }
8173
- readDir(path) {
8174
- if ((this.files.has(path) || this.binaryFiles.has(path)) && !path.endsWith("/.dir")) {
8175
- throw new Error(`ENOTDIR: not a directory, scandir '${path}'`);
8176
- }
8177
- if (!this.isDirectory(path)) {
8178
- throw new Error(`ENOENT: no such file or directory, scandir '${path}'`);
8179
- }
8180
- const normalizedPath = path.endsWith("/") ? path.slice(0, -1) : path;
8181
- const prefix = normalizedPath === "/" ? "" : `${normalizedPath}/`;
8182
- const items = new Set;
8183
- for (const filePath of this.files.keys()) {
8184
- if (filePath.startsWith(prefix)) {
8185
- const relativePath = filePath.slice(prefix.length);
8186
- if (relativePath) {
8187
- if (relativePath === ".dir") {
8188
- continue;
8189
- }
8190
- if (relativePath.endsWith("/.dir")) {
8191
- const dirName = relativePath.slice(0, -5).split("/")[0];
8192
- if (dirName) {
8193
- items.add(dirName);
8194
- }
8195
- } else {
8196
- const firstSegment = relativePath.split("/")[0];
8197
- if (firstSegment && firstSegment !== ".dir") {
8198
- items.add(firstSegment);
8199
- }
8200
- }
8201
- }
8202
- }
8203
- }
8204
- for (const filePath of this.binaryFiles.keys()) {
8205
- if (filePath.startsWith(prefix)) {
8206
- const relativePath = filePath.slice(prefix.length);
8207
- if (relativePath) {
8208
- const parts = relativePath.split("/");
8209
- if (parts[0]) {
8210
- items.add(parts[0]);
8211
- }
8212
- }
8213
- }
8175
+ deriveDisplayName(projectPath, remoteUrl) {
8176
+ if (remoteUrl) {
8177
+ const match = remoteUrl.match(/github\.com[:/][^/]+\/([^/.]+)(\.git)?$/);
8178
+ if (match)
8179
+ return match[1];
8214
8180
  }
8215
- return Array.from(items);
8181
+ return projectPath.split("/").pop() || "unknown";
8216
8182
  }
8217
- deleteDir(path) {
8218
- const prefix = `${path}/`;
8219
- for (const filePath of this.files.keys()) {
8220
- if (filePath.startsWith(prefix) || filePath === path + "/.dir") {
8221
- this.files.delete(filePath);
8222
- }
8223
- }
8224
- for (const filePath of this.binaryFiles.keys()) {
8225
- if (filePath.startsWith(prefix)) {
8226
- this.binaryFiles.delete(filePath);
8227
- }
8183
+ derivePurl(projectPath, remoteUrl) {
8184
+ if (remoteUrl) {
8185
+ const fromRemote = extractPurlFromRemoteUrl(remoteUrl);
8186
+ if (fromRemote)
8187
+ return fromRemote;
8228
8188
  }
8189
+ return createLocalRepoPurl(projectPath);
8229
8190
  }
8230
- join(...paths) {
8231
- return paths.join("/").replace(/\/+/g, "/").replace(/\/$/, "") || "/";
8232
- }
8233
- dirname(path) {
8234
- const lastSlash = path.lastIndexOf("/");
8235
- return lastSlash <= 0 ? "/" : path.slice(0, lastSlash);
8191
+ registerProject(projectPath, remoteUrl) {
8192
+ const registry = this.loadRegistry();
8193
+ const existing = registry.projects.find((p) => p.path.toLowerCase() === projectPath.toLowerCase());
8194
+ if (existing)
8195
+ return existing;
8196
+ const entry = {
8197
+ name: this.deriveDisplayName(projectPath, remoteUrl),
8198
+ path: projectPath,
8199
+ remoteUrl,
8200
+ purl: this.derivePurl(projectPath, remoteUrl),
8201
+ registeredAt: new Date().toISOString(),
8202
+ github: undefined,
8203
+ hasViews: false,
8204
+ viewCount: 0,
8205
+ views: []
8206
+ };
8207
+ registry.projects.push(entry);
8208
+ this.saveRegistry(registry);
8209
+ return entry;
8236
8210
  }
8237
- basename(filePath, ext) {
8238
- const lastSlash = filePath.lastIndexOf("/");
8239
- let name = lastSlash === -1 ? filePath : filePath.slice(lastSlash + 1);
8240
- if (ext && name.endsWith(ext)) {
8241
- name = name.slice(0, -ext.length);
8242
- }
8243
- return name;
8211
+ findClonesByGitHubId(githubId) {
8212
+ const registry = this.loadRegistry();
8213
+ return registry.projects.filter((p) => p.github?.id === githubId);
8244
8214
  }
8245
- extname(filePath) {
8246
- const name = this.basename(filePath);
8247
- const lastDot = name.lastIndexOf(".");
8248
- if (lastDot <= 0)
8249
- return "";
8250
- return name.slice(lastDot);
8215
+ findClonesByPurl(purl) {
8216
+ const registry = this.loadRegistry();
8217
+ return registry.projects.filter((p) => p.purl === purl);
8251
8218
  }
8252
- isAbsolute(path) {
8253
- return path.startsWith("/");
8219
+ listProjects() {
8220
+ const registry = this.loadRegistry();
8221
+ return registry.projects;
8254
8222
  }
8255
- relative(from, to) {
8256
- if (to.startsWith(from)) {
8257
- return to.slice(from.length + 1);
8258
- }
8259
- return to;
8223
+ getByPath(path) {
8224
+ const registry = this.loadRegistry();
8225
+ return registry.projects.find((p) => p.path === path);
8260
8226
  }
8261
- isDirectory(path) {
8262
- if (this.files.has(path + "/.dir")) {
8227
+ removeByPath(path) {
8228
+ const registry = this.loadRegistry();
8229
+ const initialLength = registry.projects.length;
8230
+ registry.projects = registry.projects.filter((p) => p.path !== path);
8231
+ if (registry.projects.length < initialLength) {
8232
+ this.saveRegistry(registry);
8263
8233
  return true;
8264
8234
  }
8265
- const prefix = `${path}/`;
8266
- for (const filePath of this.files.keys()) {
8267
- if (filePath.startsWith(prefix)) {
8268
- return true;
8269
- }
8270
- }
8271
- for (const filePath of this.binaryFiles.keys()) {
8272
- if (filePath.startsWith(prefix)) {
8273
- return true;
8274
- }
8275
- }
8276
8235
  return false;
8277
8236
  }
8278
- normalizeRepositoryPath(inputPath) {
8279
- let current = inputPath;
8280
- while (current && current !== "/") {
8281
- if (this.exists(this.join(current, ".git"))) {
8282
- return current;
8283
- }
8284
- current = this.dirname(current);
8285
- }
8286
- throw new Error(`Not a git repository: ${inputPath}`);
8287
- }
8288
- findProjectRoot(inputPath) {
8289
- return this.normalizeRepositoryPath(inputPath);
8290
- }
8291
- getRepositoryName(repositoryPath) {
8292
- const segments = repositoryPath.split("/").filter((s) => s);
8293
- return segments[segments.length - 1] || "root";
8294
- }
8295
- clear() {
8296
- this.files.clear();
8297
- this.binaryFiles.clear();
8298
- }
8299
- getFiles() {
8300
- return new Map(this.files);
8301
- }
8302
- setupTestRepo(repoPath) {
8303
- this.createDir(repoPath);
8304
- this.createDir(this.join(repoPath, ".git"));
8305
- this.createDir(this.join(repoPath, ".alexandria"));
8306
- }
8307
- debug() {
8308
- console.log("InMemory FileSystem Contents:");
8309
- for (const [path, content] of this.files.entries()) {
8310
- if (!path.endsWith("/.dir")) {
8311
- console.log(` ${path}: ${content.length} bytes`);
8312
- }
8313
- }
8314
- }
8315
- }
8316
- // node_modules/@principal-ai/alexandria-core-library/dist/pure-core/stores/CodebaseViewsStore.js
8317
- class CodebaseViewsStore {
8318
- fs;
8319
- alexandriaPath;
8320
- viewsDir;
8321
- constructor(fileSystemAdapter, alexandriaPath) {
8322
- this.fs = fileSystemAdapter;
8323
- this.alexandriaPath = alexandriaPath;
8324
- this.viewsDir = this.fs.join(alexandriaPath, "views");
8325
- }
8326
- getViewsDirectory() {
8327
- return this.viewsDir;
8328
- }
8329
- ensureViewsDirectory() {
8330
- if (!this.fs.exists(this.viewsDir)) {
8331
- this.fs.createDir(this.viewsDir);
8332
- }
8333
- }
8334
- getViewFilePath(repositoryRootPath, viewId) {
8335
- return this.fs.join(this.getViewsDirectory(), `${viewId}.json`);
8336
- }
8337
- getNextDisplayOrder(repositoryRootPath, category) {
8338
- const views = this.listViews(repositoryRootPath);
8339
- const categoryViews = views.filter((v) => v.category === category);
8340
- if (categoryViews.length === 0) {
8341
- return 0;
8237
+ removeAllByPurl(purl) {
8238
+ const registry = this.loadRegistry();
8239
+ const initialLength = registry.projects.length;
8240
+ registry.projects = registry.projects.filter((p) => p.purl !== purl);
8241
+ const removed = initialLength - registry.projects.length;
8242
+ if (removed > 0) {
8243
+ this.saveRegistry(registry);
8342
8244
  }
8343
- const maxOrder = Math.max(...categoryViews.map((v) => v.displayOrder || 0));
8344
- return maxOrder + 1;
8245
+ return removed;
8345
8246
  }
8346
- saveView(repositoryRootPath, view) {
8347
- this.ensureViewsDirectory();
8348
- const filePath = this.getViewFilePath(repositoryRootPath, view.id);
8349
- let displayOrder = view.displayOrder;
8350
- if (displayOrder === undefined || displayOrder === null) {
8351
- displayOrder = this.getNextDisplayOrder(repositoryRootPath, view.category || "other");
8247
+ updateByPath(path, updates) {
8248
+ const registry = this.loadRegistry();
8249
+ const projectIndex = registry.projects.findIndex((p) => p.path === path);
8250
+ if (projectIndex === -1) {
8251
+ throw new Error(`No project registered at path '${path}'`);
8352
8252
  }
8353
- const viewToSave = {
8354
- ...view,
8355
- version: view.version || "1.0.0",
8356
- timestamp: view.timestamp || new Date().toISOString(),
8357
- displayOrder
8253
+ const project = registry.projects[projectIndex];
8254
+ registry.projects[projectIndex] = {
8255
+ ...project,
8256
+ ...updates,
8257
+ path: project.path,
8258
+ registeredAt: project.registeredAt
8358
8259
  };
8359
- this.fs.writeFile(filePath, JSON.stringify(viewToSave, null, 2));
8360
- }
8361
- getView(repositoryRootPath, viewId) {
8362
- const filePath = this.getViewFilePath(repositoryRootPath, viewId);
8363
- if (!this.fs.exists(filePath)) {
8364
- return null;
8365
- }
8366
- try {
8367
- const content = this.fs.readFile(filePath);
8368
- return JSON.parse(content);
8369
- } catch (error) {
8370
- console.error(`Error reading view ${viewId}:`, error);
8371
- return null;
8372
- }
8373
- }
8374
- async getViewAsync(repositoryRootPath, viewId) {
8375
- const filePath = this.getViewFilePath(repositoryRootPath, viewId);
8376
- if (!this.fs.exists(filePath)) {
8377
- return null;
8378
- }
8379
- try {
8380
- const content = this.fs.readFileAsync ? await this.fs.readFileAsync(filePath) : this.fs.readFile(filePath);
8381
- return JSON.parse(content);
8382
- } catch (error) {
8383
- console.error(`Error reading view ${viewId}:`, error);
8384
- return null;
8385
- }
8386
- }
8387
- listViews(repositoryRootPath) {
8388
- const viewsDir = this.getViewsDirectory();
8389
- if (!this.fs.exists(viewsDir)) {
8390
- return [];
8391
- }
8392
- const files = this.fs.readDir(viewsDir).filter((f) => f.endsWith(".json"));
8393
- const views = [];
8394
- for (const file of files) {
8395
- const viewId = file.replace(/\.json$/, "");
8396
- const view = this.getView(repositoryRootPath, viewId);
8397
- if (view) {
8398
- views.push(view);
8399
- }
8400
- }
8401
- return views.sort((a, b) => {
8402
- const catA = a.category || "other";
8403
- const catB = b.category || "other";
8404
- if (catA !== catB) {
8405
- return catA.localeCompare(catB);
8406
- }
8407
- const orderA = a.displayOrder ?? 999999;
8408
- const orderB = b.displayOrder ?? 999999;
8409
- if (orderA !== orderB) {
8410
- return orderA - orderB;
8411
- }
8412
- return a.name.localeCompare(b.name);
8413
- });
8260
+ this.saveRegistry(registry);
8414
8261
  }
8415
- async listViewsAsync(repositoryRootPath) {
8416
- const viewsDir = this.getViewsDirectory();
8417
- if (!this.fs.exists(viewsDir)) {
8418
- return [];
8419
- }
8420
- const files = this.fs.readDir(viewsDir).filter((f) => f.endsWith(".json"));
8421
- const views = [];
8422
- for (const file of files) {
8423
- const viewId = file.replace(/\.json$/, "");
8424
- const view = await this.getViewAsync(repositoryRootPath, viewId);
8425
- if (view) {
8426
- views.push(view);
8262
+ migrateToPurl() {
8263
+ const registry = this.loadRegistry();
8264
+ let migratedCount = 0;
8265
+ for (const project of registry.projects) {
8266
+ if (project.purl)
8267
+ continue;
8268
+ let purl;
8269
+ if (project.remoteUrl) {
8270
+ purl = extractPurlFromRemoteUrl(project.remoteUrl) || undefined;
8427
8271
  }
8428
- }
8429
- return views.sort((a, b) => {
8430
- const catA = a.category || "other";
8431
- const catB = b.category || "other";
8432
- if (catA !== catB) {
8433
- return catA.localeCompare(catB);
8272
+ if (!purl && project.github?.id) {
8273
+ try {
8274
+ purl = extractPurlFromRemoteUrl(`https://github.com/${project.github.id}.git`) || undefined;
8275
+ } catch {}
8434
8276
  }
8435
- const orderA = a.displayOrder ?? 999999;
8436
- const orderB = b.displayOrder ?? 999999;
8437
- if (orderA !== orderB) {
8438
- return orderA - orderB;
8277
+ if (!purl) {
8278
+ purl = createLocalRepoPurl(project.path);
8439
8279
  }
8440
- return a.name.localeCompare(b.name);
8441
- });
8442
- }
8443
- deleteView(repositoryRootPath, viewId) {
8444
- const filePath = this.getViewFilePath(repositoryRootPath, viewId);
8445
- if (this.fs.exists(filePath)) {
8446
- this.fs.deleteFile(filePath);
8447
- return true;
8448
- }
8449
- return false;
8450
- }
8451
- updateView(repositoryRootPath, viewId, updates) {
8452
- const existingView = this.getView(repositoryRootPath, viewId);
8453
- if (!existingView) {
8454
- return false;
8455
- }
8456
- let displayOrder = updates.displayOrder;
8457
- if (updates.category && updates.category !== existingView.category && displayOrder === undefined) {
8458
- displayOrder = this.getNextDisplayOrder(repositoryRootPath, updates.category);
8459
- }
8460
- const updatedView = {
8461
- ...existingView,
8462
- ...updates,
8463
- id: viewId,
8464
- timestamp: new Date().toISOString()
8465
- };
8466
- if (displayOrder !== undefined) {
8467
- updatedView.displayOrder = displayOrder;
8280
+ project.purl = purl;
8281
+ migratedCount++;
8468
8282
  }
8469
- this.saveView(repositoryRootPath, updatedView);
8470
- return true;
8471
- }
8472
- viewExists(repositoryRootPath, viewId) {
8473
- const filePath = this.getViewFilePath(repositoryRootPath, viewId);
8474
- return this.fs.exists(filePath);
8475
- }
8476
- getDefaultView(repositoryRootPath) {
8477
- return this.getView(repositoryRootPath, "default");
8478
- }
8479
- setDefaultView(repositoryRootPath, viewId) {
8480
- const view = this.getView(repositoryRootPath, viewId);
8481
- if (!view) {
8482
- return false;
8283
+ if (migratedCount > 0) {
8284
+ this.saveRegistry(registry);
8483
8285
  }
8484
- const defaultView = {
8485
- ...view,
8486
- id: "default",
8487
- name: view.name,
8488
- description: view.description || `Default view based on ${viewId}`
8489
- };
8490
- this.saveView(repositoryRootPath, defaultView);
8491
- return true;
8286
+ return migratedCount;
8492
8287
  }
8493
8288
  }
8494
-
8495
- // node_modules/@principal-ai/alexandria-core-library/dist/pure-core/utils/idGenerator.js
8496
- function generateId() {
8497
- const timestamp = Date.now();
8498
- const random = Math.random().toString(36).substr(2, 9);
8499
- return `${timestamp}-${random}`;
8500
- }
8501
-
8502
- // node_modules/@principal-ai/alexandria-core-library/dist/pure-core/stores/DrawingStore.js
8503
- class DrawingStore {
8504
- fs;
8505
- alexandriaPath;
8506
- drawingsDir;
8507
- constructor(fileSystemAdapter, alexandriaPath) {
8508
- this.fs = fileSystemAdapter;
8509
- this.alexandriaPath = alexandriaPath;
8510
- this.drawingsDir = this.fs.join(alexandriaPath, "drawings");
8511
- }
8512
- saveDrawing(name, content) {
8513
- this.ensureDrawingsDirectory();
8514
- const fileName = this.normalizeDrawingName(name);
8515
- const filePath = this.fs.join(this.drawingsDir, fileName);
8516
- this.fs.writeFile(filePath, content);
8517
- }
8518
- saveBinaryDrawing(name, content) {
8519
- this.ensureDrawingsDirectory();
8520
- const fileName = this.normalizeDrawingName(name);
8521
- const filePath = this.fs.join(this.drawingsDir, fileName);
8522
- this.fs.writeBinaryFile(filePath, content);
8523
- }
8524
- loadDrawing(name) {
8525
- const fileName = this.normalizeDrawingName(name);
8526
- const filePath = this.fs.join(this.drawingsDir, fileName);
8527
- if (!this.fs.exists(filePath)) {
8528
- return null;
8529
- }
8530
- try {
8531
- return this.fs.readFile(filePath);
8532
- } catch (error) {
8533
- console.error(`Error reading drawing ${name}:`, error);
8534
- return null;
8535
- }
8536
- }
8537
- loadBinaryDrawing(name) {
8538
- const fileName = this.normalizeDrawingName(name);
8539
- const filePath = this.fs.join(this.drawingsDir, fileName);
8540
- if (!this.fs.exists(filePath)) {
8541
- return null;
8542
- }
8543
- try {
8544
- return this.fs.readBinaryFile(filePath);
8545
- } catch (error) {
8546
- console.error(`Error reading binary drawing ${name}:`, error);
8547
- return null;
8548
- }
8549
- }
8550
- listDrawings() {
8551
- if (!this.fs.exists(this.drawingsDir)) {
8552
- return [];
8553
- }
8554
- const files = this.fs.readDir(this.drawingsDir);
8555
- return files.filter((f) => f.endsWith(".excalidraw") || f.endsWith(".svg") || f.endsWith(".png"));
8556
- }
8557
- listDrawingsWithMetadata() {
8558
- const drawings = this.listDrawings();
8559
- const metadata = [];
8560
- for (const fileName of drawings) {
8561
- const format = fileName.endsWith(".excalidraw") ? "excalidraw" : fileName.endsWith(".svg") ? "svg" : fileName.endsWith(".png") ? "png" : "excalidraw";
8562
- metadata.push({
8563
- id: fileName,
8564
- name: fileName,
8565
- fileName,
8566
- format,
8567
- created: new Date().toISOString(),
8568
- modified: new Date().toISOString(),
8569
- size: 0
8570
- });
8571
- }
8572
- return metadata;
8573
- }
8574
- deleteDrawing(name) {
8575
- const fileName = this.normalizeDrawingName(name);
8576
- const filePath = this.fs.join(this.drawingsDir, fileName);
8577
- if (this.fs.exists(filePath)) {
8578
- this.fs.deleteFile(filePath);
8579
- return true;
8580
- }
8581
- return false;
8582
- }
8583
- renameDrawing(oldName, newName) {
8584
- const oldFileName = this.normalizeDrawingName(oldName);
8585
- const newFileName = this.normalizeDrawingName(newName);
8586
- const oldPath = this.fs.join(this.drawingsDir, oldFileName);
8587
- const newPath = this.fs.join(this.drawingsDir, newFileName);
8588
- if (!this.fs.exists(oldPath)) {
8589
- return false;
8590
- }
8591
- if (this.fs.exists(newPath)) {
8592
- console.error(`Drawing ${newName} already exists`);
8593
- return false;
8594
- }
8595
- try {
8596
- const content = this.fs.readFile(oldPath);
8597
- this.fs.writeFile(newPath, content);
8598
- this.fs.deleteFile(oldPath);
8599
- return true;
8600
- } catch (error) {
8601
- console.error(`Error renaming drawing from ${oldName} to ${newName}:`, error);
8602
- return false;
8603
- }
8604
- }
8605
- drawingExists(name) {
8606
- const fileName = this.normalizeDrawingName(name);
8607
- const filePath = this.fs.join(this.drawingsDir, fileName);
8608
- return this.fs.exists(filePath);
8609
- }
8610
- ensureDrawingsDirectory() {
8611
- if (!this.fs.exists(this.drawingsDir)) {
8612
- this.fs.createDir(this.drawingsDir);
8613
- }
8614
- }
8615
- normalizeDrawingName(name) {
8616
- if (!name.includes(".")) {
8617
- return `${name}.excalidraw`;
8618
- }
8619
- return name;
8620
- }
8621
- saveExcalidrawDrawing(data) {
8622
- this.ensureDrawingsDirectory();
8623
- const drawingId = generateId();
8624
- const fileName = `${drawingId}.excalidraw`;
8625
- const filePath = this.fs.join(this.drawingsDir, fileName);
8626
- this.fs.writeFile(filePath, JSON.stringify(data, null, 2));
8627
- return drawingId;
8628
- }
8629
- loadExcalidrawDrawing(drawingId) {
8630
- const fileName = `${drawingId}.excalidraw`;
8631
- const filePath = this.fs.join(this.drawingsDir, fileName);
8632
- if (!this.fs.exists(filePath)) {
8633
- return null;
8634
- }
8635
- try {
8636
- const content = this.fs.readFile(filePath);
8637
- return JSON.parse(content);
8638
- } catch (error) {
8639
- console.error(`Error loading Excalidraw drawing ${drawingId}:`, error);
8640
- return null;
8641
- }
8642
- }
8643
- getDrawingMetadata(drawingId) {
8644
- const fileName = `${drawingId}.excalidraw`;
8645
- const filePath = this.fs.join(this.drawingsDir, fileName);
8646
- if (!this.fs.exists(filePath)) {
8647
- return null;
8648
- }
8649
- try {
8650
- const content = this.fs.readFile(filePath);
8651
- const data = JSON.parse(content);
8652
- const stats = {
8653
- created: new Date().toISOString(),
8654
- modified: new Date().toISOString(),
8655
- size: content.length
8656
- };
8657
- return {
8658
- id: drawingId,
8659
- name: data.appState?.name || drawingId,
8660
- fileName,
8661
- format: "excalidraw",
8662
- created: stats.created,
8663
- modified: stats.modified,
8664
- size: stats.size
8665
- };
8666
- } catch (error) {
8667
- console.error(`Error getting metadata for drawing ${drawingId}:`, error);
8668
- return null;
8669
- }
8670
- }
8671
- updateDrawingName(drawingId, newName) {
8672
- const fileName = `${drawingId}.excalidraw`;
8673
- const filePath = this.fs.join(this.drawingsDir, fileName);
8674
- if (!this.fs.exists(filePath)) {
8675
- return false;
8676
- }
8677
- try {
8678
- const content = this.fs.readFile(filePath);
8679
- const data = JSON.parse(content);
8680
- data.appState = data.appState || {};
8681
- data.appState.name = newName;
8682
- this.fs.writeFile(filePath, JSON.stringify(data, null, 2));
8683
- return true;
8684
- } catch (error) {
8685
- console.error(`Error updating drawing name for ${drawingId}:`, error);
8686
- return false;
8687
- }
8688
- }
8689
- updateExcalidrawDrawingContent(drawingId, updatedData) {
8690
- const fileName = `${drawingId}.excalidraw`;
8691
- const filePath = this.fs.join(this.drawingsDir, fileName);
8692
- if (!this.fs.exists(filePath)) {
8693
- return false;
8694
- }
8695
- try {
8696
- let existingData = null;
8697
- try {
8698
- const existingContent = this.fs.readFile(filePath);
8699
- existingData = JSON.parse(existingContent);
8700
- } catch {
8701
- existingData = null;
8702
- }
8703
- const mergedAppState = {
8704
- ...existingData?.appState ?? {},
8705
- ...updatedData.appState ?? {},
8706
- name: updatedData.appState?.name ?? existingData?.appState?.name ?? drawingId
8707
- };
8708
- const contentToSave = {
8709
- ...updatedData,
8710
- appState: mergedAppState
8711
- };
8712
- this.fs.writeFile(filePath, JSON.stringify(contentToSave, null, 2));
8713
- return true;
8714
- } catch (error) {
8715
- console.error(`Error updating drawing content for ${drawingId}:`, error);
8716
- return false;
8717
- }
8718
- }
8719
- listDrawingsWithExtractedNames() {
8720
- const drawings = [];
8721
- if (!this.fs.exists(this.drawingsDir)) {
8722
- return drawings;
8723
- }
8724
- const files = this.fs.readDir(this.drawingsDir);
8725
- for (const fileName of files) {
8726
- if (fileName.endsWith(".excalidraw")) {
8727
- const drawingId = fileName.replace(".excalidraw", "");
8728
- const metadata = this.getDrawingMetadata(drawingId);
8729
- if (metadata) {
8730
- drawings.push(metadata);
8731
- }
8732
- }
8733
- }
8734
- return drawings;
8735
- }
8736
- deleteDrawingById(drawingId) {
8737
- const fileName = `${drawingId}.excalidraw`;
8738
- const filePath = this.fs.join(this.drawingsDir, fileName);
8739
- if (this.fs.exists(filePath)) {
8740
- this.fs.deleteFile(filePath);
8741
- return true;
8742
- }
8743
- return false;
8744
- }
8745
- }
8746
-
8747
- // node_modules/@principal-ai/alexandria-core-library/dist/pure-core/validation/CodebaseViewValidator.js
8748
- class CodebaseViewValidator {
8749
- fs;
8750
- constructor(fileSystemAdapter) {
8751
- this.fs = fileSystemAdapter;
8752
- }
8753
- validate(repositoryPath, view, existingViews) {
8754
- const issues = [];
8755
- let validatedView = { ...view };
8756
- this.validateRequiredFields(validatedView, issues);
8757
- this.validateFilePaths(repositoryPath, validatedView, issues);
8758
- validatedView = this.validateAndCleanScope(repositoryPath, validatedView, issues);
8759
- const summary = {
8760
- errors: issues.filter((i) => i.severity === "error").length,
8761
- warnings: issues.filter((i) => i.severity === "warning").length,
8762
- info: issues.filter((i) => i.severity === "info").length
8763
- };
8764
- const displayOrderInfo = {
8765
- current: validatedView.displayOrder,
8766
- category: validatedView.category || "other",
8767
- suggestedNext: undefined
8768
- };
8769
- if (displayOrderInfo.current === undefined || displayOrderInfo.current === null) {
8770
- if (existingViews && existingViews.length > 0) {
8771
- let maxOrder = -1;
8772
- for (const otherView of existingViews) {
8773
- if ((otherView.category || "other") === displayOrderInfo.category) {
8774
- maxOrder = Math.max(maxOrder, otherView.displayOrder || 0);
8775
- }
8776
- }
8777
- displayOrderInfo.suggestedNext = maxOrder + 1;
8778
- } else {
8779
- displayOrderInfo.suggestedNext = 0;
8780
- }
8781
- }
8782
- return {
8783
- isValid: summary.errors === 0,
8784
- issues,
8785
- validatedView,
8786
- summary,
8787
- displayOrderInfo
8788
- };
8789
- }
8790
- validateRequiredFields(view, issues) {
8791
- if (!view.id || typeof view.id !== "string") {
8792
- issues.push({
8793
- severity: "error",
8794
- type: "missing_required_field",
8795
- message: "View must have a valid string ID",
8796
- location: "view.id"
8797
- });
8798
- }
8799
- if (!view.name || typeof view.name !== "string") {
8800
- issues.push({
8801
- severity: "error",
8802
- type: "missing_required_field",
8803
- message: "View must have a valid string name",
8804
- location: "view.name"
8805
- });
8806
- }
8807
- if (view.version && typeof view.version !== "string") {
8808
- issues.push({
8809
- severity: "error",
8810
- type: "invalid_field_type",
8811
- message: "View version must be a string if provided",
8812
- location: "view.version"
8813
- });
8814
- }
8815
- if (!view.description || typeof view.description !== "string") {
8816
- issues.push({
8817
- severity: "error",
8818
- type: "missing_required_field",
8819
- message: "View must have a description",
8820
- location: "view.description"
8821
- });
8822
- }
8823
- if (!view.overviewPath || typeof view.overviewPath !== "string") {
8824
- issues.push({
8825
- severity: "error",
8826
- type: "missing_required_field",
8827
- message: "View must have an overviewPath",
8828
- location: "view.overviewPath"
8829
- });
8830
- }
8831
- if (view.displayOrder === undefined || view.displayOrder === null || typeof view.displayOrder !== "number") {
8832
- issues.push({
8833
- severity: "error",
8834
- type: "missing_required_field",
8835
- message: "View must have a displayOrder number",
8836
- location: "view.displayOrder",
8837
- context: "The displayOrder field determines the ordering within a category"
8838
- });
8839
- }
8840
- if (!view.referenceGroups || typeof view.referenceGroups !== "object") {
8841
- issues.push({
8842
- severity: "error",
8843
- type: "missing_required_field",
8844
- message: "View must have referenceGroups object",
8845
- location: "view.referenceGroups"
8846
- });
8847
- return;
8848
- }
8849
- Object.entries(view.referenceGroups).forEach(([groupName, referenceGroup]) => {
8850
- const location = `view.referenceGroups.${groupName}`;
8851
- if (!referenceGroup.coordinates || !Array.isArray(referenceGroup.coordinates) || referenceGroup.coordinates.length !== 2) {
8852
- issues.push({
8853
- severity: "error",
8854
- type: "invalid_reference_group_coordinates",
8855
- message: "Reference group must have coordinates array with [row, col]",
8856
- location: `${location}.coordinates`
8857
- });
8858
- }
8859
- if (!referenceGroup.files || !Array.isArray(referenceGroup.files)) {
8860
- issues.push({
8861
- severity: "error",
8862
- type: "missing_reference_group_files",
8863
- message: "Reference group must have files array",
8864
- location: `${location}.files`
8865
- });
8866
- } else {
8867
- referenceGroup.files.forEach((filePath, index) => {
8868
- if (typeof filePath !== "string") {
8869
- issues.push({
8870
- severity: "error",
8871
- type: "invalid_file_path",
8872
- message: "File path must be a string",
8873
- location: `${location}.files[${index}]`
8874
- });
8875
- } else if (filePath.startsWith("/")) {
8876
- issues.push({
8877
- severity: "error",
8878
- type: "absolute_file_path",
8879
- message: "File paths must be relative to repository root",
8880
- location: `${location}.files[${index}]`,
8881
- context: `Found: "${filePath}"`
8882
- });
8883
- }
8884
- });
8885
- }
8886
- });
8887
- if (view.timestamp) {
8888
- const parsedDate = new Date(view.timestamp);
8889
- if (isNaN(parsedDate.getTime())) {
8890
- issues.push({
8891
- severity: "warning",
8892
- type: "invalid_timestamp",
8893
- message: "View timestamp is not a valid ISO date string",
8894
- location: "view.timestamp"
8895
- });
8896
- }
8897
- }
8898
- }
8899
- validateFilePaths(repositoryPath, view, issues) {
8900
- if (view.overviewPath && typeof view.overviewPath === "string") {
8901
- const overviewFullPath = this.fs.join(repositoryPath, view.overviewPath);
8902
- if (!this.fs.exists(overviewFullPath)) {
8903
- issues.push({
8904
- severity: "warning",
8905
- type: "missing_overview_file",
8906
- message: `Overview file not found: ${view.overviewPath}`,
8907
- location: "view.overviewPath",
8908
- context: "The overview file will be created if it doesn't exist"
8909
- });
8910
- }
8911
- }
8912
- if (view.referenceGroups && typeof view.referenceGroups === "object") {
8913
- Object.entries(view.referenceGroups).forEach(([groupName, referenceGroup]) => {
8914
- if (referenceGroup.files && Array.isArray(referenceGroup.files)) {
8915
- referenceGroup.files.forEach((filePath, index) => {
8916
- if (typeof filePath === "string" && !filePath.startsWith("/")) {
8917
- const fullPath = this.fs.join(repositoryPath, filePath);
8918
- if (!this.fs.exists(fullPath)) {
8919
- issues.push({
8920
- severity: "warning",
8921
- type: "missing_reference_group_file",
8922
- message: `File not found: ${filePath}`,
8923
- location: `view.referenceGroups.${groupName}.files[${index}]`,
8924
- context: "Missing files will not appear in the visualization"
8925
- });
8926
- }
8927
- }
8928
- });
8929
- }
8930
- });
8931
- }
8932
- }
8933
- validateAndCleanScope(repositoryPath, view, issues) {
8934
- if (!view.scope?.basePath) {
8935
- return view;
8936
- }
8937
- const scopeBasePath = view.scope.basePath;
8938
- const violatingFiles = [];
8939
- const scopePath = this.fs.join(repositoryPath, scopeBasePath);
8940
- if (!this.fs.exists(scopePath)) {
8941
- issues.push({
8942
- severity: "warning",
8943
- type: "scope_removed_missing_path",
8944
- message: `Scope removed: base path not found: ${scopeBasePath}`,
8945
- location: "view.scope",
8946
- context: "Scope will be regenerated based on reference group contents"
8947
- });
8948
- const viewWithoutScope = { ...view };
8949
- delete viewWithoutScope.scope;
8950
- return viewWithoutScope;
8951
- }
8952
- if (view.referenceGroups && typeof view.referenceGroups === "object") {
8953
- Object.entries(view.referenceGroups).forEach(([groupName, referenceGroup]) => {
8954
- if (referenceGroup.files && Array.isArray(referenceGroup.files)) {
8955
- referenceGroup.files.forEach((filePath) => {
8956
- if (typeof filePath === "string" && !filePath.startsWith("/")) {
8957
- if (!filePath.startsWith(scopeBasePath + "/") && filePath !== scopeBasePath) {
8958
- violatingFiles.push(`${groupName}: ${filePath}`);
8959
- }
8960
- }
8961
- });
8962
- }
8963
- });
8964
- }
8965
- if (violatingFiles.length > 0) {
8966
- issues.push({
8967
- severity: "info",
8968
- type: "scope_removed_violations",
8969
- message: `Scope removed: ${violatingFiles.length} files outside scope "${scopeBasePath}"`,
8970
- location: "view.scope",
8971
- context: `Violating files: ${violatingFiles.join(", ")}. Scope will be regenerated based on reference group contents.`
8972
- });
8973
- const viewWithoutScope = { ...view };
8974
- delete viewWithoutScope.scope;
8975
- return viewWithoutScope;
8976
- }
8977
- return view;
8978
- }
8979
- }
8980
-
8981
- // node_modules/@principal-ai/alexandria-core-library/dist/constants/paths.js
8982
- var ALEXANDRIA_DIRS = {
8983
- PRIMARY: ".alexandria",
8984
- VIEWS: "views",
8985
- OVERVIEWS: "overviews",
8986
- CONFIG: "config",
8987
- GLOBAL_DIR: "~/.alexandria",
8988
- GLOBAL_PROJECTS_FILE: "projects.json",
8989
- CONFIG_FILES: [".alexandriarc.json", ".alexandriarc", "alexandria.json"]
8990
- };
8991
-
8992
- // node_modules/@principal-ai/alexandria-core-library/dist/MemoryPalace.js
8993
- class MemoryPalace {
8994
- viewsStore;
8995
- drawingStore;
8996
- validator;
8997
- repositoryRoot;
8998
- fs;
8999
- constructor(repositoryRoot, fileSystem) {
9000
- this.fs = fileSystem;
9001
- this.repositoryRoot = MemoryPalace.validateRepositoryPath(fileSystem, repositoryRoot);
9002
- const alexandriaPath = MemoryPalace.getAlexandriaPath(this.repositoryRoot, fileSystem);
9003
- this.viewsStore = new CodebaseViewsStore(fileSystem, alexandriaPath);
9004
- this.drawingStore = new DrawingStore(fileSystem, alexandriaPath);
9005
- this.validator = new CodebaseViewValidator(fileSystem);
9006
- }
9007
- static getAlexandriaPath(repositoryPath, fs) {
9008
- const alexandriaPath = fs.join(repositoryPath, ALEXANDRIA_DIRS.PRIMARY);
9009
- return alexandriaPath;
9010
- }
9011
- static validateRepositoryPath(fs, path) {
9012
- if (!fs.isAbsolute(path)) {
9013
- throw new Error(`\u274C directoryPath must be an absolute path starting with '/'. ` + `Received: "${path}". ` + `\uD83D\uDCA1 Tip: Use absolute paths like /Users/username/projects/my-repo or /home/user/project. ` + `You can get the current working directory and build the absolute path from there.`);
9014
- }
9015
- if (!fs.exists(path)) {
9016
- throw new Error(`\u274C directoryPath must point to an existing directory. ` + `Path does not exist: "${path}". ` + `Check your current working directory and build the correct absolute path.`);
9017
- }
9018
- if (!fs.isDirectory(path)) {
9019
- throw new Error(`\u274C directoryPath must point to a directory, not a file. ` + `Received: "${path}"`);
9020
- }
9021
- try {
9022
- const repoRoot = fs.findProjectRoot(path);
9023
- if (repoRoot !== path) {
9024
- throw new Error(`\u274C directoryPath must be the git repository root, not a subdirectory. ` + `Received: "${path}", but repository root is: "${repoRoot}". ` + `\uD83D\uDCA1 Tip: Navigate to the repository root directory that contains the .git folder.`);
9025
- }
9026
- } catch {
9027
- throw new Error(`\u274C directoryPath must be a git repository root containing a .git directory. ` + `Path: "${path}" is not a git repository. ` + `\uD83D\uDCA1 Tip: Initialize a git repository with 'git init' in your project root, or navigate to an existing git repository. ` + `Repository roots contain a .git directory and serve as the base for all note storage.`);
9028
- }
9029
- return path;
9030
- }
9031
- static validateRelativePath(repositoryRoot, targetPath, fs) {
9032
- if (!fs.isAbsolute(targetPath)) {
9033
- throw new Error(`\u274C targetPath must be an absolute path starting with '/'. ` + `Received: "${targetPath}". ` + `\uD83D\uDCA1 Tip: Use absolute paths like /Users/username/projects/my-repo/src/file.ts`);
9034
- }
9035
- const relativePath = fs.relative(repositoryRoot, targetPath);
9036
- if (relativePath.startsWith("../") || relativePath === ".." || relativePath.includes("..")) {
9037
- throw new Error(`\u274C targetPath "${targetPath}" is not within repository root "${repositoryRoot}". ` + `Target paths must be within the repository.`);
9038
- }
9039
- const cleanPath = relativePath.startsWith("./") ? relativePath.slice(2) : relativePath;
9040
- const finalPath = cleanPath === "." ? "" : cleanPath;
9041
- return finalPath;
9042
- }
9043
- listViews() {
9044
- return this.viewsStore.listViews(this.repositoryRoot);
9045
- }
9046
- async listViewsAsync() {
9047
- return this.viewsStore.listViewsAsync(this.repositoryRoot);
9048
- }
9049
- getView(viewId) {
9050
- return this.viewsStore.getView(this.repositoryRoot, viewId);
9051
- }
9052
- async getViewAsync(viewId) {
9053
- return this.viewsStore.getViewAsync(this.repositoryRoot, viewId);
9054
- }
9055
- saveView(view) {
9056
- return this.viewsStore.saveView(this.repositoryRoot, view);
9057
- }
9058
- validateView(view) {
9059
- const existingViews = this.viewsStore.listViews(this.repositoryRoot);
9060
- return this.validator.validate(this.repositoryRoot, view, existingViews);
9061
- }
9062
- saveViewWithValidation(view) {
9063
- const existingViews = this.viewsStore.listViews(this.repositoryRoot);
9064
- const validationResult = this.validator.validate(this.repositoryRoot, view, existingViews);
9065
- let viewToSave = validationResult.validatedView;
9066
- if (!viewToSave.version) {
9067
- viewToSave = {
9068
- ...viewToSave,
9069
- version: "1.0.0"
9070
- };
9071
- }
9072
- if (!viewToSave.timestamp) {
9073
- viewToSave = {
9074
- ...viewToSave,
9075
- timestamp: new Date().toISOString()
9076
- };
9077
- }
9078
- this.viewsStore.saveView(this.repositoryRoot, viewToSave);
9079
- return {
9080
- ...validationResult,
9081
- validatedView: viewToSave
9082
- };
9083
- }
9084
- async getDocumentsOverview(globAdapter, options = {}) {
9085
- const { includeUntracked = true, excludePatterns = [] } = options;
9086
- const defaultExcludes = [
9087
- "**/.palace-work/**",
9088
- "**/.backlog/**",
9089
- "**/.alexandria/**",
9090
- "**/node_modules/**"
9091
- ];
9092
- const allExcludes = [...defaultExcludes, ...excludePatterns];
9093
- const markdownFiles = await globAdapter.findFiles(["**/*.md", "**/*.mdx"], {
9094
- cwd: this.repositoryRoot,
9095
- ignore: allExcludes,
9096
- onlyFiles: true
9097
- });
9098
- const views = await this.listViewsAsync();
9099
- const overviewPathToView = new Map;
9100
- for (const view of views) {
9101
- if (view.overviewPath) {
9102
- const normalizedPath = view.overviewPath.startsWith("./") ? view.overviewPath.slice(2) : view.overviewPath;
9103
- overviewPathToView.set(normalizedPath, view);
9104
- }
9105
- }
9106
- const results = [];
9107
- for (const relativePath of markdownFiles) {
9108
- const normalizedPath = relativePath.startsWith("./") ? relativePath.slice(2) : relativePath;
9109
- const view = overviewPathToView.get(normalizedPath);
9110
- const isTracked = !!view;
9111
- if (!isTracked && !includeUntracked) {
9112
- continue;
9113
- }
9114
- const filename = this.fs.basename(relativePath);
9115
- const title = this.extractTitleFromFilename(filename);
9116
- let associatedFiles;
9117
- if (view?.referenceGroups) {
9118
- const files = [];
9119
- for (const groupName in view.referenceGroups) {
9120
- const group = view.referenceGroups[groupName];
9121
- if ("files" in group && Array.isArray(group.files)) {
9122
- files.push(...group.files);
9123
- }
9124
- }
9125
- if (files.length > 0) {
9126
- associatedFiles = [...new Set(files)];
9127
- }
9128
- }
9129
- const overview = {
9130
- path: this.fs.join(this.repositoryRoot, relativePath),
9131
- relativePath,
9132
- title,
9133
- isTracked
9134
- };
9135
- if (view) {
9136
- overview.viewId = view.id;
9137
- overview.viewName = view.name;
9138
- if (associatedFiles) {
9139
- overview.associatedFiles = associatedFiles;
9140
- }
9141
- }
9142
- results.push(overview);
9143
- }
9144
- results.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
9145
- return results;
9146
- }
9147
- extractTitleFromFilename(filename) {
9148
- const withoutExt = filename.replace(/\.(md|mdx)$/i, "");
9149
- return withoutExt.replace(/[-_]/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
9150
- }
9151
- getRepositoryPath() {
9152
- return this.repositoryRoot;
9153
- }
9154
- fileExists(path) {
9155
- return this.fs.exists(path);
9156
- }
9157
- readFile(path) {
9158
- return this.fs.readFile(path);
9159
- }
9160
- writeFile(path, content) {
9161
- return this.fs.writeFile(path, content);
9162
- }
9163
- createDirectory(path) {
9164
- return this.fs.createDir(path);
9165
- }
9166
- deleteFile(path) {
9167
- return this.fs.deleteFile(path);
9168
- }
9169
- saveDrawing(name, content) {
9170
- return this.drawingStore.saveDrawing(name, content);
9171
- }
9172
- saveBinaryDrawing(name, content) {
9173
- return this.drawingStore.saveBinaryDrawing(name, content);
9174
- }
9175
- loadDrawing(name) {
9176
- return this.drawingStore.loadDrawing(name);
9177
- }
9178
- loadBinaryDrawing(name) {
9179
- return this.drawingStore.loadBinaryDrawing(name);
9180
- }
9181
- listDrawings() {
9182
- return this.drawingStore.listDrawings();
9183
- }
9184
- listDrawingsWithMetadata() {
9185
- return this.drawingStore.listDrawingsWithMetadata();
9186
- }
9187
- deleteDrawing(name) {
9188
- return this.drawingStore.deleteDrawing(name);
9189
- }
9190
- renameDrawing(oldName, newName) {
9191
- return this.drawingStore.renameDrawing(oldName, newName);
9192
- }
9193
- drawingExists(name) {
9194
- return this.drawingStore.drawingExists(name);
9195
- }
9196
- saveExcalidrawDrawing(drawingData) {
9197
- return this.drawingStore.saveExcalidrawDrawing(drawingData);
9198
- }
9199
- loadExcalidrawDrawing(drawingId) {
9200
- return this.drawingStore.loadExcalidrawDrawing(drawingId);
9201
- }
9202
- updateDrawingName(drawingId, newName) {
9203
- return this.drawingStore.updateDrawingName(drawingId, newName);
9204
- }
9205
- updateExcalidrawDrawingContent(drawingId, drawingData) {
9206
- return this.drawingStore.updateExcalidrawDrawingContent(drawingId, drawingData);
9207
- }
9208
- deleteDrawingById(drawingId) {
9209
- return this.drawingStore.deleteDrawingById(drawingId);
9210
- }
9211
- getDrawingMetadata(drawingId) {
9212
- return this.drawingStore.getDrawingMetadata(drawingId);
9213
- }
9214
- listDrawingsWithExtractedNames() {
9215
- return this.drawingStore.listDrawingsWithExtractedNames();
9216
- }
9217
- }
9218
- // node_modules/@principal-ai/alexandria-core-library/dist/projects-core/ProjectRegistryStore.js
9219
- class ProjectRegistryStore {
9220
- fs;
9221
- registryPath;
9222
- constructor(fileSystemAdapter, homeDir) {
9223
- this.fs = fileSystemAdapter;
9224
- this.registryPath = this.fs.join(homeDir, ".alexandria", "projects.json");
9225
- }
9226
- ensureRegistryDir() {
9227
- const registryDir = this.fs.dirname(this.registryPath);
9228
- if (!this.fs.exists(registryDir)) {
9229
- this.fs.createDir(registryDir);
9230
- }
9231
- }
9232
- loadRegistry() {
9233
- this.ensureRegistryDir();
9234
- if (!this.fs.exists(this.registryPath)) {
9235
- return {
9236
- version: "1.0.0",
9237
- projects: []
9238
- };
9239
- }
9240
- try {
9241
- const content = this.fs.readFile(this.registryPath);
9242
- return JSON.parse(content);
9243
- } catch {
9244
- return {
9245
- version: "1.0.0",
9246
- projects: []
9247
- };
9248
- }
9249
- }
9250
- saveRegistry(registry) {
9251
- this.ensureRegistryDir();
9252
- this.fs.writeFile(this.registryPath, JSON.stringify(registry, null, 2));
9253
- }
9254
- extractGitHubId(remoteUrl) {
9255
- const match = remoteUrl.match(/github\.com[:/]([^/]+)\/([^/.]+)(\.git)?$/);
9256
- if (!match)
9257
- return null;
9258
- return `${match[1]}/${match[2]}`;
9259
- }
9260
- deriveDisplayName(projectPath, remoteUrl) {
9261
- if (remoteUrl) {
9262
- const match = remoteUrl.match(/github\.com[:/][^/]+\/([^/.]+)(\.git)?$/);
9263
- if (match)
9264
- return match[1];
9265
- }
9266
- return projectPath.split("/").pop() || "unknown";
9267
- }
9268
- derivePurl(projectPath, remoteUrl) {
9269
- if (remoteUrl) {
9270
- const fromRemote = extractPurlFromRemoteUrl(remoteUrl);
9271
- if (fromRemote)
9272
- return fromRemote;
9273
- }
9274
- return createLocalRepoPurl(projectPath);
9275
- }
9276
- registerProject(projectPath, remoteUrl) {
9277
- const registry = this.loadRegistry();
9278
- const existing = registry.projects.find((p) => p.path.toLowerCase() === projectPath.toLowerCase());
9279
- if (existing)
9280
- return existing;
9281
- const entry = {
9282
- name: this.deriveDisplayName(projectPath, remoteUrl),
9283
- path: projectPath,
9284
- remoteUrl,
9285
- purl: this.derivePurl(projectPath, remoteUrl),
9286
- registeredAt: new Date().toISOString(),
9287
- github: undefined,
9288
- hasViews: false,
9289
- viewCount: 0,
9290
- views: []
9291
- };
9292
- registry.projects.push(entry);
9293
- this.saveRegistry(registry);
9294
- return entry;
9295
- }
9296
- findClonesByGitHubId(githubId) {
9297
- const registry = this.loadRegistry();
9298
- return registry.projects.filter((p) => p.github?.id === githubId);
9299
- }
9300
- findClonesByPurl(purl) {
9301
- const registry = this.loadRegistry();
9302
- return registry.projects.filter((p) => p.purl === purl);
9303
- }
9304
- listProjects() {
9305
- const registry = this.loadRegistry();
9306
- return registry.projects;
9307
- }
9308
- getByPath(path) {
9309
- const registry = this.loadRegistry();
9310
- return registry.projects.find((p) => p.path === path);
9311
- }
9312
- removeByPath(path) {
9313
- const registry = this.loadRegistry();
9314
- const initialLength = registry.projects.length;
9315
- registry.projects = registry.projects.filter((p) => p.path !== path);
9316
- if (registry.projects.length < initialLength) {
9317
- this.saveRegistry(registry);
9318
- return true;
9319
- }
9320
- return false;
9321
- }
9322
- removeAllByPurl(purl) {
9323
- const registry = this.loadRegistry();
9324
- const initialLength = registry.projects.length;
9325
- registry.projects = registry.projects.filter((p) => p.purl !== purl);
9326
- const removed = initialLength - registry.projects.length;
9327
- if (removed > 0) {
9328
- this.saveRegistry(registry);
9329
- }
9330
- return removed;
9331
- }
9332
- updateByPath(path, updates) {
9333
- const registry = this.loadRegistry();
9334
- const projectIndex = registry.projects.findIndex((p) => p.path === path);
9335
- if (projectIndex === -1) {
9336
- throw new Error(`No project registered at path '${path}'`);
9337
- }
9338
- const project = registry.projects[projectIndex];
9339
- registry.projects[projectIndex] = {
9340
- ...project,
9341
- ...updates,
9342
- path: project.path,
9343
- registeredAt: project.registeredAt
9344
- };
9345
- this.saveRegistry(registry);
9346
- }
9347
- migrateToPurl() {
9348
- const registry = this.loadRegistry();
9349
- let migratedCount = 0;
9350
- for (const project of registry.projects) {
9351
- if (project.purl)
9352
- continue;
9353
- let purl;
9354
- if (project.remoteUrl) {
9355
- purl = extractPurlFromRemoteUrl(project.remoteUrl) || undefined;
9356
- }
9357
- if (!purl && project.github?.id) {
9358
- try {
9359
- purl = extractPurlFromRemoteUrl(`https://github.com/${project.github.id}.git`) || undefined;
9360
- } catch {}
9361
- }
9362
- if (!purl) {
9363
- purl = createLocalRepoPurl(project.path);
9364
- }
9365
- project.purl = purl;
9366
- migratedCount++;
9367
- }
9368
- if (migratedCount > 0) {
9369
- this.saveRegistry(registry);
9370
- }
9371
- return migratedCount;
9372
- }
9373
- }
9374
- // node_modules/@principal-ai/alexandria-core-library/dist/config/schema.js
9375
- var DEFAULT_CONFIG = {
9376
- version: "1.0.0",
9377
- context: {
9378
- maxDepth: 10,
9379
- followSymlinks: false,
9380
- patterns: {
9381
- exclude: [
9382
- "**/node_modules/**",
9383
- "**/.git/**",
9384
- "**/dist/**",
9385
- "**/build/**",
9386
- "**/coverage/**",
9387
- "**/.next/**",
9388
- "**/.nuxt/**",
9389
- "**/.cache/**",
9390
- "**/tmp/**",
9391
- "**/*.log",
9392
- "**/.DS_Store",
9393
- "**/Thumbs.db"
9394
- ]
9395
- }
9396
- },
9397
- reporting: {
9398
- output: "console",
9399
- format: "text",
9400
- verbose: false
9401
- }
9402
- };
9403
- var CONFIG_FILENAMES = [
9404
- ".alexandriarc.json",
9405
- ".alexandriarc",
9406
- "alexandria.config.json",
9407
- "alexandria.json"
9408
- ];
9409
-
9410
- // node_modules/@principal-ai/alexandria-core-library/dist/config/loader.js
9411
- class ConfigLoader {
9412
- configCache = new Map;
9413
- fsAdapter;
9414
- constructor(fsAdapter) {
9415
- this.fsAdapter = fsAdapter;
9416
- }
9417
- findConfigFile(startDir) {
9418
- let currentDir = startDir;
9419
- while (currentDir) {
9420
- for (const filename of CONFIG_FILENAMES) {
9421
- const configPath = this.fsAdapter.join(currentDir, filename);
9422
- if (this.fsAdapter.exists(configPath)) {
9423
- return configPath;
9424
- }
9425
- }
9426
- const parentDir = this.fsAdapter.dirname(currentDir);
9427
- if (parentDir === currentDir)
9428
- break;
9429
- currentDir = parentDir;
9430
- }
9431
- return null;
9432
- }
9433
- loadConfig(configPathOrStartDir) {
9434
- if (!configPathOrStartDir) {
9435
- return null;
9436
- }
9437
- const path = this.fsAdapter.exists(configPathOrStartDir) && !this.fsAdapter.isDirectory(configPathOrStartDir) ? configPathOrStartDir : this.findConfigFile(configPathOrStartDir);
9438
- if (!path) {
9439
- return null;
9440
- }
9441
- if (this.configCache.has(path)) {
9442
- return this.configCache.get(path);
9443
- }
9444
- try {
9445
- const content = this.fsAdapter.readFile(path);
9446
- const config = JSON.parse(content);
9447
- const merged = this.mergeWithDefaults(config);
9448
- this.configCache.set(path, merged);
9449
- return merged;
9450
- } catch (error) {
9451
- console.error(`Failed to load config from ${path}:`, error);
9452
- return null;
9453
- }
9454
- }
9455
- mergeWithDefaults(config) {
9456
- return {
9457
- ...DEFAULT_CONFIG,
9458
- ...config,
9459
- context: {
9460
- ...DEFAULT_CONFIG.context,
9461
- ...config.context,
9462
- patterns: {
9463
- ...DEFAULT_CONFIG.context?.patterns,
9464
- ...config.context?.patterns
9465
- }
9466
- },
9467
- reporting: {
9468
- ...DEFAULT_CONFIG.reporting,
9469
- ...config.reporting
9470
- }
9471
- };
9472
- }
9473
- clearCache() {
9474
- this.configCache.clear();
9475
- }
9476
- }
9477
- // node_modules/@principal-ai/alexandria-core-library/dist/rules/utils/patterns.js
9478
- function matchesPatterns(globAdapter, patterns, candidate) {
9479
- if (!patterns || patterns.length === 0) {
9480
- return false;
9481
- }
9482
- if (globAdapter?.matchesPath) {
9483
- return globAdapter.matchesPath(patterns, candidate);
9484
- }
9485
- return patterns.includes(candidate);
9486
- }
9487
-
9488
- // node_modules/@principal-ai/alexandria-core-library/dist/rules/implementations/require-references.js
9489
- var requireReferences = {
9490
- id: "require-references",
9491
- name: "Require References",
9492
- severity: "error",
9493
- category: "critical",
9494
- description: "Every markdown file must be used as an overview in at least one CodebaseView",
9495
- impact: "AI agents lack structured context for understanding this documentation",
9496
- fixable: false,
9497
- enabled: true,
9498
- async check(context) {
9499
- const violations = [];
9500
- const { markdownFiles, views, config, globAdapter } = context;
9501
- const ruleConfig = config?.context?.rules?.find((r) => r.id === "require-references");
9502
- const configOptions = ruleConfig?.options;
9503
- const associatedFiles = new Set;
9504
- for (const view of views) {
9505
- if ("overviewPath" in view && typeof view.overviewPath === "string" && view.overviewPath.endsWith(".md")) {
9506
- associatedFiles.add(view.overviewPath);
9507
- }
9508
- }
9509
- const globalExcludePatterns = config?.context?.patterns?.exclude ?? [];
9510
- for (const mdFile of markdownFiles) {
9511
- const relativePath = mdFile.relativePath;
9512
- if (relativePath.startsWith(`${ALEXANDRIA_DIRS.PRIMARY}/`)) {
9513
- continue;
9514
- }
9515
- if (matchesPatterns(globAdapter, globalExcludePatterns, relativePath)) {
9516
- continue;
9517
- }
9518
- if (matchesPatterns(globAdapter, configOptions?.excludeFiles, relativePath)) {
9519
- continue;
9520
- }
9521
- if (!associatedFiles.has(relativePath)) {
9522
- violations.push({
9523
- ruleId: this.id,
9524
- severity: this.severity,
9525
- file: relativePath,
9526
- message: `Markdown file "${relativePath}" is not used as an overview in any CodebaseView`,
9527
- impact: this.impact,
9528
- fixable: this.fixable
9529
- });
9530
- }
9531
- }
9532
- return violations;
9533
- }
9534
- };
9535
-
9536
- // node_modules/@principal-ai/alexandria-core-library/dist/rules/utils/line-numbers.js
9537
- function findLineNumberInJSON(fs, filePath, searchTerm) {
9538
- try {
9539
- const content = fs.readFile(filePath);
9540
- const lines = content.split(`
9541
- `);
9542
- for (let i = 0;i < lines.length; i++) {
9543
- if (lines[i].includes(`"${searchTerm}"`) || lines[i].includes(searchTerm)) {
9544
- return i + 1;
9545
- }
9546
- }
9547
- } catch {
9548
- return;
9549
- }
9550
- return;
9551
- }
9552
- function findFileReferenceLineNumber(fs, filePath, referencedFile) {
9553
- return findLineNumberInJSON(fs, filePath, referencedFile);
9554
- }
9555
-
9556
- // node_modules/@principal-ai/alexandria-core-library/dist/utils/alexandria-paths.js
9557
- function getAlexandriaDir(fs, projectRoot) {
9558
- return fs.join(projectRoot, ALEXANDRIA_DIRS.PRIMARY);
9559
- }
9560
- function getAlexandriaSubdir(fs, projectRoot, subdir) {
9561
- return fs.join(getAlexandriaDir(fs, projectRoot), subdir);
9562
- }
9563
- function getViewsDir(fs, projectRoot) {
9564
- return getAlexandriaSubdir(fs, projectRoot, ALEXANDRIA_DIRS.VIEWS);
9565
- }
9566
-
9567
- // node_modules/@principal-ai/alexandria-core-library/dist/rules/implementations/orphaned-references.js
9568
- var orphanedReferences = {
9569
- id: "orphaned-references",
9570
- name: "Orphaned File References",
9571
- severity: "error",
9572
- category: "critical",
9573
- description: "Context references files that no longer exist in the codebase",
9574
- impact: "AI agents will reference non-existent files, causing errors and confusion",
9575
- fixable: false,
9576
- enabled: true,
9577
- async check(context) {
9578
- const violations = [];
9579
- const { views, projectRoot, fsAdapter } = context;
9580
- if (!fsAdapter) {
9581
- throw new Error("orphaned-references rule requires fsAdapter in context");
9582
- }
9583
- for (const view of views) {
9584
- if (view.referenceGroups) {
9585
- for (const groupName in view.referenceGroups) {
9586
- const referenceGroup = view.referenceGroups[groupName];
9587
- if ("files" in referenceGroup && Array.isArray(referenceGroup.files)) {
9588
- for (const file of referenceGroup.files) {
9589
- const fullPath = fsAdapter.join(projectRoot, file);
9590
- if (!fsAdapter.exists(fullPath)) {
9591
- const viewFilePath = fsAdapter.join(getViewsDir(fsAdapter, projectRoot), `${view.name}.json`);
9592
- const lineNumber = findFileReferenceLineNumber(fsAdapter, viewFilePath, file);
9593
- violations.push({
9594
- ruleId: this.id,
9595
- severity: this.severity,
9596
- file: `views/${view.name}.json`,
9597
- line: lineNumber,
9598
- message: `View "${view.name}" reference group "${groupName}" references non-existent file: ${file}`,
9599
- impact: this.impact,
9600
- fixable: this.fixable
9601
- });
9602
- }
9603
- }
9604
- }
9605
- }
9606
- }
9607
- }
9608
- return violations;
9609
- }
9610
- };
9611
-
9612
- // node_modules/@principal-ai/alexandria-core-library/dist/rules/implementations/stale-references.js
9613
- var staleReferences = {
9614
- id: "stale-references",
9615
- name: "Stale References",
9616
- severity: "warning",
9617
- category: "quality",
9618
- description: "Context documentation has not been updated since referenced files changed",
9619
- impact: "AI agents may use outdated patterns and assumptions from stale documentation",
9620
- fixable: false,
9621
- enabled: true,
9622
- async check(context) {
9623
- const violations = [];
9624
- const { views, files, fsAdapter } = context;
9625
- if (!fsAdapter) {
9626
- throw new Error("stale-references rule requires fsAdapter in context");
9627
- }
9628
- try {
9629
- const fileModMap = new Map;
9630
- for (const fileInfo of files) {
9631
- if (fileInfo.lastModified) {
9632
- fileModMap.set(fileInfo.relativePath, fileInfo.lastModified);
9633
- }
9634
- }
9635
- const getLastModified = (relativePath) => {
9636
- return fileModMap.get(relativePath) || null;
9637
- };
9638
- for (const view of views) {
9639
- if (!view.overviewPath)
9640
- continue;
9641
- const overviewLastModified = getLastModified(view.overviewPath);
9642
- if (!overviewLastModified)
9643
- continue;
9644
- let newestFileModification = null;
9645
- let newestFile = null;
9646
- if (view.referenceGroups) {
9647
- for (const groupName in view.referenceGroups) {
9648
- const referenceGroup = view.referenceGroups[groupName];
9649
- if ("files" in referenceGroup && Array.isArray(referenceGroup.files)) {
9650
- for (const file of referenceGroup.files) {
9651
- const fileModified = getLastModified(file);
9652
- if (fileModified && (!newestFileModification || fileModified > newestFileModification)) {
9653
- newestFileModification = fileModified;
9654
- newestFile = file;
9655
- }
9656
- }
9657
- }
9658
- }
9659
- }
9660
- if (newestFileModification && newestFileModification > overviewLastModified) {
9661
- const timeDifferenceMs = newestFileModification.getTime() - overviewLastModified.getTime();
9662
- if (timeDifferenceMs < 5000) {
9663
- continue;
9664
- }
9665
- const hoursSinceUpdate = Math.floor(timeDifferenceMs / (1000 * 60 * 60));
9666
- let timeMessage;
9667
- if (hoursSinceUpdate < 24) {
9668
- if (hoursSinceUpdate === 0) {
9669
- const minutesSinceUpdate = Math.floor((newestFileModification.getTime() - overviewLastModified.getTime()) / (1000 * 60));
9670
- if (minutesSinceUpdate <= 1) {
9671
- timeMessage = "was modified just after";
9672
- } else {
9673
- timeMessage = `was modified ${minutesSinceUpdate} minutes after`;
9674
- }
9675
- } else if (hoursSinceUpdate === 1) {
9676
- timeMessage = "has not been updated for 1 hour since";
9677
- } else {
9678
- timeMessage = `has not been updated for ${hoursSinceUpdate} hours since`;
9679
- }
9680
- } else {
9681
- const daysSinceUpdate = Math.floor(hoursSinceUpdate / 24);
9682
- if (daysSinceUpdate === 1) {
9683
- timeMessage = "has not been updated for 1 day since";
9684
- } else {
9685
- timeMessage = `has not been updated for ${daysSinceUpdate} days since`;
9686
- }
9687
- }
9688
- violations.push({
9689
- ruleId: this.id,
9690
- severity: this.severity,
9691
- file: view.overviewPath,
9692
- message: `Overview "${view.overviewPath}" ${timeMessage} "${newestFile}" changed`,
9693
- impact: this.impact,
9694
- fixable: this.fixable
9695
- });
9696
- }
9697
- }
9698
- } catch (error) {
9699
- console.warn("Stale context rule skipped:", error);
9700
- }
9701
- return violations;
9702
- }
9703
- };
9704
-
9705
8289
  // node_modules/@principal-ai/alexandria-core-library/dist/rules/utils/location-bound-files.js
9706
8290
  var LOCATION_BOUND_FILES = [
9707
8291
  {
@@ -9837,13 +8421,6 @@ var LOCATION_BOUND_FILES = [
9837
8421
  exemptFromNaming: true
9838
8422
  }
9839
8423
  ];
9840
- function getLocationBoundInfo(filename) {
9841
- const basename = filename.split("/").pop() || filename;
9842
- return LOCATION_BOUND_FILES.find((lbf) => lbf.pattern.toLowerCase() === basename.toLowerCase());
9843
- }
9844
- function isLocationBound(filePath) {
9845
- return getLocationBoundInfo(filePath) !== undefined;
9846
- }
9847
8424
  function getNamingExemptions() {
9848
8425
  return LOCATION_BOUND_FILES.filter((lbf) => lbf.exemptFromNaming).map((lbf) => lbf.pattern);
9849
8426
  }
@@ -9852,562 +8429,10 @@ function getRootExceptions() {
9852
8429
  }
9853
8430
 
9854
8431
  // node_modules/@principal-ai/alexandria-core-library/dist/rules/implementations/document-organization.js
9855
- var DEFAULT_DOC_FOLDERS = ["docs", "documentation", "doc"];
9856
8432
  var DEFAULT_ROOT_EXCEPTIONS = getRootExceptions();
9857
- var documentOrganization = {
9858
- id: "document-organization",
9859
- name: "Document Organization",
9860
- severity: "warning",
9861
- category: "structure",
9862
- description: "Ensures documentation files are properly organized in designated folders",
9863
- impact: "Disorganized documentation makes it harder for both humans and AI agents to find relevant information",
9864
- fixable: false,
9865
- enabled: true,
9866
- options: {
9867
- documentFolders: DEFAULT_DOC_FOLDERS,
9868
- rootExceptions: DEFAULT_ROOT_EXCEPTIONS,
9869
- checkNested: true
9870
- },
9871
- async check(context) {
9872
- const violations = [];
9873
- const { config, globAdapter, fsAdapter } = context;
9874
- if (!fsAdapter) {
9875
- throw new Error("document-organization rule requires fsAdapter in context");
9876
- }
9877
- const ruleConfig = config?.context?.rules?.find((r) => r.id === "document-organization");
9878
- const configOptions = ruleConfig?.options;
9879
- const defaultOptions = this.options;
9880
- const options = {
9881
- documentFolders: configOptions?.documentFolders || defaultOptions.documentFolders || DEFAULT_DOC_FOLDERS,
9882
- rootExceptions: configOptions?.rootExceptions || defaultOptions.rootExceptions || DEFAULT_ROOT_EXCEPTIONS,
9883
- checkNested: configOptions?.checkNested !== undefined ? configOptions.checkNested : defaultOptions.checkNested !== false
9884
- };
9885
- try {
9886
- const markdownFiles = context.markdownFiles;
9887
- const globalExcludePatterns = config?.context?.patterns?.exclude ?? [];
9888
- for (const fileInfo of markdownFiles) {
9889
- const file = fileInfo.relativePath;
9890
- const fileName = fsAdapter.basename(file);
9891
- const dirName = fsAdapter.dirname(file);
9892
- const pathParts = dirName.split("/").filter(Boolean);
9893
- if (matchesPatterns(globAdapter, globalExcludePatterns, file)) {
9894
- continue;
9895
- }
9896
- if (dirName === "." || dirName === "" || dirName === "/") {
9897
- const isAllowedException = options.rootExceptions?.some((exception) => fileName.toLowerCase() === exception.toLowerCase()) || false;
9898
- if (!isAllowedException) {
9899
- violations.push({
9900
- ruleId: this.id,
9901
- severity: this.severity,
9902
- file,
9903
- message: `Documentation file "${fileName}" should be in a documentation folder (e.g., ${options.documentFolders?.join(", ") || "docs"}) instead of the root directory`,
9904
- impact: this.impact,
9905
- fixable: this.fixable,
9906
- line: 1
9907
- });
9908
- }
9909
- } else {
9910
- let isInDocFolder = false;
9911
- if (options.checkNested) {
9912
- isInDocFolder = pathParts.some((part) => options.documentFolders?.some((docFolder) => part.toLowerCase() === docFolder.toLowerCase()) || false);
9913
- } else {
9914
- const immediateParent = pathParts[pathParts.length - 1];
9915
- isInDocFolder = options.documentFolders?.some((docFolder) => immediateParent?.toLowerCase() === docFolder.toLowerCase()) || false;
9916
- }
9917
- const isInSpecialDir = pathParts.some((part) => part === ".github" || part === "templates" || part === "examples" || part === ".changeset");
9918
- if (!isInDocFolder && !isInSpecialDir) {
9919
- if (!isLocationBound(fileName)) {
9920
- violations.push({
9921
- ruleId: this.id,
9922
- severity: this.severity,
9923
- file,
9924
- message: `Documentation file "${file}" should be in a documentation folder (e.g., ${options.documentFolders?.map((f) => `${f}/`).join(", ") || "docs/"})`,
9925
- impact: this.impact,
9926
- fixable: this.fixable,
9927
- line: 1
9928
- });
9929
- }
9930
- }
9931
- }
9932
- }
9933
- } catch (error) {
9934
- console.warn("Document organization rule skipped:", error);
9935
- }
9936
- return violations;
9937
- }
9938
- };
9939
8433
 
9940
8434
  // node_modules/@principal-ai/alexandria-core-library/dist/rules/implementations/filename-convention.js
9941
8435
  var DEFAULT_EXCEPTIONS = getNamingExemptions();
9942
- var DEFAULT_EXTENSIONS = [".md", ".mdx"];
9943
- var DEFAULT_DOC_FOLDERS2 = ["docs", "documentation", "doc"];
9944
- var filenameConvention = {
9945
- id: "filename-convention",
9946
- name: "Filename Convention",
9947
- severity: "warning",
9948
- category: "structure",
9949
- description: "Enforces consistent filename conventions for documentation files",
9950
- impact: "Inconsistent filename conventions make it harder to locate and reference documentation, reducing maintainability",
9951
- fixable: true,
9952
- enabled: true,
9953
- options: {
9954
- style: "kebab-case",
9955
- extensions: DEFAULT_EXTENSIONS,
9956
- exceptions: DEFAULT_EXCEPTIONS,
9957
- documentFoldersOnly: false,
9958
- autoFix: false
9959
- },
9960
- async check(context) {
9961
- const violations = [];
9962
- const { files, markdownFiles, config, globAdapter, fsAdapter } = context;
9963
- if (!fsAdapter) {
9964
- throw new Error("filename-convention rule requires fsAdapter in context");
9965
- }
9966
- const ruleConfig = config?.context?.rules?.find((r) => r.id === "filename-convention");
9967
- const configOptions = ruleConfig?.options;
9968
- const defaultOptions = this.options;
9969
- const options = {
9970
- style: configOptions?.style || (configOptions?.separator ? undefined : defaultOptions.style),
9971
- separator: configOptions?.separator,
9972
- caseStyle: configOptions?.caseStyle,
9973
- extensions: configOptions?.extensions || defaultOptions.extensions || DEFAULT_EXTENSIONS,
9974
- exclude: configOptions?.exclude || [],
9975
- exceptions: configOptions?.exceptions || defaultOptions.exceptions || DEFAULT_EXCEPTIONS,
9976
- documentFoldersOnly: configOptions?.documentFoldersOnly !== undefined ? configOptions.documentFoldersOnly : defaultOptions.documentFoldersOnly,
9977
- autoFix: configOptions?.autoFix || defaultOptions.autoFix
9978
- };
9979
- const extensions = options.extensions || DEFAULT_EXTENSIONS;
9980
- let filesToCheck = extensions.includes(".md") || extensions.includes(".mdx") ? markdownFiles : files.filter((f) => extensions.some((ext) => f.relativePath.endsWith(ext)));
9981
- const globalExcludePatterns = config?.context?.patterns?.exclude ?? [];
9982
- for (const fileInfo of filesToCheck) {
9983
- const fileName = fsAdapter.basename(fileInfo.relativePath);
9984
- const fileNameWithoutExt = fsAdapter.basename(fileInfo.relativePath, fsAdapter.extname(fileInfo.relativePath));
9985
- const dirName = fsAdapter.dirname(fileInfo.relativePath);
9986
- if (matchesPatterns(globAdapter, globalExcludePatterns, fileInfo.relativePath)) {
9987
- continue;
9988
- }
9989
- if (matchesPatterns(globAdapter, options.exclude, fileInfo.relativePath)) {
9990
- continue;
9991
- }
9992
- if (options.exceptions?.some((exception) => fileName === exception)) {
9993
- continue;
9994
- }
9995
- if (options.documentFoldersOnly) {
9996
- const pathParts = dirName.split("/").filter(Boolean);
9997
- const isInDocFolder = pathParts.some((part) => DEFAULT_DOC_FOLDERS2.some((docFolder) => part.toLowerCase() === docFolder.toLowerCase()));
9998
- if (!isInDocFolder) {
9999
- continue;
10000
- }
10001
- }
10002
- const expectedFileName = convertToConvention(fileNameWithoutExt, options);
10003
- const expectedFullName = expectedFileName + fsAdapter.extname(fileInfo.relativePath);
10004
- if (fileNameWithoutExt !== expectedFileName) {
10005
- violations.push({
10006
- ruleId: this.id,
10007
- severity: this.severity,
10008
- file: fileInfo.relativePath,
10009
- message: `File "${fileName}" should be named "${expectedFullName}" to match ${getStyleName(options)} convention`,
10010
- impact: this.impact,
10011
- fixable: this.fixable,
10012
- line: 1
10013
- });
10014
- }
10015
- }
10016
- return violations;
10017
- },
10018
- async fix(violation, context) {
10019
- if (!violation.file)
10020
- return;
10021
- const { projectRoot, config, fsAdapter } = context;
10022
- if (!fsAdapter) {
10023
- throw new Error("filename-convention fix requires fsAdapter in context");
10024
- }
10025
- const ruleConfig = config?.context?.rules?.find((r) => r.id === "filename-convention");
10026
- const configOptions = ruleConfig?.options;
10027
- const defaultOptions = this.options;
10028
- const options = {
10029
- style: configOptions?.style || defaultOptions.style,
10030
- separator: configOptions?.separator,
10031
- caseStyle: configOptions?.caseStyle,
10032
- autoFix: configOptions?.autoFix || defaultOptions.autoFix
10033
- };
10034
- if (!options.autoFix) {
10035
- console.log(`Auto-fix is disabled for ${this.id}. Enable it in configuration to fix automatically.`);
10036
- return;
10037
- }
10038
- const oldPath = fsAdapter.join(projectRoot, violation.file);
10039
- const fileName = fsAdapter.basename(violation.file);
10040
- const fileNameWithoutExt = fsAdapter.basename(violation.file, fsAdapter.extname(violation.file));
10041
- const dirName = fsAdapter.dirname(violation.file);
10042
- const expectedFileName = convertToConvention(fileNameWithoutExt, options);
10043
- const expectedFullName = expectedFileName + fsAdapter.extname(violation.file);
10044
- const newPath = fsAdapter.join(projectRoot, dirName, expectedFullName);
10045
- try {
10046
- const content = fsAdapter.readFile(oldPath);
10047
- fsAdapter.writeFile(newPath, content);
10048
- fsAdapter.deleteFile(oldPath);
10049
- console.log(`Renamed "${fileName}" to "${expectedFullName}"`);
10050
- } catch (error) {
10051
- console.error(`Failed to rename file: ${error}`);
10052
- throw error;
10053
- }
10054
- }
10055
- };
10056
- function convertToConvention(filename, options) {
10057
- const words = filename.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/([A-Z])([A-Z][a-z])/g, "$1 $2").replace(/[-_.\s]+/g, " ").toLowerCase().trim().split(" ").filter(Boolean);
10058
- let result;
10059
- if (options.separator && !options.style) {
10060
- result = words.join(options.separator);
10061
- } else {
10062
- switch (options.style) {
10063
- case "snake_case":
10064
- result = words.join("_");
10065
- break;
10066
- case "kebab-case":
10067
- result = words.join("-");
10068
- break;
10069
- case "camelCase":
10070
- if (words.length === 0) {
10071
- result = "";
10072
- } else {
10073
- result = words[0] + words.slice(1).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
10074
- }
10075
- break;
10076
- case "PascalCase":
10077
- result = words.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
10078
- break;
10079
- case "lowercase":
10080
- result = words.join("");
10081
- break;
10082
- case "UPPERCASE":
10083
- result = words.join("").toUpperCase();
10084
- break;
10085
- default:
10086
- result = words.join(options.separator || "-");
10087
- }
10088
- }
10089
- if (options.caseStyle && !["lowercase", "UPPERCASE", "camelCase", "PascalCase"].includes(options.style || "")) {
10090
- switch (options.caseStyle) {
10091
- case "lower":
10092
- result = result.toLowerCase();
10093
- break;
10094
- case "upper":
10095
- result = result.toUpperCase();
10096
- break;
10097
- }
10098
- }
10099
- return result;
10100
- }
10101
- function getStyleName(options) {
10102
- if (options.style) {
10103
- return options.style;
10104
- }
10105
- if (options.separator) {
10106
- const separatorName = {
10107
- _: "underscore-separated",
10108
- "-": "hyphen-separated",
10109
- " ": "space-separated",
10110
- ".": "dot-separated"
10111
- }[options.separator] || "custom-separated";
10112
- if (options.caseStyle) {
10113
- return `${options.caseStyle}case ${separatorName}`;
10114
- }
10115
- return separatorName;
10116
- }
10117
- return "specified";
10118
- }
10119
-
10120
- // node_modules/@principal-ai/alexandria-core-library/dist/rules/implementations/codebase-coverage.js
10121
- var codebaseCoverage = {
10122
- id: "codebase-coverage",
10123
- name: "Codebase Coverage",
10124
- severity: "warning",
10125
- category: "quality",
10126
- description: "Ensures a minimum percentage of code files are covered by CodebaseViews",
10127
- impact: "Low coverage means AI agents lack context for understanding large portions of the codebase",
10128
- fixable: false,
10129
- enabled: true,
10130
- options: {
10131
- minimumCoverage: 70,
10132
- includePatterns: ["**/*.ts", "**/*.js", "**/*.tsx", "**/*.jsx"],
10133
- excludePatterns: ["**/*.test.ts", "**/*.spec.ts", "**/node_modules/**"],
10134
- reportByDirectory: false,
10135
- minimumDirectoryCoverage: 50
10136
- },
10137
- async check(context) {
10138
- const violations = [];
10139
- const { files, views, config, globAdapter } = context;
10140
- const ruleConfig = config?.context?.rules?.find((r) => r.id === "codebase-coverage");
10141
- const options = {
10142
- ...this.options,
10143
- ...ruleConfig?.options
10144
- };
10145
- const coveredFiles = new Set;
10146
- for (const view of views) {
10147
- if (view.referenceGroups) {
10148
- for (const groupName in view.referenceGroups) {
10149
- const group = view.referenceGroups[groupName];
10150
- if ("files" in group && Array.isArray(group.files)) {
10151
- for (const file of group.files) {
10152
- coveredFiles.add(file);
10153
- }
10154
- }
10155
- }
10156
- }
10157
- }
10158
- const relevantFiles = files.filter((file) => {
10159
- const relativePath = file.relativePath;
10160
- const included = matchesPatterns(globAdapter, options.includePatterns, relativePath);
10161
- if (!included)
10162
- return false;
10163
- const excluded = matchesPatterns(globAdapter, options.excludePatterns, relativePath);
10164
- return !excluded;
10165
- });
10166
- const totalFiles = relevantFiles.length;
10167
- const coveredCount = relevantFiles.filter((f) => coveredFiles.has(f.relativePath)).length;
10168
- const coveragePercent = totalFiles > 0 ? Math.round(coveredCount / totalFiles * 100) : 100;
10169
- if (coveragePercent < options.minimumCoverage) {
10170
- violations.push({
10171
- ruleId: this.id,
10172
- severity: this.severity,
10173
- message: `Codebase coverage is ${coveragePercent}% (${coveredCount}/${totalFiles} files), below minimum of ${options.minimumCoverage}%`,
10174
- impact: this.impact,
10175
- fixable: false
10176
- });
10177
- }
10178
- if (options.reportByDirectory) {
10179
- const dirCoverage = new Map;
10180
- for (const file of relevantFiles) {
10181
- const dir = file.relativePath.split("/").slice(0, -1).join("/") || ".";
10182
- const stats = dirCoverage.get(dir) || { total: 0, covered: 0 };
10183
- stats.total++;
10184
- if (coveredFiles.has(file.relativePath)) {
10185
- stats.covered++;
10186
- }
10187
- dirCoverage.set(dir, stats);
10188
- }
10189
- for (const [dir, stats] of dirCoverage) {
10190
- const dirPercent = Math.round(stats.covered / stats.total * 100);
10191
- if (dirPercent < options.minimumDirectoryCoverage) {
10192
- violations.push({
10193
- ruleId: this.id,
10194
- severity: this.severity,
10195
- file: dir,
10196
- message: `Directory "${dir}" coverage is ${dirPercent}% (${stats.covered}/${stats.total} files), below minimum of ${options.minimumDirectoryCoverage}%`,
10197
- impact: this.impact,
10198
- fixable: false
10199
- });
10200
- }
10201
- }
10202
- }
10203
- return violations;
10204
- }
10205
- };
10206
-
10207
- // node_modules/@principal-ai/alexandria-core-library/dist/rules/implementations/minimum-references.js
10208
- var minimumReferences = {
10209
- id: "minimum-references",
10210
- name: "Minimum References",
10211
- severity: "error",
10212
- category: "quality",
10213
- description: "Ensures CodebaseViews have a minimum number of file references to prevent orphaned documentation",
10214
- impact: "Views with too few file references may not provide enough context for AI agents to understand the codebase",
10215
- fixable: false,
10216
- enabled: true,
10217
- options: {
10218
- minFiles: 1,
10219
- excludeCategories: ["planning", "meta"],
10220
- excludeViews: []
10221
- },
10222
- async check(context) {
10223
- const violations = [];
10224
- const { views, config } = context;
10225
- const ruleConfig = config?.context?.rules?.find((r) => r.id === "minimum-references");
10226
- const options = {
10227
- ...this.options,
10228
- ...ruleConfig?.options
10229
- };
10230
- for (const view of views) {
10231
- if (view.category && options.excludeCategories.includes(view.category)) {
10232
- continue;
10233
- }
10234
- if (options.excludeViews.includes(view.name)) {
10235
- continue;
10236
- }
10237
- let totalFiles = 0;
10238
- if (view.referenceGroups) {
10239
- for (const groupName in view.referenceGroups) {
10240
- const referenceGroup = view.referenceGroups[groupName];
10241
- if (typeof referenceGroup === "object" && referenceGroup !== null && "files" in referenceGroup && Array.isArray(referenceGroup.files)) {
10242
- totalFiles += referenceGroup.files.length;
10243
- }
10244
- }
10245
- }
10246
- if (totalFiles < options.minFiles) {
10247
- const viewFile = `views/${view.name}.json`;
10248
- violations.push({
10249
- ruleId: this.id,
10250
- severity: this.severity,
10251
- file: viewFile,
10252
- message: `View "${view.name}" has only ${totalFiles} file reference${totalFiles === 1 ? "" : "s"}, below minimum of ${options.minFiles}`,
10253
- impact: this.impact,
10254
- fixable: this.fixable
10255
- });
10256
- }
10257
- }
10258
- return violations;
10259
- }
10260
- };
10261
-
10262
- // node_modules/@principal-ai/alexandria-core-library/dist/rules/engine.js
10263
- class LibraryRulesEngine {
10264
- rules = new Map;
10265
- configLoader;
10266
- fsAdapter;
10267
- globAdapter;
10268
- constructor(fsAdapter, globAdapter) {
10269
- this.fsAdapter = fsAdapter;
10270
- this.configLoader = new ConfigLoader(this.fsAdapter);
10271
- this.globAdapter = globAdapter;
10272
- this.registerRule(requireReferences);
10273
- this.registerRule(orphanedReferences);
10274
- this.registerRule(staleReferences);
10275
- this.registerRule(documentOrganization);
10276
- this.registerRule(filenameConvention);
10277
- this.registerRule(codebaseCoverage);
10278
- this.registerRule(minimumReferences);
10279
- }
10280
- registerRule(rule) {
10281
- this.rules.set(rule.id, rule);
10282
- }
10283
- getAllRules() {
10284
- return this.rules;
10285
- }
10286
- async scanFiles(projectRoot, useGitignore = true, excludePatterns = []) {
10287
- const files = [];
10288
- const markdownFiles = [];
10289
- try {
10290
- const allFilePaths = await this.globAdapter.findFiles(["**/*"], {
10291
- cwd: projectRoot,
10292
- gitignore: useGitignore,
10293
- dot: false,
10294
- onlyFiles: true,
10295
- ignore: excludePatterns
10296
- });
10297
- const markdownFilePaths = await this.globAdapter.findFiles(["**/*.md", "**/*.mdx"], {
10298
- cwd: projectRoot,
10299
- gitignore: useGitignore,
10300
- dot: false,
10301
- onlyFiles: true,
10302
- ignore: excludePatterns
10303
- });
10304
- const markdownPathSet = new Set(markdownFilePaths);
10305
- for (const relativePath of allFilePaths) {
10306
- const fileInfo = {
10307
- path: `${projectRoot}/${relativePath}`,
10308
- relativePath,
10309
- exists: true,
10310
- isMarkdown: markdownPathSet.has(relativePath)
10311
- };
10312
- files.push(fileInfo);
10313
- }
10314
- for (const relativePath of markdownFilePaths) {
10315
- const fileInfo = {
10316
- path: `${projectRoot}/${relativePath}`,
10317
- relativePath,
10318
- exists: true,
10319
- isMarkdown: true
10320
- };
10321
- markdownFiles.push(fileInfo);
10322
- }
10323
- } catch (error) {
10324
- console.error(`Error scanning files in ${projectRoot}:`, error);
10325
- }
10326
- return { files, markdownFiles };
10327
- }
10328
- async lint(projectRoot, options = {}) {
10329
- const validatedPath = MemoryPalace.validateRepositoryPath(this.fsAdapter, projectRoot);
10330
- const memoryPalace = new MemoryPalace(validatedPath, this.fsAdapter);
10331
- const config = options.config || this.configLoader.loadConfig(validatedPath);
10332
- const useGitignore = config?.context?.useGitignore !== false;
10333
- const excludePatterns = config?.context?.patterns?.exclude ?? [];
10334
- const { files, markdownFiles } = await this.scanFiles(validatedPath, useGitignore, excludePatterns);
10335
- const views = memoryPalace.listViews();
10336
- const context = {
10337
- projectRoot: validatedPath,
10338
- views,
10339
- files,
10340
- markdownFiles,
10341
- config: config || undefined,
10342
- globAdapter: this.globAdapter,
10343
- fsAdapter: this.fsAdapter
10344
- };
10345
- const ruleOverrides = new Map;
10346
- if (config?.context?.rules) {
10347
- for (const ruleConfig of config.context.rules) {
10348
- ruleOverrides.set(ruleConfig.id, {
10349
- severity: ruleConfig.severity,
10350
- enabled: ruleConfig.enabled
10351
- });
10352
- }
10353
- }
10354
- const violations = [];
10355
- for (const [ruleId, rule] of this.rules) {
10356
- if (options.disabledRules?.includes(ruleId)) {
10357
- continue;
10358
- }
10359
- const override = ruleOverrides.get(ruleId);
10360
- const isEnabled = override?.enabled ?? rule.enabled;
10361
- if (!options.enabledRules || options.enabledRules.includes(ruleId)) {
10362
- if (isEnabled) {
10363
- const ruleViolations = await rule.check(context);
10364
- if (override?.severity) {
10365
- for (const violation of ruleViolations) {
10366
- violation.severity = override.severity;
10367
- }
10368
- }
10369
- violations.push(...ruleViolations);
10370
- }
10371
- }
10372
- }
10373
- let errorCount = 0;
10374
- let warningCount = 0;
10375
- let infoCount = 0;
10376
- let fixableCount = 0;
10377
- for (const violation of violations) {
10378
- switch (violation.severity) {
10379
- case "error":
10380
- errorCount++;
10381
- break;
10382
- case "warning":
10383
- warningCount++;
10384
- break;
10385
- case "info":
10386
- infoCount++;
10387
- break;
10388
- }
10389
- if (violation.fixable) {
10390
- fixableCount++;
10391
- }
10392
- }
10393
- if (options.fix && fixableCount > 0) {
10394
- console.log(`Would fix ${fixableCount} violations (not yet implemented)`);
10395
- }
10396
- return {
10397
- violations,
10398
- errorCount,
10399
- warningCount,
10400
- infoCount,
10401
- fixableCount
10402
- };
10403
- }
10404
- getRuleSet() {
10405
- return {
10406
- rules: Array.from(this.rules.values()),
10407
- enabledRules: Array.from(this.rules.keys()).filter((id) => this.rules.get(id)?.enabled)
10408
- };
10409
- }
10410
- }
10411
8436
  // src/bun/alexandria.ts
10412
8437
  class NodeFsAdapter {
10413
8438
  exists(path) {
@@ -10563,16 +8588,16 @@ class BunNormalizationAdapter {
10563
8588
  const target = resolve(absolutePath);
10564
8589
  let bestMatch = null;
10565
8590
  let bestLen = 0;
10566
- for (const [root, info2] of this.knownRoots) {
8591
+ for (const [root, info] of this.knownRoots) {
10567
8592
  const rootCanon = resolve(root);
10568
8593
  if ((target === rootCanon || target.startsWith(`${rootCanon}/`)) && rootCanon.length > bestLen) {
10569
- bestMatch = info2;
8594
+ bestMatch = info;
10570
8595
  bestLen = rootCanon.length;
10571
8596
  }
10572
8597
  }
10573
8598
  if (bestMatch) {
10574
- const canonicalRoot2 = await this.canonicalizeCase(bestMatch.root);
10575
- return { ...bestMatch, root: canonicalRoot2 };
8599
+ const canonicalRoot = await this.canonicalizeCase(bestMatch.root);
8600
+ return { ...bestMatch, root: canonicalRoot };
10576
8601
  }
10577
8602
  const gitRoot = await this.findGitRoot(target);
10578
8603
  if (!gitRoot)
@@ -11650,8 +9675,8 @@ async function processSessionEvents(sessionId, opts) {
11650
9675
  const dbPath = openCodeDBPath2();
11651
9676
  let db = null;
11652
9677
  try {
11653
- const { Database: Database2 } = await import("bun:sqlite");
11654
- db = new Database2(dbPath, { readonly: true });
9678
+ const { Database } = await import("bun:sqlite");
9679
+ db = new Database(dbPath, { readonly: true });
11655
9680
  const rows = db.prepare(`SELECT id, aggregate_id, seq, type, data FROM event WHERE aggregate_id = ? ORDER BY seq ASC`).all(sessionId);
11656
9681
  if (rows.length > 0) {
11657
9682
  try {