Skip to content

ripple v0.14.0

Choose a tag to compare

@github-actions github-actions released this 08 May 16:49
· 22 commits to master since this release

AI-ergonomics polish + a correctness/robustness sweep across file-tools, OSC parsing, console routing, and worker lifecycle. peek_console drops the PSReadLine "screen reader detected" warning ConPTY-launched pwsh reprints on every snapshot. LastExit: N no longer surfaces for bare $LASTEXITCODE = N assignments — only when AST analysis confirms a native exe actually ran. EditFile streams in one pass and emits ±2 lines of context per replacement so the AI doesn't have to re-read the file to confirm the change. File-tools moved to Microsoft.Extensions.FileSystemGlobbing.Matcher (path-segment globs now work correctly on Windows), gained symlink/junction cycle detection, and retry on transient AV/indexer sharing violations. Drift handling bails with a "Pipeline NOT executed" notice instead of silently re-injecting a cd preamble — the AI re-issues to accept the user's cwd or prepends the revert hint.

Changed

  • find_files / search_files glob backend switched to Microsoft.Extensions.FileSystemGlobbing.Matcher. The hand-rolled MatchGlob (regex from Regex.Escape + chained Replace) matched against either the file basename or the absolute path with / as the only path separator, so path-segment globs (src/**/*.cs) never engaged on Windows because absolute paths use \. Each file entry is now matched as a forward-slash root-relative path against an AddInclude(pattern) rule. Bare-basename ergonomics preserved — patterns without / or \ are auto-rewritten to **/<pattern> so *.cs still finds files at every depth. Our recursive walker is kept (Matcher's built-in walker doesn't honour SkipDirs, max_results, CancellationToken, or our symlink-cycle visited tracking); ct is now threaded through FindFilesRecursive so a deep tree is cancellable. Six new test scenarios cover top-level / one-level / multi-level matches, sibling exclusion, basename-anywhere ergonomics, and SkipDirs prune.

  • Adapter schema canonicalized on prompt.primary. Dropped PromptSpec.PrimaryRegex and the worker's Primary ?? PrimaryRegex fallback. SCHEMA.md was internally inconsistent (§6 listed prompt.primary_regex while the example block used primary); all 18 embedded YAML adapters declare primary:, and IgnoreUnmatchedProperties() would have silently dropped a hand-rolled external adapter using the alias anyway. SCHEMA.md row corrected to match the example block.

  • strip_ansi default flipped to true on execute_command / wait_for_completion. AI callers almost never want raw SGR bytes mixed into the text they reason about — leaving the default off meant every pwsh tool response carried the colorized prompt / status / error spans verbatim, costing tokens. Visible console output is unaffected (ripple's shared-console model deliberately preserves color for human viewing). Description updated to call out when setting false is the right move (you'll be quoting colored output back to the user, or inspecting compiler diagnostics where color carries semantic information).

  • EditFile streams in one pass and returns ±2 lines of context per replacement. Single-line old_string (the common shape) reads with a StreamReader, writes to a same-volume temp file with a StreamWriter, and atomically renames into place — no more loading the entire file into memory. A 2-slot rotating buffer holds recent lines so the response can show the lines before / on / after each match without buffering everything. Multi-line old_string keeps the whole-file path but also picks up ±2 line context around the first replacement so the response shape is uniform. Existing test contracts (Replaced N occurrence, Error: old_string not found, Error: old_string found N times) preserved.

Fixed

  • Drift bails with notice instead of silent cd preamble. When live cwd ≠ AI's last known cwd in the same console, ripple now returns a "Pipeline NOT executed" early result with prev → new cwd and a single-quote-escaped revert hint, then updates LastAiCwd to the live cwd so user-cd state is cleared. Pre-fix, an injected cd-preamble silently overrode the user's navigation intent — brittle if the user typed cd to set up a workspace they wanted the AI to use. The bail surrenders one round-trip but gives the AI full agency: re-issue to accept the user's cwd, or prepend the suggested revert. Mirrors PowerShell.MCP's safety-first drift policy (commit 32f0f56 there).

  • OSC parser caps inter-chunk carry at 256 KB. OscParser.Parse carries unterminated OSC payloads (no BEL/ST yet) across chunks via _buffer. A malformed PTY emitter, a torn frame, or an integration script that crashed mid-write would grow the buffer one chunk at a time without bound, eventually pinning worker memory. Cap leaves a ~60× margin over legitimate OSC 633 payloads (worst case OSC R: 1000-char base64-encoded error message ~1.4 KB). Once the cap trips, the parser flushes the buffered bytes as cleaned text (visible console may briefly show \x1b]633; smear, no data loss) and resets _buffer so subsequent valid OSCs parse normally. Two new tests cover both branches (16 KB under-cap round-trip + 300 KB unterminated bail).

  • Recursive file-walk detects symlink/junction cycles. A self-referential symlink (ln -s . loop) or a Windows junction pointing at an ancestor would send find_files / search_files spinning until either max_results clipped it short or the call stack overflowed. SkipDirs only catches named conventions like .git / node_modules; hand-crafted loops elsewhere went undetected. Visited directories are now tracked by their resolved real path (DirectoryInfo.ResolveLinkTarget(returnFinalTarget: true)); the walker bails before re-entering one. Set uses OrdinalIgnoreCase on Windows to match NTFS path semantics.

  • Orphan console claim threads the discovering agent's id. FindStandbyConsoleAsync is called from PlanExecutionAsync with the caller's agentId, but the second hop into TryFindInPipesAsync dropped that context — the claim payload and new pipe name were both built with a hardcoded "default". An orphan adopted by agent X ended up at RP.{proxy}.default.{pid} instead of RP.{proxy}.X.{pid}, breaking the per-agent routing partition documented in docs/ARCHITECTURE.md. In a multi-agent setup, agent A discovering and adopting an orphan effectively published it to the "default" partition where any other agent would route through it on the next tool call. Wire contract unchanged — purely a proxy-side correctness fix; the worker already reads agent_id from the claim payload and rebuilds its pipe name from it.

  • WriteFile / EditFile retry on transient sharing violations. On Windows with on-access antivirus, Defender, or the search indexer scanning a just-closed file in the window between StreamReader/StreamWriter dispose and the next write, File.Move(temp, path, overwrite: true) and File.WriteAllText intermittently raised UnauthorizedAccessException. Three write paths now wrap in a 5-attempt exponential backoff (50/100/200/400 ms, ~750 ms worst case before re-throw). Real permission errors raise the same exception types but don't go away on retry, so the cap stays tight; the AV-scan race typically clears in well under 100 ms. Verified by running the full test suite 5 times consecutively after a temp-dir clean — flake gone.

  • Worker drops broken termios ProcessExit handler (use-after-free). InputForwardLoopUnix registered a "belt-and-braces" termios restore for signal/crash exits, but the handler was broken on both paths it claimed to cover. On graceful exit, the thread's finally already restores termios and calls Marshal.FreeHGlobal(saved); the ProcessExit handler then tcsetattr(savedSnapshot)'d freed memory. On the signal/crash exits the comment claimed to cover (SIGTERM, SIGKILL, segfault), AppDomain.ProcessExit doesn't fire at all, so the handler wasn't catching what it advertised. Drop it. The finally-block restore is sufficient on graceful shutdown; a real signal-time restore would have to come from PosixSignalRegistration on a worker-lifetime buffer — left as a comment for whoever picks that up.

  • ReadFile validates offset / limit. Negative parameters were silently mishandled — offset = -1 bypassed the start-index gate (every line passes lineNum >= -1) and read from line 0 anyway; limit = -5 made lines.Count < limit uniformly false and returned an empty string with no diagnostic. Both come from MCP tool-call integers, so a clear validation error at the entry point beats silent empty / silent full responses.

  • VT InsertLines / DeleteLines rotate SoftWrap alongside Grid. Both ops shifted Grid rows but never touched the parallel SoftWrap array, so a freshly-blank inserted/displaced row inherited whatever soft-wrap flag was sitting at that index from the previous occupant. A subsequent renderer that consults IsRowSoftWrapped would treat the blank row as a wrap continuation of the row above, producing ghost merged-line artefacts on output that exercises IL/DL (full-screen editors, multi-line readline redraws). Walk both arrays in lockstep and explicitly clear the flag on the row that becomes blank.

  • Cached file-tools regexes carry the 1 s match timeout. SearchFiles's pattern is user-supplied; a pathological (a+)+b-shape regex against a long line would have run unbounded under the cache introduced this release. Apply the same 1 s per-match timeout already used by ModeDetector and RegexPromptDetector so a bad pattern surfaces as a clean RegexMatchTimeoutException (translated by MCP into a tool-call error) rather than a hung response. Glob patterns can't realistically backtrack catastrophically after the canned-replacement transform, but the cap is applied uniformly so every cached regex in the file shares one policy.

  • peek_console strips the PSReadLine "screen reader detected" startup banner. Every pwsh started under non-interactive ConPTY — i.e. every ripple-spawned pwsh — prints this multi-line warning at the top of the screen buffer, and it persists in the rolling peek window for a long time because nothing scrolls it out. The AI seeing the same banner on every peek call was pure noise. FilterStartupBanners detects the banner start, drops continuation lines until the closing marker (or a blank terminator), and swallows the trailing blank so the trimmed output starts cleanly with the prompt. Conservative — only activates on the banner prefix; capped at 5 dropped lines so an unusual buffer state can't eat real output.

  • $LASTEXITCODE reporting gated on AST-detected native invocation. A bare $LASTEXITCODE = 7 in pure PowerShell was indistinguishable from cmd /c exit 7 to the resolver — both updated the variable, both flipped $lecChanged, so the resolver emitted OSC L and the status line showed LastExit: 7 as if cmd.exe had returned non-zero. Phantom failure signal. __rp_pipeline_uses_native now AST-parses the last history command line, walks for CommandAst nodes, and resolves each name through InvokeCommand.GetCommand filtered to Application — only native exes return a hit. Without a native sighting, $LASTEXITCODE is treated as a stray variable whose value carries no exit-code meaning, the D code falls through to $?, and OSC L stays silent. Aliases pointing at natives miss (resolve as Alias) and functions wrapping natives miss (resolve as Function) — known static-analysis limitations, accepted as the conservative direction (fewer false positives is the goal). The check runs in the prompt fn, not in PreCommandLookupAction, so the GetCommand resolution can't recurse through the engine and re-fire the action mid-resolution (an earlier version of the patch did exactly that and hung worker startup).

  • UTF-16 trailing-newline detection works. FileMetadataHelper.DetectNewlineFromBytes checked the last raw byte for 0x0A / 0x0D, which works for UTF-8 but in UTF-16 LE the last byte of a trailing \n is 0x00 (the high byte) — the check missed it and the streaming EditFile writer would then drop the trailing newline on round-trip. Now the tail bytes are decoded through the detected encoding and the last character is checked. Uncovered by the existing FileToolsTests UTF-16 round-trip suite once EditFile switched to the streaming-write path.

Internal

  • Audit-pass mechanical hardening. Three locality-bound changes from a comprehensive code-review pass, all non-behavioural on the happy path, verified with --test (68/68): drop two dead schema properties (InitSpec.WaitAfterMs, OutputSpec.StripPromptEcho) — neither is read anywhere and IgnoreUnmatchedProperties() would silently drop them today; cap regex match runtime at 1 s in ModeDetector.Detect and RegexPromptDetector (constructor + Scan, with the Scan loop wrapping Matches enumeration so a mid-scan timeout surfaces whatever was already collected) so a hand-edited adapter with a catastrophic-backtracking pattern can't pin a worker thread on every PTY chunk; add a 64 MiB ceiling to ConsoleWorker.ReadMessageAsync's pipe-frame length prefix using (uint)len > cap so a torn frame or buggy proxy with a negative or multi-GiB length stops OOM-ing the worker.

  • Per-pattern compiled Regex cache in the hot paths. FileTools.MatchGlob (per file entry inside the recursive walk), FileTools.SearchFiles (user-supplied pattern across iterative edits), and ModeDetector.Detect (per-command poll loop) were rebuilding Regex objects per invocation despite stable pattern lifetimes. Regex.IsMatch's process-wide static cache only holds 15 patterns; on a tree with thousands of files this was N compilations per glob. Caches are ConcurrentDictionary<string, Regex> keyed by raw source pattern (or null sentinel for proven-invalid patterns), unbounded — distinct patterns per session are tens at most, each compiled Regex on the order of KB. If memory pressure ever shows up, swap for an LRU.

  • RotateBuffer<T> ported from PowerShell.MCP. Fixed-capacity rotating buffer. Used by streaming EditFile to keep the most recent N lines as pre-match context without buffering the entire file. Same shape and oldest-first iteration order as the upstream copy.

  • expect_no_last_exit AdapterTest field. Asserts the worker did NOT emit a non-zero lastExitCode for the eval. Strictly distinct from expect_exit_code: 0 (= the OSC D code, the overall pipeline outcome): a manual-assignment leak shows D=0 ($? stays true through a plain assignment) but L=N (phantom native exit), and only the new assertion catches the L side. Added the matching pwsh regression test (manual_lastexitcode_does_not_leak_in_pipeline); verified it fails on the pre-fix baseline before keeping it.

  • FileToolsTests strengthened with 12 streaming-context assertions. SJIS CRLF round-trip asserts the N: / N- marker shape survives Shift-JIS decoding; replace_all asserts every replaced line shows up; a 7-line fixture asserts the ±2 window (lines outside it are absent); a two-match fixture with a 4-line gap asserts middle lines fall outside both windows. Unique tokens (MID4 / MID5) where needed so an incidental letter in the path can't pollute the assertion.

  • ShellToolsTests (new) covers FilterStartupBanners end-to-end: no-op when banner absent, empty / null passthrough, full banner with wrap-broken word stripped (the common ConPTY case), banner-only snapshot reduces to empty, 5-line cap prevents runaway when the closing marker never arrives, banner appearing mid-snapshot with surrounding real content preserved on both sides.