Skip to content

fix(config): ignore discarded SecretRefs when applying batches - #131656

Merged
steipete merged 3 commits into
mainfrom
codex/config-preflight-owner-refactor
Aug 28, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/config-preflight-owner-refactor

Conversation

@steipete

@steipete steipete commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Related: #117128 (exec-provider preflight parity), #117051 (validation accepting a command startup rejects).

What Problem This Solves

Fixes ordered config batches validating discarded SecretRefs. A ref assigned early and replaced later—either at the same field or by replacing its parent—could still reject the final config or execute an obsolete provider during --dry-run --allow-exec.

Real CLI verification also exposed truncated JSON on failed commands: config handlers immediately exited after an asynchronous pipe write. One failing dry run emitted only 512 bytes. This follow-up repairs both ownership boundaries while simplifying the surrounding code.

Why This Change Was Made

The mutation validator now selects references and affected providers from the completed candidate. It preserves registry-owned sibling-ref precedence, changed-default behavior, canonical model keys, and references that move during an agent rename. Persistence retains its explicit write paths, include ownership, roster protections, and no-op handling.

Input parsing, validation decisions, output formatting, and persistence have separate owners. The cleanup removes four derived operation fields, duplicate assignment builders and mode selection, redundant config/schema cloning, and the separate dry-run validation branch. Existing integration coverage is split by behavior without adding test-only production seams.

Already-reported config failures now unwind through the shared CLI finalizer. Resources close and output drains before exit; typed exits retain their status and are not formatted as another error. Injected runtimes keep ownership of their own exit behavior. The snapshot guard's obsolete boolean result and caller branch are removed.

User Impact

Overwritten refs no longer block writes, execute credential commands, or inflate dry-run counters. Surviving invalid refs still fail. Targeted edits can still repair config without checking unrelated dormant providers; whole provider-collection edits check all remaining providers. Model-provider IDs are not mistaken for SecretRef provider aliases.

Failed machine-readable config commands emit complete JSON through pipes. No CLI flags, config keys, environment options, schema/storage contracts, dependencies, or plugin execution policies are added or removed. The CLI reference documents final-candidate batch validation. JSON and human output retain their existing shapes.

Evidence

AI-assisted maintainer refactor with direct source review and independent review.

  • Baseline integration reproduction failed five cases before production edits: four leaf/ancestor overwrite cases and an obsolete exec provider creating its execution marker. Two surviving-invalid-ref controls passed. Additional model-alias and renamed-agent regressions failed before canonical-path repair.
  • The original pipe probe emitted only 512 bytes. A separate subprocess regression exposed the wrong exit status for a deferred typed exit. The fixed test verifies one complete 1 MiB JSON response, exact exit code 7, and no second error.
  • The config and CLI lifecycle run passed all 569 tests. After the final guard cleanup, all 228 config command tests passed again. Earlier focused secret resolver and command-path suites also passed. An existing model-catalog test timed out once while a build overlapped it; its quiet retry and the later full lifecycle run passed without changing its timeout.
  • pnpm build passed. The final CLI artifact refresh (node --import ./scripts/tsx.mjs scripts/build-all.mts cliStartup) passed at 516597002b345662dce1ed7f0b5bcee4e7368c2b.
  • All 15 real built-CLI probes passed using fresh fixture HOME/state/config directories and actual piped stdout/stderr: leaf/ancestor overwrite writes and dry runs, discarded allowed-exec refs, surviving unsafe refs, default/per-agent model aliases, agent rename, changed/unset secret defaults, large JSON errors, config validation errors, and invalid-snapshot mutation errors. Writes persisted the expected literal; every failure and dry run preserved config bytes; discarded exec providers never created their marker. Each JSON response parsed as one complete document.
  • Changed-file checks passed before the exit repair. The subsequent pass completed production/test types, formatting, export scans, and repository guards, then caught the obsolete boolean return contract. After removing it, focused lint and production types passed, and the remaining native-schema, storage, media, sidecar, import-cycle, webhook, and pairing guards passed. No guard was skipped or weakened.
  • Fresh Codex review of the full branch reported no actionable P0–P2 findings. Another fresh review covered the final guard cleanup, followed by a clean consolidated full-branch review at the final head. Direct inspection covered both guard callers and the shared typed-exit implementation.
  • Production: +449/-558, net -109. Tests/test support: +848/-599, net +249 (existing test moves discounted in the net). Docs: +2. The assertion-safety baseline decreases by five assertions.

Final hosted CI: passed, run 33157895894, head 516597002b345662dce1ed7f0b5bcee4e7368c2b. The first run hit npm tarball timeouts for the already-pinned Tlon native package, also reproduced on main. The intermediate head caught the boolean-contract lint issue fixed above.

The prior ClawSweeper review's remaining requests were exact-head CI and real CLI proof; both are now complete. A fresh review was requested because the output-exit repair adds behavior beyond that review. Its storage heuristic refers only to capturing writeJson in a test harness: no store or migration changes exist.

Windows live execution is outside this proof. Existing command-path policy and deterministic Windows tests are unchanged. No release artifact is published by this PR.

Provenance and Follow-ups

The stale-operation selection originated in #49296 (e99963100d2, authored and merged by @joshavant on March 17), then moved into the validation module in #113248. The immediate dry-run exit was carried forward by #116833 (c50a6119efc, authored and merged by @steipete on July 31). Source inspection confirms both mechanisms in shipped tag v2026.7.1-2, at src/cli/config-cli.ts:1739 and :2347. The existing finalizer dates to #113112; this PR routes already-reported typed exits through that owner.

Deferred separately: plugin metadata reuse needs a config-wide snapshot contract, including missing-file and multi-workspace cases. Main CI also exposed an unrelated Gmail watcher fixture race: existence-only readiness can read an empty PID file as NaN before its shell writes the PID. That fixture should publish PID files atomically while retaining its shutdown assertions.

@clawsweeper

clawsweeper Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation cli CLI command changes size: XL maintainer Maintainer-authored PR labels Aug 28, 2026
@steipete
steipete marked this pull request as ready for review August 28, 2026 08:27
@steipete steipete self-assigned this Aug 28, 2026
@clawsweeper

clawsweeper Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 28, 2026, 4:36 AM ET / 08:36 UTC.

ClawSweeper review

What this changes

The PR makes batch config mutations validate only surviving SecretRefs and providers from the final candidate configuration, avoiding resolution or execution of values overwritten later in the batch.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep open. Current main still derives dry-run references from intermediate operations, while this branch validates the completed candidate; the refactor is coherent and has no supported correctness finding, but exact-head CI and the planned CLI probe should finish before landing.

Priority: P2
Reviewed head: 7ab456c4c66fb72c36b395e8efad000a6c56f2e0

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) PR readiness rating was derived from proof quality, review findings, security review, and reviewer confidence.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): ClawSweeper live verification passed on the reviewed terminal surface.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): ClawSweeper live verification passed on the reviewed terminal surface.
Evidence reviewed 7 items Current main retains the reported mechanism: The fetched current-main revision collects every operation's assigned and embedded reference before considering the candidate config, so a reference from an earlier overwritten assignment remains selected.
Final-candidate ownership boundary: The branch selects references from the completed config and uses final operation paths, including registry-owned sibling-reference precedence and changed provider/default handling.
Mutation runner supplies normalized final paths: The runner records roster-normalized paths, builds the final candidate, and invokes the unified validator only after roster completion and dry-run write-topology preparation.
Findings None None.
Security None None.

Live Verification

Command: pnpm openclaw config set --help

Result: PASS (completed)

[tsdown-build] invocation 2/2 finished in 14.7s
[plugin-control-plane-loads] verified 36 built modules with native require and checked doctor closures
runtime-postbuild: 11 phases completed in 3759ms (slowest: built plugin control-plane loads 3079ms)
│
◇

OpenClaw 2026.8.1 (7ab456c) — All your chats, one OpenClaw.

Usage: openclaw config set [options] [path] [value]

Set config values by path (value mode, ref/provider builder mode, or batch JSON mode).
Examples:
openclaw config set gateway.port 19001 --strict-json
openclaw config set channels.discord.token --ref-provider default --ref-source env --ref-id DISCORD_BOT_TOKEN
openclaw config set secrets.providers.vault --provider-source file --provider-path /etc/openclaw/secrets.json --provider-mode json
openclaw config set --batch-file ./config-set.batch.json --dry-run

Arguments:
  path                                  Config path (dot or bracket notation)
  value                                 Value (JSON/JSON5 or raw string)

Options:
  --allow-exec                          Dry-run only: allow exec SecretRef resolvability checks (may execute provider commands) (default: false)
  --batch-file ‹path›                   Batch mode: read JSON array of set operations from file
  --batch-json ‹json›                   Batch mode: JSON array of set operations
  --dry-run                             Validate changes without writing openclaw.json (checks run in builder/json/batch modes; exec SecretRefs are skipped
                                        unless --allow-exec is set) (default: false)
  -h, --help                            Display help for command
  --json                                Legacy alias for --strict-json (default: false)
  --merge                               Merge object/map values instead of replacing the target path (default: false)
  --provider-allowlist ‹envVar›         Provider builder (env): allowlist entry (repeatable) (default: [])
  --provider-arg ‹arg›                  Provider builder (exec): command arg (repeatable) (default: [])
  --provider-command ‹path›             Provider builder (exec): absolute command path
  --provider-env ‹key=value›            Provider builder (exec): env assignment (repeatable) (default: [])
  --provider-json-only                  Provider builder (exec): require JSON output (default: false)
  --provider-max-bytes ‹bytes›          Provider builder (file): max bytes
  --provider-max-output-bytes ‹bytes›   Provider builder (exec): max output bytes
  --provider-mode ‹mode›                Provider builder (file): mode (singleValue|json)
  --provider-no-output-timeout-ms ‹ms›  Provider builder (exec): no-output timeout ms
  --provider-pass-env ‹envVar›          Provider builder (exec): pass host env var (repeatable) (default: [])
  --provider-path ‹path›                Provider builder (file): path
  --provider-source ‹source›            Provider builder: source (env|file|exec|store)
  --provider-timeout-ms ‹ms›            Provider builder (file|exec): timeout ms
  --provider-trusted-dir ‹path›         Provider builder (exec): trusted directory (repeatable) (default: [])
  --ref-id ‹id›                         SecretRef builder: ref id
  --ref-provider ‹alias›                SecretRef builder: provider alias
  --ref-source ‹source›                 SecretRef builder: source (env|file|exec|store)
  --replace                             Allow full replacement of protected map/list paths such as agents.defaults.models (default: false)
  --strict-json                         Strict JSON parsing (error instead of raw string fallback) (default: false)

Assertions:

  • PASS expect_output: Set config values by path

How this fits together

The Config CLI turns batch input into mutations, applies them to an in-memory candidate configuration, then validates it before writing or returning dry-run output. SecretRef resolution and exec-provider path checks occur in that validation boundary and affect whether a configuration can be accepted.

flowchart LR
  A[Batch config input] --> B[Mutation parser]
  B --> C[Candidate configuration]
  C --> D[SecretRef and provider selection]
  D --> E[Validation and dry-run result]
  E --> F[Config write or rejection]
  F --> G[Gateway reload planning]
Loading

Before merge

  • Resolve merge risk (P1) - The PR body says exact-head hosted CI and redacted real CLI probes are still being finalized; do not land until those results are recorded.
  • Complete next step (P2) - This maintainer-authored PR needs completion of its planned exact-head CI and CLI evidence, not a ClawSweeper repair branch.
Agent review details

Security

None.

PR surface

Source -118, Tests +179, Docs +2, Other 0. Total +63 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 6 408 526 -118
Tests 3 724 545 +179
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 2 0
Total 11 1136 1073 +63

Review metrics

Metric Value Why it matters
Production versus test delta production +405/-526 (net -121); tests/test support +727/-545 (net +182); docs +2 The bug fix reduces production code while adding boundary coverage for overwritten, surviving, and renamed SecretRefs.

Stored data model

Persistent data-model change detected: serialized state: src/cli/config-cli.integration.test-harness.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Use the completed candidate as the single source for SecretRef and provider validation, retain the registry and roster normalization paths, and land after exact-head checks and a redacted CLI dry-run demonstrate the observable result.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Use the completed candidate as the single source for SecretRef and provider validation, retain the registry and roster normalization paths, and land after exact-head checks and a redacted CLI dry-run demonstrate the observable result.

Do we have a high-confidence way to reproduce the issue?

Yes, source-reproducible: current main records SecretRefs from every submitted operation before final candidate composition, so an earlier overwritten exec reference remains selected. This read-only review did not execute the reproduction.

Is this the best way to solve the issue?

Yes. Moving selection to the final candidate in the mutation validator removes the stale operation metadata source while preserving registered sibling-reference precedence, provider checks, and roster-normalized paths.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 1dba34be9be1.

Labels

Label changes:

  • add P2: This repairs a bounded Config CLI validation defect without evidence of an active emergency outage.
  • add proof: sufficient: Contributor real behavior proof is sufficient. ClawSweeper live verification passed on the reviewed terminal surface.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.

Label justifications:

  • P2: This repairs a bounded Config CLI validation defect without evidence of an active emergency outage.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • proof: sufficient: Contributor real behavior proof is sufficient. ClawSweeper live verification passed on the reviewed terminal surface.

Evidence

What I checked:

  • Current main retains the reported mechanism: The fetched current-main revision collects every operation's assigned and embedded reference before considering the candidate config, so a reference from an earlier overwritten assignment remains selected. (src/cli/config-cli-validation.ts:111, 1dba34be9be1)
  • Final-candidate ownership boundary: The branch selects references from the completed config and uses final operation paths, including registry-owned sibling-reference precedence and changed provider/default handling. (src/cli/config-cli-validation.ts:114, 7ab456c4c66f)
  • Mutation runner supplies normalized final paths: The runner records roster-normalized paths, builds the final candidate, and invokes the unified validator only after roster completion and dry-run write-topology preparation. (src/cli/config-cli-runner.ts:275, 7ab456c4c66f)
  • Boundary regressions cover discard and survival: Integration coverage exercises leaf and ancestor overwrites in normal and dry-run modes, skipped versus allowed exec resolution, and a SecretRef that survives an in-batch agent rename. (src/cli/config-cli.secrets.integration.test.ts:510, 7ab456c4c66f)
  • Documented CLI contract: The CLI reference now states ordered batch application, final-config validation, discarded-reference exclusion, and retained provider trust checks. Public docs: docs/cli/config.md. (docs/cli/config.md:229, 7ab456c4c66f)
  • Related history: The shared provider-preflight boundary was introduced by the merged prior repair, and the immediately preceding roster-preservation repair supplies the renamed-agent path this branch preserves. (src/cli/config-cli-validation.ts:114, 2b263adad639)

Likely related people:

  • steipete: Current history shows sustained work on the Config CLI mutation path, including the roster-preservation change that this branch relies on. (role: recent area contributor; confidence: high; commits: 7ab456c4c66f, 629a47e3cc20, 22e892a4eaa0; files: src/cli/config-cli-input.ts, src/cli/config-cli-runner.ts, src/cli/config-cli-validation.ts)
  • SunnyShu0925: The merged exec-provider preflight repair established the validation boundary now being made final-candidate-aware. (role: introduced adjacent provider-preflight behavior; confidence: medium; commits: 2b263adad639; files: src/cli/config-cli-validation.ts, src/cli/config-cli-runner.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

Unwind already-reported config failures through the shared CLI finalizer so resources close and piped JSON drains before the requested exit. Preserve injected runtime ownership and avoid rendering typed exits twice. Cover full 1 MiB pipe output, exact status, and config error contracts.
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The final head is 5165970. Since the reviewed head, a real config dry-run probe exposed truncated JSON on a failing piped command. Config failures now unwind through the shared CLI finalizer so cleanup completes and output drains before exit, without reporting the same error twice. The full branch and the final guard cleanup have fresh Codex reviews with no actionable findings. The config/CLI lifecycle run passed 569 tests; all 228 config command tests passed again after removing the obsolete boolean guard contract.

The previous review's remaining items—final built-CLI probes and exact-head hosted CI—are still being completed and will be recorded before landing. The storage heuristic on config-cli.integration.test-harness.ts is not a persistent data change: that edit only captures the runtime JSON writer in tests. No store, schema, migration, or configuration surface changes here.

@clawsweeper

clawsweeper Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@steipete

steipete commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Final maintainer verification passed at 516597002b345662dce1ed7f0b5bcee4e7368c2b. CI run 33157895894 and its required openclaw/ci-gate succeeded. Fresh consolidated Codex review found no actionable P0–P2 findings.

The final built CLI passed all 15 fixture-isolated real command probes with actual pipes. Overwritten leaf/ancestor refs neither resolved nor executed; successful writes persisted the final literal. Surviving invalid refs, normalized model keys, renamed agents, and changed/unset defaults were still validated. All failures and dry runs preserved config bytes. Failed get/validate/mutation commands emitted exactly one complete JSON document. The formerly truncated failure now emits 629 parseable bytes instead of stopping at 512; the large get error emits 8,351 bytes with empty stderr. Separate subprocess coverage verifies a full 1 MiB JSON response and exact exit code 7.

{"head":"516597002b345662dce1ed7f0b5bcee4e7368c2b","builtCliCasesPassed":15,"discardedExecMarkerCreated":false,"failureAndDryRunConfigBytesPreserved":true,"jsonResponsesComplete":true,"requiredCi":"success"}

The config/CLI lifecycle run passed 569 tests, followed by a 228-test config rerun after the final guard cleanup. Final build, production/test types, lint, formatting, export scans, and architecture/auth/storage guards passed as recorded in the PR body. Production net -109 lines; tests/support net +249; docs +2. No new config, dependency, storage, or execution-policy surface.

This completes the prior ClawSweeper review's two remaining requests: exact-head CI and changed-behavior CLI proof. Its storage heuristic only refers to a JSON-writer test spy, so migration proof is not applicable. A refresh was requested for the additional output-exit repair; the publisher is not a landing blocker. Windows live execution remains outside this proof; its existing policy tests are unchanged.

Post-merge verification: all 228 config command tests passed again on main commit 3f31f271d5ac, which includes merge 2d625dad30e1 and the concurrent config-test fixture consolidation. The local checkout is synced and clean.

@steipete
steipete merged commit 2d625da into main Aug 28, 2026
244 checks passed
@steipete
steipete deleted the codex/config-preflight-owner-refactor branch August 28, 2026 09:21
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 29, 2026
…law#131656)

* fix(config): validate surviving batch values through one mutation flow

* fix(cli): drain config failure output before exit

Unwind already-reported config failures through the shared CLI finalizer so resources close and piped JSON drains before the requested exit. Preserve injected runtime ownership and avoid rendering typed exits twice. Cover full 1 MiB pipe output, exact status, and config error contracts.

* refactor(config): make snapshot validation throw on failure
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes docs Improvements or additions to documentation maintainer Maintainer-authored PR size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant