@floydous/pi-agent-kernel 0.5.0 → 0.6.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.
Files changed (37) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +20 -6
  2. package/CHANGELOG.md +69 -0
  3. package/README.md +23 -20
  4. package/config.example.toml +1 -0
  5. package/docs/configuration.md +1 -1
  6. package/docs/editing-and-verification.md +20 -5
  7. package/docs/podman-linux-checks.md +24 -0
  8. package/docs/release-discipline.md +10 -0
  9. package/docs/retrieval.md +14 -11
  10. package/grammars/tree-sitter-html.wasm +0 -0
  11. package/package.json +2 -2
  12. package/src/config/agent_kernel_command.ts +60 -593
  13. package/src/config/kernel_config.ts +46 -2
  14. package/src/editing/patch.ts +48 -21
  15. package/src/editing/post_edit_verification.ts +8 -4
  16. package/src/editing/smart_anchor.ts +2 -1
  17. package/src/editing/syntax-verify.ts +73 -220
  18. package/src/index.ts +105 -203
  19. package/src/retrieval/html_chunker.ts +526 -0
  20. package/src/retrieval/search_bm25.ts +36 -27
  21. package/src/retrieval/search_chunker.ts +68 -6
  22. package/src/retrieval/search_config.ts +17 -34
  23. package/src/retrieval/search_embedder.ts +11 -29
  24. package/src/retrieval/search_index.ts +307 -145
  25. package/src/retrieval/search_modal.ts +1247 -222
  26. package/src/retrieval/tag_extractor.ts +1 -1
  27. package/src/retrieval/tree_sitter_engine.ts +103 -4
  28. package/src/retrieval/workspace_walker.ts +72 -0
  29. package/src/safety/host_environment.ts +190 -0
  30. package/src/safety/output_clamper.ts +83 -19
  31. package/src/tools/code_search_output.ts +9 -1
  32. package/src/tools/code_search_tool.ts +51 -14
  33. package/src/tools/context.ts +15 -0
  34. package/src/tools/edit_tool.ts +306 -79
  35. package/src/tools/read_tool.ts +248 -39
  36. package/src/tools/stream_reader.ts +206 -0
  37. package/src/ui/tui_utils.ts +70 -12
@@ -651,7 +651,7 @@ export function extractFileTags(filePath: string, content: string): FileTags {
651
651
  }
652
652
 
653
653
  // C / C++
654
- 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") {
655
655
  const cExpressionFn = line.match(
656
656
  /^(?:[A-Za-z_][A-Za-z0-9_:<>*&\s]+?)\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)\s*\{/,
657
657
  );
@@ -32,6 +32,9 @@ const EXTENSION_TO_GRAMMAR: Record<string, LanguageGrammarSpec> = {
32
32
  ".cpp": { wasmFile: "tree-sitter-cpp.wasm", langKey: "cpp" },
33
33
  ".hpp": { wasmFile: "tree-sitter-cpp.wasm", langKey: "cpp" },
34
34
  ".cc": { wasmFile: "tree-sitter-cpp.wasm", langKey: "cpp" },
35
+ ".cxx": { wasmFile: "tree-sitter-cpp.wasm", langKey: "cpp" },
36
+ ".hh": { wasmFile: "tree-sitter-cpp.wasm", langKey: "cpp" },
37
+ ".hxx": { wasmFile: "tree-sitter-cpp.wasm", langKey: "cpp" },
35
38
  // Java
36
39
  ".java": { wasmFile: "tree-sitter-java.wasm", langKey: "java" },
37
40
  // C#
@@ -43,8 +46,42 @@ const EXTENSION_TO_GRAMMAR: Record<string, LanguageGrammarSpec> = {
43
46
  ".rb": { wasmFile: "tree-sitter-ruby.wasm", langKey: "ruby" },
44
47
  // PHP
45
48
  ".php": { wasmFile: "tree-sitter-php.wasm", langKey: "php" },
49
+ // HTML
50
+ ".html": { wasmFile: "tree-sitter-html.wasm", langKey: "html" },
51
+ ".htm": { wasmFile: "tree-sitter-html.wasm", langKey: "html" },
46
52
  };
47
53
 
54
+ // `.h` is shared by C and C++. A header is parsed as C++ only when it has a C++ marker and the C parse has errors
55
+ // that the C++ parse reduces (measured on jq/libuv/ninja/fmt headers: switches no C header, nearly every C++ one).
56
+ const CPP_HEADER_MARKER = /^\s*namespace\s+[\w:]*\s*\{|^\s*template\s*<|^\s*class\s+\w+|^\s*(public|private|protected)\s*:|\w::\w|\bconstexpr\b|\btypename\b/m;
57
+
58
+ // Rust keeps unit tests inside source files. Items under these attributes are test code: #[test], #[cfg(test)],
59
+ // #[cfg(all(test, …))], #[rstest], #[<path>::test] (e.g. tokio::test). #[cfg(not(test))] is not.
60
+ const RUST_TEST_ATTRIBUTE = /^#\[(?:test\]|cfg\((?:all\()?test\b|rstest\b|[\w:]+::test\b)/;
61
+
62
+ /** Marks Rust definitions inside an item that carries a test attribute as kind "test" (for source/test separation). */
63
+ function markRustTests(root: any, definitions: SymbolDef[]): void {
64
+ const ranges: Array<[number, number]> = [];
65
+ const walk = (node: any) => {
66
+ if (node.type === "attribute_item" && RUST_TEST_ATTRIBUTE.test(node.text.replace(/\s+/g, ""))) {
67
+ let item = node.nextNamedSibling;
68
+ while (item && (item.type === "attribute_item" || item.type === "line_comment" || item.type === "block_comment")) item = item.nextNamedSibling;
69
+ if (item) ranges.push([item.startPosition.row + 1, item.endPosition.row + 1]);
70
+ }
71
+ for (let i = 0; i < node.namedChildCount; i++) walk(node.namedChild(i));
72
+ };
73
+ walk(root);
74
+ for (const def of definitions) {
75
+ if (ranges.some(([start, end]) => def.line >= start && def.line <= end)) def.kind = "test";
76
+ }
77
+ }
78
+
79
+ function countErrorNodes(node: any): number {
80
+ let count = node.type === "ERROR" || (typeof node.isMissing === "function" ? node.isMissing() : node.isMissing) ? 1 : 0;
81
+ for (let i = 0; i < node.childCount; i++) count += countErrorNodes(node.child(i));
82
+ return count;
83
+ }
84
+
48
85
  function getGrammarsDir(): string {
49
86
  // Root of agent-kernel extension: ../../grammars relative to src/retrieval or dist/retrieval
50
87
  const candidate1 = path.join(__dirname, "..", "..", "grammars");
@@ -69,6 +106,8 @@ export class TreeSitterEngine {
69
106
  private languages = new Map<string, WtsLanguage>();
70
107
  private ParserClass: any = null;
71
108
  private LanguageClass: any = null;
109
+ // Why a grammar could not be used, by language ("*" = the engine itself), so the fallback is reported, not hidden.
110
+ private loadIssues = new Map<string, string>();
72
111
 
73
112
  public static getInstance(): TreeSitterEngine {
74
113
  if (!TreeSitterEngine.instance) {
@@ -86,6 +125,15 @@ export class TreeSitterEngine {
86
125
  return Object.keys(EXTENSION_TO_GRAMMAR);
87
126
  }
88
127
 
128
+ /** Languages whose grammar could not be used: file not found, failed to load, or the engine failed to start. */
129
+ public getLoadIssues(): Array<{ language: string; extensions: string[]; reason: string }> {
130
+ return [...this.loadIssues].map(([language, reason]) => ({
131
+ language,
132
+ extensions: Object.keys(EXTENSION_TO_GRAMMAR).filter((ext) => language === "*" || EXTENSION_TO_GRAMMAR[ext].langKey === language),
133
+ reason,
134
+ }));
135
+ }
136
+
89
137
  public async init(): Promise<boolean> {
90
138
  if (this.initialized) return true;
91
139
  if (this.initPromise) return this.initPromise;
@@ -125,6 +173,7 @@ export class TreeSitterEngine {
125
173
  return true;
126
174
  } catch (e) {
127
175
  kernelDebug(`TreeSitterEngine init failed: ${e}`);
176
+ this.loadIssues.set("*", `tree-sitter failed to start: ${String(e).split("\n")[0]}`);
128
177
  this.initialized = false;
129
178
  return false;
130
179
  }
@@ -141,6 +190,8 @@ export class TreeSitterEngine {
141
190
  if (!this.initialized || !this.ParserClass || !this.LanguageClass) return;
142
191
 
143
192
  const pending: Promise<void>[] = [];
193
+ // C++ headers named .h need the C++ grammar too (see CPP_HEADER_MARKER).
194
+ if (extensions.includes(".h") && !extensions.includes(".hpp")) extensions = [...extensions, ".hpp"];
144
195
  for (const ext of extensions) {
145
196
  const spec = EXTENSION_TO_GRAMMAR[ext];
146
197
  if (!spec) continue;
@@ -152,11 +203,15 @@ export class TreeSitterEngine {
152
203
  this.LanguageClass.load(wasmPath)
153
204
  .then((lang: any) => {
154
205
  this.languages.set(spec.langKey, lang);
206
+ this.loadIssues.delete(spec.langKey);
155
207
  })
156
208
  .catch((e: any) => {
157
209
  kernelDebug(`Failed to load grammar for ${spec.langKey}: ${e}`);
210
+ this.loadIssues.set(spec.langKey, `grammar failed to load: ${String(e).split("\n")[0]}`);
158
211
  }),
159
212
  );
213
+ } else {
214
+ this.loadIssues.set(spec.langKey, `grammar file ${spec.wasmFile} not found`);
160
215
  }
161
216
  }
162
217
  }
@@ -198,6 +253,33 @@ export class TreeSitterEngine {
198
253
  return null;
199
254
  }
200
255
 
256
+ /**
257
+ * Syntax errors in `content`: ERROR and MISSING nodes (outermost only), with 1-based positions. Both kinds are
258
+ * needed: a missing `)` can recover with a MISSING node and no ERROR node. Null when no grammar is loaded.
259
+ */
260
+ public findSyntaxErrors(ext: string, content: string): Array<{ line: number; column: number; endLine: number; missing?: string; text?: string }> | null {
261
+ const parser = this.getParser(ext);
262
+ if (!parser) return null;
263
+ let tree: any = null;
264
+ try {
265
+ tree = parser.parse(content);
266
+ const errors: Array<{ line: number; column: number; endLine: number; missing?: string; text?: string }> = [];
267
+ const visit = (node: any) => {
268
+ const at = { line: node.startPosition.row + 1, column: node.startPosition.column + 1, endLine: node.endPosition.row + 1 };
269
+ if (typeof node.isMissing === "function" ? node.isMissing() : node.isMissing) errors.push({ ...at, missing: node.type });
270
+ else if (node.type === "ERROR") errors.push({ ...at, text: node.text.trim().split("\n")[0].slice(0, 40) });
271
+ else if (node.hasError) for (let i = 0; i < node.childCount; i++) visit(node.child(i));
272
+ };
273
+ visit(tree.rootNode);
274
+ return errors;
275
+ } catch (e) {
276
+ kernelDebug(`TreeSitterEngine findSyntaxErrors error (${ext}): ${e}`);
277
+ return null;
278
+ } finally {
279
+ tree?.delete();
280
+ }
281
+ }
282
+
201
283
  public extractTags(filePath: string, content: string): FileTags | null {
202
284
  const ext = path.extname(filePath).toLowerCase();
203
285
  let parser = this.getParser(ext);
@@ -208,6 +290,16 @@ export class TreeSitterEngine {
208
290
  let tree: any = null;
209
291
  try {
210
292
  tree = parser.parse(content);
293
+ if (ext === ".h" && tree.rootNode.hasError && CPP_HEADER_MARKER.test(content)) {
294
+ const cppParser = this.getParser(".hpp");
295
+ const cppTree = cppParser ? cppParser.parse(content) : null;
296
+ if (cppTree && countErrorNodes(cppTree.rootNode) < countErrorNodes(tree.rootNode)) {
297
+ tree.delete();
298
+ tree = cppTree;
299
+ } else {
300
+ cppTree?.delete();
301
+ }
302
+ }
211
303
  const root = tree.rootNode;
212
304
  const hasSyntaxError = root.hasError;
213
305
  const definitions: SymbolDef[] = [];
@@ -613,7 +705,7 @@ export class TreeSitterEngine {
613
705
  }
614
706
 
615
707
  // --- C / C++ ---
616
- if (type === "function_definition" && (ext === ".c" || ext === ".cpp" || ext === ".h" || ext === ".hpp" || ext === ".cc")) {
708
+ if (type === "function_definition" && (ext === ".c" || ext === ".cpp" || ext === ".h" || ext === ".hpp" || ext === ".cc" || ext === ".cxx" || ext === ".hh" || ext === ".hxx")) {
617
709
  let isMethod = false;
618
710
  let p = node.parent;
619
711
  while (p) {
@@ -650,7 +742,9 @@ export class TreeSitterEngine {
650
742
  }
651
743
  if (type === "class_specifier" || type === "struct_specifier") {
652
744
  const nameNode = node.childForFieldName("name");
653
- if (nameNode) {
745
+ const body = node.childForFieldName("body");
746
+ // Without a body this is a type reference (`struct foo *p`) or forward declaration, not a definition.
747
+ if (nameNode && body) {
654
748
  definitions.push({
655
749
  name: nameNode.text,
656
750
  kind: "class",
@@ -659,7 +753,6 @@ export class TreeSitterEngine {
659
753
  endLine: node.endPosition.row + 1,
660
754
  });
661
755
  }
662
- const body = node.childForFieldName("body");
663
756
  if (body) {
664
757
  for (const member of body.namedChildren) {
665
758
  visit(member, false);
@@ -770,7 +863,12 @@ export class TreeSitterEngine {
770
863
  }
771
864
 
772
865
  // --- Imports / Exports Aliases (TS/JS) ---
773
- if (type === "export_statement" || type === "import_statement") {
866
+ // An export with a declaration or default value (`export function f() {…}`) spans the whole
867
+ // body, where any "x as y" text is not an alias; only clause-style statements carry aliases.
868
+ const isAliasStatement =
869
+ type === "import_statement" ||
870
+ (type === "export_statement" && !node.childForFieldName("declaration") && !node.childForFieldName("value"));
871
+ if (isAliasStatement) {
774
872
  const text = node.text;
775
873
  if (text.includes(" as ")) {
776
874
  const asMatch = text.match(/\b([a-zA-Z0-9_]+)\s+as\s+([a-zA-Z0-9_]+)\b/);
@@ -812,6 +910,7 @@ export class TreeSitterEngine {
812
910
  }
813
911
  }
814
912
  collectAstReferences(root);
913
+ if (ext === ".rs") markRustTests(root, definitions);
815
914
 
816
915
  return {
817
916
  filePath,
@@ -86,6 +86,8 @@ export interface WalkWorkspaceOptions {
86
86
  extensions?: Set<string>;
87
87
  includeGithub?: boolean;
88
88
  onFile?: (filePath: string) => boolean | void;
89
+ /** Called for each directory whose ignore files are consulted, before it is read. */
90
+ onDirectory?: (dirPath: string) => void;
89
91
  }
90
92
 
91
93
  /**
@@ -140,6 +142,7 @@ export function walkWorkspaceFiles(options: WalkWorkspaceOptions): string[] {
140
142
  }
141
143
 
142
144
  for (const dir of initialDirs) {
145
+ options.onDirectory?.(dir);
143
146
  const dirRel = path.relative(baseRoot, dir).replace(/\\/g, "/");
144
147
  const localGit = loadIgnoreFile(path.join(dir, ".gitignore"));
145
148
  if (localGit) {
@@ -154,6 +157,7 @@ export function walkWorkspaceFiles(options: WalkWorkspaceOptions): string[] {
154
157
  function scan(dir: string, gitStack: IgnoreFrame[], piStack: IgnoreFrame[]): boolean {
155
158
  if (files.length >= maxFiles) return false;
156
159
 
160
+ options.onDirectory?.(dir);
157
161
  let entries: fs.Dirent[];
158
162
  try {
159
163
  entries = fs.readdirSync(dir, { withFileTypes: true });
@@ -264,3 +268,71 @@ export function walkWorkspaceFiles(options: WalkWorkspaceOptions): string[] {
264
268
  scan(rootDir, rootGitFrames, rootPiFrames);
265
269
  return files;
266
270
  }
271
+
272
+ interface WalkProbe {
273
+ path: string;
274
+ /** `.git` probes only matter for existence: git operations touch .git constantly. */
275
+ existenceOnly: boolean;
276
+ stats?: fs.Stats;
277
+ }
278
+
279
+ const WALK_RACY_WINDOW_MS = 2_000;
280
+
281
+ function takeProbe(probePath: string, existenceOnly: boolean): WalkProbe {
282
+ return { path: probePath, existenceOnly, stats: fs.statSync(probePath, { throwIfNoEntry: false }) };
283
+ }
284
+
285
+ function probeUnchanged(probe: WalkProbe): boolean {
286
+ const now = fs.statSync(probe.path, { throwIfNoEntry: false });
287
+ if (!probe.stats || !now) return !probe.stats && !now;
288
+ if (probe.existenceOnly) return true;
289
+ return probe.stats.dev === now.dev && probe.stats.ino === now.ino && probe.stats.size === now.size
290
+ && probe.stats.mtimeMs === now.mtimeMs && probe.stats.isDirectory() === now.isDirectory();
291
+ }
292
+
293
+ /**
294
+ * Reuses a workspace walk until something it depended on changes: a visited directory (entry
295
+ * add/remove/rename updates its mtime), a consulted .gitignore/.piignore, or the `.git` ancestors
296
+ * that decide the ignore root. Walks recorded within the mtime-granularity window are not reused.
297
+ */
298
+ export class WorkspaceWalkCache {
299
+ private key = "";
300
+ private files: string[] = [];
301
+ private probes: WalkProbe[] = [];
302
+ private racy = true;
303
+
304
+ walk(options: WalkWorkspaceOptions): string[] {
305
+ if (options.onFile) return walkWorkspaceFiles(options);
306
+ const key = JSON.stringify([
307
+ path.resolve(options.rootDir),
308
+ options.maxFiles ?? 500,
309
+ options.includeGithub ?? true,
310
+ options.extensions ? [...options.extensions].sort() : null,
311
+ ]);
312
+ if (key === this.key && !this.racy && this.probes.every(probeUnchanged)) return this.files.slice();
313
+
314
+ const started = Date.now();
315
+ const probes = new Map<string, WalkProbe>();
316
+ const record = (probePath: string, existenceOnly = false) => {
317
+ if (!probes.has(probePath)) probes.set(probePath, takeProbe(probePath, existenceOnly));
318
+ };
319
+ for (let dir = path.resolve(options.rootDir); ; dir = path.dirname(dir)) {
320
+ record(path.join(dir, ".git"), true);
321
+ if (probes.get(path.join(dir, ".git"))!.stats || path.dirname(dir) === dir) break;
322
+ }
323
+ const files = walkWorkspaceFiles({
324
+ ...options,
325
+ onDirectory: (dir) => {
326
+ options.onDirectory?.(dir);
327
+ record(dir);
328
+ record(path.join(dir, ".gitignore"));
329
+ record(path.join(dir, ".piignore"));
330
+ },
331
+ });
332
+ this.key = key;
333
+ this.files = files;
334
+ this.probes = [...probes.values()];
335
+ this.racy = this.probes.some((p) => !p.existenceOnly && p.stats && p.stats.mtimeMs >= started - WALK_RACY_WINDOW_MS);
336
+ return files.slice();
337
+ }
338
+ }
@@ -0,0 +1,190 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+
4
+ export interface HostEnvironmentOptions {
5
+ platform?: string;
6
+ arch?: string;
7
+ osReleaseContent?: string;
8
+ isWsl?: boolean;
9
+ }
10
+
11
+ let memoizedHostEnv: string | null = null;
12
+
13
+ function unquote(val: string): string {
14
+ const trimmed = val.trim();
15
+ if (trimmed.length >= 2) {
16
+ const first = trimmed.charAt(0);
17
+ const last = trimmed.charAt(trimmed.length - 1);
18
+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
19
+ const inside = trimmed.slice(1, -1);
20
+ return first === '"' ? inside.replace(/\\([\\"$`])/g, "$1") : inside;
21
+ }
22
+ }
23
+ return trimmed;
24
+ }
25
+
26
+ export function parseOSRelease(text: string): Record<string, string> {
27
+ const result = Object.create(null) as Record<string, string>;
28
+ for (const line of text.split(/\r?\n/)) {
29
+ const trimmed = line.trim();
30
+ if (!trimmed || trimmed.startsWith("#")) continue;
31
+ const idx = trimmed.indexOf("=");
32
+ if (idx < 1) continue;
33
+ const key = trimmed.slice(0, idx);
34
+ if (/^[A-Z0-9_]+$/.test(key)) {
35
+ result[key] = unquote(trimmed.slice(idx + 1));
36
+ }
37
+ }
38
+ return result;
39
+ }
40
+
41
+ function getWindowsVersion(): string {
42
+ const rel = os.release();
43
+ const match = rel.match(/(\d+)\.(\d+)\.(\d+)/);
44
+ if (match) {
45
+ const build = parseInt(match[3], 10);
46
+ return build >= 22000 ? "Windows 11" : "Windows 10";
47
+ }
48
+ return "Windows";
49
+ }
50
+
51
+ interface LinuxDistroInfo {
52
+ name: string;
53
+ id?: string;
54
+ idLike?: string;
55
+ }
56
+
57
+ function sanitizeHostMetadataText(value: string): string {
58
+ return value
59
+ .replace(/[\r\n\t]+/g, " ")
60
+ .replace(/[\x00-\x1f\x7f]/g, "")
61
+ .replace(/&/g, "&amp;")
62
+ .replace(/</g, "&lt;")
63
+ .replace(/>/g, "&gt;")
64
+ .trim() || "Linux";
65
+ }
66
+
67
+ function resolveLinuxDistro(options?: HostEnvironmentOptions): LinuxDistroInfo {
68
+ if (options?.osReleaseContent) {
69
+ const parsed = parseOSRelease(options.osReleaseContent);
70
+ const name = sanitizeHostMetadataText(parsed.PRETTY_NAME || parsed.NAME || parsed.ID || "Linux");
71
+ return { name, id: parsed.ID?.toLowerCase(), idLike: parsed.ID_LIKE?.toLowerCase() };
72
+ }
73
+
74
+ for (const p of ["/etc/os-release", "/usr/lib/os-release"]) {
75
+ try {
76
+ if (fs.existsSync(p)) {
77
+ const content = fs.readFileSync(p, "utf8");
78
+ const parsed = parseOSRelease(content);
79
+ const name = sanitizeHostMetadataText(parsed.PRETTY_NAME || parsed.NAME || parsed.ID || "Linux");
80
+ return { name, id: parsed.ID?.toLowerCase(), idLike: parsed.ID_LIKE?.toLowerCase() };
81
+ }
82
+ } catch {}
83
+ }
84
+
85
+ return { name: "Linux" };
86
+ }
87
+
88
+ function checkIsWsl(options?: HostEnvironmentOptions): boolean {
89
+ if (options?.isWsl !== undefined) return options.isWsl;
90
+ if (process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP) return true;
91
+ try {
92
+ if (fs.existsSync("/proc/version")) {
93
+ const version = fs.readFileSync("/proc/version", "utf8");
94
+ return /microsoft|wsl/i.test(version);
95
+ }
96
+ } catch {}
97
+ return false;
98
+ }
99
+
100
+ /**
101
+ * Reset in-memory memoized host environment (useful for tests).
102
+ */
103
+ export function resetHostEnvironmentCache(): void {
104
+ memoizedHostEnv = null;
105
+ }
106
+
107
+ /**
108
+ * Render concise factual host environment block.
109
+ * Safe from prompt injection: contains only trusted OS, shell, and platform guidance.
110
+ */
111
+ export function renderHostEnvironment(options?: HostEnvironmentOptions): string {
112
+ if (!options && memoizedHostEnv) {
113
+ return memoizedHostEnv;
114
+ }
115
+
116
+ const platform = options?.platform ?? process.platform;
117
+ const arch = options?.arch ?? process.arch;
118
+ const isWin = platform === "win32";
119
+ const isMac = platform === "darwin";
120
+
121
+ if (isWin) {
122
+ const osName = getWindowsVersion();
123
+ const lines = [
124
+ "<host_environment>",
125
+ `Platform: ${osName} (${platform} ${arch})`,
126
+ "Shell: bash (Git Bash / MSYS2)",
127
+ "Line Endings: Preserved per-file (auto-detects CRLF / LF)",
128
+ "Platform Guidance:",
129
+ "- Terminal commands run through Git Bash: use POSIX syntax (ls, grep, cat, find, &&, 2>/dev/null).",
130
+ "- Paths: Use forward slashes (C:/Users/...) for native Windows tools (node, cargo, python).",
131
+ "- Python binary: invoke as 'python' ('python3' is Windows Store stub).",
132
+ "- Non-profile PowerShell: prefer .NET ([System.Security.Cryptography.SHA256]) or certutil over autoloaded cmdlets like Get-FileHash.",
133
+ "</host_environment>",
134
+ ];
135
+ const result = lines.join("\n");
136
+ if (!options) memoizedHostEnv = result;
137
+ return result;
138
+ }
139
+
140
+ if (isMac) {
141
+ const lines = [
142
+ "<host_environment>",
143
+ `Platform: macOS (${platform} ${arch})`,
144
+ "Shell: bash (macOS /bin/bash v3.2)",
145
+ "Line Endings: Preserved per-file (auto-detects CRLF / LF)",
146
+ "Platform Guidance:",
147
+ "- Stock /bin/bash is Bash 3.2: use POSIX sh / Bash 3.2 constructs (indexed arrays, while read loops, tr/awk); avoid Bash 4+ features (declare -A, mapfile/readarray, ${var^^}).",
148
+ "- BSD userland: use portable POSIX flags (e.g. sed -i '' for in-place edit, not GNU sed -i).",
149
+ "</host_environment>",
150
+ ];
151
+ const result = lines.join("\n");
152
+ if (!options) memoizedHostEnv = result;
153
+ return result;
154
+ }
155
+
156
+ // Linux
157
+ const distro = resolveLinuxDistro(options);
158
+ const isWsl = checkIsWsl(options);
159
+ const hostDisplay = isWsl ? `${distro.name} on WSL` : distro.name;
160
+
161
+ const rules: string[] = [];
162
+ const id = distro.id || "";
163
+ const idLike = distro.idLike || "";
164
+
165
+ if (id === "alpine") {
166
+ rules.push("- Alpine Linux (musl libc): package manager is 'apk'; glibc-linked binaries are incompatible without gcompat.");
167
+ } else if (id === "arch") {
168
+ rules.push("- Arch Linux (glibc): package manager is 'pacman'.");
169
+ } else if (id === "fedora" || id === "rhel" || id === "centos" || idLike.includes("fedora") || idLike.includes("rhel")) {
170
+ rules.push("- Fedora/RHEL Linux (glibc): package manager is 'dnf' / 'yum'.");
171
+ } else if (id === "debian" || id === "ubuntu" || idLike.includes("debian")) {
172
+ rules.push("- Debian/Ubuntu Linux (glibc): package manager is 'apt'.");
173
+ }
174
+
175
+ const lines = [
176
+ "<host_environment>",
177
+ `Platform: ${hostDisplay} (${platform} ${arch})`,
178
+ "Shell: bash",
179
+ "Line Endings: Preserved per-file (auto-detects CRLF / LF)",
180
+ ];
181
+
182
+ if (rules.length > 0) {
183
+ lines.push("Platform Guidance:", ...rules);
184
+ }
185
+
186
+ lines.push("</host_environment>");
187
+ const result = lines.join("\n");
188
+ if (!options) memoizedHostEnv = result;
189
+ return result;
190
+ }
@@ -27,7 +27,61 @@ export interface ClampingResult {
27
27
 
28
28
  const SPILL_PREFIX = "pi_bash_spillover_";
29
29
  const DEFAULT_SPILL_FILES = 20;
30
- const DEFAULT_SPILL_BYTES = 50 * 1024 * 1024;
30
+ export const DEFAULT_SPILL_BYTES = 50 * 1024 * 1024;
31
+
32
+ function isWithinDir(candidatePath: string, parentDir: string): boolean {
33
+ const isWindows = process.platform === "win32";
34
+ const parent = isWindows ? parentDir.toLowerCase() : parentDir;
35
+ const candidate = isWindows ? candidatePath.toLowerCase() : candidatePath;
36
+ const rel = path.relative(parent, candidate);
37
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
38
+ }
39
+
40
+ /**
41
+ * Validate whether a resolved file path is an authenticated spillover log.
42
+ * Supports both Agent Kernel spillover logs and host harness temporary logs.
43
+ * Canonicalizes directories via realpathSync to resolve symlinks and Windows short paths.
44
+ */
45
+ export function isSpilloverFilePath(candidatePath: string, cwd = process.cwd()): boolean {
46
+ try {
47
+ const trimmed = candidatePath.trim().replace(/^["']|["']$/g, "");
48
+ if (trimmed.startsWith("\\\\") || trimmed.startsWith("//")) return false;
49
+
50
+ const resolved = path.resolve(trimmed);
51
+ if (!fs.existsSync(resolved)) return false;
52
+
53
+ const lstat = fs.lstatSync(resolved);
54
+ if (lstat.isSymbolicLink() || !lstat.isFile()) return false;
55
+
56
+ const uid = typeof process.getuid === "function" ? process.getuid() : undefined;
57
+ if (uid !== undefined && lstat.uid !== uid) return false;
58
+ if (lstat.size > DEFAULT_SPILL_BYTES) return false;
59
+
60
+ const base = path.basename(resolved);
61
+ const isKernel = /^pi_bash_spillover_[a-f0-9]+\.log$/i.test(base);
62
+ const isHost = /^pi-(?:bash|powershell|output)-[a-f0-9]+\.log$/i.test(base);
63
+ if (!isKernel && !isHost) return false;
64
+
65
+ const realResolved = fs.realpathSync(resolved);
66
+ const realParent = path.dirname(realResolved);
67
+
68
+ const realTemp = fs.realpathSync(os.tmpdir());
69
+ if (isWithinDir(realParent, realTemp)) return true;
70
+
71
+ const kernelRoot = path.resolve(getSpilloverRoot(cwd));
72
+ if (fs.existsSync(kernelRoot)) {
73
+ const realKernelRoot = fs.realpathSync(kernelRoot);
74
+ if (isWithinDir(realParent, realKernelRoot)) return true;
75
+ }
76
+
77
+ const realCwd = fs.realpathSync(path.resolve(cwd));
78
+ if (isWithinDir(realParent, realCwd)) return true;
79
+
80
+ return false;
81
+ } catch {
82
+ return false;
83
+ }
84
+ }
31
85
 
32
86
  export function getSpilloverRoot(cwd = process.cwd()): string {
33
87
  const base = getPiHomeDir();
@@ -145,11 +199,14 @@ export function isExecutionOrTestCommand(command: string): boolean {
145
199
  return /\b(test|vitest|jest|pytest|ava|mocha|cargo|tsc|build|check)\b/.test(trimmed);
146
200
  }
147
201
 
202
+ const HOST_STATUS_REGEX =
203
+ /(?:\r?\n){1,2}((?:Command (?:exited with code -?\d+|timed out after \d+(?:\.\d+)? seconds?)|(?:Process|Command) terminated[^\r\n]*))[ \t\r\n]*$/;
204
+
148
205
  const HOST_TRUNCATION_REGEX =
149
- /(?:\r?\n){1,2}\[(?:Showing (?:lines \d+-\d+ of \d+(?: \([^)]+\))?|last [^)]+\))\.[ \t]*Full output:|Truncated by host harness\.[ \t]*Full:)[ \t]*([^\]\r\n]+?)(?:[ \t]+\(use offset\/limit with read if needed\))?\][ \t\r\n]*$/;
206
+ /(?:\r?\n){1,2}\[(?:Showing (?:lines \d+-\d+ of \d+(?: \([^)]+\))?|last [^\]\r\n]+?)\.[ \t]*Full output:|Truncated by host harness\.[ \t]*Full:|Full output:[ \t]*|(?:Output truncated\.[ \t]*)?Full output:[ \t]*)([^\]\r\n]+?)(?:\.[ \t]*Truncated:[^\]\r\n]*|[ \t]+\(use offset\/limit[^)]*\)|[ \t]+\(read (?:it )?with offset\/limit\))?\][ \t\r\n]*$/;
150
207
 
151
208
  const KERNEL_TRUNCATION_REGEX =
152
- /(?:\r?\n){2}\[Truncated[^\r\n\]]*?(?:\.[ \t]*(?:Full|Spillover):[ \t]*([^\]\r\n]+?)(?:[ \t]+\(use offset\/limit[^)]*\)|[ \t]+\(received fragment only\))?)?\][ \t\r\n]*$/;
209
+ /(?:\r?\n){2}\[Truncated[^\r\n\]]*?(?:\.[ \t]*(?:Full|Spillover):[ \t]*([^\]\r\n]+?)(?:[ \t]+\(use offset\/limit[^)]*\)|[ \t]+\(received fragment only\))?)?\](?:\r?\nTo inspect omitted lines[^\r\n]*)?(?:\r?\n\r?\n(?:Command (?:exited with code -?\d+|timed out after \d+(?:\.\d+)? seconds?)|(?:Process|Command) terminated[^\r\n]*))?[ \t\r\n]*$/;
153
210
 
154
211
  function validateHostSpilloverPath(candidatePath: string): string | undefined {
155
212
  try {
@@ -175,11 +232,7 @@ function validateHostSpilloverPath(candidatePath: string): string | undefined {
175
232
  const realTempDir = fs.realpathSync(os.tmpdir());
176
233
  const parentDir = path.dirname(realResolved);
177
234
 
178
- const isSameDir = process.platform === "win32"
179
- ? parentDir.toLowerCase() === realTempDir.toLowerCase()
180
- : parentDir === realTempDir;
181
-
182
- if (!isSameDir) {
235
+ if (!isWithinDir(parentDir, realTempDir)) {
183
236
  return undefined;
184
237
  }
185
238
 
@@ -218,18 +271,28 @@ export function clampCommandOutput(
218
271
  let priorKernelTruncated = false;
219
272
  let hostSpilloverPath: string | undefined;
220
273
  let priorSpilloverPath: string | undefined;
274
+ let hostStatusTrailer: string | undefined;
275
+
276
+ // Strip and remember host command status trailer if present (e.g. "Command exited with code 1")
277
+ const statusMatch = textToProcess.match(HOST_STATUS_REGEX);
278
+ if (statusMatch && statusMatch.index !== undefined) {
279
+ hostStatusTrailer = statusMatch[1].trim();
280
+ textToProcess = textToProcess.slice(0, statusMatch.index);
281
+ }
221
282
 
222
- const hostMatch = rawText.match(HOST_TRUNCATION_REGEX);
283
+ const hostMatch = textToProcess.match(HOST_TRUNCATION_REGEX);
223
284
  if (hostMatch && hostMatch.index !== undefined) {
224
285
  hostTruncated = true;
225
- textToProcess = rawText.slice(0, hostMatch.index);
286
+ textToProcess = textToProcess.slice(0, hostMatch.index);
226
287
  const candidate = hostMatch[1].trim();
227
288
  hostSpilloverPath = validateHostSpilloverPath(candidate);
228
- } else {
229
- const kernelMatch = rawText.match(KERNEL_TRUNCATION_REGEX);
289
+ }
290
+
291
+ if (!hostTruncated) {
292
+ const kernelMatch = textToProcess.match(KERNEL_TRUNCATION_REGEX);
230
293
  if (kernelMatch && kernelMatch.index !== undefined) {
231
294
  priorKernelTruncated = true;
232
- textToProcess = rawText.slice(0, kernelMatch.index);
295
+ textToProcess = textToProcess.slice(0, kernelMatch.index);
233
296
  const candidate = kernelMatch[1]?.trim();
234
297
  if (candidate) {
235
298
  const cleanCandidate = candidate.replace(/\s*\(use offset\/limit.*\)$/i, "").trim();
@@ -315,7 +378,7 @@ export function clampCommandOutput(
315
378
  const directory = options?.spilloverDir || getSpilloverRoot();
316
379
  const maxFiles = options?.maxSpilloverFiles ?? DEFAULT_SPILL_FILES;
317
380
  const maxBytes = options?.maxSpilloverBytes ?? DEFAULT_SPILL_BYTES;
318
- spilloverPath = writeSpillover(textToProcess, directory, maxFiles, maxBytes);
381
+ spilloverPath = writeSpillover(rawText, directory, maxFiles, maxBytes);
319
382
  } catch (e) {
320
383
  kernelDebug(e);
321
384
  }
@@ -456,17 +519,18 @@ export function clampCommandOutput(
456
519
  let resultText = clampedLines.join("\n");
457
520
 
458
521
  const makeFooter = (linesShown: number): string => {
522
+ const statusSuffix = hostStatusTrailer ? `\n\n${hostStatusTrailer}` : "";
459
523
  if (hostTruncated || (priorKernelTruncated && hostSpilloverPath)) {
460
524
  if (hostSpilloverPath) {
461
525
  if (linesShown < totalLines) {
462
- return `\n\n[Truncated: ${linesShown} lines shown (host truncated). Full: ${hostSpilloverPath} (use offset/limit with read if needed)]`;
526
+ return `\n\n[Truncated: ${linesShown} lines shown (host truncated). Full: ${hostSpilloverPath} (use offset/limit with read if needed)]${statusSuffix}`;
463
527
  }
464
- return `\n\n[Truncated by host harness. Full: ${hostSpilloverPath} (use offset/limit with read if needed)]`;
528
+ return `\n\n[Truncated by host harness. Full: ${hostSpilloverPath} (use offset/limit with read if needed)]${statusSuffix}`;
465
529
  }
466
530
  if (spilloverPath) {
467
- return `\n\n[Truncated by host harness. Spillover: ${spilloverPath} (received fragment only)]`;
531
+ return `\n\n[Truncated by host harness. Spillover: ${spilloverPath} (received fragment only)]${statusSuffix}`;
468
532
  }
469
- return `\n\n[Truncated by host harness]`;
533
+ return `\n\n[Truncated by host harness]${statusSuffix}`;
470
534
  }
471
535
  let f = `\n\n[Truncated: ${linesShown}/${totalLines} lines.`;
472
536
  if (spilloverPath) {
@@ -478,7 +542,7 @@ export function clampCommandOutput(
478
542
  } else {
479
543
  f += `]`;
480
544
  }
481
- return f;
545
+ return `${f}${statusSuffix}`;
482
546
  };
483
547
 
484
548
  // Append concise footer with spillover pointer