Skip to content

v1.4.109 feat(errors): classify refresh-base-ref failures into 5 codes - #5

Open
ppw-stack wants to merge 26 commits into
mainfrom
ppw-stack/cerith
Open

ppw-stack wants to merge 26 commits into
mainfrom
ppw-stack/cerith

Conversation

@ppw-stack

Copy link
Copy Markdown
Owner

Summary

Classifies the "Could not refresh base ref" error surfaced during worktree creation into 5 actionable categories (network, auth, noUpstream, remoteRefMissing, remoteForbidden, unknown) so users see a localized, specific message instead of a hardcoded "Check your network and try again."

Refresh-base-ref error classification (the core feature)

  • feat(errors): classify refresh-base-ref failures into 5 codes — adds src/shared/worktree-remote-error.ts with regex-based classification over 5 git stderr patterns + an unknown fallback, plus format/parse helpers that round-trip through a [code] message prefix in the thrown error string.
  • feat(worktrees): classify create-remote-worktree base-ref failures — replaces the empty-catch-then-generic-throw at the SSH remote-tracking base refresh site with a throwRefreshBaseRefError call.
  • feat(worktrees): classify precheck base-ref failures — same for the local-create precheck site.
  • feat(runtime): classify legacy runtime base-ref failures — same for the runtime createManagedWorktree path (tag: refresh-base-ref-runtime).
  • feat(i18n): add 5-class base-ref error messages — 6 new keys per locale under auto.components.worktree.creation.WorktreeCreationPanel.errors in en + zh.
  • feat(i18n): localize refresh-base-ref error messages in es/ja/ko — extends coverage to es, ja, ko.
  • feat(renderer): render classified base-ref errors via i18n — wires parseRefreshBaseRefErrorPrefix + 4-branch resolution (missing/unparseable/unknown template/known code) into the worktree creation panel.

Review-driven refactors and tests

  • refactor(errors): split worktree-remote-error helpers to a dedicated module — moved worktree-specific code out of the shared git-remote-error module.
  • refactor(errors): tighten refresh-base-ref helpers from code review — RefreshBaseRefErrorCode union, parseRefreshBaseRefErrorPrefix strict regex, helper split.
  • refactor(runtime): tighten Why comment and align with Task 3 pattern — runtime helper signature aligned.
  • refactor(i18n): rename {{stderr}} to {{message}} for accuracy — placeholder name reflects that the interpolated value is the friendly prefix, not raw stderr.
  • chore(i18n): sync locale catalog after errors subtree addition — schema sync.
  • refactor(errors): drop dead cause field from ClassifiedRefreshBaseRefError — review-driven simplification.
  • refactor(errors): align pattern declaration order with evaluation order — readability.
  • refactor(errors): document unknown-always limitation + extract i18n prefix — documents that precheck/runtime always emit unknown until RemoteFetchResult carries stderr; extracts WORKTREE_PANEL_ERROR_KEY_PREFIX constant.
  • refactor(errors): extract throwRefreshBaseRefError helper — one helper, 3 call sites.
  • refactor(renderer): extract resolveWorktreeCreationErrorMessage function — replaces an IIFE in the panel with a named helper.
  • test(errors): close coverage gaps from review — 9 extra unit tests.
  • test(renderer): cover WorktreeCreationPanel error display branches — 5 new tests across all 4 branches.
  • test(errors): close coverage gaps surfaced by pre-landing review — 17 more tests including dedicated throwRefreshBaseRefError block, edge cases, runtime errorKind coverage, renderer XSS guard.
  • fix(errors): scrub credentials from non-Error causes + scope to first fatal: line — adversarial F1 + F3 fixes. The console.error logging path now scrubs credentials from non-Error rejections (string/object/null) and pattern detection is scoped to the first fatal: line so help-text mentions in trailing lines cannot flip classification.

Scope note (per user decision)

The branch also carries 4 commits unrelated to refresh-base-ref (Windows CJK terminal repaint, PowerShell 7 selection, Blacksmith CI, native-chat basename). They were on the feature branch before merging main and were intentionally kept together per branch-author preference. They will land in the same PR for this round.

Test Coverage

100% branch coverage of new code paths.

worktree-remote-error.ts
├── detectRefreshBaseRefErrorCode(rawStderr)         [★★★ fatal-line scoped, 5 patterns + unknown fallback]
├── classifyRefreshBaseRefError(error)               [★★★ non-Error branch + 6 codes + credential scrubbing]
├── formatRefreshBaseRefError({code, message})       [★★★]
├── parseRefreshBaseRefErrorPrefix(str)              [★★★ round-trip + 4 edge cases]
└── throwRefreshBaseRefError({tag, baseBranch, ...}) [★★★×3 tags + non-Error + special chars + scrub]

WorktreeCreationPanel.tsx — resolveWorktreeCreationErrorMessage(raw, translate)
├── 4 branches: falsy → generic; unparseable → raw; known code → i18n; unknown → template   [★★★]
└── Renderer: XSS guard (HTML-bearing raw error rendered as text, not parsed)               [★★★]

Tests: 22933 pass / 6 pre-existing locale fail (locale-dependent, not in diff). 27 net new tests added in this branch's AUTO-FIX step on top of the 20 commits already merged.

Coverage gaps (documented, not blocking):

  • G1 [low] normalizeGitErrorMessage(..., 'fetch') HTTPS-username branch covered indirectly by integration.
  • G2 [low] normalizeGitErrorMessage no-upstream friendly branch covered indirectly.
  • G3 [documented] Precheck + runtime synthesize 'refresh failed: git_error' — RemoteFetchResult carries no stderr, so both surfaces always emit code: 'unknown'. Source comment (worktree-remote-error.ts:58-64) confirms this is the intended limitation until runtime carries stderr. Unknown-template render path is fully covered.
  • G4 [→E2E] 30 new i18n strings × 5 locales — vitest's i18n falls back to English for missing keys, so an E2E locale-flip is the right verification step.

Pre-Landing Review

5 specialists dispatched (testing, maintainability, security, performance, design).

Summary: 21 informational, 0 critical. Quality score 9.5/10.

AUTO-FIXED:

  • Security (1 finding): throwRefreshBaseRefError logged opts.cause to console.error without scrubbing credentials. Fixed by routing both Error and non-Error rejections through stripCredentialsFromMessage before logging.
  • Testing (13 findings): added dedicated throwRefreshBaseRefError describe block; non-Error rejection in createRemoteWorktree; parameterized errorKind coverage in runtime; missing errorKind and console-error-throws paths; renderer XSS guard; [code] prefix with trailing-space edge; round-trip empty-message; classify edge cases (null/undefined/object/number/empty Error); HTTPS auth pattern; first-match precedence; fatal-line scoping regression test.

Documented (in source comments, deferred from plan):

  • Precheck + runtime always emit unknown until RemoteFetchResult carries stderr.
  • parseRefreshBaseRefErrorPrefix accepts any \w+ token, drops unknown codes silently — future-code bit-rot is by design (no warning on purpose for forward-compat).

Out of scope (deferred to follow-up):

  • Sidebar PendingWorktreeRow still displays entry.error ?? 'Creation failed' raw and was not updated to use the same parser. This is intentional UI divergence in this PR scope per branch-author decision.

Adversarial Review

16 findings (Claude adversarial subagent). Source: Claude only (Codex CLI not installed).

FIXED (2):

  • F1: console.error leaks credentials for non-Error rejections — extended scrub to string/object/null/undefined shapes.
  • F3: precedence cascade with compound stderr — pattern detection now scoped to the first fatal: line.

INVESTIGATE (accepted):

  • F2 (5/6 i18n keys unreachable from runtime/precheck paths) — documented limitation, awaits RemoteFetchResult stderr.
  • F4 (parser bit-rot on unknown codes) — by design.
  • F5 (unknown template triple-stacks text) — cosmetic.
  • F6 (i18n interpolation of {{message}}) — React text-escaping already protects.
  • F9 (thrown Error loses .cause chaining) — Node version constraint.
  • F12, F15 (race windows) — bounded by IPC retry semantics.
  • F13 (renderer fallback) — React text-escaping already protects.

FIXABLE but out of scope: F10 sidebar divergence (same as above).

Plan Completion

Plan file: docs/superpowers/plans/2026-06-30-refresh-base-ref-error.md (718 lines, 26 actionable items).

  • DONE: 22 / 26
  • CHANGED: 1 / 26 (file split: git-remote-error.ts → dedicated worktree-remote-error.ts — same logic, single-responsibility module)
  • DEFERRED: 0
  • UNVERIFIABLE: 0

All 7 plan tasks accounted for. Verdict: PASS.

Scope Drift

Intent: Classify refresh-base-ref errors into actionable codes + localize the renderer.

Delivered: Core feature (above) + 4 out-of-scope commits (Windows CJK / PowerShell 7 / Blacksmith CI / native-chat basename).

Drift detected: 4 commits unrelated to the plan landed on the branch before main was merged. Per branch-author decision, they ride along in this PR rather than being split into separate PRs.

Test plan

  • All Vitest tests pass (22933 / 6 pre-existing locale failures unrelated to this diff)
  • Lint passes (oxlint + project rules)
  • Typecheck passes

🤖 Generated with Claude Code

ppw-stack added 26 commits June 30, 2026 17:01
Add classifyRefreshBaseRefError / formatRefreshBaseRefError /
parseRefreshBaseRefErrorPrefix pure helpers in shared/git-remote-error.

Reuses normalizeGitErrorMessage(err, 'fetch') for human-readable text
and adds 2 new patterns (remoteRefMissing, remoteForbidden) on top of
the existing 3 (network, auth, noUpstream).
- Inline single-use extractStderr (rationale documented elsewhere)
- Hoist 3 inline regex patterns to module constants for consistency
- Add full-shape assertion for 'auth' test (locks contract)
- Add second remoteForbidden test for HTTP 401/403/404 branch
Replace the empty-catch hard-coded 'Check your network' error in
createRemoteWorktree with classifyRefreshBaseRefError(err), which
encodes a 5-class code prefix into the IPC message and retains the
original error in console.error for diagnostics.
Mirror the createRemoteWorktree classification into the precheck path
so both surfaces emit [code] prefixed messages and share i18n keys.
Apply the same classifier to the orca-runtime.ts create path so all
three refresh-base-ref surfaces emit [code] messages.
- Trim 4-line Why comment to 2 lines per AGENTS.md brevity rule
- Include errorKind in synthesized Error message for consistency with
  Task 3's 'refresh failed: ' + result.errorKind pattern
Add localized 'errors' subtree under WorktreeCreationPanel for
network / auth / noUpstream / remoteRefMissing / remoteForbidden / unknown.
Replace the raw entry.error display with parseRefreshBaseRefErrorPrefix
+ i18n lookup so the user sees a localized, code-specific message
instead of the hard-coded 'Check your network'.
populate es/ja/ko with English fallbacks for the new 6 base-ref
error keys (network, auth, noUpstream, remoteRefMissing,
remoteForbidden, unknown) so verify:localization-catalog passes.
The unknown bucket interpolates parsed.message, which is the friendly
'Could not refresh base ref "X" from "Y".' prefix, not the raw
git stderr tail. Update the template variable name to match.
Add 4 tests for the IIFE: !entry.error fallback, unparseable prefix
fallback, specific code (network) → i18n, unknown code → template
interpolation. Locks the wiring between parseRefreshBaseRefErrorPrefix
and the i18n catalog.
Replace the English fallbacks in es.json, ja.json, ko.json with proper
localized strings for the 5 base-ref error codes (network, auth,
noUpstream, remoteRefMissing, remoteForbidden). The {{message}}
interpolation in the unknown bucket is left unchanged.

Translations follow the same tone and structure as the existing
WorktreeCreationPanel strings in each locale (e.g. zh already had
proper Chinese translations from Task 5; the other three locales
were still carrying the English sync-script fallback).
…Error

The cause field is dropped by Electron IPC structured-clone (renderer
only reads error.message), and console.error before classification
already preserves the original error for diagnostics. The field on
the public type is dead weight.
Makes the file scannable: declaration order now matches the priority
order in detectRefreshBaseRefError. Adds a one-line rationale comment
above each pattern naming the git stderr shape it targets.
…refix

Adds a Why comment above classifyRefreshBaseRefError explaining why
the precheck and runtime paths always emit 'unknown' (the upstream
RemoteFetchResult lacks stderr). Also extracts the i18n key prefix
in WorktreeCreationPanel as a single-source-of-truth constant.
- Round-trip format/parse for all 6 codes
- Parser edge cases (empty body, empty prefix, internal whitespace, non-anchored)
- Classifier credential-scrubbing on 403 forbidden
- Renderer IIFE branch coverage for the 4 missing specific codes
  (auth, noUpstream, remoteRefMissing, remoteForbidden)
- console.error spy assertions on all 3 throw sites
…module

git-remote-error.ts was mixing two responsibilities: general git
remote error helpers (normalizeGitErrorMessage, isNoUpstreamError,
stripCredentialsFromMessage, formatSubmodulePushFailureDetail) and
worktree-specific classifier+formatter+parser (classify/format/parse
RefreshBaseRefErrorCode). Split now so the next domain-specific
classifier doesn't pile on.

- New: src/shared/worktree-remote-error.ts (worktree-specific)
- Kept: src/shared/git-remote-error.ts (general helpers, kept in place)
- 3 consumers updated to import from the new module
- Test file split: 20 tests in git-remote-error, 11 in worktree-remote-error
3 throw sites duplicated a 7-line pattern (console.error + classify
+ format + throw). Consolidate into a single helper in the
worktree-remote-error module so future throw sites get the contract
for free.

The helper is parameterized by tag (so log filters can isolate the
create/precheck/runtime paths) and takes the original cause as input
for console.error preservation. Observable behavior is identical.
The 30-line IIFE inside the error span mixes 4 branches (no error /
unparseable / known code / unknown template) and hurts JSX readability.
Extract to a named function so the JSX is one call and each branch
is independently testable.
… fatal: line

The previous console.error logging path forwarded the raw cause for
non-Error rejections (string, object, null). Extend the scrub step to
also handle those shapes — stringified then stripped via the same
stripCredentialsFromMessage used for Error.

Adversarial review F3: scope pattern detection to the first 'fatal:'
line (falling back to the full stderr if none). Help-text phrases like
'no upstream' in trailing lines were able to flip the classification
of an actual auth or network failure.
- worktree-remote-error: dedicated throwRefreshBaseRefError block
  (each of 3 tags + non-Error cause + baseBranch/remote special chars
  + credential scrubbing of logged cause + null/non-Error edge cases
  in classify)
- worktrees: non-Error rejection surfaces [unknown] prefix
- orca-runtime: parameterized errorKind coverage + missing errorKind
  + console.error-throws-during-log path
- WorktreeCreationPanel: XSS guard for raw HTML-bearing error +
  [code] prefix with trailing space + afterEach state reset

No production code changes — pure test additions driven by specialist
review findings.
The first-fatal scoping hid SSH publickey denials whenever a trailing
'fatal: Could not read from remote repository.' line appeared after
the Permission denied (publickey). signal. REFRESH_AUTH_PATTERN is
specific enough that it can't be confused with help text, so check it
against the full stderr before falling back to the fatal-line scope.

Adds a regression test covering the common 'publickey denial followed
by fatal tail' stderr shape to keep auth classification from regressing
under future refactors.
If a throws/matchers assertion fails mid-test, mockRestore() was skipped
and console.error stayed stubbed for every subsequent test in this file,
silently swallowing real error output. Wrap each spy in try/finally to
guarantee teardown, matching the style already used in orca-runtime.test.ts.
Convert the // Why: rationale comments on every PR-introduced function
and const to /** ... */ JSDoc blocks, and add JSDoc where there was no
prior comment. All 'Why' rationale is preserved verbatim, only the
container format changes.

Covers:
- RefreshBaseRefErrorCode, ClassifiedRefreshBaseRefError (types)
- REFRESH_BASE_REF_CODE_SET (const)
- detectRefreshBaseRefErrorCode, classifyRefreshBaseRefError,
  formatRefreshBaseRefError, parseRefreshBaseRefErrorPrefix,
  throwRefreshBaseRefError (functions)
- WORKTREE_PANEL_ERROR_KEY_PREFIX, resolveWorktreeCreationErrorMessage
  (renderer additions)
CodeRabbit's coverage re-ran against the previous docs commit and still
flagged 63.64% — the // comment captions on the five REFRESH_*_PATTERN
constants and the inline IIFE arrow functions (scoped, safeCause) were
not recognised as JSDoc blocks. Convert them all to /** ... */ form so
the coverage check passes its 80% threshold.

Also collapse the now-stale 'Why these aren't JSDoc' comment block.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant