Skip to content

arch: configuration schema validation and structured error types #507

Closed

Description

@admarble

Problem (User Impact)

Configuration: Users who misspell a setting in .sequant/settings.json (e.g., "timoeut": 1800 instead of "timeout") get no error — the setting is silently ignored and the default is used. There's no sequant config validate command. The state schema uses Zod validation; settings don't. This inconsistency means state corruption is caught but misconfiguration is not.

Errors: When a phase fails, the error classification (error-classifier.ts) relies on regex pattern matching against stderr strings. This is fragile — a Claude Code SDK update that changes error message wording silently breaks classification. Users see "unknown" errors that could have been actionable if properly categorized.

These are independent problems but both concern boundary hardening — validating what comes in (config) and structuring what comes out (errors).

Why Now

Acceptance Criteria

Configuration Schema Validation

  • AC-1: Zod schema for .sequant/settings.json in src/lib/settings.ts (matching the existing SettingsDefaults structure). Schema uses .passthrough() at the top level to allow forward-compatible fields, but logs warnings for unknown keys
  • AC-2: Settings loaded via loadSettings() are validated against the schema. Invalid values produce clear error messages: "settings.json: 'run.timeout' must be a number, got string 'fast'"
  • AC-3: sequant status displays any settings validation warnings (misspelled keys, type mismatches)
  • AC-4: sequant init generates a settings file with inline comments documenting each field and its default value
  • AC-5: Settings schema is exported for programmatic use: import { SettingsSchema } from 'sequant'

Structured Error Types

  • AC-6: SequantError base class with typed subclasses:
    • ContextOverflowError — token/context limit exceeded
    • ApiError — rate limits, 503, auth failures (with HTTP status code if available)
    • HookFailureError — pre-commit hook failure (with hook name)
    • BuildError — TypeScript, ESLint, npm errors (with file/line if parseable)
    • TimeoutError — phase exceeded time limit (with configured timeout value)
    • SubprocessError — git/gh command failed (with command, exit code, stderr)
  • AC-7: error-classifier.ts refactored to produce typed error instances instead of string categories. Exit codes used as primary signal, stderr patterns as secondary
  • AC-8: Run logs store the error type name and structured metadata (not just the category string). Backwards compatible: old logs with string categories still parse correctly
  • AC-9: Phase executor retry logic uses error types instead of string matching — e.g., if (error instanceof ApiError && error.isRetryable) instead of if (category === "api_error")
  • AC-10: Error types are exported: import { SequantError, ApiError } from 'sequant'

Scope & Gaps to Watch

  • Gap: Settings migration — Existing .sequant/settings.json files in user projects must continue working. The schema should be lenient on load (warn, don't reject) but strict on write (init/update generates valid config)
  • Gap: Forward compatibility — Future Sequant versions may add new settings. Schema must use .passthrough() or equivalent to not reject unknown keys from newer versions. Log a warning, don't crash
  • Gap: Error message stability — Structured errors reduce reliance on stderr parsing, but some classification still requires it (e.g., distinguishing TypeScript errors from ESLint errors). Document which patterns are fragile and add integration tests for them
  • Gap: SDK error types — @anthropic-ai/claude-agent-sdk may already expose structured errors in newer versions (current: ^0.2.11). Check before wrapping. If the SDK improves, the wrapper should delegate, not duplicate
  • Risk: Over-validation — Settings validation should warn, not block. A user with a valid workflow shouldn't be stopped because they have an extra experimental field in their settings

Technical Notes

  • Current settings loading: src/lib/settings.ts — loadSettings() reads JSON, merges with DEFAULT_SETTINGS, no validation
  • Current error classifier: src/lib/workflow/error-classifier.ts — 97 lines, 6 categories, pure regex on stderr arrays
  • Current run log error storage: error?: string field in PhaseState — extend to error?: { type: string; message: string; metadata?: Record<string, unknown> } with backwards-compatible parsing
  • Zod pattern for warnings: schema.safeParse() returns { success, data, error } — use error.issues for warning messages without throwing

Dependencies

Batch Group

sequant run batch 1 (parallel with RunOrchestrator extraction #503 — no shared dependencies)

Activity

  1. added
    enhancement
    roadmap
    on Apr 8, 2026
  2. admarble commented on Apr 8, 2026

    @admarble
    ContributorAuthor

    Spec Plan — #507: Configuration Schema Validation & Structured Error Types

    Scope Assessment

    Metric Value Status
    Feature count 2 ⚠️
    AC items 10 ❌
    Directory spread 3 ⚠️

    Verdict: ❌ SCOPE_SPLIT_RECOMMENDED — but proceeding as-is since both features are independent, share no code, and are explicitly bundled as "boundary hardening" prerequisites for #505. Implemented in separate phases.

    Quality Loop: auto-enabled due to scope.

    Non-Goals

    • Settings migration tool (lenient-on-load covers existing files)
    • Custom error recovery strategies per error type
    • CLI sequant config validate subcommand (covered by status)
    • Error telemetry or crash reporting
    • SDK error wrapping if SDK already provides it

    AC Checklist with Verification

    Configuration Schema Validation

    AC Description Verification Method
    AC-1 Zod schema for settings.json matching SettingsDefaults, .passthrough() at top level, warns on unknown keys Schema parses valid JSON, rejects invalid types, passes through unknown keys with warnings Unit Test
    AC-2 loadSettings() validates against schema, produces clear error messages { "run": { "timeout": "fast" } } → warning message with path and type mismatch Unit Test
    AC-3 sequant status displays validation warnings Run status with misspelled keys → "Settings Warnings" section in output Integration Test
    AC-4 sequant init generates documented settings file Init creates JSON + companion reference doc Integration Test
    AC-5 SettingsSchema exported from sequant package import { SettingsSchema } from 'sequant' works, .safeParse() available Unit Test

    Structured Error Types

    AC Description Verification Method
    AC-6 SequantError base + 6 typed subclasses with metadata instanceof checks, .name, .isRetryable, typed metadata Unit Test
    AC-7 classifyError() returns typed instances, exit codes as primary signal classifyError(["Error 429"], 1) → ApiError instance Unit Test
    AC-8 Run logs store errorType + metadata, old format still parses New fields optional in schema; old { category: "api_error" } parses OK Unit + Integration
    AC-9 Retry logic uses error.isRetryable instead of string matching ApiError(retryable) → retry; BuildError → no retry Unit Test
    AC-10 All error types exported from sequant import { SequantError, ApiError, ... } from 'sequant' Unit Test

    Implementation Plan

    Phase 1: Settings Schema (AC-1, AC-2, AC-5)

    1. Add Zod SettingsSchema in src/lib/settings.ts mirroring existing interfaces
    2. Add validateSettings() → { settings, warnings[] } using safeParse()
    3. Refactor getSettings() to use schema validation with warn-not-reject
    4. Export SettingsSchema from src/index.ts

    Phase 2: Settings Integration (AC-3, AC-4)
    5. Update src/commands/status.ts — display validation warnings section
    6. Update init command — generate JSON + settings.reference.md companion doc

    Phase 3: Error Types (AC-6, AC-10)
    7. Create src/lib/errors.ts — SequantError base + 6 subclasses with isRetryable
    8. Export all error types from src/index.ts

    Phase 4: Error Classifier Refactor (AC-7, AC-8, AC-9)
    9. Refactor classifyError() to return SequantError instances; add exitCode param
    10. Extend ErrorContextSchema with optional errorType + metadata fields
    11. Update batch-executor.ts call sites (lines 556, 818)
    12. Update phase-executor.ts retry logic to use error.isRetryable

    Parallel Groups

    Phase 1 + Phase 3 → can run in parallel (no shared files)
    Phase 2 depends on Phase 1
    Phase 4 depends on Phase 3
    

    Design Decisions

    1. Zod schema coexists with TypeScript interfaces — Transitional; interfaces serve as documentation. Future cleanup can use z.infer<>.
    2. isRetryable on error types — Error knows if it's generally retryable (429 yes, auth no). Executor still decides based on config + attempt count.
    3. AC-4 JSON comments — JSON doesn't support comments. Generate clean JSON + companion settings.reference.md. No JSONC/JSON5 (non-standard, tooling issues).
    4. AC-9 augments retry, doesn't replace — Keep cold-start duration check; add error-type retryability as additional signal.

    Open Questions

    1. SDK error types — Check @anthropic-ai/claude-agent-sdk exports before implementing AC-6. If SDK has structured errors, extend rather than duplicate.
    2. Levenshtein threshold for "did you mean?" — Suggest distance ≤ 3 for suggestions. Too lenient = noisy, too strict = unhelpful.

    Derived ACs

    Source Derived AC Priority
    Error Handling AC-11: Malformed settings.json produces clear parse error (not stack trace) Medium
    Code Quality AC-12: Error subclass .name matches class name for serialization round-trip High

    Recommended Workflow

    Phases: spec → testgen → exec → qa
    Quality Loop: enabled (auto — scope concerns)
    Reasoning: 10 ACs, 2 features, Unit+Integration verification methods → testgen creates stubs before implementation. Quality loop ensures both features pass.

    Label Review

    Current: enhancement, roadmap
    Recommended add: refactor (AC-7/AC-9 refactor existing classifier + executor)

    → gh issue edit 507 --add-label refactor

    Conflict Risk

    Worktree for #503 exists but has 0 changes. If #503 restructures batch-executor.ts before #507 lands, a rebase will be needed for error classification call sites. Low risk — proceed in parallel.

  3. added
    planned
    on Apr 8, 2026
  4. admarble commented on Apr 8, 2026

    @admarble
    ContributorAuthor

    Test Stubs Generated

    AC Description Verification Happy Path Failure Paths File
    AC-1 Zod schema for settings.json Unit Test 3 tests 11 edge cases settings-schema.test.ts
    AC-2 loadSettings() validation Unit Test 4 tests 10 failure stubs settings-schema.test.ts
    AC-3 sequant status warnings Integration Test 3 tests 2 error scenarios settings-schema.integration.test.ts
    AC-4 sequant init settings file Integration Test 3 tests 3 error scenarios settings-schema.integration.test.ts
    AC-5 SettingsSchema exported Unit Test 3 tests 3 edge cases settings-schema.test.ts
    AC-6 SequantError base + 6 subclasses Unit Test 21 tests 13 failure stubs error-types.test.ts
    AC-7 classifyError() typed instances Unit Test 6 tests 4 failure stubs error-types.test.ts
    AC-8 Run logs errorType + metadata Integration Test 4 tests 2 error scenarios settings-schema.integration.test.ts
    AC-9 Retry uses error.isRetryable Unit Test 6 tests 3 failure stubs error-types.test.ts
    AC-10 All error types exported Unit Test 7 tests 3 edge cases error-types.test.ts
    AC-11 Malformed JSON clear error Integration Test 3 tests 4 error scenarios settings-schema.integration.test.ts
    AC-12 .name matches class name Unit Test 7 tests 9 edge cases error-types.test.ts

    Totals: 170 test stubs across 3 files (70 happy path, 67 failure paths, 33 edge cases)

    Unit Test Stubs

    • __tests__/settings-schema.test.ts — 49 tests

      • AC-1: Schema parsing, type rejection, unknown key passthrough
      • AC-2: Error messages with paths, type mismatches, malformed input
      • AC-5: Package export, safeParse, type inference
    • __tests__/error-types.test.ts — 82 tests

      • AC-6: Base class + 6 subclasses, instanceof, metadata, isRetryable
      • AC-7: classifyError() with exit codes, stderr patterns
      • AC-9: Retryability by error type
      • AC-10: Package exports for all 7 types + classifier
      • AC-12: .name serialization, stack traces, error chaining

    Integration Test Stubs

    • __tests__/integration/settings-schema.integration.test.ts — 39 tests
      • AC-3: Status command warnings display
      • AC-4: Init generates JSON + reference doc
      • AC-8: Run log backward compatibility (old/new format)
      • AC-11: Malformed JSON user-friendly errors

    Next steps:

    1. Implement the test stubs (replace throw new Error(...) with actual test logic)
    2. Run /exec 507 to implement the feature
    3. Verify tests pass with npm test

    Generated with Claude Code

  5. added 2 commits that reference this issue on Apr 9, 2026
  6. admarble commented on Apr 9, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #507

    AC Coverage

    AC Source Description Status Notes
    AC-1 Original Zod schema for settings.json with .passthrough() MET SettingsSchema in src/lib/settings.ts:337-349
    AC-2 Original loadSettings() validates with clear error messages MET validateSettings() + formatZodErrors() produce path-specific messages
    AC-3 Original sequant status displays validation warnings MET status.ts:344-348 calls getSettingsWithWarnings()
    AC-4 Original sequant init generates documented settings file MET JSONC with inline comments + companion settings.reference.md
    AC-5 Original SettingsSchema exported from sequant package MET src/index.ts:132-146
    AC-6 Original SequantError base + 6 typed subclasses MET src/lib/errors.ts — all classes with isRetryable + typed metadata
    AC-7 Original classifyError() returns typed instances MET Exit codes primary, stderr secondary. All 3 call sites updated
    AC-8 Original Run logs store errorType + metadata, backwards compatible MET run-log-schema.ts — new fields optional, old format parses
    AC-9 Original Retry logic uses error.isRetryable MET phase-executor.ts:619-633 — classifies error, checks .isRetryable
    AC-10 Original Error types exported from sequant MET src/index.ts:148-174 — all 7 types + classifier
    Derived ACs
    AC-11 Derived (Error Handling) Malformed JSON clear error MET getSettingsWithWarnings() catches SyntaxError, returns user-friendly message
    AC-12 Derived (Code Quality) .name matches class name for serialization MET toJSON() includes .name, tested with round-trip

    Coverage: 12/12 AC items fully met


    Quality Metrics

    Metric Value Status
    Type issues (any) 0 OK
    as never casts 14 (Zod pattern for nested defaults + ERROR_TYPE_MAP) OK (known pattern)
    Deleted tests 0 OK
    Files changed 13 OK
    Lines added +1824 -
    Lines deleted -67 -
    Security patterns 0 OK

    CI Status

    Check State Impact
    typecheck SUCCESS ✅ MET
    validate-plugin SUCCESS ✅ MET
    validate-skills SUCCESS ✅ MET
    build (20.x) PENDING ⏳ re-triggered after fix commit
    build (22.x) PENDING ⏳ re-triggered after fix commit

    Note: Initial CI run failed due to 2 issues (now fixed in a2a9ed6):

    1. init.test.ts mock missing generateSettingsReference export
    2. ScopeThresholdSchema didn't handle partial objects (e.g., { yellow: 10 } without red)

    MCP test failure (mcp-serve.integration.test.ts) is pre-existing on main — not caused by this PR.


    Test Coverage Analysis

    Changed File Tier Has Tests? Test File
    src/lib/errors.ts Standard ✅ Yes __tests__/error-types.test.ts
    src/lib/settings.ts Standard ✅ Yes __tests__/settings-schema.test.ts
    src/lib/workflow/error-classifier.ts Standard ✅ Yes __tests__/error-types.test.ts
    src/lib/workflow/run-log-schema.ts Standard ✅ Yes __tests__/integration/settings-schema.integration.test.ts
    src/commands/status.ts Standard ⚠️ Indirect Integration test covers getSettingsWithWarnings()
    src/commands/init.ts Standard ✅ Yes src/commands/init.test.ts
    src/lib/workflow/batch-executor.ts Standard ⚠️ Indirect Core classifyError() tested; wiring is thin
    src/lib/workflow/phase-executor.ts Standard ⚠️ Indirect Core classifyError() + isRetryable tested
    src/index.ts Optional ✅ Indirect Export-only; consumers test imports

    Coverage: 4/8 changed source files have direct tests, 4 have indirect coverage through tested dependencies. Core logic (errors, settings, classifier) is thoroughly tested (89 dedicated tests).


    Code Review

    Strengths:

    • Clean separation: errors.ts defines types, error-classifier.ts uses them, batch/phase-executor consume them
    • Backwards compatibility preserved: old log format still parses, errorTypeToCategory() bridges old/new
    • isRetryable is computed from error metadata (e.g., 429→true, 401→false) — not a hardcoded flag
    • Zod schema with .passthrough() allows forward-compatible settings from newer versions
    • 89 tests with good failure path coverage

    Issues found and fixed:

    • init.test.ts mock didn't include generateSettingsReference (fixed in a2a9ed6)
    • ScopeThresholdSchema used bare z.number() without defaults, breaking partial input (fixed with thresholdWithDefaults())

    Suggestions:

    • None blocking

    Self-Evaluation

    • Verified working: Yes — ran build, lint, and 132 tests after fixes
    • Test efficacy: High — error types, classification, validation, serialization all tested
    • Likely failure mode: If Claude SDK starts returning structured errors, the wrapping in classifyError() may double-wrap. The gap note in the issue body covers this.
    • Verdict confidence: High — all ACs verified literally, CI regression fixed

    Verdict: NEEDS_VERIFICATION

    All 12 AC items MET. CI build checks re-running after fix commit (a2a9ed6). Verdict upgrades to READY_FOR_MERGE once build (20.x) and build (22.x) pass. Pre-existing MCP test failure is not blocking.

    Documentation

    • CHANGELOG entry added
    • N/A — no new CLI commands or user-facing docs needed

    Next Steps

    1. Wait for CI build checks to pass on the fix commit
    2. Merge PR feat(#507): configuration schema validation and structured error types #511
  7. admarble commented on Apr 9, 2026

    @admarble
    ContributorAuthor

    /fullsolve Complete

    Issue: #507
    Status: NEEDS_VERIFICATION (pending CI build checks)

    Summary

    • AC: 12/12 met (10 original + 2 derived)
    • Tests: 132 passed (89 dedicated + 43 existing)
    • Build: ✅ Passed locally
    • Lint: ✅ Passed
    • QA: All checks passed

    Iterations

    • Spec: 1 (pre-completed)
    • Testgen: 1 (pre-completed)
    • Exec: 1
    • QA: 1 (found + fixed 2 CI regressions)

    Key Changes

    • src/lib/errors.ts — SequantError base + 6 typed subclasses
    • src/lib/settings.ts — Zod schema + validation + JSONC generation
    • src/lib/workflow/error-classifier.ts — Refactored to return typed instances
    • src/lib/workflow/phase-executor.ts — Retry uses isRetryable
    • src/lib/workflow/batch-executor.ts — Stores error metadata in run logs
    • src/commands/status.ts — Displays settings validation warnings
    • src/commands/init.ts — Generates settings reference doc

    PR: #511

    Self-Evaluation

    • Worked as expected: Yes — all features implemented and verified
    • Test coverage confidence: High — 89 dedicated tests + integration tests
    • Weakest part: batch-executor.ts and phase-executor.ts wiring is tested only indirectly through the functions they call
    • Honest assessment: Solid implementation. CI caught two real gaps (mock + partial threshold) that were fixed. Ready for merge once CI passes.

    Ready for human review and merge once CI build checks pass.

  8. admarble commented on Apr 9, 2026

    @admarble
    ContributorAuthor

    Documentation Generated

    File: docs/features/settings-validation-and-error-types.md

    Sections Included:

    • Settings validation (warnings for misspelled keys, type mismatches)
    • Forward compatibility via .passthrough()
    • Generated JSONC settings file with inline comments
    • Programmatic use (SettingsSchema, validateSettings())
    • Structured error type hierarchy (6 subclasses with retryability)
    • Retry logic using error.isRetryable
    • Run log format (backwards compatible)
    • Error type exports for plugins
    • Troubleshooting (3 scenarios)

    Related docs:

    • docs/features/error-capture.md — covers stderr/stdout capture (now uses typed errors internally)
    • docs/features/scope-assessment-settings.md — covers scope thresholds (validated by the same schema)

    Next Steps:

    1. Review generated documentation for accuracy
    2. Merge to deploy

    Ready to merge!

  9. added a commit that references this issue on Apr 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementplannedroadmap

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions