Skip to content

feat(plugins): the generated loader replaces managed rc blocks — user rc read-only (niubash#359 case A, 1.4.2) - #421

Merged
caomengxuan666 merged 3 commits into
masterfrom
feat/rc-readonly-loader
Oct 18, 2026
Merged

caomengxuan666 merged 3 commits into
masterfrom
feat/rc-readonly-loader

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

What

niubash#359 case A (owner-approved), 1.4.2 slice per the design doc (promotion-drafts/design/rc-readonly-redesign.md §6): the sidecar manifest drives a generated loader, plugin management stops writing the user rc entirely, and niu plugin migrate-rc is the read-only migration diagnostic. The typed-writer half (config writer, startup.rc-policy, setup create-only) stays in 1.4.3 per schedule.

Design doc: D:/repo/promotion-drafts/design/rc-readonly-redesign.md — this PR implements its §3 案 A / §4 / §5 within the 1.4.2 row.

The loader (activation plane)

  • ~/.niubash/generated/plugins.niu (plugins::loader, $NIU_PLUGIN_LOADER_PATH overrides): rendered from plugins.toml + sources/registry.toml, deterministic (sections keyed/sorted by id, no timestamps — identical manifest state ⇒ byte-identical file), validate-then-atomic-publish (structural validation; the [rc][P3] .niubashrc rewrite is not atomic (concurrent readers can see it missing) #304 temp+rename swap; a failed generation keeps the last good one; a byte-identical regeneration is a no-op and does not churn mtime).
  • Per-source section bodies are byte-identical to the retired managed-block bodies (theme line, selection arrays, per-file guarded sources, static drift guard, adapter loader snippet) — activation semantics unchanged, position moved.
  • The header records the superseded managed-block marker pairs (design §2.3.3).

Host loading (read-only, ordered, guarded)

run_startup_files sources the loader before the user rc (user PS1/alias/function overrides win), in the interactive rc branch only — login chains and -c/BASH_ENV paths are untouched. startup_decision:

  1. NIU_PLUGIN_LOADER=off|false|0|no → skip (the rollback switch; load-only, zero writes, unset rolls forward);
  2. the rc text carries a superseded managed-block marker (exact/near/any-id shapes + recorded pairs) → skip — the old block is the live path (rather skip than double-execute), with a one-time migrate-rc hint (config-dir marker, fail-open; the only startup write, and only in the legacy-block situation — clean homes stay byte-for-byte untouched);
  3. otherwise load. The [P1] niu setup 完成后当前会话不生效:用户必须手动 source ~/.niubashrc —— 向导应在退出前应用新配置或明确即时生效 #180 in-session setup handoff re-sources it with the same decision.

W1–W5 retired, rollback kept

  • enable/disable/sync/update/restore/trust + theme picks write the sidecar manifest only: materialize_spec_selection splits into compute_spec_selection (pure selection + tree-side enabled/ effects) and one publish_loader_generation per pass (keep-current carry-over for skipped ids — awaiting-trust/degraded/drifted; silent drop for the undeclared pass).
  • write_managed_block / remove_managed_block / apply_block / write_block_report / deactivate_block remain in assets.rs as an unwired rollback zone (design §4.3: code-level rollback = small diff). Gate 359.12's structure ratchet (in tests/rc_readonly_loader.rs) pins their call-syntax count to the zone-internal shape and fails if any verb re-attaches them.
  • The write-era rc "repairs" retire with the write path: user-line migration-out, duplicate collapse, near-marker repair, verb-time backups. A [P1] plugin managed-block rewrite corrupts the rc: the moved-out user-lines guard is duplicated 6x with its fi stripped, leaving five dangling ifs and a syntax error on every startup #324-style corrupt rc is preserved byte-identically through every verb (gate 359.6) — the doctor names the debris instead of repairing it.
  • niu setup stops embedding managed blocks (the pick lands in the spec; record_theme_pick_in_spec publishes the generation). W6's whole-file rc write converges to create-only in 1.4.3 — noted in the ratchet as out-of-scope-for-now.

niu plugin migrate-rc [--diff] — never writes the rc

Scans exact + near markers (line ranges, ownership vs the spec, begin-without-end reported — never fatal), publishes the candidate generation from the current manifest, records the superseded pairs, and with --diff writes the suggested post-migration rc only under ~/.niubash/candidates/. Removal of old blocks is always the user's own edit.

Adjacent hardening (design §4.4)

save_spec and write_source_registry swap whole files atomically (#304 semantics generalized to the control plane).

Gate coverage (rubash#746 ratchet format)

New tests/rc_readonly_loader.rs:

case invariant status
359.4 every explicit verb leaves rc bytes+len+mtime identical (success AND failure paths) must-match (new)
359.6 #324 corrupt fixture survives sync/enable/disable/migrate-rc/doctor byte-identically must-match (new; the diverges→fixed flip)
359.7 generation byte-stable + idempotent (mtime untouched on no-op; atomic swap under an open reader) must-match (new; unit-level validate/publish tests in plugins::loader)
359.8 double-execution guard: legacy block ⇒ loader OFF + one-time hint; hand removal ⇒ loader ON; exactly one live path must-match (new)
359.9 loader before rc, user override wins; rollback switch skips with zero writes must-match (new)
359.12 structure ratchet: retired writers reachable from no verb (source audit) must-match (new)
359.1/359.2/359.3/359.11/359.13 startup zero-write matrix, legacy rc ignored, bootstrap no-op, registry corruption, marker consumption already pinned by stage-1 suites (startup_files.rs, plugin_bootstrap_read_only.rs, issue359_startup_pty.rs) — all green
359.5 / 359.10 setup create-only, config round-trip 1.4.3 (not in this PR, per schedule)

Existing suites flipped to the new contract (design §6: "rc 不变" replaces "rc 含块"): in-crate plugins::assets/plugins::sync/setup_wizard tests, plugin_assets, plugin_spec_sync, plugin_anyplug, defaults_floor, smoke_1_3_0.

Test evidence

  • Full workspace --test-threads=1 (--no-fail-fast), two-way failure comparison against a pre-change baseline run on pristine origin/master (d60276e):
    • baseline failures (environment/contention set, several base-confirmed in the fix(startup): a shell invoked as rbash starts restricted (#400) #413 CR): host_contract::rubash_setopt_is_visible_when_sourcing_startup_rc, interactive ×5 (continuation_*, ctrl_c_*, ctrl_d_*, gitbash_factory_*), niubash-runtime lib completion::command::tests::test_get_builtin_commands — identical set before and after; no new failures.
    • cargo fmt --check -p niubash clean; cargo build --locked clean; zero compiler warnings in the runtime crate.

Not in this PR (1.4.3, per the design schedule)

setup create-only + candidate file/diff for W6, config.rs writer rework → startup.rc-policy, gate 359.5/359.10, TRUST UX sub-item. Do not merge before the 1.4.1 release window closes — this branch rebases weekly onto origin/master.

Refs: niubash#359 · #324 · #304 · #413 (activation-timing CR that informed the startup-file placement)

… rc read-only (niubash#359 case A, 1.4.2)

Case A of the #359 design (promotion-drafts/design/rc-readonly-redesign.md):
the control plane (plugins.toml + sources/registry.toml) drives a derived
activation plane, and the user rc is never written by plugin management.

- plugins::loader: ~/.niubash/generated/plugins.niu — deterministic
  render (sections sorted by id, no timestamps), structural validation,
  validate-then-atomic publish (niubash#304 swap; a failed generation
  keeps the last good one), superseded-marker record for the
  double-execution guard, $NIU_PLUGIN_LOADER_PATH override.
- Host loading: run_startup_files sources the loader BEFORE the user rc
  (user overrides win); startup_decision skips on the rollback switch
  (NIU_PLUGIN_LOADER=off) or a superseded managed-block marker in the rc
  (exactly one live activation path), with a one-time migrate-rc hint
  (config-dir marker, fail-open; the only startup write, and only in the
  legacy-block situation). #180 in-session re-apply re-sources it too.
- W1-W5 retired: enable/disable/sync/trust/restore/theme picks write the
  sidecar manifest only; materialize_spec_selection becomes
  compute_spec_selection + one publish_loader_generation per pass
  (keep-current carry-over for skipped ids; drop_silent for the
  undeclared pass). The rc writers stay as an UNWIRED rollback zone
  (design §4.3); gate 359.12's structure ratchet pins them unreachable
  from any verb.
- niu plugin migrate-rc [--diff]: read-only diagnostic — scans exact +
  near markers (malformed begin-without-end reported, never fatal),
  publishes the candidate generation, records the superseded pairs,
  writes the suggested post-migration rc ONLY under
  ~/.niubash/candidates/. Never touches the rc.
- Wizard: generate_rc embeds no activation content (the pick lands in
  the spec via record_theme_pick_in_spec, which now publishes the
  generation); W6's whole-file write converges to create-only in 1.4.3.
- Doctor: read-only plugin-loader / legacy-block / #324-debris rows.
- spec/registry writers atomic (design §4.4).
- Tests: tests/rc_readonly_loader.rs pins gate cases 359.4 (verbs never
  write the rc, success and failure), 359.6 (#324 corrupt rc preserved
  byte-identically), 359.7 (byte-stable idempotent generation),
  359.8 (double-execution guard + hand removal), 359.9 (order/override +
  rollback switch, zero writes), 359.12 (structure ratchet), migrate-rc
  and the doctor rows. Existing plugin/wizard/theme suites flipped to
  the loader + rc-untouched contract; startup/paste/host regression
  sets match the pre-change baseline two-way (--test-threads=1).

Refs: niubash#359 (case A, owner-approved). Not closing: 359.5/359.10
(setup create-only, config writer) land in 1.4.3 per schedule.
…cate, tree-wide structure ratchet, regeneration keep-current

CR findings (all verified fixed):

- F1: the 359.12 ratchet now walks the ENTIRE production source tree
  (both crates' src/ and the binary src/, no closed file list), with
  zero-tolerance absence checks outside the rollback zone — the
  compile-passing mutation (pub deactivate_block reached from
  setup_wizard.rs) is closed twice: deactivate_block demoted to private
  (pub restoration is part of the rollback itself) and the tree-wide
  scan. Mutation-verified: a pub-again + cross-module-call variant now
  fails the ratchet by name.
- F2: the double-execution guard, migrate-rc and the doctor share ONE
  predicate (guard_trip_lines): the loader is held off exactly when a
  marker pair (exact/near/any-id, plus recorded superseded lines) wraps
  executable content. Marker-shaped remarks — a single-line
  '# >>> niu source blocks were removed by hand ... <<<', lone markers,
  comment-only pairs — are inert and never hold the loader off; and when
  the guard DOES trip (an id-less pair the id-anchored scan cannot
  attribute), migrate-rc names the trip lines instead of printing
  'clean' (MigrateReport::guard_trips + loader_held_off; the doctor row
  triggers on the same evidence). New gate test
  migrate_rc_names_guard_trips_the_scan_cannot_attribute.
- F3: regenerate_loader_generation keeps the current section for spec
  entries that resolve to an id but have no registry record yet (a
  regeneration on migrate-rc must never silently de-activate); only
  never-resolvable entries are omitted, which is a no-op.
- Nits: build_theme_block doc refreshed (preview renderer, no write
  path); migrate-rc second-run assertion formats its own output; the
  359.9 self-comparison removed; the in-session setup re-apply now
  sources the loader BEFORE setting NIU_REPL_STARTUP, same order as
  run_startup_files.

Refs: niubash#359, PR #421 CR round 1.
@caomengxuan666

Copy link
Copy Markdown
Member Author

CR round 1 — all three findings fixed (ff171fc, rebased onto master b3c9c52)

F1 (structure ratchet) — fixed, mutation-verified

  • The ratchet now walks the entire production source tree (crates/niubash-runtime/src/** + src/**, every .rs, no closed file list): assets.rs gets the exact zone-shape counts; every other file gets zero-tolerance absence checks on raw text (test modules included — the integration surface must not exercise the retired path either). setup_wizard.rs, repl.rs, trust.rs and any future module are covered by construction; a file-count floor guards against the walk silently finding nothing.
  • deactivate_block demoted pub → private (doc notes restoring pub is part of the rollback itself).
  • Mutation verification, both directions:
    • the CR's shape (setup_wizard.rs referencing the writer): now a build failure (private) — and a text-only variant (pub-again + cross-module call from sync.rs) fails the ratchet by name: crates/...\plugins\sync.rs references write_managed_block( — the retired rc writer leaked out of the rollback zone.
    • the exact counts on assets.rs still pin the zone shape, so a wrapper inside the zone also trips.

F2 (guard/diagnostics vocabulary) — fixed via your option (b) + (a)

  • One shared predicate, loader::guard_trip_lines: the loader is held off exactly when a marker pair (exact/near/any-id, plus exact lines the generation recorded as superseded) wraps executable content — a non-blank, non-comment line between begin and end. Marker lines are comments: the CR's example (# >>> niu source blocks were removed by hand … <<< on one line), lone markers, and comment-only pairs are inert and never hold the loader off. startup_decision, migration_notice_if_needed, migrate-rc and the doctor all call this one predicate.
  • Remedy visibility (option a): MigrateReport::guard_trips + loader_held_off() — when the guard trips on lines the id-anchored scan cannot attribute (e.g. an id-less pair), migrate-rc prints a guard: section naming the trip lines and never prints "clean"; the doctor row triggers on the same evidence and lists guard trip at line N. The "宁关勿双执行" direction is unchanged — what changed is that a held-off loader can no longer be diagnosed as fine.
  • New gate test migrate_rc_names_guard_trips_the_scan_cannot_attribute pins the end-to-end mismatch case (id-less pair → guard: section, no clean:; hand-removal → clean:), and the loader unit test now covers the CR example, comment-only pairs, near shapes, and recorded-marker pairs in both directions.

F3 (regeneration doc vs code) — fixed

regenerate_loader_generation now inserts spec entries that resolve to an id but have no registry record into keep_current — their activation, if any was ever published, carries over instead of being silently dropped (a skip never de-activates). Only entries resolving to no id at all are omitted, which is a no-op (nothing was ever published for them). Doc comment rewritten to match.

Nits — all taken

build_theme_block doc refreshed (pure preview renderer, no write path); the migrate-rc second-run assertion formats its own output; the 359.9 self-comparison removed; the in-session setup re-apply now sources the loader before setting NIU_REPL_STARTUP, same order as run_startup_files.

Rebase + test evidence

Ready for re-review — focus areas per your note: F1 mutation re-verification (the tree walk + the private demotion) and F2 predicate sharing.

@caomengxuan666
caomengxuan666 force-pushed the feat/rc-readonly-loader branch from 7aad5e0 to ff171fc Compare October 18, 2026 18:46
@caomengxuan666

Copy link
Copy Markdown
Member Author

CR round 2 — verdict: REQUEST-CHANGES (one blocking finding; F1/F3/nits verified fixed)

Independent re-verification on ff171fc (own worktree, own builds). F1, F3 and all four nits are confirmed fixed — mutation re-run included. One new blocking finding: the F2 fix overshot and reintroduced a fail-open hole in the guard.

✅ F1 (structure ratchet) — fixed, mutation re-verified both ways

  • Tree walk read: runtime/src/** + src/**, every .rs (61 files found, floor 40 — healthy headroom), raw text, zero tolerance outside assets.rs, zone-internal count pins inside it. No closed list remains; a new module is covered by construction.
  • Mutation 1 (CR-original shape): setup_wizard.rs referencing deactivate_block → build failure (error[E0603]: function 'deactivate_block' is private) — the privatization catches it at compile time. Restored.
  • Mutation 2 (covert variant): pub restored on the zone fn + cross-module call from sync.rs → ratchet fails by name: plugins\sync.rs references deactivate_block( — the retired rc writer leaked out of the rollback zone`. Restored.

✅ F3 (regeneration keep-current) — fixed

resolve_entry_id → keep_current for record-less spec entries (a skip never de-activates, matching the sync skip semantics); entries resolving to no id are a genuine no-op; the doc comment now says exactly what the code does.

✅ Nits — all four verified (build_theme_block doc, again_report, self-comparison removed, NIU_REPL_STARTUP ordering unified). Upstream files in the rebase (completion/command.rs, shell_links.rs, winuxcmd.rs, host_contract, interactive, i368 audit doc) confirmed to come from b3c9c52, no smuggles.

❌ NEW — F2′ (blocking): an unpaired BEGIN marker no longer trips the guard, and the rc body under it still executes

guard_trip_lines requires a begin→end PAIR before checking for executable content, and treats an unpaired begin as "an inert comment". But both markers are just comments to bash — the block BODY is plain shell code and runs unconditionally, with or without its end marker. A begin marker whose end marker was lost (hand edit / partial restore — exactly the end_missing state this PR's own scanner models and its own CLI calls "malformed — still executes") leaves live write-era code executing while the loader loads on top of it.

Live repro on this branch's binary (loader = generated section mark, legacy = rc body mark):

rc:
  # >>> niu source oh-my-bash (managed by `niu plugin enable/disable`) >>>
  export LEGACY_BLOCK_RUNS=yes        # (end marker lost)

$ niu -i -c 'printf "loader=[%s] legacy=[%s]" ...'
loader=[on] legacy=[yes]        ← ff171fc: DOUBLE EXECUTION
loader=[]   legacy=[yes]        ← 7aad5e0 (round 1): loader held OFF, safe

Two aggravating symptoms in the same state:

  • doctor prints "the generated loader stays OFF while they execute" — factually false here. doctor.rs computes legacy_held = blocks_present || guard_trips but the "stays OFF" wording is keyed on blocks-present, contradicting its own comment ("the doctor reports the guard's OWN evidence").
  • migrate-rc lists the block as "malformed — still executes" and its next-steps say "restart niu — the generated loader takes over automatically" — which is only true because the guard fails open.

Suggested fix (small, keeps everything round 2 got right):

  1. In guard_trip_lines, an unpaired begin trips when any non-blank, non-comment line follows it (to EOF) — the write-era body below a begin marker is live code. Comment-only pairs and the single-line >>>…<<< remark stay inert (the CR-example remark carries both decorations and is unclassified, so this does not reopen it). This is the 359.8 fail-safe direction: rather off than double-execute.
  2. Key the doctor's "stays OFF" wording on guard_trips (the guard's own evidence), not on blocks-present.
  3. Add gate tests: lone begin + executable body → guard trips / loader OFF; the end_missing doctor row no longer contradicts the loader state.

Regression & baseline (this round, run independently)

#413

Still open; the rebase kept the loader placement intact (login → POSIX $ENV → no_rc → loader → rc). No conflict today; run_startup_files remains the known collision point for the next weekly rebase.

Once F2′ lands (the predicate fix + doctor wording + tests), this is ready from my side — everything else is green.

…ntent holds the loader off (F2-prime)

The pairing requirement made the write era's end_missing state fail
open: both markers are bash comments, so the block body below an unpaired
begin executes unconditionally — the CR measured the double execution on
ff171fc. Fix, per the CR's direction (359.8 fail-safe, CASE-1 preserved):

- guard_trip_lines rule 2: an unpaired begin with ANY executable line
  below it trips the guard (niu cannot attribute the following lines —
  rather off than double-execute). Inert stays inert: the single-line
  remark, a lone marker followed only by comments/blanks, and
  comment-only pairs never trip.
- doctor: the 'stays OFF' claim is keyed on the guard's verdict
  (guard_trips), not on the block scan — an inert legacy pair is now
  reported as 'comments only, loader unaffected' instead of being
  claimed to hold the loader off (the self-contradiction the CR
  measured).
- Gate tests, both sides: lone_begin_with_executable_content_holds_the_
  loader_off (end_missing rc → loader OFF, migrate-rc refuses 'clean',
  doctor says 'stays OFF', hand removal releases the loader) and
  lone_begin_with_only_comments_keeps_the_loader_on (inert stray →
  loader ON, migrate-rc reads clean). Unit tests cover both directions
  in the shared predicate.

Refs: niubash#359, PR #421 CR round 2.
@caomengxuan666

Copy link
Copy Markdown
Member Author

CR round 2 — F2-prime fixed (d5ee41c)

The rule: guard_trip_lines now trips in exactly two situations, both "content that executes under a marker this product wrote":

  1. a marker pair (exact/near/any-id + recorded superseded lines) wrapping executable content — unchanged from round 1;
  2. an unpaired begin with ANY executable line below it (new, the CR's fix): both markers are bash comments, so the end_missing body executes unconditionally, and niu cannot attribute the following lines — rather off than double-execute.

Inert stays inert (CASE-1 not regressed): the single-line remark # >>> niu source blocks were removed by hand … <<<, a lone marker followed only by comments/blanks, and comment-only pairs never trip.

Doctor self-contradiction fixed: the "stays OFF" claim is now keyed on the guard's verdict (guard_trips), not on the block scan. An inert legacy pair (comments only) is reported as "inert (comments only — nothing executes, the loader is unaffected)" — the doctor can no longer claim a hold the guard is not applying, nor miss one it is.

Gate tests, both sides (the two you asked for):

  • lone_begin_with_executable_content_holds_the_loader_off — the CR's measured end_missing shape: loader mark absent, rc mark present (no double execution); migrate-rc refuses clean:; doctor prints "stays OFF"; deleting the stray marker by hand releases the loader (exactly one live path again).
  • lone_begin_with_only_comments_keeps_the_loader_on — an inert stray (id-less marker + comments only): loader mark present, migrate-rc reads clean:.

Unit tests in the shared predicate cover both directions plus the boundary (lone begin + comments-only below → inert).

Evidence: runtime lib 550 passed / 0 failed (the upstream 8dc298f setopt fix cleared the last baseline lib failure); gate file 13/13; plugin_assets / plugin_spec_sync / plugin_anyplug / smoke_1_3_0 / defaults_floor / startup_files / issue359_startup_pty / plugin_bootstrap_read_only all green; cargo fmt --check clean. Branch rebased on master b3c9c52 (ff171fc → d5ee41c on top).

Ready for your one-look merge pass — the lone-begin gate pair and the new predicate tests are the verification surface.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant