@floydous/pi-agent-kernel 0.4.3 → 0.6.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 (65) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +15 -12
  2. package/CHANGELOG.md +87 -0
  3. package/README.md +6 -54
  4. package/config.example.toml +1 -8
  5. package/docs/README.md +1 -2
  6. package/docs/architecture.md +2 -3
  7. package/docs/configuration.md +11 -10
  8. package/docs/editing-and-verification.md +21 -8
  9. package/docs/podman-linux-checks.md +24 -0
  10. package/docs/release-discipline.md +10 -0
  11. package/docs/retrieval.md +21 -23
  12. package/docs/testing.md +3 -3
  13. package/grammars/tree-sitter-html.wasm +0 -0
  14. package/package.json +5 -3
  15. package/src/config/agent_kernel_command.ts +60 -625
  16. package/src/config/kernel_config.ts +53 -69
  17. package/src/config/toml.ts +6 -1
  18. package/src/editing/auto_heal.ts +1 -1
  19. package/src/editing/patch.ts +75 -37
  20. package/src/editing/post_edit_verification.ts +20 -14
  21. package/src/editing/smart_anchor.ts +9 -6
  22. package/src/editing/syntax-verify.ts +79 -222
  23. package/src/index.ts +36 -453
  24. package/src/retrieval/html_chunker.ts +526 -0
  25. package/src/retrieval/search_bm25.ts +39 -28
  26. package/src/retrieval/search_chunker.ts +69 -7
  27. package/src/retrieval/search_config.ts +21 -40
  28. package/src/retrieval/search_embedder.ts +14 -31
  29. package/src/retrieval/search_index.ts +338 -129
  30. package/src/retrieval/search_modal.ts +1208 -222
  31. package/src/retrieval/{repomap.ts → tag_extractor.ts} +6 -293
  32. package/src/retrieval/tree_sitter_engine.ts +171 -36
  33. package/src/retrieval/workspace_walker.ts +78 -2
  34. package/src/safety/atomic_write.ts +1 -1
  35. package/src/safety/epistemic_guard.ts +105 -31
  36. package/src/safety/host_environment.ts +180 -0
  37. package/src/safety/output_clamper.ts +97 -27
  38. package/src/tools/code_search_output.ts +11 -2
  39. package/src/tools/code_search_tool.ts +25 -13
  40. package/src/tools/context.ts +11 -10
  41. package/src/tools/edit_tool.ts +243 -154
  42. package/src/tools/read_tool.ts +285 -214
  43. package/src/tools/stream_reader.ts +206 -0
  44. package/src/ui/footer.ts +7 -7
  45. package/docs/lsp.md +0 -31
  46. package/src/lsp/adapters/base.ts +0 -42
  47. package/src/lsp/adapters/index.ts +0 -21
  48. package/src/lsp/adapters/python.ts +0 -37
  49. package/src/lsp/adapters/rust.ts +0 -35
  50. package/src/lsp/adapters/typescript.ts +0 -40
  51. package/src/lsp/index.ts +0 -13
  52. package/src/lsp/lsp_client.ts +0 -765
  53. package/src/lsp/lsp_detector.ts +0 -52
  54. package/src/lsp/lsp_formatter.ts +0 -323
  55. package/src/lsp/lsp_installer.ts +0 -320
  56. package/src/lsp/lsp_manager.ts +0 -202
  57. package/src/lsp/lsp_modal.ts +0 -675
  58. package/src/lsp/lsp_registry.ts +0 -600
  59. package/src/lsp/lsp_types.ts +0 -143
  60. package/src/retrieval/ast_search.ts +0 -999
  61. package/src/retrieval/symbol_reader.ts +0 -228
  62. package/src/tools/ast_search_formatter.ts +0 -161
  63. package/src/tools/ast_search_tool.ts +0 -146
  64. package/src/tools/lsp_tool.ts +0 -794
  65. package/src/tools/repo_map_tool.ts +0 -56
@@ -1,7 +1,6 @@
1
- import * as fs from "node:fs";
2
1
  import * as path from "node:path";
3
2
  import { TreeSitterEngine } from "./tree_sitter_engine";
4
- import { walkWorkspaceFiles, DEFAULT_IGNORED_DIRS } from "./workspace_walker";
3
+ import { walkWorkspaceFiles } from "./workspace_walker";
5
4
 
6
5
  export interface SymbolDef {
7
6
  name: string;
@@ -32,8 +31,6 @@ export interface FileTags {
32
31
  hasSyntaxError?: boolean;
33
32
  }
34
33
 
35
- const IGNORED_DIRS = DEFAULT_IGNORED_DIRS;
36
-
37
34
  const SUPPORTED_EXTENSIONS = new Set([
38
35
  ".ts",
39
36
  ".tsx",
@@ -75,7 +72,6 @@ function extractBalancedSig(
75
72
  let parenDepth = 0;
76
73
  let braceDepth = 0;
77
74
  let angleDepth = 0;
78
- let seenOpenParen = false;
79
75
  let seenArrow = false;
80
76
 
81
77
  for (let j = startIdx; j < Math.min(lines.length, startIdx + 20); j++) {
@@ -97,7 +93,6 @@ function extractBalancedSig(
97
93
 
98
94
  if (ch === "(") {
99
95
  parenDepth++;
100
- seenOpenParen = true;
101
96
  } else if (ch === ")") {
102
97
  if (parenDepth > 0) parenDepth--;
103
98
  } else if (ch === "<") {
@@ -628,9 +623,12 @@ export function extractFileTags(filePath: string, content: string): FileTags {
628
623
  /^(?:public|private|protected|internal|abstract|static|final|\s)*\s*(class|interface|enum)\s+([a-zA-Z0-9_]+)/,
629
624
  );
630
625
  if (jClass) {
626
+ let kind: "class" | "interface" | "enum" = "class";
627
+ if (jClass[1] === "interface") kind = "interface";
628
+ else if (jClass[1] === "enum") kind = "enum";
631
629
  definitions.push({
632
630
  name: jClass[2],
633
- kind: jClass[1] === "interface" ? "interface" : jClass[1] === "enum" ? "enum" : "class",
631
+ kind,
634
632
  signature: line.split("{")[0].trim(),
635
633
  line: i + 1,
636
634
  });
@@ -653,7 +651,7 @@ export function extractFileTags(filePath: string, content: string): FileTags {
653
651
  }
654
652
 
655
653
  // C / C++
656
- if (ext === ".c" || ext === ".cpp" || ext === ".cc" || ext === ".h" || ext === ".hpp") {
654
+ if (ext === ".c" || ext === ".cpp" || ext === ".cc" || ext === ".cxx" || ext === ".h" || ext === ".hpp" || ext === ".hh" || ext === ".hxx") {
657
655
  const cExpressionFn = line.match(
658
656
  /^(?:[A-Za-z_][A-Za-z0-9_:<>*&\s]+?)\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)\s*\{/,
659
657
  );
@@ -797,288 +795,3 @@ export function isTestPath(relPath: string): boolean {
797
795
  p.includes(".spec.")
798
796
  );
799
797
  }
800
-
801
- export interface CodebaseMetrics {
802
- implFiles: number;
803
- implBytes: number;
804
- testFiles: number;
805
- testBytes: number;
806
- isLight: boolean;
807
- }
808
-
809
- // Evaluate codebase scale by separating non-test implementation code from test suites.
810
- // A codebase is light only if both implementation file count and byte mass are small.
811
- export function evaluateCodebaseMetrics(
812
- rootDir: string,
813
- minImplFiles = 10,
814
- minImplBytes = 50 * 1024,
815
- ): CodebaseMetrics {
816
- const allFiles = findSourceFiles(rootDir);
817
- let implFiles = 0;
818
- let implBytes = 0;
819
- let testFiles = 0;
820
- let testBytes = 0;
821
-
822
- for (const file of allFiles) {
823
- const rel = path.relative(rootDir, file);
824
- let size = 0;
825
- try {
826
- size = fs.statSync(file).size;
827
- } catch {
828
- // skip unreadable
829
- }
830
-
831
- if (isTestPath(rel)) {
832
- testFiles++;
833
- testBytes += size;
834
- } else {
835
- implFiles++;
836
- implBytes += size;
837
- }
838
- }
839
-
840
- const isLight = implFiles <= minImplFiles && implBytes < minImplBytes;
841
- return {
842
- implFiles,
843
- implBytes,
844
- testFiles,
845
- testBytes,
846
- isLight,
847
- };
848
- }
849
-
850
- // Classify a file path into a PageRank demotion factor. Test suites form
851
- // dense mutual-reference clusters that otherwise dominate raw PageRank —
852
- // mirrors the test-path penalties in ast_search.computeSymbolRankScore.
853
- function getPathDemotion(relPath: string): number {
854
- if (isTestPath(relPath)) return 0.25; // strong demotion
855
- const p = relPath.replace(/\\/g, "/").toLowerCase();
856
- const isBenchmarkOrExample =
857
- p.includes("/benchmarks/") ||
858
- p.includes("/benchmark/") ||
859
- p.includes("/examples/") ||
860
- p.includes("/example/") ||
861
- p.includes("/samples/") ||
862
- p.includes("/fixtures/") ||
863
- p.startsWith("benchmarks/") ||
864
- p.startsWith("examples/") ||
865
- p.startsWith("samples/");
866
- if (isBenchmarkOrExample) return 0.6; // moderate demotion
867
- return 1;
868
- }
869
-
870
- function isTrivialDataDefinition(def: SymbolDef): boolean {
871
- if (def.kind !== "constant" && def.kind !== "variable") return false;
872
- const signature = def.signature.toLowerCase();
873
- return (
874
- signature.includes("color::rgb") ||
875
- signature.includes("lazylock") ||
876
- signature.includes("regex") ||
877
- signature.includes("hashset") ||
878
- signature.includes("mimetype") ||
879
- signature.includes("mime") ||
880
- signature.includes("once_lock") ||
881
- signature.includes("mutex") ||
882
- (signature.includes("static") && signature.includes("table"))
883
- );
884
- }
885
-
886
- /**
887
- * Return a stable orientation priority for common executable and routing
888
- * anchors. PageRank is still used for the rest of the map, but declaration
889
- * density must not hide the entry point behind UI palette constants.
890
- */
891
- function entryPointPriority(relPath: string, def: SymbolDef): number | null {
892
- const normalizedPath = relPath.replace(/\\/g, "/").toLowerCase();
893
- const fileName = path.basename(normalizedPath, path.extname(normalizedPath));
894
- const name = def.name.toLowerCase();
895
-
896
- if (name === "main") return 0;
897
- if (name === "router") return 1;
898
- if (name === "startup" || name === "start") return 2;
899
- if (fileName === "main" && (def.kind === "function" || def.kind === "method")) return 3;
900
- if ((fileName === "index" || fileName === "mod") && name === "createapp") return 4;
901
- if (name === "run" && (normalizedPath.includes("/bin/") || normalizedPath.includes("/cmd/"))) return 5;
902
- return null;
903
- }
904
-
905
- // Compute Graph PageRank for files and their symbols
906
- export function computeRepoMap(rootDir: string, tokenBudget = 1024): string {
907
- const sourceFiles = findSourceFiles(rootDir);
908
- if (sourceFiles.length === 0) {
909
- return "(No supported source files found in repository)";
910
- }
911
-
912
- // Ensure languages present in sourceFiles are loaded in TreeSitterEngine
913
- const detectedExts = new Set<string>();
914
- for (const f of sourceFiles) {
915
- const ext = path.extname(f).toLowerCase();
916
- if (ext) detectedExts.add(ext);
917
- }
918
- // Note: loadLanguages is async, but if called from an async context it is pre-warmed.
919
- // We also trigger loadLanguages asynchronously if not loaded.
920
- void TreeSitterEngine.getInstance().loadLanguages(Array.from(detectedExts));
921
-
922
- const fileTagsMap = new Map<string, FileTags>();
923
- const fileLineCounts = new Map<string, number>();
924
- const defToFile = new Map<string, Set<string>>();
925
-
926
- for (const file of sourceFiles) {
927
- try {
928
- const content = fs.readFileSync(file, "utf8");
929
- const tags = extractFileTags(file, content);
930
- fileTagsMap.set(file, tags);
931
- fileLineCounts.set(file, content.split("\n").length);
932
-
933
- for (const def of tags.definitions) {
934
- if (!defToFile.has(def.name)) {
935
- defToFile.set(def.name, new Set());
936
- }
937
- defToFile.get(def.name)!.add(file);
938
- }
939
- } catch {
940
- // Skip unreadable files
941
- }
942
- }
943
-
944
- // Build adjacency graph between files
945
- const files = Array.from(fileTagsMap.keys());
946
- const N = files.length;
947
- if (N === 0) return "(Empty repository)";
948
-
949
- const fileIndex = new Map<string, number>();
950
- files.forEach((f, idx) => fileIndex.set(f, idx));
951
-
952
- const inEdges: number[][] = Array.from({ length: N }, () => []);
953
- const outDegree = new Array(N).fill(0);
954
-
955
- for (let i = 0; i < N; i++) {
956
- const fileA = files[i];
957
- const tagsA = fileTagsMap.get(fileA)!;
958
- const referencedFiles = new Set<number>();
959
-
960
- for (const ref of tagsA.references) {
961
- const targetFiles = defToFile.get(ref);
962
- if (targetFiles) {
963
- for (const targetFile of targetFiles) {
964
- const targetIdx = fileIndex.get(targetFile);
965
- if (targetIdx !== undefined && targetIdx !== i) {
966
- referencedFiles.add(targetIdx);
967
- }
968
- }
969
- }
970
- }
971
-
972
- outDegree[i] = referencedFiles.size;
973
- for (const targetIdx of referencedFiles) {
974
- inEdges[targetIdx].push(i);
975
- }
976
- }
977
-
978
- // PageRank iteration (d = 0.85)
979
- const d = 0.85;
980
- let rank = new Array(N).fill(1 / N);
981
-
982
- for (let iter = 0; iter < 15; iter++) {
983
- const nextRank = new Array(N).fill((1 - d) / N);
984
- for (let i = 0; i < N; i++) {
985
- let sum = 0;
986
- for (const src of inEdges[i]) {
987
- if (outDegree[src] > 0) {
988
- sum += rank[src] / outDegree[src];
989
- }
990
- }
991
- nextRank[i] += d * sum;
992
- }
993
- rank = nextRank;
994
- }
995
-
996
- // Sort files by anchor priority first, then effective PageRank. This keeps
997
- // executable/router entry points visible on cold start while retaining the
998
- // graph ranking for the rest of the repository.
999
- const rankedFiles = files
1000
- .map((f, idx) => {
1001
- const relPath = path.relative(rootDir, f).replace(/\\/g, "/");
1002
- const tags = fileTagsMap.get(f)!;
1003
- const anchorPriorities = tags.definitions
1004
- .map((def) => entryPointPriority(relPath, def))
1005
- .filter((priority): priority is number => priority !== null);
1006
- return {
1007
- file: f,
1008
- effectiveRank: rank[idx] * getPathDemotion(relPath),
1009
- tags,
1010
- anchorPriority: anchorPriorities.length > 0 ? Math.min(...anchorPriorities) : Number.POSITIVE_INFINITY,
1011
- };
1012
- })
1013
- .sort((a, b) =>
1014
- a.anchorPriority - b.anchorPriority || b.effectiveRank - a.effectiveRank,
1015
- );
1016
-
1017
- // Pack symbols into token budget (~4 chars per token).
1018
- const charBudget = Math.max(80, tokenBudget * 4);
1019
- let currentChars = 0;
1020
- const lines: string[] = [];
1021
- const addLine = (line: string): boolean => {
1022
- const extra = lines.length > 0 ? 1 : 0;
1023
- if (currentChars + extra + line.length > charBudget) return false;
1024
- lines.push(line);
1025
- currentChars += extra + line.length;
1026
- return true;
1027
- };
1028
-
1029
- addLine("Repository Map (Tree-Sitter AST & PageRank Ranked):");
1030
-
1031
- // A compact orientation strip gives a cold-start caller the files it is most
1032
- // likely to need without requiring a separate `ls`/`wc` shell round trip.
1033
- if (charBudget >= 512) {
1034
- const anchors = rankedFiles
1035
- .flatMap((item) => {
1036
- const relPath = path.relative(rootDir, item.file).replace(/\\/g, "/");
1037
- return item.tags.definitions
1038
- .map((def) => ({ def, priority: entryPointPriority(relPath, def), relPath }))
1039
- .filter((entry): entry is { def: SymbolDef; priority: number; relPath: string } => entry.priority !== null);
1040
- })
1041
- .sort((a, b) => a.priority - b.priority)
1042
- .slice(0, 8)
1043
- .map((entry) => `${entry.relPath}::${entry.def.name}`);
1044
- if (anchors.length > 0) addLine(`Entry points: ${anchors.join(", ")}`);
1045
- }
1046
-
1047
- if (charBudget >= 1024) {
1048
- const sizeList = files
1049
- .slice()
1050
- .sort((a, b) => (fileLineCounts.get(b) || 0) - (fileLineCounts.get(a) || 0))
1051
- .slice(0, 12)
1052
- .map((file) => `${path.relative(rootDir, file).replace(/\\/g, "/")}(${fileLineCounts.get(file) || 0})`);
1053
- if (sizeList.length > 0) addLine(`Files by size: ${sizeList.join(", ")}`);
1054
- }
1055
-
1056
- for (const item of rankedFiles) {
1057
- const relPath = path.relative(rootDir, item.file).replace(/\\/g, "/");
1058
- const fileHeader = `${relPath}:`;
1059
- if (currentChars + fileHeader.length + 1 > charBudget) break;
1060
-
1061
- const nonAliasDefs = item.tags.definitions.filter((d) => d.kind !== "alias");
1062
- const meaningfulDefs = nonAliasDefs.filter((d) => !isTrivialDataDefinition(d));
1063
- const defs = meaningfulDefs.length > 0 ? meaningfulDefs : nonAliasDefs;
1064
- if (defs.length === 0) continue;
1065
-
1066
- if (!addLine(fileHeader)) break;
1067
- for (const def of defs) {
1068
- const cleanSig = def.signature.replace(/\s+/g, " ").trim();
1069
- const sigLine = ` ${cleanSig}`;
1070
- if (!addLine(sigLine)) break;
1071
- }
1072
- }
1073
-
1074
- // A bare header with nothing under it gives the caller zero guidance —
1075
- // say why the map is empty and how to get useful output.
1076
- if (lines.length === 1) {
1077
- lines.push("");
1078
- lines.push(
1079
- `[No symbols fit within budget_tokens=${tokenBudget} (~${charBudget} chars). Increase 'budget_tokens' (e.g. 1024+) to see the ranked symbol map.]`,
1080
- );
1081
- }
1082
-
1083
- return lines.join("\n");
1084
- }