Repository navigation
feat: --cwd-state directory memory for one-shot agent invocations - #272
Merged
Merged
Conversation
niu -c (engine route and the legacy launcher arm) now builds the shell
via Shell::new_one_shot(), which skips REPL-only initialization: the
prompt/theme backend construction (a bare placeholder takes its place),
the completion directory scan, and the final completion-state snapshot.
The history provider and managed aliases stay: the host contract pins
history/fc semantics for -c, and alias packs are config semantics, not
REPL state. bash -i -c keeps the full constructor because -i sources
the rc through the interactive branch.
The theme-preview channel is unaffected: it renders PS1 through the
engine's expand_prompt_string_mut after the precmd hooks, never through
the host prompt backend.
Adapted from x2410516039/xgr-niubash commit 890f3b1 ('perf: one-shot
fast path for -c / --encoded-command', 2026-09-19), where it was
measured at 13.9 -> 12.1 ms in-process startup for niu -c 'echo hello'
(exit trap 0.89 -> 0.37 ms) with a 29-case behavior battery at zero
diff. The skip list here is smaller than the fork's: themes, bundle
completions, native widget bindings, and oh-my-niu framework probes
have all since been externalized out of the host, so what remains to
skip is the prompt backend, the completion scan, and the completion
snapshot. cargo check --locked and cargo fmt --check --all clean;
contract tests run before merge.
New launcher word `niu --encoded-command <b64>` executes an RFC 4648 base64 command string through the same one-shot path as -c. Agents get a quoting-free channel: no heredoc gymnastics, no base64.exe subprocess, and no second interpretation layer between the caller and the parser. Padding is optional and ASCII whitespace is ignored so pre-wrapped payloads pass through untouched; the payload must decode to valid UTF-8. An optional `v1:` prefix is stripped defensively - MSYS path conversion rewrites arguments starting with '/', and a base64 payload can start with '/' (sextet 63); 'v' pins the first character. Same -c contract applies: BASH_ENV/NIU_ENV are sourced, the payload is exposed as BASH_EXECUTION_STRING, and parser diagnostics carry the __RUBASH_IS_C tag (niubash#160). Adapted from x2410516039/xgr-niubash commits 890f3b1 + deb7211 (2026-09-16). The v1: prefix came from a live failure: routing the payload through a Git Bash wrapper rewrote a leading '/' and corrupted the command. Verified here: decode unit tests (padding, whitespace, v1: prefix, invalid character, non-UTF-8 rejection), cargo check/fmt clean.
Opt-in directory memory so a chain of one-shot `niu -c` calls behaves like one shell: `niu --cwd-state <file>` restores the directory recorded in <file> before startup (before niu's own startup logic, relative script paths, and source_non_interactive_env) and records the shell's final directory back after every one-shot exit path. Without the flag, behavior is byte-for-byte unchanged - CI drivers and interactive callers keep a predictable start directory. Contract highlights (full document in docs/cwd-state.md): - recorded AFTER the exit trap (a trap's cd counts) and BEFORE exit-code propagation (`; pwd > state`, not `&& pwd > state`) - invalid/stale state heals silently; write failures never change the exit code; records are temp+rename atomic - the option scan is a prefix group, so positional parameters and bash-style options are never consumed - `-C/--repl-command` and the interactive REPL restore but never record - no NIU_CWD_STATE env form: `&`/coproc spin up new niu.exe processes that would inherit and pollute the state; a flag is call-scoped Shell::current_host_cwd() exposes "where did this invocation end" (PWD over process cwd: execute_script syncs the process cwd, but an EXIT trap's cd only updates PWD). Adapted from x2410516039/xgr-niubash commits 5c4ec1d + 2028f39 (2026-09-18/20). The design doc records the author's own deployment reversal: his DSH agent preset ultimately chose "one-shot cd + spawn cwd" over persistent cd (silent drift is the failure mode of directory memory), keeping --cwd-state for hosts that genuinely need cross-process cd - the doc names ZCode-style hooks as that host. Verified here: tests/cwd_state.rs 11/11 (roundtrip, failure-still- records, EXIT trap, subshell isolation, stale fallback, bare-path state file, parent-dir creation, opt-in neutrality, positional-param safety, relative-path pinning, missing-argument error); runtime smoke roundtrip on a debug build; workspace test failure set identical to unmodified master (see PR description); cargo check/fmt clean.
caomengxuan666
changed the base branch from
fix/upstream-xgr-encoded-command
to
master
October 12, 2026 02:33
caomengxuan666
added a commit
that referenced
this pull request
Oct 12, 2026
…it funnel CI root cause for the red `history_and_fc_use_the_host_history_provider` on this branch's Windows lane — and on master itself since #272: the one-shot exit funnel (`finish_one_shot`) ends every `niu -c` route through `std::process::exit`, which skips Drop, so the Drop-based session-end write (#265 — the only carrier of a GNU `history -c` to the file, the builtin clearing memory only, niubash#182) never fired on the -c path and `niu -c 'history -c'` silently kept the stale history file. Before #272 the funnel hard-exited only on nonzero statuses; rc=0 returned normally through main, the Shell unwound, the Drop flushed, and the test was green. #272 collapsed both arms into the `-> !` funnel and removed the rc=0 unwind without noticing it was load-bearing. Fix: Shell keeps a handle to its RubashHistoryProvider and the funnel calls `flush_session_history()` explicitly before the hard exit — the GNU shape anyway (exit_shell -> write_history, bashhist.c). Best-effort like every history-file write: no stderr, no rc change; interactive sessions that unwind keep the Drop as a second net. Evidence: master's own CI (run 38196596891, c3df161) is red with the identical assertion at tests/host_contract.rs:89; this commit turns the test green locally on a machine where the Drop path never fires, and the full-suite failure set drops to exactly the pre-existing environment-bound set.
caomengxuan666
added a commit
that referenced
this pull request
Oct 12, 2026
…l return + build.rs host-agnostic icon gate (#281) * fix(highlighting): color REPL-only commands (self-update, update-niubash, logout) as builtins (niu#260) self-update / update-niubash are intercepted by the REPL before engine command resolution, so they never resolve on PATH and the highlighter painted them as unknown tokens (red) even though they run fine (issue screenshot: red 'self-update' at the prompt). Same class of problem for 'logout', which is also a REPL-exact-match word. Add repl::is_repl_reserved_command as the shared predicate over REPL- reserved first words (exit, logout, self-update, update-niubash) and consult it from the highlighter's command-position classification, so these words get builtin styling instead of UnknownToken. Case-sensitive by design, matching the REPL's exact-match intercepts; argument positions are unaffected. Tests: highlighter repaints the three words as Builtin, argument position stays Default, predicate unit test covers exact-match semantics. * ci: gate the aarch64-linux-android and armv7-linux-androideabi cross-checks (niu#207 step 1) rubash#456 landed the bionic cfg fixes, so both android targets now check clean through rubash; this exposes them on the niubash side of the workspace check, same shape as the musl/ohos legs (#210/#221). Both targets verified green locally: cargo check --workspace --locked --target aarch64-linux-android and --target armv7-linux-androideabi. Two blockers surfaced and are fixed here: - arboard 3.6.1 (via reedline's system_clipboard feature) has no android backend and fails to compile for android targets. Gate the feature to non-android targets in Cargo.toml: Windows/macOS/Linux builds keep the system clipboard (arboard stays in their graphs), android loses Ctrl+V system paste behind a stub add_system_clipboard_keybindings, bracketed paste unaffected. - build.rs gated the icon .res embedding on #[cfg(windows)] - a HOST predicate. Cross-checking an android target from a Windows dev box made it run the SDK's arm64 rc.exe, an arm64 binary that cannot launch on x64 (os error 216). Gate on CARGO_CFG_TARGET_OS instead; the resource only links into PE binaries anyway. Ubuntu-hosted CI legs are unaffected either way. Part of niubash#207 (platform roadmap) step 1/2: make the compile surface visible and honest. Android remains compile-verified only - no release artifacts until a native smoke gate exists per docs/release.md red line. * fix(main): rc-0 one-shot exits return from main so the history session-end write runs Pre-existing master red (host_contract::history_and_fc_use_the_host_history_provider, failing on CI since 130598a): a one-shot 'niu -c history -c' left the history file holding the pre-clear list instead of truncating it. Root cause: 130598a routed every one-shot exit through finish_one_shot -> piped_stdout::finish_and_exit -> std::process::exit, which skips Rust destructors. RubashHistoryProvider::drop is the only thing that carries a GNU 'history -c' to the file at session end (niubash#265), so rc-0 -c sessions stopped flushing. 484dad3 (the original fast path) returned Ok(()) on rc 0 and only diverged on nonzero codes - the Drop ran and the test passed. finish_one_shot now calls piped_stdout::finish() and exits only on nonzero codes; rc 0 returns to the caller. Arms that previously relied on the always-diverging call tail now 'return Ok(())' explicitly so they cannot fall through into the script/REPL arms. Verified: the manual -c sequence (history; fc 2 / -s / -d 2 / -c) ends with an empty history file; 'exit 5' still propagates rc 5; host_contract and cwd_state suites green; cwd-state recording (the #272 feature) still runs before both exit forms. * fix(build): compile embed_windows_icon on every host - the call site is runtime-gated on the target OS 3ea224e (#207 step 1) moved the call site from host #[cfg(windows)] to a CARGO_CFG_TARGET_OS runtime check so a Windows host cross-checking an android target no longer runs the SDK's arm64 rc.exe (os error 216), but left the definition behind #[cfg(windows)]. On a linux/macOS host the call site now compiles while the definition is cfg'd out: E0425 on every non-Windows host (ubuntu/macos/android/ohos/armv7 cross-checks). Drop the cfg from the definition - it is std-only and dead unless the target is Windows.
caomengxuan666
added a commit
that referenced
this pull request
Oct 13, 2026
…1.4.0 section (#326) - The [Unreleased] entries (#284/#287, #293-#304, #313) move into [1.4.0]; [Unreleased] is empty again. - Newly recorded (today's wave): Git Bash compatible factory default prompt (#292, headline), WT-form shortcuts (#290/#211), the paste burst trailing-Enter fix (#308/#291), self-update SHA256 + release pinning (#311/#312), managed-block convergence (#324), completion tables/NIU_COMPDEFS/NIU_ENV probe (#305-#307), -s on-demand stdin (rubash#586 host half), bash/rbash invocation faces (#321/#322). - Older gaps recorded: closed-stdout pipe contract (#245/#286), history session-end write-back (#265), sh POSIX contract (#262), PWD persona alignment (#283), one-shot fast path (#270), --cwd-state (#272), --encoded-command (#271), REPL-command highlighting (#281), docs passes (#255/#225/#226/#227), MSRV (#267), easter-egg prune (#264). CHANGELOG-only change; no version claims.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
来源
适配自 x2410516039/xgr-niubash 提交
5c4ec1d+2028f39(2026-09-18/20),保留原作者署名。Stacked on #271。问题
niu -c是一次性的:agent 想让第二条命令落在正确目录,只能每条都写cd <root> &&。三层代价:token 浪费、命令意图被cd淹没、宿主若靠解析命令文本跟踪目录,在命令被包装成不透明 token 后彻底失效(他的文档 §1 把这三条写得很完整)。契约(设计文档随 PR:docs/cwd-state.md)
niu --cwd-state <file> [--cwd-state-verbose] <one-shot 调用>:<file>(JSON{"cwd":...,"updatedAt":...},容忍手写裸路径),有效则 chdir;发生在 niu 自身启动、相对脚本路径解析、source_non_interactive_env之前cd也算"最终在哪"——取Shell::current_host_cwd()即 PWD 优先)、记在退出码传播之前(; pwd > state而非&&——失败也记)niu -c 'echo $1' nm --cwd-state里的--cwd-state仍是位置参数;相对 state 路径启动时钉死为绝对路径(否则"从 A 读、往 B 写")-C/--repl-command与交互式 REPL 只恢复不记录;不做NIU_CWD_STATE环境变量形态(&/coproc 会自旋新 niu.exe 继承变量污染状态)关于方向的重要说明(原作者自己的反转,2028f39)
他的 DSH agent 预设最终没有采用"cd 持久"语义——静默漂移是目录记忆自身的失败模式;预设改为"一次性 cd + 会话目录由宿主 spawn cwd 传"。
--cwd-state保留给确实需要跨进程cd的宿主——他的文档 §7 点名 ZCode 风格 hook(niu --encoded-command包装加一个--cwd-state参数即得跨调用目录,天然按项目隔离)。本机 ZCode 部署正是这个形态,故值得上游。验证
tests/cwd_state.rs11 个契约测试全过(roundtrip、失败仍记录、EXIT trap、子 shell 不泄漏、失效回退、裸路径、自动建父目录、显式开关中性、位置参数安全、相对路径钉死、缺参报错)--cwd-state F -c 'cd D:/repo/research; pwd'→ 记录;再次--cwd-state F -c 'pwd'→ 直接落在D:/repo/research;状态文件为规范 JSONcargo check --locked/cargo fmt --check --all干净