Repository navigation
ripple v0.14.0
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_filesglob backend switched toMicrosoft.Extensions.FileSystemGlobbing.Matcher. The hand-rolledMatchGlob(regex fromRegex.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 anAddInclude(pattern)rule. Bare-basename ergonomics preserved — patterns without/or\are auto-rewritten to**/<pattern>so*.csstill finds files at every depth. Our recursive walker is kept (Matcher's built-in walker doesn't honourSkipDirs,max_results,CancellationToken, or our symlink-cycle visited tracking);ctis now threaded throughFindFilesRecursiveso a deep tree is cancellable. Six new test scenarios cover top-level / one-level / multi-level matches, sibling exclusion, basename-anywhere ergonomics, andSkipDirsprune. -
Adapter schema canonicalized on
prompt.primary. DroppedPromptSpec.PrimaryRegexand the worker'sPrimary ?? PrimaryRegexfallback. SCHEMA.md was internally inconsistent (§6 listedprompt.primary_regexwhile the example block usedprimary); all 18 embedded YAML adapters declareprimary:, andIgnoreUnmatchedProperties()would have silently dropped a hand-rolled external adapter using the alias anyway. SCHEMA.md row corrected to match the example block. -
strip_ansidefault flipped totrueonexecute_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 settingfalseis the right move (you'll be quoting colored output back to the user, or inspecting compiler diagnostics where color carries semantic information). -
EditFilestreams in one pass and returns ±2 lines of context per replacement. Single-lineold_string(the common shape) reads with aStreamReader, writes to a same-volume temp file with aStreamWriter, 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-lineold_stringkeeps 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
cdpreamble. 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 updatesLastAiCwdto 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 typedcdto 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.Parsecarries 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_bufferso 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 sendfind_files/search_filesspinning until eithermax_resultsclipped it short or the call stack overflowed.SkipDirsonly 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 usesOrdinalIgnoreCaseon Windows to match NTFS path semantics. -
Orphan console claim threads the discovering agent's id.
FindStandbyConsoleAsyncis called fromPlanExecutionAsyncwith the caller'sagentId, but the second hop intoTryFindInPipesAsyncdropped that context — the claim payload and new pipe name were both built with a hardcoded"default". An orphan adopted by agent X ended up atRP.{proxy}.default.{pid}instead ofRP.{proxy}.X.{pid}, breaking the per-agent routing partition documented indocs/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 readsagent_idfrom the claim payload and rebuilds its pipe name from it. -
WriteFile/EditFileretry 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)andFile.WriteAllTextintermittently raisedUnauthorizedAccessException. 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
ProcessExithandler (use-after-free).InputForwardLoopUnixregistered 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'sfinallyalready restores termios and callsMarshal.FreeHGlobal(saved); theProcessExithandler thentcsetattr(savedSnapshot)'d freed memory. On the signal/crash exits the comment claimed to cover (SIGTERM, SIGKILL, segfault),AppDomain.ProcessExitdoesn't fire at all, so the handler wasn't catching what it advertised. Drop it. Thefinally-block restore is sufficient on graceful shutdown; a real signal-time restore would have to come fromPosixSignalRegistrationon a worker-lifetime buffer — left as a comment for whoever picks that up. -
ReadFilevalidatesoffset/limit. Negative parameters were silently mishandled —offset = -1bypassed the start-index gate (every line passeslineNum >= -1) and read from line 0 anyway;limit = -5madelines.Count < limituniformly 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/DeleteLinesrotateSoftWrapalongsideGrid. Both ops shifted Grid rows but never touched the parallelSoftWraparray, 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 consultsIsRowSoftWrappedwould 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 byModeDetectorandRegexPromptDetectorso a bad pattern surfaces as a cleanRegexMatchTimeoutException(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_consolestrips 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.FilterStartupBannersdetects 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. -
$LASTEXITCODEreporting gated on AST-detected native invocation. A bare$LASTEXITCODE = 7in pure PowerShell was indistinguishable fromcmd /c exit 7to the resolver — both updated the variable, both flipped$lecChanged, so the resolver emitted OSC L and the status line showedLastExit: 7as if cmd.exe had returned non-zero. Phantom failure signal.__rp_pipeline_uses_nativenow AST-parses the last history command line, walks forCommandAstnodes, and resolves each name throughInvokeCommand.GetCommandfiltered toApplication— only native exes return a hit. Without a native sighting,$LASTEXITCODEis 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 inPreCommandLookupAction, so theGetCommandresolution 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.DetectNewlineFromByteschecked the last raw byte for0x0A/0x0D, which works for UTF-8 but in UTF-16 LE the last byte of a trailing\nis0x00(the high byte) — the check missed it and the streamingEditFilewriter 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 existingFileToolsTestsUTF-16 round-trip suite onceEditFileswitched 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 andIgnoreUnmatchedProperties()would silently drop them today; cap regex match runtime at 1 s inModeDetector.DetectandRegexPromptDetector(constructor + Scan, with the Scan loop wrappingMatchesenumeration 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 toConsoleWorker.ReadMessageAsync's pipe-frame length prefix using(uint)len > capso a torn frame or buggy proxy with a negative or multi-GiB length stops OOM-ing the worker. -
Per-pattern compiled
Regexcache in the hot paths.FileTools.MatchGlob(per file entry inside the recursive walk),FileTools.SearchFiles(user-supplied pattern across iterative edits), andModeDetector.Detect(per-command poll loop) were rebuildingRegexobjects 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 areConcurrentDictionary<string, Regex>keyed by raw source pattern (or null sentinel for proven-invalid patterns), unbounded — distinct patterns per session are tens at most, each compiledRegexon 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 streamingEditFileto 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_exitAdapterTest field. Asserts the worker did NOT emit a non-zerolastExitCodefor the eval. Strictly distinct fromexpect_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. -
FileToolsTestsstrengthened with 12 streaming-context assertions. SJIS CRLF round-trip asserts theN:/N-marker shape survives Shift-JIS decoding;replace_allasserts 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) coversFilterStartupBannersend-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.