@floydous/pi-agent-kernel 0.2.0 → 0.3.1

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.
@@ -298,11 +298,45 @@ export function extractFileTags(filePath: string, content: string): FileTags {
298
298
  }
299
299
  }
300
300
 
301
+ // Class methods and accessors are the important cold-state fallback case.
302
+ // Tree-sitter normally supplies these nested declarations; keep the
303
+ // synchronous fallback useful before a grammar has been loaded.
304
+ const tsJsGenericMethod = line.match(
305
+ /^(?:(?:public|private|protected|static|abstract|override|readonly|async)\s+)*(?:[A-Za-z_$][\w$]*(?:<[^{};]*>)?\s+)*([A-Za-z_$][\w$]*)\s*<[^{};]*>\s*\([^{}]*\)\s*(?::\s*[^{};]+)?\s*\{/,
306
+ );
307
+ const tsJsMethod = tsJsGenericMethod || line.match(
308
+ /^(?:(?:public|private|protected|static|abstract|override|readonly|async)\s+)*(?:[A-Za-z_$][\w$]*(?:<[^>]*>)?(?:\[\])?\??\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\([^)]*\)\s*(?::\s*[^={;]+)?(?:\{|;)/,
309
+ );
310
+ const controlOrExpression = /^(?:if|for|while|switch|catch|return|throw|await|new|super|this|const|let|var)\b/;
311
+ const indentation = rawLine.match(/^\s*/)?.[0].length ?? 0;
312
+ if (tsJsMethod && indentation > 0 && indentation <= 4 && !controlOrExpression.test(line)) {
313
+ definitions.push({
314
+ name: tsJsMethod[1],
315
+ kind: "method",
316
+ signature: line.split("{")[0].trim().replace(/;$/, ""),
317
+ line: i + 1,
318
+ });
319
+ continue;
320
+ }
321
+
322
+ const tsJsAccessor = line.match(
323
+ /^(?:(?:public|private|protected|static|abstract|override|readonly|async)\s+)*(?:get|set)\s+([A-Za-z_$][\w$]*)\s*(?:\([^)]*\))?\s*(?::\s*[^={;]+)?\s*(?:\{|;)/,
324
+ );
325
+ if (tsJsAccessor && indentation > 0 && indentation <= 4) {
326
+ definitions.push({
327
+ name: tsJsAccessor[1],
328
+ kind: "method",
329
+ signature: line.split("{")[0].trim().replace(/;$/, ""),
330
+ line: i + 1,
331
+ });
332
+ continue;
333
+ }
334
+
301
335
  // const variable / constant declaration: const FOO = ... or const FOO: string = ... (only top-level declarations)
302
336
  const constDecl = line.match(
303
337
  /^(?:export\s+)?const\s+([a-zA-Z0-9_]+)(?:\s*:\s*([^=]+))?\s*=/,
304
338
  );
305
- if (constDecl && braceDepth === 0) {
339
+ if (constDecl && braceDepth === 0 && rawLine === rawLine.trimStart()) {
306
340
  const isAllUpper = /^[A-Z0-9_]{2,}$/.test(constDecl[1]);
307
341
  definitions.push({
308
342
  name: constDecl[1],
@@ -544,27 +578,28 @@ export function extractFileTags(filePath: string, content: string): FileTags {
544
578
 
545
579
  // Go
546
580
  if (ext === ".go") {
547
- const goFn = line.match(/^func\s+(?:\([^)]+\)\s+)?([a-zA-Z0-9_]+)/);
581
+ const goFn = line.match(/^func\s+(\([^)]+\)\s+)?([a-zA-Z0-9_]+)/);
548
582
  if (goFn) {
549
583
  const sig =
550
584
  extractBalancedSig(lines, i, "go_fn") || line.split("{")[0].trim();
551
585
  definitions.push({
552
- name: goFn[1],
553
- kind: "function",
586
+ name: goFn[2],
587
+ kind: goFn[1] ? "method" : "function",
554
588
  signature: sig,
555
589
  line: i + 1,
556
590
  });
557
591
  continue;
558
592
  }
559
593
 
560
- const goType = line.match(/^type\s+([a-zA-Z0-9_]+)\s+(struct|interface)/);
594
+ const goType = line.match(/^type\s+([a-zA-Z0-9_]+)\s+(.+)/);
561
595
  if (goType) {
596
+ const typeBody = goType[2].trim();
562
597
  const sig =
563
598
  extractBalancedSig(lines, i, "go_type") ||
564
- `type ${goType[1]} ${goType[2]}`;
599
+ line.replace(/\s*\{\s*$/, "").trim();
565
600
  definitions.push({
566
601
  name: goType[1],
567
- kind: "class",
602
+ kind: typeBody.startsWith("interface") ? "interface" : "class",
568
603
  signature: sig,
569
604
  line: i + 1,
570
605
  });
@@ -585,6 +620,156 @@ export function extractFileTags(filePath: string, content: string): FileTags {
585
620
  }
586
621
  }
587
622
 
623
+ // Java / C# / C++ fallback regex scanner when TreeSitter is cold
624
+ if (ext === ".java" || ext === ".cs") {
625
+ // Methods may be expression-bodied (`... FindById(...) => ...`) and
626
+ // therefore have no opening brace for the balanced-signature helper.
627
+ const expressionMethod = line.match(
628
+ /^(?:public|private|protected|internal|static|final|synchronized|async|virtual|override|sealed|readonly|new|partial|unsafe|extern|\s)+\s+([A-Za-z0-9_<>,.?\[\]\s]+?)\s+([A-Za-z0-9_]+)\s*\(([^)]*)\)\s*=>/,
629
+ );
630
+ if (expressionMethod) {
631
+ definitions.push({
632
+ name: expressionMethod[2],
633
+ kind: "method",
634
+ signature: line.split("=>")[0].trim(),
635
+ line: i + 1,
636
+ });
637
+ continue;
638
+ }
639
+
640
+ // Class / interface / enum
641
+ const jClass = line.match(
642
+ /^(?:public|private|protected|internal|abstract|static|final|\s)*\s*(class|interface|enum)\s+([a-zA-Z0-9_]+)/,
643
+ );
644
+ if (jClass) {
645
+ definitions.push({
646
+ name: jClass[2],
647
+ kind: jClass[1] === "interface" ? "interface" : jClass[1] === "enum" ? "enum" : "class",
648
+ signature: line.split("{")[0].trim(),
649
+ line: i + 1,
650
+ });
651
+ continue;
652
+ }
653
+
654
+ // Method (requires return type and parentheses)
655
+ const jMethod = line.match(
656
+ /^(?:public|private|protected|internal|static|final|synchronized|async|virtual|override|\s)+\s+([a-zA-Z0-9_<>\[\],\s]+)\s+([a-zA-Z0-9_]+)\s*\(([^)]*)\)/,
657
+ );
658
+ if (jMethod && !jMethod[1].includes("class") && !jMethod[1].includes("return")) {
659
+ definitions.push({
660
+ name: jMethod[2],
661
+ kind: "method",
662
+ signature: line.split("{")[0].trim(),
663
+ line: i + 1,
664
+ });
665
+ continue;
666
+ }
667
+ }
668
+
669
+ // C / C++
670
+ if (ext === ".c" || ext === ".cpp" || ext === ".cc" || ext === ".h" || ext === ".hpp") {
671
+ const cExpressionFn = line.match(
672
+ /^(?:[A-Za-z_][A-Za-z0-9_:<>*&\s]+?)\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)\s*\{/,
673
+ );
674
+ if (cExpressionFn && !cExpressionFn[1].match(/^(if|for|while|switch|return)$/)) {
675
+ definitions.push({
676
+ name: cExpressionFn[1],
677
+ kind: rawLine !== rawLine.trimStart() ? "method" : "function",
678
+ signature: line.split("{")[0].trim(),
679
+ line: i + 1,
680
+ });
681
+ continue;
682
+ }
683
+
684
+ const cClass = line.match(/^(?:class|struct)\s+([a-zA-Z0-9_]+)/);
685
+ if (cClass) {
686
+ definitions.push({
687
+ name: cClass[1],
688
+ kind: "class",
689
+ signature: line.split("{")[0].trim(),
690
+ line: i + 1,
691
+ });
692
+ continue;
693
+ }
694
+
695
+ const cFn = line.match(
696
+ /^(?:[a-zA-Z0-9_&*]+\s+)+([a-zA-Z0-9_]+)\s*\(([^)]*)\)\s*(?:const)?\s*[{;]?$/,
697
+ );
698
+ if (cFn && !cFn[1].match(/^(if|for|while|switch|return)$/)) {
699
+ definitions.push({
700
+ name: cFn[1],
701
+ kind: rawLine !== rawLine.trimStart() ? "method" : "function",
702
+ signature: line.split("{")[0].trim(),
703
+ line: i + 1,
704
+ });
705
+ continue;
706
+ }
707
+ }
708
+
709
+ // Ruby
710
+ if (ext === ".rb") {
711
+ const rbClass = line.match(/^(?:class|module)\s+([a-zA-Z0-9_:]+)/);
712
+ if (rbClass) {
713
+ definitions.push({
714
+ name: rbClass[1],
715
+ kind: "class",
716
+ signature: line.trim(),
717
+ line: i + 1,
718
+ });
719
+ continue;
720
+ }
721
+
722
+ const rbMethod = line.match(/^\s*def\s+([a-zA-Z0-9_!?=.]+)/);
723
+ if (rbMethod) {
724
+ definitions.push({
725
+ name: rbMethod[1],
726
+ kind: "method",
727
+ signature: line.trim(),
728
+ line: i + 1,
729
+ });
730
+ continue;
731
+ }
732
+ }
733
+
734
+ // PHP
735
+ if (ext === ".php") {
736
+ const phpClass = line.match(/^(?:abstract\s+|final\s+)?(class|interface|trait)\s+([a-zA-Z0-9_]+)/);
737
+ if (phpClass) {
738
+ definitions.push({
739
+ name: phpClass[2],
740
+ kind: phpClass[1] === "interface" ? "interface" : "class",
741
+ signature: line.split("{")[0].trim(),
742
+ line: i + 1,
743
+ });
744
+ continue;
745
+ }
746
+
747
+ const phpFn = line.match(/^(?:public|private|protected|static|\s)*function\s+([a-zA-Z0-9_]+)\s*\(/);
748
+ if (phpFn) {
749
+ definitions.push({
750
+ name: phpFn[1],
751
+ kind: braceDepth > 0 ? "method" : "function",
752
+ signature: line.split("{")[0].trim(),
753
+ line: i + 1,
754
+ });
755
+ continue;
756
+ }
757
+ }
758
+
759
+ // Bash / Shell
760
+ if (ext === ".sh" || ext === ".bash") {
761
+ const shFn = line.match(/^(?:function\s+)?([a-zA-Z0-9_]+)\s*\(\)\s*\{?/);
762
+ if (shFn) {
763
+ definitions.push({
764
+ name: shFn[1],
765
+ kind: "function",
766
+ signature: `${shFn[1]}()`,
767
+ line: i + 1,
768
+ });
769
+ continue;
770
+ }
771
+ }
772
+
588
773
  for (const ch of line) {
589
774
  if (ch === "{") braceDepth++;
590
775
  else if (ch === "}") braceDepth = Math.max(0, braceDepth - 1);
@@ -632,12 +817,10 @@ export function findSourceFiles(rootDir: string, maxFiles = 300): string[] {
632
817
  return results;
633
818
  }
634
819
 
635
- // Classify a file path into a PageRank demotion factor. Test suites form
636
- // dense mutual-reference clusters that otherwise dominate raw PageRank —
637
- // mirrors the test-path penalties in ast_search.computeSymbolRankScore.
638
- function getPathDemotion(relPath: string): number {
820
+ // Check if a path corresponds to a test file or test directory
821
+ export function isTestPath(relPath: string): boolean {
639
822
  const p = relPath.replace(/\\/g, "/").toLowerCase();
640
- const isTestPath =
823
+ return (
641
824
  p.includes("/test/") ||
642
825
  p.includes("/tests/") ||
643
826
  p.includes("/__tests__/") ||
@@ -649,8 +832,65 @@ function getPathDemotion(relPath: string): number {
649
832
  p.includes("test_") ||
650
833
  p.includes("_test.") ||
651
834
  p.includes(".test.") ||
652
- p.includes(".spec.");
653
- if (isTestPath) return 0.25; // strong demotion
835
+ p.includes(".spec.")
836
+ );
837
+ }
838
+
839
+ export interface CodebaseMetrics {
840
+ implFiles: number;
841
+ implBytes: number;
842
+ testFiles: number;
843
+ testBytes: number;
844
+ isLight: boolean;
845
+ }
846
+
847
+ // Evaluate codebase scale by separating non-test implementation code from test suites.
848
+ // A codebase is light only if both implementation file count and byte mass are small.
849
+ export function evaluateCodebaseMetrics(
850
+ rootDir: string,
851
+ minImplFiles = 10,
852
+ minImplBytes = 50 * 1024,
853
+ ): CodebaseMetrics {
854
+ const allFiles = findSourceFiles(rootDir);
855
+ let implFiles = 0;
856
+ let implBytes = 0;
857
+ let testFiles = 0;
858
+ let testBytes = 0;
859
+
860
+ for (const file of allFiles) {
861
+ const rel = path.relative(rootDir, file);
862
+ let size = 0;
863
+ try {
864
+ size = fs.statSync(file).size;
865
+ } catch {
866
+ // skip unreadable
867
+ }
868
+
869
+ if (isTestPath(rel)) {
870
+ testFiles++;
871
+ testBytes += size;
872
+ } else {
873
+ implFiles++;
874
+ implBytes += size;
875
+ }
876
+ }
877
+
878
+ const isLight = implFiles <= minImplFiles && implBytes < minImplBytes;
879
+ return {
880
+ implFiles,
881
+ implBytes,
882
+ testFiles,
883
+ testBytes,
884
+ isLight,
885
+ };
886
+ }
887
+
888
+ // Classify a file path into a PageRank demotion factor. Test suites form
889
+ // dense mutual-reference clusters that otherwise dominate raw PageRank —
890
+ // mirrors the test-path penalties in ast_search.computeSymbolRankScore.
891
+ function getPathDemotion(relPath: string): number {
892
+ if (isTestPath(relPath)) return 0.25; // strong demotion
893
+ const p = relPath.replace(/\\/g, "/").toLowerCase();
654
894
  const isBenchmarkOrExample =
655
895
  p.includes("/benchmarks/") ||
656
896
  p.includes("/benchmark/") ||
@@ -665,6 +905,41 @@ function getPathDemotion(relPath: string): number {
665
905
  return 1;
666
906
  }
667
907
 
908
+ function isTrivialDataDefinition(def: SymbolDef): boolean {
909
+ if (def.kind !== "constant" && def.kind !== "variable") return false;
910
+ const signature = def.signature.toLowerCase();
911
+ return (
912
+ signature.includes("color::rgb") ||
913
+ signature.includes("lazylock") ||
914
+ signature.includes("regex") ||
915
+ signature.includes("hashset") ||
916
+ signature.includes("mimetype") ||
917
+ signature.includes("mime") ||
918
+ signature.includes("once_lock") ||
919
+ signature.includes("mutex") ||
920
+ (signature.includes("static") && signature.includes("table"))
921
+ );
922
+ }
923
+
924
+ /**
925
+ * Return a stable orientation priority for common executable and routing
926
+ * anchors. PageRank is still used for the rest of the map, but declaration
927
+ * density must not hide the entry point behind UI palette constants.
928
+ */
929
+ function entryPointPriority(relPath: string, def: SymbolDef): number | null {
930
+ const normalizedPath = relPath.replace(/\\/g, "/").toLowerCase();
931
+ const fileName = path.basename(normalizedPath, path.extname(normalizedPath));
932
+ const name = def.name.toLowerCase();
933
+
934
+ if (name === "main") return 0;
935
+ if (name === "router") return 1;
936
+ if (name === "startup" || name === "start") return 2;
937
+ if (fileName === "main" && (def.kind === "function" || def.kind === "method")) return 3;
938
+ if ((fileName === "index" || fileName === "mod") && name === "createapp") return 4;
939
+ if (name === "run" && (normalizedPath.includes("/bin/") || normalizedPath.includes("/cmd/"))) return 5;
940
+ return null;
941
+ }
942
+
668
943
  // Compute Graph PageRank for files and their symbols
669
944
  export function computeRepoMap(rootDir: string, tokenBudget = 1024): string {
670
945
  const sourceFiles = findSourceFiles(rootDir);
@@ -683,6 +958,7 @@ export function computeRepoMap(rootDir: string, tokenBudget = 1024): string {
683
958
  void TreeSitterEngine.getInstance().loadLanguages(Array.from(detectedExts));
684
959
 
685
960
  const fileTagsMap = new Map<string, FileTags>();
961
+ const fileLineCounts = new Map<string, number>();
686
962
  const defToFile = new Map<string, Set<string>>();
687
963
 
688
964
  for (const file of sourceFiles) {
@@ -690,6 +966,7 @@ export function computeRepoMap(rootDir: string, tokenBudget = 1024): string {
690
966
  const content = fs.readFileSync(file, "utf8");
691
967
  const tags = extractFileTags(file, content);
692
968
  fileTagsMap.set(file, tags);
969
+ fileLineCounts.set(file, content.split("\n").length);
693
970
 
694
971
  for (const def of tags.definitions) {
695
972
  if (!defToFile.has(def.name)) {
@@ -754,42 +1031,81 @@ export function computeRepoMap(rootDir: string, tokenBudget = 1024): string {
754
1031
  rank = nextRank;
755
1032
  }
756
1033
 
757
- // Sort files by effective rank descending (raw PageRank demoted for
758
- // test/benchmark/example paths so production code leads the map).
1034
+ // Sort files by anchor priority first, then effective PageRank. This keeps
1035
+ // executable/router entry points visible on cold start while retaining the
1036
+ // graph ranking for the rest of the repository.
759
1037
  const rankedFiles = files
760
- .map((f, idx) => ({
761
- file: f,
762
- effectiveRank: rank[idx] * getPathDemotion(path.relative(rootDir, f)),
763
- tags: fileTagsMap.get(f)!,
764
- }))
765
- .sort((a, b) => b.effectiveRank - a.effectiveRank);
766
-
767
- // Pack symbols into token budget (~4 chars per token)
768
- const charBudget = tokenBudget * 4;
1038
+ .map((f, idx) => {
1039
+ const relPath = path.relative(rootDir, f).replace(/\\/g, "/");
1040
+ const tags = fileTagsMap.get(f)!;
1041
+ const anchorPriorities = tags.definitions
1042
+ .map((def) => entryPointPriority(relPath, def))
1043
+ .filter((priority): priority is number => priority !== null);
1044
+ return {
1045
+ file: f,
1046
+ effectiveRank: rank[idx] * getPathDemotion(relPath),
1047
+ tags,
1048
+ anchorPriority: anchorPriorities.length > 0 ? Math.min(...anchorPriorities) : Number.POSITIVE_INFINITY,
1049
+ };
1050
+ })
1051
+ .sort((a, b) =>
1052
+ a.anchorPriority - b.anchorPriority || b.effectiveRank - a.effectiveRank,
1053
+ );
1054
+
1055
+ // Pack symbols into token budget (~4 chars per token).
1056
+ const charBudget = Math.max(80, tokenBudget * 4);
769
1057
  let currentChars = 0;
770
1058
  const lines: string[] = [];
1059
+ const addLine = (line: string): boolean => {
1060
+ const extra = lines.length > 0 ? 1 : 0;
1061
+ if (currentChars + extra + line.length > charBudget) return false;
1062
+ lines.push(line);
1063
+ currentChars += extra + line.length;
1064
+ return true;
1065
+ };
1066
+
1067
+ addLine("Repository Map (Tree-Sitter AST & PageRank Ranked):");
1068
+
1069
+ // A compact orientation strip gives a cold-start caller the files it is most
1070
+ // likely to need without requiring a separate `ls`/`wc` shell round trip.
1071
+ if (charBudget >= 512) {
1072
+ const anchors = rankedFiles
1073
+ .flatMap((item) => {
1074
+ const relPath = path.relative(rootDir, item.file).replace(/\\/g, "/");
1075
+ return item.tags.definitions
1076
+ .map((def) => ({ def, priority: entryPointPriority(relPath, def), relPath }))
1077
+ .filter((entry): entry is { def: SymbolDef; priority: number; relPath: string } => entry.priority !== null);
1078
+ })
1079
+ .sort((a, b) => a.priority - b.priority)
1080
+ .slice(0, 8)
1081
+ .map((entry) => `${entry.relPath}::${entry.def.name}`);
1082
+ if (anchors.length > 0) addLine(`Entry points: ${anchors.join(", ")}`);
1083
+ }
771
1084
 
772
- lines.push("Repository Map (Tree-Sitter AST & PageRank Ranked):");
1085
+ if (charBudget >= 1024) {
1086
+ const sizeList = files
1087
+ .slice()
1088
+ .sort((a, b) => (fileLineCounts.get(b) || 0) - (fileLineCounts.get(a) || 0))
1089
+ .slice(0, 12)
1090
+ .map((file) => `${path.relative(rootDir, file).replace(/\\/g, "/")}(${fileLineCounts.get(file) || 0})`);
1091
+ if (sizeList.length > 0) addLine(`Files by size: ${sizeList.join(", ")}`);
1092
+ }
773
1093
 
774
1094
  for (const item of rankedFiles) {
775
1095
  const relPath = path.relative(rootDir, item.file).replace(/\\/g, "/");
776
- const fileHeader = `\n${relPath}:`;
777
- if (currentChars + fileHeader.length > charBudget) break;
1096
+ const fileHeader = `${relPath}:`;
1097
+ if (currentChars + fileHeader.length + 1 > charBudget) break;
778
1098
 
779
- const defs = item.tags.definitions.filter((d) => d.kind !== "alias");
1099
+ const nonAliasDefs = item.tags.definitions.filter((d) => d.kind !== "alias");
1100
+ const meaningfulDefs = nonAliasDefs.filter((d) => !isTrivialDataDefinition(d));
1101
+ const defs = meaningfulDefs.length > 0 ? meaningfulDefs : nonAliasDefs;
780
1102
  if (defs.length === 0) continue;
781
1103
 
782
- lines.push(fileHeader);
783
- currentChars += fileHeader.length;
784
-
1104
+ if (!addLine(fileHeader)) break;
785
1105
  for (const def of defs) {
786
1106
  const cleanSig = def.signature.replace(/\s+/g, " ").trim();
787
1107
  const sigLine = ` ${cleanSig}`;
788
- if (currentChars + sigLine.length > charBudget) {
789
- break;
790
- }
791
- lines.push(sigLine);
792
- currentChars += sigLine.length;
1108
+ if (!addLine(sigLine)) break;
793
1109
  }
794
1110
  }
795
1111