#892

Define provider identity primitives and persisted-name validation (1/4)

OpenPierrunoYTwants to merge intofrom

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 as config.SameProviderIdentity. Callers deciding whether two spellings share one stored secret use it rather than strings.EqualFold: Unicode case folding equates s and ſ while strings.ToLower does not, so an EqualFold comparison can promise a survivor access to a key it can never look up.
  • Exact row identity — trimmed provider.Name equality, used by every row-targeting mutator (MarkProviderAPIKeyStored, ProviderPersisted's mutating callers, SetProviderModel, ClearProviderKeyStored, RemoveProvider, and the oldName lookups in RenameProvider/EditProvider).
  • Publication validation — ValidatePersistedProviderNames rejects persisted rows repeating a folded identity, whether the spellings are identical or only case variants. writeConfigFile guards every write with it, and Resolve() 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:

HelperWhat 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 before EnsureCatalogProvider's case-insensitive lookup, then publishes through PublishProviderCredential. A legacy openrouter/OPENROUTER config 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 the ProviderPersisted gate and the mutator, so zero providers remove work against a sole WORK row 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 from ProviderKeyRetainedAfterRemoval so 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 — switchProviderModel persists with the spelling SetActiveProvider resolved, and persistSelectedModel resolves before writing; write failures on a persisted row are surfaced instead of dropped into _, _ =.
  • EqualFold audit — every provider-name comparison in auth.go, picker.go, provider_wizard.go, provider_wizard_discovery.go, session.go, and EnsureCatalogProvider was classified by intent and moved to either exact row spelling or SameProviderIdentity.

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 (work vs WORK) and s/ſ 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 ● active marker, the rename ZERO_PROVIDER sync, the delete "keeps running" note, and the edit restart note. reloadProviderManagerRows resolves once into manageActiveName so render and sync share one value.
  • syncSavedProviderModel is the single reconciliation point for a persisted model change. The manager's rows and the picker's model sections read savedProviders, not the live profile, so switchProviderModel and handleModelCommand (via persistSelectedModel, which now returns the exact row it wrote) both mirror the write into that list — otherwise /providers kept 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, stale activeProvider repair, and s vs ſ 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, wizardProviderStoredKey Unicode identity, and case-variant model persistence.
  • Config-level tests for ResolvePersistedProviderName, CredentialKeyRetained, ProviderKeyRetainedAfterRemoval, and PublishProviderCredential's restore/delete rollback paths.
  • TestModelSwitchSyncsSavedProviders — a case-variant switch mirrors onto the row SetProviderModel actually wrote, leaves unrelated rows alone, and shows through providerManagerRowMeta without a restart; persistSelectedModel returns the resolved row spelling its caller mirrors with.
  • TestProviderManagerSoleRowCaseVariantTracksLiveSession — live work against a sole WORK row gets the active marker, and a rename carries onto providerName, providerProfile, and ZERO_PROVIDER.
  • TestProviderManagerCaseVariantDeleteDoesNotChangeLiveSibling — the sibling guard: rows work+WORK, live work, deleting WORK leaves 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.
  • TestProviderManagerCaseVariantEditDoesNotChangeLiveSibling was split in two. Its fixture held a single row (WORK) with live work, 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 because EditProvider rejects a duplicate-identity config before mutating.
  • assertAmbiguousConfigUnchanged follows 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

78
coderabbitai[bot]3mo ago

NOTE

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

  • Last reviewed commit: 383346a4ebcbf9ea69740ee8967ffb94b2acbce0
  • Latest commit, not reviewed: dd265a269341c623fe63ab327b87955f7b686f2b

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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

Layer / File(s)Summary
Identity and validation contracts
internal/credstore/credstore.go, internal/config/credentials.go, internal/config/writer.go, internal/config/resolver.go, internal/config/*_test.go
Added shared normalization, file locking, persisted-name validation, resolver matching, preflight checks, exact marker matching, case-variant cleanup, credential retention checks, and atomic credential publication with rollback.
CLI validation and credential cleanup
internal/cli/auth.go, internal/cli/setup.go, internal/cli/provider_setup.go, internal/cli/provider_onboarding.go, internal/cli/*_test.go
CLI writes and logout now preflight configuration. Provider removal retains shared credentials and reports cleanup failures. Authentication publication restores credentials when marker updates fail.
TUI provider lifecycle handling
internal/tui/model.go, internal/tui/command_center.go, internal/tui/provider_manager.go, internal/tui/provider_wizard.go, internal/tui/*_test.go
TUI provider lookup and mutations now use explicit identity rules, preserve shared credentials, preflight writes, report cleanup failures, and synchronize live state.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLIOrTUI
  participant Config
  participant CredentialStore
  CLIOrTUI->>Config: preflight provider mutation
  Config->>CredentialStore: resolve normalized provider identity
  CredentialStore-->>Config: identity and retention result
  Config-->>CLIOrTUI: allow or reject mutation
  CLIOrTUI->>CredentialStore: store, retain, or delete credential
  CLIOrTUI->>Config: persist provider or API-key marker

Possibly related PRs

  • Gitlawb/zero#725 — Extends the same provider-identity, validation, preflight, and credential-cleanup flows.
  • Gitlawb/zero#893 — Modifies the same provider-identity and credential-marker paths.
  • Gitlawb/zero#894 — Extends transactional provider and credential handling.

Suggested reviewers: jatmn, vasanthdev2004, gnanam1990

Merge Risk: Low · up to 705de

The 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

Failed checks: 1 warning

Check nameStatusExplanationResolution
Docstring CoverageDocstring coverage is 49.25% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed checks: 4 passed
Check nameStatusExplanation
Linked Issues checkCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes checkCheck skipped because no linked issues were found for this pull request.
Title checkThe 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, ResolveP…
Description CheckCheck skipped - CodeRabbit’s high-level summary is enabled.
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)
  • Create PR with unit tests
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

coderabbitai[bot]requested changes3mo ago
coderabbitai[bot]3mo ago

Actionable comments posted: 1

🧹 Nitpick comments (1)
internal/config/credentials.go (1)

102-148: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Collapse the two clear functions into one predicate-driven helper.

ClearProviderKeyStored and ClearProviderKeyStoredCaseVariants differ 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)
+}

ClearProviderKeyStored then passes func(row string) bool { return strings.TrimSpace(row) == provider }, and ClearProviderKeyStoredCaseVariants passes a credstore.NormalizeProvider comparison.

🤖 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.go
  • internal/config/credentials_test.go
  • internal/config/resolver.go
  • internal/config/resolver_test.go
  • internal/config/writer.go
  • internal/config/writer_test.go
  • internal/credstore/credstore.go
jatmnrequested changes3mo ago
jatmn3mo ago

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:58 The new collision check is inside UpsertProvider, but Go evaluates SecureProviderProfile(profile, configPath) first. That helper immediately calls Store.Set, and the store canonicalizes WORK to work. Consequently, starting with a valid saved work profile holding key OLD, zero providers add ... --name WORK --api-key NEW overwrites the work secret with NEW and only then rejects the duplicate config row. The command reports failure while the existing provider has silently changed credentials. saveSetupProvider and 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 UpsertProvider behavior 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:401 This new path intentionally allows RemoveProvider("WORK") to repair a legacy work/WORK config and leave the exact work row. 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 to work, cleanup deletes the survivor's shared key; its surviving apiKeyStored: true marker 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:452 auth logout WORK calls ForgetProviderKey, whose credential-store deletion canonicalizes the argument to work, then calls the newly exact-only ClearProviderKeyStored(configPath, "WORK"). A normal config row named work is not matched, so its secret is removed while apiKeyStored stays true. This is a regression from the base implementation's EqualFold cleanup: subsequent status/selection logic sees a configured credential, while ApplyStoredAPIKey cannot load one. The TUI's key-removal flow has the same mismatch, and the new ClearProviderKeyStoredCaseVariants helper 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:634 The new contract deliberately permits s and Unicode long-s (ſ) as distinct credential identities because strings.ToLower keeps their store keys distinct. The provider manager still uses strings.EqualFold, which equates them. If the session runs ſ and the user edits non-active s, the config edit targets the correct exact row, but the subsequent live-session sync treats it as the active provider and rewrites m.providerName, m.providerProfile.Name, and ZERO_PROVIDER to 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, and config.SameProviderIdentity only when reasoning about a shared credential. Add a live-session test covering active ſ plus an edit/remove of s.

  • [P2] Do not turn a case-variant providers use request into a successful no-op internal/cli/provider_onboarding.go:63 ProviderPersisted now returns false unless the input spelling exactly matches the saved row. The fallback added for environment-derived providers is unchanged and uses strings.EqualFold. For a saved OpenAI row, zero providers use openai therefore concludes it is not persisted, finds the row in the resolved list case-insensitively, prints the environment-provider explanation, and exits successfully without calling SetActiveProvider or 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 EqualFold as 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, and s/ſ inputs.

  • [P2] Validate implicit provider names before accepting persisted identities internal/config/writer.go:26 The validator indexes the trimmed raw name, so an empty name and openai are accepted as different identities. Later, normalizeProvider supplies openai for 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.

PierrunoYT3mo ago

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 use behavior without conflating s and ſ.
  • Reject blank persisted provider names before implicit openai normalization.
  • 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.

coderabbitai[bot]requested changes3mo ago
coderabbitai[bot]3mo ago

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.go
  • internal/cli/auth_test.go
  • internal/cli/provider_onboarding.go
  • internal/cli/provider_onboarding_test.go
  • internal/cli/provider_setup.go
  • internal/cli/setup.go
  • internal/cli/setup_test.go
  • internal/config/credentials.go
  • internal/config/credentials_test.go
  • internal/config/resolver_test.go
  • internal/config/writer.go
  • internal/config/writer_test.go
  • internal/tui/provider_manager.go
  • internal/tui/provider_manager_test.go
  • internal/tui/provider_wizard.go
  • internal/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
PierrunoYT3mo ago

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 build
  • go run ./cmd/zero-release smoke
  • go 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.

PierrunoYT2mo ago

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 --name escape. 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 build and go 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), and internal/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.

PierrunoYT1mo ago

@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:

PRnew headmerge
#892dc6b3876main → pr1 (3 conflicted files, below)
#8938ae20369refreshed pr1 → pr2 (one import line)
#894542258carefreshed pr2 → pr3 (clean)
#8959be29248refreshed pr3 → pr4 (clean)

The only real resolution is in #892:

  • internal/tui: main's #1083 moved the model-picker switch decision into modelPickerSwitchOwner (picker.go), so the row's owner label and the switch use one decision. That helper still had the old identity comparison (EqualFold against m.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 with activeProviderRowName(), and return the resolved row name. model.go switches to that name, and modelPickerEffectiveOwner labels with it, so the label and the switch still agree.
  • internal/config/writer.go and writer_test.go: import unions (credstore + notify, fmt + io), and both sides' appended tests kept.
  • (#893: runtime + slices import 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.

PierrunoYT1mo ago

@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 == persistedName arm. Only a concrete row with the requested spelling shadows the persisted row now. Copilot's case (persisted OpenAI, resolved [OpenAI], row openai) is in the table as "sole case variant listed under its persisted spelling". With the arm restored it fails with UserBacked = 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 (project WORK beside user work, and project WORK alone after the unusable user row is filtered out) hit resolved == name and still pass.
  • Browser-flow BeforeSave: TestLoginLoopbackBeforeSaveFailurePreservesPreviousToken drives 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 from Login it 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) and TestProviderIdentityMatrix (dd265a26) ran through providerSetupDeps, 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's providerEnvSetupDeps with 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) and git diff --check.
  • go test ./... on Windows and on Linux (WSL). What's left fails the same way on clean main on that machine: git can't open NUL from Git Bash (gitsafe, zerogit, one cli test), and under WSL two daemon/remote bundle tests and one sandbox backend test.
Vasanthdev20041mo ago

@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.