devos-os 1.0.1 → 1.1.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 (2) hide show
  1. package/dist/devos.mjs +817 -273
  2. package/package.json +5 -2
package/dist/devos.mjs CHANGED
@@ -1517,8 +1517,8 @@ var require_dataType = __commonJS({
1517
1517
  return types;
1518
1518
  }
1519
1519
  exports.getSchemaTypes = getSchemaTypes;
1520
- function getJSONTypes(ts) {
1521
- const types = Array.isArray(ts) ? ts : ts ? [ts] : [];
1520
+ function getJSONTypes(ts2) {
1521
+ const types = Array.isArray(ts2) ? ts2 : ts2 ? [ts2] : [];
1522
1522
  if (types.every(rules_1.isJSONType))
1523
1523
  return types;
1524
1524
  throw new Error("type must be JSONType or JSONType[]: " + types.join(","));
@@ -2560,18 +2560,18 @@ var require_validate = __commonJS({
2560
2560
  });
2561
2561
  narrowSchemaTypes(it, types);
2562
2562
  }
2563
- function checkMultipleTypes(it, ts) {
2564
- if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
2563
+ function checkMultipleTypes(it, ts2) {
2564
+ if (ts2.length > 1 && !(ts2.length === 2 && ts2.includes("null"))) {
2565
2565
  strictTypesError(it, "use allowUnionTypes to allow union type keyword");
2566
2566
  }
2567
2567
  }
2568
- function checkKeywordTypes(it, ts) {
2568
+ function checkKeywordTypes(it, ts2) {
2569
2569
  const rules = it.self.RULES.all;
2570
2570
  for (const keyword in rules) {
2571
2571
  const rule = rules[keyword];
2572
2572
  if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
2573
2573
  const { type } = rule.definition;
2574
- if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
2574
+ if (type.length && !type.some((t) => hasApplicableType(ts2, t))) {
2575
2575
  strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
2576
2576
  }
2577
2577
  }
@@ -2580,18 +2580,18 @@ var require_validate = __commonJS({
2580
2580
  function hasApplicableType(schTs, kwdT) {
2581
2581
  return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");
2582
2582
  }
2583
- function includesType(ts, t) {
2584
- return ts.includes(t) || t === "integer" && ts.includes("number");
2583
+ function includesType(ts2, t) {
2584
+ return ts2.includes(t) || t === "integer" && ts2.includes("number");
2585
2585
  }
2586
2586
  function narrowSchemaTypes(it, withTypes) {
2587
- const ts = [];
2587
+ const ts2 = [];
2588
2588
  for (const t of it.dataTypes) {
2589
2589
  if (includesType(withTypes, t))
2590
- ts.push(t);
2590
+ ts2.push(t);
2591
2591
  else if (withTypes.includes("integer") && t === "number")
2592
- ts.push("integer");
2592
+ ts2.push("integer");
2593
2593
  }
2594
- it.dataTypes = ts;
2594
+ it.dataTypes = ts2;
2595
2595
  }
2596
2596
  function strictTypesError(it, msg) {
2597
2597
  const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
@@ -3262,8 +3262,8 @@ var require_utils = __commonJS({
3262
3262
  }
3263
3263
  return ind;
3264
3264
  }
3265
- function removeDotSegments(path13) {
3266
- let input2 = path13;
3265
+ function removeDotSegments(path15) {
3266
+ let input2 = path15;
3267
3267
  const output2 = [];
3268
3268
  let nextSlash = -1;
3269
3269
  let len = 0;
@@ -3337,11 +3337,11 @@ var require_utils = __commonJS({
3337
3337
  }
3338
3338
  return output2.join("");
3339
3339
  }
3340
- function removeDotSegmentsRelative(path13) {
3341
- if (path13 === "" || path13[0] === "/") {
3342
- return removeDotSegments(path13);
3340
+ function removeDotSegmentsRelative(path15) {
3341
+ if (path15 === "" || path15[0] === "/") {
3342
+ return removeDotSegments(path15);
3343
3343
  }
3344
- const segments = path13.split("/");
3344
+ const segments = path15.split("/");
3345
3345
  const last = segments.length - 1;
3346
3346
  const output2 = [];
3347
3347
  let trailingDirectory = false;
@@ -3704,8 +3704,8 @@ var require_schemes = __commonJS({
3704
3704
  }
3705
3705
  if (wsComponent.resourceName) {
3706
3706
  const queryIndex = wsComponent.resourceName.indexOf("?");
3707
- const path13 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
3708
- wsComponent.path = path13 && path13 !== "/" ? path13 : void 0;
3707
+ const path15 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
3708
+ wsComponent.path = path15 && path15 !== "/" ? path15 : void 0;
3709
3709
  wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1);
3710
3710
  wsComponent.resourceName = void 0;
3711
3711
  }
@@ -10366,9 +10366,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
10366
10366
  * @param {string} [path]
10367
10367
  * @return {(string|null|Command)}
10368
10368
  */
10369
- executableDir(path13) {
10370
- if (path13 === void 0) return this._executableDir;
10371
- this._executableDir = path13;
10369
+ executableDir(path15) {
10370
+ if (path15 === void 0) return this._executableDir;
10371
+ this._executableDir = path15;
10372
10372
  return this;
10373
10373
  }
10374
10374
  /**
@@ -10628,7 +10628,7 @@ function useColor() {
10628
10628
  var program = new Command();
10629
10629
 
10630
10630
  // apps/cli/dist/commands/scan.js
10631
- import path8 from "node:path";
10631
+ import path9 from "node:path";
10632
10632
 
10633
10633
  // packages/scanner/dist/constants.js
10634
10634
  var PIPELINE_STAGES = [
@@ -10658,7 +10658,7 @@ var DEFAULT_IGNORED_DIRECTORIES = [
10658
10658
  ];
10659
10659
 
10660
10660
  // packages/scanner/dist/scanner.js
10661
- import path7 from "node:path";
10661
+ import path8 from "node:path";
10662
10662
  import { stat as stat4, readFile as readFile4 } from "node:fs/promises";
10663
10663
  import { performance } from "node:perf_hooks";
10664
10664
 
@@ -11173,17 +11173,17 @@ function globToRegExp(glob) {
11173
11173
  function createIgnoreMatcher(input2) {
11174
11174
  const extra = (input2.extraIgnore ?? []).map((glob) => globToRegExp(glob));
11175
11175
  return {
11176
- isIgnored(path13) {
11177
- const segments = path13.split("/");
11176
+ isIgnored(path15) {
11177
+ const segments = path15.split("/");
11178
11178
  for (const segment of segments) {
11179
11179
  if (BASELINE_DIRS.has(segment))
11180
11180
  return true;
11181
11181
  }
11182
- const name = segments[segments.length - 1] ?? path13;
11182
+ const name = segments[segments.length - 1] ?? path15;
11183
11183
  if (isSecretPath(name))
11184
11184
  return true;
11185
11185
  for (const re of extra) {
11186
- if (re.test(path13) || re.test(name))
11186
+ if (re.test(path15) || re.test(name))
11187
11187
  return true;
11188
11188
  }
11189
11189
  return false;
@@ -11312,13 +11312,13 @@ function extension(name) {
11312
11312
  }
11313
11313
  function createClassifier() {
11314
11314
  return {
11315
- classify(path13) {
11316
- const name = basename(path13).toLowerCase();
11315
+ classify(path15) {
11316
+ const name = basename(path15).toLowerCase();
11317
11317
  if (LOCKFILES.has(name))
11318
11318
  return "lockfile";
11319
11319
  if (MANIFESTS.has(name) || name.endsWith(".csproj") || name.endsWith(".fsproj"))
11320
11320
  return "manifest";
11321
- if (name.includes(".test.") || name.includes(".spec.") || path13.includes("/tests/") || path13.includes("/test/") || path13.includes("/__tests__/") || path13.startsWith("tests/"))
11321
+ if (name.includes(".test.") || name.includes(".spec.") || path15.includes("/tests/") || path15.includes("/test/") || path15.includes("/__tests__/") || path15.startsWith("tests/"))
11322
11322
  return "test";
11323
11323
  const ext = extension(name);
11324
11324
  if (DOC_EXTS.has(ext))
@@ -11401,8 +11401,8 @@ var BY_EXTENSION = {
11401
11401
  };
11402
11402
  function createLanguageDetector() {
11403
11403
  return {
11404
- detect(path13) {
11405
- const name = (path13.split("/").pop() ?? path13).toLowerCase();
11404
+ detect(path15) {
11405
+ const name = (path15.split("/").pop() ?? path15).toLowerCase();
11406
11406
  const dot = name.lastIndexOf(".");
11407
11407
  if (dot <= 0)
11408
11408
  return void 0;
@@ -11526,14 +11526,66 @@ function createMetadataCollector() {
11526
11526
  };
11527
11527
  }
11528
11528
 
11529
+ // packages/scanner/dist/ast/ts-ast.js
11530
+ import ts from "typescript";
11531
+ function isTypeScriptFamily(language) {
11532
+ return language === "typescript" || language === "javascript";
11533
+ }
11534
+ function scriptKindFor(fileName) {
11535
+ const lower = fileName.toLowerCase();
11536
+ if (lower.endsWith(".tsx"))
11537
+ return ts.ScriptKind.TSX;
11538
+ if (lower.endsWith(".jsx"))
11539
+ return ts.ScriptKind.JSX;
11540
+ if (lower.endsWith(".ts") || lower.endsWith(".mts") || lower.endsWith(".cts")) {
11541
+ return ts.ScriptKind.TS;
11542
+ }
11543
+ return ts.ScriptKind.JS;
11544
+ }
11545
+ var cache = /* @__PURE__ */ new WeakMap();
11546
+ function getTypeScriptSourceFile(tree, fileName) {
11547
+ if (tree.content === void 0 || !isTypeScriptFamily(tree.language))
11548
+ return void 0;
11549
+ const kind = scriptKindFor(fileName);
11550
+ let byKind = cache.get(tree);
11551
+ if (byKind === void 0) {
11552
+ byKind = /* @__PURE__ */ new Map();
11553
+ cache.set(tree, byKind);
11554
+ }
11555
+ let sourceFile = byKind.get(kind);
11556
+ if (sourceFile === void 0) {
11557
+ sourceFile = ts.createSourceFile(
11558
+ fileName,
11559
+ tree.content,
11560
+ ts.ScriptTarget.Latest,
11561
+ /* setParentNodes */
11562
+ true,
11563
+ kind
11564
+ );
11565
+ byKind.set(kind, sourceFile);
11566
+ }
11567
+ return sourceFile;
11568
+ }
11569
+ function lineColOf(sourceFile, position) {
11570
+ const lc = sourceFile.getLineAndCharacterOfPosition(position);
11571
+ return { line: lc.line + 1, column: lc.character + 1 };
11572
+ }
11573
+
11529
11574
  // packages/scanner/dist/ast/index.js
11530
11575
  function createAstParser() {
11531
11576
  return {
11532
- parse: (content, language) => ({ language, content })
11577
+ parse: (content, language) => {
11578
+ const tree = { language, content };
11579
+ if (isTypeScriptFamily(language)) {
11580
+ getTypeScriptSourceFile(tree, "file.ts");
11581
+ }
11582
+ return tree;
11583
+ }
11533
11584
  };
11534
11585
  }
11535
11586
 
11536
11587
  // packages/scanner/dist/graph/import-graph.js
11588
+ import path4 from "node:path";
11537
11589
  function lineCol(content, index) {
11538
11590
  let line = 1;
11539
11591
  let lastBreak = -1;
@@ -11545,12 +11597,6 @@ function lineCol(content, index) {
11545
11597
  }
11546
11598
  return { line, column: index - lastBreak };
11547
11599
  }
11548
- var SPECIFIER_PATTERNS = [
11549
- /\bimport\s+(?:[^"']*?\s+from\s+)?["']([^"']+)["']/g,
11550
- /\bexport\s+[^"']*?\s+from\s+["']([^"']+)["']/g,
11551
- /\brequire\(\s*["']([^"']+)["']\s*\)/g,
11552
- /\bimport\(\s*["']([^"']+)["']\s*\)/g
11553
- ];
11554
11600
  function resolveInternal(fromPath, specifier) {
11555
11601
  const dir = fromPath.split("/").slice(0, -1);
11556
11602
  const parts = [...dir];
@@ -11564,37 +11610,157 @@ function resolveInternal(fromPath, specifier) {
11564
11610
  }
11565
11611
  return parts.join("/");
11566
11612
  }
11613
+ function toReference(fromPath, specifier) {
11614
+ return specifier.startsWith(".") ? { kind: "internal", path: resolveInternal(fromPath, specifier) } : { kind: "external", specifier };
11615
+ }
11616
+ function buildWithAst(path15, tree) {
11617
+ const sourceFile = getTypeScriptSourceFile(tree, String(path15));
11618
+ if (sourceFile === void 0)
11619
+ return void 0;
11620
+ const seen = /* @__PURE__ */ new Set();
11621
+ const out = [];
11622
+ const push = (specifier, position) => {
11623
+ const key = `${specifier}|${position}`;
11624
+ if (seen.has(key))
11625
+ return;
11626
+ seen.add(key);
11627
+ const { line, column } = lineColOf(sourceFile, position);
11628
+ out.push({
11629
+ from: path15,
11630
+ to: toReference(String(path15), specifier),
11631
+ provenance: { file: path15, stage: "graph", location: { line, column } }
11632
+ });
11633
+ };
11634
+ const visit2 = (node2) => {
11635
+ if (ts.isImportDeclaration(node2) && ts.isStringLiteral(node2.moduleSpecifier)) {
11636
+ push(node2.moduleSpecifier.text, node2.getStart(sourceFile));
11637
+ } else if (ts.isExportDeclaration(node2) && node2.moduleSpecifier !== void 0 && ts.isStringLiteral(node2.moduleSpecifier)) {
11638
+ push(node2.moduleSpecifier.text, node2.getStart(sourceFile));
11639
+ } else if (ts.isCallExpression(node2)) {
11640
+ const first = node2.arguments[0];
11641
+ if (first !== void 0 && ts.isStringLiteral(first)) {
11642
+ if (node2.expression.kind === ts.SyntaxKind.ImportKeyword) {
11643
+ push(first.text, node2.getStart(sourceFile));
11644
+ } else if (ts.isIdentifier(node2.expression) && node2.expression.text === "require") {
11645
+ push(first.text, node2.getStart(sourceFile));
11646
+ }
11647
+ }
11648
+ }
11649
+ ts.forEachChild(node2, visit2);
11650
+ };
11651
+ visit2(sourceFile);
11652
+ return out;
11653
+ }
11654
+ var SPECIFIER_PATTERNS = [
11655
+ /\bimport\s+(?:[^"']*?\s+from\s+)?["']([^"']+)["']/g,
11656
+ /\bexport\s+[^"']*?\s+from\s+["']([^"']+)["']/g,
11657
+ /\brequire\(\s*["']([^"']+)["']\s*\)/g,
11658
+ /\bimport\(\s*["']([^"']+)["']\s*\)/g
11659
+ ];
11660
+ function buildWithPatterns(path15, tree) {
11661
+ const content = tree.content;
11662
+ if (content === void 0 || content.length === 0)
11663
+ return [];
11664
+ const seen = /* @__PURE__ */ new Set();
11665
+ const out = [];
11666
+ for (const re of SPECIFIER_PATTERNS) {
11667
+ re.lastIndex = 0;
11668
+ let match;
11669
+ while ((match = re.exec(content)) !== null) {
11670
+ const specifier = match[1];
11671
+ if (specifier === void 0)
11672
+ continue;
11673
+ const key = `${specifier}|${match.index}`;
11674
+ if (seen.has(key))
11675
+ continue;
11676
+ seen.add(key);
11677
+ const { line, column } = lineCol(content, match.index);
11678
+ out.push({
11679
+ from: path15,
11680
+ to: toReference(String(path15), specifier),
11681
+ provenance: { file: path15, stage: "graph", location: { line, column } }
11682
+ });
11683
+ }
11684
+ }
11685
+ return out;
11686
+ }
11567
11687
  function createImportGraphBuilder() {
11568
11688
  return {
11569
- build(path13, tree) {
11570
- const content = tree.content;
11571
- if (content === void 0 || content.length === 0)
11572
- return [];
11573
- const seen = /* @__PURE__ */ new Set();
11574
- const out = [];
11575
- for (const re of SPECIFIER_PATTERNS) {
11576
- re.lastIndex = 0;
11577
- let match;
11578
- while ((match = re.exec(content)) !== null) {
11579
- const specifier = match[1];
11580
- if (specifier === void 0)
11581
- continue;
11582
- const key = `${specifier}|${match.index}`;
11583
- if (seen.has(key))
11584
- continue;
11585
- seen.add(key);
11586
- const to = specifier.startsWith(".") ? { kind: "internal", path: resolveInternal(path13, specifier) } : { kind: "external", specifier };
11587
- const { line, column } = lineCol(content, match.index);
11588
- out.push({
11589
- from: path13,
11590
- to,
11591
- provenance: { file: path13, stage: "graph", location: { line, column } }
11592
- });
11593
- }
11689
+ build(path15, tree) {
11690
+ return buildWithAst(path15, tree) ?? buildWithPatterns(path15, tree);
11691
+ }
11692
+ };
11693
+ }
11694
+ function resolveImportEdges(edges, fileSet, root) {
11695
+ let options = {
11696
+ module: ts.ModuleKind.ESNext,
11697
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
11698
+ target: ts.ScriptTarget.ES2022,
11699
+ allowJs: true
11700
+ };
11701
+ try {
11702
+ const configPath = ts.findConfigFile(root, ts.sys.fileExists, "tsconfig.json");
11703
+ if (configPath !== void 0) {
11704
+ const read = ts.readConfigFile(configPath, ts.sys.readFile);
11705
+ if (read.config !== void 0) {
11706
+ const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, root);
11707
+ options = { ...options, ...parsed.options };
11708
+ }
11709
+ }
11710
+ } catch {
11711
+ }
11712
+ const host = {
11713
+ fileExists: (file2) => fileSet.has(toProjectRelative(root, file2)),
11714
+ readFile: () => ""
11715
+ };
11716
+ const cache2 = /* @__PURE__ */ new Map();
11717
+ const resolveSpecifier = (from, specifier) => {
11718
+ const key = `${String(from)}|${specifier}`;
11719
+ const hit = cache2.get(key);
11720
+ if (hit !== void 0 || cache2.has(key))
11721
+ return hit;
11722
+ let resolved;
11723
+ try {
11724
+ const containing = path4.join(root, String(from));
11725
+ const result = ts.resolveModuleName(specifier, containing, options, host);
11726
+ const fileName = result.resolvedModule?.resolvedFileName;
11727
+ if (fileName !== void 0) {
11728
+ const rel = toProjectRelative(root, fileName);
11729
+ if (fileSet.has(rel))
11730
+ resolved = rel;
11594
11731
  }
11595
- return out;
11732
+ } catch {
11733
+ resolved = void 0;
11596
11734
  }
11735
+ cache2.set(key, resolved);
11736
+ return resolved;
11597
11737
  };
11738
+ return edges.map((edge) => {
11739
+ const specifier = edge.to.kind === "external" ? edge.to.specifier : reconstructSpecifier(String(edge.from), String(edge.to.path));
11740
+ if (specifier === void 0)
11741
+ return edge;
11742
+ const resolved = resolveSpecifier(edge.from, specifier);
11743
+ if (resolved === void 0 || resolved === String(edge.to.kind === "internal" ? edge.to.path : "")) {
11744
+ return edge;
11745
+ }
11746
+ return { ...edge, to: { kind: "internal", path: resolved } };
11747
+ });
11748
+ }
11749
+ function toProjectRelative(root, absolute) {
11750
+ return path4.relative(root, absolute).split(path4.sep).join("/");
11751
+ }
11752
+ function reconstructSpecifier(from, internalPath) {
11753
+ const dir = from.split("/").slice(0, -1);
11754
+ const target = internalPath.split("/");
11755
+ let common = 0;
11756
+ while (common < dir.length && common < target.length && dir[common] === target[common]) {
11757
+ common += 1;
11758
+ }
11759
+ const ups = dir.length - common;
11760
+ const rest = target.slice(common).join("/");
11761
+ if (rest.length === 0)
11762
+ return void 0;
11763
+ return ups === 0 ? `./${rest}` : `${"../".repeat(ups)}${rest}`;
11598
11764
  }
11599
11765
 
11600
11766
  // packages/scanner/dist/graph/export-graph.js
@@ -11609,52 +11775,107 @@ function lineCol2(content, index) {
11609
11775
  }
11610
11776
  return { line, column: index - lastBreak };
11611
11777
  }
11778
+ function hasModifier(node2, kind) {
11779
+ const modifiers = ts.canHaveModifiers(node2) ? ts.getModifiers(node2) : void 0;
11780
+ return modifiers?.some((m) => m.kind === kind) ?? false;
11781
+ }
11782
+ function buildWithAst2(path15, tree) {
11783
+ const sourceFile = getTypeScriptSourceFile(tree, String(path15));
11784
+ if (sourceFile === void 0)
11785
+ return void 0;
11786
+ const seen = /* @__PURE__ */ new Set();
11787
+ const out = [];
11788
+ const push = (name, position) => {
11789
+ const key = `${name}|${position}`;
11790
+ if (seen.has(key))
11791
+ return;
11792
+ seen.add(key);
11793
+ const { line, column } = lineColOf(sourceFile, position);
11794
+ out.push({
11795
+ module: path15,
11796
+ name,
11797
+ provenance: { file: path15, stage: "graph", location: { line, column } }
11798
+ });
11799
+ };
11800
+ for (const statement of sourceFile.statements) {
11801
+ if (ts.isExportDeclaration(statement) && statement.exportClause !== void 0) {
11802
+ if (ts.isNamedExports(statement.exportClause)) {
11803
+ for (const element of statement.exportClause.elements) {
11804
+ push(element.name.text, element.getStart(sourceFile));
11805
+ }
11806
+ }
11807
+ continue;
11808
+ }
11809
+ if (ts.isExportAssignment(statement)) {
11810
+ push("default", statement.getStart(sourceFile));
11811
+ continue;
11812
+ }
11813
+ if (!hasModifier(statement, ts.SyntaxKind.ExportKeyword))
11814
+ continue;
11815
+ if (hasModifier(statement, ts.SyntaxKind.DefaultKeyword)) {
11816
+ push("default", statement.getStart(sourceFile));
11817
+ }
11818
+ if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement) || ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) || ts.isEnumDeclaration(statement)) && statement.name !== void 0) {
11819
+ push(statement.name.text, statement.name.getStart(sourceFile));
11820
+ } else if (ts.isVariableStatement(statement)) {
11821
+ for (const declaration of statement.declarationList.declarations) {
11822
+ if (ts.isIdentifier(declaration.name)) {
11823
+ push(declaration.name.text, declaration.name.getStart(sourceFile));
11824
+ }
11825
+ }
11826
+ }
11827
+ }
11828
+ return out;
11829
+ }
11612
11830
  var DECLARATION = /\bexport\s+(?:default\s+)?(?:async\s+)?(?:function\s*\*?|class|interface|type|enum|const|let|var)\s+([A-Za-z_$][\w$]*)/g;
11613
11831
  var DEFAULT_EXPORT = /\bexport\s+default\b/g;
11614
11832
  var LIST_EXPORT = /\bexport\s*\{([^}]*)\}/g;
11833
+ function buildWithPatterns2(path15, tree) {
11834
+ const content = tree.content;
11835
+ if (content === void 0 || content.length === 0)
11836
+ return [];
11837
+ const seen = /* @__PURE__ */ new Set();
11838
+ const out = [];
11839
+ const push = (name, index) => {
11840
+ const key = `${name}|${index}`;
11841
+ if (seen.has(key))
11842
+ return;
11843
+ seen.add(key);
11844
+ const { line, column } = lineCol2(content, index);
11845
+ out.push({
11846
+ module: path15,
11847
+ name,
11848
+ provenance: { file: path15, stage: "graph", location: { line, column } }
11849
+ });
11850
+ };
11851
+ let match;
11852
+ DECLARATION.lastIndex = 0;
11853
+ while ((match = DECLARATION.exec(content)) !== null) {
11854
+ if (match[1] !== void 0)
11855
+ push(match[1], match.index);
11856
+ }
11857
+ DEFAULT_EXPORT.lastIndex = 0;
11858
+ while ((match = DEFAULT_EXPORT.exec(content)) !== null) {
11859
+ push("default", match.index);
11860
+ }
11861
+ LIST_EXPORT.lastIndex = 0;
11862
+ while ((match = LIST_EXPORT.exec(content)) !== null) {
11863
+ const list = match[1] ?? "";
11864
+ for (const part of list.split(",")) {
11865
+ const cleaned = part.trim();
11866
+ if (cleaned.length === 0)
11867
+ continue;
11868
+ const alias = cleaned.split(/\s+as\s+/).pop()?.trim();
11869
+ if (alias !== void 0 && alias.length > 0)
11870
+ push(alias, match.index);
11871
+ }
11872
+ }
11873
+ return out;
11874
+ }
11615
11875
  function createExportGraphBuilder() {
11616
11876
  return {
11617
- build(path13, tree) {
11618
- const content = tree.content;
11619
- if (content === void 0 || content.length === 0)
11620
- return [];
11621
- const seen = /* @__PURE__ */ new Set();
11622
- const out = [];
11623
- const push = (name, index) => {
11624
- const key = `${name}|${index}`;
11625
- if (seen.has(key))
11626
- return;
11627
- seen.add(key);
11628
- const { line, column } = lineCol2(content, index);
11629
- out.push({
11630
- module: path13,
11631
- name,
11632
- provenance: { file: path13, stage: "graph", location: { line, column } }
11633
- });
11634
- };
11635
- let match;
11636
- DECLARATION.lastIndex = 0;
11637
- while ((match = DECLARATION.exec(content)) !== null) {
11638
- if (match[1] !== void 0)
11639
- push(match[1], match.index);
11640
- }
11641
- DEFAULT_EXPORT.lastIndex = 0;
11642
- while ((match = DEFAULT_EXPORT.exec(content)) !== null) {
11643
- push("default", match.index);
11644
- }
11645
- LIST_EXPORT.lastIndex = 0;
11646
- while ((match = LIST_EXPORT.exec(content)) !== null) {
11647
- const list = match[1] ?? "";
11648
- for (const part of list.split(",")) {
11649
- const cleaned = part.trim();
11650
- if (cleaned.length === 0)
11651
- continue;
11652
- const alias = cleaned.split(/\s+as\s+/).pop()?.trim();
11653
- if (alias !== void 0 && alias.length > 0)
11654
- push(alias, match.index);
11655
- }
11656
- }
11657
- return out;
11877
+ build(path15, tree) {
11878
+ return buildWithAst2(path15, tree) ?? buildWithPatterns2(path15, tree);
11658
11879
  }
11659
11880
  };
11660
11881
  }
@@ -11671,46 +11892,80 @@ function lineCol3(content, index) {
11671
11892
  }
11672
11893
  return { line, column: index - lastBreak };
11673
11894
  }
11895
+ function extractWithAst(path15, tree) {
11896
+ const sourceFile = getTypeScriptSourceFile(tree, String(path15));
11897
+ if (sourceFile === void 0)
11898
+ return void 0;
11899
+ const seen = /* @__PURE__ */ new Set();
11900
+ const out = [];
11901
+ const push = (name, kind, position) => {
11902
+ const { line, column } = lineColOf(sourceFile, position);
11903
+ const key = `${name}|${kind}|${line}`;
11904
+ if (seen.has(key))
11905
+ return;
11906
+ seen.add(key);
11907
+ out.push({
11908
+ name,
11909
+ kind,
11910
+ provenance: { file: path15, stage: "symbols", location: { line, column } }
11911
+ });
11912
+ };
11913
+ const visit2 = (node2) => {
11914
+ if (ts.isFunctionDeclaration(node2) && node2.name !== void 0) {
11915
+ push(node2.name.text, "function", node2.name.getStart(sourceFile));
11916
+ } else if (ts.isClassDeclaration(node2) && node2.name !== void 0) {
11917
+ push(node2.name.text, "class", node2.name.getStart(sourceFile));
11918
+ } else if (ts.isInterfaceDeclaration(node2)) {
11919
+ push(node2.name.text, "interface", node2.name.getStart(sourceFile));
11920
+ } else if (ts.isTypeAliasDeclaration(node2)) {
11921
+ push(node2.name.text, "type", node2.name.getStart(sourceFile));
11922
+ } else if (ts.isEnumDeclaration(node2)) {
11923
+ push(node2.name.text, "enum", node2.name.getStart(sourceFile));
11924
+ } else if (ts.isVariableDeclaration(node2) && ts.isIdentifier(node2.name)) {
11925
+ push(node2.name.text, "variable", node2.name.getStart(sourceFile));
11926
+ }
11927
+ ts.forEachChild(node2, visit2);
11928
+ };
11929
+ visit2(sourceFile);
11930
+ return out;
11931
+ }
11674
11932
  var PATTERNS = [
11675
- { re: /\b(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/g, kind: "function" },
11676
- { re: /\b(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/g, kind: "class" },
11677
- { re: /\b(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)/g, kind: "interface" },
11678
- { re: /\b(?:export\s+)?type\s+([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*=/g, kind: "type" },
11679
- { re: /\b(?:export\s+)?enum\s+([A-Za-z_$][\w$]*)/g, kind: "enum" },
11680
- { re: /\b(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?\s*=(?:\s*(?:async\s*)?\(|\s*(?:async\s+)?function\b)?/g, kind: "variable" },
11681
11933
  { re: /^\s*def\s+([A-Za-z_][\w]*)/gm, kind: "function" },
11682
11934
  { re: /^\s*class\s+([A-Za-z_][\w]*)/gm, kind: "class" },
11683
11935
  { re: /\bfunc\s+(?:\([^)]*\)\s*)?([A-Za-z_][\w]*)/g, kind: "function" },
11684
11936
  { re: /\bfn\s+([A-Za-z_][\w]*)/g, kind: "function" }
11685
11937
  ];
11938
+ function extractWithPatterns(path15, tree) {
11939
+ const content = tree.content;
11940
+ if (content === void 0 || content.length === 0)
11941
+ return [];
11942
+ const seen = /* @__PURE__ */ new Set();
11943
+ const out = [];
11944
+ for (const { re, kind } of PATTERNS) {
11945
+ re.lastIndex = 0;
11946
+ let match;
11947
+ while ((match = re.exec(content)) !== null) {
11948
+ const name = match[1];
11949
+ if (name === void 0)
11950
+ continue;
11951
+ const { line, column } = lineCol3(content, match.index);
11952
+ const key = `${name}|${kind}|${line}`;
11953
+ if (seen.has(key))
11954
+ continue;
11955
+ seen.add(key);
11956
+ out.push({
11957
+ name,
11958
+ kind,
11959
+ provenance: { file: path15, stage: "symbols", location: { line, column } }
11960
+ });
11961
+ }
11962
+ }
11963
+ return out;
11964
+ }
11686
11965
  function createSymbolExtractor() {
11687
11966
  return {
11688
- extract(path13, tree) {
11689
- const content = tree.content;
11690
- if (content === void 0 || content.length === 0)
11691
- return [];
11692
- const seen = /* @__PURE__ */ new Set();
11693
- const out = [];
11694
- for (const { re, kind } of PATTERNS) {
11695
- re.lastIndex = 0;
11696
- let match;
11697
- while ((match = re.exec(content)) !== null) {
11698
- const name = match[1];
11699
- if (name === void 0)
11700
- continue;
11701
- const { line, column } = lineCol3(content, match.index);
11702
- const key = `${name}|${kind}|${line}`;
11703
- if (seen.has(key))
11704
- continue;
11705
- seen.add(key);
11706
- out.push({
11707
- name,
11708
- kind,
11709
- provenance: { file: path13, stage: "symbols", location: { line, column } }
11710
- });
11711
- }
11712
- }
11713
- return out;
11967
+ extract(path15, tree) {
11968
+ return extractWithAst(path15, tree) ?? extractWithPatterns(path15, tree);
11714
11969
  }
11715
11970
  };
11716
11971
  }
@@ -11753,13 +12008,13 @@ function createScannerCache(_location) {
11753
12008
  // packages/scanner/dist/git/index.js
11754
12009
  import { execFile } from "node:child_process";
11755
12010
  import { existsSync } from "node:fs";
11756
- import path4 from "node:path";
12011
+ import path5 from "node:path";
11757
12012
  import { promisify } from "node:util";
11758
12013
  var execFileAsync = promisify(execFile);
11759
12014
  function createGitAnalyzer(projectRoot) {
11760
12015
  return {
11761
12016
  async analyze() {
11762
- if (!existsSync(path4.join(projectRoot, ".git"))) {
12017
+ if (!existsSync(path5.join(projectRoot, ".git"))) {
11763
12018
  return { isRepository: false, tracked: [] };
11764
12019
  }
11765
12020
  try {
@@ -11845,19 +12100,19 @@ function diffSnapshots(prev, next) {
11845
12100
  const modified = [];
11846
12101
  const unchanged = [];
11847
12102
  const removed = [];
11848
- for (const [path13, hash2] of next) {
11849
- const prevHash = prev.get(path13);
12103
+ for (const [path15, hash2] of next) {
12104
+ const prevHash = prev.get(path15);
11850
12105
  if (prevHash === void 0) {
11851
- added.push(path13);
12106
+ added.push(path15);
11852
12107
  } else if (prevHash !== hash2) {
11853
- modified.push(path13);
12108
+ modified.push(path15);
11854
12109
  } else {
11855
- unchanged.push(path13);
12110
+ unchanged.push(path15);
11856
12111
  }
11857
12112
  }
11858
- for (const path13 of prev.keys()) {
11859
- if (!next.has(path13)) {
11860
- removed.push(path13);
12113
+ for (const path15 of prev.keys()) {
12114
+ if (!next.has(path15)) {
12115
+ removed.push(path15);
11861
12116
  }
11862
12117
  }
11863
12118
  added.sort();
@@ -11877,7 +12132,7 @@ function toChangeSet(diff) {
11877
12132
 
11878
12133
  // packages/scanner/dist/hash/hash-cache.js
11879
12134
  import { readFile as readFile3, writeFile, mkdir, rename, unlink } from "node:fs/promises";
11880
- import path5 from "node:path";
12135
+ import path6 from "node:path";
11881
12136
  import os from "node:os";
11882
12137
  var CACHE_VERSION = 1;
11883
12138
  var CACHE_FILENAME = "hash-cache.json";
@@ -11902,7 +12157,7 @@ var HashCacheImpl = class {
11902
12157
  /** Absolute path to the cache file on disk. */
11903
12158
  _cacheFilePath;
11904
12159
  constructor(cacheDir, initialEntries) {
11905
- this._cacheFilePath = path5.join(cacheDir, CACHE_FILENAME);
12160
+ this._cacheFilePath = path6.join(cacheDir, CACHE_FILENAME);
11906
12161
  this._entries = initialEntries;
11907
12162
  }
11908
12163
  get size() {
@@ -11945,9 +12200,9 @@ var HashCacheImpl = class {
11945
12200
  }
11946
12201
  const store = { version: CACHE_VERSION, entries };
11947
12202
  const json2 = serialiseStore(store);
11948
- const cacheDir = path5.dirname(this._cacheFilePath);
12203
+ const cacheDir = path6.dirname(this._cacheFilePath);
11949
12204
  await mkdir(cacheDir, { recursive: true });
11950
- const tmpPath = path5.join(os.tmpdir(), `devos-hash-cache-${process.pid}-${Date.now()}.tmp`);
12205
+ const tmpPath = path6.join(os.tmpdir(), `devos-hash-cache-${process.pid}-${Date.now()}.tmp`);
11951
12206
  try {
11952
12207
  await writeFile(tmpPath, json2, "utf8");
11953
12208
  await rename(tmpPath, this._cacheFilePath);
@@ -11962,7 +12217,7 @@ var HashCacheImpl = class {
11962
12217
  }
11963
12218
  };
11964
12219
  async function loadHashCache(cacheDir) {
11965
- const cacheFilePath = path5.join(cacheDir, CACHE_FILENAME);
12220
+ const cacheFilePath = path6.join(cacheDir, CACHE_FILENAME);
11966
12221
  let raw = "";
11967
12222
  try {
11968
12223
  raw = await readFile3(cacheFilePath, "utf8");
@@ -11977,7 +12232,7 @@ async function loadHashCache(cacheDir) {
11977
12232
  }
11978
12233
 
11979
12234
  // packages/scanner/dist/hash/engine.js
11980
- import path6 from "node:path";
12235
+ import path7 from "node:path";
11981
12236
  import { stat as stat3 } from "node:fs/promises";
11982
12237
  function createSemaphore(limit) {
11983
12238
  let active = 0;
@@ -12003,23 +12258,23 @@ function createSemaphore(limit) {
12003
12258
  };
12004
12259
  }
12005
12260
  function toAbsolutePosix(projectRoot, relativePath) {
12006
- return path6.join(projectRoot, relativePath).split(path6.sep).join("/");
12261
+ return path7.join(projectRoot, relativePath).split(path7.sep).join("/");
12007
12262
  }
12008
12263
  async function runHashEngine(options) {
12009
- const { projectRoot, filePaths, cache, concurrency = 8, onProgress, chunkSizeBytes = 64 * 1024 } = options;
12264
+ const { projectRoot, filePaths, cache: cache2, concurrency = 8, onProgress, chunkSizeBytes = 64 * 1024 } = options;
12010
12265
  const diagnostics = [];
12011
12266
  const fileResults = [];
12012
12267
  const currentSnapshot = /* @__PURE__ */ new Map();
12013
12268
  let cacheHits = 0;
12014
12269
  let cacheMisses = 0;
12015
- const previousSnapshot = buildPreviousSnapshot(cache);
12270
+ const previousSnapshot = buildPreviousSnapshot(cache2);
12016
12271
  const sem = createSemaphore(concurrency);
12017
12272
  const total = filePaths.length;
12018
12273
  await Promise.all(filePaths.map(async (relativePath, index) => {
12019
12274
  await sem.acquire();
12020
12275
  try {
12021
12276
  const absolutePath = toAbsolutePosix(projectRoot, relativePath);
12022
- const result = await hashOneFile(absolutePath, relativePath, chunkSizeBytes, cache);
12277
+ const result = await hashOneFile(absolutePath, relativePath, chunkSizeBytes, cache2);
12023
12278
  if (result.kind === "ok") {
12024
12279
  fileResults.push(result.value);
12025
12280
  currentSnapshot.set(relativePath, result.value.hash);
@@ -12027,8 +12282,8 @@ async function runHashEngine(options) {
12027
12282
  cacheHits++;
12028
12283
  } else {
12029
12284
  cacheMisses++;
12030
- if (cache !== void 0) {
12031
- cache.set(relativePath, {
12285
+ if (cache2 !== void 0) {
12286
+ cache2.set(relativePath, {
12032
12287
  hash: result.value.hash,
12033
12288
  sizeBytes: result.value.sizeBytes,
12034
12289
  mtimeMs: result.value.mtimeMs
@@ -12057,9 +12312,9 @@ async function runHashEngine(options) {
12057
12312
  const ib = pathOrder.get(b.relativePath) ?? 0;
12058
12313
  return ia - ib;
12059
12314
  });
12060
- if (cache !== void 0) {
12315
+ if (cache2 !== void 0) {
12061
12316
  const activePaths = new Set(filePaths);
12062
- cache.prune(activePaths);
12317
+ cache2.prune(activePaths);
12063
12318
  }
12064
12319
  const snapshot = currentSnapshot;
12065
12320
  const diff = diffSnapshots(previousSnapshot, snapshot);
@@ -12075,8 +12330,8 @@ async function runHashEngine(options) {
12075
12330
  cacheMisses
12076
12331
  };
12077
12332
  }
12078
- async function hashOneFile(absolutePath, relativePath, chunkSizeBytes, cache) {
12079
- if (cache !== void 0) {
12333
+ async function hashOneFile(absolutePath, relativePath, chunkSizeBytes, cache2) {
12334
+ if (cache2 !== void 0) {
12080
12335
  let currentMtimeMs;
12081
12336
  try {
12082
12337
  const s = await stat3(absolutePath);
@@ -12089,7 +12344,7 @@ async function hashOneFile(absolutePath, relativePath, chunkSizeBytes, cache) {
12089
12344
  message: `Cannot stat file: ${relativePath} (${code})`
12090
12345
  };
12091
12346
  }
12092
- const cached2 = cache.get(relativePath, currentMtimeMs);
12347
+ const cached2 = cache2.get(relativePath, currentMtimeMs);
12093
12348
  if (cached2 !== void 0) {
12094
12349
  return {
12095
12350
  kind: "ok",
@@ -12116,12 +12371,12 @@ async function hashOneFile(absolutePath, relativePath, chunkSizeBytes, cache) {
12116
12371
  };
12117
12372
  }
12118
12373
  }
12119
- function buildPreviousSnapshot(cache) {
12120
- if (cache === void 0)
12374
+ function buildPreviousSnapshot(cache2) {
12375
+ if (cache2 === void 0)
12121
12376
  return /* @__PURE__ */ new Map();
12122
12377
  const previous = /* @__PURE__ */ new Map();
12123
- for (const [path13, entry] of cache.snapshotEntries()) {
12124
- previous.set(path13, entry.hash);
12378
+ for (const [path15, entry] of cache2.snapshotEntries()) {
12379
+ previous.set(path15, entry.hash);
12125
12380
  }
12126
12381
  return previous;
12127
12382
  }
@@ -12254,7 +12509,7 @@ async function discoverDependenciesFromManifests(files, projectRoot) {
12254
12509
  continue;
12255
12510
  let parsed;
12256
12511
  try {
12257
- const text2 = await readFile4(path7.join(projectRoot, file2.path), "utf8");
12512
+ const text2 = await readFile4(path8.join(projectRoot, file2.path), "utf8");
12258
12513
  parsed = JSON.parse(text2);
12259
12514
  } catch {
12260
12515
  continue;
@@ -12332,7 +12587,7 @@ var Scanner = class {
12332
12587
  const token = toCancellationToken(options.signal);
12333
12588
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
12334
12589
  const scanStart = this.deps.clock();
12335
- const root = path7.resolve(projectRoot);
12590
+ const root = path8.resolve(projectRoot);
12336
12591
  this.emit(listeners, { stage: "validate", phase: "start" });
12337
12592
  const validateStart = this.deps.clock();
12338
12593
  try {
@@ -12501,7 +12756,7 @@ var Scanner = class {
12501
12756
  async loadHashCache(root, options, diagnostics) {
12502
12757
  if (!options.incremental)
12503
12758
  return void 0;
12504
- const directory = path7.join(options.cacheLocation ?? path7.join(root, ".devos"), "hash-cache");
12759
+ const directory = path8.join(options.cacheLocation ?? path8.join(root, ".devos"), "hash-cache");
12505
12760
  try {
12506
12761
  return await this.deps.loadHashCache(directory);
12507
12762
  } catch (error62) {
@@ -12514,7 +12769,7 @@ var Scanner = class {
12514
12769
  const symbolExtractor = this.instantiate("symbols", diagnostics, () => this.deps.createSymbolExtractor(), NEUTRAL_SYMBOL_EXTRACTOR);
12515
12770
  const importBuilder = this.instantiate("graph", diagnostics, () => this.deps.createImportGraphBuilder(), NEUTRAL_IMPORT_BUILDER);
12516
12771
  const exportBuilder = this.instantiate("graph", diagnostics, () => this.deps.createExportGraphBuilder(), NEUTRAL_EXPORT_BUILDER);
12517
- const cacheLocation = path7.join(options.cacheLocation ?? path7.join(root, ".devos"), "facts");
12772
+ const cacheLocation = path8.join(options.cacheLocation ?? path8.join(root, ".devos"), "facts");
12518
12773
  const factCache = this.instantiate("graph", diagnostics, () => this.deps.createScannerCache(cacheLocation), NEUTRAL_SCANNER_CACHE);
12519
12774
  const analyzable = files.filter((file2) => (file2.classification === "source" || file2.classification === "test") && file2.language !== void 0);
12520
12775
  const toAnalyze = options.incremental ? analyzable.filter((file2) => changedPaths.has(file2.path)) : analyzable;
@@ -12568,7 +12823,9 @@ var Scanner = class {
12568
12823
  exportsOut.push(...cached2.facts.exports);
12569
12824
  }
12570
12825
  }
12571
- return { symbols: symbols2, imports, exports: exportsOut };
12826
+ const fileSet = new Set(files.map((file2) => String(file2.path)));
12827
+ const resolvedImports = resolveImportEdges(imports, fileSet, root);
12828
+ return { symbols: symbols2, imports: resolvedImports, exports: exportsOut };
12572
12829
  });
12573
12830
  }
12574
12831
  aggregate(files, directoryCount) {
@@ -12954,11 +13211,11 @@ async function runScan(targetPath, options, logger) {
12954
13211
  }
12955
13212
  }
12956
13213
  function resolveProjectRoot(targetPath) {
12957
- return path8.resolve(process.cwd(), targetPath);
13214
+ return path9.resolve(process.cwd(), targetPath);
12958
13215
  }
12959
13216
  function projectName(targetPath) {
12960
13217
  const resolved = resolveProjectRoot(targetPath);
12961
- return path8.basename(resolved) || resolved;
13218
+ return path9.basename(resolved) || resolved;
12962
13219
  }
12963
13220
  function buildScanOptions(options) {
12964
13221
  const scanOptions = {};
@@ -13190,7 +13447,8 @@ async function readScannerVersion() {
13190
13447
  }
13191
13448
 
13192
13449
  // apps/cli/dist/composition.js
13193
- import path10 from "node:path";
13450
+ import path11 from "node:path";
13451
+ import { readFile as readFile7 } from "node:fs/promises";
13194
13452
 
13195
13453
  // packages/kernel/dist/index.js
13196
13454
  function ok(value) {
@@ -13415,7 +13673,7 @@ var KnowledgeService = class {
13415
13673
  });
13416
13674
  }
13417
13675
  const factConfidence = confidence(0.95);
13418
- const fileNodeId = (path13) => nodeId(projectId, `file:${path13}`);
13676
+ const fileNodeId = (path15) => nodeId(projectId, `file:${path15}`);
13419
13677
  if (report.files !== void 0) {
13420
13678
  for (const file2 of [...report.files].sort((a, b) => a.path.localeCompare(b.path))) {
13421
13679
  const id = fileNodeId(file2.path);
@@ -220085,6 +220343,8 @@ function estimateTokens(text2) {
220085
220343
  }
220086
220344
  }
220087
220345
  var MAX_FACT_LINES = 120;
220346
+ var MAX_SNIPPET_FILES = 8;
220347
+ var SNIPPET_BUDGET_SHARE = 0.55;
220088
220348
  var ContextCompiler = class {
220089
220349
  #defaultTokenBudget;
220090
220350
  #knowledge;
@@ -220105,7 +220365,7 @@ ${request.task.trim()}`];
220105
220365
  if (this.#knowledge !== void 0) {
220106
220366
  const graph = await this.#knowledge.query({ projectId: request.projectId });
220107
220367
  if (!isErr(graph) && graph.value.nodes.length > 0) {
220108
- candidates.push(buildKnowledgeFragment(graph.value.nodes, request.task));
220368
+ candidates.push(await buildKnowledgeFragment(graph.value, request.task, request.readFile, budget));
220109
220369
  }
220110
220370
  }
220111
220371
  if (this.#memory !== void 0) {
@@ -220119,13 +220379,20 @@ ${request.task.trim()}`];
220119
220379
  }
220120
220380
  }
220121
220381
  const selected = [];
220122
- let runningTokens = 0;
220123
220382
  for (const fragment of candidates) {
220383
+ if (selected.length === 0) {
220384
+ selected.push(fragment);
220385
+ continue;
220386
+ }
220124
220387
  const projected = estimateTokens([...selected, fragment].join("\n\n"));
220125
- if (selected.length > 0 && projected > budget)
220388
+ if (projected <= budget) {
220389
+ selected.push(fragment);
220126
220390
  continue;
220127
- selected.push(fragment);
220128
- runningTokens = projected;
220391
+ }
220392
+ const remaining = budget - estimateTokens(selected.join("\n\n"));
220393
+ const trimmed = trimFragmentToBudget(fragment, remaining);
220394
+ if (trimmed !== void 0)
220395
+ selected.push(trimmed);
220129
220396
  }
220130
220397
  const content = selected.join("\n\n");
220131
220398
  const tokenEstimate = estimateTokens(content);
@@ -220140,10 +220407,29 @@ ${request.task.trim()}`];
220140
220407
  contextScore,
220141
220408
  secretsRedacted: true
220142
220409
  };
220143
- void runningTokens;
220144
220410
  return ok(pack);
220145
220411
  }
220146
220412
  };
220413
+ function trimFragmentToBudget(fragment, maxTokens) {
220414
+ if (maxTokens < 40)
220415
+ return void 0;
220416
+ const marker = "\u2026 (trimmed to the token budget)";
220417
+ const lines = fragment.split("\n");
220418
+ const kept = [];
220419
+ let used = estimateTokens(marker) + 1;
220420
+ for (const line of lines) {
220421
+ const cost = estimateTokens(line) + 1;
220422
+ if (used + cost > maxTokens)
220423
+ break;
220424
+ kept.push(line);
220425
+ used += cost;
220426
+ }
220427
+ if (kept.length === 0)
220428
+ return void 0;
220429
+ if (kept.length < lines.length)
220430
+ kept.push(marker);
220431
+ return kept.join("\n");
220432
+ }
220147
220433
  function byConfidenceThenLabel(a, b) {
220148
220434
  if (b.confidence !== a.confidence)
220149
220435
  return b.confidence - a.confidence;
@@ -220156,8 +220442,16 @@ function clamp01(value) {
220156
220442
  return 1;
220157
220443
  return value;
220158
220444
  }
220159
- function buildKnowledgeFragment(nodes, task) {
220160
- const terms = task.toLowerCase().split(/[^a-z0-9_]+/).filter((term) => term.length >= 3);
220445
+ function taskTerms(task) {
220446
+ return task.toLowerCase().split(/[^a-z0-9_]+/).filter((term) => term.length >= 3);
220447
+ }
220448
+ function symbolFile(label) {
220449
+ const marker = label.lastIndexOf(" in ");
220450
+ return marker === -1 ? void 0 : label.slice(marker + 4);
220451
+ }
220452
+ async function buildKnowledgeFragment(graph, task, readFile10, budget) {
220453
+ const nodes = graph.nodes;
220454
+ const terms = taskTerms(task);
220161
220455
  const relevance2 = (node2) => {
220162
220456
  const label = node2.label.toLowerCase();
220163
220457
  let score = 0;
@@ -220181,8 +220475,126 @@ function buildKnowledgeFragment(nodes, task) {
220181
220475
  ...[...structural].sort(byConfidenceThenLabel).map((node2) => `- (${node2.kind}) ${node2.label} \xB7 confidence ${node2.confidence.toFixed(2)}`),
220182
220476
  ...shown.map((node2) => `- (${node2.kind}) ${node2.label} \xB7 confidence ${node2.confidence.toFixed(2)}`)
220183
220477
  ];
220478
+ if (readFile10 !== void 0) {
220479
+ const excerpts = await buildExcerpts(graph, terms, readFile10, budget);
220480
+ if (excerpts.length > 0)
220481
+ lines.push("", "## Code excerpts", ...excerpts);
220482
+ }
220184
220483
  return lines.join("\n");
220185
220484
  }
220485
+ async function buildExcerpts(graph, terms, readFile10, budget) {
220486
+ const byId = new Map(graph.nodes.map((node2) => [node2.id, node2]));
220487
+ const fileNodes = graph.nodes.filter((node2) => node2.kind === "file");
220488
+ if (fileNodes.length === 0)
220489
+ return [];
220490
+ const symbolNamesByFile = /* @__PURE__ */ new Map();
220491
+ for (const node2 of graph.nodes) {
220492
+ if (node2.kind !== "symbol")
220493
+ continue;
220494
+ const file2 = symbolFile(node2.label);
220495
+ if (file2 === void 0)
220496
+ continue;
220497
+ const name = node2.label.split(" (")[0] ?? node2.label;
220498
+ const list = symbolNamesByFile.get(file2) ?? [];
220499
+ list.push(name);
220500
+ symbolNamesByFile.set(file2, list);
220501
+ }
220502
+ const score = (node2) => {
220503
+ const label = node2.label.toLowerCase();
220504
+ let value = 0;
220505
+ for (const term of terms)
220506
+ if (label.includes(term))
220507
+ value += 2;
220508
+ for (const name of symbolNamesByFile.get(node2.label) ?? []) {
220509
+ const lower = name.toLowerCase();
220510
+ for (const term of terms)
220511
+ if (lower.includes(term))
220512
+ value += 1;
220513
+ }
220514
+ return value;
220515
+ };
220516
+ const ranked = [...fileNodes].sort((a, b) => {
220517
+ const byScore = score(b) - score(a);
220518
+ if (byScore !== 0)
220519
+ return byScore;
220520
+ return byConfidenceThenLabel(a, b);
220521
+ });
220522
+ const primaries = ranked.filter((node2) => score(node2) > 0).slice(0, 5);
220523
+ const chosen = primaries.length > 0 ? primaries : ranked.slice().sort((a, b) => (symbolNamesByFile.get(b.label)?.length ?? 0) - (symbolNamesByFile.get(a.label)?.length ?? 0)).slice(0, 2);
220524
+ const chosenIds = new Set(chosen.map((node2) => node2.id));
220525
+ for (const rel of graph.relationships) {
220526
+ if (chosen.length >= MAX_SNIPPET_FILES)
220527
+ break;
220528
+ if (rel.kind !== "imports")
220529
+ continue;
220530
+ const otherId = chosenIds.has(rel.from) ? rel.to : chosenIds.has(rel.to) ? rel.from : void 0;
220531
+ if (otherId === void 0 || chosenIds.has(otherId))
220532
+ continue;
220533
+ const other = byId.get(otherId);
220534
+ if (other !== void 0 && other.kind === "file") {
220535
+ chosen.push(other);
220536
+ chosenIds.add(other.id);
220537
+ }
220538
+ }
220539
+ const snippetBudget = Math.max(200, Math.floor(budget * SNIPPET_BUDGET_SHARE));
220540
+ const perFile = Math.max(80, Math.floor(snippetBudget / Math.max(1, chosen.length)));
220541
+ const excerpts = [];
220542
+ for (const node2 of chosen) {
220543
+ const content = await readFile10(node2.label);
220544
+ if (content === void 0 || content.length === 0)
220545
+ continue;
220546
+ const excerpt = excerptFor(content, terms, symbolNamesByFile.get(node2.label) ?? [], perFile);
220547
+ if (excerpt !== void 0)
220548
+ excerpts.push(`### ${node2.label}
220549
+ \`\`\`
220550
+ ${excerpt}
220551
+ \`\`\``);
220552
+ }
220553
+ return excerpts;
220554
+ }
220555
+ function excerptFor(content, terms, symbolNames, maxTokens) {
220556
+ const lines = content.split("\n");
220557
+ const needles = [...terms, ...symbolNames.map((name) => name.toLowerCase())].filter((needle) => needle.length >= 3);
220558
+ const matchLines = /* @__PURE__ */ new Set();
220559
+ lines.forEach((line, index) => {
220560
+ const lower = line.toLowerCase();
220561
+ if (needles.some((needle) => lower.includes(needle)))
220562
+ matchLines.add(index);
220563
+ });
220564
+ const windows = [];
220565
+ if (matchLines.size === 0) {
220566
+ windows.push([0, Math.min(lines.length, 30)]);
220567
+ } else {
220568
+ const sorted = [...matchLines].sort((a, b) => a - b).slice(0, 6);
220569
+ for (const index of sorted) {
220570
+ const start = Math.max(0, index - 6);
220571
+ const end = Math.min(lines.length, index + 7);
220572
+ const last = windows[windows.length - 1];
220573
+ if (last !== void 0 && start <= last[1]) {
220574
+ windows[windows.length - 1] = [last[0], Math.max(last[1], end)];
220575
+ } else {
220576
+ windows.push([start, end]);
220577
+ }
220578
+ }
220579
+ }
220580
+ const out = [];
220581
+ let used = 0;
220582
+ for (const [start, end] of windows) {
220583
+ if (out.length > 0) {
220584
+ out.push("// \u2026");
220585
+ used += 2;
220586
+ }
220587
+ for (let i = start; i < end; i += 1) {
220588
+ const line = lines[i] ?? "";
220589
+ const cost = estimateTokens(line) + 1;
220590
+ if (used + cost > maxTokens)
220591
+ return out.length > 0 ? out.join("\n") : void 0;
220592
+ out.push(line);
220593
+ used += cost;
220594
+ }
220595
+ }
220596
+ return out.length > 0 ? out.join("\n") : void 0;
220597
+ }
220186
220598
 
220187
220599
  // packages/provider-router/dist/index.js
220188
220600
  var ProviderRouter = class {
@@ -220222,15 +220634,68 @@ function pickByPolicy(providers, policy) {
220222
220634
 
220223
220635
  // packages/security/dist/index.js
220224
220636
  var SECRET_PATTERNS = [
220225
- /\b(?:sk|pk|rk)-[A-Za-z0-9]{16,}\b/g,
220226
- // provider-style keys
220227
- /\bghp_[A-Za-z0-9]{20,}\b/g,
220228
- // GitHub tokens
220637
+ // PEM private keys — the whole block, header to footer.
220638
+ /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----/g,
220639
+ // JSON Web Tokens (three base64url segments, header starts with eyJ).
220640
+ /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,
220641
+ // Connection strings with an embedded password: scheme://user:pass@host.
220642
+ /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss|amqp|amqps):\/\/[^\s/:@]+:[^\s/@]+@[^\s/]+/g,
220643
+ // Authorization bearer values.
220644
+ /(?<=\bBearer\s+)[A-Za-z0-9._~+/=-]{10,}/gi,
220645
+ // Provider token shapes.
220646
+ /\b(?:sk|pk|rk)-(?:live|test|proj)?-?[A-Za-z0-9_-]{16,}\b/g,
220647
+ // Stripe / OpenAI-style keys
220648
+ /\bgh[pousr]_[A-Za-z0-9]{20,}\b/g,
220649
+ // GitHub classic tokens
220650
+ /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,
220651
+ // GitHub fine-grained PATs
220229
220652
  /\bAKIA[0-9A-Z]{16}\b/g,
220230
220653
  // AWS access key ids
220231
- /(?<=(?:password|secret|token|api[_-]?key)\s*[:=]\s*)\S+/gi
220232
- // key: value
220654
+ /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,
220655
+ // Slack tokens
220656
+ /\bAIza[A-Za-z0-9_-]{35,}/g,
220657
+ // Google API keys
220658
+ /\bnpm_[A-Za-z0-9]{36}\b/g,
220659
+ // npm tokens
220660
+ /\bglpat-[A-Za-z0-9_-]{20,}\b/g,
220661
+ // GitLab PATs
220662
+ // Generic key: value assignments (password/secret/token/api-key/...).
220663
+ /(?<=(?:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|auth)\s*[:=]\s*)["']?\S+["']?/gi
220233
220664
  ];
220665
+ var QUOTED_TOKEN = /["'`]([^\s"'`]{24,})["'`]/g;
220666
+ function shannonEntropy(value) {
220667
+ const counts = /* @__PURE__ */ new Map();
220668
+ for (const ch of value)
220669
+ counts.set(ch, (counts.get(ch) ?? 0) + 1);
220670
+ let entropy = 0;
220671
+ for (const count of counts.values()) {
220672
+ const p = count / value.length;
220673
+ entropy -= p * Math.log2(p);
220674
+ }
220675
+ return entropy;
220676
+ }
220677
+ function characterClasses(value) {
220678
+ let classes = 0;
220679
+ if (/[a-z]/.test(value))
220680
+ classes += 1;
220681
+ if (/[A-Z]/.test(value))
220682
+ classes += 1;
220683
+ if (/[0-9]/.test(value))
220684
+ classes += 1;
220685
+ if (/[^A-Za-z0-9]/.test(value))
220686
+ classes += 1;
220687
+ return classes;
220688
+ }
220689
+ function redactHighEntropyTokens(text2) {
220690
+ return text2.replace(QUOTED_TOKEN, (whole, token) => {
220691
+ if (token.includes("://"))
220692
+ return whole;
220693
+ if (characterClasses(token) >= 3 && shannonEntropy(token) >= 4.2) {
220694
+ return whole.replace(token, "[REDACTED]");
220695
+ }
220696
+ return whole;
220697
+ });
220698
+ }
220234
220699
  var HIGH_RISK = ["delete", "rm -rf", "drop", "force push", "credential"];
220235
220700
  var MEDIUM_RISK = ["write", "overwrite", "push", "publish", "install"];
220236
220701
  var SecurityEngine = class {
@@ -220239,6 +220704,7 @@ var SecurityEngine = class {
220239
220704
  for (const pattern of SECRET_PATTERNS) {
220240
220705
  redacted = redacted.replace(pattern, "[REDACTED]");
220241
220706
  }
220707
+ redacted = redactHighEntropyTokens(redacted);
220242
220708
  return Promise.resolve(ok(redacted));
220243
220709
  }
220244
220710
  assessRisk(action) {
@@ -220266,7 +220732,7 @@ var SecurityEngine = class {
220266
220732
 
220267
220733
  // packages/storage/dist/index.js
220268
220734
  import { mkdir as mkdir2, readFile as readFile6, readdir as readdir2, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
220269
- import path9 from "node:path";
220735
+ import path10 from "node:path";
220270
220736
  function digestOf(text2) {
220271
220737
  let hash2 = 2166136261;
220272
220738
  for (let index = 0; index < text2.length; index += 1) {
@@ -220331,7 +220797,7 @@ var FileStorage = class {
220331
220797
  return ok(keys);
220332
220798
  }
220333
220799
  #fileFor(key) {
220334
- return path9.join(this.#dir, `${encodeURIComponent(key)}.json`);
220800
+ return path10.join(this.#dir, `${encodeURIComponent(key)}.json`);
220335
220801
  }
220336
220802
  };
220337
220803
 
@@ -220622,7 +221088,7 @@ function storageDirectory() {
220622
221088
  const override2 = process.env["DEVOS_STORAGE_DIR"];
220623
221089
  if (override2 !== void 0 && override2.trim().length > 0)
220624
221090
  return override2;
220625
- return path10.join(process.cwd(), ".devos", "storage");
221091
+ return path11.join(process.cwd(), ".devos", "storage");
220626
221092
  }
220627
221093
  function createConfiguredProvider() {
220628
221094
  const apiKey = process.env["OPENAI_API_KEY"];
@@ -220672,6 +221138,35 @@ function routingMetaFor(adapter) {
220672
221138
  return ROUTING_META.gemini;
220673
221139
  return ROUTING_META.openai;
220674
221140
  }
221141
+ function createProjectFileReader(root) {
221142
+ const base = path11.resolve(root);
221143
+ return async (relativePath) => {
221144
+ const resolved = path11.resolve(base, relativePath);
221145
+ if (resolved !== base && !resolved.startsWith(base + path11.sep))
221146
+ return void 0;
221147
+ try {
221148
+ return await readFile7(resolved, "utf8");
221149
+ } catch {
221150
+ return void 0;
221151
+ }
221152
+ };
221153
+ }
221154
+ async function sendWithRouting(engine, pack) {
221155
+ const adapters = createConfiguredProviders();
221156
+ if (adapters.length === 0)
221157
+ return void 0;
221158
+ const decision = await engine.dependencies.providerRouter.route({
221159
+ capability: "completion",
221160
+ pack
221161
+ });
221162
+ if (isErr(decision))
221163
+ return void 0;
221164
+ const adapter = adapters.find((a) => a.describe().id === decision.value.providerId) ?? adapters[0];
221165
+ if (adapter === void 0)
221166
+ return void 0;
221167
+ const sent = await adapter.send({ capability: "completion", pack });
221168
+ return isErr(sent) ? void 0 : sent.value;
221169
+ }
220675
221170
  function buildEngine() {
220676
221171
  const scanner = new ScannerAdapter();
220677
221172
  const knowledge = new KnowledgeService();
@@ -220881,10 +221376,70 @@ function registerVersionCommand(program2) {
220881
221376
  }
220882
221377
 
220883
221378
  // apps/cli/dist/commands/project-id.js
221379
+ import { execFile as execFile3 } from "node:child_process";
221380
+ import { createHash as createHash2 } from "node:crypto";
221381
+ import { mkdir as mkdir3, readFile as readFile8, writeFile as writeFile3 } from "node:fs/promises";
221382
+ import path12 from "node:path";
221383
+ import { promisify as promisify3 } from "node:util";
221384
+ var execFileAsync3 = promisify3(execFile3);
220884
221385
  function stableProjectId(fingerprint) {
220885
221386
  const clean = fingerprint.replace(/[^A-Za-z0-9]/g, "").slice(0, 24);
220886
221387
  return `project_${clean}`;
220887
221388
  }
221389
+ function idFromSeed(seed) {
221390
+ const digest = createHash2("sha256").update(seed).digest("hex").slice(0, 24);
221391
+ return `project_${digest}`;
221392
+ }
221393
+ async function gitRemote(rootPath) {
221394
+ try {
221395
+ const { stdout } = await execFileAsync3("git", ["-C", rootPath, "remote", "get-url", "origin"], { timeout: 3e3 });
221396
+ const url2 = stdout.trim();
221397
+ return url2.length > 0 ? url2 : void 0;
221398
+ } catch {
221399
+ return void 0;
221400
+ }
221401
+ }
221402
+ async function resolveProjectId(rootPath) {
221403
+ const idFile = path12.join(rootPath, ".devos", "project.json");
221404
+ try {
221405
+ const parsed = JSON.parse(await readFile8(idFile, "utf8"));
221406
+ if (typeof parsed.id === "string" && parsed.id.startsWith("project_")) {
221407
+ return parsed.id;
221408
+ }
221409
+ } catch {
221410
+ }
221411
+ const remote = await gitRemote(rootPath);
221412
+ const seed = remote !== void 0 ? `remote:${remote}` : `path:${path12.resolve(rootPath)}`;
221413
+ const id = idFromSeed(seed);
221414
+ try {
221415
+ await mkdir3(path12.dirname(idFile), { recursive: true });
221416
+ const record2 = { id, version: 1, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
221417
+ await writeFile3(idFile, `${JSON.stringify(record2, null, 2)}
221418
+ `, "utf8");
221419
+ } catch {
221420
+ }
221421
+ return id;
221422
+ }
221423
+ async function migrateLegacyMemory(storage, legacyId, stableId) {
221424
+ if (legacyId === stableId)
221425
+ return;
221426
+ try {
221427
+ const existing = await storage.load(`memory:${stableId}`);
221428
+ if (!isErr(existing) && existing.value.value.length > 0)
221429
+ return;
221430
+ const legacy = await storage.load(`memory:${legacyId}`);
221431
+ if (isErr(legacy) || legacy.value.value.length === 0)
221432
+ return;
221433
+ const moved = legacy.value.value.map((record2) => ({ ...record2, projectId: stableId }));
221434
+ await storage.save(`memory:${stableId}`, moved);
221435
+ } catch {
221436
+ }
221437
+ }
221438
+ async function resolveProjectIdWithMigration(rootPath, fingerprint, storage) {
221439
+ const id = await resolveProjectId(rootPath);
221440
+ await migrateLegacyMemory(storage, stableProjectId(fingerprint), id);
221441
+ return id;
221442
+ }
220888
221443
 
220889
221444
  // apps/cli/dist/commands/ask.js
220890
221445
  function registerAskCommand(program2, logger) {
@@ -220895,7 +221450,7 @@ function registerAskCommand(program2, logger) {
220895
221450
  throw new CliError(understood.error.message, EXIT.ERROR);
220896
221451
  }
220897
221452
  const report = understood.value;
220898
- const projectId = stableProjectId(report.fingerprint);
221453
+ const projectId = await resolveProjectIdWithMigration(targetPath, report.fingerprint, engine.dependencies.storage);
220899
221454
  const stableReport = {
220900
221455
  ...report,
220901
221456
  project: { ...report.project, id: projectId }
@@ -220908,6 +221463,7 @@ function registerAskCommand(program2, logger) {
220908
221463
  const compiled = await engine.compileContext({
220909
221464
  projectId,
220910
221465
  task,
221466
+ readFile: createProjectFileReader(targetPath),
220911
221467
  ...budget !== void 0 && Number.isFinite(budget) ? { tokenBudget: budget } : {}
220912
221468
  });
220913
221469
  if (isErr(compiled)) {
@@ -220918,16 +221474,7 @@ function registerAskCommand(program2, logger) {
220918
221474
  capability: "completion",
220919
221475
  pack
220920
221476
  });
220921
- const adapters = createConfiguredProviders();
220922
- const adapter = isErr(decision) ? adapters[0] : adapters.find((a) => a.describe().id === decision.value.providerId) ?? adapters[0];
220923
- let answer;
220924
- if (!isErr(decision) && adapter !== void 0) {
220925
- const sent = await adapter.send({ capability: "completion", pack });
220926
- if (isErr(sent)) {
220927
- throw new CliError(`Provider call failed: ${sent.error.message}`, EXIT.ERROR);
220928
- }
220929
- answer = sent.value;
220930
- }
221477
+ const answer = await sendWithRouting(engine, pack);
220931
221478
  if (options.json === true) {
220932
221479
  process.stdout.write(`${JSON.stringify({
220933
221480
  project: stableReport.project,
@@ -220962,8 +221509,8 @@ function registerMemoryCommands(program2, logger) {
220962
221509
  const parsed = Number.parseFloat(options.confidence ?? "0.9");
220963
221510
  const level = Number.isFinite(parsed) ? Math.min(1, Math.max(0, parsed)) : 0.9;
220964
221511
  const result = await runScan(targetPath, {}, logger);
220965
- const projectId = stableProjectId(String(result.projectFingerprint.hash));
220966
221512
  const engine = buildEngine();
221513
+ const projectId = await resolveProjectIdWithMigration(targetPath, String(result.projectFingerprint.hash), engine.dependencies.storage);
220967
221514
  const saved = await engine.dependencies.memory.remember({
220968
221515
  projectId,
220969
221516
  record: {
@@ -220983,8 +221530,8 @@ function registerMemoryCommands(program2, logger) {
220983
221530
  });
220984
221531
  program2.command("recall").description("Recall notes from the project's persistent memory").argument("<path>", "path to the project root").argument("[query]", "optional search words").option("--json", "emit the records as JSON on stdout").action(async (targetPath, query, options) => {
220985
221532
  const result = await runScan(targetPath, {}, logger);
220986
- const projectId = stableProjectId(String(result.projectFingerprint.hash));
220987
221533
  const engine = buildEngine();
221534
+ const projectId = await resolveProjectIdWithMigration(targetPath, String(result.projectFingerprint.hash), engine.dependencies.storage);
220988
221535
  const recalled = await engine.dependencies.memory.recall({
220989
221536
  projectId,
220990
221537
  ...query !== void 0 ? { query } : {}
@@ -221009,7 +221556,7 @@ function registerMemoryCommands(program2, logger) {
221009
221556
  }
221010
221557
 
221011
221558
  // apps/cli/dist/commands/pack.js
221012
- import { writeFile as writeFile3 } from "node:fs/promises";
221559
+ import { writeFile as writeFile4 } from "node:fs/promises";
221013
221560
  function registerPackCommand(program2, logger) {
221014
221561
  program2.command("pack").description("Pack the project's knowledge graph + memory into one AI-ready file").argument("<path>", "path to the project root").option("--out <file>", "write to a file instead of stdout").option("--format <fmt>", "markdown | xml", "markdown").option("--budget <n>", "max tokens for the symbol listing", "6000").action(async (targetPath, options) => {
221015
221562
  const engine = buildEngine();
@@ -221017,7 +221564,7 @@ function registerPackCommand(program2, logger) {
221017
221564
  if (isErr(understood))
221018
221565
  throw new CliError(understood.error.message, EXIT.ERROR);
221019
221566
  const report = understood.value;
221020
- const projectId = stableProjectId(report.fingerprint);
221567
+ const projectId = await resolveProjectIdWithMigration(targetPath, report.fingerprint, engine.dependencies.storage);
221021
221568
  const stableReport = { ...report, project: { ...report.project, id: projectId } };
221022
221569
  const built = await engine.dependencies.knowledge.build(stableReport);
221023
221570
  if (isErr(built))
@@ -221049,7 +221596,7 @@ function registerPackCommand(program2, logger) {
221049
221596
  });
221050
221597
  const tokens = encode(doc).length;
221051
221598
  if (options.out !== void 0) {
221052
- await writeFile3(options.out, doc, "utf8");
221599
+ await writeFile4(options.out, doc, "utf8");
221053
221600
  logger.info(`Packed ${color.bold(report.project.name)}: ${files.length} files, ${symbols2.length} symbols, ${importEdges.length} imports, ~${tokens} tokens -> ${options.out}`);
221054
221601
  } else {
221055
221602
  process.stdout.write(doc);
@@ -221555,8 +222102,8 @@ function getErrorMap() {
221555
222102
 
221556
222103
  // node_modules/zod/v3/helpers/parseUtil.js
221557
222104
  var makeIssue = (params) => {
221558
- const { data, path: path13, errorMaps, issueData } = params;
221559
- const fullPath = [...path13, ...issueData.path || []];
222105
+ const { data, path: path15, errorMaps, issueData } = params;
222106
+ const fullPath = [...path15, ...issueData.path || []];
221560
222107
  const fullIssue = {
221561
222108
  ...issueData,
221562
222109
  path: fullPath
@@ -221671,11 +222218,11 @@ var errorUtil;
221671
222218
 
221672
222219
  // node_modules/zod/v3/types.js
221673
222220
  var ParseInputLazyPath = class {
221674
- constructor(parent, value, path13, key) {
222221
+ constructor(parent, value, path15, key) {
221675
222222
  this._cachedPath = [];
221676
222223
  this.parent = parent;
221677
222224
  this.data = value;
221678
- this._path = path13;
222225
+ this._path = path15;
221679
222226
  this._key = key;
221680
222227
  }
221681
222228
  get path() {
@@ -225630,10 +226177,10 @@ function mergeDefs(...defs) {
225630
226177
  function cloneDef(schema) {
225631
226178
  return mergeDefs(schema._zod.def);
225632
226179
  }
225633
- function getElementAtPath(obj, path13) {
225634
- if (!path13)
226180
+ function getElementAtPath(obj, path15) {
226181
+ if (!path15)
225635
226182
  return obj;
225636
- return path13.reduce((acc, key) => acc?.[key], obj);
226183
+ return path15.reduce((acc, key) => acc?.[key], obj);
225637
226184
  }
225638
226185
  function promiseAllObject(promisesObj) {
225639
226186
  const keys = Object.keys(promisesObj);
@@ -225973,11 +226520,11 @@ function explicitlyAborted(x, startIndex = 0) {
225973
226520
  }
225974
226521
  return false;
225975
226522
  }
225976
- function prefixIssues(path13, issues) {
226523
+ function prefixIssues(path15, issues) {
225977
226524
  return issues.map((iss) => {
225978
226525
  var _a3;
225979
226526
  (_a3 = iss).path ?? (_a3.path = []);
225980
- iss.path.unshift(path13);
226527
+ iss.path.unshift(path15);
225981
226528
  return iss;
225982
226529
  });
225983
226530
  }
@@ -226439,16 +226986,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
226439
226986
  }
226440
226987
  function formatError(error62, mapper = (issue2) => issue2.message) {
226441
226988
  const fieldErrors = { _errors: [] };
226442
- const processError = (error63, path13 = []) => {
226989
+ const processError = (error63, path15 = []) => {
226443
226990
  for (const issue2 of error63.issues) {
226444
226991
  if (issue2.code === "invalid_union" && issue2.errors.length) {
226445
- issue2.errors.map((issues) => processError({ issues }, [...path13, ...issue2.path]));
226992
+ issue2.errors.map((issues) => processError({ issues }, [...path15, ...issue2.path]));
226446
226993
  } else if (issue2.code === "invalid_key") {
226447
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
226994
+ processError({ issues: issue2.issues }, [...path15, ...issue2.path]);
226448
226995
  } else if (issue2.code === "invalid_element") {
226449
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
226996
+ processError({ issues: issue2.issues }, [...path15, ...issue2.path]);
226450
226997
  } else {
226451
- const fullpath = [...path13, ...issue2.path];
226998
+ const fullpath = [...path15, ...issue2.path];
226452
226999
  if (fullpath.length === 0) {
226453
227000
  fieldErrors._errors.push(mapper(issue2));
226454
227001
  } else {
@@ -226487,17 +227034,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
226487
227034
  }
226488
227035
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
226489
227036
  const result = { errors: [] };
226490
- const processError = (error63, path13 = []) => {
227037
+ const processError = (error63, path15 = []) => {
226491
227038
  var _a3;
226492
227039
  for (const issue2 of error63.issues) {
226493
227040
  if (issue2.code === "invalid_union" && issue2.errors.length) {
226494
- issue2.errors.map((issues) => processError({ issues }, [...path13, ...issue2.path]));
227041
+ issue2.errors.map((issues) => processError({ issues }, [...path15, ...issue2.path]));
226495
227042
  } else if (issue2.code === "invalid_key") {
226496
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
227043
+ processError({ issues: issue2.issues }, [...path15, ...issue2.path]);
226497
227044
  } else if (issue2.code === "invalid_element") {
226498
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
227045
+ processError({ issues: issue2.issues }, [...path15, ...issue2.path]);
226499
227046
  } else {
226500
- const fullpath = [...path13, ...issue2.path];
227047
+ const fullpath = [...path15, ...issue2.path];
226501
227048
  if (fullpath.length === 0) {
226502
227049
  result.errors.push(mapper(issue2));
226503
227050
  continue;
@@ -226536,8 +227083,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
226536
227083
  }
226537
227084
  function toDotPath(_path) {
226538
227085
  const segs = [];
226539
- const path13 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
226540
- for (const seg of path13) {
227086
+ const path15 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
227087
+ for (const seg of path15) {
226541
227088
  if (typeof seg === "number")
226542
227089
  segs.push(`[${seg}]`);
226543
227090
  else if (typeof seg === "symbol")
@@ -241856,21 +242403,21 @@ function visit(schema, fnOrHandlers) {
241856
242403
  const h = fnOrHandlers[node2._zod.def.type];
241857
242404
  return h ? h(node2, rewritten) : node2;
241858
242405
  };
241859
- const cache = /* @__PURE__ */ new Map();
242406
+ const cache2 = /* @__PURE__ */ new Map();
241860
242407
  function run(s) {
241861
- const cached2 = cache.get(s);
242408
+ const cached2 = cache2.get(s);
241862
242409
  if (cached2 === RESOLVING) {
241863
242410
  return new $ZodLazy({
241864
242411
  type: "lazy",
241865
- getter: () => cache.get(s)
242412
+ getter: () => cache2.get(s)
241866
242413
  });
241867
242414
  }
241868
242415
  if (cached2 !== void 0)
241869
242416
  return cached2;
241870
- cache.set(s, RESOLVING);
242417
+ cache2.set(s, RESOLVING);
241871
242418
  const inner = mapInner(s);
241872
242419
  const mapped = fn(inner, inner !== s);
241873
- cache.set(s, mapped);
242420
+ cache2.set(s, mapped);
241874
242421
  return mapped;
241875
242422
  }
241876
242423
  function mapInner(s) {
@@ -242088,11 +242635,11 @@ function normalizeObjectSchema(schema) {
242088
242635
  }
242089
242636
  return void 0;
242090
242637
  }
242091
- function getDotPath(path13) {
242092
- if (path13.length === 0) {
242638
+ function getDotPath(path15) {
242639
+ if (path15.length === 0) {
242093
242640
  return "object root";
242094
242641
  }
242095
- return path13.reduce((acc, seg, index) => {
242642
+ return path15.reduce((acc, seg, index) => {
242096
242643
  if (index === 0) {
242097
242644
  return String(seg);
242098
242645
  }
@@ -244319,13 +244866,13 @@ function resolveRef(ref, ctx) {
244319
244866
  if (!ref.startsWith("#")) {
244320
244867
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
244321
244868
  }
244322
- const path13 = ref.slice(1).split("/").filter(Boolean);
244323
- if (path13.length === 0) {
244869
+ const path15 = ref.slice(1).split("/").filter(Boolean);
244870
+ if (path15.length === 0) {
244324
244871
  return ctx.rootSchema;
244325
244872
  }
244326
244873
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
244327
- if (path13[0] === defsKey) {
244328
- const key = path13[1] === void 0 ? void 0 : decodeJSONPointerSegment(path13[1]);
244874
+ if (path15[0] === defsKey) {
244875
+ const key = path15[1] === void 0 ? void 0 : decodeJSONPointerSegment(path15[1]);
244329
244876
  if (!key || !ctx.defs[key]) {
244330
244877
  throw new Error(`Reference not found: ${ref}`);
244331
244878
  }
@@ -250581,12 +251128,12 @@ var StdioServerTransport = class {
250581
251128
  };
250582
251129
 
250583
251130
  // apps/cli/dist/commands/mcp.js
250584
- async function projectContext(engine, path13) {
250585
- const understood = await engine.understand(path13);
251131
+ async function projectContext(engine, path15) {
251132
+ const understood = await engine.understand(path15);
250586
251133
  if (isErr(understood))
250587
251134
  throw new Error(understood.error.message);
250588
251135
  const report = understood.value;
250589
- const projectId = stableProjectId(report.fingerprint);
251136
+ const projectId = await resolveProjectIdWithMigration(path15, report.fingerprint, engine.dependencies.storage);
250590
251137
  const stableReport = { ...report, project: { ...report.project, id: projectId } };
250591
251138
  const built = await engine.dependencies.knowledge.build(stableReport);
250592
251139
  if (isErr(built))
@@ -250610,8 +251157,8 @@ function registerMcpCommand(program2, _logger) {
250610
251157
  server.registerTool("devos_scan", {
250611
251158
  description: "Deterministically scan a project: files, languages, frameworks, dependencies, fingerprint.",
250612
251159
  inputSchema: { path: external_exports.string() }
250613
- }, async ({ path: path13 }) => {
250614
- const { report, graph } = await projectContext(engine, path13);
251160
+ }, async ({ path: path15 }) => {
251161
+ const { report, graph } = await projectContext(engine, path15);
250615
251162
  return text({
250616
251163
  name: report.project.name,
250617
251164
  fingerprint: report.fingerprint,
@@ -250625,8 +251172,8 @@ function registerMcpCommand(program2, _logger) {
250625
251172
  server.registerTool("devos_pack", {
250626
251173
  description: "Return the project's smart knowledge pack (files, symbols, imports, dependencies, memory) as markdown.",
250627
251174
  inputSchema: { path: external_exports.string() }
250628
- }, async ({ path: path13 }) => {
250629
- const { report, projectId, graph } = await projectContext(engine, path13);
251175
+ }, async ({ path: path15 }) => {
251176
+ const { report, projectId, graph } = await projectContext(engine, path15);
250630
251177
  const recalled = await engine.dependencies.memory.recall({ projectId });
250631
251178
  const memories = isErr(recalled) ? [] : recalled.value;
250632
251179
  const lines = [
@@ -250643,18 +251190,15 @@ function registerMcpCommand(program2, _logger) {
250643
251190
  server.registerTool("devos_ask", {
250644
251191
  description: "Compile the minimal secret-free context pack for a task; answers via the configured provider when a key is set.",
250645
251192
  inputSchema: { path: external_exports.string(), task: external_exports.string() }
250646
- }, async ({ path: path13, task }) => {
250647
- const { projectId } = await projectContext(engine, path13);
250648
- const compiled = await engine.compileContext({ projectId, task });
251193
+ }, async ({ path: path15, task }) => {
251194
+ const { projectId } = await projectContext(engine, path15);
251195
+ const compiled = await engine.compileContext({ projectId, task, readFile: createProjectFileReader(path15) });
250649
251196
  if (isErr(compiled))
250650
251197
  throw new Error(compiled.error.message);
250651
251198
  const pack = compiled.value;
250652
- const adapter = createConfiguredProviders()[0];
250653
- if (adapter !== void 0) {
250654
- const sent = await adapter.send({ capability: "completion", pack });
250655
- if (!isErr(sent))
250656
- return text(sent.value.content);
250657
- }
251199
+ const answer = await sendWithRouting(engine, pack);
251200
+ if (answer !== void 0)
251201
+ return text(answer.content);
250658
251202
  return text(pack.content);
250659
251203
  });
250660
251204
  server.registerTool("devos_remember", {
@@ -250664,8 +251208,8 @@ function registerMcpCommand(program2, _logger) {
250664
251208
  note: external_exports.string(),
250665
251209
  kind: external_exports.enum(["decision", "convention", "correction", "preference"]).optional()
250666
251210
  }
250667
- }, async ({ path: path13, note, kind }) => {
250668
- const { projectId } = await projectContext(engine, path13);
251211
+ }, async ({ path: path15, note, kind }) => {
251212
+ const { projectId } = await projectContext(engine, path15);
250669
251213
  const saved = await engine.dependencies.memory.remember({
250670
251214
  projectId,
250671
251215
  record: {
@@ -250683,8 +251227,8 @@ function registerMcpCommand(program2, _logger) {
250683
251227
  server.registerTool("devos_recall", {
250684
251228
  description: "Recall the project's persistent memory, optionally filtered by a query.",
250685
251229
  inputSchema: { path: external_exports.string(), query: external_exports.string().optional() }
250686
- }, async ({ path: path13, query }) => {
250687
- const { projectId } = await projectContext(engine, path13);
251230
+ }, async ({ path: path15, query }) => {
251231
+ const { projectId } = await projectContext(engine, path15);
250688
251232
  const recalled = await engine.dependencies.memory.recall({
250689
251233
  projectId,
250690
251234
  ...query === void 0 ? {} : { query }
@@ -250700,11 +251244,11 @@ function registerMcpCommand(program2, _logger) {
250700
251244
  }
250701
251245
 
250702
251246
  // apps/cli/dist/commands/plugins.js
250703
- import path12 from "node:path";
251247
+ import path14 from "node:path";
250704
251248
 
250705
251249
  // packages/plugin-host/dist/index.js
250706
- import { readdir as readdir3, readFile as readFile7 } from "node:fs/promises";
250707
- import path11 from "node:path";
251250
+ import { readdir as readdir3, readFile as readFile9 } from "node:fs/promises";
251251
+ import path13 from "node:path";
250708
251252
  import { pathToFileURL } from "node:url";
250709
251253
  var PluginHost = class {
250710
251254
  #plugins = /* @__PURE__ */ new Map();
@@ -250789,9 +251333,9 @@ async function discoverPlugins(dir) {
250789
251333
  }
250790
251334
  const discovered = [];
250791
251335
  for (const entry of entries.sort()) {
250792
- const directory = path11.join(dir, entry);
251336
+ const directory = path13.join(dir, entry);
250793
251337
  try {
250794
- const raw = await readFile7(path11.join(directory, "plugin.json"), "utf8");
251338
+ const raw = await readFile9(path13.join(directory, "plugin.json"), "utf8");
250795
251339
  const parsed = JSON.parse(raw);
250796
251340
  if (isManifest(parsed))
250797
251341
  discovered.push({ manifest: parsed, directory });
@@ -250801,7 +251345,7 @@ async function discoverPlugins(dir) {
250801
251345
  return ok(discovered);
250802
251346
  }
250803
251347
  async function loadPlugin(discovered) {
250804
- const entryPath = path11.join(discovered.directory, discovered.manifest.entry);
251348
+ const entryPath = path13.join(discovered.directory, discovered.manifest.entry);
250805
251349
  let mod;
250806
251350
  try {
250807
251351
  mod = await import(pathToFileURL(entryPath).href);
@@ -250839,7 +251383,7 @@ async function loadPluginsFromDirectory(host, dir) {
250839
251383
  // apps/cli/dist/commands/plugins.js
250840
251384
  function registerPluginsCommand(program2, logger) {
250841
251385
  program2.command("plugins").description("Discover, load and activate local plugins for a project").argument("<path>", "path to the project root").option("--dir <dir>", "plugin directory (default: <path>/.devos/plugins)").action(async (targetPath, options) => {
250842
- const dir = options.dir ?? path12.join(targetPath, ".devos", "plugins");
251386
+ const dir = options.dir ?? path14.join(targetPath, ".devos", "plugins");
250843
251387
  const allowed = (process.env["DEVOS_PLUGIN_PERMISSIONS"] ?? "").split(",").map((p) => p.trim()).filter((p) => p.length > 0);
250844
251388
  const host = new PluginHost({
250845
251389
  allowedPermissions: allowed,