Summary
This is PR 1 of a 4-PR split of #725, opened in response to review feedback that the combined branch changed four distinct contracts at once and could not be reviewed against a stable baseline.
It defines the provider identity contract and wires every consumer boundary it touches onto that contract, so no caller is left on the old mental model. It does not implement cross-process locking or the full writer-inventory transaction — that stays with #894.
NOTE
#893 (2/4) is stacked on this PR and should merge after it.
The contract
Persisted provider rows and credential-store entries answer two different questions, and mixing them let one profile's mutation reach another profile's row and secret.
- Credential identity —
credstore.NormalizeProvider(trim +ToLower), exposed asconfig.SameProviderIdentity. Callers deciding whether two spellings share one stored secret use it rather thanstrings.EqualFold: Unicode case folding equatessandſwhilestrings.ToLowerdoes not, so anEqualFoldcomparison can promise a survivor access to a key it can never look up. - Exact row identity — trimmed
provider.Nameequality, used by every row-targeting mutator (MarkProviderAPIKeyStored,ProviderPersisted's mutating callers,SetProviderModel,ClearProviderKeyStored,RemoveProvider, and theoldNamelookups inRenameProvider/EditProvider). - Publication validation —
ValidatePersistedProviderNamesrejects persisted rows repeating a folded identity, whether the spellings are identical or only case variants.writeConfigFileguards every write with it, andResolve()validates user config before merging.
The four shared helpers (the "front door")
Defining two rules is not enough — every boundary that gated on one rule and mutated with the other needed one place to cross between them:
| Helper | What it owns |
|---|---|
ResolvePersistedProviderName(path, input) | User/session spelling → the exact persisted row. Exact wins, credential identity is a fallback, an identity matching 2+ rows is an error, not an arbitrary pick. SetActiveProvider's loop was extracted into it rather than copied a fourth time. |
CredentialKeyRetained(providers, removedName) | Retention by ownership, not name survival: keep the shared secret only when a remaining row has APIKeyStored. A markerless case variant can no longer orphan a key ApplyStoredAPIKey will never read. ProviderKeyRetainedAfterRemoval(path, name) answers the same question before mutating, so confirmation copy and behavior share one predicate. |
PublishProviderCredential(path, exactName, key) | One operation for validate → snapshot → store.Set → MarkProviderAPIKeyStored, restoring the previous stored value when publication is rejected instead of deleting the shared entry. |
applyProviderKeyRemovalToSession(name) (TUI) | Reconciles savedProviders / providerProfile with a disk key removal, so the session cannot claim a key that is gone until restart. |
Consumer boundaries wired onto it
auth openrouter— preflights beforeEnsureCatalogProvider's case-insensitive lookup, then publishes throughPublishProviderCredential. A legacyopenrouter/OPENROUTERconfig no longer costs the user their working key, and a login that could not be persisted now exits non-zero while still printing the minted key for manual use.auth logout— clears the marker before deleting the secret, and both halves address the store beside the config being edited rather than one using the default-path store.providers remove/providers rename— resolve the user's spelling to the exact row between theProviderPersistedgate and the mutator, sozero providers remove workagainst a soleWORKrow works instead of failing "not found"; an ambiguous duplicate config errors before anything is touched.- TUI provider manager — delete and edit resolve the row spelling; retention uses
CredentialKeyRetained; the delete confirmation text is computed fromProviderKeyRetainedAfterRemovalso it cannot promise a key removal the delete will not perform. - TUI wizard manage-key remove — marker first, secret second, then session reconciliation.
- Model persistence —
switchProviderModelpersists with the spellingSetActiveProviderresolved, andpersistSelectedModelresolves before writing; write failures on a persisted row are surfaced instead of dropped into_, _ =. EqualFoldaudit — every provider-name comparison inauth.go,picker.go,provider_wizard.go,provider_wizard_discovery.go,session.go, andEnsureCatalogProviderwas classified by intent and moved to either exact row spelling orSameProviderIdentity.
activeProvider repair
Repairing a case-duplicate config could strand activeProvider on a third spelling (WoRk with rows work/WORK) that matches no remaining row exactly, blocking every exact mutator. RemoveProvider now re-points it at the survivor's own spelling when exactly one row carries the identity.
Live-session reconciliation
Three spellings exist, not two: credential identity, the persisted row's exact name, and the live session's name (m.providerName, ZERO_PROVIDER, resumed session metadata), which may differ from disk. The session spelling gets its own predicate rather than reusing either config-level rule:
sessionRowName(live, providers)resolves the live spelling to the row it refers to. An exact spelling wins — so case-variant siblings (workvsWORK) ands/ſstay distinct, and a session never follows a mutation aimed at its sibling — and only a credential identity carried by exactly one row resolves to that row's own spelling. Anything else falls back to exact equality rather than guessing, which keeps env-derived and ambiguous cases out. It feeds the manager's● activemarker, the renameZERO_PROVIDERsync, the delete "keeps running" note, and the edit restart note.reloadProviderManagerRowsresolves once intomanageActiveNameso render and sync share one value.syncSavedProviderModelis the single reconciliation point for a persisted model change. The manager's rows and the picker's model sections readsavedProviders, not the live profile, soswitchProviderModelandhandleModelCommand(viapersistSelectedModel, which now returns the exact row it wrote) both mirror the write into that list — otherwise/providerskept showing the previous model until restart.
Legacy case-duplicate configs are rejected at read time
ValidatePersistedProviderNames runs on user-config load, so a pre-existing config with rows differing only by case (work + WORK) now fails Resolve(). Interactive zero, TUI startup, auth logout, and wizard key removal all refuse to run until it is repaired. This is intentional — ambiguous configs are rejected rather than silently coalesced — but it is a user-visible behavior change for configs that worked before this PR, so it needs a release note.
Repair path: zero providers remove WORK (the exact row spelling). RemoveProvider reads config.json directly instead of going through Resolve, so it still works while everything else refuses to start; hand-editing config.json works too. Rename/edit cannot shrink a duplicate — those mutators validate before mutating. The rejection message now names that command instead of only describing the problem.
A guided in-TUI repair or a zero providers repair-config command is a larger change than this slice; #893 is the natural home if we want one.
Scope: what #894 still owns
This PR wires boundary compatibility — preflight before capture, resolve before exact mutation, ownership-based retention, session sync, and restore-on-failure for the OpenRouter/explicit-key publication path (PublishProviderCredential: preflight → snapshot → set → publish → restore).
It does not make capture atomic everywhere. providers add, zero setup, wizard finalize, and manager edit-with-new-key still run preflight → SecureProviderProfile (store Set) → config write, with documented fail-soft on store errors and no rollback if the config write fails after a successful capture. Preflight removes the validation-failure-after-capture case; what remains is a rare write failure (permissions, disk full) leaving a store entry without apiKeyStored — pre-merge-base behavior, not a new regression here. Each of those call sites now carries a one-line comment saying so, so the next reader does not assume OpenRouter-grade rollback already landed.
It also deliberately does not introduce cross-process locking or a single transaction spanning the full writer inventory; the premature CommitProviderProfile/lockProviderWrite implementation was reverted for that reason. #894 introduces one authoritative transaction over every config/key lifecycle mutation with its declared fail-closed lock policy, and owns atomic capture+publish for the paths listed above.
Tests
TestProviderIdentityMatrix(internal/cli) — one table-driven test over CLI + config writer + credstore temp dirs covering case-variant remove/rename/use, ambiguous duplicate rejection with byte-for-byte config comparison, shared-credential retention, markerless-survivor deletion, staleactiveProviderrepair, andsvsſend to end.- Regressions for OpenRouter key preservation on rejected publication, logout marker cleanup for a case-variant argument, delete-confirmation retention copy, wizard session sync,
wizardProviderStoredKeyUnicode identity, and case-variant model persistence. - Config-level tests for
ResolvePersistedProviderName,CredentialKeyRetained,ProviderKeyRetainedAfterRemoval, andPublishProviderCredential's restore/delete rollback paths. TestModelSwitchSyncsSavedProviders— a case-variant switch mirrors onto the rowSetProviderModelactually wrote, leaves unrelated rows alone, and shows throughproviderManagerRowMetawithout a restart;persistSelectedModelreturns the resolved row spelling its caller mirrors with.TestProviderManagerSoleRowCaseVariantTracksLiveSession— liveworkagainst a soleWORKrow gets the active marker, and a rename carries ontoproviderName,providerProfile, andZERO_PROVIDER.TestProviderManagerCaseVariantDeleteDoesNotChangeLiveSibling— the sibling guard: rowswork+WORK, livework, deletingWORKleaves the live session, its env export, and the status notes untouched.
Pre-existing tests adjusted
TestProviderWizardManageKeyRemoveReportsCleanupFailures/stored key deletion— now asserts the marker is cleared before the secret delete is attempted (the new ordering).- Three fixtures relying on case-insensitive row matching still exercise whitespace trimming:
TestSetActiveProviderSwitchesConfiguredProvider,TestSetProviderModelUpdatesConfiguredProvider,TestRemoveProviderDeletesAndHandsOffActive. TestProviderManagerCaseVariantEditDoesNotChangeLiveSiblingwas split in two. Its fixture held a single row (WORK) with livework, so it never exercised the sibling case its name claimed — it was exactly the sole-row case, and now asserts the sync as…SoleRowCaseVariantTracksLiveSession. The real sibling guard moved to a two-row delete fixture; edit cannot be used for it becauseEditProviderrejects a duplicate-identity config before mutating.assertAmbiguousConfigUnchangedfollows the rejection message now naming the repair command.
Validation
go build ./...go vet ./...gofmt -l .(clean)go test ./...(full suite green)
Refs #721. Split of #725.
🤖 Generated with Claude Code
Summary by CodeRabbit
- Bug Fixes
- Improved provider-name matching across configuration, CLI, and TUI workflows.
- Prevented ambiguous or duplicate names from overwriting configuration or credentials.
- Preserved shared credentials when removing provider profiles.
- Improved logout and key-removal cleanup across name variations.
- Prevented partial updates when saving providers or migrating credentials.
- Correctly distinguishes visually similar Unicode provider names.
- Restored existing credentials when configuration updates fail.
- Improved error reporting for configuration and credential cleanup failures.
- Improved reliability when multiple credential operations occur concurrently.
Activity
78Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/config/credentials.go (1)
102-148: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCollapse the two clear functions into one predicate-driven helper.
ClearProviderKeyStoredandClearProviderKeyStoredCaseVariantsdiffer only in the name-match predicate. The read, unmarshal, loop, and write logic are identical. Extract a shared helper so a future change to the read-modify-write sequence cannot drift between the two.♻️ Proposed refactor
+func clearProviderKeyStored(path, provider string, matches func(rowName string) bool) (bool, error) { + path = strings.TrimSpace(path) + provider = strings.TrimSpace(provider) + if path == "" || provider == "" { + return false, nil + } + data, err := os.ReadFile(path) + if err != nil { + if os.IsNotExist(err) { + return false, nil + } + return false, fmt.Errorf("read config %s: %w", path, err) + } + var cfg FileConfig + if err := json.Unmarshal(data, &cfg); err != nil { + return false, fmt.Errorf("invalid config JSON %s: %w", path, err) + } + changed := false + for index := range cfg.Providers { + if matches(cfg.Providers[index].Name) && cfg.Providers[index].APIKeyStored { + cfg.Providers[index].APIKeyStored = false + changed = true + } + } + if !changed { + return false, nil + } + return true, writeConfigFile(path, cfg) +}
ClearProviderKeyStoredthen passesfunc(row string) bool { return strings.TrimSpace(row) == provider }, andClearProviderKeyStoredCaseVariantspasses acredstore.NormalizeProvidercomparison.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/config/credentials.go` around lines 102 - 148, Extract the duplicated read, unmarshal, iteration, change detection, and write logic from ClearProviderKeyStored and ClearProviderKeyStoredCaseVariants into one predicate-driven helper. Have each public function retain its input normalization and pass the appropriate row-name matcher: trimmed exact equality for ClearProviderKeyStored and credstore.NormalizeProvider equality for ClearProviderKeyStoredCaseVariants.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/config/writer_test.go`:
- Around line 1027-1125: Add a regression test for UpsertProvider using an
existing provider name and a case-variant name, asserting the error reports
`provider %q already exists as %q`. Read the file before and after the call and
verify the configuration remains byte-for-byte unchanged.
---
Nitpick comments:
In `@internal/config/credentials.go`:
- Around line 102-148: Extract the duplicated read, unmarshal, iteration, change
detection, and write logic from ClearProviderKeyStored and
ClearProviderKeyStoredCaseVariants into one predicate-driven helper. Have each
public function retain its input normalization and pass the appropriate row-name
matcher: trimmed exact equality for ClearProviderKeyStored and
credstore.NormalizeProvider equality for ClearProviderKeyStoredCaseVariants.🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 2683b057-81af-4a37-b441-4dd71c88077a
📥 Commits
Reviewing files that changed from the base of the PR and between cabfeefc4eb9d247d907d3dee0786fe2e745207d and 8c94956598388ccb7187c8271ef006aebdf4df3a.
📒 Files selected for processing (7)
internal/config/credentials.gointernal/config/credentials_test.gointernal/config/resolver.gointernal/config/resolver_test.gointernal/config/writer.gointernal/config/writer_test.gointernal/credstore/credstore.go
I found issues that need to be addressed before this is ready.
This review respects the stated 1/4 split. The findings below do not ask to fold the later catalog, transaction, or UX work into this PR; they identify cases where PR1 changes a shared identity contract that existing CLI/TUI code already consumes. Each boundary needs to remain backward-compatible until its designated successor lands, or the producer and its dependent consumer need to move into the same mergeable slice.
Findings
-
[P1] Validate before storing a credential for a new provider
internal/cli/provider_setup.go:58The new collision check is insideUpsertProvider, but Go evaluatesSecureProviderProfile(profile, configPath)first. That helper immediately callsStore.Set, and the store canonicalizesWORKtowork. Consequently, starting with a valid savedworkprofile holding keyOLD,zero providers add ... --name WORK --api-key NEWoverwrites theworksecret withNEWand only then rejects the duplicate config row. The command reports failure while the existing provider has silently changed credentials.saveSetupProviderand the TUI wizard have the same capture-before-validation ordering; plaintext-key migration also writes secrets before the new write-time validator can reject an invalid file.The root cause is splitting one logical provider update across independently mutating config and credential-store operations, with validation occurring after the first side effect. The planned transaction work in PR3 is a suitable long-term home, but PR1 cannot expose the rejecting
UpsertProviderbehavior while existing callers still capture first. Either land a narrow preflight/rollback bridge with this producer change, or defer this behavior change to the transaction slice. Add regression coverage that asserts a rejected case-variant add/setup leaves both config bytes and the existing store entry unchanged. -
[P2] Keep the shared credential when repairing a case-duplicate config
internal/config/writer.go:401This new path intentionally allowsRemoveProvider("WORK")to repair a legacywork/WORKconfig and leave the exactworkrow. After that successful config write, both the CLI and TUI unconditionally delete the removed name from the credential store. Because the store canonicalizes both spellings towork, cleanup deletes the survivor's shared key; its survivingapiKeyStored: truemarker then causes the repaired provider to be presented as credentialed although runtime key lookup fails.The root cause is treating a row deletion as proof that its credential identity has no remaining owners. The planned credential-candidate work in PR2 can own the final shared-credential policy, but this PR's new repair behavior must not reach current unconditional cleanup first. Either keep the prior non-repairing behavior until that consumer changes, or add the narrow post-mutation ownership check now. Only delete when no same-identity survivor remains; otherwise retain the key and preserve the survivor's marker. Exercise the full CLI and TUI cleanup paths with a legacy duplicate and assert the remaining row can still load its key.
-
[P1] Clear the marker with the same identity used to delete the key
internal/cli/auth.go:452auth logout WORKcallsForgetProviderKey, whose credential-store deletion canonicalizes the argument towork, then calls the newly exact-onlyClearProviderKeyStored(configPath, "WORK"). A normal config row namedworkis not matched, so its secret is removed whileapiKeyStoredstays true. This is a regression from the base implementation'sEqualFoldcleanup: subsequent status/selection logic sees a configured credential, whileApplyStoredAPIKeycannot load one. The TUI's key-removal flow has the same mismatch, and the newClearProviderKeyStoredCaseVariantshelper is unused.The root cause is one lifecycle operation using two different identity relations: normalized identity for secret deletion and exact spelling for marker cleanup. The summary assigns logout/API-key cleanup migration to PR2, so PR1 should preserve the old compatible clearer until PR2 switches both halves of the lifecycle together—or move this exact-match change with that PR2 consumer work. The final operation should either clear every marker that refers to the removed credential or reject an ambiguous request before deleting anything. Add logout and TUI regressions for a mixed-case saved row and verify that no stale marker remains.
-
[P1] Stop using Unicode case folding for live provider identity
internal/tui/provider_manager.go:634The new contract deliberately permitssand Unicode long-s (ſ) as distinct credential identities becausestrings.ToLowerkeeps their store keys distinct. The provider manager still usesstrings.EqualFold, which equates them. If the session runsſand the user edits non-actives, the config edit targets the correct exact row, but the subsequent live-session sync treats it as the active provider and rewritesm.providerName,m.providerProfile.Name, andZERO_PROVIDERto the edited name. The manager's in-memory edit/remove helpers use the same incompatible comparison.The root cause is leaving a second provider-identity implementation at a consumer boundary after defining the credential store as the authority. The summary assigns TUI synchronization to PR4, so this does not require absorbing that UX work here: PR1 can instead avoid making the distinct
s/ſstate reachable by current TUI consumers until PR4, or move the minimal comparison fixes alongside this contract change. Audit provider-name comparisons by intent: use exact persisted spelling to address a row, andconfig.SameProviderIdentityonly when reasoning about a shared credential. Add a live-session test covering activeſplus an edit/remove ofs. -
[P2] Do not turn a case-variant
providers userequest into a successful no-opinternal/cli/provider_onboarding.go:63ProviderPersistednow returns false unless the input spelling exactly matches the saved row. The fallback added for environment-derived providers is unchanged and usesstrings.EqualFold. For a savedOpenAIrow,zero providers use openaitherefore concludes it is not persisted, finds the row in the resolved list case-insensitively, prints the environment-provider explanation, and exits successfully without callingSetActiveProvideror changing config. Before this PR, the same command selected the saved row.The root cause is the CLI's classification path applying a broader matching rule than the mutation path. The summary assigns provider-selection UX to PR4, so retain the previous compatible lookup until that slice updates the classification and mutation paths together, or include only the small bridge that prevents this false-success result now. Do not use
EqualFoldas a proxy for credential identity here, since it also incorrectly conflates the Unicode identities this PR explicitly preserves. Add CLI tests for exact, case-variant, environment-derived, ands/ſinputs. -
[P2] Validate implicit provider names before accepting persisted identities
internal/config/writer.go:26The validator indexes the trimmed raw name, so an empty name andopenaiare accepted as different identities. Later,normalizeProvidersuppliesopenaifor an empty name and the merge path uses the same effective name. A persisted file containing both rows therefore passes the new invariant while resolving to one semantic provider—the exact resolver coalescing/ambiguous-ownership situation the validator says it prevents.The root cause is validating raw serialization names rather than the names the resolver and credential lifecycle actually use. Either reject blank persisted provider names at the file boundary or canonicalize each name with the same effective-name rule before duplicate detection. Include a persisted
{name:""}plus{name:"openai"}regression test and ensure the error is raised before any credential migration or config rewrite.
Addressed the latest review in 50bca0a8.
- Preflight provider writes before CLI/setup/TUI credential capture, and validate before plaintext-key migration.
- Preserve shared credentials when repairing legacy case-duplicate rows.
- Clear stored-key markers using credential identity for logout and TUI key removal, while failing closed on ambiguous configs.
- Replace provider-name EqualFold comparisons at the affected CLI/TUI boundaries with exact row matching or config.SameProviderIdentity as appropriate.
- Restore case-variant
providers usebehavior without conflatingsandſ. - Reject blank persisted provider names before implicit
openainormalization. - Added regression coverage for CLI, TUI, resolver, migration, and credential-store paths.
Validation: focused regressions, affected package suites, go vet ./..., go test ./..., release build, release smoke, govulncheck, and git diff HEAD --check passed. make is unavailable on this Windows workstation; advisory static lint still reports the unrelated pre-existing ST1005 finding in internal/peermsg/private_dir_windows.go:107.
Actionable comments posted: 5
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/cli/auth_test.go`:
- Around line 361-399: Extend
TestRunAuthLogoutRejectsAmbiguousConfigBeforeCredentialDeletion to seed an OAuth
credential for the same provider alongside the API key, then assert that the
OAuth credential remains unchanged after the ambiguous configuration rejection.
Use the existing credential-store setup and retrieval APIs, preserving the
current config-file and API-key assertions.
In `@internal/config/credentials_test.go`:
- Around line 140-148: Update the invalid-configuration assertions around the
credential-store mutation and file rewrite checks to avoid printing
secret-bearing values. In the failure message using store.keys, report only the
key count; in the before/after content mismatch message, report byte lengths or
other non-sensitive metadata instead of raw contents.
In `@internal/tui/provider_manager.go`:
- Line 649: Use exact trimmed persisted-name comparisons, rather than
SameProviderIdentity, for live-provider state updates in
internal/tui/provider_manager.go:381-383, 649, and 667; preserve
SameProviderIdentity only for credential identity checks. Update the related
tests in internal/tui/provider_manager_test.go:649-688 to verify deleting WORK
leaves live work unchanged and reports the surviving active row, and in 690-744
add an ASCII case-variant edit test proving the inactive row cannot change the
live provider or ZERO_PROVIDER.
- Line 367: Update the delete confirmation text in providerManagerCleanupCmd to
reflect whether providerIdentitySurvives(cfg.Providers, name) finds another
equivalent provider: state that the stored API key is removed only when no
equivalent identity remains, and that it is retained otherwise.
In `@internal/tui/provider_wizard.go`:
- Around line 1341-1345: The provider-key cleanup flow around the wizard’s
removal handler must stop discarding errors: handle failures from both
store.Delete and ClearProviderKeyStoredCaseVariants, keep the wizard open, and
show a redacted failure instead of the success transcript. Update
internal/tui/provider_wizard.go lines 1341-1345 accordingly; add cross-platform
regression tests in internal/tui/provider_wizard_test.go lines 1195-1223
covering injected key-store deletion and marker-clear failures.🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: a194d95f-a01b-44ba-92d3-3b2b567b0cbc
📥 Commits
Reviewing files that changed from the base of the PR and between 723e9112759bb73b80f7ba2588dd9b4675f3635e and 50bca0a84c5e45f4d8d877a7f1434d6b4b32f1e8.
📒 Files selected for processing (16)
internal/cli/auth.gointernal/cli/auth_test.gointernal/cli/provider_onboarding.gointernal/cli/provider_onboarding_test.gointernal/cli/provider_setup.gointernal/cli/setup.gointernal/cli/setup_test.gointernal/config/credentials.gointernal/config/credentials_test.gointernal/config/resolver_test.gointernal/config/writer.gointernal/config/writer_test.gointernal/tui/provider_manager.gointernal/tui/provider_manager_test.gointernal/tui/provider_wizard.gointernal/tui/provider_wizard_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
- internal/config/writer_test.go
- internal/config/writer.go
Addressed all latest CodeRabbit findings in 70773eae.
- Extended ambiguous-logout coverage to preserve OAuth credentials as well as API keys.
- Removed secret-bearing values from credential migration test failures.
- Switched TUI live-provider updates and restart messaging to exact trimmed persisted-name matching, with case-variant edit/delete regressions.
- Made provider deletion text accurately describe conditional shared-key retention.
- Surfaced stored-key deletion and marker-cleanup failures in the provider wizard, kept the wizard open, redacted errors, and added injected failure-path tests.
Validation:
- focused CodeRabbit regression tests
go vet ./...go test ./...go run ./cmd/zero-release buildgo run ./cmd/zero-release smokego run golang.org/x/vuln/cmd/govulncheck@v1.3.0 ./...git diff HEAD --check- changed files are
gofmt-clean
make is unavailable on this Windows workstation. The pinned advisory static lint still reports only the unrelated pre-existing ST1005 finding at internal/peermsg/private_dir_windows.go:107.
Addressed the latest review in 83fa9eb.
- Resume keeps the live provider context. Removed the block that copied recorded provider/model labels without rebuilding the client. Resuming history now retains the live client, complete endpoint/credential profile, model, and removed-row identity. The regression covers a different session, the same session, and no deletion, and checks the actual client/profile as well as labels and the resume summary. Empty-provider initialization remains unchanged.
- Stored-key case-collision guidance. Repair now explicitly explains that the case sibling must be renamed manually and its credential references reconciled before retrying, rather than suggesting an impossible
--nameescape. Refusal preserves config bytes; existing credential-identity protections remain intact. - Persistence diagnostics. The concrete persistence error is printed once, while the note still explains that the switch applies only to the live session.
Fail-before/pass-after evidence:
- Resume regression failed with
resume identity = ("", "work", "resumed-model", "work"), want ("WORK", "WORK", "project-model", "WORK")while the original client/profile remained unchanged. - Repair-guidance regression failed because bare repair suggested
--name <unique-name>instead of explaining manual recovery. - Both persistence-failure cases failed with
persistence error must appear exactly once in the switch status. - All of these regressions pass with the corrections.
Validation on Linux:
make fmt-check— passed.go vet ./...— passed.go test ./...— passed.go test -race ./internal/config/... ./internal/cli/... ./internal/tui/...— all three packages passed.go run ./cmd/zero-release buildandgo run ./cmd/zero-release smoke— passed (0.9.0).make vulncheck— No vulnerabilities found.- Diff hygiene — passed.
make lint-static— four existing advisory staticcheck suggestions in unchanged files:internal/installtest/workflow_permissions_test.go,internal/proxydial/proxydial.go(two), andinternal/tools/web_fetch.go. No unrelated lint cleanup included.
Git test fixtures ran with commit signing disabled through command-scoped Git configuration. Native macOS/Windows execution was not performed. The PR head already contained current upstream main when checked. Stacked PRs #893–#895 are unchanged and still need this correction propagated; no catalog, transaction, or broader UX work was moved into this slice. Orb bootstrapping was kept on a separate local branch and is not included in this push.
@Vasanthdev2004 @jatmn Refreshed the whole stack onto current main by merging (no history rewrite), as asked on Sep 19. Each push is a fast-forward of the previous PR head:
| PR | new head | merge |
|---|---|---|
| #892 | dc6b3876 | main → pr1 (3 conflicted files, below) |
| #893 | 8ae20369 | refreshed pr1 → pr2 (one import line) |
| #894 | 542258ca | refreshed pr2 → pr3 (clean) |
| #895 | 9be29248 | refreshed pr3 → pr4 (clean) |
The only real resolution is in #892:
internal/tui: main's #1083 moved the model-picker switch decision intomodelPickerSwitchOwner(picker.go), so the row's owner label and the switch use one decision. That helper still had the old identity comparison (EqualFoldagainstm.providerName), which is the bug this PR fixes. I ported this PR's row-based check into the helper: resolve the owner to a saved row, compare it withactiveProviderRowName(), and return the resolved row name.model.goswitches to that name, andmodelPickerEffectiveOwnerlabels with it, so the label and the switch still agree.internal/config/writer.goandwriter_test.go: import unions (credstore+notify,fmt+io), and both sides' appended tests kept.- (#893:
runtime+slicesimport union.)
Verification: at the top of the stack (#895), go vet ./... passes (plus linux/darwin), and the config, tui, cli and credstore tests pass on Windows and Linux (WSL). The only local Windows failure is a git init environment issue (unable to access 'NUL') that fails identically on main. Build and smoke pass.
One thing I noticed on #892 alone: TestRunProvidersUseMatchesCredentialIdentityButNotUnicodeCaseFold (the "long s is not plain s" case) fails on Windows, both before and after this merge. It passes on Linux, and it passes on Windows at the top of the stack, so a later PR in the stack appears to fix it. CI's Windows job doesn't run it.
@Vasanthdev2004 Thanks for doing the whole stack in one round. Both findings here are fixed in 32791312, and the rest of the stack is refreshed on top. Current main (8c4e7597) is merged in at every level.
#892 (head dd265a26)
- Ownership of a sole case alias: I dropped the
resolved == persistedNamearm. Only a concrete row with the requested spelling shadows the persisted row now. Copilot's case (persistedOpenAI, resolved[OpenAI], rowopenai) is in the table as "sole case variant listed under its persisted spelling". With the arm restored it fails withUserBacked = false, want true (reason "\"openai\" is not the saved provider \"OpenAI\" — this resolved row comes from project config or the environment"). The cases that should still refuse (projectWORKbeside userwork, and projectWORKalone after the unusable user row is filtered out) hitresolved == nameand still pass. - Browser-flow
BeforeSave:TestLoginLoopbackBeforeSaveFailurePreservesPreviousTokendrives the loopback redirect and asserts the token exchange ran, so it can only pass by reaching the guard. It also checks the earlier token survives. With the check removed fromLoginit fails:Login error = <nil>, want pre-save rejection. - Hermetic tests, found while running the stack on a dev machine (Windows, with real provider keys exported):
TestRunProvidersUseMatchesCredentialIdentityButNotUnicodeCaseFold(973a4f82) andTestProviderIdentityMatrix(dd265a26) ran throughproviderSetupDeps, which only redirects writes. They resolved the developer's real user config and environment.- The long-s case failed against a real config that had a
ſrow. Both now use main'sproviderEnvSetupDepswith a fixed environment. - CI didn't catch it because its runners have neither.
#893 (df51fe4d): only the merge, plus one test fix. resolveProviderMutationName gets source names from DefaultResolveOptions, which reads the process environment rather than deps. So with OPENAI_API_KEY exported, the matrix's case-variant use is correctly refused, because a concrete openai row exists. The matrix now calls clearProviderEnv the way the file's environment-derived tests already do.
#894 (d1ebea58): the post-rename publish failure is fixed in d826ec77; details are on that PR.
#895 (38fe6386): effectiveProvider is resolvedOverride (d7996e43); details are on that PR.
Verification, at the #895 head (which contains the whole stack):
go vet ./...for linux/darwin/windows, gofmt, build and smoke,govulncheck(no vulnerabilities) andgit diff --check.go test ./...on Windows and on Linux (WSL). What's left fails the same way on cleanmainon that machine: git can't openNULfrom Git Bash (gitsafe,zerogit, oneclitest), and under WSL twodaemon/remotebundle tests and onesandboxbackend test.
@PierrunoYT heads-up: #1105 moved the module to github.com/Twigpine/zero, and six of your open PRs (#685, #892, #893, #894, #895 and #987) still add imports with the old path, so each needs main merged and those imports renamed before it can go in. Main itself won't build until #1153 lands (my #1149 went in a minute after #1105 with the old path), so it's easiest to merge main after that. While you're in #892, the CHANGELOG.md hunk can come out too.
Walkthrough
Provider identity handling now uses trimmed lowercase credential-store identities while preserving exact persisted names. Configuration writes and migrations validate names before side effects. CLI and TUI provider operations preserve shared credentials and reject ambiguous or colliding names.
Changes
Provider identity consistency
internal/credstore/credstore.go,internal/config/credentials.go,internal/config/writer.go,internal/config/resolver.go,internal/config/*_test.gointernal/cli/auth.go,internal/cli/setup.go,internal/cli/provider_setup.go,internal/cli/provider_onboarding.go,internal/cli/*_test.gointernal/tui/model.go,internal/tui/command_center.go,internal/tui/provider_manager.go,internal/tui/provider_wizard.go,internal/tui/*_test.goEstimated code review effort: 4 (Complex) | ~60 minutes
Sequence Diagram(s)
Possibly related PRs
Suggested reviewers:
jatmn,vasanthdev2004,gnanam1990Merge Risk: Low · up to
705deThe PR changes provider identity matching, persistence, and credential cleanup across CLI and TUI flows. It is mergeable with explicit owner follow-up because some failure paths can expose unredacted details or leave credential state inconsistent, while the remaining concerns are bounded and do not indicate a release-blocking correctness or availability issue.
Pre-merge checks: 4 · 1
Full details: Title check
Explanation
The title "Define provider identity primitives and persisted-name validation (1/4)" matches the main change in the changeset. The raw summary shows new identity helpers (SameProviderIdentity, ResolvePersistedProviderName, ValidatePersistedProviderNames, NormalizeProvider) and persisted-name validation in resolver and writer code, and the PR objectives describe it as the first of a four-PR split. The title is specific and concise. The "(1/4)" suffix is a series marker and does not affect the assessment.
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment
@coderabbitai helpto get the list of available commands.